-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathtest_nn_module.cc
More file actions
2076 lines (1735 loc) · 98.1 KB
/
test_nn_module.cc
File metadata and controls
2076 lines (1735 loc) · 98.1 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
#include "test_nn_module.h"
#include "infinicore/ops.hpp"
namespace infinicore::test {
// Helper function to format shape for logging
inline std::string formatShape(const std::vector<size_t> &shape) {
std::ostringstream oss;
oss << "[";
for (size_t i = 0; i < shape.size(); ++i) {
if (i > 0) {
oss << ", ";
}
oss << shape[i];
}
oss << "]";
return oss.str();
}
// Test 1: Basic module operations (creation, parameters, state_dict, load_state_dict)
TestResult NNModuleTest::testBasicModuleCreation() {
return measureTime("BasicModuleOperations", [this]() {
try {
spdlog::info("==========================================");
spdlog::info("Testing Basic Module Operations");
spdlog::info("==========================================");
// Test 1a: Module creation and parameter registration
spdlog::info("Test 1a: Module creation and parameter registration");
MockLinearModule module(8, 4, infinicore::Device());
// Verify the module was created successfully
auto state_dict = module.state_dict();
if (state_dict.size() != 2) {
spdlog::error("Expected 2 parameters, got {}", state_dict.size());
return false;
}
// Test weight and bias parameters
const auto &weight = module.get_weight();
const auto &bias = module.get_bias();
// Verify parameter shapes
if (weight->shape() != std::vector<size_t>({4, 8})) {
spdlog::error("Weight shape mismatch. Expected {{4, 8}}");
return false;
}
if (bias->shape() != std::vector<size_t>({4})) {
spdlog::error("Bias shape mismatch. Expected {{4}}");
return false;
}
spdlog::info("✓ Module creation and parameter registration passed");
// Test 1b: State dictionary functionality
spdlog::info("Test 1b: State dictionary functionality");
// Check if both parameters are in state dict
if (state_dict.find("weight") == state_dict.end()) {
spdlog::error("'weight' parameter not found in state dict");
return false;
}
if (state_dict.find("bias") == state_dict.end()) {
spdlog::error("'bias' parameter not found in state dict");
return false;
}
spdlog::debug("State dict contains {} parameters:", state_dict.size());
for (const auto &[name, tensor] : state_dict) {
std::ostringstream shape_str;
shape_str << "[";
for (size_t i = 0; i < tensor->shape().size(); ++i) {
if (i > 0) {
shape_str << ", ";
}
shape_str << tensor->shape()[i];
}
shape_str << "]";
spdlog::debug(" - {} with shape: {}", name, shape_str.str());
}
spdlog::info("✓ State dict functionality passed");
// Test 1c: Load state dict functionality
spdlog::info("Test 1c: Load state dict functionality");
// Create new tensors to load
auto new_weight = infinicore::Tensor::ones({4, 8}, infinicore::DataType::F32, infinicore::Device());
auto new_bias = infinicore::Tensor::zeros({4}, infinicore::DataType::F32, infinicore::Device());
// Load using load_parameter_
module.load_parameter_("weight", new_weight);
module.load_parameter_("bias", new_bias);
// Verify the parameters were updated
auto updated_state_dict = module.state_dict();
if (!tensorsAllClose(updated_state_dict.at("weight"), new_weight, 1e-6, 1e-6)) {
spdlog::error("Weight parameter values do not match after load_parameter_");
return false;
}
if (!tensorsAllClose(updated_state_dict.at("bias"), new_bias, 1e-6, 1e-6)) {
spdlog::error("Bias parameter values do not match after load_parameter_");
return false;
}
// Test load_state_dict
std::unordered_map<std::string, infinicore::Tensor> new_state_dict;
new_state_dict.emplace("weight", infinicore::Tensor::ones({4, 8}, infinicore::DataType::F32, infinicore::Device()));
new_state_dict.emplace("bias", infinicore::Tensor::ones({4}, infinicore::DataType::F32, infinicore::Device()));
module.load_state_dict(new_state_dict);
auto final_state_dict = module.state_dict();
if (final_state_dict.size() != 2) {
spdlog::error("State dict size mismatch after load_state_dict");
return false;
}
spdlog::info("✓ Load state dict functionality passed");
spdlog::info("=== All Basic Module Operations Passed ===");
return true;
} catch (const std::exception &e) {
spdlog::error("Exception in testBasicModuleOperations: {}", e.what());
return false;
}
});
}
TestResult NNModuleTest::testTensorParallelParameters() {
return measureTime("TensorParallelParameters", [this]() {
try {
spdlog::info("==========================================");
spdlog::info("Testing Tensor Parallel Parameters");
spdlog::info("==========================================");
auto device = infinicore::context::getDevice();
spdlog::info("Test Tensor Parallel Parameter");
// Case 1: Partition along dimension 0 (row-wise partitioning)
infinicore::nn::Parameter param_dim0({8, 4}, infinicore::DataType::F32, device, 0, 0, 2);
if (param_dim0->shape() != std::vector<size_t>({4, 4})) {
spdlog::error("TP dim0: Expected shape [4, 4], got [{}]", formatShape(param_dim0->shape()));
return false;
}
spdlog::info("✓ TP dim0 parameter created with correct partitioned shape");
// Case 2: Partition along dimension 1 (column-wise partitioning)
infinicore::nn::Parameter param_dim1({8, 4}, infinicore::DataType::F32, device, 1, 0, 2);
if (param_dim1->shape() != std::vector<size_t>({8, 2})) {
spdlog::error("TP dim1: Expected shape [8, 2], got [{}]", formatShape(param_dim1->shape()));
return false;
}
spdlog::info("✓ TP dim1 parameter created with correct partitioned shape");
spdlog::info("✓ Parameter creation with tensor parallelism passed");
spdlog::info("Test Tensor Parallel Linear Module");
auto w_data = std::vector<float>(32 * 64);
auto b_data = std::vector<float>(32);
for (size_t i = 0; i < 32; ++i) {
for (size_t j = 0; j < 64; ++j) {
w_data[i * 64 + j] = static_cast<float>(j);
}
b_data[i] = static_cast<float>(i);
}
{
spdlog::info("Test tp_size=4 tp_dim=0");
Size tp_size = 4;
Size tp_dim = 0;
std::vector<std::unique_ptr<MockLinearModule>> tp_modules;
for (Size tp_rank = 0; tp_rank < tp_size; ++tp_rank) {
auto module = std::make_unique<MockLinearModule>(64, 32, device, tp_dim, tp_rank, tp_size);
tp_modules.push_back(std::move(module));
}
// Verify each partition has correct shape
for (size_t i = 0; i < tp_modules.size(); ++i) {
const auto &weight = tp_modules[i]->get_weight();
const auto &bias = tp_modules[i]->get_bias();
// Weight should be partitioned along output dimension (dim 0)
if (weight->shape() != std::vector<size_t>({8, 64})) { // 32/4 = 8
spdlog::error("TP rank {}: Weight shape mismatch. Expected [8, 64], got [{}]",
i, formatShape(weight->shape()));
return false;
}
// Bias should be partitioned along output dimension
if (bias->shape() != std::vector<size_t>({8})) { // 32/4 = 8
spdlog::error("TP rank {}: Bias shape mismatch. Expected [8], got [{}]",
i, formatShape(bias->shape()));
return false;
}
spdlog::debug("TP rank {}: weight shape [{}], bias shape [{}]",
i, formatShape(weight->shape()), formatShape(bias->shape()));
tp_modules[i]->load_parameter_from_blob("weight", w_data.data());
tp_modules[i]->load_parameter_from_blob("bias", b_data.data());
auto weight_loaded = infinicore::Tensor::from_blob(
w_data.data(),
{32, 64},
infinicore::DataType::F32,
infinicore::Device::cpu())
->narrow({{0, i * 8, 8}})
->to(device); // Narrow to get the partition
auto bias_loaded = infinicore::Tensor::from_blob(
b_data.data(),
{32},
infinicore::DataType::F32,
infinicore::Device::cpu())
->narrow({{0, i * 8, 8}})
->to(device); // Narrow to get the partition
if (!tensorsAllClose(tp_modules[i]->get_weight(), weight_loaded, 1e-6, 1e-6)) {
spdlog::error("TP rank {}: Weight values do not match after load_parameter_from_blob", i);
return false;
}
if (!tensorsAllClose(tp_modules[i]->get_bias(), bias_loaded, 1e-6, 1e-6)) {
spdlog::error("TP rank {}: Bias values do not match after load_parameter_from_blob", i);
return false;
}
}
}
{
spdlog::info("Test tp_size=4 tp_dim=1");
Size tp_size = 4;
Size tp_dim = 1;
std::vector<std::unique_ptr<MockLinearModule>> tp_modules;
for (Size tp_rank = 0; tp_rank < tp_size; ++tp_rank) {
auto module = std::make_unique<MockLinearModule>(64, 32, device, tp_dim, tp_rank, tp_size);
tp_modules.push_back(std::move(module));
}
// Verify each partition has correct shape
for (size_t i = 0; i < tp_modules.size(); ++i) {
const auto &weight = tp_modules[i]->get_weight();
const auto &bias = tp_modules[i]->get_bias();
// Weight should be partitioned along output dimension (dim 0)
if (weight->shape() != std::vector<size_t>({32, 16})) { // 64/4 = 16
spdlog::error("TP rank {}: Weight shape mismatch. Expected [32, 16], got [{}]",
i, formatShape(weight->shape()));
return false;
}
// Bias should be partitioned along output dimension
if (bias->shape() != std::vector<size_t>({32})) { // Bias not partitioned when tp_dim=1
spdlog::error("TP rank {}: Bias shape mismatch. Expected [32], got [{}]",
i, formatShape(bias->shape()));
return false;
}
spdlog::debug("TP rank {}: weight shape [{}], bias shape [{}]",
i, formatShape(weight->shape()), formatShape(bias->shape()));
;
tp_modules[i]->load_parameter_from_blob("weight", w_data.data());
tp_modules[i]->load_parameter_from_blob("bias", b_data.data());
auto weight_loaded = infinicore::Tensor::from_blob(
w_data.data(),
{32, 64},
infinicore::DataType::F32,
infinicore::Device::cpu())
->narrow({{1, i * 16, 16}})
->to(device); // Narrow to get the partition
auto bias_loaded = infinicore::Tensor::from_blob(
b_data.data(),
{32},
infinicore::DataType::F32,
infinicore::Device::cpu())
->to(device); // Narrow to get the partition
if (!tensorsAllClose(tp_modules[i]->get_weight(), weight_loaded, 1e-6, 1e-6)) {
spdlog::error("TP rank {}: Weight values do not match after load_parameter_from_blob", i);
return false;
}
if (!tensorsAllClose(tp_modules[i]->get_bias(), bias_loaded, 1e-6, 1e-6)) {
spdlog::error("TP rank {}: Bias values do not match after load_parameter_from_blob", i);
return false;
}
}
}
spdlog::info("=== All Tensor Parallel Parameter Tests Passed ===");
return true;
} catch (const std::exception &e) {
spdlog::error("Exception in testTensorParallelParameters: {}", e.what());
return false;
}
});
}
TestResult NNModuleTest::testParalleLinear() {
return measureTime("ParalleLinear", [this]() {
try {
spdlog::info("==========================================");
spdlog::info(" Testing Tensor Parallel Linear ");
spdlog::info("==========================================");
auto device = infinicore::context::getDevice();
spdlog::info("Test Tensor Parallel Linear");
spdlog::info(device.toString());
auto w_data = std::vector<float>(32 * 64);
auto b_data = std::vector<float>(32);
for (size_t i = 0; i < 32; ++i) {
for (size_t j = 0; j < 64; ++j) {
w_data[i * 64 + j] = static_cast<float>(j);
}
b_data[i] = static_cast<float>(i);
}
{
spdlog::info("Test tp_size=4 tp_dim=0");
Size tp_size = 4;
// Size tp_dim = 0;
std::vector<std::unique_ptr<infinicore::nn::ColumnParallelLinear>> tp_modules;
for (Size tp_rank = 0; tp_rank < tp_size; ++tp_rank) {
auto module = std::make_unique<infinicore::nn::ColumnParallelLinear>(64, 32, true, DataType::F32, device, tp_rank, tp_size);
tp_modules.push_back(std::move(module));
}
// Verify each partition has correct shape
for (size_t i = 0; i < tp_modules.size(); ++i) {
const auto &weight = tp_modules[i]->weight();
const auto &bias = tp_modules[i]->bias();
// Weight should be partitioned along output dimension (dim 0)
if (weight->shape() != std::vector<size_t>({8, 64})) { // 32/4 = 8
spdlog::error("TP rank {}: Weight shape mismatch. Expected [8, 64], got [{}]",
i, formatShape(weight->shape()));
return false;
}
// Bias should be partitioned along output dimension
if (bias->shape() != std::vector<size_t>({8})) { // 32/4 = 8
spdlog::error("TP rank {}: Bias shape mismatch. Expected [8], got [{}]",
i, formatShape(bias->shape()));
return false;
}
spdlog::debug("TP rank {}: weight shape [{}], bias shape [{}]",
i, formatShape(weight->shape()), formatShape(bias->shape()));
tp_modules[i]->load_parameter_from_blob("weight", w_data.data());
tp_modules[i]->load_parameter_from_blob("bias", b_data.data());
auto weight_loaded = infinicore::Tensor::from_blob(
w_data.data(),
{32, 64},
infinicore::DataType::F32,
infinicore::Device::cpu())
->narrow({{0, i * 8, 8}})
->to(device); // Narrow to get the partition
auto bias_loaded = infinicore::Tensor::from_blob(
b_data.data(),
{32},
infinicore::DataType::F32,
infinicore::Device::cpu())
->narrow({{0, i * 8, 8}})
->to(device); // Narrow to get the partition
if (!tensorsAllClose(tp_modules[i]->weight(), weight_loaded, 1e-6, 1e-6)) {
spdlog::error("TP rank {}: Weight values do not match after load_parameter_from_blob", i);
return false;
}
if (!tensorsAllClose(tp_modules[i]->bias(), bias_loaded, 1e-6, 1e-6)) {
spdlog::error("TP rank {}: Bias values do not match after load_parameter_from_blob", i);
return false;
}
}
}
{
spdlog::info("Test tp_size=4 tp_dim=1");
Size tp_size = 4;
// Size tp_dim = 1;
std::vector<std::unique_ptr<infinicore::nn::RowParallelLinear>> tp_modules;
for (Size tp_rank = 0; tp_rank < tp_size; ++tp_rank) {
auto module = std::make_unique<infinicore::nn::RowParallelLinear>(64, 32, true, DataType::F32, device, tp_rank, tp_size);
tp_modules.push_back(std::move(module));
}
// Verify each partition has correct shape
for (size_t i = 0; i < tp_modules.size(); ++i) {
const auto &weight = tp_modules[i]->weight();
const auto &bias = tp_modules[i]->bias();
// Weight should be partitioned along output dimension (dim 0)
if (weight->shape() != std::vector<size_t>({32, 16})) { // 64/4 = 16
spdlog::error("TP rank {}: Weight shape mismatch. Expected [32, 16], got [{}]",
i, formatShape(weight->shape()));
return false;
}
// Bias should be partitioned along output dimension
if (bias->shape() != std::vector<size_t>({32})) { // Bias not partitioned when tp_dim=1
spdlog::error("TP rank {}: Bias shape mismatch. Expected [32], got [{}]",
i, formatShape(bias->shape()));
return false;
}
spdlog::debug("TP rank {}: weight shape [{}], bias shape [{}]",
i, formatShape(weight->shape()), formatShape(bias->shape()));
;
tp_modules[i]->load_parameter_from_blob("weight", w_data.data());
tp_modules[i]->load_parameter_from_blob("bias", b_data.data());
auto weight_loaded = infinicore::Tensor::from_blob(
w_data.data(),
{32, 64},
infinicore::DataType::F32,
infinicore::Device::cpu())
->narrow({{1, i * 16, 16}})
->to(device); // Narrow to get the partition
auto bias_loaded = infinicore::Tensor::from_blob(
b_data.data(),
{32},
infinicore::DataType::F32,
infinicore::Device::cpu())
->to(device); // Narrow to get the partition
if (!tensorsAllClose(tp_modules[i]->weight(), weight_loaded, 1e-6, 1e-6)) {
spdlog::error("TP rank {}: Weight values do not match after load_parameter_from_blob", i);
return false;
}
if (!tensorsAllClose(tp_modules[i]->bias(), bias_loaded, 1e-6, 1e-6)) {
spdlog::error("TP rank {}: Bias values do not match after load_parameter_from_blob", i);
return false;
}
}
}
spdlog::info("=== All Tensor Parallel Linear Tests Passed ===");
return true;
} catch (const std::exception &e) {
spdlog::error("Exception in testTensorParallelParameters: {}", e.what());
return false;
}
});
}
// Test 2: Advanced load state dict functionality (hierarchical modules)
TestResult NNModuleTest::testLoadStateDict() {
return measureTime("AdvancedLoadStateDict", [this]() {
try {
spdlog::info("==========================================");
spdlog::info("Testing Advanced load_state_dict with Hierarchical Modules");
spdlog::info("==========================================");
// Test: Deep nesting (2-level hierarchy)
spdlog::info("Test 4: Testing load_state_dict with 2-level deep nesting");
// Create parent -> child -> grandchild hierarchy using proper module definition
class DeepGrandchildModule : public infinicore::nn::Module {
protected:
INFINICORE_NN_MODULE(MockLinearModule, sublayer);
public:
DeepGrandchildModule() {
INFINICORE_NN_MODULE_INIT(sublayer, 6, 4, infinicore::Device());
}
};
class DeepChildModule : public infinicore::nn::Module {
protected:
INFINICORE_NN_MODULE(MockLinearModule, own_layer);
INFINICORE_NN_MODULE(DeepGrandchildModule, sublayer);
public:
DeepChildModule() {
INFINICORE_NN_MODULE_INIT(own_layer, 8, 6, infinicore::Device());
INFINICORE_NN_MODULE_INIT(sublayer);
}
};
class DeepParentModule : public infinicore::nn::Module {
protected:
INFINICORE_NN_MODULE(MockLinearModule, own_layer);
INFINICORE_NN_MODULE(DeepChildModule, layer1);
public:
DeepParentModule() {
INFINICORE_NN_MODULE_INIT(own_layer, 10, 8, infinicore::Device());
INFINICORE_NN_MODULE_INIT(layer1);
}
};
DeepParentModule deep_parent;
// Verify initial state dict includes all 2-level hierarchical parameters
auto deep_initial_state = deep_parent.state_dict();
spdlog::debug("Deep hierarchical state dict has {} parameters", deep_initial_state.size());
// Expected parameters:
// parent: own_layer.weight, own_layer.bias (2)
// layer1: layer1.own_layer.weight, layer1.own_layer.bias (2)
// sublayer: layer1.sublayer.sublayer.weight, layer1.sublayer.sublayer.bias (2)
// Total: 6 parameters
if (deep_initial_state.size() < 6) {
spdlog::error("Deep hierarchy state dict size mismatch. Expected at least 6, got {}",
deep_initial_state.size());
return false;
}
// Verify 2-level parameter names exist
bool has_sublayer_weight = deep_initial_state.find("layer1.sublayer.sublayer.weight") != deep_initial_state.end();
bool has_sublayer_bias = deep_initial_state.find("layer1.sublayer.sublayer.bias") != deep_initial_state.end();
if (!has_sublayer_weight || !has_sublayer_bias) {
spdlog::error("2-level nested parameters missing from state dict");
return false;
}
spdlog::debug("All 2-level hierarchical parameter names verified");
// Create state dict for 2-level hierarchy with all 1.0 values
std::unordered_map<std::string, infinicore::Tensor> deep_state_dict;
deep_state_dict.emplace("own_layer.weight", infinicore::Tensor::ones({8, 10}, infinicore::DataType::F32, infinicore::Device()));
deep_state_dict.emplace("own_layer.bias", infinicore::Tensor::ones({8}, infinicore::DataType::F32, infinicore::Device()));
deep_state_dict.emplace("layer1.own_layer.weight", infinicore::Tensor::ones({6, 8}, infinicore::DataType::F32, infinicore::Device()));
deep_state_dict.emplace("layer1.own_layer.bias", infinicore::Tensor::ones({6}, infinicore::DataType::F32, infinicore::Device()));
deep_state_dict.emplace("layer1.sublayer.sublayer.weight", infinicore::Tensor::ones({4, 6}, infinicore::DataType::F32, infinicore::Device()));
deep_state_dict.emplace("layer1.sublayer.sublayer.bias", infinicore::Tensor::ones({4}, infinicore::DataType::F32, infinicore::Device()));
// Load the deep hierarchical state dict
deep_parent.load_state_dict(deep_state_dict);
spdlog::debug("Successfully loaded 2-level deep hierarchical state dict");
// Verify all parameters were loaded correctly
auto deep_loaded_state = deep_parent.state_dict();
// Verify shapes at all levels
if (deep_loaded_state.at("own_layer.weight")->shape() != std::vector<size_t>({8, 10})) {
spdlog::error("Deep parent weight shape mismatch");
return false;
}
if (deep_loaded_state.at("layer1.own_layer.weight")->shape() != std::vector<size_t>({6, 8})) {
spdlog::error("Deep layer1 weight shape mismatch");
return false;
}
if (deep_loaded_state.at("layer1.sublayer.sublayer.weight")->shape() != std::vector<size_t>({4, 6})) {
spdlog::error("Deep sublayer weight shape mismatch");
return false;
}
spdlog::debug("All 2-level deep parameter shapes verified");
// Verify actual weight loading correctness by checking that loaded parameters
// match what we provided in the state dict (use the original tensors)
spdlog::info("Verifying weight loading correctness by direct comparison");
// Get the tensors we loaded from the state dict
auto loaded_parent_weight = deep_loaded_state.at("own_layer.weight");
auto loaded_layer1_weight = deep_loaded_state.at("layer1.own_layer.weight");
auto loaded_sublayer_weight = deep_loaded_state.at("layer1.sublayer.sublayer.weight");
// Compare with the original tensors we put in the state dict
if (!tensorsAllClose(loaded_parent_weight, deep_state_dict.at("own_layer.weight"), 1e-5, 1e-5)) {
spdlog::error("Deep parent weight not preserved after loading");
return false;
}
if (!tensorsAllClose(loaded_layer1_weight, deep_state_dict.at("layer1.own_layer.weight"), 1e-5, 1e-5)) {
spdlog::error("Deep layer1 weight not preserved after loading");
return false;
}
if (!tensorsAllClose(loaded_sublayer_weight, deep_state_dict.at("layer1.sublayer.sublayer.weight"), 1e-5, 1e-5)) {
spdlog::error("Deep sublayer weight not preserved after loading");
return false;
}
spdlog::info("✓ Weight loading correctness verified - loaded values match input state dict");
spdlog::info("✓ 2-level deep hierarchy load_state_dict verification passed");
spdlog::info("=== All Advanced load_state_dict Tests Passed ===");
return true;
} catch (const std::exception &e) {
spdlog::error("Exception in testLoadStateDict: {}", e.what());
return false;
}
});
}
// Test 3: Module hierarchy (demonstrates proper hierarchical construction pattern)
TestResult NNModuleTest::testModuleHierarchy() {
return measureTime("ModuleHierarchy", [this]() {
try {
// Create a hierarchy using proper module definition: root -> layer1 -> layer2
class Layer2Module : public infinicore::nn::Module {
protected:
INFINICORE_NN_MODULE(MockLinearModule, sublayer);
public:
Layer2Module() {
INFINICORE_NN_MODULE_INIT(sublayer, 8, 4, infinicore::Device());
}
};
class Layer1Module : public infinicore::nn::Module {
protected:
INFINICORE_NN_MODULE(MockLinearModule, sublayer);
INFINICORE_NN_MODULE(Layer2Module, layer2);
public:
Layer1Module() {
INFINICORE_NN_MODULE_INIT(sublayer, 16, 8, infinicore::Device());
INFINICORE_NN_MODULE_INIT(layer2);
}
};
class RootModule : public infinicore::nn::Module {
protected:
INFINICORE_NN_MODULE(MockLinearModule, root_layer);
INFINICORE_NN_MODULE(Layer1Module, layer1);
public:
RootModule() {
INFINICORE_NN_MODULE_INIT(root_layer, 20, 16, infinicore::Device());
INFINICORE_NN_MODULE_INIT(layer1);
}
};
RootModule root_module;
// Check the complete state dict
auto root_state_dict = root_module.state_dict();
// Debug: Print all parameters
spdlog::debug("Found {} parameters:", root_state_dict.size());
for (const auto &pair : root_state_dict) {
spdlog::debug(" - {}", pair.first);
}
// Should have: root_layer.weight, root_layer.bias,
// layer1.sublayer.weight, layer1.sublayer.bias,
// layer1.layer2.sublayer.weight, layer1.layer2.sublayer.bias
if (root_state_dict.size() < 6) {
spdlog::error("Error: Expected at least 6 parameters in hierarchy, got {}", root_state_dict.size());
return false;
}
spdlog::info("Module hierarchy test passed. Root state dict has {} parameters", root_state_dict.size());
// Print the hierarchy
std::cout << "Module hierarchy:" << std::endl;
for (const auto &pair : root_state_dict) {
std::cout << " - " << pair.first << std::endl;
}
// Additional: Test INFINICORE_NN_MODULE_VEC vector registration
spdlog::info("Testing INFINICORE_NN_MODULE_VEC (vector of submodules)");
class VecModule : public infinicore::nn::Module {
protected:
INFINICORE_NN_MODULE_VEC(MockLinearModule, layers);
public:
VecModule() {
INFINICORE_NN_MODULE_VEC_INIT(layers, 3, MockLinearModule, 16, 8, infinicore::Device());
}
};
VecModule vec_mod;
auto vec_state = vec_mod.state_dict();
// Expect parameters for layers.0, layers.1, layers.2 (weight and bias for each)
std::vector<std::string> expected_vec_params = {
"layers.0.weight", "layers.0.bias",
"layers.1.weight", "layers.1.bias",
"layers.2.weight", "layers.2.bias"};
for (const auto ¶m : expected_vec_params) {
if (vec_state.find(param) == vec_state.end()) {
spdlog::error("INFINICORE_NN_MODULE_VEC: missing '{}' in state_dict", param);
return false;
}
}
spdlog::info("INFINICORE_NN_MODULE_VEC test passed - found all vector layer parameters");
return true;
} catch (const std::exception &e) {
spdlog::error("Exception in testModuleHierarchy: {}", e.what());
return false;
}
});
}
// Test 4: Parameter loading from blob
TestResult NNModuleTest::testParameterLoading() {
return measureTime("ParameterLoading", [this]() {
try {
spdlog::info("==========================================");
spdlog::info("Testing Parameter loading from blob");
spdlog::info("==========================================");
MockLinearModule module(3, 2, infinicore::Device());
// Create test data
std::vector<float> weight_data = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f};
std::vector<float> bias_data = {0.1f, 0.2f};
// Load parameters from blob data
module.load_parameter_from_blob("weight", weight_data.data());
module.load_parameter_from_blob("bias", bias_data.data());
spdlog::info("Successfully loaded parameters from blob data");
// Verify parameters exist
auto state_dict = module.state_dict();
if (state_dict.find("weight") == state_dict.end() || state_dict.find("bias") == state_dict.end()) {
spdlog::error("Error: Parameters not found after loading");
return false;
}
MockLinearModule module_row_parallel(3, 2, infinicore::Device(), 0, 1, 2);
spdlog::info("Parameter loading test passed");
return true;
} catch (const std::exception &e) {
spdlog::error("Exception in testParameterLoading: {}", e.what());
return false;
}
});
}
// Test 5: Linear module implementation and behavior
TestResult NNModuleTest::testModuleLinear() {
return measureTime("ModuleLinear", [this]() {
try {
// Test with bias
spdlog::info("==========================================");
spdlog::info("Testing Linear module with bias (8->4 features)");
spdlog::info("==========================================");
infinicore::nn::Linear m1(8, 4, true);
auto sd1 = m1.state_dict();
if (sd1.find("weight") == sd1.end()) {
spdlog::error("weight missing");
return false;
}
if (sd1.find("bias") == sd1.end()) {
spdlog::error("bias missing when bias=true");
return false;
}
if (sd1.at("weight")->shape() != std::vector<size_t>({4, 8})) {
spdlog::error("weight shape mismatch. Expected {{4, 8}}, got different shape");
return false;
}
if (sd1.at("bias")->shape() != std::vector<size_t>({4})) {
spdlog::error("bias shape mismatch. Expected {{4}}, got different shape");
return false;
}
spdlog::debug("Parameter shapes verified: weight {{4, 8}}, bias {{4}}");
// Test module properties
if (m1.in_features() != 8) {
spdlog::error("in_features mismatch. Expected 8, got {}", m1.in_features());
return false;
}
if (m1.out_features() != 4) {
spdlog::error("out_features mismatch. Expected 4, got {}", m1.out_features());
return false;
}
if (!m1.has_bias()) {
spdlog::error("has_bias should be true");
return false;
}
// Test linear computation with bias
spdlog::info("Testing linear computation with bias");
auto input1 = infinicore::Tensor::ones({2, 8}, infinicore::DataType::F32, infinicore::Device());
auto output1 = m1.forward(input1);
if (output1->shape() != std::vector<size_t>({2, 4})) {
spdlog::error("Linear output shape mismatch with bias. Expected {{2, 4}}, got different shape");
return false;
}
spdlog::debug("Linear computation with bias passed. Input shape: {{2, 8}}, Output shape: {{2, 4}}");
// Test without bias
spdlog::info("Testing Linear module without bias (16->3 features)");
infinicore::nn::Linear m2(16, 3, false);
auto sd2 = m2.state_dict();
if (sd2.find("weight") == sd2.end()) {
spdlog::error("weight missing (no-bias)");
return false;
}
if (sd2.find("bias") != sd2.end()) {
spdlog::error("bias should not exist when bias=false");
return false;
}
if (sd2.at("weight")->shape() != std::vector<size_t>({3, 16})) {
spdlog::error("weight shape mismatch (no-bias). Expected {{3, 16}}, got different shape");
return false;
}
spdlog::debug("Parameter shapes verified: weight {{3, 16}}, no bias");
// Test module properties
if (m2.in_features() != 16) {
spdlog::error("in_features mismatch. Expected 16, got {}", m2.in_features());
return false;
}
if (m2.out_features() != 3) {
spdlog::error("out_features mismatch. Expected 3, got {}", m2.out_features());
return false;
}
if (m2.has_bias()) {
spdlog::error("has_bias should be false");
return false;
}
// Test linear computation without bias
spdlog::info("Testing linear computation without bias");
auto input2 = infinicore::Tensor::ones({1, 16}, infinicore::DataType::F32, infinicore::Device());
auto output2 = m2.forward(input2);
if (output2->shape() != std::vector<size_t>({1, 3})) {
spdlog::error("Linear output shape mismatch without bias. Expected {{1, 3}}, got different shape");
return false;
}
spdlog::debug("Linear computation without bias passed. Input shape: {{1, 16}}, Output shape: {{1, 3}}");
// Test load_state_dict for m2 (without bias)
spdlog::info("Testing load_state_dict on Linear without bias");
auto m2_load_weight = infinicore::Tensor::ones({3, 16}, infinicore::DataType::F32, infinicore::Device());
std::unordered_map<std::string, infinicore::Tensor> m2_state_dict;
m2_state_dict.emplace("weight", m2_load_weight);
// Note: no bias parameter
m2.load_state_dict(m2_state_dict);
// Verify via state_dict() and direct access
if (!tensorsAllClose(m2.state_dict().at("weight"), m2_load_weight, 1e-5, 1e-5)) {
spdlog::error("m2 weight not loaded correctly");
return false;
}
if (!tensorsAllClose(m2.weight(), m2_load_weight, 1e-5, 1e-5)) {
spdlog::error("m2 weight field not synchronized");
return false;
}
spdlog::debug("m2 load_state_dict verified - weight loaded correctly (no bias)");
// Test batch processing
spdlog::info("Testing batch linear computation (batch size 3)");
auto input3 = infinicore::Tensor::ones({3, 8}, infinicore::DataType::F32, infinicore::Device());
auto output3 = m1.forward(input3);
if (output3->shape() != std::vector<size_t>({3, 4})) {
spdlog::error("Batch linear output shape mismatch. Expected {{3, 4}}, got different shape");
return false;
}
spdlog::debug("Batch linear computation passed. Input shape: {{3, 8}}, Output shape: {{3, 4}}");
// Test parameter accessors
spdlog::info("Testing parameter accessors");
auto weight_accessor = m1.weight();
auto bias_accessor = m1.bias();
if (weight_accessor->shape() != std::vector<size_t>({4, 8})) {
spdlog::error("Weight accessor shape mismatch");
return false;
}
if (bias_accessor->shape() != std::vector<size_t>({4})) {
spdlog::error("Bias accessor shape mismatch");
return false;
}
// Test load_state_dict for m1 (with bias)
spdlog::info("Testing load_state_dict on Linear with bias");
auto m1_load_weight = infinicore::Tensor::ones({4, 8}, infinicore::DataType::F32, infinicore::Device());
auto m1_load_bias = infinicore::Tensor::ones({4}, infinicore::DataType::F32, infinicore::Device());
std::unordered_map<std::string, infinicore::Tensor> m1_state_dict;
m1_state_dict.emplace("weight", m1_load_weight);
m1_state_dict.emplace("bias", m1_load_bias);
m1.load_state_dict(m1_state_dict);
// Verify via state_dict() and direct access
if (!tensorsAllClose(m1.state_dict().at("weight"), m1_load_weight, 1e-5, 1e-5)) {
spdlog::error("m1 weight not loaded correctly");
return false;
}
if (!tensorsAllClose(m1.weight(), m1_load_weight, 1e-5, 1e-5)) {
spdlog::error("m1 weight field not synchronized");
return false;
}
if (!tensorsAllClose(m1.bias(), m1_load_bias, 1e-5, 1e-5)) {
spdlog::error("m1 bias field not synchronized");
return false;
}
spdlog::debug("m1 load_state_dict verified - parameters and fields synchronized");
// Test extra_repr
std::string repr = m1.extra_repr();
spdlog::debug("Linear module representation: {}", repr);
// Test forward with residual connection
spdlog::info("Testing Linear forward with residual connection");
// auto residual = infinicore::Tensor::ones({2, 4}, infinicore::DataType::F32, infinicore::Device());
auto output_with_residual = m1.forward(input1);
if (output_with_residual->shape() != std::vector<size_t>({2, 4})) {
spdlog::error("Linear output with residual shape mismatch. Expected {{2, 4}}, got different shape");
return false;
}
spdlog::debug("Linear forward with residual passed. Input shape: {{2, 8}}, Residual shape: {{2, 4}}, Output shape: {{2, 4}}");
// Test computation correctness: InfiniCore vs Naive implementation
spdlog::info("Testing computation correctness: InfiniCore vs Naive implementation");
// Create test data with known values for verification
auto test_input = infinicore::Tensor::ones({2, 8}, infinicore::DataType::F32, infinicore::Device());
// auto test_residual = infinicore::Tensor::ones({2, 4}, infinicore::DataType::F32, infinicore::Device());
// Get InfiniCore result
auto infinicore_output = m1.forward(test_input);
// Compute naive result: output = input @ weight.T + bias + residual
auto naive_output = infinicore::Tensor::empty({2, 4}, infinicore::DataType::F32, infinicore::Device());
auto weight_naive = m1.weight();
auto bias_naive = m1.bias();
// Naive computation step by step
auto weight_t = weight_naive->permute({1, 0}); // [4, 8] -> [8, 4]
auto matmul_result = infinicore::op::matmul(test_input, weight_t); // [2, 4]
// Broadcast bias to [2, 4]
size_t ndim_diff = naive_output->ndim() - 1;
std::vector<infinicore::Stride> strides(ndim_diff, 0);
strides.push_back(bias_naive->stride(0));
auto bias_view = bias_naive->as_strided(naive_output->shape(), strides);
// Add bias to matmul result
infinicore::op::add_(naive_output, matmul_result, bias_view);
// Add residual
// infinicore::op::add_(naive_output, naive_output, test_residual);
// Compare results with actual value checking
if (infinicore_output->shape() != naive_output->shape()) {
spdlog::error("Shape mismatch between InfiniCore and naive implementation");
return false;
}
// Compare actual tensor values using local checker
if (!tensorsAllClose(infinicore_output, naive_output, 1e-5, 1e-5)) {
spdlog::error("Value mismatch between InfiniCore and naive implementation");
return false;
}
spdlog::debug("Value comparison passed - InfiniCore and naive results match within tolerance");
spdlog::debug("Computation correctness test passed - both implementations produce identical results");
spdlog::debug("InfiniCore output shape: {{2, 4}}, Naive output shape: {{2, 4}}");
// Test computation correctness without bias (using m2)
spdlog::info("Testing computation correctness without bias");
auto test_input_no_bias = infinicore::Tensor::ones({1, 16}, infinicore::DataType::F32, infinicore::Device());
// auto test_residual_no_bias = infinicore::Tensor::ones({1, 3}, infinicore::DataType::F32, infinicore::Device());
// Get InfiniCore result (no bias)
auto infinicore_output_no_bias = m2.forward(test_input_no_bias);
// Compute naive result without bias: output = input @ weight.T + residual
auto naive_output_no_bias = infinicore::Tensor::empty({1, 3}, infinicore::DataType::F32, infinicore::Device());
auto weight_no_bias_naive = m2.weight();
// Naive computation: just matmul + residual
auto weight_t_no_bias = weight_no_bias_naive->permute({1, 0}); // [3, 16] -> [16, 3]
auto matmul_result_no_bias = infinicore::op::matmul(test_input_no_bias, weight_t_no_bias); // [1, 3]
// Add residual
// infinicore::op::add_(naive_output_no_bias, matmul_result_no_bias, test_residual_no_bias);
// Compare results with actual value checking
if (infinicore_output_no_bias->shape() != naive_output_no_bias->shape()) {
spdlog::error("Shape mismatch between InfiniCore and naive implementation (no bias)");
return false;
}
// Compare actual tensor values for no-bias case
if (!tensorsAllClose(infinicore_output_no_bias, naive_output_no_bias, 1e-5, 1e-5)) {
spdlog::error("Value mismatch in no-bias computation");
return false;
}
spdlog::debug("No-bias value comparison passed - results match within tolerance");
spdlog::debug("No-bias computation correctness test passed - both implementations produce identical results");
spdlog::debug("InfiniCore no-bias output shape: {{1, 3}}, Naive no-bias output shape: {{1, 3}}");
// Test basic forward (no residual) vs naive
spdlog::info("Testing basic forward vs naive implementation");
auto basic_infinicore = m1.forward(test_input);
auto basic_naive = infinicore::Tensor::empty({2, 4}, infinicore::DataType::F32, infinicore::Device());
// Naive basic computation: input @ weight.T + bias
auto basic_matmul = infinicore::op::matmul(test_input, weight_t);
infinicore::op::add_(basic_naive, basic_matmul, bias_view);
if (basic_infinicore->shape() != basic_naive->shape()) {