-
Notifications
You must be signed in to change notification settings - Fork 699
/
Copy pathCachingGraphRunner.cpp
1705 lines (1512 loc) · 65.9 KB
/
CachingGraphRunner.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 "CachingGraphRunner.h"
#include "ShapeInferenceEngine.h"
#include "glow/Base/Type.h"
#include "glow/Exporter/ONNXModelWriter.h"
#include "glow/Flags/Flags.h"
#include "glow/Importer/ONNXModelLoader.h"
#include "glow/Runtime/DeferredWeightLoader.h"
#include "glow/Runtime/RuntimeTypes.h"
#include "glow/Runtime/TraceExporter.h"
#include "glow/Support/Support.h"
#include <mutex>
namespace glow {
namespace {
/// Initialize the Glow compilation context \p cctx from glow::flags
/// This is backward compatible with existing PyTorchLoaderSettings, who
/// will overwrite any overlapping settings in this function.
Error initializeCompilationContextFromGlowFlags(
glow::CompilationContext &cctx) {
auto &precConfig = cctx.precisionConfig;
if (glow::flags::ConvertToFP16) {
precConfig.convertToFP16 = glow::flags::ConvertToFP16;
LOG(INFO) << "Conversion to fp16 enabled";
}
if (glow::flags::SkipBiasFp32tofp16Convert) {
precConfig.skipBiasFp32tofp16Convert =
glow::flags::SkipBiasFp32tofp16Convert;
LOG(INFO) << "Skip fp16 convert for bias";
}
if (glow::flags::ConvertPlaceholdersToFP16) {
precConfig.convertPlaceholdersToFP16 =
glow::flags::ConvertPlaceholdersToFP16;
LOG(INFO) << "Conversion of Placeholders to fp16 enabled";
}
if (glow::flags::ConvertConstantsToFP16) {
precConfig.convertConstantsToFP16 = glow::flags::ConvertConstantsToFP16;
LOG(INFO) << "Conversion of Constants to fp16 enabled";
}
if (glow::flags::ConvertFusedScaleOffsetToFP16) {
precConfig.convertFusedToFP16 = glow::flags::ConvertFusedScaleOffsetToFP16;
LOG(INFO) << "Conversion of fused scales/offsets to fp16 enabled";
}
if (glow::flags::ClipToFP16) {
precConfig.clipFP16 = glow::flags::ClipToFP16;
LOG(INFO) << "Clipping to fp16 enabled";
}
if (glow::flags::SkipInputsOnClipToFP16) {
precConfig.clipFP16SkipInputs = glow::flags::SkipInputsOnClipToFP16;
LOG(INFO) << "Skipping clipping for fp16 Node inputs fp16";
}
if (glow::flags::ForceSLSToFP16Accum) {
precConfig.forceFP16AccumSLS = glow::flags::ForceSLSToFP16Accum;
LOG(INFO) << "Forcing all SLS/SLWS ops to use FP16 accumulation enabled";
}
if (!glow::flags::EnableQuantParamChanges) {
cctx.optimizationOpts.enableQuantParamChanges = false;
LOG(INFO) << "Disabling quantization param changes during optimizations";
}
if (glow::flags::DumpCompilationLog) {
cctx.compilationLogPrefix = "torch-glow";
}
if (glow::flags::ConvertFusedScaleOffsetToFP32) {
precConfig.convert4BitFusedToFP32 = true;
precConfig.convert8BitFusedToFP32 = true;
LOG(INFO) << "Conversion of fused scales/offsets to fp32 enabled";
}
// glow_sparsenn_partitioning_add_sls_concats
// (SparseNNPartitioningAddSLSConcats) enables addition of concats to create a
// bigger tensor out of many smaller tensors that needs to be communicated
// with other partitions so that communication is efficient. This doesn't work
// if one of the tensor is [1, x] (coming from user embeddings and it's [1, x]
// due to inbatch broadcast, i.e., broadcast happens on accelerator card) and
// other (coming from ad embeddings) is [32, y]. However, [1, x] is followed
// by tile in glow graph to make it [32, x]. This diff D27781184 (
// glow_sparsenn_partitioning_pair_tile_with_sls, i.e.,
// SparseNNPartitioningPairTileWithSLS) pulls in the tile operator on user
// embeddings to sls partition as well so that sls_concat can now work since
// post-tile tensors become [32, x] and [32, y]. Thus,
// SparseNNPartitioningPairTileWithSLS is required for
// SparseNNPartitioningAddSLSConcats to work.
if (glow::flags::SparseNNPartitioningAddSLSConcats) {
LOG(INFO)
<< "Enabling glow_sparsenn_partitioning_pair_tile_with_sls because "
"glow_sparsenn_partitioning_add_sls_concats is enabled ";
cctx.optimizationOpts.sparseNNPartitioningPairTileWithSLS = true;
}
if (glow::flags::UseDAGOptimizer) {
LOG(INFO) << "Enabling DAG optimizer and related options (server AOT)";
cctx.callDAGOptimizer = true;
cctx.optimizationOpts.DAGOptimizerNumParallelChunks =
glow::flags::DAGOptimizerNumParallelChunks;
cctx.optimizationOpts.DAGOptimizerParallelizationTaggingAlgorithm =
glow::flags::DAGOptimizerParallelizationTaggingAlgorithm;
cctx.optimizationOpts.DAGOptimizerPlacementTaggingAlgorithm =
glow::flags::DAGOptimizerPlacementTaggingAlgorithm;
}
if (glow::flags::UseSparseNNPartitioningScheme) {
cctx.optimizationOpts.useSparseNNPartitioningScheme = true;
cctx.optimizationOpts.sparseNNPartitioningAddSLSConcats =
glow::flags::SparseNNPartitioningAddSLSConcats;
cctx.optimizationOpts.sparseNNPartitioningBalancePerfModel =
glow::flags::SparseNNPartitioningBalancePerfModel;
cctx.optimizationOpts.sparseNNPartitioningPairLNWithSLS =
glow::flags::SparseNNPartitioningPairLNWithSLS;
cctx.optimizationOpts.sparseNNPartitioningPairTileWithSLS =
glow::flags::SparseNNPartitioningPairTileWithSLS;
cctx.optimizationOpts.sparseNNPartitioningPairSLSWith =
glow::flags::SparseNNPartitioningPairSLSWith;
cctx.optimizationOpts.sparseNNPartitioningConcatSplitSize =
glow::flags::SparseNNPartitioningConcatSplitSize;
cctx.optimizationOpts.sparseNNPartitioningSchemeNumCards =
glow::flags::SparseNNPartitioningSchemeNumCards;
cctx.optimizationOpts.sparseNNPartitioningSchemeSLSTableKBytesPerCard =
glow::flags::SparseNNPartitioningSchemeSLSTableKBytesPerCard;
cctx.optimizationOpts.sparseNNPartitioningSchemeNumCoresSLS =
glow::flags::SparseNNPartitioningSchemeNumCoresSLS;
cctx.optimizationOpts.sparseNNPartitioningSchemeNumCoresOther =
glow::flags::SparseNNPartitioningSchemeNumCoresOther;
LOG(INFO) << "Using SLS partitioning scheme";
}
cctx.saturateHost = glow::flags::SaturateHost;
if (!glow::flags::processBackendSpecificOpts(
cctx.backendOpts.backendSpecificOpts,
glow::flags::BackendSpecificOpts)) {
MAKE_ERR("Failed glow::flags::processBackendSpecificOpts");
}
if (glow::runtime::flags::EnableP2P) {
LOG(INFO) << "Glow P2P Enabled";
cctx.enableP2P = true;
}
if (glow::runtime::flags::EnableDRT) {
LOG(INFO) << "Glow DRT Enabled";
cctx.enableDRT = true;
}
return Error::success();
}
/// Initialize the Glow compilation context \p cctx with \p settings
void initializeCompilationContextFromSettings(
glow::CompilationContext &cctx, const PyTorchLoaderSettings &settings) {
if (!cctx.precisionConfig.convertToFP16 && settings.convertToFP16) {
cctx.precisionConfig.convertToFP16 = settings.convertToFP16;
LOG(INFO) << "Conversion to fp16 enabled";
}
if (!cctx.precisionConfig.skipBiasFp32tofp16Convert &&
settings.skipBiasFp32tofp16Convert) {
cctx.precisionConfig.skipBiasFp32tofp16Convert =
settings.skipBiasFp32tofp16Convert;
LOG(INFO) << "Skipping bias fp32 -> fp16 conversion enabled";
}
if (!cctx.precisionConfig.convertPlaceholdersToFP16 &&
settings.convertPlaceholdersToFP16) {
cctx.precisionConfig.convertPlaceholdersToFP16 =
settings.convertFusedToFP16;
LOG(INFO) << "Conversion of Placeholders to fp16 enabled";
}
if (!cctx.precisionConfig.convertConstantsToFP16 &&
settings.convertConstantsToFP16) {
cctx.precisionConfig.convertConstantsToFP16 =
settings.convertConstantsToFP16;
LOG(INFO) << "Conversion of Constants to fp16 enabled";
}
if (!cctx.precisionConfig.convertFusedToFP16 && settings.convertFusedToFP16) {
cctx.precisionConfig.convertFusedToFP16 = settings.convertFusedToFP16;
LOG(INFO) << "Conversion of fused scales/offsets to fp16 enabled";
}
if (!cctx.precisionConfig.clipFP16 && settings.clipFP16) {
cctx.precisionConfig.clipFP16 = settings.clipFP16;
LOG(INFO) << "Clipping to fp16 enabled";
}
if (!cctx.precisionConfig.clipFP16SkipInputs && settings.clipFP16SkipInputs) {
cctx.precisionConfig.clipFP16SkipInputs = settings.clipFP16SkipInputs;
LOG(INFO) << "Skipping clipping for fp16 Node inputs fp16";
}
if (!cctx.precisionConfig.forceFP16AccumSLS && settings.forceFP16AccumSLS) {
cctx.precisionConfig.forceFP16AccumSLS = settings.forceFP16AccumSLS;
LOG(INFO) << "Forcing all SLS/SLWS ops to use FP16 accumulation enabled";
}
if (!cctx.precisionConfig.convert8BitFusedToFP32 &&
settings.convert8BitFusedToFP32) {
LOG(INFO) << "Enabling conversion of FP16 scale and bias to FP32 for 8bit "
"EmbeddingBagByteRowwiseOffset";
cctx.precisionConfig.convert8BitFusedToFP32 =
settings.convert8BitFusedToFP32;
}
if (!cctx.precisionConfig.convert4BitFusedToFP32 &&
settings.convert4BitFusedToFP32) {
LOG(INFO) << "Enabling conversion of FP16 scale and bias to FP32 for 4bit "
"EmbeddingBagByteRowwiseOffset";
cctx.precisionConfig.convert4BitFusedToFP32 =
settings.convert4BitFusedToFP32;
}
if (!glow::flags::DisableLayoutVerifying && settings.disableLayoutVerifying) {
glow::flags::DisableLayoutVerifying = true;
LOG(INFO) << "Skipping all layout verifying";
}
// If we want to enable serialize, we have to not free compiled stream in
// provisoner.
if (settings.enableSerialize) {
glow::flags::DisableFreeCompilationResource = true;
LOG(INFO)
<< "Free compilation resource after compiling on backend is disabled";
}
if (settings.dumpFinalGlowGraph) {
cctx.dumpFinalGraph = settings.dumpFinalGlowGraph;
}
if (settings.saturateHost) {
cctx.saturateHost = settings.saturateHost;
}
if (settings.saturateKDevices > 0) {
cctx.saturateKDevices = settings.saturateKDevices;
}
if (settings.use_dag_optimizer) {
cctx.callDAGOptimizer = true;
if (!settings.apl_placement_alg.empty()) {
cctx.optimizationOpts.DAGOptimizerPlacementTaggingAlgorithm =
settings.apl_placement_alg;
}
if (!settings.apl_parallelization_alg.empty()) {
cctx.optimizationOpts.DAGOptimizerParallelizationTaggingAlgorithm =
settings.apl_parallelization_alg;
cctx.optimizationOpts.DAGOptimizerNumParallelChunks =
settings.apl_num_parallel_chunks;
}
}
if (!settings.backendSpecificOpts.empty()) {
cctx.backendOpts.backendSpecificOpts = settings.backendSpecificOpts;
}
cctx.replicationCount = settings.replicationCount;
if (settings.skipProvisioning) {
LOG(INFO) << "Will skip provisioning (likely due to AOT opt).";
cctx.skipProvisioning = true;
}
if (settings.sinkTanhBelowConcat) {
LOG(INFO) << "Sinking tanh below concat";
cctx.optimizationOpts.sinkTanhBelowConcat = true;
}
if (settings.useSparseNNPartitioningScheme) {
cctx.optimizationOpts.useSparseNNPartitioningScheme = true;
cctx.optimizationOpts.sparseNNPartitioningAddSLSConcats =
settings.sparseNNPartitioningAddSLSConcats;
cctx.optimizationOpts.sparseNNPartitioningBalancePerfModel =
settings.sparseNNPartitioningBalancePerfModel;
cctx.optimizationOpts.sparseNNPartitioningPairLNWithSLS =
settings.sparseNNPartitioningPairLNWithSLS;
cctx.optimizationOpts.sparseNNPartitioningPairTileWithSLS =
settings.sparseNNPartitioningPairTileWithSLS;
cctx.optimizationOpts.sparseNNPartitioningPairSLSWith =
settings.sparseNNPartitioningPairSLSWith;
cctx.optimizationOpts.sparseNNPartitioningSchemeNumCards =
settings.sparseNNPartitioningSchemeNumCards;
cctx.optimizationOpts.sparseNNPartitioningSchemeSLSTableKBytesPerCard =
settings.sparseNNPartitioningSchemeSLSTableKBytesPerCard;
cctx.optimizationOpts.sparseNNPartitioningSchemeNumCoresSLS =
settings.SparseNNPartitioningSchemeNumCoresSLS;
cctx.optimizationOpts.sparseNNPartitioningSchemeNumCoresOther =
settings.SparseNNPartitioningSchemeNumCoresOther;
}
if (settings.enableP2P) {
LOG(INFO) << "Glow P2P Enabled";
cctx.enableP2P = true;
}
if (settings.enableDRT) {
LOG(INFO) << "Glow DRT Enabled";
cctx.enableDRT = true;
}
}
/// Initialize the Glow compilation context \p cctx with \p
/// ModelCompilationConfigOverride configOverride
void initializeCompilationContextFromModelCompilationConfigOverride(
glow::CompilationContext &cctx,
const glow::ModelCompilationConfigOverride &configOverride) {
if (configOverride.useDagOptimizer.has_value()) {
cctx.callDAGOptimizer = configOverride.useDagOptimizer.value();
}
if (configOverride.aplNumParallelChunks.has_value()) {
cctx.optimizationOpts.DAGOptimizerNumParallelChunks =
configOverride.aplNumParallelChunks.value();
}
if (configOverride.aplAsapPlacement.has_value()) {
cctx.optimizationOpts.enableAPLASAPPlacement =
configOverride.aplAsapPlacement.value();
}
}
/// This function slice the input Tensor according to the expected shape in the
/// zero dimension.
/// TODO: Multi-dimension slicing will be supported later.
at::Tensor sliceTensor(at::Tensor &t, const TensorShape &shape) {
CHECK_GT(shape.size(), 0);
return at::native::slice(t, 0, 0, shape[0]);
}
/// The following two methods account for the auto FP32->FP16 conversion in Glow
/// for placeholder \p type match in AOT
ElemKind getConvertElemTypeForAOT(const Type &type,
const CompilationContext &cctx) {
auto elementType = type.getElementType();
if (cctx.precisionConfig.convertToFP16 && elementType == ElemKind::FloatTy) {
elementType = ElemKind::Float16Ty;
} else if (cctx.precisionConfig.convertFusedToFP16 &&
elementType == ElemKind::UInt8FusedQTy) {
elementType = ElemKind::UInt8FusedFP16QTy;
}
return elementType;
}
std::vector<unsigned long>
getConvertDimVecForAOT(const Type &type, const CompilationContext &cctx) {
auto dims = type.dims();
auto dimVec = dims.vec();
if (cctx.precisionConfig.convertFusedToFP16 &&
type.getElementType() == ElemKind::UInt8FusedQTy) {
assert(dimVec.size() == 2);
dimVec[1] = dimVec[1] - 4;
}
return dimVec;
}
/// This function is the preparation of Glow serialization. It sets \p
/// GlowDeserializationSpec for AOT model loading and sets cctx to let
/// HostManager serialize lowerred Glow IR into onnx file
Error setupGlowDeserializationSpecAndCctx(
const PyTorchLoaderSettings &settings,
const std::shared_ptr<CachingGraphRunner::PerGlowGraphInfo> &info,
CompilationContext &cctx, Function *f, GlowDeserializationSpec &spec,
std::shared_ptr<std::string> glowAOTSerializationModelStrPtr) {
auto glowPyTorchLoaderSettings = spec.pytorchLoaderSettings;
glowPyTorchLoaderSettings->overrideSettings(settings);
spec.functionName = info->functionName;
auto &inputPHNames = spec.inputPHNames;
auto &inputPHTypes = spec.inputPHTypes;
auto &staticPHNames = spec.staticPHNames;
auto &staticPHTypes = spec.staticPHTypes;
auto &outputPHNames = spec.outputPHNames;
size_t inputIdx = 0;
for (const auto &ph : info->inputPlaceholders) {
inputPHNames.emplace_back(ph->getName().data());
inputPHTypes.emplace_back(ph->getType()->toString());
cctx.loadedPHNames.emplace(ph,
std::make_pair(ph->getName().data(), inputIdx));
++inputIdx;
}
std::map<std::string, glow::Type> staticPlaceholderTypes;
for (const auto &ph : f->findPlaceholders()) {
if (ph->isStatic()) {
auto type = *ph->getType();
/// Account for the auto FP32->FP16 conversion in Glow
/// for placeholder \p type match
auto convertedElemType = getConvertElemTypeForAOT(type, cctx);
auto convertedDimVec = getConvertDimVecForAOT(type, cctx);
auto convertedDims = llvm::ArrayRef<unsigned long>(convertedDimVec);
auto convertedType =
type.isQuantizedType()
? f->getParent()->uniqueType(convertedElemType, convertedDims,
type.getScale(), type.getOffset())
: f->getParent()->uniqueType(convertedElemType, convertedDims);
// Here staticPlaceholderTypes is used for serializing Glow IR in
// hostManager, which is post-precision conversion. staticPHTypes on the
// other hand is used in Glow deserialization, which requires the input
// tensor types (i.e., pre-precision conversion)
staticPlaceholderTypes[std::string(ph->getName())] = *convertedType;
staticPHNames.emplace_back(ph->getName().data());
staticPHTypes.emplace_back(type.toString());
}
}
size_t outputIdx = 0;
for (const auto &ph : info->outputPlaceholders) {
outputPHNames.emplace_back(ph->getName().data());
cctx.loadedPHNames.emplace(ph,
std::make_pair(ph->getName().data(), outputIdx));
++outputIdx;
}
cctx.serializeCompiledDAG = true;
cctx.saveConstantInSerializeCompiledDAG = true;
cctx.staticPlaceholderTypesForAOT = staticPlaceholderTypes;
cctx.returnGlowSerializedModelStr = true;
cctx.glowAOTSerializationModelStrPtr = glowAOTSerializationModelStrPtr;
// We currently save all the non-embedding weights in the ONNX file
// and thus do not delay/record constant modification. Since AOT
// compilation is performed for every training snapshot, we do not
// need to support updating quantization params for AOT.
RETURN_ERR_IF_NOT(
!cctx.optimizationOpts.delayAndRecordConstantModification,
"delayAndRecordConstantModification should be false when loading "
"PyTorch models in Glow");
return Error::success();
}
/// This function serialize Glow deserialization spec in JSON format
/// The JSON file contains
/// 1. PyTorchLoaderSettings;
/// 2. Glow function name;
/// 3. Input placeholder names & types;
/// 4. Static placeholder names & types;
/// 5. Output placeholder names;
/// Remarks: (1) ONNXModelLoader initialization requires both input and
/// static PHs and types as the inputTensors and inputTypes;
/// (2) Glow deserialization will reset PH static status in
/// GlowIR, we need to set them static manually during
/// deserialization
/// (3) Input&Output PH names are used for reconstructing
/// PerGlowGraphInfo
Error saveGlowDeserializationSpec(
GlowDeserializationSpec &spec,
std::shared_ptr<std::string> glowAOTSerializationSpecStrPtr) {
std::string serializedSpec;
ASSIGN_VALUE_OR_RETURN_ERR(serializedSpec, spec.toJson());
*glowAOTSerializationSpecStrPtr = std::move(serializedSpec);
return Error::success();
}
glow::Expected<std::string> getOnnxFilePath(const std::string &filePrefix,
bool writeOnnxToTmp,
const char *extension = ".onnx") {
if (writeOnnxToTmp) {
std::string filepath;
ASSIGN_VALUE_OR_RETURN_ERR(filepath, getTempFileLoc(filePrefix, extension));
return filepath;
} else {
return filePrefix + extension;
}
}
} // namespace
void CachingGraphRunner::aggregateAndDumpTraces(TraceContext *traceContext,
bool flush) {
size_t numTracesPerDump = defaultSettings_.numTracesPerDump;
bool doDump = false;
std::string filename;
{
std::unique_lock<std::mutex> lock(tracesMutex_);
if (traceContext) {
mergedTraceContext_->merge(traceContext);
numTraces_++;
} else if (mergedTraceContext_->getTraceEvents().empty()) {
return;
}
size_t numTraces = numTraces_;
// If numTracesPerDump <= 0, it means we don't merge unless there is a flush
if (flush || (numTracesPerDump > 0 && numTraces % numTracesPerDump == 0)) {
// Initial way of differentiating the dump files when there are multiple
// graph runners
// TODO(allwu): find a better way to generate trace file names
size_t hash = reinterpret_cast<size_t>(this);
size_t dumpNum = numTraceDumps_++;
filename =
strFormat("glow-trace-%04lx-%zu.json", hash % (1 << 16), dumpNum);
doDump = true;
}
}
if (doDump) {
mergedTraceContext_->dump(filename);
mergedTraceContext_ = glow::make_unique<TraceContext>(TraceLevel::STANDARD);
}
}
std::unique_ptr<
std::unordered_map<std::string, std::unique_ptr<BlockStreamBase>>>
CachingGraphRunner::getAllSerializedFunctionsMap() {
return hostManager_->getAllSerializedFunctions();
}
Expected<std::shared_ptr<CachingGraphRunner::PerGlowGraphInfo>>
CachingGraphRunner::loadImpl(torch::jit::Stack &stack,
const PyTorchLoaderSettings &settings,
TraceContext *traceContext) {
TRACE_EVENT_SCOPE(traceContext, TraceLevel::RUNTIME, "torch_glow::loadImpl");
RECORD_USER_SCOPE("torch_glow::loadImpl");
const auto inputs = torch::jit::last(stack, graph_->inputs().size());
TRACE_EVENT_BEGIN(traceContext, TraceLevel::RUNTIME,
"InputMetaStack_creation");
InputMetaStack metaStack;
{
RECORD_USER_SCOPE("InputMetaStack_creation");
ASSIGN_VALUE_OR_RETURN_ERR(
metaStack, inputMetaStackFromStack(stack, /*ignoreObjects*/ true));
}
TRACE_EVENT_END(traceContext, TraceLevel::RUNTIME, "InputMetaStack_creation");
// If we already have a Glow function compiled for this graph with and the
// given inputs then use that.
TRACE_EVENT_BEGIN(traceContext, TraceLevel::RUNTIME,
"perGlowGraphInfoMap__lookup");
std::unique_lock<std::shared_timed_mutex> wlock(graphInfoMapMutex);
size_t hash = getGraphMapKeyFromInputStack(metaStack);
{
auto it = perGlowGraphInfoMap_.find(hash);
if (it != perGlowGraphInfoMap_.end()) {
return it->second;
}
}
TRACE_EVENT_END(traceContext, TraceLevel::RUNTIME,
"perGlowGraphInfoMap__lookup");
LOG(INFO) << "Compiling graph for inputs:" << std::endl << metaStack.print();
PyTorchLoaderSettings loadSettings = settings;
if (settings.lazyCompile) {
auto it = pyTorchLoaderSettingsMap_.find(metaStack.hash());
if (it != pyTorchLoaderSettingsMap_.end()) {
LOG(INFO) << "Loading compilation settping for hash:" << metaStack.hash();
loadSettings = it->second;
}
}
auto info = std::make_shared<PerGlowGraphInfo>(
strFormat("pt_function_%lu_%lu", size_t(this), metaStack.hash()),
loadSettings);
std::unique_ptr<Module> module = glow::make_unique<Module>();
Function *f = module->createFunction(info->functionName);
glow::CompilationContext cctx;
RETURN_IF_ERR(initializeCompilationContextFromGlowFlags(cctx));
initializeCompilationContextFromSettings(cctx, loadSettings);
TRACE_EVENT_BEGIN(traceContext, TraceLevel::RUNTIME, "loadJITGraph");
{
RECORD_USER_SCOPE("loadJITGraph");
RETURN_IF_ERR(PyTorchModelLoader::loadJITGraph(
*f, *graph_, info->inputPlaceholders, info->outputPlaceholders,
outputCorrectTypes_, loadSettings, inputs, {}));
}
TRACE_EVENT_END(traceContext, TraceLevel::RUNTIME, "loadJITGraph");
info->inputSanitizers = runtime::getInputSanitizers(*f);
if (loadSettings.convertToFP16) {
cctx.precisionConfig.precisionModeKindSet.insert(
Kinded::Kind::ChannelwiseQuantizedConvolutionNodeKind);
cctx.precisionConfig.precisionModeKindSet.insert(
Kinded::Kind::RowwiseQuantizedFullyConnectedNodeKind);
}
cctx.replicationCount = loadSettings.replicationCount;
cctx.backendOpts.backendSpecificOpts = loadSettings.backendSpecificOpts;
TRACE_EVENT_BEGIN(traceContext, TraceLevel::RUNTIME, "addNetwork");
{
RECORD_USER_SCOPE("addNetwork");
// If --load-backend-specific-opts was passed from python, add it to the
// compile context so the host manager knows to load backend options from
// yaml.
if (!loadSettings.backendOptionsFile.empty()) {
std::pair<std::string, std::string> loadBackendSpecificOpts(
"loadBackendSpecificOptions", loadSettings.backendOptionsFile);
cctx.backendOpts.backendSpecificOpts.insert(loadBackendSpecificOpts);
}
RETURN_IF_ERR(hostManager_->addNetwork(std::move(module), cctx));
}
TRACE_EVENT_END(traceContext, TraceLevel::RUNTIME, "addNetwork");
auto ret = perGlowGraphInfoMap_.emplace(hash, info);
RETURN_ERR_IF_NOT(ret.second,
strFormat("Tried to store duplicate Glow graph for %s",
metaStack.print().c_str()));
return info;
}
Expected<MetaStack *>
CachingGraphRunner::loadShape(const c10::ArrayRef<c10::IValue> &inputs,
TraceContext *traceContext) {
TRACE_EVENT_SCOPE(traceContext, TraceLevel::RUNTIME, "torch_glow::loadShape");
RECORD_USER_SCOPE("torch_glow::loadShape");
TRACE_EVENT_BEGIN(traceContext, TraceLevel::RUNTIME,
"computeShapeInputMetaStack");
InputMetaStack metaStack;
{
RECORD_USER_SCOPE("computeShapeInputMetaStack");
ASSIGN_VALUE_OR_RETURN_ERR(metaStack,
inputMetaStackFromStack(inputs, true));
}
TRACE_EVENT_END(traceContext, TraceLevel::RUNTIME,
"computeShapeInputMetaStack");
// If we already have a shape info for this graph output with and the
// given inputs then use that.
size_t hash = getGraphMapKeyFromInputStack(metaStack);
{
std::lock_guard<std::mutex> graphShapeLock(glowGraphShapeMapMutex_);
auto it = perGlowGraphShapeMap_.find(hash);
if (it != perGlowGraphShapeMap_.end()) {
return &(it->second);
}
}
VLOG(1) << "Compiling graph with tensor shape:\n" << metaStack.print();
// If we don't have a shape info for this graph output with and the
// given inputs then run shape inference, then push into the map.
TRACE_EVENT_BEGIN(traceContext, TraceLevel::RUNTIME, "runShapeInference");
MetaStack outputShape;
{
RECORD_USER_SCOPE("runShapeInference");
ShapeInferenceEngine shapeG(*graph_, inputs);
RETURN_IF_ERR(shapeG.run());
outputShape = shapeG.getGraphOutputShape();
}
TRACE_EVENT_END(traceContext, TraceLevel::RUNTIME, "runShapeInference");
{
std::lock_guard<std::mutex> graphShapeLock(glowGraphShapeMapMutex_);
auto ret = perGlowGraphShapeMap_.emplace(hash, outputShape);
return &(ret.first->second);
}
}
int64_t CachingGraphRunner::runOnJit(torch::jit::Stack &stack) {
static std::mutex runJitLock;
std::lock_guard<std::mutex> guard(runJitLock);
bool temp = getGlobalPyTorchLoaderSettingsMutable().fusionPassEnabled;
getGlobalPyTorchLoaderSettingsMutable().fusionPassEnabled = false;
int64_t startTime;
startTime = TraceEvent::now();
ptGraphExecutor_.run(stack);
int64_t runTime = TraceEvent::now() - startTime;
getGlobalPyTorchLoaderSettingsMutable().fusionPassEnabled = temp;
return runTime;
}
struct TensorCompareResult {
double relErr;
double maxErr;
double maxRelErr;
};
template <typename Ty>
TensorCompareResult compareTensors(glow::Tensor &RefT, glow::Tensor &CmpT) {
TensorCompareResult result = {INFINITY, INFINITY, INFINITY};
if (CmpT.getHandle<Ty>().size() != RefT.getHandle<Ty>().size()) {
LOG(ERROR) << "Dimension mismatch: " << "\tReference dims: "
<< RefT.getHandle().getType().dims()
<< "\tGlow dims: " << CmpT.getHandle().getType().dims()
<< std::endl;
return result;
}
double totalErrSq = 0.0;
double totalMagSq = 0.0;
double maxErr = 0.0;
double maxRelErr = 0.0;
for (dim_t idx = 0; idx < RefT.getHandle().size(); idx++) {
double refVal = (double)RefT.getHandle<Ty>().raw(idx);
double cmpVal = (double)CmpT.getHandle<Ty>().raw(idx);
double diff = refVal - cmpVal;
double mag = refVal * refVal;
double eltRelErr = (fabs(refVal)) > 0.0 ? fabs(diff) / fabs(refVal) : 0.0;
totalErrSq += diff * diff;
totalMagSq += mag;
maxErr = (fabs(diff) > maxErr) ? fabs(diff) : maxErr;
maxRelErr = (eltRelErr > maxRelErr) ? eltRelErr : maxRelErr;
}
result.relErr = (totalMagSq > 0.0) ? std::sqrt(totalErrSq / totalMagSq) : 0.0;
result.maxErr = maxErr;
result.maxRelErr = maxRelErr;
return result;
}
/// Create an onnx graph for the tensors in \p glowTensors with names from \p
/// placeholders and write the graph to \p filePrefix
static Error
writeGlowTensorsToOnnx(const std::string &filePrefix,
const PyTorchLoaderSettings &settings,
const std::vector<glow::Placeholder *> &placeholders,
const std::vector<glow::Tensor> &glowTensors) {
DCHECK_EQ(placeholders.size(), glowTensors.size());
ONNX_NAMESPACE::GraphProto onnxGraph;
for (size_t i = 0; i < placeholders.size(); ++i) {
const auto *ph = placeholders[i];
if (ph->getNumUsers() == 0) {
LOG(INFO) << "Tensor onnxification not required. Not being used: "
<< ph->getName().str() << "\n";
continue;
}
auto *onnxT = onnxGraph.add_initializer();
const auto &t = glowTensors[i];
onnxT->set_name(ph->getName().str());
size_t unpaddedSize = t.getUnpaddedSizeInBytes();
size_t tensorSize = t.getSizeInBytes();
if (unpaddedSize == tensorSize) {
ONNXModelWriter::writeTensor(t, onnxT,
/*useGlowCustomOps*/ true);
} else {
// If the tensor is a partial tensor, then save only the part
// that has data.
auto ty = t.getType();
auto dims = ty.dims().vec();
DCHECK_GT(dims.size(), 0);
dims[0] = dims[0] * unpaddedSize / tensorSize;
const auto &resized = t.getUnowned(dims);
ONNXModelWriter::writeTensor(resized, onnxT,
/*useGlowCustomOps*/ true);
}
}
std::string filename;
ASSIGN_VALUE_OR_RETURN_ERR(
filename, getOnnxFilePath(filePrefix, settings.writeOnnxToTmp));
std::ofstream of(filename, std::ios::binary);
if (!of) {
return MAKE_ERR(
strFormat("Cannot create onnx tensor file %s", filename.c_str()));
}
std::string buffer;
onnxGraph.SerializeToString(&buffer);
of << buffer;
return Error::success();
}
/// Get outputs from \p stack which contains PyTorch tensors from running on JIT
/// GraphExector and create a onnx file for those outputs at \p filePrefix.
static Error
writeJITOutputsToOnnxFile(const std::string &filePrefix,
const torch::jit::Stack &stack,
const CachingGraphRunner::PerGlowGraphInfo &info) {
// pull outputs off the stack, create corresponding vector of Glow tensors
std::vector<glow::Tensor> glowTensorOutputs;
std::vector<torch::Tensor> ptTensorOutputs;
size_t numOutputs = info.outputPlaceholders.size();
for (size_t i = 0; i < numOutputs; ++i) {
auto &jitOutput = torch::jit::peek(stack, i, numOutputs);
auto jitPtTensor = jitOutput.toTensor().contiguous();
glow::Tensor jitGlowT = ptTensorToGlowTensor(jitPtTensor);
glowTensorOutputs.push_back(std::move(jitGlowT));
ptTensorOutputs.push_back(std::move(jitPtTensor));
}
// write outputs to file
RETURN_IF_ERR(writeGlowTensorsToOnnx(
filePrefix, info.settings, info.outputPlaceholders, glowTensorOutputs));
return Error::success();
}
Error CachingGraphRunner::writeJitIOToOnnxFile(
const std::string &inputFilePrefix, const std::string &outputFilePrefix,
const torch::jit::Stack &stack) {
if (!defaultSettings_.dumpFailedInputsToOnnxFiles) {
return Error::success();
}
std::shared_ptr<PerGlowGraphInfo> info;
ASSIGN_VALUE_OR_RETURN_ERR(info, findGraphInfoForStack(stack));
// Write inputs
size_t numInputs = graph_->inputs().size();
const auto inputs = torch::jit::last(stack, numInputs);
std::vector<glow::Tensor> glowTensorInputs;
std::vector<torch::Tensor> ptTensorInputs;
if (auto tensorsOrErr =
processPyTorchInputs(inputs, info->inputPlaceholders)) {
glowTensorInputs = std::move(tensorsOrErr->first);
ptTensorInputs = std::move(tensorsOrErr->second);
} else {
RETURN_ERR(tensorsOrErr.takeError());
}
RETURN_IF_ERR(writeGlowTensorsToOnnx(inputFilePrefix, info->settings,
info->inputPlaceholders,
glowTensorInputs));
// Write InputMetaStack to file so we know the type of the inputs
InputMetaStack metaStack;
ASSIGN_VALUE_OR_RETURN_ERR(metaStack, inputMetaStackFromStack(inputs));
std::string metaStackFilename;
ASSIGN_VALUE_OR_RETURN_ERR(
metaStackFilename,
getOnnxFilePath(inputFilePrefix, info->settings.writeOnnxToTmp, ".txt"));
std::ofstream metaStackOF(metaStackFilename, std::ios::binary);
if (!metaStackOF) {
return MAKE_ERR(strFormat("Cannot create metastack text file %s",
metaStackFilename.c_str()));
}
metaStackOF << metaStack.print();
// Run the stack on JIT to get outputs then write them to file
torch::jit::Stack copyStack;
// We will use original graph for runOnJit, which means the first input
// should be module.
if (origGraph_ != nullptr) {
copyStack.push_back(module_);
}
for (auto &ival : stack) {
if (ival.isTensor()) {
copyStack.push_back(ival.deepcopy());
} else {
copyStack.push_back(ival);
}
}
runOnJit(copyStack);
// Write outputs
RETURN_IF_ERR(writeJITOutputsToOnnxFile(outputFilePrefix, copyStack, *info));
return Error::success();
}
Expected<std::pair<glow::Tensor, torch::Tensor>>
CachingGraphRunner::convertPyTorchInputToGlowInput(
torch::Tensor &&ptTensor, const glow::Placeholder *ph) {
glow::Tensor glowTensor;
glow::TypeRef ty = ph->getType();
if (ptTensor.is_quantized()) {
ptTensor = convertQuantizedToDtype(ptTensor, at::kQInt8);
}
// If the tensor is an int64 tensor but should be an int32 tensor in Glow,
// convert it.
if (ptTensor.scalar_type() == at::kLong &&
ty->getElementType() == ElemKind::Int32ITy) {
ptTensor = ptTensor.to(at::kInt);
}
// Make sure the runtime pytorch tensor type matches the placeholder.
// Note this needs to be placed after convertQuantizedToDtype to
// correctly handle quantized types.
if (ty->getElementType() != scalarTypeToElemKind(ptTensor.scalar_type())) {
std::stringstream ss;
ss << "Found type mismatch for input \"" << ph->getName().str() << "\""
<< ": pytorch tensor is " << ptTensor.toString() << ", ph type is "
<< ty->toString();
return MAKE_ERR(ss.str());
}
if (!ptTensor.is_contiguous()) {
ptTensor = ptTensor.contiguous();
}
// Check Tensor size, making sure enough memory is allocated
if (ptTensor.numel() > ty->size()) {
std::stringstream ss;
ss << "Input tensor is too large: " << ptTensor.numel() << " vs "
<< ty->size() << ": " << ph->getName().str();
return MAKE_ERR(ss.str());
}
if (ty->dims().size() == ptTensor.ndimension() &&
std::equal(ty->dims().begin(), ty->dims().end(),
ptTensor.sizes().begin())) {
glowTensor = glow::Tensor(ptTensor.data_ptr(), ty);
} else if (ptTensor.data_ptr() && ptTensor.numel() > 0 &&
backend_.supportsPartialTensors()) {
// This is a partial tensor, to create padded unown tensor
glowTensor = glow::Tensor(ptTensor.data_ptr(), ty, ptTensor.nbytes());
} else if (ptTensor.numel() == 0) {
// Handles zero-size input tensor
// Here zeroLengthSequence_ is pre-allocated if warmCache is called
assert(zeroLengthSequence_.getUnsafePtr());
glowTensor = glow::Tensor((void *)zeroLengthSequence_.getUnsafePtr(), ty);
} else {
// For backends that does not support partial tensor, last-element padding
// based on size
auto inputTensorOpt = tensorPool_.get(ty);
if (!inputTensorOpt) {
std::stringstream ss;
ss << "Tensorpool tensor not found for input " << ptTensor.name();
return MAKE_ERR(ss.str());
}
// We want fresh DeviceResidencyInfo for this fresh Tensor.
glow::Tensor inputTensor(std::move(inputTensorOpt.value()));
inputTensor.resetDeviceInfo();
if (ptTensor.data_ptr()) {
auto *inTensorPtr = inputTensor.getUnsafePtr();
memcpy(inTensorPtr, ptTensor.data_ptr(), ptTensor.nbytes());
auto hostElementSize = inputTensor.getType().getElementSize();
int numElements = ptTensor.nbytes() / hostElementSize;
int numPaddedElements = inputTensor.getSizeInBytes() / hostElementSize;
if (hostElementSize == 1) {
std::fill(
reinterpret_cast<uint8_t *>(inTensorPtr) + numElements,
reinterpret_cast<uint8_t *>(inTensorPtr) + numPaddedElements,
reinterpret_cast<const uint8_t *>(inTensorPtr)[numElements - 1]);
} else if (hostElementSize == 2) {
std::fill(
reinterpret_cast<uint16_t *>(inTensorPtr) + numElements,
reinterpret_cast<uint16_t *>(inTensorPtr) + numPaddedElements,
reinterpret_cast<const uint16_t *>(inTensorPtr)[numElements - 1]);
} else if (hostElementSize == 4) {
std::fill(
reinterpret_cast<uint32_t *>(inTensorPtr) + numElements,
reinterpret_cast<uint32_t *>(inTensorPtr) + numPaddedElements,
reinterpret_cast<const uint32_t *>(inTensorPtr)[numElements - 1]);
} else if (hostElementSize == 8) {
std::fill(
reinterpret_cast<uint64_t *>(inTensorPtr) + numElements,
reinterpret_cast<uint64_t *>(inTensorPtr) + numPaddedElements,
reinterpret_cast<const uint64_t *>(inTensorPtr)[numElements - 1]);
} else {
LOG(ERROR) << "Invalid Tensor type, padding is unsuccessful";
}
// // Pad remaining space with zeroes.
// memset(inputTensor.getUnsafePtr() + ptTensor.nbytes(), 0,
// inputTensor.getSizeInBytes() - ptTensor.nbytes());
} else {
inputTensor.zero();
}
glowTensor = std::move(inputTensor);
}
std::pair<glow::Tensor, torch::Tensor> tensors = {std::move(glowTensor),
std::move(ptTensor)};
return tensors;
}
Expected<std::pair<std::vector<glow::Tensor>, std::vector<torch::Tensor>>>
CachingGraphRunner::processPyTorchInputs(
at::ArrayRef<at::IValue> inputs,
const std::vector<Placeholder *> &inputPlaceholders) {
size_t numInputs = inputs.size();
std::vector<glow::Tensor> glowTensorInputs;
std::vector<torch::Tensor> ptTensorInputs;
glowTensorInputs.reserve(numInputs);
ptTensorInputs.reserve(numInputs);
// We only hold placeholders for tensor inputs so indexing them is
// different than indexing all inputs.
size_t placeholderI = 0;
for (const auto &input : inputs) {
if (!input.isTensor()) {
continue;
}
glow::Placeholder *ph = inputPlaceholders[placeholderI++];
auto ptTensorOrig = input.toTensor();
std::pair<glow::Tensor, torch::Tensor> tensors;
ASSIGN_VALUE_OR_RETURN_ERR(
tensors, convertPyTorchInputToGlowInput(std::move(ptTensorOrig), ph));
glowTensorInputs.push_back(std::move(tensors.first));
// Save the PyTorch tensor in case it owns memory we need for inference
ptTensorInputs.push_back(std::move(tensors.second));
}