-
Notifications
You must be signed in to change notification settings - Fork 421
Expand file tree
/
Copy pathort_patching.py
More file actions
executable file
·1755 lines (1505 loc) · 73.1 KB
/
ort_patching.py
File metadata and controls
executable file
·1755 lines (1505 loc) · 73.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Adapted from https://github.com/microsoft/onnxruntime/blob/baeece44ba075009c6bfe95891a8c1b3d4571cb3/onnxruntime/python/tools/quantization/quant_utils.py
# and https://github.com/microsoft/onnxruntime/blob/baeece44ba075009c6bfe95891a8c1b3d4571cb3/onnxruntime/python/tools/quantization/calibrate.py
# and https://github.com/microsoft/onnxruntime/blob/2ac381c55397dffff327cc6efecf6f95a70f90a1/onnxruntime/python/tools/quantization/onnx_quantizer.py
#
# MIT License
#
# Copyright (c) Microsoft Corporation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0 AND MIT
#
# 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.
"""This module contains all the patched functions from ORT."""
import gc
import tempfile
import uuid
from collections.abc import Sequence
from pathlib import Path
import numpy as np
import onnx
import onnxruntime as ort
import pynvml
from onnx import onnx_pb
from onnxruntime.quantization import calibrate
from onnxruntime.quantization.base_quantizer import BaseQuantizer
from onnxruntime.quantization.calibrate import (
CalibraterBase,
CalibrationDataReader,
CalibrationMethod,
DistributionCalibrater,
EntropyCalibrater,
HistogramCalibrater,
HistogramCollector,
MinMaxCalibrater,
PercentileCalibrater,
TensorData,
TensorsData,
)
from onnxruntime.quantization.qdq_quantizer import QDQQuantizer
from onnxruntime.quantization.quant_utils import (
QuantFormat,
QuantizationMode,
QuantType,
add_infer_metadata,
)
from onnxruntime.quantization.quantize import check_static_quant_arguments
from onnxruntime.quantization.registry import QDQRegistry, QLinearOpsRegistry
from onnxruntime.tools.symbolic_shape_infer import SymbolicShapeInference
from tqdm import tqdm
import modelopt.onnx.utils as onnx_utils
from modelopt.onnx.logging_config import logger
def load_model_with_shape_infer(model_path: Path) -> onnx.ModelProto:
"""Load model while performing symbolic shape infer and ONNX shape inference."""
model = onnx.load(str(model_path), load_external_data=True)
try:
model = onnx_utils.infer_shapes(model)
add_infer_metadata(model)
except Exception as e:
logger.info(f"Failed to infer shapes for model {model_path}: {e}")
return model
def _collect_value(histogram_collector, name_to_arr):
"""Collect histogram on real value."""
for tensor, data_arr in tqdm(name_to_arr.items()):
# ====================== Modification ======================
concat_data_arr = np.asarray(data_arr[0])
concat_data_arr = concat_data_arr.flatten()
for i in range(1, len(data_arr)):
curr_data_arr = np.asarray(data_arr[i])
curr_data_arr = curr_data_arr.flatten()
concat_data_arr = np.concatenate((concat_data_arr, curr_data_arr))
data_arr = concat_data_arr
# ==========================================================
if data_arr.size > 0:
min_value = np.min(data_arr)
max_value = np.max(data_arr)
else:
min_value = np.array(0, dtype=data_arr.dtype)
max_value = np.array(0, dtype=data_arr.dtype)
# Change the inf and nan values to meaningful min/max
min_value = (
np.finfo(np.float32).tiny if np.isinf(min_value) or np.isnan(min_value) else min_value
)
max_value = (
np.finfo(np.float32).max if np.isinf(max_value) or np.isnan(max_value) else max_value
)
threshold = max(abs(min_value), abs(max_value))
if tensor in histogram_collector.histogram_dict:
old_histogram = histogram_collector.histogram_dict[tensor]
histogram_collector.histogram_dict[tensor] = histogram_collector.merge_histogram(
old_histogram, data_arr, min_value, max_value, threshold
)
else:
hist, hist_edges = np.histogram(
data_arr, histogram_collector.num_bins, range=(-threshold, threshold)
)
histogram_collector.histogram_dict[tensor] = (
hist,
hist_edges,
min_value,
max_value,
threshold,
)
def _collect_absolute_value(histogram_collector, name_to_arr):
"""Collect histogram on absolute value."""
for tensor, data_arr in name_to_arr.items():
if isinstance(data_arr, list):
for arr in data_arr:
assert isinstance(arr, np.ndarray), (
f"Unexpected type {type(arr)} for tensor={tensor!r}"
)
dtypes = {a.dtype for a in data_arr}
assert len(dtypes) == 1, (
f"The calibration expects only one element type but got {dtypes} for tensor={tensor!r}"
)
# ====================== Modification ======================
concat_data_arr = np.asarray(data_arr[0])
concat_data_arr = concat_data_arr.flatten()
for i in range(1, len(data_arr)):
curr_data_arr = np.asarray(data_arr[i])
curr_data_arr = curr_data_arr.flatten()
concat_data_arr = np.concatenate((concat_data_arr, curr_data_arr))
data_arr_np = concat_data_arr
# ==========================================================
elif not isinstance(data_arr, np.ndarray):
raise ValueError(f"Unexpected type {type(data_arr)} for tensor={tensor!r}")
else:
data_arr_np = data_arr
data_arr_np = data_arr_np.flatten()
if data_arr_np.size > 0:
min_value = np.min(data_arr_np)
max_value = np.max(data_arr_np)
else:
min_value = np.array(0, dtype=data_arr_np.dtype)
max_value = np.array(0, dtype=data_arr_np.dtype)
data_arr_np = np.absolute(data_arr_np) # only consider absolute value
if tensor not in histogram_collector.histogram_dict:
# first time it uses num_bins to compute histogram.
hist, hist_edges = np.histogram(data_arr_np, bins=histogram_collector.num_bins)
hist_edges = hist_edges.astype(data_arr_np.dtype)
assert data_arr_np.dtype != np.float64, (
"only float32 or float16 is supported, every constant must be explicitly typed"
)
histogram_collector.histogram_dict[tensor] = (hist, hist_edges, min_value, max_value)
else:
old_histogram = histogram_collector.histogram_dict[tensor]
old_min = old_histogram[2]
old_max = old_histogram[3]
assert hasattr(old_min, "dtype"), (
f"old_min should be a numpy array but is {type(old_min)}"
)
assert hasattr(old_max, "dtype"), (
f"old_min should be a numpy array but is {type(old_max)}"
)
old_hist = old_histogram[0]
old_hist_edges = old_histogram[1]
temp_amax = np.max(data_arr_np)
if temp_amax > old_hist_edges[-1]:
# increase the number of bins
width = old_hist_edges[1] - old_hist_edges[0]
# NOTE: np.arange may create an extra bin after the one containing temp_amax
new_bin_edges = np.arange(old_hist_edges[-1] + width, temp_amax + width, width)
old_hist_edges = np.hstack((old_hist_edges, new_bin_edges))
hist, hist_edges = np.histogram(data_arr_np, bins=old_hist_edges)
hist_edges = hist_edges.astype(data_arr_np.dtype)
hist[: len(old_hist)] += old_hist
assert data_arr_np.dtype != np.float64, (
"only float32 or float16 is supported, every constant must be explicitly typed"
)
histogram_collector.histogram_dict[tensor] = (
hist,
hist_edges,
min(old_min, min_value),
max(old_max, max_value),
)
def _check_opset_version(onnx_quantizer):
ai_onnx_domain = [
opset
for opset in onnx_quantizer.model.model.opset_import
if not opset.domain or opset.domain in ["ai.onnx", "ai.onnx.contrib"]
]
opset_version = ai_onnx_domain[0].version
if opset_version == 10:
return 10
if opset_version < 10:
onnx_quantizer.model.model.opset_import.remove(ai_onnx_domain[0])
onnx_quantizer.model.model.opset_import.extend([onnx.helper.make_opsetid("", 11)])
opset_version = 11
if opset_version < 19 and onnx_quantizer.weight_qType == onnx_pb.TensorProto.FLOAT8E4M3FN:
onnx_quantizer.model.model.opset_import.remove(ai_onnx_domain[0])
onnx_quantizer.model.model.opset_import.extend([onnx.helper.make_opsetid("", 19)])
# Set ir_version to 10, remove it once ORT supports ir_version 11
onnx_quantizer.model.model.ir_version = 10
opset_version = 19
onnx_quantizer.fuse_dynamic_quant = True
return opset_version
def _select_tensors_to_calibrate(calibrator, model: onnx.ModelProto):
"""Select input/output tensors of candidate nodes to calibrate.
Returns:
tensors (set): set of tensor name.
value_infos (dict): tensor name to value info.
"""
value_infos = {vi.name: vi for vi in model.graph.value_info}
value_infos.update({ot.name: ot for ot in model.graph.output})
value_infos.update({it.name: it for it in model.graph.input})
initializer = {init.name for init in model.graph.initializer}
tensors_to_calibrate = set()
tensor_type_to_calibrate = {onnx_pb.TensorProto.FLOAT, onnx_pb.TensorProto.FLOAT16}
for node in model.graph.node:
# Hack: in calibrator.op_types_to_calibrate we pass nodes_to_quantize
if node.name in calibrator.op_types_to_calibrate:
for tensor_name in node.input:
if tensor_name in value_infos:
vi = value_infos[tensor_name]
if (
vi.type.HasField("tensor_type")
and (vi.type.tensor_type.elem_type in tensor_type_to_calibrate)
and (tensor_name not in initializer)
):
tensors_to_calibrate.add(tensor_name)
for tensor_name in node.output:
if tensor_name in value_infos:
vi = value_infos[tensor_name]
if vi.type.HasField("tensor_type") and (
vi.type.tensor_type.elem_type in tensor_type_to_calibrate
):
tensors_to_calibrate.add(tensor_name)
return tensors_to_calibrate, value_infos
def _create_inference_session_with_ep_config(calibrator, **kwargs):
"""Create an ORT InferenceSession."""
model_path = kwargs.get("model_path")
logger.debug("Creating inference session with Execution Provider configuration")
sess_options = ort.SessionOptions()
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL
sess_options.add_session_config_entry("session.use_device_allocator_for_initializers", "1")
sess_options.enable_cpu_mem_arena = False
providers = kwargs.get("execution_providers", [])
logger.debug(f"Execution providers: {providers}")
# Note. This path can be an empty string, which denotes that the model has custom ops and TRT EP is needed.
calibrator.trt_extra_plugin_lib_paths = kwargs.get("trt_extra_plugin_lib_paths")
if calibrator.trt_extra_plugin_lib_paths is not None:
logger.debug(f"TRT extra plugin paths: {calibrator.trt_extra_plugin_lib_paths}")
if "TensorrtExecutionProvider" not in ort.get_available_providers():
raise RuntimeError(
f"Could not find `TensorrtExecutionProvider`, only {ort.get_available_providers()}"
)
trt_ep_options = (
{"trt_extra_plugin_lib_paths": calibrator.trt_extra_plugin_lib_paths}
if calibrator.trt_extra_plugin_lib_paths
else {}
)
# Set GPU memory usage limit
trt_ep_options["trt_max_workspace_size"] = 80 * (1024**3) # 80GB
logger.debug(f"TRT EP options: {trt_ep_options}")
if "TensorrtExecutionProvider" in providers:
providers.remove("TensorrtExecutionProvider")
providers.insert(0, ("TensorrtExecutionProvider", trt_ep_options))
def _update_provider_config(provider, config):
if isinstance(provider, tuple) and len(provider) > 1 and isinstance(provider[1], dict):
provider[1].update(config)
else:
provider = (provider, config)
return provider
for i in range(len(providers)):
if any(p in providers[i] for p in ["CPUExecutionProvider", "CUDAExecutionProvider"]):
providers[i] = _update_provider_config(
providers[i], {"arena_extend_strategy": "kSameAsRequested"}
)
if model_path is None:
# Create the inference session with EP configuration on augmented_model
calibrator.infer_session = ort.InferenceSession(
calibrator.augmented_model_path,
sess_options=sess_options,
providers=providers,
)
else:
# Create the inference session with EP configuration on provided model path
calibrator.infer_session = ort.InferenceSession(
model_path,
sess_options=sess_options,
providers=providers,
)
# Group qdq tensors will have the same scaling factor.
calibrator.group_qdq_tensors = kwargs.get("group_qdq_tensors")
if calibrator.group_qdq_tensors:
logger.debug(f"Group QDQ tensors: {calibrator.group_qdq_tensors}")
def _compute_data_minmax_calibrator(calibrator):
"""Compute the min-max range of tensor.
:returns: dictionary mapping: {added node names: (ReduceMin, ReduceMax) pairs }
"""
if len(calibrator.intermediate_outputs) == 0:
return calibrator.calibrate_tensors_range
output_names = [
calibrator.infer_session.get_outputs()[i].name
for i in range(len(calibrator.intermediate_outputs[0]))
]
output_dicts_list = [
dict(zip(output_names, intermediate_output), strict=True)
for intermediate_output in calibrator.intermediate_outputs
]
merged_output_dict = {}
for d in output_dicts_list:
for k, v in d.items():
merged_output_dict.setdefault(k, []).append(v)
# ====================== Modification ======================
# Group qdq tensors should have the same scaling factor. Each tensor in group should add
# other tensors in its merged_dict value. In this way, calibrator will generate the same
# scaling factor.
if calibrator.group_qdq_tensors:
for cur, group in calibrator.group_qdq_tensors.items():
for other in group:
if cur == other:
continue
for d in output_dicts_list:
for k, v in d.items():
cur_min = cur + "_" + "ReduceMin"
cur_max = cur + "_" + "ReduceMax"
other_min = other + "_" + "ReduceMin"
other_max = other + "_" + "ReduceMax"
if k == other_min:
merged_output_dict[cur_min].append(v)
elif k == other_max:
merged_output_dict[cur_max].append(v)
# ============================================================
added_output_names = output_names[calibrator.num_model_outputs :]
calibrate_tensor_names = [
added_output_names[i].rpartition("_")[0] for i in range(0, len(added_output_names), 2)
] # output names
merged_added_output_dict = {
i: merged_output_dict[i]
for i in merged_output_dict
if i not in calibrator.model_original_outputs
}
pairs = []
for i in range(0, len(added_output_names), 2):
if calibrator.moving_average:
min_value_array = np.mean(merged_added_output_dict[added_output_names[i]], axis=0)
max_value_array = np.mean(merged_added_output_dict[added_output_names[i + 1]], axis=0)
else:
min_value_array = np.min(merged_added_output_dict[added_output_names[i]], axis=0)
max_value_array = np.max(merged_added_output_dict[added_output_names[i + 1]], axis=0)
if calibrator.symmetric:
max_absolute_value = np.max([np.abs(min_value_array), np.abs(max_value_array)], axis=0)
pairs.append((-max_absolute_value, max_absolute_value))
else:
pairs.append((min_value_array, max_value_array))
new_calibrate_tensors_range = TensorsData(
CalibrationMethod.MinMax, dict(zip(calibrate_tensor_names, pairs, strict=False))
)
if calibrator.calibrate_tensors_range:
calibrator.calibrate_tensors_range = calibrator.merge_range(
calibrator.calibrate_tensors_range, new_calibrate_tensors_range
)
else:
calibrator.calibrate_tensors_range = new_calibrate_tensors_range
return calibrator.calibrate_tensors_range
def _compute_data_min_max_calibrater_single_node_calibration(calibrater) -> TensorData:
"""Compute the min-max range of tensor.
:return: dictionary mapping: {added node names: (ReduceMin, ReduceMax) pairs }
Modification: Instead of aggregating two consecutive outputs to a MinMax pair, retrieve a MinMax pair from
outputs of Concat.
"""
if not calibrater.intermediate_outputs:
return calibrater.calibrate_tensors_range
# Get output names and merge all intermediate outputs
output_names = [out.name for out in calibrater.infer_session.get_outputs()]
# Merge outputs across all batches, filtering out original model outputs
merged_outputs = {}
for intermediate_output in calibrater.intermediate_outputs:
for name, value in zip(output_names, intermediate_output):
if name not in calibrater.model_original_outputs:
merged_outputs.setdefault(name, []).append(value)
# Compute min/max pairs for each tensor
pairs = []
tensor_names = []
for output_name, values in merged_outputs.items():
tensor_names.append(output_name.rpartition("_")[0])
if calibrater.moving_average:
min_val, max_val = np.mean(values, axis=0)
else:
stacked_values = np.stack(values, axis=0)
min_val = np.min(stacked_values, axis=0)[0]
max_val = np.max(stacked_values, axis=0)[1]
if calibrater.symmetric:
max_abs = max(np.abs(min_val), np.abs(max_val))
pairs.append((-max_abs, max_abs))
else:
pairs.append((min_val, max_val))
# Create and merge tensor range data
new_range = TensorsData(CalibrationMethod.MinMax, dict(zip(tensor_names, pairs)))
calibrater.calibrate_tensors_range = (
calibrater.merge_range(calibrater.calibrate_tensors_range, new_range)
if calibrater.calibrate_tensors_range
else new_range
)
return calibrater.calibrate_tensors_range
def _collect_data_minmax_calibrator(calibrator, data_reader: CalibrationDataReader):
"""This function overwrite is needed to solve OOM issue due to the unlimited accumulation of intermediate_outputs.
Support for: MinMax Calibrator.
Modification: indented the last lines of code inside the while loop in order to run compute_data for each sample
batch individually instead of the entire data at once. The assumption here is that the ONNX file has bs=N
and the calibration data size is M (where M is a multiple of N). So the calibrator is a sequence of M/N
samples with bs=N.
"""
run_options = ort.RunOptions()
try:
pynvml.nvmlInit()
gpu_count = pynvml.nvmlDeviceGetCount()
pynvml.nvmlShutdown()
except Exception as e:
logger.error(f"Failed to get GPU count: {e}")
gpu_count = 0
gpu_str = ";".join([f"gpu:{i}" for i in range(gpu_count)])
run_options.add_run_config_entry("memory.enable_memory_arena_shrinkage", f"cpu:0;{gpu_str}")
while True:
inputs = data_reader.get_next()
if not inputs:
break
run_options = ort.RunOptions()
calibrator.intermediate_outputs.append(
calibrator.infer_session.run(None, inputs, run_options=run_options)
)
# ======== Modification: block is indentend in ========
if len(calibrator.intermediate_outputs) == 0:
raise ValueError("No data is collected.")
t = calibrator.compute_data()
if not isinstance(t, TensorsData):
raise TypeError(f"compute_data must return a TensorsData not {type(t)}.")
calibrator.clear_collected_data()
# =====================================================
def _merge_range_minmax_calibrator(calibrator, old_range: TensorsData, new_range: TensorsData):
"""This function is an auxiliary function of collect_data to solve the OOM issue in the MinMax Calibrator.
Issue fixed with this function: old_range is not a dictionary, but old_range.data is.
TODO: create an MR in the ORT repository for this function. Alternatively, we can also file the MR fixing
TensorData (need to at least add items() function there).
"""
if not old_range:
return new_range
for key, value in old_range.data.items():
value_tuple = value.range_value
new_range_tuple = new_range.data[key].range_value
if calibrator.moving_average:
min_value = value_tuple[0] + calibrator.averaging_constant * (
new_range_tuple[0] - value_tuple[0]
)
max_value = value_tuple[1] + calibrator.averaging_constant * (
new_range_tuple[1] - value_tuple[1]
)
else:
min_value = min(value_tuple[0], new_range_tuple[0])
max_value = max(value_tuple[1], new_range_tuple[1])
new_range.data[key] = TensorData(lowest=min_value, highest=max_value)
return new_range
def _merge_range_min_max_calibrater_single_node_calibration(
calibrater, old_range: TensorsData, new_range: TensorsData
):
"""This function is an auxiliary function of collect_data to solve the OOM issue in the MinMax Calibrator.
Issue fixed with this function: old_range is not a dictionary, but old_range.data is.
TODO: create an MR in the ORT repository for this function. Alternatively, we can also file the MR fixing
TensorData (need to at least add items() function there).
"""
if not old_range:
return new_range
def _merge_ranges(old_min, old_max, new_min, new_max):
if calibrater.moving_average:
alpha = calibrater.averaging_constant
return (old_min + alpha * (new_min - old_min), old_max + alpha * (new_max - old_max))
return min(old_min, new_min), max(old_max, new_max)
old_data = old_range.data
for key, new_tensor in new_range.data.items():
if key in old_data:
old_min, old_max = old_data[key].range_value
new_min, new_max = new_tensor.range_value
merged_min, merged_max = _merge_ranges(old_min, old_max, new_min, new_max)
old_data[key] = TensorData(lowest=merged_min, highest=merged_max)
else:
old_data[key] = new_tensor
return old_range
def _collect_data_histogram_calibrator(calibrator, data_reader: CalibrationDataReader):
"""This function overwrite is needed to solve OOM issue due to the unlimited accumulation of intermediate_outputs.
Support for: Histogram Calibrator (which affects Entropy, Percentile, and DIstribution Calibrators).
Modification: indented the last lines of code inside the while loop in order to run compute_data for each sample
batch individually instead of the entire data at once.
"""
while True:
inputs = data_reader.get_next()
if not inputs:
break
calibrator.intermediate_outputs.append(calibrator.infer_session.run(None, inputs))
# ======== Modification: block is indentend in ========
# Here, compute_date is calculated for every sample batch instead of the entire data at once.
if len(calibrator.intermediate_outputs) == 0:
raise ValueError("No data is collected.")
output_names = [
calibrator.infer_session.get_outputs()[i].name
for i in range(len(calibrator.intermediate_outputs[0]))
]
output_dicts_list = [
dict(zip(output_names, intermediate_output))
for intermediate_output in calibrator.intermediate_outputs
]
merged_dict = {}
for d in output_dicts_list:
for k, v in d.items():
merged_dict.setdefault(k, []).append(v)
# Group qdq tensors should have the same scaling factor. Each tensor in group should add
# other tensors in its merged_dict value. In this way, calibrator will generate the same
# scaling factor.
if calibrator.group_qdq_tensors:
for cur, group in calibrator.group_qdq_tensors.items():
for other in group:
if cur == other:
continue
for d in output_dicts_list:
for k, v in d.items():
if k == other:
merged_dict[cur].append(v)
clean_merged_dict = {
i: merged_dict[i] for i in merged_dict if i in calibrator.tensors_to_calibrate
}
if not calibrator.collector:
calibrator.collector = HistogramCollector(
method=calibrator.method,
symmetric=calibrator.symmetric,
num_bins=calibrator.num_bins,
num_quantized_bins=calibrator.num_quantized_bins,
percentile=calibrator.percentile,
scenario=calibrator.scenario,
)
calibrator.collector.collect(clean_merged_dict)
calibrator.clear_collected_data()
# =====================================================
def _collect_data_min_max_calibrater_single_node_calibration(
calibrater, data_reader: CalibrationDataReader
):
"""Collects calibration data (min/max) for a MinMax Calibrator by processing single-node models batch by batch.
This function addresses an OOM issue by computing calibration data for each batch individually,
rather than accumulating all intermediate outputs across the entire dataset. It assumes the ONNX model
has a batch size of N, and the calibration data size M is a multiple of N, processing M/N batches.
Args:
calibrater: The calibrater object managing model inference and data collection.
data_reader: Provides batches of input data for calibration.
"""
input_counter = 0
while True:
inputs = data_reader.get_next()
if not inputs:
break
logger.debug(f"Collecting tensor data and finding min & max for input #{input_counter}")
# We are using single node model scheme. Set up model to input dependency map
model_to_input_dep_map = {}
for model_path, io_tensors in calibrater.single_node_model_path_map.items():
model_to_input_dep_map[model_path] = io_tensors[0].copy() # List of input names
# Setup input queues
input_queue = [model_input.name for model_input in calibrater.model.graph.input]
pbar = tqdm(total=len(model_to_input_dep_map.keys()))
# Resolve nodes are independent from inputs to add their outputs as inputs
inferred_model_list = []
for model_path, input_deps in model_to_input_dep_map.items():
if len(input_deps) == 0:
calibrater.create_inference_session(
execution_providers=calibrater.providers,
trt_extra_plugin_lib_paths=calibrater.trt_extra_plugin_lib_paths,
model_path=model_path,
)
outputs = calibrater.infer_session.run(None, {})
# Add output to inputs
need_calibration = False
for output_idx, output in enumerate(outputs):
output_name = calibrater.infer_session.get_outputs()[output_idx].name
inputs[output_name] = output
input_queue.append(output_name)
if (
output_name
in [output_tensor.name for output_tensor in calibrater.model.graph.output]
and output_name not in calibrater.model_original_outputs
):
need_calibration = True
# Mark model path to remove it from dependency map
inferred_model_list.append(model_path)
# For each inference, compute data before moving to other nodes if tensor is to be calibrated
if need_calibration:
calibrater.intermediate_outputs.append(outputs)
if len(calibrater.intermediate_outputs) == 0:
raise ValueError("No data is collected.")
t = calibrater.compute_data()
if not isinstance(t, TensorsData):
raise TypeError(f"compute_data must return a TensorsData not {type(t)}.")
calibrater.clear_collected_data()
gc.collect()
pbar.update(1)
# Remove inferred model from dependency map
for model_path in inferred_model_list:
model_to_input_dep_map.pop(model_path)
gc.collect()
# Process topological inference
input_ref_count = {}
while input_queue:
current_input_name = input_queue.pop(0)
# Initialize input reference count
input_ref_count[current_input_name] = sum(
current_input_name in input_deps for input_deps in model_to_input_dep_map.values()
)
# Perform inference
inferred_model_list = []
for model_path, input_deps in model_to_input_dep_map.items():
if current_input_name in input_deps:
input_deps.remove(current_input_name)
# If all dependencies are met, perform inference for the node.
if len(input_deps) == 0:
# Make dictionary of only needed inputs.
inputs_to_feed = {}
for input_name_to_feed in calibrater.single_node_model_path_map[model_path][
0
]:
inputs_to_feed[input_name_to_feed] = inputs[input_name_to_feed]
calibrater.create_inference_session(
execution_providers=calibrater.providers,
trt_extra_plugin_lib_paths=calibrater.trt_extra_plugin_lib_paths,
model_path=model_path,
)
outputs = calibrater.infer_session.run(None, inputs_to_feed)
# Mark model path to remove it from dependency map
inferred_model_list.append(model_path)
# Decrease reference count for used inputs and remove if no reference
for input_name in calibrater.single_node_model_path_map[model_path][0]:
input_ref_count[input_name] -= 1
if input_ref_count[input_name] == 0:
del inputs[input_name]
del input_ref_count[input_name]
gc.collect()
# Add outputs to inputs
need_calibration = False
for output_idx, output in enumerate(outputs):
output_name = calibrater.infer_session.get_outputs()[output_idx].name
inputs[output_name] = output
input_queue.append(output_name)
if (
output_name
in [
output_tensor.name
for output_tensor in calibrater.model.graph.output
]
and output_name not in calibrater.model_original_outputs
):
need_calibration = True
# For each inference, compute data before moving to other nodes if tensor is to be calibrated
if need_calibration:
calibrater.intermediate_outputs.append(outputs)
if len(calibrater.intermediate_outputs) == 0:
raise ValueError("No data is collected.")
t = calibrater.compute_data()
if not isinstance(t, TensorsData):
raise TypeError(
f"compute_data must return a TensorsData not {type(t)}."
)
calibrater.clear_collected_data()
gc.collect()
pbar.update(1)
# Remove inferred model from dependency map
for model_path in inferred_model_list:
model_to_input_dep_map.pop(model_path)
gc.collect()
pbar.close()
input_counter += 1
def _collect_data_histogram_calibrater_single_node_calibration(calibrator, data_reader):
"""Collects histogram data for single-node calibration, processing batches to avoid OOM.
Args:
calibrator: Histogram calibrator instance.
data_reader: CalibrationDataReader providing input data.
"""
input_counter = 0
while True:
inputs = data_reader.get_next()
if not inputs:
break
logger.debug(f"Collecting tensor data for input #{input_counter}")
# We are using single node model scheme. Set up model to input dependency map
model_to_input_dep_map = {}
for model_path, io_tensors in calibrator.single_node_model_path_map.items():
model_to_input_dep_map[model_path] = io_tensors[0].copy() # List of input names
# Compute data for input tensors
input_only_model = onnx.helper.make_model(
onnx.helper.make_graph(
[],
f"{calibrator.augmented_model_path[:-5]}_input_only",
calibrator.model.graph.input,
calibrator.model.graph.input,
),
opset_imports=calibrator.model.opset_import,
functions=calibrator.model.functions,
ir_version=calibrator.model.ir_version,
)
calibrator.infer_session = ort.InferenceSession(input_only_model.SerializeToString())
calibrator.intermediate_outputs.append(
[
inputs[calibrator.infer_session.get_outputs()[i].name]
for i in range(len(calibrator.infer_session.get_outputs()))
]
)
if len(calibrator.intermediate_outputs) == 0:
raise ValueError("No data is collected.")
output_names = [
calibrator.infer_session.get_outputs()[i].name
for i in range(len(calibrator.intermediate_outputs[0]))
]
output_dicts_list = [
dict(zip(output_names, intermediate_output))
for intermediate_output in calibrator.intermediate_outputs
]
merged_dict = {}
for d in output_dicts_list:
for k, v in d.items():
merged_dict.setdefault(k, []).append(v)
clean_merged_dict = {
i: merged_dict[i] for i in merged_dict if i in calibrator.tensors_to_calibrate
}
if not calibrator.collector:
calibrator.collector = HistogramCollector(
method=calibrator.method,
symmetric=calibrator.symmetric,
num_bins=calibrator.num_bins,
num_quantized_bins=calibrator.num_quantized_bins,
percentile=calibrator.percentile,
scenario=calibrator.scenario,
)
calibrator.collector.collect(clean_merged_dict)
calibrator.clear_collected_data()
gc.collect()
# Setup input queues
input_queue = [model_input.name for model_input in calibrator.model.graph.input]
pbar = tqdm(total=len(model_to_input_dep_map.keys()))
# Resolve nodes are independent from inputs to add their outputs as inputs
inferred_model_list = []
for model_path, input_deps in model_to_input_dep_map.items():
if len(input_deps) == 0:
calibrator.create_inference_session(
execution_providers=calibrator.providers,
trt_extra_plugin_lib_paths=calibrator.trt_extra_plugin_lib_paths,
model_path=model_path,
)
outputs = calibrator.infer_session.run(None, {})
# Add output to inputs
need_calibration = False
for output_idx, output in enumerate(outputs):
output_name = calibrator.infer_session.get_outputs()[output_idx].name
inputs[output_name] = output
input_queue.append(output_name)
if output_name in calibrator.tensors_to_calibrate:
need_calibration = True
# Mark model path to remove it from dependency map
inferred_model_list.append(model_path)
# For each inference, compute data before moving to other nodes if tensor is to be calibrated
if need_calibration:
calibrator.intermediate_outputs.append(outputs)
if len(calibrator.intermediate_outputs) == 0:
raise ValueError("No data is collected.")
output_names = [
calibrator.infer_session.get_outputs()[i].name
for i in range(len(calibrator.intermediate_outputs[0]))
]
output_dicts_list = [
dict(zip(output_names, intermediate_output))
for intermediate_output in calibrator.intermediate_outputs
]
merged_dict = {}
for d in output_dicts_list:
for k, v in d.items():
merged_dict.setdefault(k, []).append(v)
clean_merged_dict = {
i: merged_dict[i]
for i in merged_dict
if i in calibrator.tensors_to_calibrate
}
if not calibrator.collector:
calibrator.collector = HistogramCollector(
method=calibrator.method,
symmetric=calibrator.symmetric,
num_bins=calibrator.num_bins,
num_quantized_bins=calibrator.num_quantized_bins,
percentile=calibrator.percentile,
scenario=calibrator.scenario,
)
calibrator.collector.collect(clean_merged_dict)
calibrator.clear_collected_data()
gc.collect()
pbar.update(1)
# Remove inferred model from dependency map
for model_path in inferred_model_list:
model_to_input_dep_map.pop(model_path)
gc.collect()
# Process topological inference
input_ref_count = {}
while input_queue:
current_input_name = input_queue.pop(0)
# Initialize input reference count
input_ref_count[current_input_name] = sum(
current_input_name in input_deps for input_deps in model_to_input_dep_map.values()
)
# Perform inference
inferred_model_list = []
for model_path, input_deps in model_to_input_dep_map.items():
if current_input_name in input_deps:
input_deps.remove(current_input_name)
# If all dependencies are met, perform inference for the node.
if len(input_deps) == 0:
# Make dictionary of only needed inputs.
inputs_to_feed = {}
for input_name_to_feed in calibrator.single_node_model_path_map[model_path][
0
]:
inputs_to_feed[input_name_to_feed] = inputs[input_name_to_feed]
calibrator.create_inference_session(
execution_providers=calibrator.providers,
trt_extra_plugin_lib_paths=calibrator.trt_extra_plugin_lib_paths,
model_path=model_path,
)
outputs = calibrator.infer_session.run(None, inputs_to_feed)
# Mark model path to remove it from dependency map
inferred_model_list.append(model_path)