ADAPT-Chase commited on
Commit
3379dc5
·
verified ·
1 Parent(s): 341e2e4

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/_remove_auto_functionalized_pass.cpython-312.pyc +0 -0
  2. tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/_remove_effect_tokens_pass.cpython-312.pyc +0 -0
  3. tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/_safeguard.cpython-312.pyc +0 -0
  4. tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/_swap.cpython-312.pyc +0 -0
  5. tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/_trace.cpython-312.pyc +0 -0
  6. tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/_tree_utils.cpython-312.pyc +0 -0
  7. tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/_unlift.cpython-312.pyc +0 -0
  8. tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/custom_obj.cpython-312.pyc +0 -0
  9. tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/custom_ops.cpython-312.pyc +0 -0
  10. tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/decomp_utils.cpython-312.pyc +0 -0
  11. tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/dynamic_shapes.cpython-312.pyc +0 -0
  12. tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/exported_program.cpython-312.pyc +0 -0
  13. tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/graph_signature.cpython-312.pyc +0 -0
  14. tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/unflatten.cpython-312.pyc +0 -0
  15. tool_server/.venv/lib/python3.12/site-packages/torch/export/experimental/__pycache__/__init__.cpython-312.pyc +0 -0
  16. tool_server/.venv/lib/python3.12/site-packages/torch/export/passes/__pycache__/__init__.cpython-312.pyc +0 -0
  17. tool_server/.venv/lib/python3.12/site-packages/torch/fft/__pycache__/__init__.cpython-312.pyc +0 -0
  18. tool_server/.venv/lib/python3.12/site-packages/torch/func/__pycache__/__init__.cpython-312.pyc +0 -0
  19. tool_server/.venv/lib/python3.12/site-packages/torch/futures/__pycache__/__init__.cpython-312.pyc +0 -0
  20. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/__init__.cpython-312.pyc +0 -0
  21. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/_compatibility.cpython-312.pyc +0 -0
  22. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/_graph_pickler.cpython-312.pyc +0 -0
  23. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/_lazy_graph_module.cpython-312.pyc +0 -0
  24. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/_pytree.cpython-312.pyc +0 -0
  25. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/_symbolic_trace.cpython-312.pyc +0 -0
  26. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/_utils.cpython-312.pyc +0 -0
  27. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/annotate.cpython-312.pyc +0 -0
  28. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/config.cpython-312.pyc +0 -0
  29. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/graph.cpython-312.pyc +0 -0
  30. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/graph_module.cpython-312.pyc +0 -0
  31. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/immutable_collections.cpython-312.pyc +0 -0
  32. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/interpreter.cpython-312.pyc +0 -0
  33. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/node.cpython-312.pyc +0 -0
  34. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/operator_schemas.cpython-312.pyc +0 -0
  35. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/proxy.cpython-312.pyc +0 -0
  36. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/subgraph_rewriter.cpython-312.pyc +0 -0
  37. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/tensor_type.cpython-312.pyc +0 -0
  38. tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/traceback.cpython-312.pyc +0 -0
  39. tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/__init__.py +0 -0
  40. tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/__pycache__/__init__.cpython-312.pyc +0 -0
  41. tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/__pycache__/_backward_state.cpython-312.pyc +0 -0
  42. tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/__pycache__/_config.cpython-312.pyc +0 -0
  43. tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/__pycache__/_constant_symnode.cpython-312.pyc +0 -0
  44. tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/__pycache__/_dynamism.cpython-312.pyc +0 -0
  45. tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/_backward_state.py +27 -0
  46. tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/_config.py +103 -0
  47. tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/_constant_symnode.py +69 -0
  48. tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/_dynamism.py +111 -0
  49. tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/accelerator_partitioner.py +1080 -0
  50. tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/const_fold.py +304 -0
tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/_remove_auto_functionalized_pass.cpython-312.pyc ADDED
Binary file (2.95 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/_remove_effect_tokens_pass.cpython-312.pyc ADDED
Binary file (7.78 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/_safeguard.cpython-312.pyc ADDED
Binary file (2.19 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/_swap.cpython-312.pyc ADDED
Binary file (19.8 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/_trace.cpython-312.pyc ADDED
Binary file (88.9 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/_tree_utils.cpython-312.pyc ADDED
Binary file (2.97 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/_unlift.cpython-312.pyc ADDED
Binary file (17.8 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/custom_obj.cpython-312.pyc ADDED
Binary file (634 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/custom_ops.cpython-312.pyc ADDED
Binary file (1.29 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/decomp_utils.cpython-312.pyc ADDED
Binary file (7.9 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/dynamic_shapes.cpython-312.pyc ADDED
Binary file (49.5 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/exported_program.cpython-312.pyc ADDED
Binary file (67.4 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/graph_signature.cpython-312.pyc ADDED
Binary file (31.6 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/export/__pycache__/unflatten.cpython-312.pyc ADDED
Binary file (74.4 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/export/experimental/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (4.15 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/export/passes/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (3.68 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fft/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (56.8 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/func/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (780 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/futures/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (16.9 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (4.35 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/_compatibility.cpython-312.pyc ADDED
Binary file (1.84 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/_graph_pickler.cpython-312.pyc ADDED
Binary file (30.7 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/_lazy_graph_module.cpython-312.pyc ADDED
Binary file (8.24 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/_pytree.cpython-312.pyc ADDED
Binary file (4.88 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/_symbolic_trace.cpython-312.pyc ADDED
Binary file (55.3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/_utils.cpython-312.pyc ADDED
Binary file (2.94 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/annotate.cpython-312.pyc ADDED
Binary file (1.51 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/config.cpython-312.pyc ADDED
Binary file (235 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/graph.cpython-312.pyc ADDED
Binary file (87.5 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/graph_module.cpython-312.pyc ADDED
Binary file (44.5 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/immutable_collections.cpython-312.pyc ADDED
Binary file (4.73 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/interpreter.cpython-312.pyc ADDED
Binary file (27.8 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/node.cpython-312.pyc ADDED
Binary file (40.1 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/operator_schemas.cpython-312.pyc ADDED
Binary file (22 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/proxy.cpython-312.pyc ADDED
Binary file (34.4 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/subgraph_rewriter.cpython-312.pyc ADDED
Binary file (15.2 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/tensor_type.cpython-312.pyc ADDED
Binary file (5.18 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/__pycache__/traceback.cpython-312.pyc ADDED
Binary file (9.41 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/__init__.py ADDED
File without changes
tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (191 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/__pycache__/_backward_state.cpython-312.pyc ADDED
Binary file (1.42 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/__pycache__/_config.cpython-312.pyc ADDED
Binary file (2.11 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/__pycache__/_constant_symnode.cpython-312.pyc ADDED
Binary file (3.86 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/__pycache__/_dynamism.cpython-312.pyc ADDED
Binary file (6.05 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/_backward_state.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.fx
2
+
3
+
4
+ class BackwardState:
5
+ """
6
+ BackwardState is used to pass Python hooks from the forwards pass
7
+ into the backwards pass in Dynamo+Compiled Autograd.
8
+
9
+ It is created by TorchDynamo and has special handling there.
10
+ Dynamo will pass an empty BackwardState to the forwards, then populate
11
+ members on it (via setattr) only after the forwards graph is finished.
12
+ Later on, in CompileAutograd we will inline and add the needed guards
13
+ on the BackwardState.
14
+
15
+ BackwardState is identified and has special handling in AOTAutograd.
16
+ During AOTAutograd:
17
+ 1) BackwardState is an input to the forwards graph
18
+ 2) It must only be used in the backwards
19
+ 3) It will be empty in the forwards
20
+ 4) In the forwards we add a wrapper to save it
21
+ 5) In the backwards it becomes an input
22
+ 6) There can only be one per graph
23
+
24
+ BackwardState requires CompiledAutograd.
25
+ """
26
+
27
+ proxy: torch.fx.Proxy
tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/_config.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from typing import Optional
4
+
5
+
6
+ # [@compile_ignored: debug] Fails hard instead of graph breaking on guard on data dependent errors.
7
+ no_data_dependent_graph_break = (
8
+ os.environ.get("TORCHDYNAMO_NO_DATA_DEPENDENT_GRAPH_BREAK", "0") == "1"
9
+ )
10
+ # [@compile_ignored: debug] Uses z3 for validating the guard optimizations transformations.
11
+ translation_validation = (
12
+ os.environ.get("TORCHDYNAMO_TRANSLATION_VALIDATION", "0") == "1"
13
+ )
14
+ # Timeout (in milliseconds) for z3 finding a solution.
15
+ # [@compile_ignored: debug]
16
+ translation_validation_timeout = int(
17
+ os.environ.get("TORCHDYNAMO_TRANSLATION_VALIDATION_TIMEOUT", "600000")
18
+ )
19
+ # Disables bisection for translation validation.
20
+ #
21
+ # Translation validation bisection is enabled by default, if translation validation
22
+ # is also enabled. This should help finding guard simplification issues. However,
23
+ # since validation uses Z3 for bisecting, it might take a lot of time.
24
+ #
25
+ # Set this configuration option so as to avoid bisecting.
26
+ # [@compile_ignored: debug]
27
+ translation_validation_no_bisect = (
28
+ os.environ.get("TORCHDYNAMO_TRANSLATION_NO_BISECT", "0") == "1"
29
+ )
30
+ # Checks whether replaying ShapeEnv events on a freshly constructed one yields
31
+ # the a ShapeEnv with the same state. This should be used only in testing.
32
+ check_shape_env_recorded_events = False
33
+
34
+ # TODO: Perhaps consider allowing unions for the configs below (so you can hit
35
+ # multiple reps at the same time)
36
+
37
+ # Give extended debug information if the string representation of a guard
38
+ # matches this. For example, set this to "Ne(s0, 10)" and whenever we issue
39
+ # this guard, we will generate full Python and C++ backtrace
40
+ # [@compile_ignored: debug]
41
+ extended_debug_guard_added = os.environ.get(
42
+ "TORCHDYNAMO_EXTENDED_DEBUG_GUARD_ADDED", None
43
+ )
44
+
45
+ # Give extended debug information when a particular symbol is allocated. For
46
+ # example, set this to "u2" and whenever we create this symbol, we will
47
+ # generate full Python and C++ backtrace
48
+ # [@compile_ignored: debug]
49
+ extended_debug_create_symbol = os.environ.get(
50
+ "TORCHDYNAMO_EXTENDED_DEBUG_CREATE_SYMBOL", None
51
+ )
52
+
53
+ # Give extended debug information (C++ backtrace) for all extended debug
54
+ # settings as well as errors. The C++ backtrace is slow and very spammy so we
55
+ # don't include it by default even when you're requesting extended debug.
56
+ # [@compile_ignored: debug]
57
+ extended_debug_cpp = os.environ.get("TORCHDYNAMO_EXTENDED_DEBUG_CPP", "") != ""
58
+
59
+ # Give extended debug information (line of code) when a torch function
60
+ # is called during export. This is useful for showing progress and detecting
61
+ # where export might be stuck. Currently only works for strict=False.
62
+ # [@compile_ignored: debug]
63
+ extended_debug_current_loc = (
64
+ os.environ.get("TORCHEXPORT_EXTENDED_DEBUG_CURRENT_LOC", "0") == "1"
65
+ )
66
+
67
+ # [@compile_ignored: debug] Show a warning for every specialization
68
+ print_specializations = False
69
+
70
+ # wraps (un)equalities with 'Not' class after recording the correct expression
71
+ # in the FX graph. This should incorrectly construct the divisible and replacement
72
+ # lists, and incorrectly issue guards.
73
+ inject_EVALUATE_EXPR_flip_equality_TESTING_ONLY = False
74
+
75
+ # [@compile_ignored: debug] Validate that ShapeEnv's version key is updated correctly
76
+ validate_shape_env_version_key = False
77
+
78
+ # If we produce more than this many guards on a symbol, force the symbol to
79
+ # get specialized and bail out if this many guards mention this particular
80
+ # symbol. This may be slightly more aggressive than the true number of guards
81
+ # issued (as we test if we've hit the limit on-the-fly, whereas we may
82
+ # do further simplifications at final guard issuance time that make guards
83
+ # irrelevant.)
84
+ symbol_guard_limit_before_specialize: Optional[int] = None
85
+
86
+ # This flag changes whether we should use the same symbolic variable to represent input sizes that are the same.
87
+ use_duck_shape = True
88
+
89
+ # Controls the registration of torch.nonzero() on the meta device.
90
+ # When True, nonzero returns a tensor with shape (self.numel(), self.dim())
91
+ # assuming all elements are none-zero.
92
+ # Default is False to prevent unintended registration. Set to True to enable.
93
+ meta_nonzero_assume_all_nonzero = False
94
+
95
+ # Applies size-oblivious reasoning to backed symbols. This allocates a [0, inf] range for backed size symbols,
96
+ # and relies on size-oblivious semantics to avoid 0/1 specialization guards by marking them size-like.
97
+ # Currently an experimental option for export.
98
+ backed_size_oblivious = False
99
+
100
+ from torch.utils._config_module import install_config_module
101
+
102
+
103
+ install_config_module(sys.modules[__name__])
tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/_constant_symnode.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import * # noqa: F403
2
+
3
+
4
+ # Python version of c10/core/ConstantSymNodeImpl.cpp
5
+ # This needs to exist because the Python version of nested int is not compatible
6
+ # with the C++ version of constant symnode.
7
+ class ConstantIntNode:
8
+ def __init__(self, val: int):
9
+ self.val = val
10
+
11
+ def is_constant(self) -> bool:
12
+ return True
13
+
14
+ def maybe_as_int(self) -> int:
15
+ return self.val
16
+
17
+ def is_int(self) -> bool:
18
+ return True
19
+
20
+ def is_float(self) -> bool:
21
+ return False
22
+
23
+ def is_bool(self) -> bool:
24
+ return False
25
+
26
+ def is_nested_int(self) -> bool:
27
+ return False
28
+
29
+ def clone(self) -> "ConstantIntNode":
30
+ return self
31
+
32
+ def _str(self) -> str:
33
+ return str(self.val)
34
+
35
+ def __str__(self) -> str:
36
+ return self._str()
37
+
38
+ def __repr__(self) -> str:
39
+ return self._str()
40
+
41
+ def _graph_repr(self) -> str:
42
+ return self._str()
43
+
44
+ def mul(self, other: Any) -> Any:
45
+ return other.mul(self)
46
+
47
+ def eq(self, other: Any) -> Any:
48
+ return other.eq(self)
49
+
50
+ def ne(self, other: Any) -> Any:
51
+ return other.ne(self)
52
+
53
+ def gt(self, other: Any) -> Any:
54
+ return other.lt(self)
55
+
56
+ def lt(self, other: Any) -> Any:
57
+ return other.gt(self)
58
+
59
+ def le(self, other: Any) -> Any:
60
+ return other.ge(self)
61
+
62
+ def ge(self, other: Any) -> Any:
63
+ return other.le(self)
64
+
65
+ def is_symbolic(self) -> bool:
66
+ return False
67
+
68
+ def constant_int(self) -> int:
69
+ return self.val
tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/_dynamism.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from typing import Any, Callable, Union
3
+
4
+ import torch
5
+ from torch.utils._pytree import tree_flatten_with_path, tree_map
6
+
7
+
8
+ KeyPath = tuple[Any, ...]
9
+ NonTensorShapeFn = Callable[[Union[int, float]], tuple[Any, ...]]
10
+
11
+ __all__ = [
12
+ "normalize_source_name",
13
+ "module_to_nested_dict",
14
+ "track_dynamism_across_examples",
15
+ "clone_and_convert_to_meta",
16
+ ]
17
+
18
+
19
+ def normalize_source_name(name: str) -> str:
20
+ # Match attribute access like .x and replace with ['x']
21
+ return re.sub(r"\.([a-zA-Z_][a-zA-Z0-9_]*)", r"['\1']", name)
22
+
23
+
24
+ def module_to_nested_dict(module: torch.nn.Module) -> dict[str, Any]:
25
+ """Recursively converts an nn.Module into a nested dictionary with explicit 'parameters' and 'modules' keys."""
26
+ self_dict: dict[str, Any] = {}
27
+
28
+ self_dict["_parameters"] = {}
29
+ self_dict["_modules"] = {}
30
+
31
+ for attr_name in dir(module):
32
+ if not attr_name.startswith("_") and not callable(getattr(module, attr_name)):
33
+ attr_value = getattr(module, attr_name)
34
+ if (
35
+ not isinstance(attr_value, torch.nn.Module)
36
+ and isinstance(attr_value, (int, float, torch.Tensor))
37
+ and type(attr_value) is not bool
38
+ ):
39
+ self_dict[attr_name] = attr_value
40
+
41
+ for name, param in module.named_parameters(recurse=False):
42
+ self_dict["_parameters"][name] = param
43
+ for name, buffer in module.named_buffers(recurse=False):
44
+ self_dict["_parameters"][name] = buffer
45
+
46
+ for name, submodule in module.named_children():
47
+ self_dict["_modules"][name] = module_to_nested_dict(submodule)
48
+
49
+ return self_dict
50
+
51
+
52
+ def track_dynamism_across_examples(
53
+ example_inputs: list[Any],
54
+ ) -> dict[Any, Any]:
55
+ """
56
+ This function analyzes a list of example inputs to determine the dynamism of their shapes.
57
+ It tracks whether the dimensions of tensors or non-tensor values change across
58
+ different examples. The function returns a dictionary where each key represents
59
+ a path to a value in the input examples, and the corresponding value is a tuple
60
+ indicating which dimensions are dynamic (i.e., change across examples). This
61
+ helps in understanding how the structure of data varies across different instances.
62
+ """
63
+ tracking: dict[KeyPath, tuple[list[set[Any]], bool]] = {}
64
+
65
+ for ex in example_inputs:
66
+ if "self" in ex and isinstance(ex["self"], torch.nn.Module):
67
+ ex["self"] = module_to_nested_dict(ex["self"])
68
+ leaves_with_paths, _ = tree_flatten_with_path(ex)
69
+ for key_path, value in leaves_with_paths:
70
+ if not isinstance(value, (int, float, torch.Tensor)):
71
+ continue
72
+ if isinstance(value, torch.Tensor):
73
+ shape: tuple[int | float, ...] = tuple(value.shape)
74
+ is_tensor = True
75
+ else:
76
+ shape = (value,)
77
+ is_tensor = False
78
+ if key_path not in tracking:
79
+ tracking[key_path] = ([set() for _ in range(len(shape))], is_tensor)
80
+ else:
81
+ dim_sets, flag = tracking[key_path]
82
+ if flag != is_tensor:
83
+ pass
84
+ while len(dim_sets) < len(shape):
85
+ dim_sets.append(set())
86
+ for i, dim in enumerate(shape):
87
+ tracking[key_path][0][i].add(dim)
88
+
89
+ output: dict[Any, Any] = {}
90
+ for key_path, (dim_sets, _is_tensor) in tracking.items():
91
+ final_dyn = tuple(len(s) > 1 for s in dim_sets)
92
+ key_str = "L" + "".join(f"{str(k)}" for k in key_path)
93
+ key = key_path[0].key # type: ignore[attr-defined]
94
+ if key not in output:
95
+ output[key] = {}
96
+ output[key][key_str] = final_dyn
97
+ return output
98
+
99
+
100
+ def clone_and_convert_to_meta(example_input: Any) -> Any:
101
+ """
102
+ This function takes a list of example inputs and for each tensor, clones it and converts it to device=meta.
103
+ For non-tensor values, it keeps the reference. It uses pytree to handle nested structures recursively.
104
+ """
105
+
106
+ def transform_fn(value: Any) -> Any:
107
+ if isinstance(value, torch.Tensor):
108
+ return value.clone().to(device="meta")
109
+ return value
110
+
111
+ return tree_map(transform_fn, example_input)
tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/accelerator_partitioner.py ADDED
@@ -0,0 +1,1080 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import operator
3
+ from collections import deque
4
+ from typing import NamedTuple
5
+
6
+ import torch
7
+ from torch.fx.experimental.partitioner_utils import (
8
+ Device,
9
+ get_extra_size_of,
10
+ get_latency_of_partitioned_graph,
11
+ get_partition_to_latency_mapping,
12
+ NodeLatency,
13
+ Partition,
14
+ PartitionerConfig,
15
+ PartitionMode,
16
+ )
17
+ from torch.fx.graph_module import GraphModule
18
+ from torch.fx.node import map_arg, Node
19
+ from torch.fx.passes.graph_manipulation import get_size_of_all_nodes
20
+ from torch.fx.passes.split_module import split_module
21
+
22
+
23
+ class DAGNode:
24
+ """DAGNode class maintains useful information for a partition (submodule),
25
+ and its input submodules and output submodules.
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ submodule_node: Node,
31
+ input_nodes: list[Node],
32
+ output_nodes: list[Node],
33
+ logical_device_ids: list[int],
34
+ size_bytes: int,
35
+ ) -> None:
36
+ self.submodule_node: Node = submodule_node
37
+ self.input_nodes: list[Node] = input_nodes
38
+ self.output_nodes: list[Node] = output_nodes
39
+ self.logical_device_ids: list[int] = logical_device_ids
40
+ self.size_bytes = size_bytes
41
+
42
+ def __str__(self) -> str:
43
+ return str(self.submodule_node)
44
+
45
+
46
+ class DAG:
47
+ """DAG class contains all the DAG nodes"""
48
+
49
+ def __init__(self) -> None:
50
+ self.nodes: list[DAGNode] = []
51
+
52
+ def create_node(
53
+ self,
54
+ submodule_node: Node,
55
+ input_nodes: list[Node],
56
+ output_nodes: list[Node],
57
+ logical_devices: list[int],
58
+ size_bytes: int,
59
+ ) -> None:
60
+ node = DAGNode(
61
+ submodule_node, input_nodes, output_nodes, logical_devices, size_bytes
62
+ )
63
+ self.nodes.append(node)
64
+
65
+
66
+ class PartitionResult(NamedTuple):
67
+ """NameTuple used for returning DAG and a new fx module"""
68
+
69
+ dag: DAG
70
+ module_with_submodules: GraphModule
71
+
72
+
73
+ """Followings are some helper functions for partition manipulation"""
74
+
75
+
76
+ def reset_partition_device(partitions):
77
+ for partition in partitions:
78
+ partition.logical_device_ids = []
79
+
80
+
81
+ def combine_two_partitions(
82
+ partition_0: Partition, partition_1: Partition, partitions: list[Partition]
83
+ ) -> None:
84
+ """Given a list of partitions and its two partitions,
85
+ combine these two partitions into a new one appending to the partitions
86
+ and remove the previous two partitions from the list of partitions
87
+ """
88
+ partition = Partition(len(partitions))
89
+ partition.nodes = partition_0.nodes.union(partition_1.nodes)
90
+ partition.recalculate_mem_size()
91
+ partitions.append(partition)
92
+ partitions.remove(partition_0)
93
+ partitions.remove(partition_1)
94
+ reorganize_partitions(partitions)
95
+ return
96
+
97
+
98
+ def set_parents_and_children(partitions: list[Partition]) -> None:
99
+ """Given a list of partitions, mark parents and children for each partition"""
100
+ # Go through all nodes in a partition.
101
+ # If a node's user is in other partition,
102
+ # then the other partition is this partition's children.
103
+ # This partition is the other partition's parent
104
+ for partition in partitions:
105
+ partition.children = set()
106
+ partition.parents = set()
107
+ for partition in partitions:
108
+ for node in partition.nodes:
109
+ # For each node in the current partition, find its users
110
+ users = node.users
111
+ for n in users:
112
+ # Find which the partition the user node belongs to.
113
+ # Note that if the node itself is also belongs to that partition,
114
+ # that partition is not the child of the current partition
115
+ for p in partitions:
116
+ if p != partition and n in p.nodes and node not in p.nodes:
117
+ partition.children.add(p)
118
+ p.parents.add(partition)
119
+ return
120
+
121
+
122
+ def reorganize_partitions(partitions: list[Partition]) -> None:
123
+ """Given a list of partitions, reorganize partition id,
124
+ its parents and its children for each partition
125
+ """
126
+ # Rearrange partition ids
127
+ for i, partition in enumerate(partitions):
128
+ partition.partition_id = i
129
+ set_parents_and_children(partitions)
130
+ return
131
+
132
+
133
+ def get_bfs_level_partition(partitions: list[Partition]) -> None:
134
+ """Given a list of partitions,
135
+ mark the bfs level for each partition
136
+ """
137
+ current_level: set[Partition] = set()
138
+ visited: set[Partition] = set()
139
+ for partition in partitions:
140
+ # If a partition has no parent, it should be in root level
141
+ if len(partition.parents) == 0:
142
+ current_level.add(partition)
143
+ next_level: set[Partition] = set()
144
+ level = 0
145
+ # bfs
146
+ while current_level:
147
+ partition = current_level.pop()
148
+ partition.bfs_level = level
149
+ visited.add(partition)
150
+ children = partition.children
151
+ for child in children:
152
+ if child not in next_level:
153
+ next_level.add(child)
154
+ if not current_level:
155
+ current_level = next_level.copy()
156
+ next_level = set()
157
+ level += 1
158
+ return
159
+
160
+
161
+ def get_node_to_partition_mapping(partitions: list[Partition]) -> dict[Node, int]:
162
+ """Given a list of partitions,return node to partition mapping"""
163
+ node_to_partition: dict[Node, int] = {}
164
+ for partition in partitions:
165
+ for node in partition.nodes:
166
+ node_to_partition[node] = partition.partition_id
167
+ return node_to_partition
168
+
169
+
170
+ def get_logical_id_to_device(devices: list[Device]) -> dict[int, Device]:
171
+ """Get a mapping from device logical ID to Device object."""
172
+ logical_id_to_device: dict[int, Device] = {}
173
+ for d in devices:
174
+ logical_id_to_device[d.logical_id] = d
175
+ return logical_id_to_device
176
+
177
+
178
+ def get_device_partition_stats(
179
+ partitions: list[Partition], devices: list[Device]
180
+ ) -> tuple[dict[Device, list[Partition]], dict[Device, int], list[Partition]]:
181
+ """Given a list of partitions and a list of devices, returns:
182
+ 1. A mapping from device to partitions on it;
183
+ 2. A mapping from device to its remaining memory size;
184
+ 3. A list of partitions that do not have a device.
185
+ """
186
+ # logical id to device
187
+ logical_id_to_device = get_logical_id_to_device(devices)
188
+ # Track partitions on device
189
+ device_to_partitions: dict[Device, list[Partition]] = {}
190
+ # Track device's left mem size
191
+ device_to_left_mem_bytes: dict[Device, int] = {}
192
+ for d in devices:
193
+ device_to_partitions[d] = []
194
+ device_to_left_mem_bytes[d] = d.available_mem_bytes
195
+
196
+ # Deal with the partitions that already have a device
197
+ # and also collect all partitions without a device (no_device_partitions)
198
+ no_device_partitions = []
199
+ for partition in partitions:
200
+ if partition.logical_device_ids != []:
201
+ for logical_id in partition.logical_device_ids:
202
+ device = logical_id_to_device[logical_id]
203
+ device_to_partitions[device].append(partition)
204
+ device_to_left_mem_bytes[device] -= partition.used_mem_bytes
205
+ else:
206
+ no_device_partitions.append(partition)
207
+
208
+ return (
209
+ device_to_partitions,
210
+ device_to_left_mem_bytes,
211
+ no_device_partitions,
212
+ )
213
+
214
+
215
+ def get_device_to_partitions_mapping(
216
+ partitions: list[Partition], devices: list[Device]
217
+ ):
218
+ """Given a list of partitions and a list of devices,
219
+ map each partition into a device.
220
+ """
221
+
222
+ def calculate_extra_mem_bytes_needed_for(
223
+ partition: Partition, partitions: list[Partition]
224
+ ):
225
+ all_nodes: set[Node] = set()
226
+ for p in partitions:
227
+ all_nodes = all_nodes.union(p.nodes)
228
+ if len(all_nodes) == 0:
229
+ return partition.used_mem_bytes
230
+ all_nodes = all_nodes.union(partition.nodes)
231
+ extra_size_needed = 0
232
+ for node in partition.nodes:
233
+ extra_size_needed += get_extra_size_of(node, all_nodes)
234
+ return extra_size_needed
235
+
236
+ def find_device_for(partition: Partition):
237
+ """Given a partition, find a logical device for the partition
238
+ The algorithm is to put the partition on the device
239
+ that has just enough mem left for that partition.
240
+ device_to_left_mem_bytes is a dictionary between device and its left mem size
241
+ sorted by its left mem size
242
+ """
243
+ for d in device_to_left_mem_bytes:
244
+ extra_size_needed = calculate_extra_mem_bytes_needed_for(
245
+ partition, device_to_partitions[d]
246
+ )
247
+ if extra_size_needed < device_to_left_mem_bytes[d]:
248
+ device_to_partitions[d].append(partition)
249
+ partition.logical_device_ids.append(d.logical_id)
250
+ device_to_left_mem_bytes[d] -= extra_size_needed
251
+ return True
252
+ return False
253
+
254
+ (
255
+ device_to_partitions,
256
+ device_to_left_mem_bytes,
257
+ no_device_partitions,
258
+ ) = get_device_partition_stats(partitions, devices)
259
+
260
+ # Find devices for all the partitions without a device
261
+ found_device = True
262
+ for partition in no_device_partitions:
263
+ device_to_left_mem_bytes = dict(
264
+ sorted(device_to_left_mem_bytes.items(), key=operator.itemgetter(1))
265
+ )
266
+ found_device = find_device_for(partition)
267
+ if not found_device:
268
+ break
269
+ return found_device
270
+
271
+
272
+ def check_dependency(partition):
273
+ """Given a partition,check if there is a circular dependency on
274
+ this partition using bfs
275
+ """
276
+ visited: set[Partition] = {partition}
277
+ queue: deque[Partition] = deque([partition])
278
+ while queue:
279
+ p = queue.popleft()
280
+ for child in p.children:
281
+ if child == partition:
282
+ return True
283
+ else:
284
+ if child not in visited:
285
+ visited.add(child)
286
+ queue.append(child)
287
+ return False
288
+
289
+
290
+ class Partitioner:
291
+ """A fx module may not fit into one device.
292
+ Partitioner class helps partition one fx module into submodules (partitions),
293
+ so that the submodules can be executed crossing different accelerators.
294
+ The main function of this class is self.partition_graph.
295
+ It partitions the fx module based on the scheme specified in partition_config
296
+ A DAG structure is returned
297
+ along with a new fx module with submodule nodes.
298
+ """
299
+
300
+ def __init__(self) -> None:
301
+ self.partitions: list[Partition] = []
302
+ self.node_to_partition: dict[Node, int] = {}
303
+ self.devices: list[Device] = []
304
+
305
+ def partition_graph(
306
+ self,
307
+ fx_module: GraphModule,
308
+ torch_module: torch.nn.Module,
309
+ partitioner_config: PartitionerConfig,
310
+ ) -> PartitionResult:
311
+ """Given the fx module, torch module and partitioner_config,
312
+ find the partitions, do the partitions,
313
+ and then return a DAG and a new fx module with submodule nodes (partitions)
314
+ """
315
+ self.graph_module = fx_module
316
+ self.torch_module = torch_module
317
+ self.devices = partitioner_config.devices
318
+ if len(self.devices) == 0:
319
+ raise RuntimeError("No devices")
320
+ # Tag the size in bytes to all nodes in the graph_module.
321
+ get_size_of_all_nodes(self.graph_module)
322
+ # Check if there are op nodes in the fx module
323
+ nodes = self.graph_module.graph.nodes
324
+ if all(node.op in {"placeholder", "get_attr", "output"} for node in nodes):
325
+ raise RuntimeError("No Partition since no operations in the module")
326
+ # Calculate total size of the fx module
327
+ total_size_of_graph = 0
328
+ for node in nodes:
329
+ if node.op == "output":
330
+ break
331
+ total_size_of_graph += node.size_bytes.total_size
332
+ # Find the device with the max mem size
333
+ device_with_max_mem = max(self.devices, key=lambda d: d.available_mem_bytes)
334
+ # AOT based partition
335
+ if partitioner_config.mode == PartitionMode.aot_based:
336
+ self.aot_based_partition(
337
+ partitioner_config.node_to_partition_mapping,
338
+ partitioner_config.partition_to_logical_device_mapping,
339
+ )
340
+ # Single partition if the whole module can be fit into one device
341
+ elif total_size_of_graph <= device_with_max_mem.available_mem_bytes:
342
+ self.find_single_partition(
343
+ total_size_of_graph, logical_device_id=device_with_max_mem.logical_id
344
+ )
345
+ elif total_size_of_graph > sum(d.available_mem_bytes for d in self.devices):
346
+ raise RuntimeError("Devices have no enough memory for the module")
347
+ else:
348
+ # Sparse nn based partition
349
+ if partitioner_config.mode == PartitionMode.sparse_nn:
350
+ available_mem_bytes = self.devices[0].available_mem_bytes
351
+ if not all(
352
+ device.available_mem_bytes == available_mem_bytes
353
+ for device in self.devices
354
+ ):
355
+ raise RuntimeError("All devices must have same memory size!")
356
+ # sparse_nn_partition only support same memory size
357
+ # TODO: add different size support for sparse_nn_partition
358
+ self.sparse_nn_partition(available_mem_bytes)
359
+ # Cost aware partition
360
+ elif partitioner_config.mode == PartitionMode.cost_aware:
361
+ self.cost_aware_partition(
362
+ partitioner_config.transfer_rate_bytes_per_sec,
363
+ partitioner_config.node_to_latency_mapping,
364
+ )
365
+ # KL based partition
366
+ elif partitioner_config.mode == PartitionMode.kl_based:
367
+ self.kl_based_partition(
368
+ partitioner_config.transfer_rate_bytes_per_sec,
369
+ partitioner_config.node_to_latency_mapping,
370
+ )
371
+ else:
372
+ self.size_based_partition()
373
+
374
+ # Saturate host if possible.
375
+ if partitioner_config.saturate_host:
376
+ self.saturate_host()
377
+
378
+ # Partition the graph module based on the partition assignment.
379
+ module_with_submodules = self.do_partition()
380
+
381
+ # The DAG contains DAGNodes with info of each partition's input nodes, output nodes
382
+ # and how partitions are connected.
383
+ dag = self.dump_dag(module_with_submodules)
384
+ ret = PartitionResult(dag, module_with_submodules)
385
+ return ret
386
+
387
+ def find_single_partition(
388
+ self, total_size_of_graph, logical_device_id: int = 0
389
+ ) -> None:
390
+ """Fit the whole fx module into one device"""
391
+ partition_0 = self.create_partition()
392
+ for node in self.graph_module.graph.nodes:
393
+ if node.op == "output":
394
+ # Skip the output node, but there can
395
+ # be nodes after the output in certain cases.
396
+ continue
397
+ partition_0.nodes.add(node)
398
+ partition_0.used_mem_bytes = total_size_of_graph
399
+ partition_0.logical_device_ids = [logical_device_id]
400
+ # Get the node to partition mapping
401
+ self.node_to_partition = get_node_to_partition_mapping(self.partitions)
402
+ return
403
+
404
+ def size_based_partition(self) -> None:
405
+ """This method is to partition the fx module based on memory size.
406
+ It uses greedy approach. The result may not be the best.
407
+ The basic idea is:
408
+ Step 1:
409
+ Find a device which has enough memory to fit the current node, create a empty partition
410
+ with the size of that device.
411
+ Then keep adding the following nodes into the partition until the partition is full.
412
+ Step 2:
413
+ Repeat Step 1 until no device left
414
+ Step 3:
415
+ If some nodes are left, create a partition for each left node (single node partition).
416
+ and then try to map those partitions into logical devices with enough mem left.
417
+ """
418
+
419
+ def find_device_based_on_size(node) -> Device:
420
+ """Given a node, this function is to find a logical device
421
+ that could fit the node.
422
+ """
423
+ mem_size_needed = get_extra_size_of(node, set())
424
+ device = Device("", -1, -1)
425
+ for d in self.devices:
426
+ if (
427
+ d not in occupied_devices
428
+ and d.available_mem_bytes >= mem_size_needed
429
+ ):
430
+ device = d
431
+ break
432
+ if device.available_mem_bytes < 0:
433
+ raise RuntimeError(str(node) + "is too large to fit any device")
434
+ occupied_devices.append(device)
435
+ return device
436
+
437
+ # Track partition and its left mem size
438
+ partition_to_left_mem_bytes: dict[Partition, int] = {}
439
+ # Track all the devices that have been used
440
+ occupied_devices: list[Device] = []
441
+ partition = self.create_partition()
442
+ for node in self.graph_module.graph.nodes:
443
+ if node.op in {"call_module", "call_method", "call_function"}:
444
+ # Check if there are devices left
445
+ if len(self.partitions) <= len(self.devices):
446
+ total_size_of_input_nodes = get_extra_size_of(node, partition.nodes)
447
+ # Check if the current partition is the very first partition
448
+ if partition.used_mem_bytes == 0:
449
+ # Find a device to fit the first node, return available mem size
450
+ device = find_device_based_on_size(node)
451
+ occupied_devices.append(device)
452
+ # Update partition and its left mem size
453
+ partition_to_left_mem_bytes[
454
+ partition
455
+ ] = device.available_mem_bytes
456
+ # Update available mem for the current partition
457
+ partition.logical_device_ids.append(device.logical_id)
458
+ else:
459
+ # The current partition is not the first partition
460
+ # Check if the current node can fit into current partition
461
+ if (
462
+ partition_to_left_mem_bytes[partition]
463
+ < total_size_of_input_nodes
464
+ ):
465
+ # Check if no device is left
466
+ if len(self.partitions) == len(self.devices):
467
+ # No device is left
468
+ # Create the first single node partition for the current node
469
+ self.create_single_node_partition(node)
470
+ continue
471
+ # Some devices are still left
472
+ # Create a new partition with a mem size that is enough for the current node
473
+ device = find_device_based_on_size(node)
474
+ partition = self.create_partition()
475
+ total_size_of_input_nodes = get_extra_size_of(
476
+ node, partition.nodes
477
+ )
478
+ partition_to_left_mem_bytes[
479
+ partition
480
+ ] = device.available_mem_bytes
481
+ partition.logical_device_ids.append(device.logical_id)
482
+ partition.add_node(node)
483
+ partition_to_left_mem_bytes[partition] -= total_size_of_input_nodes
484
+ # Create single node partitions if no device is left
485
+ else:
486
+ self.create_single_node_partition(node)
487
+ reorganize_partitions(self.partitions)
488
+ # Get the node to partition mapping
489
+ self.node_to_partition = get_node_to_partition_mapping(self.partitions)
490
+ # Mapping all partitions into device
491
+ found_partition_to_device_mapping = get_device_to_partitions_mapping(
492
+ self.partitions, self.devices
493
+ )
494
+ if not found_partition_to_device_mapping:
495
+ raise RuntimeError("Cannot Get a Valid Partition to Logical Device Mapping")
496
+ return
497
+
498
+ def saturate_host(self) -> None:
499
+ """Saturate host by assigning replicates to unused devices with enough memory.
500
+ It uses a greedy approach to find a next available set of devices to place all split
501
+ partitions: For each used device, it searches for an idle device with minimal memory
502
+ size that can hold all the partition located on that device; If the search is successful
503
+ for all used devices, it then assigns the new devices' logical ID to the corresponding
504
+ partition.
505
+ """
506
+ (
507
+ device_to_partitions,
508
+ device_to_left_mem_bytes,
509
+ no_device_partitions,
510
+ ) = get_device_partition_stats(self.partitions, self.devices)
511
+
512
+ assert (
513
+ len(no_device_partitions) == 0
514
+ ), f"Expect no_device_partitions has 0 device, but get {len(no_device_partitions)}"
515
+
516
+ # Devices that hold partitions
517
+ used_devices = [d for d in self.devices if len(device_to_partitions[d]) > 0]
518
+ # Track replicates of the assigned devices
519
+ replicated_device_to_used_device: dict[Device, Device] = {}
520
+
521
+ while len(used_devices) * 2 + len(replicated_device_to_used_device) <= len(
522
+ self.devices
523
+ ):
524
+ # Success flag for this round
525
+ success = True
526
+ # Devices that have not been assigned
527
+ idle_devices = [
528
+ d
529
+ for d in self.devices
530
+ if d not in used_devices and d not in replicated_device_to_used_device
531
+ ]
532
+ # Temporary mapping from replicated device to original device
533
+ temp_replicate_mapping = {}
534
+
535
+ # Find a new device to replicate all partitions on an used device
536
+ for used_device in used_devices:
537
+ # Idle devices that have enough memory
538
+ available_devices = [
539
+ d
540
+ for d in idle_devices
541
+ if d.available_mem_bytes
542
+ >= used_device.available_mem_bytes
543
+ - device_to_left_mem_bytes[used_device]
544
+ ]
545
+ if len(available_devices) == 0:
546
+ success = False
547
+ break
548
+ new_device = min(available_devices, key=lambda d: d.available_mem_bytes)
549
+ idle_devices.remove(new_device)
550
+ temp_replicate_mapping[new_device] = used_device
551
+
552
+ if not success:
553
+ break
554
+ replicated_device_to_used_device.update(temp_replicate_mapping)
555
+
556
+ # Update logical device IDs assigned to the partitions
557
+ for (
558
+ replicate_device,
559
+ original_device,
560
+ ) in replicated_device_to_used_device.items():
561
+ logical_id = replicate_device.logical_id
562
+ for partition in device_to_partitions[original_device]:
563
+ partition.logical_device_ids.append(logical_id)
564
+ for p in self.partitions:
565
+ print(p.logical_device_ids)
566
+
567
+ def do_partition(self) -> GraphModule:
568
+ """Return a new fx module with submodule nodes (partitions)."""
569
+ module_with_submodules = split_module(
570
+ self.graph_module,
571
+ self.torch_module,
572
+ lambda node: self.node_to_partition[node],
573
+ )
574
+ return module_with_submodules
575
+
576
+ def dump_dag(self, module_with_submodules: GraphModule) -> DAG:
577
+ """Return the dag structure and the new fx module with submodules."""
578
+ dag = DAG()
579
+ for node in module_with_submodules.graph.nodes:
580
+ if node.op == "output":
581
+ break
582
+ if node.op in {"placeholder", "get_attr"}:
583
+ continue
584
+ if node.target == operator.__getitem__:
585
+ continue
586
+ input_nodes: dict[Node, None] = {}
587
+ map_arg(node.args, input_nodes.setdefault)
588
+ map_arg(node.kwargs, input_nodes.setdefault)
589
+ # When a node has two or more output nodes,
590
+ # it outputs its result to 'getitem' nodes.
591
+ # Those 'getitem' nodes are the output node for this node.
592
+ # Otherwise, the output node is this node itself.
593
+ if len(node.users) > 1:
594
+ output_nodes = list(node.users)
595
+ else:
596
+ output_nodes = [node]
597
+ partition_id = int(node.name.rsplit("_", 1)[-1])
598
+ device_ids = self.partitions[partition_id].logical_device_ids
599
+ size_bytes = self.partitions[partition_id].used_mem_bytes
600
+ dag.create_node(
601
+ node, list(input_nodes), output_nodes, device_ids, size_bytes
602
+ )
603
+ return dag
604
+
605
+ def create_partition(self) -> Partition:
606
+ """Create a partition and append it to self.partitions."""
607
+ partition_id = len(self.partitions)
608
+ partition = Partition(partition_id)
609
+ self.partitions.append(partition)
610
+ return partition
611
+
612
+ def create_single_node_partition(self, node):
613
+ """Create a partition for a single node"""
614
+ partition = self.create_partition()
615
+ partition.add_node(node)
616
+ return
617
+
618
+ def sparse_nn_partition(self, available_mem_bytes: int) -> None:
619
+ """This method partition a sparse nn module.
620
+ It is size based partition but different from size_based_partition,
621
+ it only works when all the devices have same memory size (available_mem_bytes).
622
+ In the future, devices with different mem sizes will be supported like size_based_partition.
623
+ It first traverse all the nodes and do the partitions based on the same memory size.
624
+ If the current partition has no enough memory left for a new op node
625
+ (call_module, call_method, call_function), a new partition is created.
626
+ When crossing the boundary between non-embedding nodes and embedding nodes,
627
+ a new partition is created regardlessly.
628
+ For example, if the current node is a non-embedding node but the next node is an
629
+ embedding node, a new partition is created for the next node.
630
+ After the partition, the partitions are combined as much as possible.
631
+ The rule is that a non-embedding partition only
632
+ combines with another non-embedding one.
633
+ So as the embedding partitions.
634
+ """
635
+
636
+ def combine_partitions_based_on_size(
637
+ partitions: list[Partition], available_mem_bytes: int
638
+ ) -> None:
639
+ """Combining small partitions together to keep as less partitions as possible.
640
+ Here is an example of the algorithm to do this:
641
+ Assume some partitions, we first sort them based on partition used memory size.
642
+ [(partition_4, 1), (partition_3, 1), (partition_2, 2), (partition_1, 7), (partition_0, 9)]
643
+ The available memory is 10.
644
+ step 1: self.find_partition_to_combine_based_on_size()
645
+ First, mark bfs level for each partition
646
+ Second, look the smallest partition, partition_4: 10 - 1 = 9
647
+ It means any partition has a used memory equal or less than 9 could combine this partition
648
+ We go from the largest and selection partition_0.
649
+ Check the bfs level for two partitions, if the level difference is less than 2,
650
+ it can be combined.
651
+ step 2: repeat step 1 until no partitions can be combined
652
+ """
653
+ find_combination = True
654
+ while find_combination:
655
+ # Sort partitions based on memory size
656
+ sorted_partitions = sorted(partitions, key=lambda p: p.used_mem_bytes)
657
+ # Mark bfs level
658
+ get_bfs_level_partition(self.partitions)
659
+ find_combination, partitions = find_partition_to_combine_based_on_size(
660
+ sorted_partitions, available_mem_bytes, partitions
661
+ )
662
+ return
663
+
664
+ def calculate_mem_bytes_needed(p1, p2):
665
+ """Given two partitions, calculate how many mem bytes
666
+ are needed if two partitions are combined
667
+ """
668
+ nodes = p1.nodes.union(p2.nodes)
669
+ mem_bytes_needed = 0
670
+ for node in nodes:
671
+ mem_bytes_needed += get_extra_size_of(node, nodes)
672
+ return mem_bytes_needed
673
+
674
+ def find_partition_to_combine_based_on_size(
675
+ sorted_partitions: list[Partition],
676
+ available_mem_bytes: int,
677
+ partitions: list[Partition],
678
+ ) -> tuple[bool, list[Partition]]:
679
+ """step 1 in combine_partition_based_on_size()"""
680
+ find_combination = False
681
+ smallest_partition = sorted_partitions.pop(0)
682
+ for p in sorted_partitions[::-1]:
683
+ if abs(smallest_partition.bfs_level - p.bfs_level) <= 1:
684
+ # Calculate how many bytes needed if combined
685
+ mem_bytes_needed = calculate_mem_bytes_needed(p, smallest_partition)
686
+ if mem_bytes_needed <= available_mem_bytes:
687
+ combine_two_partitions(p, smallest_partition, self.partitions)
688
+ partitions.remove(smallest_partition)
689
+ partitions.remove(p)
690
+ partitions.append(self.partitions[-1])
691
+ find_combination = True
692
+ break
693
+ return find_combination, partitions
694
+
695
+ def reset_partition_in_sparse_nn(partition, new_partition=True):
696
+ """If crossing the boundary between non-embedding nodes and
697
+ embedding nodes, create a new partition
698
+ """
699
+ if in_embedding_region:
700
+ embedding_partitions.append(partition)
701
+ else:
702
+ non_embedding_partitions.append(partition)
703
+ if new_partition:
704
+ partition = self.create_partition()
705
+ partition.left_mem_bytes = available_mem_bytes
706
+ return partition
707
+ return None
708
+
709
+ def is_embedding_node(node: Node) -> bool:
710
+ """Check if a node is an embedding node"""
711
+ if node.op == "call_module":
712
+ submodule = self.graph_module
713
+ for atom in str(node.target).split("."):
714
+ if not hasattr(submodule, atom):
715
+ raise RuntimeError(
716
+ f"Module {submodule} has no attribute {atom}"
717
+ )
718
+ submodule = getattr(submodule, atom)
719
+ if "Embedding" in str(submodule):
720
+ return True
721
+ return False
722
+
723
+ # Track embedding partitions and non-embedding partitions separately
724
+ embedding_partitions: list[Partition] = []
725
+ non_embedding_partitions: list[Partition] = []
726
+ # A Flag to check the boundary
727
+ in_embedding_region: bool = False
728
+ partition = self.create_partition()
729
+ for node in self.graph_module.graph.nodes:
730
+ if node.op in {"call_module", "call_method", "call_function"}:
731
+ # Check if crossing the boundary between embedding nodes and non embedding nodes
732
+ if is_embedding_node(node) != in_embedding_region:
733
+ # Crossing the boundary
734
+ # Check if the current partition is an empty partition
735
+ if partition.used_mem_bytes != 0:
736
+ # The current partition isn't an empty partition. Create a new one.
737
+ partition = reset_partition_in_sparse_nn(partition)
738
+ in_embedding_region = not in_embedding_region
739
+ total_size_of_input_nodes = get_extra_size_of(node, partition.nodes)
740
+ if (
741
+ total_size_of_input_nodes + partition.used_mem_bytes
742
+ > available_mem_bytes
743
+ ):
744
+ partition = reset_partition_in_sparse_nn(partition)
745
+ total_size_of_input_nodes = get_extra_size_of(node, partition.nodes)
746
+ if total_size_of_input_nodes > available_mem_bytes:
747
+ raise RuntimeError(
748
+ node.target + "is too large to fit into a device"
749
+ )
750
+ partition.add_node(node)
751
+ reset_partition_in_sparse_nn(partition, new_partition=False)
752
+ # Set parents and children for partitions
753
+ set_parents_and_children(self.partitions)
754
+ # Combining non-embedding partitions
755
+ combine_partitions_based_on_size(non_embedding_partitions, available_mem_bytes)
756
+ # Combining embedding partitions
757
+ combine_partitions_based_on_size(embedding_partitions, available_mem_bytes)
758
+ total_size_of_non_embedding_partitions = 0
759
+ for partition in non_embedding_partitions:
760
+ total_size_of_non_embedding_partitions += partition.used_mem_bytes
761
+ # Check if devices are enough for all partitions
762
+ if len(embedding_partitions) > len(self.devices):
763
+ msg = (
764
+ "Need "
765
+ + str(len(embedding_partitions))
766
+ + " devices, but only "
767
+ + str(len(self.devices))
768
+ + " provided"
769
+ )
770
+ raise RuntimeError(msg)
771
+ occupied_devices = []
772
+ for i, partition in enumerate(embedding_partitions):
773
+ # Check if all non-embedding partitions can fit into embedding partition devices
774
+ if (
775
+ total_size_of_non_embedding_partitions + partition.used_mem_bytes
776
+ > available_mem_bytes
777
+ ):
778
+ raise RuntimeError(
779
+ "partition_"
780
+ + str(partition.partition_id)
781
+ + "(embedding partition) and non embedding partitions can not fit into one device"
782
+ )
783
+ else:
784
+ # Add logical device to the partition
785
+ partition.logical_device_ids = [self.devices[i].logical_id]
786
+ occupied_devices.append(self.devices[i].logical_id)
787
+ # Add logical devices to the non_embedding_partitions
788
+ for partition in non_embedding_partitions:
789
+ partition.logical_device_ids = occupied_devices
790
+ # Get the node to partition mapping
791
+ self.node_to_partition = get_node_to_partition_mapping(self.partitions)
792
+ return
793
+
794
+ def cost_aware_partition(
795
+ self,
796
+ transfer_rate_bytes_per_sec: float,
797
+ node_to_latency_mapping: dict[Node, NodeLatency],
798
+ ) -> None:
799
+ """This method is to partition the fx module based on the cost.
800
+ The cost is the total latency of running the whole fx module.
801
+ In partitioner_utils.py, the cost model is built.
802
+ The cost aware partition algorithm is:
803
+ #1. At every beginning, each node is a partition.
804
+ Then we map all the partitions to the devices
805
+ and calculate the cost
806
+ #2. Then try to pre-combine any two of the partitions if the two
807
+ partitions can be combined.
808
+ (the bfs level is less than 2 or two partitions are connected and
809
+ can find partition to device mapping)
810
+ See if any partition pair could reduce the current cost.
811
+ Choose the pair that shows the minimum cost and then combine them
812
+ #3. Repeat #2 until the cost cannot be reduced.
813
+ """
814
+
815
+ def try_combining_partitions(p0_index, p1_index, partitions) -> float:
816
+ """Given two partitions and a list of partitions, combine these two partitions
817
+ and see what is the cost of the modified partition list
818
+ """
819
+ p0 = partitions[p0_index]
820
+ p1 = partitions[p1_index]
821
+ """If two partitions' bfs level are less than 2 or two partitions are connected to each other,
822
+ then they can be combined
823
+ """
824
+ if (
825
+ (abs(p0.bfs_level - p1.bfs_level) <= 1)
826
+ or (p0 in p1.parents)
827
+ or p0 in (p1.children)
828
+ ):
829
+ combine_two_partitions(p0, p1, partitions)
830
+ # Check if a circular dependency exists after combining
831
+ if check_dependency(partitions[-1]):
832
+ return float("inf")
833
+ # Check if the modified partition list can be mapped to devices after combination
834
+ reset_partition_device(partitions)
835
+ found_deivce = get_device_to_partitions_mapping(
836
+ partitions, self.devices
837
+ )
838
+ if not found_deivce:
839
+ return float("inf")
840
+ # Calculate the new cost
841
+ partition_to_latency_mapping = get_partition_to_latency_mapping(
842
+ partitions, node_to_latency_mapping
843
+ )
844
+ cost = get_latency_of_partitioned_graph(
845
+ partitions,
846
+ partition_to_latency_mapping,
847
+ transfer_rate_bytes_per_sec,
848
+ )
849
+ return cost
850
+ # If two partition can not be combined, the cost is inf
851
+ return float("inf")
852
+
853
+ def search_combination(
854
+ transfer_rate_bytes_per_sec, node_to_latency_mapping
855
+ ) -> bool:
856
+ """Given transfer rate between partitions and each node's latency,
857
+ find two partitions to combine so the cost of the partitions can
858
+ be reduced.
859
+ The algorithm is :
860
+ 1. Go through all the partition pairs and see
861
+ if any pair of partitions can be combined.
862
+ 2. Calculate the cost after the combination.
863
+ 3. Select the minimum cost and combine its corresponding partition pair.
864
+ """
865
+ partition_to_latency_mapping = get_partition_to_latency_mapping(
866
+ self.partitions, node_to_latency_mapping
867
+ )
868
+ cost = get_latency_of_partitioned_graph(
869
+ self.partitions,
870
+ partition_to_latency_mapping,
871
+ transfer_rate_bytes_per_sec,
872
+ )
873
+ if len(self.partitions) == 1:
874
+ return False
875
+ partition_pair: list[int] = []
876
+ for i in range(len(self.partitions) - 1):
877
+ for j in range(i + 1, len(self.partitions)):
878
+ # Try to combine the partition pair
879
+ # and see the new cost after combination
880
+ new_cost = try_combining_partitions(i, j, self.partitions[:])
881
+ if new_cost <= cost:
882
+ partition_pair = [i, j]
883
+ cost = new_cost
884
+ reorganize_partitions(self.partitions)
885
+ # If a partition pair is found, combine them
886
+ if len(partition_pair) != 0:
887
+ p0 = self.partitions[partition_pair[0]]
888
+ p1 = self.partitions[partition_pair[1]]
889
+ combine_two_partitions(p0, p1, self.partitions)
890
+ get_bfs_level_partition(self.partitions)
891
+ reset_partition_device(self.partitions)
892
+ get_device_to_partitions_mapping(self.partitions, self.devices)
893
+ return len(partition_pair) != 0
894
+
895
+ for node in self.graph_module.graph.nodes:
896
+ if node.op not in {"placeholder", "get_attr", "output"}:
897
+ self.create_single_node_partition(node)
898
+ # Set up parent partitions and children partitions for each partition
899
+ set_parents_and_children(self.partitions)
900
+ # Get bfs level for each partition
901
+ get_bfs_level_partition(self.partitions)
902
+ find_combination = True
903
+ while find_combination:
904
+ # Search for a pair partition to generate the minimum new cost,
905
+ # then combine them
906
+ find_combination = search_combination(
907
+ transfer_rate_bytes_per_sec, node_to_latency_mapping
908
+ )
909
+ # Make sure all partitions are set up correctly
910
+ reorganize_partitions(self.partitions)
911
+ # Set up node to partition mapping
912
+ self.node_to_partition = get_node_to_partition_mapping(self.partitions)
913
+ return
914
+
915
+ def kl_based_partition(
916
+ self,
917
+ transfer_rate_bytes_per_sec: float,
918
+ node_to_latency_mapping: dict[Node, NodeLatency],
919
+ ) -> None:
920
+ """This function is a cost aware partition based
921
+ on Kernighan-Lin algorithm.
922
+ First, the graph is partitioned using size_based_partition.
923
+ Then, each node is swapped with any other node in a different
924
+ partition, and at the same time, the cost is estimated after
925
+ the swapping.
926
+ For example, we have nodes n0, n1, n2, n3 and n4.
927
+ Using size_based_partition, n0 and n1 are in Partition p0.
928
+ n2, n3 and n4 in Partition p1. The current cost is estimated.
929
+ We first tried using n0 to swap with n2 from the other partition.
930
+ Then we see that swapping n0 and n2 shows a lower cost
931
+ than the current cost and it is the minimum among other pairs like
932
+ (n0, None)(This means moving n0 to Partition without swapping other nodes),
933
+ (n0, n3) and (n0, n4). We swap n0 and n2 and set the new cost
934
+ as the current cost.
935
+ Then We repeat this process for all the other nodes until all swapping pairs
936
+ are tried.
937
+ """
938
+
939
+ def swap_nodes(n0, n1, p0, p1):
940
+ # Either n0 or n1 could be None
941
+ # That means we simply move the node
942
+ # to another partition
943
+ if n0 is not None:
944
+ p0.remove_node(n0)
945
+ p1.add_node(n0)
946
+ if n1 is not None:
947
+ p0.add_node(n1)
948
+ p1.remove_node(n1)
949
+
950
+ def try_swap_nodes(
951
+ n0, n1, p0, p1, node_to_latency_mapping, transfer_rate_per_sec
952
+ ):
953
+ cost = float("inf")
954
+ swap_nodes(n0, n1, p0, p1)
955
+ # Reorganize partitions after swapping
956
+ reorganize_partitions(self.partitions)
957
+ # Check if there is a circular dependency after swapping
958
+ if (not check_dependency(p0)) and (not check_dependency(p1)):
959
+ reset_partition_device(self.partitions)
960
+ partition_to_latency_mapping = get_partition_to_latency_mapping(
961
+ self.partitions, node_to_latency_mapping
962
+ )
963
+ # Check if all partitions can be mapped to logical devices after swapping
964
+ found_device = get_device_to_partitions_mapping(
965
+ self.partitions, self.devices
966
+ )
967
+ if not found_device:
968
+ cost = float("inf")
969
+ else:
970
+ cost = get_latency_of_partitioned_graph(
971
+ self.partitions,
972
+ partition_to_latency_mapping,
973
+ transfer_rate_bytes_per_sec,
974
+ )
975
+ # Swap back and reset all partitions back to original
976
+ swap_nodes(n1, n0, p0, p1)
977
+ reorganize_partitions(self.partitions)
978
+ reset_partition_device(self.partitions)
979
+ get_device_to_partitions_mapping(self.partitions, self.devices)
980
+ return cost
981
+
982
+ def swap_node_to_partition(
983
+ node, p0, p1, node_to_latency_mapping, transfer_rate_per_sec
984
+ ):
985
+ """This function helps to swap one node from partition p0
986
+ with all the nodes in another partition p1
987
+ """
988
+ p1_nodes = list(p1.nodes) + [None]
989
+ min_cost = float("inf")
990
+ node_pair: list[Node] = []
991
+ for n1 in p1_nodes:
992
+ # Ignore the node if it is not a op node
993
+ if n1 is not None and n1.op in {"placeholder", "get_attr"}:
994
+ continue
995
+ # Try swapping node in p0 with n1 in p1
996
+ cost = try_swap_nodes(
997
+ node, n1, p0, p1, node_to_latency_mapping, transfer_rate_per_sec
998
+ )
999
+ if cost < min_cost:
1000
+ node_pair = [node, n1]
1001
+ min_cost = cost
1002
+ return cost, node_pair # type: ignore[possibly-undefined]
1003
+
1004
+ # First use size_base_partition
1005
+ self.size_based_partition()
1006
+ partition_to_latency_mapping = get_partition_to_latency_mapping(
1007
+ self.partitions, node_to_latency_mapping
1008
+ )
1009
+ # Calculate the cost of the partitions
1010
+ cost = get_latency_of_partitioned_graph(
1011
+ self.partitions, partition_to_latency_mapping, transfer_rate_bytes_per_sec
1012
+ )
1013
+ # Keep tracking the node pair that shows the better cost
1014
+ node_pair: list[Node] = []
1015
+ # Keep tracking the partition pair of node pair
1016
+ partition_pair: list[Partition] = []
1017
+ # Collect all the op nodes from the graph
1018
+ op_nodes = [
1019
+ n
1020
+ for n in self.graph_module.graph.nodes
1021
+ if n.op not in {"placeholder", "get_attr", "output"}
1022
+ ]
1023
+ for node in op_nodes:
1024
+ # Find which partition the current node belongs
1025
+ p0_index = self.node_to_partition[node]
1026
+ p0 = self.partitions[p0_index]
1027
+ # Go through all the other partitions to swap
1028
+ # with other nodes from those partitions
1029
+ for p1_index, _ in enumerate(self.partitions):
1030
+ if p0_index != p1_index:
1031
+ p1 = self.partitions[p1_index]
1032
+ new_cost, new_node_pair = swap_node_to_partition(
1033
+ node,
1034
+ p0,
1035
+ p1,
1036
+ node_to_latency_mapping,
1037
+ transfer_rate_bytes_per_sec,
1038
+ )
1039
+ # Update the cost
1040
+ # Track the swapped node pair and their partitions
1041
+ if new_cost < cost:
1042
+ cost = new_cost
1043
+ node_pair = new_node_pair
1044
+ partition_pair = [p0, p1]
1045
+ # Do the swapping after trying all the nodes from a partition
1046
+ if len(node_pair) != 0:
1047
+ swap_nodes(
1048
+ node_pair[0], node_pair[1], partition_pair[0], partition_pair[1]
1049
+ )
1050
+ reorganize_partitions(self.partitions)
1051
+ get_device_to_partitions_mapping(self.partitions, self.devices)
1052
+ reorganize_partitions(self.partitions)
1053
+ # Mapping the device to the partition
1054
+ get_device_to_partitions_mapping(self.partitions, self.devices)
1055
+ return
1056
+
1057
+ def aot_based_partition(
1058
+ self, node_to_partition_mapping, partition_to_logical_device_mapping
1059
+ ):
1060
+ """This function helps to rebuild the partitions given the nodes and its
1061
+ corresponding partition id
1062
+ """
1063
+ partition_id_to_partition_mapping: dict[int, Partition] = {}
1064
+ self.node_to_partition = node_to_partition_mapping
1065
+ for node in self.node_to_partition:
1066
+ partition_id = self.node_to_partition[node]
1067
+ # If the requested partition has not been created, create the partition
1068
+ if partition_id not in partition_id_to_partition_mapping:
1069
+ partition = Partition(partition_id)
1070
+ self.partitions.append(partition)
1071
+ partition_id_to_partition_mapping[partition_id] = partition
1072
+ partition.logical_device_ids = partition_to_logical_device_mapping[
1073
+ partition_id
1074
+ ]
1075
+ else:
1076
+ partition = partition_id_to_partition_mapping[
1077
+ self.node_to_partition[node]
1078
+ ]
1079
+ # Add the current node into the partition
1080
+ partition.add_node(node)
tool_server/.venv/lib/python3.12/site-packages/torch/fx/experimental/const_fold.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import re
3
+ from typing import Callable, Optional, Union
4
+
5
+ import torch.fx
6
+ from torch.fx.node import map_arg
7
+ from torch.fx.passes.split_module import split_module
8
+
9
+
10
+ __all__ = [
11
+ "FoldedGraphModule",
12
+ "get_unique_attr_name_in_module",
13
+ "split_const_subgraphs",
14
+ ]
15
+
16
+
17
+ class FoldedGraphModule(torch.fx.GraphModule):
18
+ """
19
+ FoldedGraphModule is a GraphModule which also contains another
20
+ `const_subgraph_module` representing a subgraph which has all const attr
21
+ inputs and which can be run once before running the main standard
22
+ `graph`. The `const_output_names` are the ordered list names of attrs which
23
+ represent what each respective output from the const_subgraph should be set
24
+ on which attrs.
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ root: torch.nn.Module,
30
+ graph: torch.fx.Graph,
31
+ const_subgraph: Optional[torch.fx.Graph] = None,
32
+ fx_const_folded_attrs_name: Optional[str] = None,
33
+ device_for_folded_attrs: str = "cuda",
34
+ ):
35
+ super().__init__(root, graph)
36
+ self.const_subgraph_module = (
37
+ None
38
+ if const_subgraph is None
39
+ else torch.fx.GraphModule(root, const_subgraph)
40
+ )
41
+ self.has_folding_been_run = False
42
+ self.fx_const_folded_attrs_name = fx_const_folded_attrs_name
43
+ self.device_for_folded_attrs = device_for_folded_attrs
44
+
45
+ def __call__(self, *args, **kwargs):
46
+ if not self.has_folding_been_run:
47
+ self.run_folding()
48
+ return super().__call__(*args)
49
+
50
+ def run_folding(self):
51
+ # If there's no const subgraph module or attr output names to use, return
52
+ # early as there is no const folding to perform.
53
+ if (
54
+ self.const_subgraph_module is None
55
+ or self.fx_const_folded_attrs_name is None
56
+ ):
57
+ return
58
+
59
+ assert not self.has_folding_been_run
60
+ self.has_folding_been_run = True
61
+
62
+ # Actually run const folding subgraph. Note that single attr const fold
63
+ # subgraphs output a single Tensor while multiple outputs are returned as
64
+ # Tuple[Tensor,].
65
+ folded_attrs = self.const_subgraph_module()
66
+
67
+ def _create_param(i):
68
+ return torch.nn.Parameter(
69
+ i.detach().clone()
70
+ if not isinstance(i, int)
71
+ else torch.Tensor([i]).to(device=self.device_for_folded_attrs),
72
+ requires_grad=i.requires_grad if isinstance(i, torch.Tensor) else False,
73
+ )
74
+
75
+ params = (
76
+ torch.nn.ParameterList([_create_param(i) for i in folded_attrs])
77
+ if isinstance(folded_attrs, tuple)
78
+ else _create_param(folded_attrs)
79
+ )
80
+ setattr(self, self.fx_const_folded_attrs_name, params)
81
+
82
+
83
+ def _inline_module(gm: torch.fx.GraphModule, inline_mod_name: str):
84
+ """
85
+ Given `gm` and some graph module which is called with target name `inline_mod_name`,
86
+ this helper will inline all of the nodes from that called graph module into `gm`.
87
+ """
88
+ # Fetch the inner graph module that we want to inline inside `gm`.
89
+ inline_mod = dict(gm.named_modules())[inline_mod_name]
90
+ assert isinstance(inline_mod, torch.fx.GraphModule)
91
+ call_mod_node_to_replace = None
92
+ for node in gm.graph.nodes:
93
+ if node.op == "call_module" and node.target == inline_mod_name:
94
+ call_mod_node_to_replace = node
95
+ break
96
+ assert call_mod_node_to_replace is not None
97
+
98
+ # Now actually do the swap. Note that we have to keep track of new nodes that are
99
+ # copied into `gm` -- we do this via replacement_mapping.
100
+ call_mod_args = call_mod_node_to_replace.args
101
+ call_mod_kwargs = call_mod_node_to_replace.kwargs
102
+
103
+ replacement_mapping: dict[torch.fx.Node, torch.fx.Node] = {}
104
+ ph_count = 0
105
+
106
+ def replacement_fn(node):
107
+ new_node = replacement_mapping[node]
108
+ new_node.meta = node.meta.copy()
109
+ return new_node
110
+
111
+ for inline_node in inline_mod.graph.nodes:
112
+ if inline_node.op == "placeholder":
113
+ replacement_mapping[inline_node] = (
114
+ call_mod_kwargs[inline_node.name]
115
+ if inline_node.name in call_mod_kwargs
116
+ else call_mod_args[ph_count]
117
+ )
118
+
119
+ ph_count += 1
120
+ continue
121
+
122
+ if inline_node.op == "output":
123
+ outputs = inline_node.args[0]
124
+ output_replacements = map_arg(outputs, replacement_fn)
125
+ call_mod_node_to_replace.replace_all_uses_with(output_replacements)
126
+ continue
127
+
128
+ with gm.graph.inserting_before(call_mod_node_to_replace):
129
+ new_node = gm.graph.node_copy(inline_node, replacement_fn)
130
+ replacement_mapping[inline_node] = new_node
131
+
132
+ gm.graph.eliminate_dead_code()
133
+
134
+
135
+ def get_unique_attr_name_in_module(mod_traced: torch.fx.GraphModule, name: str) -> str:
136
+ """
137
+ Make sure the name is unique (in a module) and can represents an attr.
138
+ """
139
+ # Delete all characters that are illegal in a Python identifier.
140
+ name = re.sub("[^0-9a-zA-Z_]+", "_", name)
141
+ if name[0].isdigit():
142
+ name = f"_{name}"
143
+ # Now make sure it is in fact unique to the module by incrementing suffix value.
144
+ while hasattr(mod_traced, name):
145
+ match = re.match(r"(.*)_(\d+)$", name)
146
+ if match is None:
147
+ name = name + "_1"
148
+ else:
149
+ base, num = match.group(1, 2)
150
+ name = f"{base}_{int(num) + 1}"
151
+
152
+ return name
153
+
154
+
155
+ def split_const_subgraphs(
156
+ module: Union[torch.nn.Module, torch.fx.GraphModule],
157
+ skip_folding_node_fn: Optional[Callable[[torch.fx.Node], bool]] = None,
158
+ device_for_folded_attrs: str = "cpu",
159
+ ) -> FoldedGraphModule:
160
+ """
161
+ Looks through `module` for any nodes that have all constant attribute inputs
162
+ and separates them out into their own constant subgraph, and returns a
163
+ FoldedGraphModule which runs that constant subgraph on the first run to set
164
+ attributes on the module prior to running the non-constant portion of the
165
+ graph.
166
+ """
167
+ if not isinstance(module, torch.fx.GraphModule):
168
+ mod_traced = torch.fx.symbolic_trace(module)
169
+ else:
170
+ mod_traced = module
171
+
172
+ # Build up a list of const_nodes, defined as nodes that are themselves
173
+ # get_attrs, or have all get_attr or other constant node inputs.
174
+ const_nodes: set[torch.fx.Node] = set()
175
+ found_const_folding = False
176
+ for node in mod_traced.graph.nodes:
177
+ # Skip over placeholders/outputs because they can't be const folded and
178
+ # we don't want to add tags to them.
179
+ if node.op in {"placeholder", "output"}:
180
+ continue
181
+
182
+ # If the node itself is constant, or all of its inputs are constant,
183
+ # then tag it as constant.
184
+ if node.op != "get_attr" and not set(node.all_input_nodes).issubset(
185
+ const_nodes
186
+ ):
187
+ continue
188
+
189
+ # If provided skip folding function says to skip, then skip.
190
+ if skip_folding_node_fn and skip_folding_node_fn(node):
191
+ continue
192
+
193
+ # Skip folding side-effectful functions
194
+ if node.is_impure():
195
+ continue
196
+
197
+ # Must be a constant foldable node at this point.
198
+ const_nodes.add(node)
199
+ if node.op != "get_attr":
200
+ found_const_folding = True
201
+
202
+ # If we did not find any const folding then return early without a const fold subgraph.
203
+ if not found_const_folding:
204
+ return FoldedGraphModule(mod_traced, mod_traced.graph)
205
+
206
+ # Partition the module into two: submod_0 for constant folding subgraph, and
207
+ # submod_1 for the rest.
208
+ def mod_partition(node: torch.fx.Node):
209
+ return 0 if node in const_nodes else 1
210
+
211
+ split = split_module(mod_traced, module, mod_partition)
212
+
213
+ const_mod_name, non_const_mod_name = "submod_0", "submod_1"
214
+ # Safely get submod_1 in case there are no non-const nodes
215
+ const_gm, non_const_gm = split.submod_0, getattr(split, non_const_mod_name, None)
216
+
217
+ # The module that a call_module node refers to gets copied to submodules during split.
218
+ # The path to the module also gets inlined, i.e. mod.a.b -> mod_a_b. Here we need to
219
+ # attach inlined modules to `split` as it's the owning module now.
220
+ for node in non_const_gm.graph.nodes if non_const_gm else []:
221
+ if node.op == "call_module":
222
+ setattr(split, node.target, getattr(non_const_gm, node.target))
223
+ for node in const_gm.graph.nodes:
224
+ if node.op == "call_module":
225
+ setattr(split, node.target, getattr(const_gm, node.target))
226
+
227
+ # split_module currently does not use get_attrs for attrs. Instead it passes
228
+ # them in as args from the parent module, which used get_attrs. Here we set
229
+ # them as get_attrs inside const_gm, allowing for running folding without
230
+ # somehow a priori knowing the attrs that should be passed as args. We can
231
+ # unconditionally do this for all placeholders because we know all
232
+ # placeholders to const_gm must be constants accessible via get_attr.
233
+ call_const_gm_args = None
234
+ for node in split.graph.nodes:
235
+ if node.op == "call_module":
236
+ if node.target == const_mod_name:
237
+ call_const_gm_args = node.args
238
+ break
239
+ assert call_const_gm_args is not None
240
+
241
+ # Here we do the actual replacement of placeholders to get_attrs. Note that here we
242
+ # set the const_gm.graph into a new root_const_gm with split as the root module,
243
+ # because we are fetching attributes directly from the root module, instead of
244
+ # fetching them from const_gm. Example: The const_gm must have some format like:
245
+ # graph():
246
+ # %inp : [num_users=1] = placeholder[target=const_inp]
247
+ # %add : [num_users=1] = call_function[target=operator.add](args = (%inp, %inp), kwargs = {})
248
+ # return add
249
+ # We replace that with the following, which does not have any placeholders:
250
+ # graph():
251
+ # %inp_1 : [num_users=1] = get_attr[target=const_inp]
252
+ # %add : [num_users=1] = call_function[target=operator.add](args = (%inp_1, %inp_1), kwargs = {})
253
+ # return add
254
+ root_const_gm = torch.fx.GraphModule(split, const_gm.graph)
255
+ for node in root_const_gm.graph.nodes:
256
+ if node.op == "output":
257
+ multiple_outputs = isinstance(node.args[0], tuple)
258
+ continue
259
+ if node.op != "placeholder":
260
+ continue
261
+ in_node = next(n for n in call_const_gm_args if n.name == node.target)
262
+ assert in_node.op == "get_attr"
263
+ with root_const_gm.graph.inserting_before(node):
264
+ new_node = root_const_gm.graph.get_attr(in_node.target)
265
+ new_node.meta = node.meta.copy()
266
+ node.replace_all_uses_with(new_node)
267
+ root_const_gm.graph.erase_node(node)
268
+ assert "multiple_outputs" in locals()
269
+
270
+ # Now find the call to const_gm inside split, and replace it with a getattr to the
271
+ # folded tensor(s) that result from constant folding. Note that we don't need to
272
+ # worry about whether this is one or more tensors because the original graph
273
+ # correctly uses getitem to extract individual tensors if there are multiple folded.
274
+ fx_const_folded_attrs_name = get_unique_attr_name_in_module(
275
+ mod_traced, "_FX_CONST_FOLDED_ATTRS"
276
+ )
277
+ setattr(
278
+ split,
279
+ fx_const_folded_attrs_name,
280
+ torch.nn.ParameterList() if multiple_outputs else torch.nn.Parameter(), # type: ignore[possibly-undefined]
281
+ )
282
+ for node in split.graph.nodes:
283
+ if node.op == "call_module" and node.target == const_mod_name:
284
+ with node.graph.inserting_before(node):
285
+ folded_attrs = node.graph.get_attr(fx_const_folded_attrs_name)
286
+ folded_attrs.meta = node.meta.copy()
287
+ node.replace_all_uses_with(folded_attrs)
288
+ break
289
+
290
+ # Finally, inline the non-constant submod (if it exists) into the split submod.
291
+ # This is so that the original caller who may have passed in a graph module will
292
+ # get back out a graph module whose graph is traced to the same granularity.
293
+ if hasattr(split, non_const_mod_name):
294
+ _inline_module(split, non_const_mod_name)
295
+
296
+ split.graph.eliminate_dead_code()
297
+
298
+ return FoldedGraphModule(
299
+ split,
300
+ split.graph,
301
+ root_const_gm.graph,
302
+ fx_const_folded_attrs_name,
303
+ device_for_folded_attrs,
304
+ )