Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / high_availability / replica_transport.py: 96%

137 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"""Direct device tensor repair; only rank-owned metadata is mirrored during training.""" 

16 

17import io 

18from datetime import timedelta 

19from typing import Any 

20 

21import torch 

22import torch.distributed as dist 

23 

24from hyper_parallel.high_availability.recovery_state import local_tensor 

25 

26_TRANSFER_CHUNK_BYTES = 4 * 1024 * 1024 

27_METADATA_TIMEOUT_SECONDS = 10 

28 

29 

30def serialize_metadata(value: Any) -> bytes: 

31 """Serialize Python training metadata, never model weights or optimizer moments.""" 

32 stream = io.BytesIO() 

33 torch.save(value, stream) 

34 return stream.getvalue() 

35 

36 

37def deserialize_metadata(encoded_metadata: torch.Tensor) -> Any: 

38 """Decode a serialized byte tensor from a trusted peer into CPU metadata.""" 

39 payload = encoded_metadata.cpu().numpy().tobytes() 

40 return torch.load(io.BytesIO(payload), map_location="cpu", weights_only=False) 

41 

42 

43def metadata_to_device(value: Any, device: torch.device) -> torch.Tensor: 

44 """Place serialized metadata in a device byte buffer.""" 

45 return torch.frombuffer(bytearray(serialize_metadata(value)), dtype=torch.uint8).to(device) 

46 

47 

48class DeviceMetadataBank: 

49 """Retain one committed metadata and buffer snapshot per rank for the live weights.""" 

50 

51 def __init__(self, rank: int, device: torch.device) -> None: 

52 """Keep local metadata unencoded alongside CPU buffer snapshots.""" 

53 self.rank = rank 

54 self.device = device 

55 self._rank_snapshots = {} 

56 self._replica_snapshot = None 

57 

58 def put_snapshot(self, step: int, rank_metadata: dict[str, Any], replica_state: dict[str, Any]) -> None: 

59 """Take ownership of an independent snapshot without copying it again. 

60 

61 Args: 

62 step: Committed training step represented by this snapshot. 

63 rank_metadata: Independently captured or decoded rank metadata including CPU 

64 buffer snapshots. The caller must not mutate snapshot values after this call. 

65 replica_state: Independent same-step state shared by full replicas, no longer 

66 mutated by the caller after this call. 

67 """ 

68 self.store_rank_snapshot(self.rank, step, rank_metadata) 

69 self._replica_snapshot = {"step": step, "state": replica_state} 

70 

71 def store_rank_snapshot( 

72 self, 

73 owner: int, 

74 step: int, 

75 rank_metadata: dict[str, Any], 

76 ) -> None: 

77 """Replace rank metadata with owned metadata and CPU buffer snapshots.""" 

78 self._rank_snapshots[owner] = { 

79 "step": step, 

80 "rank_metadata": rank_metadata, 

81 } 

82 

83 def get_rank_metadata(self, owner: int, step: int) -> dict[str, Any]: 

84 """Return rank metadata only when the stored snapshot matches the exact owner and step.""" 

85 rank_snapshot = self._rank_snapshots.get(owner) 

86 if rank_snapshot is None or rank_snapshot["step"] != step: 

87 raise RuntimeError(f"exact training metadata unavailable: owner={owner}, step={step}") 

88 return rank_snapshot["rank_metadata"] 

89 

90 def get_replica_state(self, step: int) -> dict[str, Any]: 

91 """Return the local replica-provider snapshot for the exact committed step. 

92 

93 Args: 

94 step: Exact committed step required for the replica providers. 

95 

96 Returns: 

97 Read-only replica state. Restore adapters copy at load boundaries. 

98 """ 

99 if self._replica_snapshot is None or self._replica_snapshot["step"] != step: 

100 raise RuntimeError(f"exact replica provider metadata unavailable: step={step}") 

101 return self._replica_snapshot["state"] 

102 

103 

104class ReplicaTransport: 

105 """Send the donor's live device model/main/moment tensors directly over HCCL.""" 

106 

107 def __init__( 

108 self, 

109 group: Any, 

110 bank: DeviceMetadataBank, 

111 state: Any, 

112 device: torch.device, 

113 mirror_metadata: bool = True, 

114 ) -> None: 

115 """Bind the exact replica collective group and persistent live device state.""" 

116 self.group = group 

117 self.metadata_bank = bank 

118 self.state = state 

119 self.device = device 

120 self.ranks = tuple(dist.get_process_group_ranks(group)) 

121 self._mirror_metadata = mirror_metadata 

122 

123 @staticmethod 

124 def _wait(work: Any) -> None: 

125 try: 

126 work.wait(timeout=timedelta(seconds=_METADATA_TIMEOUT_SECONDS)) 

127 except RuntimeError as error: 

128 raise RuntimeError("SUSPECT REMOTE ERROR: training metadata communication failed") from error 

129 

130 def mirror_metadata(self, step: int) -> None: 

131 """Mirror RNG/cursor and rank-local buffers; never mirror parameter or moment values. 

132 

133 Args: 

134 step: Exact committed step whose rank metadata must be mirrored. 

135 """ 

136 if not self._mirror_metadata: 

137 return 

138 rank_metadata = self.metadata_bank.get_rank_metadata(self.metadata_bank.rank, step) 

139 training_metadata = {name: value for name, value in rank_metadata.items() if name != "buffers"} 

140 encoded_metadata = metadata_to_device(training_metadata, self.device) 

141 size = torch.tensor([encoded_metadata.numel()], dtype=torch.int64, device=self.device) 

142 sizes = [torch.empty_like(size) for _ in self.ranks] 

143 self._wait(dist.all_gather(sizes, size, group=self.group, async_op=True)) 

144 lengths = [int(value.item()) for value in sizes] 

145 if encoded_metadata.numel() < max(lengths): 

146 padded = torch.empty(max(lengths), dtype=torch.uint8, device=self.device) 

147 padded[:encoded_metadata.numel()].copy_(encoded_metadata) 

148 padded[encoded_metadata.numel():].zero_() 

149 encoded_metadata = padded 

150 gathered_metadata = [torch.empty_like(encoded_metadata) for _ in self.ranks] 

151 self._wait(dist.all_gather(gathered_metadata, encoded_metadata, group=self.group, async_op=True)) 

152 buffers = [{} for _ in self.ranks] 

153 for name, tensor in rank_metadata["buffers"].items(): 

154 communication_tensor = tensor.to(device=self.device).contiguous() 

155 values = [torch.empty_like(communication_tensor) for _ in self.ranks] 

156 self._wait(dist.all_gather(values, communication_tensor, group=self.group, async_op=True)) 

157 for owner, saved, value in zip(self.ranks, buffers, values): 

158 if owner != self.metadata_bank.rank: 

159 saved[name] = value.cpu() 

160 for owner, length, value, saved in zip(self.ranks, lengths, gathered_metadata, buffers): 

161 if owner != self.metadata_bank.rank: 

162 peer_metadata = deserialize_metadata(value[:length]) 

163 peer_metadata["buffers"] = saved 

164 self.metadata_bank.store_rank_snapshot(owner, step, peer_metadata) 

165 self._wait(dist.barrier(group=self.group, async_op=True)) 

166 

167 def _send_tensor(self, tensor: torch.Tensor, destination: int, group: Any = None) -> None: 

168 """Send live storage with at most one CPU-to-device staging block.""" 

169 flat = tensor.detach().contiguous().view(-1) 

170 chunk = max(1, _TRANSFER_CHUNK_BYTES // tensor.element_size()) 

171 for start in range(0, flat.numel(), chunk): 

172 # Host tables can exceed device memory; stage only the current block. 

173 dist.send( 

174 flat[start:start + chunk].to(device=self.device), 

175 dst=destination, 

176 group=group, 

177 ) 

178 

179 @torch.no_grad() 

180 def _receive_tensor(self, tensor: torch.Tensor, source: int, group: Any = None) -> None: 

181 """Receive bounded device blocks and write them into the original destination storage.""" 

182 target = tensor if tensor.is_contiguous() else torch.empty_like(tensor, memory_format=torch.contiguous_format) 

183 flat = target.view(-1) 

184 chunk = max(1, _TRANSFER_CHUNK_BYTES // tensor.element_size()) 

185 staging = (torch.empty(min(chunk, flat.numel()), dtype=tensor.dtype, device=self.device) 

186 if tensor.device != self.device else None) 

187 for start in range(0, flat.numel(), chunk): 

188 destination = flat[start:start + chunk] 

189 block = destination if staging is None else staging[:destination.numel()] 

190 dist.recv(block, src=source, group=group) 

191 if staging is not None: 

192 destination.copy_(block) 

193 if target is not tensor: 

194 tensor.copy_(target) 

195 

196 def send(self, destination: int, step: int, group: Any = None) -> None: 

197 """Send metadata, then the donor's current device tensors, never a stored weight copy. 

198 

199 Args: 

200 destination: Global rank of the replacement full replica. 

201 step: Exact committed step selected by MindIO. 

202 group: MindIO-selected temporary repair group, or the default group. 

203 """ 

204 if destination not in self.ranks or destination == self.metadata_bank.rank: 

205 raise ValueError("destination is not an equivalent device replica") 

206 owner = destination if self._mirror_metadata else self.metadata_bank.rank 

207 rank_metadata = self.metadata_bank.get_rank_metadata(owner, step) 

208 training_metadata = { 

209 "state": { 

210 "rank_state": rank_metadata["rank_state"], 

211 "replica_state": self.metadata_bank.get_replica_state(step), 

212 }, 

213 "extra": rank_metadata["extra"], 

214 } 

215 header = { 

216 "optimizer": self.state.metadata(), 

217 "training": training_metadata, 

218 "owner": destination, 

219 "step": step 

220 } 

221 encoded_metadata = metadata_to_device(header, self.device) 

222 dist.send(torch.tensor([encoded_metadata.numel()], dtype=torch.int64, device=self.device), 

223 dst=destination, group=group) 

224 self._send_tensor(encoded_metadata, destination, group) 

225 for _, tensor in self.state.tensor_items(): 

226 self._send_tensor(tensor, destination, group) 

227 for tensor in rank_metadata["buffers"].values(): 

228 self._send_tensor(tensor, destination, group) 

229 

230 def receive(self, source: int, step: int, group: Any = None) -> None: 

231 """Receive weights directly into device storage, rebuilding optimizer slots in place. 

232 

233 Args: 

234 source: Global rank of the full device-state donor selected by MindIO. 

235 step: Exact committed step selected by MindIO. 

236 group: MindIO-selected temporary repair group, or the default group. 

237 """ 

238 if source not in self.ranks or source == self.metadata_bank.rank: 

239 raise ValueError("source is not an equivalent device replica") 

240 length = torch.empty(1, dtype=torch.int64, device=self.device) 

241 dist.recv(length, src=source, group=group) 

242 if length.item() <= 0: 

243 raise RuntimeError("empty device repair header") 

244 encoded_metadata = torch.empty(int(length.item()), dtype=torch.uint8, device=self.device) 

245 self._receive_tensor(encoded_metadata, source, group) 

246 header = deserialize_metadata(encoded_metadata) 

247 if header["owner"] != self.metadata_bank.rank or header["step"] != step: 

248 raise RuntimeError("repair metadata belongs to another logical rank or step") 

249 self.state.prepare_receive(header["optimizer"]) 

250 for _, tensor in self.state.tensor_items(): 

251 self._receive_tensor(tensor, source, group) 

252 buffers = { 

253 name: torch.empty_like(local_tensor(buffer), device="cpu") 

254 for name, buffer in self.state.buffers.items() 

255 } 

256 for tensor in buffers.values(): 

257 self._receive_tensor(tensor, source, group) 

258 training_metadata = header["training"] 

259 training_state = training_metadata["state"] 

260 rank_metadata = { 

261 "rank_state": training_state["rank_state"], 

262 "extra": training_metadata["extra"], 

263 "buffers": buffers, 

264 } 

265 self.metadata_bank.put_snapshot(step, rank_metadata, training_state["replica_state"])