spmd-types 0.2.1__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.
spmd_types/__init__.py ADDED
@@ -0,0 +1,109 @@
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # spmd_types package
8
+ from __future__ import annotations
9
+
10
+ from spmd_types._backward_hooks import ( # noqa: F401
11
+ register_local_backward_hook,
12
+ )
13
+ from spmd_types._collectives import ( # noqa: F401
14
+ all_gather,
15
+ all_reduce,
16
+ all_to_all,
17
+ redistribute,
18
+ reduce_scatter,
19
+ unshard,
20
+ )
21
+ from spmd_types._dist import set_dist # noqa: F401
22
+ from spmd_types._dtensor import ( # noqa: F401
23
+ dtensor_placement_to_spmd_type,
24
+ spmd_redistribute,
25
+ spmd_type_to_dtensor_placement,
26
+ )
27
+ from spmd_types._local import ( # noqa: F401
28
+ convert,
29
+ invariant_to_replicate,
30
+ reinterpret,
31
+ shard,
32
+ )
33
+ from spmd_types._mesh import set_current_mesh # noqa: F401
34
+ from spmd_types._mesh_axis import MeshAxis # noqa: F401
35
+
36
+ # reinterpret_mesh lives in its own module
37
+ from spmd_types._reinterpret_mesh import reinterpret_mesh # noqa: F401
38
+ from spmd_types._scalar import Scalar # noqa: F401
39
+ from spmd_types._state import ( # noqa: F401
40
+ current_mesh,
41
+ current_mesh_all_names,
42
+ current_mesh_names,
43
+ is_type_checking,
44
+ no_typecheck,
45
+ )
46
+ from spmd_types._traceback import traceback_filtering # noqa: F401
47
+ from spmd_types._type_attr import ( # noqa: F401
48
+ get_axis_local_type,
49
+ get_local_type,
50
+ maybe_get_axis_local_type,
51
+ )
52
+
53
+ # Collectives and operations -- runtime API (no _checker dependency)
54
+ from spmd_types.runtime import ( # noqa: F401
55
+ assert_local_type,
56
+ assert_type,
57
+ assert_type_like,
58
+ Infer,
59
+ local,
60
+ local_map,
61
+ mutate_type,
62
+ register_autograd_function,
63
+ register_decomposition,
64
+ register_local_autograd_function,
65
+ trace,
66
+ )
67
+
68
+ # Types
69
+ from spmd_types.types import ( # noqa: F401
70
+ DimSharding,
71
+ I,
72
+ Invariant,
73
+ LocalSpmdType,
74
+ normalize_axis,
75
+ normalize_mesh,
76
+ normalize_partition_spec,
77
+ P,
78
+ Partial,
79
+ PartitionSpec,
80
+ PerMeshAxisLocalSpmdType,
81
+ PerMeshAxisSpmdType,
82
+ PerMeshAxisSpmdTypes,
83
+ R,
84
+ Replicate,
85
+ S,
86
+ Shard,
87
+ SpmdTypeError,
88
+ TensorSharding,
89
+ V,
90
+ Varying,
91
+ )
92
+
93
+
94
+ class _TypeCheckingSentinel:
95
+ """Singleton whose bool value reflects whether type checking is active.
96
+
97
+ ``bool(TYPE_CHECKING)`` returns True when a ``typecheck()`` context is
98
+ active on the current thread, False otherwise. This avoids the
99
+ sys.modules replacement trick which breaks torch.compile / Dynamo.
100
+ """
101
+
102
+ def __bool__(self) -> bool:
103
+ return is_type_checking()
104
+
105
+ def __repr__(self) -> str:
106
+ return f"TYPE_CHECKING({is_type_checking()})"
107
+
108
+
109
+ TYPE_CHECKING = _TypeCheckingSentinel()
@@ -0,0 +1,133 @@
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Per-hook SPMD type-propagation registry for nn.Module backward hooks.
8
+
9
+ BackwardHookFunction (nn.Module.register_full_backward_hook) has a pure
10
+ pass-through forward. Each user hook callable must be explicitly registered
11
+ via ``register_local_backward_hook`` to declare that it does not alter SPMD
12
+ types; unregistered hooks raise SpmdTypeError when type checking is active.
13
+
14
+ TODO: a per-hook rule API (for hooks that do collectives on grads, e.g.
15
+ all-reduce flipping I -> R) can be added later when a real use case
16
+ motivates the exact shape.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from collections.abc import Callable
22
+
23
+ import torch
24
+ import torch.utils.hooks as _torch_hooks
25
+ from spmd_types._state import is_type_checking
26
+ from spmd_types.runtime import (
27
+ _set_partition_spec,
28
+ assert_type_like,
29
+ get_partition_spec,
30
+ )
31
+ from spmd_types.types import SpmdTypeError
32
+ from torch.nn.modules._functions import BackwardHookFunction
33
+
34
+ _LOCAL_BACKWARD_HOOKS: set[Callable] = set()
35
+
36
+
37
+ def register_local_backward_hook(fn: Callable) -> Callable:
38
+ """Declare that ``fn`` does not alter SPMD types when it runs in backward.
39
+
40
+ Analogous to :func:`register_local_autograd_function`: the hook's backward
41
+ is treated as local (no collectives, no type-changing effects on grads).
42
+ Side-agnostic: covers both ``register_full_backward_hook`` (post) and
43
+ ``register_full_backward_pre_hook`` (pre) use. Usable as a decorator.
44
+ """
45
+ _LOCAL_BACKWARD_HOOKS.add(fn)
46
+ return fn
47
+
48
+
49
+ def _validate(hooks):
50
+ if not is_type_checking():
51
+ return
52
+ for fn in hooks:
53
+ if fn in _LOCAL_BACKWARD_HOOKS:
54
+ continue
55
+ raise SpmdTypeError(
56
+ f"Backward hook {getattr(fn, '__qualname__', fn)!r} attached to "
57
+ f"nn.Module is not registered for SPMD type propagation. Call "
58
+ f"register_local_backward_hook(fn) if the hook does not alter "
59
+ f"gradient SPMD types."
60
+ )
61
+
62
+
63
+ def _apply_types(hooks, inputs, outputs):
64
+ """Copy SPMD annotations across BackwardHookFunction wrappers.
65
+
66
+ BackwardHookFunction.apply creates fresh tensor objects for module
67
+ backward hooks. Registered local hooks are semantically pass-through, so
68
+ their wrapper tensors should keep the input SPMD metadata.
69
+ """
70
+ if not isinstance(inputs, tuple):
71
+ inputs = (inputs,)
72
+ if not isinstance(outputs, tuple):
73
+ outputs = (outputs,)
74
+
75
+ for fn in hooks:
76
+ if fn in _LOCAL_BACKWARD_HOOKS:
77
+ for inp, out in zip(inputs, outputs):
78
+ if isinstance(inp, torch.Tensor) and isinstance(out, torch.Tensor):
79
+ spec = get_partition_spec(inp)
80
+ assert_type_like(out, inp)
81
+ if spec is not None:
82
+ _set_partition_spec(out, spec)
83
+
84
+
85
+ _orig_setup_input_hook = None
86
+ _orig_setup_output_hook = None
87
+
88
+
89
+ def _patched_setup_input_hook(self, input):
90
+ _validate(self.user_hooks)
91
+ result = _orig_setup_input_hook(self, input)
92
+ _apply_types(self.user_hooks, input, result)
93
+ _apply_types(self.user_pre_hooks, input, result)
94
+ return result
95
+
96
+
97
+ def _patched_setup_output_hook(self, output):
98
+ _validate(self.user_pre_hooks)
99
+ result = _orig_setup_output_hook(self, output)
100
+ _apply_types(self.user_pre_hooks, output, result)
101
+ _apply_types(self.user_hooks, output, result)
102
+ return result
103
+
104
+
105
+ def install() -> None:
106
+ """Install the BackwardHook monkey-patch. Idempotent."""
107
+ global _orig_setup_input_hook, _orig_setup_output_hook
108
+
109
+ if _orig_setup_input_hook is not None:
110
+ return
111
+
112
+ from spmd_types._checker import register_autograd_function
113
+
114
+ BackwardHookFunction.typecheck_forward = staticmethod(BackwardHookFunction.apply)
115
+ register_autograd_function(BackwardHookFunction)
116
+
117
+ _orig_setup_input_hook = _torch_hooks.BackwardHook.setup_input_hook
118
+ _orig_setup_output_hook = _torch_hooks.BackwardHook.setup_output_hook
119
+ _torch_hooks.BackwardHook.setup_input_hook = _patched_setup_input_hook
120
+ _torch_hooks.BackwardHook.setup_output_hook = _patched_setup_output_hook
121
+
122
+
123
+ def uninstall() -> None:
124
+ """Remove the BackwardHook monkey-patch. Idempotent."""
125
+ global _orig_setup_input_hook, _orig_setup_output_hook
126
+
127
+ if _orig_setup_input_hook is None:
128
+ return
129
+
130
+ _torch_hooks.BackwardHook.setup_input_hook = _orig_setup_input_hook
131
+ _torch_hooks.BackwardHook.setup_output_hook = _orig_setup_output_hook
132
+ _orig_setup_input_hook = None
133
+ _orig_setup_output_hook = None