Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / tools / dryrun / patches / trainer / host_scalar.py: 100%

65 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"""Training-flow host-scalar shim and token-count binding for FakeTensors.""" 

16 

17from contextlib import AbstractContextManager, contextmanager 

18from typing import Any, Callable, Dict, Iterator, Mapping 

19 

20import torch 

21from torch.overrides import TorchFunctionMode 

22 

23 

24class FakeHostScalarShim(AbstractContextManager): 

25 """Resolve host-scalar reads on FakeTensors with probe-derived values. 

26 

27 The Trainer step loop reads host scalars (``loss.item()``, token counts for 

28 gradient normalization, ``grad_norm.item()``). This scope resolves scalar 

29 reads on FakeTensors to probe-known values when registered and ``0.0`` 

30 otherwise; real tensors pass through unchanged. 

31 """ 

32 

33 def __init__(self) -> None: 

34 """Create the scope without activating it.""" 

35 resolve = self._resolve 

36 resolve_scalar = self._resolve_scalar 

37 

38 class _Mode(TorchFunctionMode): 

39 """Intercept host-scalar reads before FakeTensor rejects them.""" 

40 

41 def __torch_function__(self, func, types, args=(), kwargs=None): 

42 del types 

43 kwargs = kwargs or {} 

44 if args and hasattr(args[0], "fake_mode"): 

45 name = getattr(func, "__name__", "") 

46 if func is torch.Tensor.item: 

47 return resolve_scalar(args[0]) 

48 if name == "__float__": 

49 return float(resolve(args[0])) 

50 if name in ("__int__", "__index__"): 

51 return int(resolve(args[0])) 

52 if name == "__bool__": 

53 return bool(resolve(args[0])) 

54 return func(*args, **kwargs) 

55 

56 self._mode = _Mode() 

57 self._known: Dict[int, float] = {} 

58 

59 def register(self, tensor: Any, value: float) -> None: 

60 """Pin a probe-derived host value onto one FakeTensor identity. 

61 

62 Args: 

63 tensor: FakeTensor whose host reads are resolved. 

64 value: Probe-observed host value for ``tensor``. 

65 """ 

66 self._known[id(tensor)] = float(value) 

67 

68 def clear(self) -> None: 

69 """Forget pinned values from a consumed batch before ids are reused.""" 

70 self._known.clear() 

71 

72 def _resolve(self, tensor: Any) -> float: 

73 """Return the pinned value for ``tensor``, or zero otherwise.""" 

74 return self._known.get(id(tensor), 0.0) 

75 

76 def _resolve_scalar(self, tensor: Any) -> Any: 

77 """Return the pinned value cast to the tensor's Python scalar type.""" 

78 value = self._resolve(tensor) 

79 if tensor.dtype is torch.bool: 

80 return bool(value) 

81 if not tensor.is_floating_point() and not tensor.is_complex(): 

82 return int(value) 

83 return float(value) 

84 

85 def __enter__(self) -> "FakeHostScalarShim": 

86 """Activate scalar interception.""" 

87 self._mode.__enter__() 

88 return self 

89 

90 def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> bool: 

91 """Deactivate scalar interception.""" 

92 self._mode.__exit__(exc_type, exc_value, traceback) 

93 return False 

94 

95 

96@contextmanager 

97def token_count_scalar_context( 

98 get_token_counts: Callable[[], Mapping[str, int]], 

99 scalar_shim: FakeHostScalarShim, 

100) -> Iterator[None]: 

101 """Bind real CPU token counts onto fake scalar outputs of ``count_loss_token``. 

102 

103 Args: 

104 get_token_counts: Zero-argument callable returning the active batch's 

105 CPU-derived token count mapping. 

106 scalar_shim: Active :class:`FakeHostScalarShim` receiving the pinned counts. 

107 """ 

108 # Lazy import keeps FakeHostScalarShim usable without optional trainer/transformers deps. 

109 from hyper_parallel.trainer import base as base_module # pylint: disable=import-outside-toplevel 

110 from hyper_parallel.trainer import text_trainer as text_trainer_module # pylint: disable=import-outside-toplevel 

111 from hyper_parallel.trainer.runtime.loss_aggregation import count_loss_token # pylint: disable=import-outside-toplevel 

112 

113 original_base_count = base_module.count_loss_token 

114 original_text_count = text_trainer_module.count_loss_token 

115 

116 def counted(batches: Any) -> dict: 

117 """Recompute fake count tensors, then pin their real CPU host values.""" 

118 result = count_loss_token(batches) 

119 known = get_token_counts() 

120 for name, tensor in result.items(): 

121 if hasattr(tensor, "fake_mode") and name in known: 

122 scalar_shim.register(tensor, known[name]) 

123 return result 

124 

125 base_module.count_loss_token = counted 

126 text_trainer_module.count_loss_token = counted 

127 try: 

128 yield 

129 finally: 

130 base_module.count_loss_token = original_base_count 

131 text_trainer_module.count_loss_token = original_text_count 

132 

133 

134__all__ = [ 

135 "FakeHostScalarShim", 

136 "token_count_scalar_context", 

137]