-
Notifications
You must be signed in to change notification settings - Fork 966
Expand file tree
/
Copy pathtest_program.py
More file actions
1297 lines (1147 loc) · 52.5 KB
/
test_program.py
File metadata and controls
1297 lines (1147 loc) · 52.5 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
#!/usr/bin/env fbpython
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
# pyre-unsafe
import copy
import dataclasses
import difflib
import json
import math
import unittest
from typing import Dict, List, Sequence
from executorch.exir._serialize._flatbuffer import _program_flatbuffer_to_json
from executorch.exir._serialize._named_data_store import NamedDataStoreOutput
from executorch.exir._serialize._program import (
_ExtendedHeader,
_get_extended_header,
_json_to_program,
_program_to_json,
deserialize_pte_binary,
PTEFile,
serialize_pte_binary,
)
from executorch.exir._serialize.data_serializer import DataEntry
from executorch.exir._serialize.padding import aligned_size
from executorch.exir.schema import (
BackendDelegate,
BackendDelegateDataReference,
BackendDelegateInlineData,
Buffer,
ContainerMetadata,
DataLocation,
DataSegment,
DeviceType,
ExecutionPlan,
NonConstBufferDevice,
Program,
SubsegmentOffsets,
)
from executorch.exir.tests.common import get_test_program
SEGMENT_ALIGNMENT: int = 128
CONSTANT_TENSOR_ALIGNMENT: int = 16
def add_constant_data(program: Program, blobs: Sequence[bytes]) -> None:
"""Adds the provided constant data blobs to the program."""
for blob in blobs:
program.constant_buffer.append(Buffer(storage=blob))
def add_delegate_data(
program: Program, plan: ExecutionPlan, blobs: Sequence[bytes]
) -> None:
"""Adds the provided delegate data blobs to the execution plan."""
di = len(plan.delegates)
for blob in blobs:
data_index: int = len(program.backend_delegate_data)
program.backend_delegate_data.append(
BackendDelegateInlineData(
data=blob,
)
)
delegate = BackendDelegate(
id=f"delegate{di}",
processed=BackendDelegateDataReference(
location=DataLocation.INLINE,
index=data_index,
),
compile_specs=[],
)
plan.delegates.append(delegate)
di += 1
def canonicalize_delegate_indices(program: Program) -> Program:
"""Returns a copy of the program with the backend delegate data list in
a predictable order.
"""
program = copy.deepcopy(program)
# Original index and its data.
delegate_entries: list[tuple[int, bytes]] = [
(i, entry.data) for i, entry in enumerate(program.backend_delegate_data)
]
# Sort by the contents of the data, which is the second entry in the tuple.
# NOTE: This is unstable if multiple entries have the same data contents.
delegate_entries.sort(key=lambda x: x[1])
# Build up the sorted Program.backend_delegate_data list, and a mapping from
# the old index to the new index.
old_to_new_index: dict[int, int] = {}
program.backend_delegate_data = []
for i, data in delegate_entries:
old_to_new_index[i] = len(program.backend_delegate_data)
print(f">>> Mapping [{i}]: {old_to_new_index[i]} '{data}'")
program.backend_delegate_data.append(BackendDelegateInlineData(data=data))
# Patch up the index pointers from the BackendDelegate entries.
for plan in program.execution_plan:
for delegate in plan.delegates:
delegate.processed.index = old_to_new_index[delegate.processed.index]
return program
class TestProgram(unittest.TestCase):
def assert_file_magic_present(self, program_data: bytes) -> None:
self.assertEqual(program_data[4:6], b"ET")
# Ignore the other bytes, which can change over time and are not
# important for this test.
def assert_programs_equal(self, program1: Program, program2: Program) -> None:
def prepare_json_string(j: str) -> List[str]:
"""Formats the JSON and splits it into lines."""
return json.dumps(json.loads(j), indent=2, sort_keys=True).splitlines(
keepends=True
)
# This JSON comparison is fragile: some parts of the program do not care
# about order (like the operators list), so those are technically free
# to be reordered. If they become a problem, we can canonicalize them
# like we do for the backend delegate data list.
json1 = _program_to_json(canonicalize_delegate_indices(program1))
json2 = _program_to_json(canonicalize_delegate_indices(program2))
# Use unified_diff so it only prints the differences instead of the
# entire string.
diff: str = "".join(
difflib.unified_diff(
prepare_json_string(json1),
prepare_json_string(json2),
)
)
if diff:
self.fail(msg="Programs are not equal\n" + diff)
def get_and_validate_extended_header(self, pte_data: bytes) -> _ExtendedHeader:
"""When an extended header is expected, check that it exists and is valid.
Does not check correctness of the contents."""
eh = _get_extended_header(pte_data)
self.assertIsNotNone(eh)
self.assertTrue(eh.is_valid())
self.assertLess(eh.program_size, len(pte_data))
return eh
def constant_segment_with_tensor_alignment(
self, constant_tensor_alignment: int
) -> None:
"""Utility to test constant segment with varying alignment.
Args:
constant_tensor_alignment: Alignment of constant tensor data.
Must be a multiple of 2.
Must be > 8 for the purposes of the test, which checks +- 3 bytes on the edges of each tensor.
"""
# Create a program with some constant tensor data.
program = get_test_program()
blobs = (
b"", # Empty tensor.
self.gen_blob_data(constant_tensor_alignment // 2, b"\x10\x11\x01"),
self.gen_blob_data(constant_tensor_alignment - 1, b"\x20\x22\x02"),
self.gen_blob_data(constant_tensor_alignment, b"\x30\x33\x03"),
self.gen_blob_data(constant_tensor_alignment + 1, b"\x40\x44\x04"),
)
add_constant_data(program, blobs)
# Extract blobs into constant segment during serialization.
pte_data = bytes(
serialize_pte_binary(
PTEFile(program=program),
segment_alignment=SEGMENT_ALIGNMENT,
constant_tensor_alignment=constant_tensor_alignment,
)
)
# The input Program should not be modified.
self.assertEqual(program.segments, [])
# Extended header should be present in the serialized data.
eh = self.get_and_validate_extended_header(pte_data)
# Segment offset should be non-zero since there are segments. It
# should point past the end of the program data, but not beyond
# the end of the file.
self.assertGreaterEqual(eh.segment_base_offset, eh.program_size)
self.assertLess(eh.segment_base_offset, len(pte_data))
# Segment data_size should be non-zero since there are segments.
self.assertGreater(eh.segment_data_size, 0)
# Peek inside the actual flatbuffer data to see the segments.
program_with_segments = _json_to_program(_program_flatbuffer_to_json(pte_data))
# The constant tensor data should appear as the only segment.
self.assertEqual(len(program_with_segments.segments), 1)
# The constant buffer should appear now as a constant segment.
segment_table: List[DataSegment] = program_with_segments.segments
self.assertEqual(len(segment_table), 1)
# Tensor sizes
# - tensor[0]: 0
# - tensors[1,2,3]: constant_tensor_alignment
# - tensor[4]: constant_tensor_alignment + 1 (no padding on the last tensor)
self.assertEqual(
segment_table[0].size,
constant_tensor_alignment * 3 + (constant_tensor_alignment + 1),
)
# Check constant_segment index and offsets.
subsegment_offsets: SubsegmentOffsets = program_with_segments.constant_segment
self.assertEqual(subsegment_offsets.segment_index, 0)
self.assertEqual(
subsegment_offsets.offsets,
[
0, # Start at offset 0.
0, # tensor[0] is empty.
constant_tensor_alignment, # tensor[1] has size constant_tensor_alignment // 2. Round up.
constant_tensor_alignment
* 2, # tensor[2] has size constant_tensor_alignment - 1. Round up.
constant_tensor_alignment
* 3, # tensor[3] has size constant_tensor_alignment. No padding needed.
],
)
# Check constant_buffer is empty, because the data was moved into the segment.
self.assertEqual(len(program_with_segments.constant_buffer), 0)
# Check segment data.
offsets = subsegment_offsets.offsets
segment_data: bytes = pte_data[eh.segment_base_offset :]
# Check segment data size.
self.assertEqual(len(segment_data), eh.segment_data_size)
# tensor[1]: padding.
self.assertEqual(
segment_data[offsets[1] : offsets[1] + 3],
# Tensor data.
b"\x10\x11\x11",
)
self.assertEqual(
segment_data[
offsets[1]
+ constant_tensor_alignment // 2 : offsets[1]
+ constant_tensor_alignment // 2
+ 3
],
# Padding.
b"\x00\x00\x00",
)
# tensor[3]: no padding.
self.assertEqual(
segment_data[offsets[4] - 3 : offsets[4] + 3],
# End of tensor 3.
b"\x33\x33\x03"
# Start of tensor 4.
+ b"\x40\x44\x44",
)
# tensor[4]: no padding for last tensor.
self.assertEqual(
segment_data[
offsets[4]
+ constant_tensor_alignment
- 3 : offsets[4]
+ constant_tensor_alignment
+ 1
],
b"\x44\x44\x44\x04",
)
# The final segment should not point past the end of the file.
self.assertLessEqual(
segment_table[-1].offset + segment_table[-1].size,
len(pte_data),
f"{segment_table}",
)
# Convert back.
deserialized = deserialize_pte_binary(pte_data)
# Programs are the same besides constant_buffer, as deserialization
# does not preserve constant segment; padding may be added
# during serialization.
self.assertEqual(deserialized.program.execution_plan, program.execution_plan)
# Number of constant tensors should be the same.
self.assertEqual(
len(deserialized.program.constant_buffer), len(program.constant_buffer)
)
self.assertEqual(deserialized.mutable_data, None)
self.assertEqual(deserialized.named_data, None)
def _check_named_data_entries(
self, reference: Dict[str, DataEntry], actual: Dict[str, DataEntry]
) -> None:
self.assertEqual(reference.keys(), actual.keys())
SKIP_FIELDS = {"alignment"} # Fields to ignore in comparison.
for key in reference.keys():
ref_entry = reference[key]
actual_entry = actual[key]
for field in dataclasses.fields(ref_entry):
if field.name not in SKIP_FIELDS:
self.assertEqual(
getattr(ref_entry, field.name),
getattr(actual_entry, field.name),
f"Named data record {key}.{field.name} does not match.",
)
def _check_named_data_store_output(
self, reference: NamedDataStoreOutput, actual: NamedDataStoreOutput
) -> None:
# Check buffers.
self.assertEqual(reference.buffers, actual.buffers)
# Check pte_data.
self._check_named_data_entries(reference.pte_data, actual.pte_data)
# Should be empty.
self.assertEqual(reference.external_data, actual.external_data)
def test_canonicalize_delegate_indices(self) -> None:
def make_execution_plan(
name: str, delegates: List[BackendDelegate]
) -> ExecutionPlan:
return ExecutionPlan(
name=name,
container_meta_type=ContainerMetadata(
encoded_inp_str="encoded_inp_str",
encoded_out_str="encoded_out_str",
),
values=[],
inputs=[],
outputs=[],
chains=[],
operators=[],
delegates=delegates,
non_const_buffer_sizes=[],
)
# A program with three delegates across two execution plans. To start
# with, the data indices in the delegates are in a non-canonical order.
program = Program(
version=0,
execution_plan=[
make_execution_plan(
name="forward0",
delegates=[
BackendDelegate(
id="delegate0",
processed=BackendDelegateDataReference(
location=DataLocation.INLINE, index=2
),
compile_specs=[],
),
BackendDelegate(
id="delegate1",
processed=BackendDelegateDataReference(
location=DataLocation.INLINE, index=1
),
compile_specs=[],
),
],
),
make_execution_plan(
name="forward1",
delegates=[
BackendDelegate(
id="delegate2",
processed=BackendDelegateDataReference(
location=DataLocation.INLINE, index=0
),
compile_specs=[],
),
],
),
],
constant_buffer=[],
backend_delegate_data=[
# Data is in non-canonical (unsorted) order.
BackendDelegateInlineData(data=b"CC delegate [1,0] data"),
BackendDelegateInlineData(data=b"BB delegate [0,1] data"),
BackendDelegateInlineData(data=b"AA delegate [0,0] data"),
],
segments=[],
constant_segment=SubsegmentOffsets(segment_index=0, offsets=[]),
)
# Demonstrate which data each delegate points to.
self.assertEqual(
program.backend_delegate_data[
program.execution_plan[0].delegates[0].processed.index
].data,
b"AA delegate [0,0] data",
)
self.assertEqual(
program.backend_delegate_data[
program.execution_plan[0].delegates[1].processed.index
].data,
b"BB delegate [0,1] data",
)
self.assertEqual(
program.backend_delegate_data[
program.execution_plan[1].delegates[0].processed.index
].data,
b"CC delegate [1,0] data",
)
# Canonicalize the program.
canonical_program: Program = canonicalize_delegate_indices(program)
# The delegate data list should be sorted by contents.
self.assertListEqual(
canonical_program.backend_delegate_data,
[
# Should have been sorted.
BackendDelegateInlineData(data=b"AA delegate [0,0] data"),
BackendDelegateInlineData(data=b"BB delegate [0,1] data"),
BackendDelegateInlineData(data=b"CC delegate [1,0] data"),
],
)
# Demonstrate that the delegate entries still point to the correct data.
self.assertEqual(
canonical_program.backend_delegate_data[
canonical_program.execution_plan[0].delegates[0].processed.index
].data,
b"AA delegate [0,0] data",
)
self.assertEqual(
canonical_program.backend_delegate_data[
canonical_program.execution_plan[0].delegates[1].processed.index
].data,
b"BB delegate [0,1] data",
)
self.assertEqual(
canonical_program.backend_delegate_data[
canonical_program.execution_plan[1].delegates[0].processed.index
].data,
b"CC delegate [1,0] data",
)
def test_round_trip_no_header_no_segments(self) -> None:
"""Tests that a Program remains the same after serializing and
deserializing.
"""
program = get_test_program()
pte_data = bytes(serialize_pte_binary(pte_file=PTEFile(program)))
self.assertGreater(len(pte_data), 16)
# File magic should be present at the expected offset.
self.assert_file_magic_present(pte_data)
# Extended header should not be present.
eh = _get_extended_header(pte_data)
self.assertIsNone(eh)
# Convert back.
deserialized = deserialize_pte_binary(pte_data)
# Programs should be the same.
self.assert_programs_equal(program, deserialized.program)
self.assertEqual(deserialized.mutable_data, None)
self.assertEqual(deserialized.named_data, None)
def test_round_trip_large_buffer_sizes(self) -> None:
"""Tests that when the non_const_buffer_sizes contains integers
overflowing a signed/unsigned 32 bit integer, we can still serialize the
model and get the same program by deserialization.
"""
program = get_test_program()
program.execution_plan[0].non_const_buffer_sizes = [0, 2**48]
flatbuffer_from_py = bytes(serialize_pte_binary(pte_file=PTEFile(program)))
self.assert_programs_equal(
program, deserialize_pte_binary(flatbuffer_from_py).program
)
def test_round_trip_with_non_const_buffer_device(self) -> None:
"""Tests that non_const_buffer_device survives round-trip
serialization/deserialization. This verifies the schema extension
for per-buffer device mapping works correctly.
"""
program = get_test_program()
program.execution_plan[0].non_const_buffer_device = [
NonConstBufferDevice(
buffer_idx=0, device_type=DeviceType.CPU, device_index=0
),
NonConstBufferDevice(
buffer_idx=1, device_type=DeviceType.CUDA, device_index=0
),
]
flatbuffer_from_py = bytes(serialize_pte_binary(pte_file=PTEFile(program)))
self.assert_programs_equal(
program, deserialize_pte_binary(flatbuffer_from_py).program
)
def test_round_trip_without_non_const_buffer_device(self) -> None:
"""Tests backward compatibility: a program without non_const_buffer_device
(the default) round-trips correctly and the field remains None.
"""
program = get_test_program()
self.assertIsNone(program.execution_plan[0].non_const_buffer_device)
flatbuffer_from_py = bytes(serialize_pte_binary(pte_file=PTEFile(program)))
deserialized = deserialize_pte_binary(flatbuffer_from_py).program
self.assert_programs_equal(program, deserialized)
self.assertIsNone(deserialized.execution_plan[0].non_const_buffer_device)
def test_round_trip_no_segments_and_no_header(self) -> None:
"""Tests that a Program serialized with extract_delegate_segments=True
when there are no segments does not contain an extended header,
constant segment, or delegate segments. Confirm that a Program remains
the same after serializing and deserializing.
"""
program = get_test_program()
pte_data = bytes(
serialize_pte_binary(
pte_file=PTEFile(program), extract_delegate_segments=True
)
)
self.assertGreater(len(pte_data), 16)
# File magic should be present at the expected offset.
self.assert_file_magic_present(pte_data)
# Extended header should not be present when no segments are created.
eh = _get_extended_header(pte_data)
self.assertIsNone(eh)
# Peek inside the flatbuffer data to confirm that there are no segments.
program_with_segments = _json_to_program(_program_flatbuffer_to_json(pte_data))
self.assertEqual(program_with_segments.segments, [])
# Convert back.
deserialized = deserialize_pte_binary(pte_data)
# Programs should be the same.
self.assert_programs_equal(program, deserialized.program)
self.assertEqual(deserialized.mutable_data, None)
self.assertEqual(deserialized.named_data, None)
@staticmethod
def gen_blob_data(size: int, pattern: bytes) -> bytes:
"""Generates a buffer with special first and last bytes,
repeating the middle byte of the pattern."""
assert len(pattern) == 3
assert size >= 3
# Stretch out the middle byte to fill the space.
ret = pattern[0:1] + pattern[1:2] * (size - 2) + pattern[2:3]
assert len(ret) == size
return ret
def test_round_trip_with_segments(self) -> None:
# Create a program with some delegate data blobs.
program = get_test_program()
blobs = (
self.gen_blob_data(SEGMENT_ALIGNMENT // 5, b"\x10\x11\x01"),
# Focus on blobs whose sizes fall close to the alignment.
self.gen_blob_data(SEGMENT_ALIGNMENT - 1, b"\x20\x22\x02"),
self.gen_blob_data(SEGMENT_ALIGNMENT, b"\x30\x33\x03"),
self.gen_blob_data(SEGMENT_ALIGNMENT + 1, b"\x40\x44\x04"),
b"", # Empty segment.
self.gen_blob_data(SEGMENT_ALIGNMENT // 10, b"\x50\x55\x05"),
)
add_delegate_data(program, program.execution_plan[0], blobs)
# Extract the blobs into segments during serialization.
pte_data = bytes(
serialize_pte_binary(
PTEFile(program=program),
extract_delegate_segments=True,
segment_alignment=SEGMENT_ALIGNMENT,
)
)
# The input Program should not have been modified.
self.assertEqual(program.segments, [])
self.assertEqual(
program.execution_plan[0].delegates[0].processed.location,
DataLocation.INLINE,
)
# Extended header should be present in the serialized data.
eh = self.get_and_validate_extended_header(pte_data)
# Segment offset should be non-zero since there are segments. It
# should point past the end of the program data, but not beyond
# the end of the file.
self.assertGreaterEqual(eh.segment_base_offset, eh.program_size)
self.assertLess(eh.segment_base_offset, len(pte_data))
# Segment data size should be non-zero since there are segments.
self.assertGreater(eh.segment_data_size, 0)
# Peek inside the actual flatbuffer data to see the segments. Note that
# this also implicity tests the case where we try parsing the entire
# file with segment data following it, demonstrating that the extra data
# doesn't upset the flatbuffer parsing path.
program_with_segments = _json_to_program(_program_flatbuffer_to_json(pte_data))
# The delegate blobs we added to the program should appear as segments.
# The one empty blob should have been ignored, hence the `- 1`.
self.assertEqual(len(program_with_segments.segments), len(blobs) - 1)
segment_table: List[DataSegment] = program_with_segments.segments
# Check segment range invariants.
for i in range(len(segment_table)):
# All offsets should be a multiple of SEGMENT_ALIGNMENT.
self.assertTrue(
segment_table[i].offset % SEGMENT_ALIGNMENT == 0,
f"Segment {i} offset is not aligned: {segment_table[i]}",
)
# There should be no empty segments.
self.assertGreater(
segment_table[i].size, 0, f"Segment {i}: {segment_table}"
)
if i > 0:
# Segments should not overlap, and should be sorted from
# smallest offset to largest.
self.assertLessEqual(
segment_table[i - 1].offset + segment_table[i - 1].size,
segment_table[i].offset,
f"Segment {i} overlaps or is out of order: {segment_table}",
)
# The first segment should begin at zero; i.e., at the segment base
# offset.
self.assertEqual(segment_table[0].offset, 0, f"{segment_table}")
# The final segment should not point past the end of the file.
self.assertLessEqual(
segment_table[-1].offset + segment_table[-1].size,
len(pte_data),
f"{segment_table}",
)
# Check the segment base offset boundary.
segment_base_offset = eh.segment_base_offset
self.assertEqual(
pte_data[segment_base_offset : segment_base_offset + 3],
# The first few bytes of the first segment.
b"\x10\x11\x11",
)
# Now that we've shown that the base offset is correct, slice off the
# front so that all segment offsets are relative to zero.
segment_data: bytes = pte_data[segment_base_offset:]
# Check segment data size.
self.assertEqual(len(segment_data), eh.segment_data_size)
# End of the first segment. It's much smaller than the alignment,
# so we know that it's followed by zeros.
self.assertEqual(
segment_data[segment_table[0].size - 3 : segment_table[0].size + 2],
# The end of the segment.
b"\x11\x11\x01"
# The padding that follows it.
+ b"\x00\x00",
)
# Look at the end of segment[2], which is exactly the same size as
# the alignment. There should be no padding, running right into the
# next segment.
self.assertEqual(
segment_data[segment_table[3].offset - 3 : segment_table[3].offset + 3],
# The end of segment[2].
b"\x33\x33\x03"
# The beginning of segment[3]
b"\x40\x44\x44",
)
# Convert back; the programs should be the same after a round trip,
# meaning that the segments were moved back to inline. This also
# demonstrates that the contents of all segments survived, and weren't
# truncated or corrupted.
deserialized = deserialize_pte_binary(pte_data)
self.assert_programs_equal(program, deserialized.program)
self.assertEqual(deserialized.mutable_data, None)
self.assertEqual(deserialized.named_data, None)
def test_no_constants(self) -> None:
program = get_test_program()
# Insert placeholder for non-const tensors.
add_constant_data(program, [b""])
pte_data = bytes(
serialize_pte_binary(
PTEFile(program=program),
extract_delegate_segments=True,
segment_alignment=SEGMENT_ALIGNMENT,
constant_tensor_alignment=CONSTANT_TENSOR_ALIGNMENT,
)
)
# The input Program should not be modified.
self.assertEqual(program.segments, [])
# Peek inside the actual flatbuffer data to see the segments.
flatbuffer_program = _json_to_program(_program_flatbuffer_to_json(pte_data))
# Constant buffer should be empty.
self.assertEqual(len(flatbuffer_program.constant_buffer), 0)
# Constant segment should contain the placeholder.
self.assertEqual(flatbuffer_program.constant_segment.segment_index, 0)
self.assertEqual(len(flatbuffer_program.constant_segment.offsets), 1)
self.assertEqual(flatbuffer_program.constant_segment.offsets[0], 0)
def test_unused_inline_delegate_blobs_with_segments(self) -> None:
# Create a program with some delegate data blobs.
program = get_test_program()
blobs = (
self.gen_blob_data(16, b"\x10\x11\x01"),
self.gen_blob_data(32, b"\x20\x22\x02"),
)
add_delegate_data(program, program.execution_plan[0], blobs)
# Extract the blobs into segments should succeeed.
pte_data = bytes(
serialize_pte_binary(
PTEFile(program=program),
extract_delegate_segments=True,
segment_alignment=SEGMENT_ALIGNMENT,
)
)
self.assertGreater(len(pte_data), 16)
# Add another inline blob that is not pointed to by a delegate.
program.backend_delegate_data.append(
BackendDelegateInlineData(data=self.gen_blob_data(16, b"\x30\x33\x03"))
)
# Should cause serialization to fail.
with self.assertRaises(ValueError):
serialize_pte_binary(
PTEFile(program=program),
extract_delegate_segments=True,
segment_alignment=SEGMENT_ALIGNMENT,
)
def test_constant_segment_tensor_alignment_16(self) -> None:
self.constant_segment_with_tensor_alignment(16)
def test_constant_segment_tensor_alignment_128(self) -> None:
self.constant_segment_with_tensor_alignment(128)
def test_constant_segment_tensor_alignment_non_power_of_2_fails(self) -> None:
# Create a program with some constant tensor data.
program = get_test_program()
program.constant_buffer.append(Buffer(storage=b"12345"))
constant_tensor_alignment: int = 14
# Extract blobs into constant segment during serialization.
# Expect failure as tensor alignment 14 is not a power of 2.
with self.assertRaises(ValueError):
serialize_pte_binary(
PTEFile(program=program),
segment_alignment=SEGMENT_ALIGNMENT,
constant_tensor_alignment=constant_tensor_alignment,
)
def test_constant_delegate_and_named_data_segments(self) -> None:
# Create a program with some constant tensor data and delegate data blobs.
program = get_test_program()
constant_blobs = (
self.gen_blob_data(CONSTANT_TENSOR_ALIGNMENT // 2, b"\x10\x11\x01"),
self.gen_blob_data(CONSTANT_TENSOR_ALIGNMENT + 1, b"\x20\x22\x02"),
)
delegate_blobs = (
self.gen_blob_data(SEGMENT_ALIGNMENT // 2, b"\x30\x33\x03"),
self.gen_blob_data(SEGMENT_ALIGNMENT + 1, b"\x40\x44\x04"),
)
add_constant_data(program, constant_blobs)
add_delegate_data(program, program.execution_plan[0], delegate_blobs)
# Create named data segment.
named_data_buffers = [
self.gen_blob_data(8, b"\x50\x55\x05"),
self.gen_blob_data(16, b"\x60\x66\x06"),
]
buffer_alignment = [3, 256]
pte_named_data = {
"key0": DataEntry(0, buffer_alignment[0], None), # expect lcm(3, 128) = 384
"key1": DataEntry(1, buffer_alignment[1], None),
} # expect lcm(256, 128) = 256
named_data = NamedDataStoreOutput(
buffers=named_data_buffers, pte_data=pte_named_data, external_data={}
)
# Extract the blobs into segments during serialization.
pte_data = bytes(
serialize_pte_binary(
PTEFile(program=program, named_data=named_data),
extract_delegate_segments=True,
segment_alignment=SEGMENT_ALIGNMENT,
constant_tensor_alignment=CONSTANT_TENSOR_ALIGNMENT,
)
)
# The input Program should not be modified.
self.assertEqual(program.segments, [])
self.assertEqual(
program.execution_plan[0].delegates[0].processed.location,
DataLocation.INLINE,
)
self.assertEqual(program.named_data, [])
# Extended header should be present in the serialized data.
eh = self.get_and_validate_extended_header(pte_data)
# Segment offset should be non-zero since there are segments. It
# should point past the end of the program data, but not beyond
# the end of the file.
self.assertGreaterEqual(eh.segment_base_offset, eh.program_size)
self.assertLess(eh.segment_base_offset, len(pte_data))
# Segment data size should be non-zero since there are segments.
self.assertGreater(eh.segment_data_size, 0)
# Peek inside the actual flatbuffer data to see the segments.
program_with_segments = _json_to_program(_program_flatbuffer_to_json(pte_data))
# Segment table should contain a constant segment, the delegate blobs
# and a named data segment.
segment_table: List[DataSegment] = program_with_segments.segments
self.assertEqual(
len(segment_table), len(delegate_blobs) + len(pte_named_data) + 1
)
self.assertEqual(segment_table[0].offset, 0)
# segment_table[0] is the constant segment, which
# contains a couple of tensors with sizes:
# - tensor[0] = CONSTANT_TENSOR_ALIGNMENT
# - tensor[1] = CONSTANT_TENSOR_ALIGNMENT + 1 (no padding on last tensor)
self.assertEqual(segment_table[0].size, CONSTANT_TENSOR_ALIGNMENT * 2 + 1)
self.assertEqual(segment_table[1].offset, SEGMENT_ALIGNMENT)
self.assertEqual(segment_table[1].size, SEGMENT_ALIGNMENT // 2)
self.assertEqual(segment_table[2].offset, SEGMENT_ALIGNMENT * 2)
self.assertEqual(segment_table[2].size, SEGMENT_ALIGNMENT + 1)
# Named data segments.
expected_offset = aligned_size(
(segment_table[2].offset + segment_table[2].size),
math.lcm(buffer_alignment[0], SEGMENT_ALIGNMENT),
)
self.assertEqual(segment_table[3].offset, expected_offset)
self.assertEqual(segment_table[3].size, len(named_data_buffers[0]))
expected_offset = aligned_size(
(segment_table[3].offset + segment_table[3].size),
math.lcm(buffer_alignment[1], SEGMENT_ALIGNMENT),
)
self.assertEqual(segment_table[4].offset, expected_offset)
self.assertEqual(segment_table[4].size, len(named_data_buffers[1]))
# Named data.
self.assertTrue(program_with_segments.named_data is not None)
program_named_data = program_with_segments.named_data
self.assertEqual(len(program_named_data), len(pte_named_data))
# Check named data values.
self.assertEqual(program_named_data[0].key, "key0")
self.assertEqual(program_named_data[0].segment_index, 3)
self.assertEqual(program_named_data[1].key, "key1")
self.assertEqual(program_named_data[1].segment_index, 4)
# Check constant_segment index and offsets.
subsegment_offsets: SubsegmentOffsets = program_with_segments.constant_segment
self.assertEqual(subsegment_offsets.segment_index, 0)
self.assertEqual(
subsegment_offsets.offsets,
[
0, # Start at offset 0.
16, # tensor[0] has size CONSTANT_TENSOR_ALIGNMENT. No padding required.
],
)
# Check constant_buffer is empty, because the data was moved into the segment.
self.assertEqual(len(program_with_segments.constant_buffer), 0)
# The first segment should begin at zero; i.e., at the segment base
# offset.
self.assertEqual(segment_table[0].offset, 0, f"{segment_table}")
# The final segment should not point past the end of the file.
self.assertLessEqual(
segment_table[-1].offset + segment_table[-1].size,
len(pte_data),
f"{segment_table}",
)
# Check the segment base offset boundary.
segment_base_offset = eh.segment_base_offset
self.assertEqual(
pte_data[segment_base_offset - 2 : segment_base_offset + 3],
# Padding before the first segment.
b"\x00\x00"
# First few bytes of the first segment.
+ b"\x10\x11\x11",
)
# Now that we've shown that the base offset is correct, slice off the
# front so that all segment offsets are relative to zero.
segment_data: bytes = pte_data[segment_base_offset:]
# Check segment data size.
self.assertEqual(len(segment_data), eh.segment_data_size)
# Check segment[0] for constants.
offsets = subsegment_offsets.offsets
# Check tensor[0]: padding at the end.
self.assertEqual(
segment_data[0 : offsets[1]],
# Tensor data.
b"\x10\x11\x11\x11\x11\x11\x11\x01"
# Padding.
+ b"\x00\x00\x00\x00\x00\x00\x00\x00",
)
# Check tensor[1]: padding at CONSTANT_TENSOR_ALIGNMENT.
self.assertEqual(
segment_data[
offsets[1]
+ CONSTANT_TENSOR_ALIGNMENT
- 3 : offsets[1]
+ CONSTANT_TENSOR_ALIGNMENT
+ 3
],
# Tensor data.
b"\x22\x22\x22"
# Padding.
+ b"\x02\x00\x00",
)
# Check segment[0] and segment[1] border.
self.assertEqual(
segment_data[segment_table[1].offset - 3 : segment_table[1].offset + 3],
# Padding for segment[0].
b"\x00\x00\x00"
# Start of segment[1].
+ b"\x30\x33\x33",
)
# Check segment[1] and segment[2] border.
self.assertEqual(
segment_data[segment_table[2].offset - 3 : segment_table[2].offset + 3],
# Padding for segment[1].
b"\x00\x00\x00"
# Start of segment[2].
+ b"\x40\x44\x44",
)
# Check named data segments
self.assertEqual(
segment_data[
segment_table[3].offset : segment_table[3].offset
+ segment_table[3].size
],
named_data_buffers[0],
)
self.assertEqual(
segment_data[
segment_table[4].offset : segment_table[4].offset
+ segment_table[4].size
],
named_data_buffers[1],
)
# Convert back.
deserialized = deserialize_pte_binary(pte_data)
# Programs are the same besides constant_buffer, as deserialization
# does not preserve constant segment; padding may be added
# during serialization.
self.assertEqual(deserialized.program.execution_plan, program.execution_plan)
# Number of constant tensors should be the same.
self.assertEqual(
len(deserialized.program.constant_buffer), len(program.constant_buffer)
)
self.assertEqual(deserialized.mutable_data, None)
self._check_named_data_store_output(deserialized.named_data, named_data)
def test_named_data_segments(self) -> None:
# Set segment alignment to 12 to test the padding.
SEGMENT_ALIGNMENT: int = 12
# Create a program with some named data segments.
program = get_test_program()
# Create named data segments with different alignments.
buffers = [
self.gen_blob_data(8, b"\x10\x11\x01"),
self.gen_blob_data(16, b"\x20\x22\x02"),
self.gen_blob_data(24, b"\x30\x33\x03"),
]
buffer_alignment = [8, 16, 24]
pte_named_data = {
"key1": DataEntry(0, buffer_alignment[0], None), # expect lcm(8, 12) = 24
"key2": DataEntry(0, buffer_alignment[0], None), # expect lcm(8, 12) = 24
"key3": DataEntry(1, buffer_alignment[1], None), # expect lcm(32, 12) = 96
"key4": DataEntry(2, buffer_alignment[2], None),
} # expect lcm(24, 12) = 24
named_data = NamedDataStoreOutput(
buffers=buffers, pte_data=pte_named_data, external_data={}
)
# Serialize the program with named data segments.
pte_data = bytes(
serialize_pte_binary(
PTEFile(program=program, named_data=named_data),