ai-edge-torch-nightly 0.2.0.dev20240617__py3-none-any.whl → 0.2.0.dev20240619__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of ai-edge-torch-nightly might be problematic. Click here for more details.

@@ -13,4 +13,5 @@
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
15
 
16
+ from .culprit import _search_model
16
17
  from .culprit import find_culprits
@@ -21,7 +21,7 @@ import io
21
21
  import operator
22
22
  import os
23
23
  import sys
24
- from typing import Any, Generator, List, Optional, Tuple
24
+ from typing import Any, Callable, Generator, List, Optional, Tuple, Union
25
25
 
26
26
  from functorch.compile import minifier as fx_minifier
27
27
  import torch
@@ -85,10 +85,9 @@ def _tensor_to_buffer(t: torch.Tensor):
85
85
 
86
86
 
87
87
  @dataclasses.dataclass
88
- class Culprit:
88
+ class SearchResult:
89
89
  graph_module: torch.fx.GraphModule
90
90
  inputs: Tuple[Any]
91
- _runtime_errors: bool
92
91
 
93
92
  @property
94
93
  def graph(self) -> torch.fx.Graph:
@@ -98,6 +97,11 @@ class Culprit:
98
97
  def graph(self, fx_g: torch.fx.Graph):
99
98
  self.graph_module.graph = fx_g
100
99
 
100
+
101
+ @dataclasses.dataclass
102
+ class Culprit(SearchResult):
103
+ _runtime_errors: bool
104
+
101
105
  @property
102
106
  def stack_traces(self) -> List[str]:
103
107
  stack_traces = set()
@@ -342,42 +346,42 @@ def _fx_minifier_checker(fx_gm, inputs, runtime_errors=False):
342
346
  return False
343
347
 
344
348
 
345
- def find_culprits(
346
- torch_model: torch.nn.Module,
347
- args: Tuple[Any],
348
- max_granularity: Optional[int] = None,
349
- runtime_errors: bool = False,
349
+ def _search_model(
350
+ predicate_f: Callable[[torch.fx.GraphModule, List[Any]], bool],
351
+ model: Union[torch.export.ExportedProgram, torch.nn.Module],
352
+ export_args: Tuple[Any] = None,
350
353
  *,
354
+ max_granularity: Optional[int] = None,
351
355
  enable_fx_minifier_logging: bool = False,
352
- ) -> Generator[Culprit, None, None]:
353
- """Finds culprits in the AI Edge Torch model conversion.
356
+ ) -> Generator[SearchResult, None, None]:
357
+ """Finds subgraphs in the torch model that satify a certain predicate function provided by the users.
354
358
 
355
359
  Args:
356
- torch_model: model to export and save
357
- args: A set of args to trace the model with, i.e.
358
- torch_model(*args) must run
360
+ predicate_f: a predicate function the users specify.
361
+ It takes a FX (sub)graph and the inputs to this graph,
362
+ return True if the graph satisfies the predicate,
363
+ return False otherwise.
364
+ model: model in which to search subgraph.
365
+ export_args: A set of args to trace the model with,
366
+ i.e. model(*args) must run.
359
367
  max_granularity - FX minifier arg. The maximum granularity (number of nodes)
360
368
  in the returned ATen FX subgraph of the culprit.
361
- runtime_errors: If true, find culprits for Python runtime errors
362
- with converted model.
363
- enable_fx_minifier_logging: If true, allows the underlying FX minifier to log
364
- the progress.
369
+ enable_fx_minifier_logging: If true, allows the underlying FX minifier to log the progress.
365
370
  """
366
371
 
367
- try:
368
- ep = torch.export.export(torch_model, args)
369
- except Exception as err:
370
- raise ValueError(
371
- "Your model is not exportable by torch.export.export. Please modify your model to be torch-exportable first."
372
- ) from err
372
+ if isinstance(model, torch.nn.Module):
373
+ try:
374
+ ep = torch.export.export(model, export_args)
375
+ except Exception as err:
376
+ raise ValueError(
377
+ "Your model is not exportable by torch.export.export. Please modify your model to be torch-exportable first."
378
+ ) from err
379
+ else:
380
+ ep = model
373
381
 
374
382
  fx_gm, fx_inputs = utils.exported_program_to_fx_graph_module_and_inputs(ep)
375
383
  fx_gm = _normalize_getitem_nodes(fx_gm)
376
384
 
377
- fx_minifier_checker = functools.partial(
378
- _fx_minifier_checker, runtime_errors=runtime_errors
379
- )
380
-
381
385
  # HACK: temporarily disable XLA_HLO_DEBUG so that fx_minifier won't dump
382
386
  # intermediate stablehlo files to storage.
383
387
  # https://github.com/pytorch/pytorch/blob/main/torch/_functorch/fx_minifier.py#L440
@@ -405,13 +409,13 @@ def find_culprits(
405
409
  raw_min_fx_gm, raw_min_inputs = fx_minifier(
406
410
  fx_gm,
407
411
  fx_inputs,
408
- fx_minifier_checker,
412
+ predicate_f,
409
413
  max_granularity=max_granularity,
410
414
  )
411
415
 
412
416
  min_fx_gm, min_inputs = _normalize_minified_fx_gm(raw_min_fx_gm, raw_min_inputs)
413
417
  found_culprits_num += 1
414
- yield Culprit(min_fx_gm, min_inputs, _runtime_errors=runtime_errors)
418
+ yield SearchResult(min_fx_gm, min_inputs)
415
419
 
416
420
  fx_gm, fx_inputs = _erase_sub_gm_from_gm(
417
421
  fx_gm, fx_inputs, raw_min_fx_gm, raw_min_inputs
@@ -421,3 +425,40 @@ def find_culprits(
421
425
  if str(e) == "Input graph did not fail the tester" and found_culprits_num > 0:
422
426
  break
423
427
  raise e
428
+
429
+
430
+ def find_culprits(
431
+ torch_model: torch.nn.Module,
432
+ args: Tuple[Any],
433
+ max_granularity: Optional[int] = None,
434
+ runtime_errors: bool = False,
435
+ *,
436
+ enable_fx_minifier_logging: bool = False,
437
+ ) -> Generator[Culprit, None, None]:
438
+ """Finds culprits in the AI Edge Torch model conversion.
439
+
440
+ Args:
441
+ torch_model: model to export and save
442
+ args: A set of args to trace the model with, i.e.
443
+ torch_model(*args) must run
444
+ max_granularity - FX minifier arg. The maximum granularity (number of nodes)
445
+ in the returned ATen FX subgraph of the culprit.
446
+ runtime_errors: If true, find culprits for Python runtime errors
447
+ with converted model.
448
+ enable_fx_minifier_logging: If true, allows the underlying FX minifier to log the progress.
449
+ """
450
+
451
+ fx_minifier_checker = functools.partial(
452
+ _fx_minifier_checker, runtime_errors=runtime_errors
453
+ )
454
+
455
+ for search_result in _search_model(
456
+ fx_minifier_checker,
457
+ torch_model,
458
+ args,
459
+ max_granularity=max_granularity,
460
+ enable_fx_minifier_logging=enable_fx_minifier_logging,
461
+ ):
462
+ yield Culprit(
463
+ search_result.graph_module, search_result.inputs, _runtime_errors=runtime_errors
464
+ )
@@ -0,0 +1,50 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+
17
+ import unittest
18
+
19
+ import torch
20
+
21
+ from ai_edge_torch.debug import _search_model
22
+
23
+
24
+ class TestSearchModel(unittest.TestCase):
25
+
26
+ def test_search_model_with_ops(self):
27
+ class MultipleOpsModel(torch.nn.Module):
28
+
29
+ def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
30
+ sub_0 = x - 1
31
+ add_0 = y + 1
32
+ mul_0 = x * y
33
+ add_1 = sub_0 + add_0
34
+ mul_1 = add_0 * mul_0
35
+ sub_1 = add_1 - mul_1
36
+ return sub_1
37
+
38
+ model = MultipleOpsModel().eval()
39
+ args = (torch.rand(10), torch.rand(10))
40
+
41
+ def find_subgraph_with_sub(fx_gm, inputs):
42
+ return torch.ops.aten.sub.Tensor in [n.target for n in fx_gm.graph.nodes]
43
+
44
+ results = list(_search_model(find_subgraph_with_sub, model, args))
45
+ self.assertEqual(len(results), 2)
46
+ self.assertIn(torch.ops.aten.sub.Tensor, [n.target for n in results[0].graph.nodes])
47
+
48
+
49
+ if __name__ == "__main__":
50
+ unittest.main()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ai-edge-torch-nightly
3
- Version: 0.2.0.dev20240617
3
+ Version: 0.2.0.dev20240619
4
4
  Summary: Supporting PyTorch models with the Google AI Edge TFLite runtime.
5
5
  Home-page: https://github.com/google-ai-edge/ai-edge-torch
6
6
  Keywords: On-Device ML,AI,Google,TFLite,PyTorch,LLMs,GenAI
@@ -24,11 +24,12 @@ ai_edge_torch/convert/test/__init__.py,sha256=hHLluseD2R0Hh4W6XZRIXY_dRQeYudjsrK
24
24
  ai_edge_torch/convert/test/test_convert.py,sha256=2qPmmGqnfV_o1gfsSdjGq3-JR1b323ligiy5MdAv9NA,8021
25
25
  ai_edge_torch/convert/test/test_convert_composites.py,sha256=_Ojc-H6GOS5s8ek3_8eRBL_AiCs-k3srziPJ2R4Ulrg,7255
26
26
  ai_edge_torch/convert/test/test_convert_multisig.py,sha256=kMaGnHe9ylfyU68qCifYcaGwJqyejKz--QQt9jS2oUA,4537
27
- ai_edge_torch/debug/__init__.py,sha256=TKvmnjVk3asvYcVh6C-LPr6srgAF_nppSAupWEXqwPY,707
28
- ai_edge_torch/debug/culprit.py,sha256=vklaxBUfINdo44OsH7csILK70N41gEThCGchGEfbTZw,12789
27
+ ai_edge_torch/debug/__init__.py,sha256=N05Mmvi41KgSuK0JhuMejERESgP8QekiGdp9_PEyuKU,742
28
+ ai_edge_torch/debug/culprit.py,sha256=urtCKPXORPvn6oyDxDSCSjgvngUnjjcsUMwAOeIl15E,14236
29
29
  ai_edge_torch/debug/utils.py,sha256=hjVmQVVl1dKxEF0D6KB4a3ouQ3wBkTsebOX2YsUObZM,1430
30
30
  ai_edge_torch/debug/test/__init__.py,sha256=hHLluseD2R0Hh4W6XZRIXY_dRQeYudjsrKGf6LZz65g,671
31
31
  ai_edge_torch/debug/test/test_culprit.py,sha256=9An_n9p_RWTAYdHYTCO-__EJlbnjclCDo8tDhOzMlwk,3731
32
+ ai_edge_torch/debug/test/test_search_model.py,sha256=0guAEon5cvwBpPXk6J0wVOKj7TXMDaiuomEEQmHgO5o,1590
32
33
  ai_edge_torch/experimental/__init__.py,sha256=hHLluseD2R0Hh4W6XZRIXY_dRQeYudjsrKGf6LZz65g,671
33
34
  ai_edge_torch/generative/__init__.py,sha256=hHLluseD2R0Hh4W6XZRIXY_dRQeYudjsrKGf6LZz65g,671
34
35
  ai_edge_torch/generative/examples/__init__.py,sha256=hHLluseD2R0Hh4W6XZRIXY_dRQeYudjsrKGf6LZz65g,671
@@ -109,8 +110,8 @@ ai_edge_torch/quantize/quant_config.py,sha256=eO9Ra160ITjQSyRBEGy6nNIVH3gYacSWDd
109
110
  ai_edge_torch/testing/__init__.py,sha256=hHLluseD2R0Hh4W6XZRIXY_dRQeYudjsrKGf6LZz65g,671
110
111
  ai_edge_torch/testing/model_coverage/__init__.py,sha256=5P8J6Zk5YYtDvTBucFvB9NGSRI7Gw_24WnrbhXgycEE,765
111
112
  ai_edge_torch/testing/model_coverage/model_coverage.py,sha256=EIyKz-HY70DguWuSrJal8LpYXQ5ZSEUf3ZrVl7jikFM,4286
112
- ai_edge_torch_nightly-0.2.0.dev20240617.dist-info/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
113
- ai_edge_torch_nightly-0.2.0.dev20240617.dist-info/METADATA,sha256=Z9rUO2CabVbBpydpRk8OxNlwK4yznGCb2QHGlJhqRsM,1748
114
- ai_edge_torch_nightly-0.2.0.dev20240617.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
115
- ai_edge_torch_nightly-0.2.0.dev20240617.dist-info/top_level.txt,sha256=5KXRaF2hwkApYxf7Y8y_tVb9aulGTlbOoNdbx1aKRkE,14
116
- ai_edge_torch_nightly-0.2.0.dev20240617.dist-info/RECORD,,
113
+ ai_edge_torch_nightly-0.2.0.dev20240619.dist-info/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
114
+ ai_edge_torch_nightly-0.2.0.dev20240619.dist-info/METADATA,sha256=F-t0dJdKRPuHzfMRHK0trNEa5EFlL4c6JjFKXhvKmU4,1748
115
+ ai_edge_torch_nightly-0.2.0.dev20240619.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
116
+ ai_edge_torch_nightly-0.2.0.dev20240619.dist-info/top_level.txt,sha256=5KXRaF2hwkApYxf7Y8y_tVb9aulGTlbOoNdbx1aKRkE,14
117
+ ai_edge_torch_nightly-0.2.0.dev20240619.dist-info/RECORD,,