Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / compile / mixed_precision.py: 90%

58 statements  

« 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"""Capture the existing FSDP precision policy in a joint graph.""" 

16 

17from contextlib import ExitStack, contextmanager 

18from dataclasses import is_dataclass 

19from functools import partial 

20from typing import Any, Callable, Iterator 

21 

22import torch 

23from torch import nn 

24from torch.utils._pytree import tree_flatten, tree_map, tree_unflatten 

25 

26from hyper_parallel.core.fully_shard.utils import ( 

27 MixedPrecisionPolicy, 

28 apply_to_tensors, 

29 cast_fp_tensor, 

30 resolve_param_dtypes, 

31) 

32 

33 

34def _cast_input_leaf(cast: Callable, value: Any) -> Any: 

35 """Cast graph leaves while preserving opaque state and unchanged dataclasses.""" 

36 if not is_dataclass(value): 

37 return cast(value) 

38 leaves, spec = tree_flatten(value) 

39 converted = [cast(leaf) for leaf in leaves] 

40 if all(before is after for before, after in zip(leaves, converted)): 

41 return value 

42 return tree_unflatten(converted, spec) 

43 

44 

45class GraphMixedPrecision: 

46 """Describe casts without changing the live parameter storage.""" 

47 

48 def __init__(self, model: nn.Module, policy: MixedPrecisionPolicy, modules: tuple[nn.Module, ...]) -> None: 

49 """Bind the resolved eager policy before the graph pass slices parameters.""" 

50 self.policy = policy 

51 self.modules = modules 

52 self.parameter_dtypes = {} 

53 for name, parameter in model.named_parameters(remove_duplicate=False): 

54 if not parameter.is_floating_point(): 

55 continue 

56 compute, reduce = resolve_param_dtypes(policy, id(parameter), parameter.dtype) 

57 # Autograd returns the gradient in the compute weight's dtype. 

58 if reduce == (compute or parameter.dtype): 

59 reduce = None 

60 self.parameter_dtypes[name] = (compute, reduce) 

61 

62 @property 

63 def has_param_or_grad_casts(self) -> bool: 

64 """Whether FSDP parameters or their gradients need a different dtype.""" 

65 return any(compute is not None or reduce is not None for compute, reduce in self.parameter_dtypes.values()) 

66 

67 def cast_state(self, state: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]: 

68 """Differentiate the same compute-precision weights that forward reads.""" 

69 compute_state = state.copy() 

70 for name, (dtype, _) in self.parameter_dtypes.items(): 

71 if dtype is not None and name in state: 

72 compute_state[name] = cast_fp_tensor(dtype, state[name]) 

73 return compute_state 

74 

75 def cast_gradient(self, name: str, gradient: torch.Tensor) -> torch.Tensor: 

76 """Convert to the reduction dtype even if no collective is needed.""" 

77 _, dtype = self.parameter_dtypes.get(name, (None, None)) 

78 return cast_fp_tensor(dtype, gradient) if dtype is not None else gradient 

79 

80 @contextmanager 

81 def module_casts(self) -> Iterator[None]: 

82 """Install input/output conversions only while the graph is captured.""" 

83 with ExitStack() as stack: 

84 for module in self.modules: 

85 if self.policy.cast_forward_inputs and self.policy.param_dtype is not None: 

86 handle = module.register_forward_pre_hook(self._cast_inputs, with_kwargs=True) 

87 stack.callback(handle.remove) 

88 if self.policy.output_dtype is not None: 

89 handle = module.register_forward_hook(self._cast_outputs) 

90 stack.callback(handle.remove) 

91 yield 

92 

93 def _cast_inputs(self, module: nn.Module, args: tuple, kwargs: dict) -> tuple: 

94 """Capture casts of the floating arguments at the eager unit boundary.""" 

95 del module 

96 cast = partial(cast_fp_tensor, self.policy.param_dtype) 

97 return tree_map(partial(_cast_input_leaf, cast), (args, kwargs), is_leaf=is_dataclass) 

98 

99 def _cast_outputs(self, module: nn.Module, args: tuple, output: Any) -> Any: 

100 """Capture the eager unit's output conversion.""" 

101 del module, args 

102 return apply_to_tensors(partial(cast_fp_tensor, self.policy.output_dtype), output)