forked from Stonepia/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataloader.cpp
2322 lines (1983 loc) · 76.1 KB
/
dataloader.cpp
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 <gtest/gtest.h>
#include <torch/torch.h>
#include <test/cpp/api/support.h>
#include <c10/util/ArrayRef.h>
#include <c10/util/irange.h>
#include <c10/util/tempfile.h>
#include <algorithm>
#include <chrono>
#include <future>
#include <iostream>
#include <iterator>
#include <limits>
#include <mutex>
#include <numeric>
#include <stdexcept>
#include <string>
#include <thread>
#include <unordered_set>
#include <vector>
using namespace torch::data; // NOLINT
const std::chrono::milliseconds kMillisecond(1);
struct DummyDataset : datasets::Dataset<DummyDataset, int> {
explicit DummyDataset(size_t size = 100) : size_(size) {}
int get(size_t index) override {
// NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions)
return 1 + index;
}
torch::optional<size_t> size() const override {
return size_;
}
size_t size_;
};
TEST(DataTest, DatasetCallsGetCorrectly) {
DummyDataset d;
std::vector<int> batch = d.get_batch({0, 1, 2, 3, 4});
std::vector<int> expected = {1, 2, 3, 4, 5};
ASSERT_EQ(batch, expected);
}
TEST(DataTest, TransformCallsGetApplyCorrectly) {
struct T : transforms::Transform<int, std::string> {
std::string apply(int input) override {
return std::to_string(input);
}
};
auto d = DummyDataset{}.map(T{});
std::vector<std::string> batch = d.get_batch({0, 1, 2, 3, 4});
std::vector<std::string> expected = {"1", "2", "3", "4", "5"};
ASSERT_EQ(batch, expected);
}
// dummy chunk data reader with 3 chunks and 35 examples in total. Each chunk
// contains 10, 5, 20 examples respectively.
struct DummyChunkDataReader : public datasets::ChunkDataReader<int> {
public:
using BatchType = datasets::ChunkDataReader<int>::ChunkType;
using DataType = datasets::ChunkDataReader<int>::ExampleType;
/// Read an entire chunk.
BatchType read_chunk(size_t chunk_index) override {
BatchType batch_data;
int start_index = chunk_index == 0
? 0
// NOLINTNEXTLINE(bugprone-fold-init-type)
: std::accumulate(chunk_sizes, chunk_sizes + chunk_index, 0);
batch_data.resize(chunk_sizes[chunk_index]);
std::iota(batch_data.begin(), batch_data.end(), start_index);
return batch_data;
}
size_t chunk_count() override {
return chunk_count_;
};
void reset() override{};
const static size_t chunk_count_ = 3;
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-magic-numbers,cppcoreguidelines-avoid-c-arrays)
size_t chunk_sizes[chunk_count_] = {10, 5, 20};
};
TEST(DataTest, ChunkDataSetWithInvalidInitParameter) {
DummyChunkDataReader data_reader;
samplers::SequentialSampler sampler(0);
auto initialization_function = [&](size_t preloader_count,
size_t batch_size,
size_t cache_size,
size_t cross_chunk_shuffle_count = 1) {
datasets::SharedBatchDataset<datasets::ChunkDataset<
DummyChunkDataReader,
samplers::SequentialSampler,
samplers::SequentialSampler>>
dataset = datasets::make_shared_dataset<datasets::ChunkDataset<
DummyChunkDataReader,
samplers::SequentialSampler,
samplers::SequentialSampler>>(
data_reader,
sampler,
sampler,
datasets::ChunkDatasetOptions(
preloader_count,
batch_size,
cache_size,
cross_chunk_shuffle_count));
};
ASSERT_THROWS_WITH(
initialization_function(0, 1, 1),
"Preloader count is 0. At least one preloader needs to be specified.");
ASSERT_THROWS_WITH(
initialization_function(1, 0, 1),
"Batch size is 0. A positive batch size needs to be specified.");
ASSERT_THROWS_WITH(
initialization_function(1, 1, 0),
"Cache size is 0. A positive cache size needs to be specified.");
ASSERT_THROWS_WITH(
initialization_function(1, 10, 5),
"Cache size is less than batch size. Cache needs to be large enough to "
"hold at least one batch.");
ASSERT_THROWS_WITH(
initialization_function(1, 10, 20, 0),
"cross_chunk_shuffle_count needs to be greater than 0.");
}
struct InfiniteStreamDataset
: datasets::StreamDataset<InfiniteStreamDataset, std::vector<int>> {
std::vector<int> get_batch(size_t batch_size) override {
std::vector<int> batch(batch_size);
for (auto& i : batch) {
i = counter++;
}
return batch;
}
torch::optional<size_t> size() const override {
return torch::nullopt;
}
size_t counter = 0;
};
TEST(DataTest, InfiniteStreamDataset) {
const size_t kBatchSize = 13;
auto dataset = InfiniteStreamDataset().map(
transforms::Lambda<int>([](int x) { return x + 1; }));
auto data_loader = torch::data::make_data_loader(
std::move(dataset),
samplers::StreamSampler(/*epoch_size=*/39),
kBatchSize);
size_t batch_index = 0;
for (auto& batch : *data_loader) {
ASSERT_LT(batch_index, 3);
ASSERT_EQ(batch.size(), kBatchSize);
for (const auto j : c10::irange(kBatchSize)) {
ASSERT_EQ(batch.at(j), 1 + (batch_index * kBatchSize) + j);
}
batch_index += 1;
}
ASSERT_EQ(batch_index, 3);
}
TEST(DataTest, NoSequencerIsIdentity) {
using namespace torch::data::detail::sequencers; // NOLINT
NoSequencer<int> no_sequencer;
const auto value = no_sequencer.next([] { return 5; }).value();
ASSERT_EQ(value, 5);
}
TEST(DataTest, OrderedSequencerIsSetUpWell) {
using namespace torch::data::detail::sequencers; // NOLINT
struct S {
size_t sequence_number;
};
const size_t kMaxJobs = 5;
OrderedSequencer<S> sequencer(kMaxJobs);
ASSERT_EQ(sequencer.next_sequence_number_, 0);
ASSERT_EQ(sequencer.buffer_.size(), kMaxJobs);
}
TEST(DataTest, OrderedSequencerReOrdersValues) {
using namespace torch::data::detail::sequencers; // NOLINT
struct S {
size_t sequence_number;
};
const size_t kMaxJobs = 5;
OrderedSequencer<S> sequencer(kMaxJobs);
std::vector<size_t> v = {0, 2, 4, 3, 1};
size_t index = 0;
auto getter = [&v, &index]() { return S{v.at(index++)}; };
// Let's say the sequence number matches for the batch one, then it should
// return immediately.
const auto batch = sequencer.next(getter);
ASSERT_EQ(batch.value().sequence_number, 0);
ASSERT_EQ(index, 1);
// Now it should call the getter until it gets the next value.
ASSERT_EQ(1, sequencer.next(getter).value().sequence_number);
ASSERT_EQ(index, 5);
// The next three should come in order.
for (size_t i = 2; i <= 4; ++i) {
// New value doesn't matter. In fact, it shouldn't be accessed.
ASSERT_EQ(i, sequencer.next(getter).value().sequence_number);
// The index doesn't change.
ASSERT_EQ(index, 5);
}
}
TEST(DataTest, BatchLambdaAppliesFunctionToBatch) {
using InputBatch = std::vector<int>;
using OutputBatch = std::string;
DummyDataset d;
auto e = d.map(transforms::BatchLambda<InputBatch, OutputBatch>(
[](std::vector<int> input) {
return std::to_string(std::accumulate(input.begin(), input.end(), 0));
}));
ASSERT_EQ(e.get_batch({1, 2, 3, 4, 5}), std::string("20"));
}
TEST(DataTest, LambdaAppliesFunctionToExample) {
auto d = DummyDataset().map(transforms::Lambda<int, std::string>(
static_cast<std::string (*)(int)>(std::to_string)));
std::vector<std::string> expected = {"1", "2", "3", "4", "5"};
ASSERT_EQ(d.get_batch({0, 1, 2, 3, 4}), expected);
}
TEST(DataTest, CollateReducesBatch) {
auto d =
DummyDataset().map(transforms::Collate<int>([](std::vector<int> input) {
return std::accumulate(input.begin(), input.end(), 0);
}));
ASSERT_EQ(d.get_batch({1, 2, 3, 4, 5}), 20);
}
TEST(DataTest, CollationReducesBatch) {
struct Summer : transforms::Collation<int> {
int apply_batch(std::vector<int> input) override {
return std::accumulate(input.begin(), input.end(), 0);
}
};
auto d = DummyDataset().map(Summer{});
ASSERT_EQ(d.get_batch({1, 2, 3, 4, 5}), 20);
}
TEST(DataTest, SequentialSamplerReturnsIndicesInOrder) {
samplers::SequentialSampler sampler(10);
ASSERT_EQ(sampler.next(3).value(), std::vector<size_t>({0, 1, 2}));
ASSERT_EQ(sampler.next(5).value(), std::vector<size_t>({3, 4, 5, 6, 7}));
ASSERT_EQ(sampler.next(2).value(), std::vector<size_t>({8, 9}));
ASSERT_FALSE(sampler.next(2).has_value());
}
TEST(DataTest, SequentialSamplerReturnsLessValuesForLastBatch) {
samplers::SequentialSampler sampler(5);
ASSERT_EQ(sampler.next(3).value(), std::vector<size_t>({0, 1, 2}));
ASSERT_EQ(sampler.next(100).value(), std::vector<size_t>({3, 4}));
ASSERT_FALSE(sampler.next(2).has_value());
}
TEST(DataTest, SequentialSamplerResetsWell) {
samplers::SequentialSampler sampler(5);
ASSERT_EQ(sampler.next(5).value(), std::vector<size_t>({0, 1, 2, 3, 4}));
ASSERT_FALSE(sampler.next(2).has_value());
sampler.reset();
ASSERT_EQ(sampler.next(5).value(), std::vector<size_t>({0, 1, 2, 3, 4}));
ASSERT_FALSE(sampler.next(2).has_value());
}
TEST(DataTest, SequentialSamplerResetsWithNewSizeWell) {
samplers::SequentialSampler sampler(5);
ASSERT_EQ(sampler.next(5).value(), std::vector<size_t>({0, 1, 2, 3, 4}));
ASSERT_FALSE(sampler.next(2).has_value());
sampler.reset(7);
ASSERT_EQ(
sampler.next(7).value(), std::vector<size_t>({0, 1, 2, 3, 4, 5, 6}));
ASSERT_FALSE(sampler.next(2).has_value());
sampler.reset(3);
ASSERT_EQ(sampler.next(3).value(), std::vector<size_t>({0, 1, 2}));
ASSERT_FALSE(sampler.next(2).has_value());
}
TEST(DataTest, CanSaveAndLoadSequentialSampler) {
{
samplers::SequentialSampler a(10);
ASSERT_EQ(a.index(), 0);
std::stringstream stream;
torch::save(a, stream);
samplers::SequentialSampler b(10);
torch::load(b, stream);
ASSERT_EQ(b.index(), 0);
}
{
samplers::SequentialSampler a(10);
a.next(3);
a.next(4);
ASSERT_EQ(a.index(), 7);
std::stringstream stream;
torch::save(a, stream);
samplers::SequentialSampler b(10);
torch::load(b, stream);
ASSERT_EQ(b.index(), 7);
}
}
TEST(DataTest, RandomSamplerReturnsIndicesInCorrectRange) {
samplers::RandomSampler sampler(10);
std::vector<size_t> indices = sampler.next(3).value();
for (auto i : indices) {
ASSERT_GE(i, 0);
ASSERT_LT(i, 10);
}
indices = sampler.next(5).value();
for (auto i : indices) {
ASSERT_GE(i, 0);
ASSERT_LT(i, 10);
}
indices = sampler.next(2).value();
for (auto i : indices) {
ASSERT_GE(i, 0);
ASSERT_LT(i, 10);
}
ASSERT_FALSE(sampler.next(10).has_value());
}
TEST(DataTest, RandomSamplerReturnsLessValuesForLastBatch) {
samplers::RandomSampler sampler(5);
ASSERT_EQ(sampler.next(3).value().size(), 3);
ASSERT_EQ(sampler.next(100).value().size(), 2);
ASSERT_FALSE(sampler.next(2).has_value());
}
TEST(DataTest, RandomSamplerResetsWell) {
samplers::RandomSampler sampler(5);
ASSERT_EQ(sampler.next(5).value().size(), 5);
ASSERT_FALSE(sampler.next(2).has_value());
sampler.reset();
ASSERT_EQ(sampler.next(5).value().size(), 5);
ASSERT_FALSE(sampler.next(2).has_value());
}
TEST(DataTest, RandomSamplerResetsWithNewSizeWell) {
samplers::RandomSampler sampler(5);
ASSERT_EQ(sampler.next(5).value().size(), 5);
ASSERT_FALSE(sampler.next(2).has_value());
sampler.reset(7);
ASSERT_EQ(sampler.next(7).value().size(), 7);
ASSERT_FALSE(sampler.next(2).has_value());
sampler.reset(3);
ASSERT_EQ(sampler.next(3).value().size(), 3);
ASSERT_FALSE(sampler.next(2).has_value());
}
TEST(DataTest, SavingAndLoadingRandomSamplerYieldsSameSequence) {
{
samplers::RandomSampler a(10);
std::stringstream stream;
torch::save(a, stream);
samplers::RandomSampler b(10);
torch::load(b, stream);
ASSERT_EQ(a.next(10).value(), b.next(10).value());
}
{
samplers::RandomSampler a(10);
a.next(3);
ASSERT_EQ(a.index(), 3);
std::stringstream stream;
torch::save(a, stream);
samplers::RandomSampler b(10);
torch::load(b, stream);
ASSERT_EQ(b.index(), 3);
auto b_sequence = b.next(10).value();
ASSERT_EQ(b_sequence.size(), 7);
ASSERT_EQ(a.next(10).value(), b_sequence);
}
}
TEST(DataTest, StreamSamplerReturnsTheBatchSizeAndThenRemainder) {
samplers::StreamSampler sampler(/*epoch_size=*/100);
ASSERT_EQ(sampler.next(10).value(), 10);
ASSERT_EQ(sampler.next(2).value(), 2);
ASSERT_EQ(sampler.next(85).value(), 85);
ASSERT_EQ(sampler.next(123).value(), 3);
ASSERT_FALSE(sampler.next(1).has_value());
}
TEST(DataTest, StreamSamplerResetsWell) {
samplers::StreamSampler sampler(/*epoch_size=*/5);
ASSERT_EQ(sampler.next(5).value().size(), 5);
ASSERT_FALSE(sampler.next(2).has_value());
sampler.reset();
ASSERT_EQ(sampler.next(5).value().size(), 5);
ASSERT_FALSE(sampler.next(2).has_value());
}
TEST(DataTest, StreamSamplerResetsWithNewSizeWell) {
samplers::StreamSampler sampler(/*epoch_size=*/5);
ASSERT_EQ(sampler.next(5).value().size(), 5);
ASSERT_FALSE(sampler.next(2).has_value());
sampler.reset(7);
ASSERT_EQ(sampler.next(7).value().size(), 7);
ASSERT_FALSE(sampler.next(2).has_value());
sampler.reset(3);
ASSERT_EQ(sampler.next(3).value().size(), 3);
ASSERT_FALSE(sampler.next(2).has_value());
}
TEST(DataTest, TensorDatasetConstructsFromSingleTensor) {
datasets::TensorDataset dataset(torch::eye(5));
ASSERT_TRUE(
torch::tensor({0, 0, 1, 0, 0}, torch::kFloat32).allclose(dataset.get(2)));
}
TEST(DataTest, TensorDatasetConstructsFromInitializerListOfTensors) {
std::vector<torch::Tensor> vector = torch::eye(5).chunk(5);
datasets::TensorDataset dataset(vector);
ASSERT_TRUE(
torch::tensor({0, 0, 1, 0, 0}, torch::kFloat32).allclose(dataset.get(2)));
}
TEST(DataTest, StackTransformWorksForExample) {
struct D : public datasets::Dataset<D> {
Example<> get(size_t index) override {
return {tensor[index], 1 + tensor[index]};
}
torch::optional<size_t> size() const override {
return tensor.size(0);
}
torch::Tensor tensor{torch::eye(4)};
};
auto d = D().map(transforms::Stack<Example<>>());
Example<> batch = d.get_batch({0, 1});
ASSERT_TRUE(batch.data.allclose(torch::eye(4).slice(/*dim=*/0, 0, 2)));
ASSERT_TRUE(batch.target.allclose(1 + torch::eye(4).slice(/*dim=*/0, 0, 2)));
Example<> second = d.get_batch({2, 3});
ASSERT_TRUE(second.data.allclose(torch::eye(4).slice(/*dim=*/0, 2, 4)));
ASSERT_TRUE(second.target.allclose(1 + torch::eye(4).slice(/*dim=*/0, 2, 4)));
}
TEST(DataTest, StackTransformWorksForTensorExample) {
auto d = datasets::TensorDataset(torch::eye(4))
.map(transforms::Stack<TensorExample>());
TensorExample batch = d.get_batch({0, 1});
ASSERT_TRUE(batch.data.allclose(torch::eye(4).slice(/*dim=*/0, 0, 2)));
TensorExample second = d.get_batch({2, 3});
ASSERT_TRUE(second.data.allclose(torch::eye(4).slice(/*dim=*/0, 2, 4)));
}
// Template classes cannot be nested in functions.
template <typename Target>
struct T : transforms::TensorTransform<Target> {
torch::Tensor operator()(torch::Tensor input) override {
return input * 2;
}
};
struct TensorStringDataset
: datasets::
Dataset<TensorStringDataset, Example<torch::Tensor, std::string>> {
Example<torch::Tensor, std::string> get(size_t index) override {
return {torch::tensor(static_cast<double>(index)), std::to_string(index)};
}
torch::optional<size_t> size() const override {
return 100;
}
};
TEST(DataTest, TensorTransformWorksForAnyTargetType) {
auto d = TensorStringDataset().map(T<std::string>{});
std::vector<Example<torch::Tensor, std::string>> batch = d.get_batch({1, 2});
ASSERT_EQ(batch.size(), 2);
ASSERT_TRUE(batch[0].data.allclose(torch::tensor(2.0)));
ASSERT_EQ(batch[0].target, "1");
ASSERT_TRUE(batch[1].data.allclose(torch::tensor(4.0)));
ASSERT_EQ(batch[1].target, "2");
}
TEST(DataTest, TensorLambdaWorksforAnyTargetType) {
auto d = TensorStringDataset().map(transforms::TensorLambda<std::string>(
[](torch::Tensor input) { return input * 2; }));
std::vector<Example<torch::Tensor, std::string>> batch = d.get_batch({1, 2});
ASSERT_EQ(batch.size(), 2);
ASSERT_TRUE(batch[0].data.allclose(torch::tensor(2.0)));
ASSERT_EQ(batch[0].target, "1");
ASSERT_TRUE(batch[1].data.allclose(torch::tensor(4.0)));
ASSERT_EQ(batch[1].target, "2");
}
struct DummyTensorDataset
: datasets::Dataset<DummyTensorDataset, Example<torch::Tensor, int>> {
Example<torch::Tensor, int> get(size_t index) override {
const auto channels = static_cast<int64_t>(index);
torch::Tensor tensor =
(channels > 0) ? torch::ones({channels, 4, 4}) : torch::ones({4, 4});
return {tensor, static_cast<int>(channels)};
}
torch::optional<size_t> size() const override {
return 100;
}
};
TEST(DataTest, NormalizeTransform) {
auto dataset = DummyTensorDataset().map(transforms::Normalize<int>(0.5, 0.1));
// Works for zero (one implicit) channels
std::vector<Example<torch::Tensor, int>> output = dataset.get_batch(0);
ASSERT_EQ(output.size(), 1);
// (1 - 0.5) / 0.1 = 5
ASSERT_TRUE(output[0].data.allclose(torch::ones({4, 4}) * 5))
<< output[0].data;
// Works for one explicit channel
output = dataset.get_batch(1);
ASSERT_EQ(output.size(), 1);
ASSERT_EQ(output[0].data.size(0), 1);
ASSERT_TRUE(output[0].data.allclose(torch::ones({1, 4, 4}) * 5))
<< output[0].data;
// Works for two channels with different moments
dataset = DummyTensorDataset().map(
transforms::Normalize<int>({0.5, 1.5}, {0.1, 0.2}));
output = dataset.get_batch(2);
ASSERT_EQ(output.size(), 1);
ASSERT_EQ(output[0].data.size(0), 2);
ASSERT_TRUE(output[0]
.data.slice(/*dim=*/0, /*start=*/0, /*end=*/1)
.allclose(torch::ones({1, 4, 4}) * 5))
<< output[0].data;
ASSERT_TRUE(output[0]
.data.slice(/*dim=*/0, /*start=*/1)
.allclose(torch::ones({1, 4, 4}) * -2.5))
<< output[0].data;
// Works for three channels with one moment value
dataset = DummyTensorDataset().map(transforms::Normalize<int>(1.5, 0.2));
output = dataset.get_batch(3);
ASSERT_EQ(output.size(), 1);
ASSERT_EQ(output[0].data.size(0), 3);
ASSERT_TRUE(output[0].data.allclose(torch::ones({3, 4, 4}) * -2.5))
<< output[0].data;
// Works for three channels with different moments
dataset = DummyTensorDataset().map(
transforms::Normalize<int>({0.5, 1.5, -1.5}, {0.1, 0.2, 0.2}));
output = dataset.get_batch(3);
ASSERT_EQ(output.size(), 1);
ASSERT_EQ(output[0].data.size(0), 3);
ASSERT_TRUE(output[0]
.data.slice(/*dim=*/0, /*start=*/0, /*end=*/1)
.allclose(torch::ones({1, 4, 4}) * 5))
<< output[0].data;
ASSERT_TRUE(output[0]
.data.slice(/*dim=*/0, /*start=*/1, /*end=*/2)
.allclose(torch::ones({1, 4, 4}) * -2.5))
<< output[0].data;
ASSERT_TRUE(output[0]
.data.slice(/*dim=*/0, /*start=*/2)
.allclose(torch::ones({1, 4, 4}) * 12.5))
<< output[0].data;
}
struct UnCopyableDataset : public datasets::Dataset<UnCopyableDataset> {
UnCopyableDataset() = default;
UnCopyableDataset(const UnCopyableDataset&) = delete;
UnCopyableDataset& operator=(const UnCopyableDataset&) = delete;
UnCopyableDataset(UnCopyableDataset&&) = default;
UnCopyableDataset& operator=(UnCopyableDataset&&) = default;
~UnCopyableDataset() override = default;
Example<> get(size_t index) override {
return {
torch::tensor({static_cast<int64_t>(index)}),
torch::tensor({static_cast<int64_t>(index)})};
}
torch::optional<size_t> size() const override {
return 100;
}
};
TEST(DataTest, MapDoesNotCopy) {
auto dataset = UnCopyableDataset()
.map(transforms::TensorLambda<>(
[](torch::Tensor tensor) { return tensor + 1; }))
.map(transforms::TensorLambda<>(
[](torch::Tensor tensor) { return tensor + 2; }))
.map(transforms::TensorLambda<>(
[](torch::Tensor tensor) { return tensor + 3; }));
auto data = dataset.get_batch(1).at(0).data;
ASSERT_EQ(data.numel(), 1);
ASSERT_EQ(data[0].item<float>(), 7);
}
TEST(DataTest, QueuePushAndPopFromSameThread) {
torch::data::detail::Queue<int> queue;
queue.push(1);
queue.push(2);
ASSERT_EQ(queue.pop(), 1);
ASSERT_EQ(queue.pop(), 2);
}
TEST(DataTest, QueuePopWithTimeoutThrowsUponTimeout) {
torch::data::detail::Queue<int> queue;
ASSERT_THROWS_WITH(
queue.pop(10 * kMillisecond),
"Timeout in DataLoader queue while waiting for next batch "
"(timeout was 10 ms)");
}
TEST(DataTest, QueuePushAndPopFromDifferentThreads) {
using torch::data::detail::Queue;
// First test: push batch and the pop in thread.
{
Queue<int> queue;
queue.push(1);
auto future =
std::async(std::launch::async, [&queue] { return queue.pop(); });
ASSERT_EQ(future.get(), 1);
}
// Second test: attempt to pop batch (and block), then push.
{
Queue<int> queue;
std::thread thread([&queue] {
std::this_thread::sleep_for(20 * kMillisecond);
queue.push(123);
});
ASSERT_EQ(queue.pop(), 123);
thread.join();
}
}
TEST(DataTest, QueueClearEmptiesTheQueue) {
torch::data::detail::Queue<int> queue;
queue.push(1);
queue.push(2);
queue.push(3);
ASSERT_EQ(queue.clear(), 3);
ASSERT_THROWS_WITH(queue.pop(1 * kMillisecond), "Timeout");
}
TEST(DataTest, DataShuttleCanPushAndPopJob) {
torch::data::detail::DataShuttle<int, int> shuttle;
shuttle.push_job(1);
shuttle.push_job(2);
ASSERT_EQ(shuttle.pop_job(), 1);
ASSERT_EQ(shuttle.pop_job(), 2);
}
TEST(DataTest, DataShuttleCanPushAndPopResult) {
torch::data::detail::DataShuttle<int, int> shuttle;
// pop_result() will only attempt to pop if there was a push_job() batch.
shuttle.push_job(1);
shuttle.push_job(2);
shuttle.pop_job();
shuttle.push_result(1);
ASSERT_EQ(shuttle.pop_result().value(), 1);
shuttle.pop_job();
shuttle.push_result(2);
ASSERT_EQ(shuttle.pop_result().value(), 2);
}
TEST(DataTest, DataShuttlePopResultReturnsNulloptWhenNoJobsInFlight) {
torch::data::detail::DataShuttle<int, int> shuttle;
ASSERT_FALSE(shuttle.pop_result().has_value());
shuttle.push_job(1);
shuttle.pop_job();
shuttle.push_result(1);
ASSERT_EQ(shuttle.pop_result().value(), 1);
ASSERT_FALSE(shuttle.pop_result().has_value());
ASSERT_FALSE(shuttle.pop_result().has_value());
}
TEST(DataTest, DataShuttleDrainMeansPopResultReturnsNullopt) {
torch::data::detail::DataShuttle<int, int> shuttle;
shuttle.push_job(1);
shuttle.push_result(1);
shuttle.drain();
ASSERT_FALSE(shuttle.pop_result().has_value());
}
TEST(DataTest, DataShuttlePopResultTimesOut) {
torch::data::detail::DataShuttle<int, int> shuttle;
shuttle.push_job(1);
ASSERT_THROWS_WITH(shuttle.pop_result(10 * kMillisecond), "Timeout");
}
struct UncopyableDataset : datasets::Dataset<UncopyableDataset, int> {
UncopyableDataset(const std::string& /* unused */) {}
UncopyableDataset(UncopyableDataset&&) = default;
UncopyableDataset& operator=(UncopyableDataset&&) = default;
UncopyableDataset(const UncopyableDataset&) = delete;
UncopyableDataset& operator=(const UncopyableDataset&) = delete;
int get(size_t index) override {
// NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions)
return 1 + index;
}
torch::optional<size_t> size() const override {
return 100;
}
};
TEST(DataTest, SharedBatchDatasetReallyIsShared) {
// This test will only compile if we really are not making any copies.
// There is otherwise no logic to test and because it is not deterministic
// how many and when worker threads access the shareddataset, we don't have
// any additional assertions here.
auto shared_dataset =
torch::data::datasets::make_shared_dataset<UncopyableDataset>(
"uncopyable");
auto data_loader = torch::data::make_data_loader(
shared_dataset, torch::data::DataLoaderOptions().workers(3));
for (auto batch : *data_loader) {
/* exhaust */
}
}
TEST(DataTest, SharedBatchDatasetDoesNotIncurCopyWhenPassedDatasetObject) {
// This will not compile if a copy is made.
auto shared_dataset =
torch::data::datasets::make_shared_dataset<UncopyableDataset>(
UncopyableDataset("uncopyable"));
ASSERT_EQ(shared_dataset.size().value(), 100);
}
struct TestIndex : public torch::data::samplers::CustomBatchRequest {
explicit TestIndex(size_t offset, std::vector<size_t> index)
: offset(offset), index(std::move(index)) {}
size_t size() const override {
return index.size();
}
size_t offset;
std::vector<size_t> index;
};
struct TestIndexDataset
: datasets::BatchDataset<TestIndexDataset, std::vector<int>, TestIndex> {
explicit TestIndexDataset(size_t size) : data(size) {
std::iota(data.begin(), data.end(), size_t(0));
}
std::vector<int> get_batch(TestIndex index) override {
std::vector<int> batch;
for (auto i : index.index) {
batch.push_back(index.offset + data.at(i));
}
return batch;
}
torch::optional<size_t> size() const override {
return data.size();
}
std::vector<int> data;
};
struct TestIndexSampler : public samplers::Sampler<TestIndex> {
explicit TestIndexSampler(size_t size) : size_(size) {}
void reset(torch::optional<size_t> new_size = torch::nullopt) override {}
torch::optional<TestIndex> next(size_t batch_size) override {
if (index_ >= size_) {
return torch::nullopt;
}
std::vector<size_t> indices(batch_size);
std::iota(indices.begin(), indices.end(), size_t(0));
index_ += batch_size;
return TestIndex(batch_size, std::move(indices));
}
void save(torch::serialize::OutputArchive& archive) const override {}
void load(torch::serialize::InputArchive& archive) override {}
size_t index_ = 0;
size_t size_;
};
TEST(DataTest, CanUseCustomTypeAsIndexType) {
const int kBatchSize = 10;
auto data_loader = torch::data::make_data_loader(
TestIndexDataset(23), TestIndexSampler(23), kBatchSize);
for (auto batch : *data_loader) {
for (const auto j : c10::irange(kBatchSize)) {
ASSERT_EQ(batch.at(j), 10 + j);
}
}
}
TEST(DataTest, DistributedRandomSamplerSingleReplicaProduceCorrectSamples) {
size_t sample_count = 10;
samplers::DistributedRandomSampler drs(sample_count);
std::vector<size_t> res;
torch::optional<std::vector<size_t>> idx;
while ((idx = drs.next(3)).has_value()) {
res.insert(std::end(res), std::begin(*idx), std::end(*idx));
}
ASSERT_EQ(res.size(), sample_count);
std::sort(res.begin(), res.end());
for (const auto i : c10::irange(res.size())) {
ASSERT_EQ(res[i], i);
}
}
TEST(DataTest, DistributedRandomSamplerMultiReplicaProduceCorrectSamples) {
size_t sample_count = 10;
size_t num_replicas = 3;
auto test_function = [&](bool allow_duplicates,
size_t local_sample_count,
std::vector<size_t>& output,
size_t batch_size) {
std::vector<std::unique_ptr<samplers::DistributedRandomSampler>> samplers;
for (const auto i : c10::irange(num_replicas)) {
samplers.emplace_back(
torch::make_unique<samplers::DistributedRandomSampler>(
sample_count, num_replicas, i, allow_duplicates));
}
std::vector<size_t> res;
for (const auto i : c10::irange(num_replicas)) {
(*samplers[i]).reset();
torch::optional<std::vector<size_t>> idx;
while ((idx = (*samplers[i]).next(batch_size)).has_value()) {
res.insert(std::end(res), std::begin(*idx), std::end(*idx));
}
ASSERT_EQ(res.size(), local_sample_count * (i + 1));
}
std::sort(res.begin(), res.end());
ASSERT_EQ(res, output);
};
for (size_t batch_size = 1; batch_size <= 3; ++batch_size) {
size_t local_sample_count =
static_cast<size_t>(std::ceil(sample_count * 1.0 / num_replicas));
std::vector<size_t> output1{0, 0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9};
test_function(true, local_sample_count, output1, batch_size);
local_sample_count =
static_cast<size_t>(std::floor(sample_count * 1.0 / num_replicas));
std::vector<size_t> output2{0, 1, 2, 3, 4, 5, 6, 7, 8};
test_function(false, local_sample_count, output2, batch_size);
}
}
TEST(DataTest, CanSaveAndLoadDistributedRandomSampler) {
{
samplers::DistributedRandomSampler a(10);
ASSERT_EQ(a.index(), 0);
std::stringstream stream;
torch::save(a, stream);
samplers::DistributedRandomSampler b(10);
torch::load(b, stream);
ASSERT_EQ(b.index(), 0);
}
{
samplers::DistributedRandomSampler a(10);
a.next(3);
a.next(4);
ASSERT_EQ(a.index(), 7);
std::stringstream stream;
torch::save(a, stream);
samplers::DistributedRandomSampler b(10);
torch::load(b, stream);
ASSERT_EQ(b.index(), 7);
}
{
samplers::DistributedRandomSampler a(10);
a.set_epoch(3);
std::stringstream stream;
torch::save(a, stream);
samplers::DistributedRandomSampler b(10);
torch::load(b, stream);
ASSERT_EQ(b.epoch(), 3);
}
}
TEST(DataTest, DistributedSequentialSamplerSingleReplicaProduceCorrectSamples) {
size_t sample_count = 10;
size_t batch_size = 3;
samplers::DistributedSequentialSampler dss(sample_count);
std::vector<size_t> res;
torch::optional<std::vector<size_t>> idx;
while ((idx = dss.next(batch_size)).has_value()) {
res.insert(std::end(res), std::begin(*idx), std::end(*idx));
}
ASSERT_EQ(res.size(), sample_count);
std::sort(res.begin(), res.end());
for (const auto i : c10::irange(res.size())) {
ASSERT_EQ(res[i], i);
}
}
TEST(DataTest, DistributedSequentialSamplerMultiReplicaProduceCorrectSamples) {
size_t sample_count = 10;
size_t num_replicas = 3;
auto test_function = [&](bool allow_duplicates,
size_t local_sample_count,
std::vector<size_t>& output,
size_t batch_size) {
std::vector<std::unique_ptr<samplers::DistributedSequentialSampler>>
samplers;
for (const auto i : c10::irange(num_replicas)) {
samplers.emplace_back(
torch::make_unique<samplers::DistributedSequentialSampler>(
sample_count, num_replicas, i, allow_duplicates));
}
std::vector<size_t> res;
for (const auto i : c10::irange(num_replicas)) {
(*samplers[i]).reset();
torch::optional<std::vector<size_t>> idx;
while ((idx = (*samplers[i]).next(batch_size)).has_value()) {
res.insert(std::end(res), std::begin(*idx), std::end(*idx));
}
ASSERT_EQ(res.size(), local_sample_count * (i + 1));
}
std::sort(res.begin(), res.end());
ASSERT_EQ(res, output);
};
for (size_t batch_size = 1; batch_size <= 3; ++batch_size) {
size_t local_sample_count =
static_cast<size_t>(std::ceil(sample_count * 1.0 / num_replicas));
std::vector<size_t> output1{0, 0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9};
test_function(true, local_sample_count, output1, batch_size);
local_sample_count =
static_cast<size_t>(std::floor(sample_count * 1.0 / num_replicas));
std::vector<size_t> output2{0, 1, 2, 3, 4, 5, 6, 7, 8};
test_function(false, local_sample_count, output2, batch_size);
}
}