forked from onnx/onnx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.py
1676 lines (1461 loc) · 54.7 KB
/
helper.py
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) ONNX Project Contributors
#
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import collections.abc
import numbers
import struct
from cmath import isnan
from typing import (
Any,
Callable,
Dict,
KeysView,
List,
Sequence,
Tuple,
TypeVar,
Union,
cast,
)
import google.protobuf.message
import numpy as np
import onnx._custom_element_types as custom_np_types
from onnx import (
IR_VERSION,
AttributeProto,
FunctionProto,
GraphProto,
MapProto,
ModelProto,
NodeProto,
OperatorSetIdProto,
OptionalProto,
SequenceProto,
SparseTensorProto,
TensorProto,
TensorShapeProto,
TrainingInfoProto,
TypeProto,
ValueInfoProto,
defs,
mapping,
subbyte,
)
VersionRowType = Union[Tuple[str, int, int, int], Tuple[str, int, int, int, int]]
VersionTableType = List[VersionRowType]
AssignmentBindingType = List[Tuple[str, str]]
# This is a copy of the documented version in https://github.com/onnx/onnx/blob/main/docs/Versioning.md#released-versions
# Both must be updated whenever a new version of ONNX is released.
VERSION_TABLE: VersionTableType = [
# Release-version, IR version, ai.onnx version, ai.onnx.ml version, (optional) ai.onnx.training version
("1.0", 3, 1, 1),
("1.1", 3, 5, 1),
("1.1.2", 3, 6, 1),
("1.2", 3, 7, 1),
("1.3", 3, 8, 1),
("1.4.1", 4, 9, 1),
("1.5.0", 5, 10, 1),
("1.6.0", 6, 11, 2),
("1.7.0", 7, 12, 2, 1),
("1.8.0", 7, 13, 2, 1),
("1.8.1", 7, 13, 2, 1),
("1.9.0", 7, 14, 2, 1),
("1.10.0", 8, 15, 2, 1),
("1.10.1", 8, 15, 2, 1),
("1.10.2", 8, 15, 2, 1),
("1.11.0", 8, 16, 3, 1),
("1.12.0", 8, 17, 3, 1),
("1.13.0", 8, 18, 3, 1),
("1.13.1", 8, 18, 3, 1),
("1.14.0", 9, 19, 3, 1),
("1.14.1", 9, 19, 3, 1),
("1.15.0", 9, 20, 4, 1),
("1.16.0", 10, 21, 5, 1),
("1.17.0", 10, 22, 5, 1),
]
VersionMapType = Dict[Tuple[str, int], int]
def create_op_set_id_version_map(table: VersionTableType) -> VersionMapType:
"""Create a map from (opset-domain, opset-version) to ir-version from above table."""
result: VersionMapType = {}
def process(release_version: str, ir_version: int, *args: Any) -> None:
del release_version # Unused
for pair in zip(["ai.onnx", "ai.onnx.ml", "ai.onnx.training"], args):
if pair not in result:
result[pair] = ir_version
if pair[0] == "ai.onnx.training":
result["ai.onnx.preview.training", pair[1]] = ir_version
for row in table:
process(*row)
return result
OP_SET_ID_VERSION_MAP = create_op_set_id_version_map(VERSION_TABLE)
def find_min_ir_version_for(
opsetidlist: Sequence[OperatorSetIdProto], ignore_unknown: bool = False
) -> int:
"""Given list of opset ids, determine minimum IR version required.
Args:
opsetidlist: A sequence of OperatorSetIdProto.
ignore_unknown: If True, ignore unknown domain and return default minimum
version for that domain.
Returns:
The minimum IR version required (integer)
"""
default_min_version = 3
def find_min(domain: str | None, version: int) -> int:
key = (domain or "ai.onnx", version)
if key in OP_SET_ID_VERSION_MAP:
return OP_SET_ID_VERSION_MAP[key]
if ignore_unknown:
return default_min_version
raise ValueError("Unsupported opset-version.")
if opsetidlist:
return max(find_min(x.domain, x.version) for x in opsetidlist)
return default_min_version # if no opsets specified
def make_node(
op_type: str,
inputs: Sequence[str],
outputs: Sequence[str],
name: str | None = None,
doc_string: str | None = None,
domain: str | None = None,
overload: str | None = None,
**kwargs: Any,
) -> NodeProto:
"""Construct a NodeProto.
Args:
op_type (string): The name of the operator to construct
inputs (list of string): list of input names
outputs (list of string): list of output names
name (string, default None): optional unique identifier for NodeProto
doc_string (string, default None): optional documentation string for NodeProto
domain (string, default None): optional domain for NodeProto.
If it's None, we will just use default domain (which is empty)
overload (string, default None): optional field, used to
resolve calls to model-local functions
**kwargs (dict): the attributes of the node. The acceptable values
are documented in :func:`make_attribute`.
Returns:
NodeProto
"""
node = NodeProto()
node.op_type = op_type
node.input.extend(inputs)
node.output.extend(outputs)
if name:
node.name = name
if doc_string:
node.doc_string = doc_string
if domain is not None:
node.domain = domain
if overload is not None:
node.overload = overload
if kwargs:
node.attribute.extend(
make_attribute(key, value)
for key, value in sorted(kwargs.items())
if value is not None
)
return node
def make_operatorsetid(
domain: str,
version: int,
) -> OperatorSetIdProto:
"""Construct an OperatorSetIdProto.
Args:
domain (string): The domain of the operator set id
version (integer): Version of operator set id
Returns:
OperatorSetIdProto
"""
operatorsetid = OperatorSetIdProto()
operatorsetid.domain = domain
operatorsetid.version = version
return operatorsetid
def make_graph(
nodes: Sequence[NodeProto],
name: str,
inputs: Sequence[ValueInfoProto],
outputs: Sequence[ValueInfoProto],
initializer: Sequence[TensorProto] | None = None,
doc_string: str | None = None,
value_info: Sequence[ValueInfoProto] | None = None,
sparse_initializer: Sequence[SparseTensorProto] | None = None,
) -> GraphProto:
"""Construct a GraphProto
Args:
nodes: list of NodeProto
name (string): graph name
inputs: list of ValueInfoProto
outputs: list of ValueInfoProto
initializer: list of TensorProto
doc_string (string): graph documentation
value_info: list of ValueInfoProto
sparse_initializer: list of SparseTensorProto
Returns:
GraphProto
"""
if initializer is None:
initializer = []
if sparse_initializer is None:
sparse_initializer = []
if value_info is None:
value_info = []
graph = GraphProto()
graph.node.extend(nodes)
graph.name = name
graph.input.extend(inputs)
graph.output.extend(outputs)
graph.initializer.extend(initializer)
graph.sparse_initializer.extend(sparse_initializer)
graph.value_info.extend(value_info)
if doc_string:
graph.doc_string = doc_string
return graph
def make_opsetid(domain: str, version: int) -> OperatorSetIdProto:
"""Construct an OperatorSetIdProto.
Args:
domain (string): The domain of the operator set id
version (integer): Version of operator set id
Returns:
OperatorSetIdProto
"""
opsetid = OperatorSetIdProto()
opsetid.domain = domain
opsetid.version = version
return opsetid
def make_function(
domain: str,
fname: str,
inputs: Sequence[str],
outputs: Sequence[str],
nodes: Sequence[NodeProto],
opset_imports: Sequence[OperatorSetIdProto],
attributes: Sequence[str] | None = None,
attribute_protos: Sequence[AttributeProto] | None = None,
doc_string: str | None = None,
overload: str | None = None,
value_info: Sequence[ValueInfoProto] | None = None,
) -> FunctionProto:
if attributes is None:
attributes = []
if attribute_protos is None:
attribute_protos = []
if value_info is None:
value_info = []
f = FunctionProto()
f.domain = domain
f.name = fname
f.input.extend(inputs)
f.output.extend(outputs)
f.node.extend(nodes)
f.opset_import.extend(opset_imports)
f.attribute.extend(attributes)
f.attribute_proto.extend(attribute_protos)
if doc_string:
f.doc_string = doc_string
if overload is not None:
f.overload = overload
f.value_info.extend(value_info)
return f
def make_model(graph: GraphProto, **kwargs: Any) -> ModelProto:
"""Construct a ModelProto
Args:
graph (GraphProto): *make_graph* returns
**kwargs: any attribute to add to the returned instance
Returns:
ModelProto
"""
model = ModelProto()
# Touch model.ir_version so it is stored as the version from which it is
# generated.
model.ir_version = IR_VERSION
model.graph.CopyFrom(graph)
opset_imports: Sequence[OperatorSetIdProto] | None = None
opset_imports = kwargs.pop("opset_imports", None) # type: ignore
if opset_imports is not None:
model.opset_import.extend(opset_imports)
else:
# Default import
imp = model.opset_import.add()
imp.version = defs.onnx_opset_version()
functions: Sequence[FunctionProto] | None = None
functions = kwargs.pop("functions", None) # type: ignore
if functions is not None:
model.functions.extend(functions)
for k, v in kwargs.items():
# TODO: Does this work with repeated fields?
setattr(model, k, v)
return model
# An extension of make_model that infers an IR_VERSION for the model,
# if not specified, using a best-effort-basis.
def make_model_gen_version(graph: GraphProto, **kwargs: Any) -> ModelProto:
ir_version_field = "ir_version"
if ir_version_field not in kwargs:
opset_imports_field = "opset_imports"
imports = kwargs.get(opset_imports_field, [])
kwargs[ir_version_field] = find_min_ir_version_for(imports)
return make_model(graph, **kwargs)
def set_metadata_props(
proto: (
ModelProto
| GraphProto
| FunctionProto
| NodeProto
| TensorProto
| ValueInfoProto
),
dict_value: dict[str, str],
) -> None:
del proto.metadata_props[:]
for k, v in dict_value.items():
entry = proto.metadata_props.add()
entry.key = k
entry.value = v
def set_model_props(model: ModelProto, dict_value: dict[str, str]) -> None:
set_metadata_props(model, dict_value)
def split_complex_to_pairs(ca: Sequence[np.complex64]) -> Sequence[int]:
return [
(ca[i // 2].real if (i % 2 == 0) else ca[i // 2].imag) # type: ignore[misc]
for i in range(len(ca) * 2)
]
# convert a float32 value to a bfloat16 (as int)
# By default, this conversion rounds-to-nearest-even and supports NaN
# Setting `truncate` to True enables a simpler conversion. In this mode the
# conversion is performed by simply dropping the 2 least significant bytes of
# the significand. In this mode an error of up to 1 bit may be introduced and
# preservation of NaN values is not be guaranteed.
def float32_to_bfloat16(fval: float, truncate: bool = False) -> int:
ival = int.from_bytes(struct.pack("<f", fval), "little")
if truncate:
return ival >> 16
# NaN requires at least 1 significand bit set
if isnan(fval):
return 0x7FC0 # sign=0, exp=all-ones, sig=0b1000000
# drop bottom 16-bits
# round remaining bits using round-to-nearest-even
rounded = ((ival >> 16) & 1) + 0x7FFF
return (ival + rounded) >> 16
def float32_to_float8e4m3( # noqa: PLR0911
fval: float,
scale: float = 1.0,
fn: bool = True,
uz: bool = False,
saturate: bool = True,
) -> int:
"""Convert a float32 value to a float8, e4m3 (as int).
See :ref:`onnx-detail-float8` for technical details.
Args:
fval: float to convert
scale: scale, divide *fval* by *scale* before casting it
fn: no infinite values
uz: no negative zero
saturate: if True, any value out of range included inf becomes
the maximum value, otherwise, it becomes NaN. The
description of operator Cast fully describes the
differences.
Returns:
converted float
"""
if not fn:
raise NotImplementedError(
"float32_to_float8e4m3 not implemented with fn=False."
)
x = fval / scale
b = int.from_bytes(struct.pack("<f", np.float32(x)), "little")
ret = (b & 0x80000000) >> 24 # sign
if uz:
if (b & 0x7FC00000) == 0x7FC00000: # noqa: PLR2004
return 0x80
if np.isinf(x):
if saturate:
return ret | 127
return 0x80
e = (b & 0x7F800000) >> 23 # exponent
m = b & 0x007FFFFF # mantissa
if e < 116: # noqa: PLR2004
ret = 0
elif e < 120: # noqa: PLR2004
# denormalized number
ex = e - 119
if ex >= -2: # noqa: PLR2004
ret |= 1 << (2 + ex)
ret |= m >> (21 - ex)
elif m > 0:
ret |= 1
else:
ret = 0
mask = 1 << (20 - ex)
if m & mask and (
ret & 1
or m & (mask - 1) > 0
or (m & mask and m & (mask << 1) and m & (mask - 1) == 0)
):
# rounding
ret += 1
elif e < 135: # noqa: PLR2004
# normalized number
ex = e - 119 # 127 - 8
if ex == 0:
ret |= 0x4
ret |= m >> 21
else:
ret |= ex << 3
ret |= m >> 20
if m & 0x80000 and ((m & 0x100000) or (m & 0x7FFFF)):
if (ret & 0x7F) < 0x7F: # noqa: PLR2004
# rounding
ret += 1
elif not saturate:
return 0x80
elif saturate:
ret |= 0x7F # 01111110
else:
ret = 0x80
return int(ret)
else:
if (b & 0x7FC00000) == 0x7FC00000: # noqa: PLR2004
return 0x7F | ret
if np.isinf(x):
if saturate:
return ret | 126
return 0x7F | ret
e = (b & 0x7F800000) >> 23 # exponent
m = b & 0x007FFFFF # mantissa
if e != 0:
if e < 117: # noqa: PLR2004
pass
elif e < 121: # noqa: PLR2004
# denormalized number
ex = e - 120
if ex >= -2: # noqa: PLR2004
ret |= 1 << (2 + ex)
ret |= m >> (21 - ex)
elif m > 0:
ret |= 1
mask = 1 << (20 - ex)
if m & mask and (
ret & 1
or m & (mask - 1) > 0
or (m & mask and m & (mask << 1) and m & (mask - 1) == 0)
):
# rounding
ret += 1
elif e < 136: # noqa: PLR2004
# normalized number
ex = e - 120
if ex == 0:
ret |= 0x4
ret |= m >> 21
else:
ret |= ex << 3
ret |= m >> 20
if (ret & 0x7F) == 0x7F: # noqa: PLR2004
ret &= 0xFE
if (m & 0x80000) and ((m & 0x100000) or (m & 0x7FFFF)):
if (ret & 0x7F) < 0x7E: # noqa: PLR2004
# rounding
ret += 1
elif not saturate:
ret |= 0x7F
elif saturate:
ret |= 126 # 01111110
else:
ret |= 0x7F
return int(ret)
def float32_to_float8e5m2( # noqa: PLR0911
fval: float,
scale: float = 1.0,
fn: bool = False,
uz: bool = False,
saturate: bool = True,
) -> int:
"""Convert a float32 value to a float8, e5m2 (as int).
Args:
fval: float to convert
scale: scale, divide *fval* by *scale* before casting it
fn: no infinite values
uz: no negative zero
saturate: if True, any value out of range included inf becomes
the maximum value, otherwise, it becomes NaN. The
description of operator Cast fully describes the
differences.
Returns:
converted float
"""
x = fval / scale
b = int.from_bytes(struct.pack("<f", np.float32(x)), "little")
ret = (b & 0x80000000) >> 24 # sign
if fn and uz:
if (b & 0x7FC00000) == 0x7FC00000: # noqa: PLR2004
return 0x80
if (b & 0x7FFFFFFF) == 0x7F800000: # noqa: PLR2004
# inf
if saturate:
return ret | 0x7F
return 0x80
e = (b & 0x7F800000) >> 23 # exponent
m = b & 0x007FFFFF # mantissa
if e < 109: # noqa: PLR2004
ret = 0
elif e < 112: # noqa: PLR2004
# denormalized number
ex = e - 111
if ex >= -1:
ret |= 1 << (1 + ex)
ret |= m >> (22 - ex)
elif m > 0:
ret |= 1
else:
ret = 0
mask = 1 << (21 - ex)
if m & mask and (
ret & 1
or m & (mask - 1) > 0
or (m & mask and m & (mask << 1) and m & (mask - 1) == 0)
):
# rounding
ret += 1
elif e < 143: # noqa: PLR2004
# normalized number
ex = e - 111
ret |= ex << 2
ret |= m >> 21
if m & 0x100000 and ((m & 0xFFFFF) or (m & 0x200000)):
if (ret & 0x7F) < 0x7F: # noqa: PLR2004
# rounding
ret += 1
elif not saturate:
ret = 0x80
elif e == 255 and m == 0: # inf # noqa: PLR2004
ret = 0x80
elif saturate:
ret |= 0x7F # last possible number
else:
ret = 0x80
return int(ret)
elif not fn and not uz:
if (b & 0x7FC00000) == 0x7FC00000: # noqa: PLR2004
return 0x7F | ret
if np.isinf(x):
if saturate:
return 0x7B | ret
return 0x7C | ret
e = (b & 0x7F800000) >> 23 # exponent
m = b & 0x007FFFFF # mantissa
if e != 0:
if e < 110: # noqa: PLR2004
pass
elif e < 113: # noqa: PLR2004
# denormalized number
ex = e - 112
if ex >= -1:
ret |= 1 << (1 + ex)
ret |= m >> (22 - ex)
elif m > 0:
ret |= 1
mask = 1 << (21 - ex)
if m & mask and (
ret & 1
or m & (mask - 1) > 0
or (m & mask and m & (mask << 1) and m & (mask - 1) == 0)
):
# rounding
ret += 1
elif e < 143: # noqa: PLR2004
# normalized number
ex = e - 112
ret |= ex << 2
ret |= m >> 21
if m & 0x100000 and ((m & 0xFFFFF) or (m & 0x200000)):
if (ret & 0x7F) < 0x7B: # noqa: PLR2004
# rounding
ret += 1
elif saturate:
ret |= 0x7B
else:
ret |= 0x7C
elif saturate:
ret |= 0x7B
else:
ret |= 0x7C
return int(ret)
else:
raise NotImplementedError("fn and uz must be both False or True.")
def pack_float32_to_4bit(array: np.ndarray | Sequence, signed: bool) -> np.ndarray:
"""Convert an array of float32 value to a 4bit data-type and pack every two concecutive elements in a byte.
See :ref:`onnx-detail-int4` for technical details.
Args:
array: array of float to convert and pack
signed: Whether the 4 bit variant is signed or unsigned
Returns:
Packed array with size `ceil(farray.size/2)` (single dimension).
"""
if not isinstance(array, np.ndarray):
array = np.asarray(array, dtype=np.float32)
array_flat = array.ravel()
is_odd_volume = np.prod(array.shape) % 2 == 1
if is_odd_volume:
array_flat = np.append(array_flat, np.array([0]))
single_func = lambda x, y: subbyte.float32x2_to_4bitx2(x, y, signed) # noqa: E731
func = np.frompyfunc(single_func, 2, 1)
arr = func(array_flat[0::2], array_flat[1::2])
return arr.astype(np.uint8) # type: ignore[no-any-return]
def pack_float32_to_float4e2m1(array: np.ndarray | Sequence) -> np.ndarray:
"""Convert an array of float32 value to float4e2m1 and pack every two concecutive elements in a byte.
See :ref:`onnx-detail-float4` for technical details.
Args:
array: array of float to convert and pack
Returns:
Packed array of float4e2m1 (as uint8) with size `ceil(farray.size/2)` (single dimension).
"""
if not isinstance(array, np.ndarray):
array = np.asarray(array, dtype=np.float32)
array_flat = array.ravel()
is_odd_volume = np.prod(array.shape) % 2 == 1
if is_odd_volume:
array_flat = np.append(array_flat, np.array([0]))
arr = subbyte.float32x2_to_float4e2m1x2(array_flat[0::2], array_flat[1::2])
return arr.astype(np.uint8) # type: ignore[no-any-return]
def make_tensor(
name: str, data_type: int, dims: Sequence[int], vals: Any, raw: bool = False
) -> TensorProto:
"""Make a TensorProto with specified arguments. If raw is False, this
function will choose the corresponding proto field to store the
values based on data_type. If raw is True, use "raw_data" proto
field to store the values, and values should be of type bytes in
this case.
Args:
name (string): tensor name
data_type (int): a value such as onnx.TensorProto.FLOAT
dims (List[int]): shape
vals: values
raw (bool): if True, vals contains the serialized content of the tensor,
otherwise, vals should be a list of values of the type defined by *data_type*
Returns:
TensorProto
"""
tensor = TensorProto()
tensor.data_type = data_type
tensor.name = name
if data_type == TensorProto.STRING and raw:
raise TypeError("Can not use raw_data to store string type.")
np_dtype = tensor_dtype_to_np_dtype(data_type)
# Check number of vals specified equals tensor size
expected_size = 1
if raw:
# NumPy doesn't have BFLOAT16. TENSOR_TYPE_MAP maps it to float32, which has the wrong itemsize.
if data_type == TensorProto.BFLOAT16:
expected_size = 2
elif data_type in (
TensorProto.FLOAT8E4M3FN,
TensorProto.FLOAT8E4M3FNUZ,
TensorProto.FLOAT8E5M2,
TensorProto.FLOAT8E5M2FNUZ,
):
expected_size = 1
# NumPy doesn't have INT4/FP4. It is packed in couples to UINT8 buffers.
elif data_type in (TensorProto.UINT4, TensorProto.INT4, TensorProto.FLOAT4E2M1):
expected_size = 0.5 # type: ignore[assignment]
else:
expected_size = np_dtype.itemsize
if type(vals) is np.ndarray and len(vals.shape) > 1:
vals = vals.flatten()
for d in dims:
expected_size *= d
if len(vals) != expected_size:
# padding of half a byte is acceptable for 4bit types
if not (
data_type in (TensorProto.UINT4, TensorProto.INT4, TensorProto.FLOAT4E2M1)
and len(vals) == expected_size + 0.5
):
raise ValueError(
f"Number of values does not match tensor's size. Expected {expected_size}, but it is {len(vals)}. "
)
if raw:
tensor.raw_data = vals
else:
if data_type in (TensorProto.COMPLEX64, TensorProto.COMPLEX128):
vals = split_complex_to_pairs(vals)
elif data_type == TensorProto.FLOAT16:
vals = (
np.array(vals).astype(np_dtype).view(dtype=np.uint16).flatten().tolist()
)
elif data_type in (
TensorProto.BFLOAT16,
TensorProto.FLOAT8E4M3FN,
TensorProto.FLOAT8E4M3FNUZ,
TensorProto.FLOAT8E5M2,
TensorProto.FLOAT8E5M2FNUZ,
):
fcast = {
TensorProto.BFLOAT16: float32_to_bfloat16,
TensorProto.FLOAT8E4M3FN: float32_to_float8e4m3,
TensorProto.FLOAT8E4M3FNUZ: lambda *args: float32_to_float8e4m3( # type: ignore[misc]
*args, uz=True
),
TensorProto.FLOAT8E5M2: float32_to_float8e5m2,
TensorProto.FLOAT8E5M2FNUZ: lambda *args: float32_to_float8e5m2( # type: ignore[misc]
*args, fn=True, uz=True
),
}[
data_type # type: ignore[index]
]
vals = list(
map( # type: ignore[call-overload]
fcast,
np.array(vals).astype(np_dtype).flatten().tolist(),
)
)
elif data_type in (
TensorProto.UINT4,
TensorProto.INT4,
):
signed = data_type == TensorProto.INT4
# Two packed 4-bit values must be represented as a single uint8 value.
# Therefore, pack_float32_to_4bit() sets the dtype of the output vals
# to uint8 regardless of the value of 'signed'. Using int8 would cause
# the size of int4 tensors to increase ~5x if the tensor contains negative values (due to
# the way negative values are serialized by protobuf).
vals = pack_float32_to_4bit(vals, signed=signed).flatten().tolist()
elif data_type == TensorProto.FLOAT4E2M1:
vals = pack_float32_to_float4e2m1(vals).flatten().tolist()
elif data_type == TensorProto.BOOL:
vals = np.array(vals).astype(int)
elif data_type == TensorProto.STRING:
vals = np.array(vals).astype(bytes)
field = tensor_dtype_to_field(data_type)
getattr(tensor, field).extend(vals)
tensor.dims.extend(dims)
return tensor
def make_sparse_tensor(
values: TensorProto, indices: TensorProto, dims: Sequence[int]
) -> SparseTensorProto:
"""Construct a SparseTensorProto
Args:
values (TensorProto): the values
indices (TensorProto): the indices
dims: the shape
Returns:
SparseTensorProto
"""
sparse = SparseTensorProto()
sparse.values.CopyFrom(values)
sparse.indices.CopyFrom(indices)
sparse.dims.extend(dims)
return sparse
def make_sequence(
name: str,
elem_type: SequenceProto.DataType,
values: Sequence[Any],
) -> SequenceProto:
"""Make a Sequence with specified value arguments."""
sequence = SequenceProto()
sequence.name = name
sequence.elem_type = elem_type
if elem_type == SequenceProto.UNDEFINED:
return sequence
if elem_type == SequenceProto.TENSOR:
attribute = sequence.tensor_values
elif elem_type == SequenceProto.SPARSE_TENSOR:
attribute = sequence.sparse_tensor_values # type: ignore[assignment]
elif elem_type == SequenceProto.SEQUENCE:
attribute = sequence.sequence_values # type: ignore[assignment]
elif elem_type == SequenceProto.MAP:
attribute = sequence.map_values # type: ignore[assignment]
elif elem_type == OptionalProto.OPTIONAL:
attribute = sequence.optional_values # type: ignore[assignment]
else:
raise TypeError("The element type in the input sequence is not supported.")
attribute.extend(values)
return sequence
def make_map(
name: str, key_type: int, keys: list[Any], values: SequenceProto
) -> MapProto:
"""Make a Map with specified key-value pair arguments.
Criteria for conversion:
- Keys and Values must have the same number of elements
- Every key in keys must be of the same type
- Every value in values must be of the same type
"""
map_proto = MapProto()
valid_key_int_types = [
TensorProto.INT8,
TensorProto.INT16,
TensorProto.INT32,
TensorProto.INT64,
TensorProto.UINT8,
TensorProto.UINT16,
TensorProto.UINT32,
TensorProto.UINT64,
]
map_proto.name = name
map_proto.key_type = key_type
if key_type == TensorProto.STRING:
map_proto.string_keys.extend(keys)
elif key_type in valid_key_int_types:
map_proto.keys.extend(keys)
map_proto.values.CopyFrom(values)
return map_proto
def make_optional(
name: str,
elem_type: OptionalProto.DataType,
value: Any | None,
) -> OptionalProto:
"""Make an Optional with specified value arguments."""
optional = OptionalProto()
optional.name = name
optional.elem_type = elem_type
if elem_type == OptionalProto.UNDEFINED:
return optional
if elem_type == OptionalProto.TENSOR:
attribute = optional.tensor_value
elif elem_type == OptionalProto.SPARSE_TENSOR:
attribute = optional.sparse_tensor_value # type: ignore[assignment]
elif elem_type == OptionalProto.SEQUENCE:
attribute = optional.sequence_value # type: ignore[assignment]
elif elem_type == OptionalProto.MAP:
attribute = optional.map_value # type: ignore[assignment]
elif elem_type == OptionalProto.OPTIONAL:
attribute = optional.optional_value # type: ignore[assignment]
else:
raise TypeError("The element type in the input optional is not supported.")
attribute.CopyFrom(value) # type: ignore[arg-type]
return optional
def _to_bytes(value: str | bytes) -> bytes:
"""Coerce a string (or bytes) value into UTF-8 bytes."""
return value if isinstance(value, bytes) else value.encode("utf-8")
def make_attribute(
key: str,
value: Any,
doc_string: str | None = None,
attr_type: int | None = None,
) -> AttributeProto:
"""Makes an AttributeProto based on the value type."""
attr = AttributeProto()
attr.name = key
if doc_string:
attr.doc_string = doc_string
# Singular cases
if isinstance(value, numbers.Integral):
attr.i = int(value)
attr.type = AttributeProto.INT
elif isinstance(value, numbers.Real):
attr.f = float(value)
attr.type = AttributeProto.FLOAT
elif isinstance(value, (str, bytes)):
# Encode strings into utf-8
attr.s = _to_bytes(value)
attr.type = AttributeProto.STRING
elif isinstance(value, TensorProto):
attr.t.CopyFrom(value)
attr.type = AttributeProto.TENSOR
elif isinstance(value, SparseTensorProto):
attr.sparse_tensor.CopyFrom(value)
attr.type = AttributeProto.SPARSE_TENSOR
elif isinstance(value, GraphProto):
attr.g.CopyFrom(value)
attr.type = AttributeProto.GRAPH
elif isinstance(value, TypeProto):
attr.tp.CopyFrom(value)
attr.type = AttributeProto.TYPE_PROTO
# Iterable cases
elif isinstance(value, collections.abc.Iterable):
value = list(value)
if len(value) == 0 and attr_type is None:
raise ValueError(
f"Could not infer attribute `{key}` type from empty iterator"
)
if attr_type is None:
types = {type(v) for v in value}
for exp_t, exp_enum in (
(numbers.Integral, AttributeProto.INTS),
(numbers.Real, AttributeProto.FLOATS),
((str, bytes), AttributeProto.STRINGS),
(TensorProto, AttributeProto.TENSORS),
(SparseTensorProto, AttributeProto.SPARSE_TENSORS),
(GraphProto, AttributeProto.GRAPHS),
(TypeProto, AttributeProto.TYPE_PROTOS),
):
if all(issubclass(t, exp_t) for t in types): # type: ignore[arg-type]
attr_type = exp_enum
break
if attr_type is None:
raise ValueError(
"Could not infer the attribute type from the elements of the passed Iterable value."
)
if attr_type == AttributeProto.INTS:
attr.ints.extend(value)
attr.type = AttributeProto.INTS
elif attr_type == AttributeProto.FLOATS:
attr.floats.extend(value)
attr.type = AttributeProto.FLOATS
elif attr_type == AttributeProto.STRINGS: