-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathtest_export_session.py
More file actions
973 lines (815 loc) · 34.8 KB
/
Copy pathtest_export_session.py
File metadata and controls
973 lines (815 loc) · 34.8 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
# 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-strict
import unittest
from typing import List
from unittest.mock import Mock
import torch
from executorch.export import ExportRecipe, ExportSession
from executorch.export.recipe import (
AOQuantizationConfig,
LoweringRecipe,
QuantizationRecipe,
)
from executorch.export.stages import PipelineArtifact
from executorch.export.types import StageType
class SimpleTestModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.linear: torch.nn.Module = torch.nn.Linear(10, 5)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.linear(x)
class TestExportSessionCoreFlow(unittest.TestCase):
"""Test core export flow and pipeline execution."""
def setUp(self) -> None:
self.model = SimpleTestModel()
self.example_inputs = [(torch.randn(2, 10),)]
self.recipe = ExportRecipe(name="test")
def _create_mock_stage(self, stage_type: StageType) -> Mock:
mock_stage = Mock()
mock_artifact = Mock(spec=PipelineArtifact)
mock_artifact.data = Mock()
mock_artifact.context = {}
mock_stage.get_artifacts.return_value = mock_artifact
mock_stage.stage_type = stage_type
# Add the new properties required by the Stage interface
if stage_type == StageType.SOURCE_TRANSFORM:
mock_stage.valid_predecessor_stages = []
mock_stage.can_start_pipeline = True
elif stage_type == StageType.QUANTIZE:
mock_stage.valid_predecessor_stages = [StageType.SOURCE_TRANSFORM]
mock_stage.can_start_pipeline = True
elif stage_type == StageType.TORCH_EXPORT:
mock_stage.valid_predecessor_stages = [
StageType.SOURCE_TRANSFORM,
StageType.QUANTIZE,
]
mock_stage.can_start_pipeline = True
elif stage_type == StageType.TO_EDGE_TRANSFORM_AND_LOWER:
mock_stage.valid_predecessor_stages = [StageType.TORCH_EXPORT]
mock_stage.can_start_pipeline = True
elif stage_type == StageType.TO_EXECUTORCH:
mock_stage.valid_predecessor_stages = [
StageType.TO_EDGE_TRANSFORM_AND_LOWER,
StageType.TO_BACKEND,
]
mock_stage.can_start_pipeline = True
else:
mock_stage.valid_predecessor_stages = []
mock_stage.can_start_pipeline = True
return mock_stage
def test_default_pipeline_execution_order(self) -> None:
# Test that pipeline stages are executed in the correct order
stage_types = [
StageType.SOURCE_TRANSFORM,
StageType.QUANTIZE,
StageType.TORCH_EXPORT,
StageType.TO_EDGE_TRANSFORM_AND_LOWER,
StageType.TO_EXECUTORCH,
]
mock_stages = [
self._create_mock_stage(stage_type) for stage_type in stage_types
]
session = ExportSession(
model=self.model,
example_inputs=self.example_inputs,
export_recipe=self.recipe,
)
# Replace the stages in the registry with our mocked stages
for stage_type, mock_stage in zip(stage_types, mock_stages):
session.register_stage(stage_type, mock_stage)
session.export()
# Verify all stages were called
for stage in mock_stages:
stage.run.assert_called_once()
# Verify artifacts were stored for each stage
self.assertEqual(len(session._stage_to_artifacts), 5)
self.assertEqual(set(session._stage_to_artifacts.keys()), set(stage_types))
def test_overridden_pipeline_execution_order(self) -> None:
# Test when pipeline stages that are passed through recipe
stage_types = [
StageType.SOURCE_TRANSFORM,
StageType.TORCH_EXPORT,
StageType.TO_EDGE_TRANSFORM_AND_LOWER,
StageType.TO_EXECUTORCH,
]
mock_stages = [
self._create_mock_stage(stage_type) for stage_type in stage_types
]
self.recipe.pipeline_stages = stage_types
session = ExportSession(
model=self.model,
example_inputs=self.example_inputs,
export_recipe=self.recipe,
)
# Replace the stages in the registry with our mocked stages
for stage_type, mock_stage in zip(stage_types, mock_stages):
session.register_stage(stage_type, mock_stage)
session.export()
# Verify all stages were called
for stage in mock_stages:
stage.run.assert_called_once()
# Verify artifacts were stored for each stage
self.assertEqual(len(session._stage_to_artifacts), 4)
self.assertEqual(set(session._stage_to_artifacts.keys()), set(stage_types))
def test_model_standardization_single_to_dict(self) -> None:
session = ExportSession(
model=self.model,
example_inputs=self.example_inputs,
export_recipe=self.recipe,
)
self.assertIsInstance(session._model, dict)
self.assertIn("forward", session._model)
self.assertEqual(session._model["forward"], self.model)
self.assertIsInstance(session._example_inputs, dict)
self.assertIn("forward", session._example_inputs)
self.assertEqual(session._example_inputs["forward"], self.example_inputs)
def test_model_standardization_preserves_dict(self) -> None:
# Test that dictionary models are preserved as-is.
model_dict = {"method1": self.model, "method2": SimpleTestModel()}
inputs_dict = {
"method1": self.example_inputs,
"method2": [(torch.randn(1, 10),)],
}
session = ExportSession(
model=model_dict, # pyre-ignore[6]
example_inputs=inputs_dict,
export_recipe=self.recipe,
)
self.assertEqual(session._model, model_dict)
self.assertEqual(session._example_inputs, inputs_dict)
def test_context_propagation_through_pipeline(self) -> None:
# Test that context is properly propagated through the pipeline
session = ExportSession(
model=self.model,
example_inputs=self.example_inputs,
export_recipe=self.recipe,
name="test_session",
constant_methods={"const_method": lambda: torch.tensor([1, 2, 3])},
)
# Check that initial context is set up correctly
expected_context_keys = {
"example_inputs",
"dynamic_shapes",
"constant_methods",
"export_recipe",
"session_name",
"artifact_dir",
"generate_etrecord",
}
self.assertEqual(set(session._run_context.keys()), expected_context_keys)
self.assertEqual(session._run_context["session_name"], "test_session")
self.assertIsNotNone(session._run_context["constant_methods"])
def test_stage_registry_unknown_stage_type(self) -> None:
# Test error handling for unknown stage types in pipeline
unknown_stage_type = Mock()
unknown_stage_type.name = "UNKNOWN_STAGE"
recipe = ExportRecipe(name="test", pipeline_stages=[unknown_stage_type])
with self.assertRaises(ValueError) as cm:
ExportSession(
model=self.model,
example_inputs=self.example_inputs,
export_recipe=recipe,
)._run_pipeline()
self.assertIn("not found in registry", str(cm.exception))
def test_multi_method_model_export(self) -> None:
# Test export with multi-method models
model_dict = {
"forward": self.model,
"inference": SimpleTestModel(),
}
inputs_dict = {
"forward": self.example_inputs,
"inference": [(torch.randn(1, 10),)],
}
session = ExportSession(
model=model_dict, # pyre-ignore[6]
example_inputs=inputs_dict,
export_recipe=ExportRecipe(name="multi_method_test"),
)
# Verify proper initialization
self.assertEqual(session._model, model_dict)
self.assertEqual(session._example_inputs, inputs_dict)
# Test getting example inputs for different methods
forward_input = session.get_example_input("forward")
inference_input = session.get_example_input("inference")
self.assertEqual(forward_input, self.example_inputs[0])
self.assertEqual(inference_input, inputs_dict["inference"][0])
class TestPipelineValidation(unittest.TestCase):
def setUp(self) -> None:
self.model = SimpleTestModel()
self.example_inputs = [(torch.randn(2, 10),)]
self.recipe = ExportRecipe(name="test")
# pyre-ignore
def _get_export_session(self, stages: List[StageType]):
self.recipe.pipeline_stages = stages
return ExportSession(
model=self.model,
example_inputs=self.example_inputs,
export_recipe=self.recipe,
)
def test_valid_pipeline_sequences(self) -> None:
"""Test various valid pipeline sequences."""
valid_sequences = [
# Full pipeline with to_edge_transform_lower
[
StageType.SOURCE_TRANSFORM,
StageType.QUANTIZE,
StageType.TORCH_EXPORT,
StageType.TO_EDGE_TRANSFORM_AND_LOWER,
StageType.TO_EXECUTORCH,
],
# Full pipeline with to_edge, to_backend
[
StageType.SOURCE_TRANSFORM,
StageType.QUANTIZE,
StageType.TORCH_EXPORT,
StageType.TO_EDGE,
StageType.TO_BACKEND,
StageType.TO_EXECUTORCH,
],
# Skip quantize
[
StageType.SOURCE_TRANSFORM,
StageType.TORCH_EXPORT,
StageType.TO_EDGE_TRANSFORM_AND_LOWER,
StageType.TO_EXECUTORCH,
],
# Skip source transform and start with quantize
[
StageType.QUANTIZE,
StageType.TORCH_EXPORT,
StageType.TO_EDGE_TRANSFORM_AND_LOWER,
StageType.TO_EXECUTORCH,
],
# Start with torch export
[
StageType.TORCH_EXPORT,
StageType.TO_EDGE_TRANSFORM_AND_LOWER,
StageType.TO_EXECUTORCH,
],
# Start with edge transform and lower (ExportedProgram input)
[
StageType.TO_EDGE_TRANSFORM_AND_LOWER,
StageType.TO_EXECUTORCH,
],
# Start with to_edge and to_backend
[
StageType.TO_EDGE,
StageType.TO_BACKEND,
StageType.TO_EXECUTORCH,
],
]
for i, stages in enumerate(valid_sequences):
with self.subTest(sequence=i, stages=[s.name for s in stages]):
session = self._get_export_session(stages)
# Should not raise any exception
try:
session._validate_pipeline_sequence(stages)
except Exception as e:
self.fail(f"Valid sequence {[s.name for s in stages]} raised {e}")
def test_invalid_pipeline_start_stages(self) -> None:
"""Test stages that cannot start a pipeline."""
invalid_stage_sequence = [
# Executorch stage cannot start pipeline (requires edge stage first)
[StageType.TO_EXECUTORCH],
# Backend stage cannot start pipeline (requires TO_EDGE first)
[StageType.TO_BACKEND],
[StageType.TO_BACKEND, StageType.TO_EXECUTORCH],
]
for i, stages in enumerate(invalid_stage_sequence):
with self.subTest(sequence=i, stages=[s.name for s in stages]):
session = self._get_export_session(stages)
with self.assertRaises(ValueError) as cm:
session._validate_pipeline_sequence(stages)
self.assertIn("cannot start a pipeline", str(cm.exception))
def test_pipeline_transitions(self) -> None:
"""Test both valid and invalid pipeline transitions"""
test_cases = [
# Valid cases
([StageType.SOURCE_TRANSFORM, StageType.QUANTIZE], True),
([StageType.QUANTIZE, StageType.TORCH_EXPORT], True),
([StageType.SOURCE_TRANSFORM, StageType.TORCH_EXPORT], True),
([StageType.TORCH_EXPORT, StageType.TO_EDGE_TRANSFORM_AND_LOWER], True),
# Invalid cases - transitions
([StageType.QUANTIZE, StageType.TO_EDGE_TRANSFORM_AND_LOWER], False),
(
[StageType.SOURCE_TRANSFORM, StageType.TO_EDGE_TRANSFORM_AND_LOWER],
False,
),
(
[
StageType.TORCH_EXPORT,
StageType.TO_EDGE_TRANSFORM_AND_LOWER,
StageType.QUANTIZE,
],
False,
),
([StageType.TO_EXECUTORCH, StageType.TORCH_EXPORT], False),
]
for i, (stages, should_pass) in enumerate(test_cases):
with self.subTest(
sequence=i, stages=[s.name for s in stages], should_pass=should_pass
):
session = self._get_export_session(stages)
if should_pass:
try:
session._validate_pipeline_sequence(stages)
except Exception as e:
self.fail(
f"Expected valid sequence {[s.name for s in stages]} but got {e}"
)
else:
with self.assertRaises(ValueError):
session._validate_pipeline_sequence(stages)
def test_empty_pipeline_sequence(self) -> None:
"""Test empty pipeline sequence."""
session = self._get_export_session([])
with self.assertRaises(ValueError) as cm:
session._validate_pipeline_sequence([])
self.assertIn("Pipeline stages cannot be empty", str(cm.exception))
class TestExportSessionErrorHandling(unittest.TestCase):
"""Test error handling in export session."""
def setUp(self) -> None:
self.model = SimpleTestModel()
self.example_inputs = [(torch.randn(2, 10),)]
self.recipe = ExportRecipe(name="test")
def test_access_results_before_export(self) -> None:
"""Test that accessing results before export raises appropriate errors."""
session = ExportSession(
model=self.model,
example_inputs=self.example_inputs,
export_recipe=self.recipe,
)
with self.assertRaises(RuntimeError) as cm:
session.get_executorch_program_manager()
self.assertIn(
"Executorch program manager is not initialized", str(cm.exception)
)
with self.assertRaises(RuntimeError) as cm:
session.get_executorch_program()
self.assertIn(
"Executorch program manager is not initialized", str(cm.exception)
)
with self.assertRaises(RuntimeError) as cm:
session.get_pte_buffer()
self.assertIn(
"Executorch program manager is not initialized", str(cm.exception)
)
def test_invalid_method_name_in_example_inputs(self) -> None:
"""Test error handling for invalid method names."""
session = ExportSession(
model=self.model,
example_inputs=self.example_inputs,
export_recipe=self.recipe,
)
with self.assertRaises(KeyError) as cm:
session.get_example_input("nonexistent_method")
self.assertIn("Method name 'nonexistent_method' not found", str(cm.exception))
def test_empty_example_inputs_list(self) -> None:
"""Test error handling for empty example inputs."""
session = ExportSession(
model={"forward": self.model},
example_inputs={"forward": []},
export_recipe=self.recipe,
)
with self.assertRaises(ValueError) as cm:
session.get_example_input("forward")
self.assertIn(
"Example inputs list for method forward is empty", str(cm.exception)
)
def test_save_to_pte_invalid_name(self) -> None:
"""Test save_to_pte with invalid output name."""
session = ExportSession(
model=self.model,
example_inputs=self.example_inputs,
export_recipe=self.recipe,
)
with self.assertRaises(AssertionError):
session.save_to_pte("")
with self.assertRaises(AssertionError):
session.save_to_pte(None) # pyre-ignore
class TestExportSessionPipelineBuilding(unittest.TestCase):
"""Test pipeline building and stage configuration."""
def setUp(self) -> None:
self.model = SimpleTestModel()
self.example_inputs = [(torch.randn(2, 10),)]
def test_pipeline_building_with_all_recipes(self) -> None:
"""Test pipeline building with quantization and lowering recipes."""
# Create comprehensive recipes
quant_recipe = QuantizationRecipe(
ao_quantization_configs=[AOQuantizationConfig(Mock())],
quantizers=[Mock()],
)
lowering_recipe = LoweringRecipe(
partitioners=[Mock()],
edge_transform_passes=[Mock()],
edge_compile_config=Mock(),
)
recipe = ExportRecipe(
name="comprehensive_test",
quantization_recipe=quant_recipe,
lowering_recipe=lowering_recipe,
executorch_backend_config=Mock(),
)
session = ExportSession(
model=self.model,
example_inputs=self.example_inputs,
export_recipe=recipe,
)
registered_stages = session.get_all_registered_stages()
self.assertEqual(len(registered_stages), 5)
expected_types = [
StageType.SOURCE_TRANSFORM,
StageType.QUANTIZE,
StageType.TORCH_EXPORT,
StageType.TO_EDGE_TRANSFORM_AND_LOWER,
StageType.TO_EXECUTORCH,
]
self.assertListEqual(list(registered_stages.keys()), expected_types)
class TestExportSessionExtendedInputTypes(unittest.TestCase):
"""Test extended input type support (GraphModule, ExportedProgram, etc.)"""
def setUp(self) -> None:
self.model = SimpleTestModel()
self.example_inputs = (torch.randn(2, 10),)
self.recipe = ExportRecipe(name="test")
def test_nn_module_input_type_detection(self) -> None:
"""Test that nn.Module input is detected correctly."""
session = ExportSession(
model=self.model,
example_inputs=[self.example_inputs],
export_recipe=self.recipe,
)
self.assertEqual(session._input_model_type, "nn.Module")
# Verify default pipeline includes quantization stages
pipeline = session._get_default_pipeline()
self.assertIn(StageType.SOURCE_TRANSFORM, pipeline)
self.assertIn(StageType.QUANTIZE, pipeline)
self.assertIn(StageType.TORCH_EXPORT, pipeline)
self.assertIn(StageType.TO_EDGE_TRANSFORM_AND_LOWER, pipeline)
self.assertIn(StageType.TO_EXECUTORCH, pipeline)
def test_graph_module_input_type_detection(self) -> None:
"""Test that GraphModule input is detected correctly."""
# Create a GraphModule using fx.symbolic_trace
graph_module = torch.fx.symbolic_trace(self.model)
session = ExportSession(
model=graph_module,
example_inputs=[self.example_inputs],
export_recipe=self.recipe,
)
self.assertEqual(session._input_model_type, "GraphModule")
# Verify default pipeline skips quantization stages
pipeline = session._get_default_pipeline()
self.assertNotIn(StageType.SOURCE_TRANSFORM, pipeline)
self.assertNotIn(StageType.QUANTIZE, pipeline)
self.assertIn(StageType.TORCH_EXPORT, pipeline)
self.assertIn(StageType.TO_EDGE_TRANSFORM_AND_LOWER, pipeline)
self.assertIn(StageType.TO_EXECUTORCH, pipeline)
def test_exported_program_input_type_detection(self) -> None:
"""Test that ExportedProgram input is detected correctly."""
# Create an ExportedProgram
exported_program = torch.export.export(self.model, self.example_inputs)
# ExportedProgram should not require example_inputs
session = ExportSession(
model=exported_program,
export_recipe=self.recipe,
)
self.assertEqual(session._input_model_type, "ExportedProgram")
# Verify default pipeline skips quantization and torch export stages
pipeline = session._get_default_pipeline()
self.assertNotIn(StageType.SOURCE_TRANSFORM, pipeline)
self.assertNotIn(StageType.QUANTIZE, pipeline)
self.assertNotIn(StageType.TORCH_EXPORT, pipeline)
self.assertIn(StageType.TO_EDGE_TRANSFORM_AND_LOWER, pipeline)
self.assertIn(StageType.TO_EXECUTORCH, pipeline)
def test_dict_nn_module_input_type_detection(self) -> None:
"""Test that Dict[str, nn.Module] input is detected correctly."""
model_dict = {
"forward": self.model,
"method2": SimpleTestModel(),
}
inputs_dict = {
"forward": [self.example_inputs],
"method2": [(torch.randn(1, 10),)],
}
session = ExportSession(
model=model_dict,
example_inputs=inputs_dict,
export_recipe=self.recipe,
)
# Should detect type based on first value
self.assertEqual(session._input_model_type, "nn.Module")
def test_dict_graph_module_input_type_detection(self) -> None:
"""Test that Dict[str, GraphModule] input is detected correctly."""
graph_module1 = torch.fx.symbolic_trace(self.model)
graph_module2 = torch.fx.symbolic_trace(SimpleTestModel())
model_dict = {
"forward": graph_module1,
"method2": graph_module2,
}
inputs_dict = {
"forward": [self.example_inputs],
"method2": [(torch.randn(1, 10),)],
}
session = ExportSession(
model=model_dict,
example_inputs=inputs_dict,
export_recipe=self.recipe,
)
# Should detect GraphModule type
self.assertEqual(session._input_model_type, "GraphModule")
# Verify pipeline skips quantization
pipeline = session._get_default_pipeline()
self.assertNotIn(StageType.QUANTIZE, pipeline)
def test_dict_exported_program_input_type_detection(self) -> None:
"""Test that Dict[str, ExportedProgram] input is detected correctly."""
ep1 = torch.export.export(self.model, self.example_inputs)
ep2 = torch.export.export(SimpleTestModel(), (torch.randn(1, 10),))
model_dict = {
"forward": ep1,
"method2": ep2,
}
session = ExportSession(
model=model_dict,
export_recipe=self.recipe,
)
# Should detect ExportedProgram type
self.assertEqual(session._input_model_type, "ExportedProgram")
# Verify pipeline skips export stages
pipeline = session._get_default_pipeline()
self.assertNotIn(StageType.TORCH_EXPORT, pipeline)
def test_example_inputs_required_for_nn_module(self) -> None:
"""Test that example_inputs are required for nn.Module."""
with self.assertRaises(ValueError) as cm:
ExportSession(
model=self.model,
export_recipe=self.recipe,
)
self.assertIn("example_inputs are required", str(cm.exception))
self.assertIn("nn.Module", str(cm.exception))
def test_example_inputs_required_for_graph_module(self) -> None:
"""Test that example_inputs are required for GraphModule."""
graph_module = torch.fx.symbolic_trace(self.model)
with self.assertRaises(ValueError) as cm:
ExportSession(
model=graph_module,
export_recipe=self.recipe,
)
self.assertIn("example_inputs are required", str(cm.exception))
self.assertIn("GraphModule", str(cm.exception))
def test_example_inputs_optional_for_exported_program(self) -> None:
"""Test that example_inputs are optional for ExportedProgram."""
exported_program = torch.export.export(self.model, self.example_inputs)
# Should not raise
session = ExportSession(
model=exported_program,
export_recipe=self.recipe,
)
self.assertEqual(session._input_model_type, "ExportedProgram")
def test_validation_graph_module_cannot_run_quantization(self) -> None:
"""Test that GraphModule input cannot run quantization stages."""
graph_module = torch.fx.symbolic_trace(self.model)
# Try to force quantization stages
recipe = ExportRecipe(
pipeline_stages=[
StageType.QUANTIZE,
StageType.TORCH_EXPORT,
StageType.TO_EDGE_TRANSFORM_AND_LOWER,
StageType.TO_EXECUTORCH,
]
)
session = ExportSession(
model=graph_module,
example_inputs=[self.example_inputs],
export_recipe=recipe,
)
with self.assertRaises(ValueError) as cm:
session.export()
self.assertIn("Cannot run", str(cm.exception))
self.assertIn("stage(s)", str(cm.exception))
self.assertIn("QUANTIZE", str(cm.exception))
self.assertIn("GraphModule", str(cm.exception))
def test_validation_graph_module_cannot_run_source_transform(self) -> None:
"""Test that GraphModule input cannot run source transform stage."""
graph_module = torch.fx.symbolic_trace(self.model)
# Try to force source transform stage
recipe = ExportRecipe(
pipeline_stages=[
StageType.SOURCE_TRANSFORM,
StageType.TORCH_EXPORT,
StageType.TO_EDGE_TRANSFORM_AND_LOWER,
StageType.TO_EXECUTORCH,
]
)
session = ExportSession(
model=graph_module,
example_inputs=[self.example_inputs],
export_recipe=recipe,
)
with self.assertRaises(ValueError) as cm:
session.export()
self.assertIn("Cannot run", str(cm.exception))
self.assertIn("stage(s)", str(cm.exception))
self.assertIn("SOURCE_TRANSFORM", str(cm.exception))
self.assertIn("GraphModule", str(cm.exception))
def test_validation_exported_program_cannot_run_torch_export(self) -> None:
"""Test that ExportedProgram input cannot run torch export stage."""
exported_program = torch.export.export(self.model, self.example_inputs)
# Try to force torch export stage
recipe = ExportRecipe(
pipeline_stages=[
StageType.TORCH_EXPORT,
StageType.TO_EDGE_TRANSFORM_AND_LOWER,
StageType.TO_EXECUTORCH,
]
)
session = ExportSession(
model=exported_program,
export_recipe=recipe,
)
with self.assertRaises(ValueError) as cm:
session.export()
self.assertIn("Cannot run", str(cm.exception))
self.assertIn("stage(s)", str(cm.exception))
self.assertIn("TORCH_EXPORT", str(cm.exception))
self.assertIn("ExportedProgram", str(cm.exception))
def test_validation_exported_program_cannot_run_quantization(self) -> None:
"""Test that ExportedProgram input cannot run quantization stages."""
exported_program = torch.export.export(self.model, self.example_inputs)
# Try to force quantization stages
recipe = ExportRecipe(
pipeline_stages=[
StageType.QUANTIZE,
StageType.TO_EDGE_TRANSFORM_AND_LOWER,
StageType.TO_EXECUTORCH,
]
)
session = ExportSession(
model=exported_program,
export_recipe=recipe,
)
with self.assertRaises(ValueError) as cm:
session.export()
self.assertIn("Cannot run", str(cm.exception))
self.assertIn("stage(s)", str(cm.exception))
self.assertIn("QUANTIZE", str(cm.exception))
self.assertIn("ExportedProgram", str(cm.exception))
def test_graph_module_valid_pipeline(self) -> None:
"""Test valid pipeline for GraphModule input."""
graph_module = torch.fx.symbolic_trace(self.model)
# Valid pipeline starting from torch export
recipe = ExportRecipe(
pipeline_stages=[
StageType.TORCH_EXPORT,
StageType.TO_EDGE_TRANSFORM_AND_LOWER,
StageType.TO_EXECUTORCH,
]
)
session = ExportSession(
model=graph_module,
example_inputs=[self.example_inputs],
export_recipe=recipe,
)
# Should not raise during validation
session._validate_pipeline_sequence(recipe.pipeline_stages)
def test_exported_program_valid_pipeline(self) -> None:
"""Test valid pipeline for ExportedProgram input."""
exported_program = torch.export.export(self.model, self.example_inputs)
# Valid pipeline starting from edge stages
recipe = ExportRecipe(
pipeline_stages=[
StageType.TO_EDGE_TRANSFORM_AND_LOWER,
StageType.TO_EXECUTORCH,
]
)
session = ExportSession(
model=exported_program,
export_recipe=recipe,
)
# Should not raise during validation
session._validate_pipeline_sequence(recipe.pipeline_stages)
class TestIntermediateStateGetters(unittest.TestCase):
"""Test convenience getters for intermediate pipeline states."""
def setUp(self) -> None:
self.model = SimpleTestModel()
self.example_inputs = [(torch.randn(2, 10),)]
def test_get_exported_program_after_torch_export(self) -> None:
"""Test that get_exported_program works after torch export stage."""
recipe = ExportRecipe(
name="test",
pipeline_stages=[
StageType.TORCH_EXPORT,
StageType.TO_EDGE_TRANSFORM_AND_LOWER,
StageType.TO_EXECUTORCH,
],
)
session = ExportSession(
model=self.model,
example_inputs=self.example_inputs,
export_recipe=recipe,
)
session.export()
exported_program = session.get_exported_program()
self.assertIsNotNone(exported_program)
self.assertIsInstance(exported_program, torch.export.ExportedProgram)
def test_get_exported_program_before_export_fails(self) -> None:
"""Test that get_exported_program fails before torch export stage."""
recipe = ExportRecipe(name="test")
session = ExportSession(
model=self.model,
example_inputs=self.example_inputs,
export_recipe=recipe,
)
with self.assertRaises(RuntimeError) as cm:
session.get_exported_program()
self.assertIn("Exported program is not available", str(cm.exception))
def test_get_exported_program_invalid_method_name(self) -> None:
"""Test that get_exported_program fails with invalid method name."""
recipe = ExportRecipe(name="test")
session = ExportSession(
model=self.model,
example_inputs=self.example_inputs,
export_recipe=recipe,
)
session.export()
with self.assertRaises(KeyError) as cm:
session.get_exported_program("nonexistent_method")
self.assertIn("Method name 'nonexistent_method' not found", str(cm.exception))
def test_get_exported_program_multi_method(self) -> None:
"""Test get_exported_program with multi-method model."""
model_dict = {
"forward": self.model,
"inference": SimpleTestModel(),
}
inputs_dict = {
"forward": self.example_inputs,
"inference": [(torch.randn(1, 10),)],
}
recipe = ExportRecipe(name="multi_method_test")
session = ExportSession(
model=model_dict,
example_inputs=inputs_dict,
export_recipe=recipe,
)
session.export()
forward_ep = session.get_exported_program("forward")
inference_ep = session.get_exported_program("inference")
self.assertIsNotNone(forward_ep)
self.assertIsNotNone(inference_ep)
self.assertIsInstance(forward_ep, torch.export.ExportedProgram)
self.assertIsInstance(inference_ep, torch.export.ExportedProgram)
def test_get_edge_program_manager_with_transform_and_lower(self) -> None:
"""Test get_edge_program_manager with TO_EDGE_TRANSFORM_AND_LOWER stage."""
recipe = ExportRecipe(
name="test",
pipeline_stages=[
StageType.TORCH_EXPORT,
StageType.TO_EDGE_TRANSFORM_AND_LOWER,
StageType.TO_EXECUTORCH,
],
)
session = ExportSession(
model=self.model,
example_inputs=self.example_inputs,
export_recipe=recipe,
)
session.export()
edge_manager = session.get_edge_program_manager()
self.assertIsNotNone(edge_manager)
def test_get_edge_program_manager_with_separate_stages(self) -> None:
"""Test get_edge_program_manager with separate TO_EDGE and TO_BACKEND stages."""
recipe = ExportRecipe(
name="test",
pipeline_stages=[
StageType.TORCH_EXPORT,
StageType.TO_EDGE,
StageType.TO_BACKEND,
StageType.TO_EXECUTORCH,
],
)
session = ExportSession(
model=self.model,
example_inputs=self.example_inputs,
export_recipe=recipe,
)
session.export()
edge_manager = session.get_edge_program_manager()
self.assertIsNotNone(edge_manager)
def test_get_edge_program_manager_before_edge_stage_fails(self) -> None:
"""Test that get_edge_program_manager fails before edge stages."""
recipe = ExportRecipe(
name="test",
pipeline_stages=[StageType.TORCH_EXPORT],
)
session = ExportSession(
model=self.model,
example_inputs=self.example_inputs,
export_recipe=recipe,
)
session.export()
with self.assertRaises(RuntimeError) as cm:
session.get_edge_program_manager()
self.assertIn("Edge program manager is not available", str(cm.exception))