Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / auto_parallel / hyper_offload / execution / framework.py: 96%
46 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
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"""Export framework reads without adopting framework-owned tensor storage."""
17from typing import Any
19import torch
20from torch.utils._pytree import tree_iter, tree_map
22from hyper_parallel.auto_parallel.hyper_offload.execution.tensor import ShadowTensor
25def dispatch_framework_read(executor: Any, func: Any, args: tuple, kwargs: dict, *, native_inputs: bool = False) -> Any:
26 """Record a framework read while keeping its outputs outside activation ownership.
28 Args:
29 executor: Active warmup or replay executor.
30 func: Framework-owned tensor operation.
31 args: Positional operation inputs.
32 kwargs: Keyword operation inputs.
33 native_inputs: Whether all tensor inputs are outside managed ownership.
34 """
35 output = None
37 def framework_read(*inputs: Any, **options: Any) -> tuple:
38 """Expose input lifetimes without adopting framework-owned outputs.
40 Args:
41 inputs: Positional operation inputs.
42 options: Keyword operation inputs.
43 """
44 nonlocal output
45 output = func(*inputs, **options) if native_inputs else dispatch_framework_op(func, inputs, options)
46 recorder = getattr(executor, "record_framework_allocation", None)
47 if recorder is not None:
48 input_storages = {
49 value.untyped_storage()._cdata # pylint: disable=protected-access
50 for value in tree_iter((inputs, options))
51 if isinstance(value, torch.Tensor)
52 }
53 allocated = {
54 value.untyped_storage()._cdata: value.untyped_storage().nbytes() # pylint: disable=protected-access
55 for value in tree_iter(output) if isinstance(value, torch.Tensor)
56 and value.untyped_storage()._cdata not in input_storages # pylint: disable=protected-access
57 }
58 recorder(sum(allocated.values()))
59 return ()
61 framework_read.__name__ = "framework_read:" + func.__name__
62 if hasattr(func, "_schema"):
63 framework_read._schema = func._schema # pylint: disable=protected-access
64 executor.dispatch(framework_read, args, kwargs)
65 return output
68def dispatch_framework_op(func: Any, args: tuple, kwargs: dict) -> Any:
69 """Export activation views to framework-owned storage at the dispatch boundary.
71 FSDP may resize collective inputs after communication. Alias outputs must
72 therefore own independent storage; writes still update the original inputs.
73 Cloning entire byte storages preserves offsets and aliases among outputs.
75 Args:
76 func: Framework-owned tensor operation.
77 args: Positional operation inputs.
78 kwargs: Keyword operation inputs.
79 """
80 activation_storages = set()
82 def unwrap(value: Any) -> Any:
83 """Resolve managed inputs while recording their source storage.
85 Args:
86 value: Input tree leaf.
87 """
88 if not isinstance(value, ShadowTensor):
89 return value
90 resolved = value.resolve()
91 activation_storages.add(resolved.untyped_storage())
92 return resolved
94 # Only local materialization bypasses modes. The framework op itself still
95 # passes through any unrelated dispatch mode installed below this one.
96 with torch._C._DisableTorchDispatch(): # pylint: disable=protected-access
97 real_args, real_kwargs = tree_map(unwrap, (args, kwargs))
98 result = func(*real_args, **real_kwargs)
99 owned = {}
101 def export(value: Any) -> Any:
102 """Give aliased outputs storage owned by the framework caller.
104 Args:
105 value: Output tree leaf.
106 """
107 if not isinstance(value, torch.Tensor):
108 return value
109 storage = value.untyped_storage()
110 if storage not in activation_storages:
111 return value
112 if storage not in owned:
113 raw = torch.empty(0, dtype=torch.uint8, device=value.device)
114 raw.set_(storage, 0, (storage.nbytes(),), (1,))
115 owned[storage] = raw.clone()
116 output = torch.empty(0, dtype=value.dtype, device=value.device)
117 output.set_(owned[storage].untyped_storage(), value.storage_offset(), value.size(), value.stride())
118 return output
120 with torch._C._DisableTorchDispatch(): # pylint: disable=protected-access
121 return tree_map(export, result)