-
Notifications
You must be signed in to change notification settings - Fork 699
/
Copy pathBackendTestUtils.cpp
1487 lines (1308 loc) · 59 KB
/
BackendTestUtils.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
/**
* Copyright (c) Glow Contributors. See CONTRIBUTORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "BackendTestUtils.h"
#include "glow/Converter/TypeAToTypeBFunctionConverter.h"
#include "glow/ExecutionEngine/ExecutionEngine.h"
#include "glow/Graph/Graph.h"
#include "glow/IR/IR.h"
#include "glow/IR/IRBuilder.h"
#include "glow/IR/Instrs.h"
#include "glow/Optimizer/GraphOptimizer/GraphOptimizer.h"
#include "glow/Quantization/Quantization.h"
#include "gtest/gtest.h"
#include "llvm/Support/CommandLine.h"
#include <future>
namespace glow {
llvm::cl::OptionCategory backendTestUtilsCat("BackendTestUtils Category");
unsigned parCloneCountOpt;
llvm::cl::opt<unsigned, /* ExternalStorage */ true> parCloneCountI(
"parallel-clone-count",
llvm::cl::desc(
"Number of times to clone a graph in parallel. Intended to stress test "
"different backends. This option is not used by all unit "
"tests; for now you must check the test to see if so."),
llvm::cl::location(parCloneCountOpt), llvm::cl::Optional, llvm::cl::init(1),
llvm::cl::cat(backendTestUtilsCat));
bool runDisabledTests;
llvm::cl::opt<bool, /* ExternalStorage */ true> runDisabledTestsI(
"run-disabled-tests",
llvm::cl::desc("If set, disabled tests will not be skipped."),
llvm::cl::location(runDisabledTests), llvm::cl::Optional,
llvm::cl::init(false), llvm::cl::cat(backendTestUtilsCat));
using llvm::cast;
namespace {
static Placeholder *createQuantizedPlaceholder(Module &mod,
PlaceholderBindings &bindings,
Tensor *tensor, float scale,
int32_t offset,
llvm::StringRef name) {
auto *P = mod.createPlaceholder(tensor->getElementType(), tensor->dims(),
scale, offset, name, false);
auto *PTensor = bindings.allocate(P);
PTensor->assign(tensor);
return P;
}
/// Create and initialize a function using the argument \p createAndInitFunction
/// then run the function in profiling mode to get the profiling parameters.
/// \p count is the number of times to clone the Function inside itself before
/// profiling. \returns the profiling parameters for all the function nodes.
static std::vector<NodeProfilingInfo>
profileAndGetNodeProfilingInfo(CreateAndInitFunction createAndInitFunction,
unsigned count) {
LoweredInfoMap loweredMapForProf;
PlaceholderBindings pBindings;
// Note: deviceMemory = 0 is a signal to use the defaultMemory.
ExecutionEngine PEE{"Interpreter", /* deviceMemory */ 0,
/* ignoreUserDeviceConfig */ true};
auto FT = createAndInitFunction(pBindings, PEE);
CompilationContext cctx{&pBindings, &loweredMapForProf};
// Clone the number of times as requested to match the Function that will be
// quantized.
cloneFunInsideFun(FT, &pBindings, cctx, count);
cctx.precisionConfig.quantMode = QuantizationMode::Profile;
PEE.compile(cctx);
PEE.run(pBindings);
// We get the new function using front() because the original function was
// deleted as part of the Partitioner quantization flow.
return quantization::generateNodeProfilingInfos(
pBindings, PEE.getModule().getFunctions().front(), loweredMapForProf);
}
/// Helper that sets up and \returns a pair of configs for both interpreter and
/// backend being tested.
static std::pair<CompilationContext, CompilationContext>
setupInterpAndBackendConfigs(
Function *IF, ExecutionEngine &IEE, PlaceholderBindings &iBindings,
LoweredInfoMap &ILIM, PlaceholderBindings &bBindings, LoweredInfoMap &BLIM,
ElemKind interpElemKind, ElemKind backendElemKind,
quantization::Schema schema, bool convertToRowwiseQuantization,
CreateAndInitFunction createAndInitFunction, ElemKind biasElemKind,
bool forceFP16AccumSLS, PrecisionConfiguration::Float16Format float16Format,
unsigned count, bool convertToChannelwiseQuantization,
bool skipQuantizeFCBias) {
CompilationContext cctxI{&iBindings, &ILIM};
CompilationContext cctxB{&bBindings, &BLIM};
PrecisionConfiguration &precConfigI = cctxI.precisionConfig;
PrecisionConfiguration &precConfigB = cctxB.precisionConfig;
if (isQuantizedElemKind(interpElemKind) ||
isQuantizedElemKind(backendElemKind)) {
// If either interp or backend need to be quantized then we need to profile
// and get quantization infos.
if (isQuantizedElemKind(interpElemKind)) {
// Note: We only do parallel cloning for the backend, so always use count
// of 1 here.
auto NQII =
profileAndGetNodeProfilingInfo(createAndInitFunction, /* count */ 1);
precConfigI.quantMode = QuantizationMode::Quantize;
precConfigI.quantConfig.infos = NQII;
precConfigI.quantConfig.enableRowwise = convertToRowwiseQuantization;
precConfigI.quantConfig.enableChannelwise =
convertToChannelwiseQuantization;
precConfigI.quantConfig.schema = schema;
precConfigI.quantConfig.precision = interpElemKind;
precConfigI.quantConfig.assertAllNodesQuantized = true;
precConfigI.quantConfig.precisionBias = biasElemKind;
precConfigI.quantConfig.skipQuantizeFCBias = skipQuantizeFCBias;
}
if (isQuantizedElemKind(backendElemKind)) {
// Always clone count times here. This matches the Function the backend
// will quantize.
auto NQIB = profileAndGetNodeProfilingInfo(createAndInitFunction, count);
precConfigB.quantMode = QuantizationMode::Quantize;
precConfigB.quantConfig.infos = NQIB;
precConfigB.quantConfig.enableRowwise = convertToRowwiseQuantization;
precConfigB.quantConfig.enableChannelwise =
convertToChannelwiseQuantization;
precConfigB.quantConfig.schema = schema;
precConfigB.quantConfig.precision = backendElemKind;
precConfigB.quantConfig.assertAllNodesQuantized = true;
precConfigB.quantConfig.precisionBias = biasElemKind;
precConfigB.quantConfig.skipQuantizeFCBias = skipQuantizeFCBias;
}
}
// For now if the ElemKind is FP16 then we use Float16Ty, UInt8FusedFP16QTy.
precConfigI.convertToFP16 = interpElemKind == ElemKind::Float16Ty;
precConfigI.convertFusedToFP16 = interpElemKind == ElemKind::Float16Ty;
precConfigI.forceFP16AccumSLS = forceFP16AccumSLS;
precConfigB.convertToFP16 = backendElemKind == ElemKind::Float16Ty;
precConfigB.convertFusedToFP16 = backendElemKind == ElemKind::Float16Ty;
precConfigB.forceFP16AccumSLS = forceFP16AccumSLS;
return std::make_pair(cctxI, cctxB);
}
} // namespace
void dispatchInference(const std::string &fname,
runtime::HostManager *hostManager,
ExecutionContext &context,
unsigned concurrentRequestsOpt,
bool useNewExecutionContext) {
// If additional requests are desired, setup additional contexts.
std::vector<std::unique_ptr<ExecutionContext>> contexts;
std::unique_ptr<ExecutionContext> originalContextPtr(&context);
contexts.push_back(std::move(originalContextPtr));
if (concurrentRequestsOpt > 1) {
// Clone the placeholder bindings into a new executionContext.
for (unsigned i = 0, max = concurrentRequestsOpt - 1; i < max; i++) {
std::unique_ptr<ExecutionContext> newContext =
(useNewExecutionContext)
? glow::make_unique<ExecutionContext>()
: glow::make_unique<ExecutionContext>(
glow::make_unique<PlaceholderBindings>(
context.getPlaceholderBindings()->clone()));
contexts.push_back(std::move(newContext));
}
}
std::vector<std::promise<void>> promises(concurrentRequestsOpt);
std::vector<std::future<void>> futures;
for (auto &promise : promises) {
futures.push_back(promise.get_future());
}
for (unsigned i = 0; i < concurrentRequestsOpt; i++) {
hostManager->runNetwork(fname, std::move(contexts[i]),
[&contexts, &promises,
i](runtime::RunIdentifierTy, Error err,
std::unique_ptr<ExecutionContext> contextPtr) {
contexts[i] = std::move(contextPtr);
// Expect no errors.
EXIT_ON_ERR(std::move(err));
promises[i].set_value();
});
}
for (auto &future : futures) {
future.wait();
}
for (auto &c : contexts) {
c->getPlaceholderBindings()->ensureOnHost();
}
// Release the original context passed in by reference so we don't free it.
contexts[0].release();
}
/// Helper that iterates over all of the Placeholders from the function \p F
/// and converts the Tensors found in \p bindings to the same type as the
/// Placeholders if necessary.
static void convertBindingsToCorrectType(Function *F,
PlaceholderBindings &bindings) {
PlaceholderList PHs = F->findPlaceholders();
for (Placeholder *PH : PHs) {
Tensor *T = bindings.get(PH);
TypeRef newTy = PH->getType();
if (T->getType().isEqual(newTy)) {
continue;
}
// For input placeholders convert tensor type and values.
// For output placeholders convert only the tensor type.
if (isInput(PH, *F)) {
ElemKind newK = newTy->getElementType();
if (isQuantizedElemKind(newK)) {
Tensor QT = quantization::quantizeTensor(
*T, {newTy->getScale(), newTy->getOffset()}, newK);
T->assign(&QT);
} else {
T->convertToType(newK);
}
} else {
T->reset(*newTy);
}
}
}
/// Helper to get a float copy of a Tensor \p T if needed.
static Tensor convertToFloatIfNecessary(Tensor &T) {
const ElemKind srcK = T.getType().getElementType();
if (srcK == ElemKind::FloatTy) {
return T.clone();
}
if (isQuantizedElemKind(srcK)) {
return quantization::dequantizeTensor(T, ElemKind::FloatTy);
}
return T.getCopyConvertedToType(ElemKind::FloatTy);
}
void compareAgainstInterpreter(
llvm::StringRef backendName, CreateAndInitFunction createAndInitFunction,
ElemKind interpElemKind, ElemKind backendElemKind, float allowedError,
unsigned count, bool convertToRowwiseQuantization,
quantization::Schema schema, ElemKind biasElemKind, bool forceFP16AccumSLS,
PrecisionConfiguration::Float16Format float16Format,
bool convertToChannelwiseQuantization, bool skipQuantizeFCBias) {
// Note: deviceMemory = 0 is a signal to use the defaultMemory.
ExecutionEngine IEE{"Interpreter", /* deviceMemory */ 0,
/* ignoreUserDeviceConfig */ true};
ExecutionEngine BEE{backendName};
PlaceholderBindings iBindings, bBindings;
LOG(INFO) << "Comparing Interpreter with precision "
<< Type::getElementName(interpElemKind).str() << " against "
<< backendName.str() << " with precision "
<< Type::getElementName(backendElemKind).str() << " with Bias "
<< (skipQuantizeFCBias ? "unquantized"
: Type::getElementName(biasElemKind).str())
<< " with FP16 AccumulationSLS " << forceFP16AccumSLS;
// Create the same network on the interpreter and the backend being tested.
FunctionTensorPair IFT = createAndInitFunction(iBindings, IEE);
FunctionTensorPair BFT = createAndInitFunction(bBindings, BEE);
Function *IF = IFT.first;
// Set up the configs for interpreter and backend. If one or both functions
// will be quantized, then gather a profile the graph on the interpreter, and
// then quantize the Functions as requested.
LoweredInfoMap ILIM, BLIM;
auto configs = setupInterpAndBackendConfigs(
IF, IEE, iBindings, ILIM, bBindings, BLIM, interpElemKind,
backendElemKind, schema, convertToRowwiseQuantization,
createAndInitFunction, biasElemKind, forceFP16AccumSLS, float16Format,
count, convertToChannelwiseQuantization, skipQuantizeFCBias);
CompilationContext &cctxI = configs.first;
CompilationContext &cctxB = configs.second;
// Skip conversion for rowwise quantized tests as they are a special case
// which don't fit cleanly here -- e.g. RWQ-SLS has FloatTy outputs.
if (!convertToRowwiseQuantization) {
// We want to compare the ops themselves and not see differences in
// conversion, so fold ElemKind conversion nodes into IO.
cctxI.optimizationOpts.foldElemKindConversionIntoIO = true;
cctxB.optimizationOpts.foldElemKindConversionIntoIO = true;
}
// Clone the Function inside itself many times if desired.
std::unordered_set<Tensor *> resultTensors =
cloneFunInsideFun(BFT, &bBindings, cctxB, count);
assert(resultTensors.size() == count &&
"Should get the same number of Tensors back as count.");
IEE.compile(cctxI);
BEE.compile(cctxB);
// Again skip rowwise quantization as before.
if (!convertToRowwiseQuantization) {
// Now that we have compiled, precision transformation has occurred. Now
// convert all mismatches for Placeholders given their original bindings.
convertBindingsToCorrectType(IEE.getSingleFunctionFromModule(), iBindings);
convertBindingsToCorrectType(BEE.getSingleFunctionFromModule(), bBindings);
}
IEE.run(iBindings);
BEE.run(bBindings);
// Compare each of our result tensors to the original. Always convert back to
// float if necessary, as allowed error is expected to compare float.
Tensor finalIT = convertToFloatIfNecessary(*IFT.second);
for (Tensor *T : resultTensors) {
Tensor finalBT = convertToFloatIfNecessary(*T);
EXPECT_TRUE(finalIT.isEqual(finalBT, allowedError, /* verbose */ true));
}
// Additionally check that each of the results from the parallel cloned
// Functions are bitwise equal.
auto it = resultTensors.begin();
Tensor *firstResult = *it;
for (it++; it != resultTensors.end(); it++) {
EXPECT_TRUE(firstResult->isBitwiseEqual(**it));
}
}
std::unordered_set<Tensor *> cloneFunInsideFun(FunctionTensorPair FTP,
PlaceholderBindings *bindings,
CompilationContext &cctx,
unsigned count) {
Function *origF = FTP.first;
// Always save the original Function's Tensor, which we will keep around.
std::unordered_set<Tensor *> resultTensors;
resultTensors.insert(FTP.second);
// Nothing to do if we just want the one.
if (count == 1) {
return resultTensors;
}
Module *mod = origF->getParent();
// Clone the original Function to repeatedly add it to the original.
auto *cloneF = origF->clone("single_clone");
// We keep the original Function, then clone/add count-1 more.
for (size_t i = 1; i < count; i++) {
// Clone the clone, and then add all the new nodes to the original function.
auto *tmpF = cloneF->clone("tmp" + std::to_string(i));
std::unordered_set<Node *> clonedNodes;
[[maybe_unused]] bool foundSaveNode = false;
for (auto &N : tmpF->getNodes()) {
clonedNodes.insert(&N);
// For every Node we add, check if it uses a Placeholder node, and if so
// clone it in the Module so that CSE doesn't undo all our hard work.
for (size_t j = 0, f = N.getNumInputs(); j < f; j++) {
Placeholder *origPH = llvm::dyn_cast<Placeholder>(N.getNthInput(j));
if (!origPH) {
continue;
}
// Clone the Placeholder, allocate it in the bindings, and replace the
// usage of the original node to point to the clone.
Placeholder *clonePH = mod->createPlaceholder(
origPH->getType(), origPH->getName(), origPH->isTraining());
Tensor *oldT = bindings->get(origPH);
assert(oldT);
Tensor *newT = bindings->allocate(clonePH);
newT->assign(oldT);
N.setNthInput(j, clonePH);
// Save the result Tensors to return so we can compare the results of
// all of our clones.
if (llvm::isa<SaveNode>(N)) {
assert(!foundSaveNode &&
"Can only handle Functions with a single SaveNode.");
foundSaveNode = true;
resultTensors.insert(newT);
}
}
}
for (auto &N : clonedNodes) {
origF->takeOwnershipOfNode(N);
}
mod->eraseFunction(tmpF);
}
// Now erase the clone we used to copy in, as it's no longer needed.
mod->eraseFunction(cloneF);
// Finally, duplicate all of the node profiling infos with the new expected
// clone's name so that the cloned copies will find the same profiling info
// as the original node if being quantized.
auto &origInfos = cctx.precisionConfig.quantConfig.infos;
origInfos.reserve(count * origInfos.size());
std::vector<NodeProfilingInfo> newInfos;
newInfos.reserve((count - 1) * origInfos.size());
for (const auto &PI : origInfos) {
const size_t colonIdx = PI.nodeOutputName_.find(":");
assert(colonIdx != std::string::npos && "Name should always contain ':'");
for (size_t i = 1; i < count; i++) {
std::string newName(PI.nodeOutputName_);
// Cloned nodes end up with the original name plus the count number
// appended to their name due to uniquing. Replicate the same thing.
newName.insert(colonIdx, std::to_string(i));
newInfos.emplace_back(newName, PI.tensorProfilingParams_);
}
}
origInfos.insert(origInfos.end(), newInfos.begin(), newInfos.end());
return resultTensors;
}
unsigned countNodeKind(Function *F, Kinded::Kind kind) {
unsigned count = 0;
for (auto &n : F->getNodes()) {
if (n.getKind() == kind) {
count++;
}
}
return count;
}
void inferIntLookupTableNetInt8(Tensor *input, Tensor *out,
llvm::ArrayRef<int8_t> table,
llvm::StringRef kind) {
PlaceholderBindings bindings;
ExecutionEngine EE(kind);
auto &mod = EE.getModule();
Function *F = mod.createFunction("main");
auto outTy = mod.uniqueType(ElemKind::Int8QTy, {(dim_t)input->size()}, 3, 3);
auto var = createQuantizedPlaceholder(mod, bindings, input,
input->getType().getScale(),
input->getType().getOffset(), "var");
auto *lookupTable = F->createIntLookupTable("lookuptable", var, table, outTy);
auto *result = F->createSave("ret", lookupTable);
auto *resultTensor = bindings.allocate(result->getPlaceholder());
EE.compile(CompilationMode::Infer);
bindings.allocate(mod.getPlaceholders());
updateInputPlaceholders(bindings, {var}, {input});
EE.run(bindings);
out->assign(resultTensor);
}
void inferIntLookupTableNetInt16(Tensor *input, Tensor *out,
llvm::ArrayRef<int16_t> table,
llvm::StringRef kind) {
PlaceholderBindings bindings;
ExecutionEngine EE(kind);
auto &mod = EE.getModule();
Function *F = mod.createFunction("main");
auto outTy = mod.uniqueType(ElemKind::Int16QTy, {(dim_t)input->size()}, 3, 3);
auto var = createQuantizedPlaceholder(mod, bindings, input,
input->getType().getScale(),
input->getType().getOffset(), "var");
auto *lookupTable = F->createIntLookupTable("lookuptable", var, table, outTy);
auto *result = F->createSave("ret", lookupTable);
auto *resultTensor = bindings.allocate(result->getPlaceholder());
EE.compile(CompilationMode::Infer);
bindings.allocate(mod.getPlaceholders());
updateInputPlaceholders(bindings, {var}, {input});
EE.run(bindings);
out->assign(resultTensor);
}
void inferConvNet(Tensor *inputs, Tensor *filter, Tensor *bias, Tensor *out,
llvm::StringRef kind) {
PlaceholderBindings bindings;
ExecutionEngine EE(kind);
auto &mod = EE.getModule();
Function *F = mod.createFunction("main");
Placeholder *inputP;
Placeholder *filterP;
Placeholder *biasP;
Placeholder *outP;
TypeRef OT;
if (inputs->getType().isQuantizedType()) {
auto &outType = out->getType();
auto &inType = inputs->getType();
auto &filterType = filter->getType();
auto &biasType = bias->getType();
inputP = createQuantizedPlaceholder(
mod, bindings, inputs, inType.getScale(), inType.getOffset(), "inputP");
filterP =
createQuantizedPlaceholder(mod, bindings, filter, filterType.getScale(),
filterType.getOffset(), "filterP");
biasP = createQuantizedPlaceholder(mod, bindings, bias, biasType.getScale(),
biasType.getOffset(), "biasP");
outP = createQuantizedPlaceholder(mod, bindings, out, outType.getScale(),
outType.getOffset(), "outP");
OT = F->getParent()->uniqueType(out->getElementType(), out->dims(),
outType.getScale(), outType.getOffset());
} else {
inputP = createPlaceholder(mod, bindings, inputs, "inputP");
filterP = createPlaceholder(mod, bindings, filter, "filterP");
biasP = createPlaceholder(mod, bindings, bias, "biasP");
outP = createPlaceholder(mod, bindings, out, "outP");
OT = F->getParent()->uniqueType(out->getElementType(), out->dims());
}
auto *conv = F->createConv("conv", inputP, filterP, biasP, OT, 5, 3, 4, 1);
auto *result = F->createSave("ret", conv, outP);
auto *resultTensor = bindings.get(result->getPlaceholder());
EE.compile(CompilationMode::Infer);
updateInputPlaceholders(bindings, {inputP, filterP, biasP},
{inputs, filter, bias});
EE.run(bindings);
out->assign(resultTensor);
}
int inferConvReluNet(Tensor *inputs, Tensor *filter, Tensor *bias, Tensor *out,
unsigned_t kernel, unsigned_t stride, unsigned_t pad,
llvm::StringRef kind) {
PlaceholderBindings bindings;
ExecutionEngine EE(kind);
auto &mod = EE.getModule();
Function *F = mod.createFunction("main");
Placeholder *inputP;
Placeholder *filterP;
Placeholder *biasP;
Placeholder *outP;
TypeRef OT;
if (inputs->getType().isQuantizedType()) {
auto &outType = out->getType();
auto &inType = inputs->getType();
auto &filterType = filter->getType();
auto &biasType = bias->getType();
inputP = createQuantizedPlaceholder(
mod, bindings, inputs, inType.getScale(), inType.getOffset(), "inputP");
filterP =
createQuantizedPlaceholder(mod, bindings, filter, filterType.getScale(),
filterType.getOffset(), "filterP");
biasP = createQuantizedPlaceholder(mod, bindings, bias, biasType.getScale(),
biasType.getOffset(), "biasP");
outP = createQuantizedPlaceholder(mod, bindings, out, outType.getScale(),
outType.getOffset(), "outP");
OT = F->getParent()->uniqueType(out->getElementType(), out->dims(),
outType.getScale(), outType.getOffset());
} else {
inputP = createPlaceholder(mod, bindings, inputs, "inputP");
filterP = createPlaceholder(mod, bindings, filter, "filterP");
biasP = createPlaceholder(mod, bindings, bias, "biasP");
outP = createPlaceholder(mod, bindings, out, "outP");
OT = F->getParent()->uniqueType(out->getElementType(), out->dims());
}
auto *conv =
F->createConv("conv", inputP, filterP, biasP, OT, kernel, stride, pad, 1);
// Relu
auto *relu = F->createRELU("relu", conv);
auto *result = F->createSave("ret", relu, outP);
auto *resultTensor = bindings.get(result->getPlaceholder());
EE.compile(CompilationMode::Infer);
// check fusion depending on build option.
// EXPECT_EQ(conv->getFusedActivation(), FusedActivation::RELU);
updateInputPlaceholders(bindings, {inputP, filterP, biasP},
{inputs, filter, bias});
EE.run(bindings);
out->assign(resultTensor);
return conv->getFusedActivation();
}
void trainConvNet(Tensor *inputs, Tensor *kernel1, Tensor *bias1,
Tensor *kernel2, Tensor *bias2, Tensor *selected,
llvm::ArrayRef<dim_t> shape1, llvm::ArrayRef<dim_t> shape2,
Tensor *out, llvm::StringRef kind) {
ExecutionEngine EET(kind);
ExecutionEngine EEI(kind);
std::vector<ExecutionEngine *> engines;
engines.push_back(&EEI);
engines.push_back(&EET);
TrainingConfig TC;
PlaceholderBindings bindings, inferBindings, trainingBindings;
// This variable records the number of the next sample to be used for
// training.
size_t sampleCounter = 0;
TC.learningRate = 0.03;
TC.momentum = 0.3;
TC.L2Decay = 0.01;
Function *F;
Placeholder *var1, *var2;
for (auto *EE : engines) {
auto &mod = EE->getModule();
F = mod.createFunction("main");
var1 = createPlaceholder(mod, bindings, inputs, "var1");
var2 = createPlaceholder(mod, bindings, selected, "var2");
auto *conv1 = F->createConv(bindings, "conv1", var1, 3, {5, 3}, {2, 1},
{2, 1, 2, 1}, 1);
bindings.get(cast<Placeholder>(conv1->getFilter()))->assign(kernel1);
bindings.get(cast<Placeholder>(conv1->getBias()))->assign(bias1);
auto *reshape1 = F->createReshape("reshape1", conv1, shape1);
auto *conv2 = F->createConv(bindings, "conv2", reshape1, 2, 2, 2, 0, 1);
bindings.get(cast<Placeholder>(conv2->getFilter()))->assign(kernel2);
bindings.get(cast<Placeholder>(conv2->getBias()))->assign(bias2);
auto *reshape2 = F->createReshape("reshape2", conv2, shape2);
auto *softmax = F->createSoftMax("softmax", reshape2, var2);
F->createSave("ret", softmax);
}
auto *TF = glow::differentiate(F, TC);
auto tfName = TF->getName();
auto fName = F->getName();
EET.compile(CompilationMode::Train);
trainingBindings.allocate(EET.getModule().getPlaceholders());
inferBindings.allocate(EEI.getModule().getPlaceholders());
bindings.copyTrainableWeightsTo(trainingBindings);
auto *res =
inferBindings.get(EEI.getModule().getPlaceholderByNameSlow("ret"));
runBatch(EET, trainingBindings, 8, sampleCounter, {var1, var2},
{inputs, selected}, tfName);
trainingBindings.copyTrainableWeightsTo(inferBindings);
EEI.compile(CompilationMode::Infer);
var1 = inferBindings.getPlaceholderByNameSlow("var1");
var2 = inferBindings.getPlaceholderByNameSlow("var2");
updateInputPlaceholders(inferBindings, {var1, var2}, {inputs, selected});
EEI.run(inferBindings, fName);
out->assign(res);
}
void inferLocalResponseNormalizationNet(Tensor *inputs, Tensor *out,
llvm::StringRef kind) {
PlaceholderBindings bindings;
ExecutionEngine EE(kind);
auto &mod = EE.getModule();
Function *F = mod.createFunction("main");
auto *var = createPlaceholder(mod, bindings, inputs, "var");
auto *lrn = F->createLocalResponseNormalization("lrn", var, 5, 3.0, 0.5, 1.5);
auto *result = F->createSave("ret", lrn);
auto *resultTensor = bindings.allocate(result->getPlaceholder());
EE.compile(CompilationMode::Infer);
updateInputPlaceholders(bindings, {var}, {inputs});
EE.run(bindings);
out->assign(resultTensor);
}
void trainLocalResponseNormalizationNet(Tensor *inputs, Tensor *weights,
Tensor *bias, Tensor *selected,
llvm::ArrayRef<dim_t> shape1,
llvm::ArrayRef<dim_t> shape2,
Tensor *out, llvm::StringRef kind) {
PlaceholderBindings bindings, trainingBindings;
ExecutionEngine EET(kind);
ExecutionEngine EEI(kind);
std::vector<ExecutionEngine *> engines{&EEI, &EET};
TrainingConfig TC;
// This variable records the number of the next sample to be used for
// training.
size_t sampleCounter = 0;
TC.learningRate = 0.06;
TC.momentum = 0.1;
TC.L2Decay = 0.01;
Placeholder *var1, *var2;
std::string fName;
for (auto *EE : engines) {
auto &mod = EE->getModule();
Function *F = mod.createFunction("main");
fName = F->getName().str();
var1 = createPlaceholder(mod, bindings, inputs, "var1");
var2 = createPlaceholder(mod, bindings, selected, "var2");
auto *fc = F->createFullyConnected(bindings, "fc", var1, bias->dims()[0]);
bindings.get(cast<Placeholder>(fc->getWeights()))->assign(weights);
bindings.get(cast<Placeholder>(fc->getBias()))->assign(bias);
auto *reshape1 = F->createReshape("reshape1", fc, shape1);
auto *lrn =
F->createLocalResponseNormalization("lrn", reshape1, 2, 2.0, 0.5, 1.0);
auto *reshape2 = F->createReshape("reshape2", lrn, shape2);
auto *softmax = F->createSoftMax("softmax", reshape2, var2);
auto *result = F->createSave("ret", softmax);
bindings.allocate(result->getPlaceholder());
}
auto *TF = glow::differentiate(EET.getModule().getFunction(fName), TC);
auto tfName = TF->getName();
EET.compile(CompilationMode::Train);
trainingBindings.allocate(EET.getModule().getPlaceholders());
bindings.copyTrainableWeightsTo(trainingBindings);
bindings.clear();
bindings.allocate(EEI.getModule().getPlaceholders());
runBatch(EET, trainingBindings, 8, sampleCounter, {var1, var2},
{inputs, selected}, tfName);
trainingBindings.copyTrainableWeightsTo(bindings);
var1 = bindings.getPlaceholderByNameSlow("var1");
var2 = bindings.getPlaceholderByNameSlow("var2");
EEI.compile(CompilationMode::Infer);
runBatch(EEI, bindings, 1, sampleCounter, {var1, var2}, {inputs, selected});
out->assign(bindings.get(bindings.getPlaceholderByNameSlow("ret")));
}
void trainAvgPoolNet(Tensor *inputs, Tensor *weights, Tensor *bias,
Tensor *selected, llvm::ArrayRef<dim_t> shape1,
llvm::ArrayRef<dim_t> shape2, Tensor *out,
llvm::StringRef kind) {
ExecutionEngine EET(kind);
ExecutionEngine EEI(kind);
std::vector<ExecutionEngine *> engines{&EEI, &EET};
TrainingConfig TC;
PlaceholderBindings bindings, trainingBindings;
// This variable records the number of the next sample to be used for
// training.
size_t sampleCounter = 0;
TC.learningRate = 0.01;
TC.momentum = 0.4;
TC.L2Decay = 0.01;
Placeholder *var1, *var2;
std::string fName;
for (auto *EE : engines) {
auto &mod = EE->getModule();
Function *F = mod.createFunction("main");
fName = F->getName().str();
var1 = createPlaceholder(mod, bindings, inputs, "var1");
var2 = createPlaceholder(mod, bindings, selected, "var2");
auto *fc = F->createFullyConnected(bindings, "fc", var1, bias->dims()[0]);
bindings.get(cast<Placeholder>(fc->getWeights()))->assign(weights);
bindings.get(cast<Placeholder>(fc->getBias()))->assign(bias);
auto *reshape1 = F->createReshape("reshape1", fc, shape1);
auto *pool = F->createAvgPool("pool", reshape1, 2, 2, 0);
auto *reshape2 = F->createReshape("reshape2", pool, shape2);
auto *softmax = F->createSoftMax("softmax", reshape2, var2);
auto *result = F->createSave("ret", softmax);
bindings.allocate(result->getPlaceholder());
}
auto *TF = glow::differentiate(EET.getModule().getFunction("main"), TC);
auto tfName = TF->getName();
EET.compile(CompilationMode::Train);
trainingBindings.allocate(EET.getModule().getPlaceholders());
bindings.copyTrainableWeightsTo(trainingBindings);
bindings.clear();
bindings.allocate(EEI.getModule().getPlaceholders());
runBatch(EET, trainingBindings, 10, sampleCounter, {var1, var2},
{inputs, selected}, tfName);
trainingBindings.copyTrainableWeightsTo(bindings);
var1 = bindings.getPlaceholderByNameSlow("var1");
var2 = bindings.getPlaceholderByNameSlow("var2");
EEI.compile(CompilationMode::Infer);
updateInputPlaceholders(bindings, {var1, var2}, {inputs, selected});
EEI.run(bindings);
out->assign(bindings.get(bindings.getPlaceholderByNameSlow("ret")));
}
void trainMaxPoolNet(Tensor *inputs, Tensor *weights, Tensor *bias,
Tensor *selected, llvm::ArrayRef<dim_t> shape1,
llvm::ArrayRef<dim_t> shape2, Tensor *out,
llvm::StringRef kind) {
ExecutionEngine EET(kind);
ExecutionEngine EEI(kind);
std::vector<ExecutionEngine *> engines;
engines.push_back(&EEI);
engines.push_back(&EET);
TrainingConfig TC;
PlaceholderBindings bindings, inferBindings, trainingBindings;
// This variable records the number of the next sample to be used for
// training.
size_t sampleCounter = 0;
TC.learningRate = 0.03;
TC.momentum = 0.3;
TC.L2Decay = 0.003;
Function *F;
Placeholder *var1, *var2;
for (auto *EE : engines) {
bindings.clear();
auto &mod = EE->getModule();
F = mod.createFunction("main");
var1 = createPlaceholder(mod, bindings, inputs, "var1");
var2 = createPlaceholder(mod, bindings, selected, "var2");
auto *fc = F->createFullyConnected(bindings, "fc", var1, bias->dims()[0]);
bindings.get(cast<Placeholder>(fc->getWeights()))->assign(weights);
bindings.get(cast<Placeholder>(fc->getBias()))->assign(bias);
auto *reshape1 = F->createReshape("reshape1", fc, shape1);
auto *pool = F->createMaxPool("pool", reshape1, 5, 3, 4);
auto *reshape2 = F->createReshape("reshape2", pool->getResult(), shape2);
auto *softmax = F->createSoftMax("softmax", reshape2, var2);
F->createSave("ret", softmax);
}
auto *TF = glow::differentiate(F, TC);
auto fName = F->getName();
auto tfName = TF->getName();
EET.compile(CompilationMode::Train);
trainingBindings.allocate(EET.getModule().getPlaceholders());
inferBindings.allocate(EEI.getModule().getPlaceholders());
bindings.copyTrainableWeightsTo(trainingBindings);
auto *res =
inferBindings.get(EEI.getModule().getPlaceholderByNameSlow("ret"));
runBatch(EET, trainingBindings, 7, sampleCounter, {var1, var2},
{inputs, selected}, tfName);
trainingBindings.copyTrainableWeightsTo(inferBindings);
EEI.compile(CompilationMode::Infer);
var1 = inferBindings.getPlaceholderByNameSlow("var1");
var2 = inferBindings.getPlaceholderByNameSlow("var2");
runBatch(EEI, inferBindings, 1, sampleCounter, {var1, var2},
{inputs, selected}, fName);
out->assign(res);
}
void inferSmallConv(Tensor *inputs, Tensor *out, llvm::StringRef kind) {
PlaceholderBindings bindings;
ExecutionEngine EE(kind);
auto &mod = EE.getModule();
auto *F = mod.createFunction("main");
auto *in = createPlaceholder(mod, bindings, inputs, "in", "NHWC");
auto *C = F->createConv(bindings, "conv2a", in, 64, 1, 1, 0, 1);
bindings.get(cast<Placeholder>(C->getFilter()))->getHandle().clear(0.3);
bindings.get(cast<Placeholder>(C->getBias()))->getHandle().clear(0.4);
auto *result = F->createSave("ret", C);
auto *resultTensor = bindings.allocate(result->getPlaceholder());
convertPlaceholdersToConstants(F, bindings, {in, result->getPlaceholder()});
EE.compile(CompilationMode::Infer);
updateInputPlaceholders(bindings, {in}, {inputs});
EE.run(bindings);
out->assign(resultTensor);
}
void inferGroupConv(Tensor *out, llvm::StringRef kind) {
PlaceholderBindings bindings;
ExecutionEngine EE(kind);
auto &mod = EE.getModule();
auto *F = mod.createFunction("main");
auto *input =
mod.createPlaceholder(ElemKind::FloatTy, {1, 2, 1, 32}, "input", false);
auto *inputTensor = bindings.allocate(input);
auto IH = inputTensor->getHandle();
for (size_t i = 0; i < 2 * 32; i++) {
IH.raw(i) = (i + 1) / 10.0;
}
auto *filter = mod.createPlaceholder(ElemKind::FloatTy, {128, 1, 1, 16},
"filter", false);
auto *filterTensor = bindings.allocate(filter);
auto FH = filterTensor->getHandle();
for (dim_t i = 0; i < 128; i++)
for (dim_t j = 0; j < 16; j++) {
FH.at({i, 0, 0, j}) = (i + j) / 100.0;
}
auto *zeroBias =
mod.createPlaceholder(ElemKind::FloatTy, {128}, "bias", false);
auto *zeroBiasTensor = bindings.allocate(zeroBias);
zeroBiasTensor->zero();
auto outTy = mod.uniqueType(ElemKind::FloatTy, {1, 2, 1, 128});
ConvolutionNode *CN =
F->createConv("Conv", input, filter, zeroBias, outTy, 1, 1, 0, 2);
SaveNode *result = F->createSave("save", CN);
auto *resultTensor = bindings.allocate(result->getPlaceholder());
EE.compile(CompilationMode::Infer);
EE.run(bindings);
out->assign(resultTensor);
}
void inferNonSquarePaddingConv(Tensor *out, llvm::StringRef kind) {
PlaceholderBindings bindings;
ExecutionEngine EE(kind);
auto &mod = EE.getModule();
auto *F = mod.createFunction("main");
auto *input =
mod.createPlaceholder(ElemKind::FloatTy, {1, 2, 1, 32}, "input", false);
auto *inputTensor = bindings.allocate(input);
auto IH = inputTensor->getHandle();
for (size_t i = 0; i < 2 * 32; i++) {
IH.raw(i) = (i + 1) / 10.0;
}
auto *filter = mod.createPlaceholder(ElemKind::FloatTy, {128, 1, 1, 32},
"filter", false);
auto *filterTensor = bindings.allocate(filter);
auto FH = filterTensor->getHandle();
for (dim_t i = 0; i < 128; i++)
for (dim_t j = 0; j < 32; j++) {
FH.at({i, 0, 0, j}) = (i + j) / 100.0;
}
auto *zeroBias =
mod.createPlaceholder(ElemKind::FloatTy, {128}, "bias", false);
auto *zeroBiasTensor = bindings.allocate(zeroBias);
zeroBiasTensor->zero();
auto outTy = mod.uniqueType(ElemKind::FloatTy, {1, 4, 5, 128});
ConvolutionNode *CN = F->createConv("Conv", input, filter, zeroBias, outTy,
{1, 1}, {1, 1}, {0, 1, 2, 3}, 1);
SaveNode *result = F->createSave("save", CN);
auto *resultTensor = bindings.allocate(result->getPlaceholder());
EE.compile(CompilationMode::Infer);
EE.run(bindings);
out->assign(resultTensor);
}
void inferNonSquareKernelConv(Tensor *out, llvm::StringRef kind) {
PlaceholderBindings bindings;
ExecutionEngine EE(kind);
auto &mod = EE.getModule();
auto *F = mod.createFunction("main");
auto *input =
mod.createPlaceholder(ElemKind::FloatTy, {1, 2, 1, 32}, "input", false);
auto *inputTensor = bindings.allocate(input);
auto IH = inputTensor->getHandle();
for (size_t i = 0; i < 2 * 32; i++) {
IH.raw(i) = (i + 1) / 10.0;
}
auto *filter = mod.createPlaceholder(ElemKind::FloatTy, {128, 2, 1, 32},
"filter", false);
auto *filterTensor = bindings.allocate(filter);
auto FH = filterTensor->getHandle();
for (dim_t i = 0; i < 128; i++)
for (dim_t j = 0; j < 2; j++)
for (dim_t k = 0; k < 32; k++) {
FH.at({i, j, 0, k}) = (i + j + k) / 100.0;
}
auto *zeroBias =
mod.createPlaceholder(ElemKind::FloatTy, {128}, "bias", false);
auto *zeroBiasTensor = bindings.allocate(zeroBias);
zeroBiasTensor->zero();
auto outTy = mod.uniqueType(ElemKind::FloatTy, {1, 3, 5, 128});
ConvolutionNode *CN = F->createConv("Conv", input, filter, zeroBias, outTy,
{2, 1}, {1, 1}, {0, 1, 2, 3}, 1);
SaveNode *result = F->createSave("save", CN);
auto *resultTensor = bindings.allocate(result->getPlaceholder());
EE.compile(CompilationMode::Infer);
EE.run(bindings);
out->assign(resultTensor);
}
void inferNonSquareStrideConv(Tensor *out, llvm::StringRef kind) {
PlaceholderBindings bindings;
ExecutionEngine EE(kind);
auto &mod = EE.getModule();
auto *F = mod.createFunction("main");
auto *input =
mod.createPlaceholder(ElemKind::FloatTy, {1, 2, 1, 32}, "input", false);
auto *inputTensor = bindings.allocate(input);
auto IH = inputTensor->getHandle();
for (size_t i = 0; i < 2 * 32; i++) {
IH.raw(i) = (i + 1) / 10.0;
}
auto *filter = mod.createPlaceholder(ElemKind::FloatTy, {128, 2, 1, 32},
"filter", false);
auto *filterTensor = bindings.allocate(filter);
auto FH = filterTensor->getHandle();
for (dim_t i = 0; i < 128; i++)
for (dim_t j = 0; j < 2; j++)
for (dim_t k = 0; k < 32; k++) {
FH.at({i, j, 0, k}) = (i + j + k) / 100.0;
}
auto *zeroBias =
mod.createPlaceholder(ElemKind::FloatTy, {128}, "bias", false);
auto *zeroBiasTensor = bindings.allocate(zeroBias);
zeroBiasTensor->zero();
auto outTy = mod.uniqueType(ElemKind::FloatTy, {1, 2, 5, 128});