Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / encoder_parallel / attention.py: 98%

40 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"""Encoder attention segments and exact execution auditing.""" 

16 

17from __future__ import annotations 

18 

19from contextlib import AbstractContextManager, contextmanager, nullcontext 

20from contextvars import ContextVar 

21from dataclasses import dataclass, field, replace 

22from typing import Iterator, Mapping 

23 

24from hyper_parallel.core.dtensor.device_mesh import DeviceMesh 

25from hyper_parallel.distributed.encoder_parallel.contracts import EncoderSegment 

26 

27 

28@dataclass 

29class EncoderAttentionContext: 

30 """One ViT pass: segment boundaries, Ulysses mesh, and call audit.""" 

31 

32 segments: tuple[EncoderSegment, ...] 

33 cp_mesh: DeviceMesh 

34 declared_heads: Mapping[str, int] 

35 expected: frozenset[str] 

36 seen: dict[str, int] = field(default_factory=dict) 

37 packed_sequence_lengths: tuple[int, ...] | None = None 

38 overlap: bool = False 

39 

40 def record(self, module_fqn: str) -> None: 

41 """Record one replacement invocation. 

42 

43 Args: 

44 module_fqn: Final module path for the attention block. 

45 """ 

46 self.seen[module_fqn] = self.seen.get(module_fqn, 0) + 1 

47 

48 def assert_exactly_once(self) -> None: 

49 """Reject missing or repeated calls in an active ViT pass.""" 

50 if set(self.seen) != self.expected or any(count != 1 for count in self.seen.values()): 

51 raise RuntimeError( 

52 "vision attention execution mismatch; " 

53 f"expected={sorted(self.expected)}; seen={self.seen}" 

54 ) 

55 

56 def validate_runtime_head_counts(self, *, module_fqn: str, query_heads: int, 

57 key_heads: int, value_heads: int) -> None: 

58 """Check projected head counts before entering a collective.""" 

59 actual = {"query": query_heads, "key": key_heads, "value": value_heads} 

60 if actual != self.declared_heads or any(count % self.cp_mesh.size() for count in actual.values()): 

61 raise ValueError( 

62 "Ulysses runtime head count mismatch; phase=runtime; " 

63 f"module_fqn={module_fqn}; declared_head_counts={self.declared_heads}; " 

64 f"runtime_head_counts={actual}; encoder_cp_size={self.cp_mesh.size()}" 

65 ) 

66 

67 

68_ACTIVE_CONTEXT: ContextVar[EncoderAttentionContext | None] = ContextVar("encoder_attention_context", default=None) 

69 

70 

71def current_encoder_attention_context() -> EncoderAttentionContext | None: 

72 """Return the complete attention state for the current ViT pass.""" 

73 return _ACTIVE_CONTEXT.get() 

74 

75 

76@contextmanager 

77def activate_encoder_attention(context: EncoderAttentionContext) -> Iterator[EncoderAttentionContext]: 

78 """Scope attention work and its exact-call audit to one packed ViT pass. 

79 

80 Args: 

81 context: Segments, executor, and expected module paths for this pass. 

82 """ 

83 token = _ACTIVE_CONTEXT.set(context) 

84 try: 

85 yield context 

86 finally: 

87 _ACTIVE_CONTEXT.reset(token) 

88 

89 

90def encoder_attention_checkpoint_contexts() -> tuple[AbstractContextManager, AbstractContextManager]: 

91 """Retain one forward's Encoder-CP metadata for checkpoint replay. 

92 

93 Each checkpoint invocation owns its replay audit. Recomputing an earlier 

94 microbatch must neither use a later batch's segments nor change its audit. 

95 """ 

96 context = current_encoder_attention_context() 

97 if context is None: 

98 return nullcontext(), nullcontext() 

99 replay = replace(context, seen={}) 

100 return nullcontext(), activate_encoder_attention(replay)