Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / checkpoint / hf_storage.py: 98%

135 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"""Safetensors checkpoints written outside DCP, loaded through the DCP read path. 

16 

17Two kinds of directory are read, each by a reader of its own, since what makes a directory of one 

18kind valid makes one of the other kind wrong: 

19 

20* :class:`HuggingFaceStorageReader` reads a Hugging Face checkpoint, as ``save_pretrained`` writes 

21 one: whole tensors, each in exactly one file, which is ``model.safetensors`` or one of the files a 

22 ``model.safetensors.index.json`` names; a Diffusers component directory is read the same way under 

23 its ``diffusion_pytorch_model`` stem. 

24* :class:`TorchShardedSafetensorsReader` reads what torch's ``HuggingFaceStorageWriter`` writes with 

25 ``save_distributed=True`` before consolidating it: every rank's shard of a tensor in a file of its 

26 own, where the shard sits in the whole tensor recorded in the file's header, and no index. 

27 

28A safetensors file opens with a JSON header giving the dtype and shape of every tensor in it, and 

29that is all a load plans against. Both readers build the checkpoint :class:`Metadata` out of those 

30headers, where :class:`FileSystemReader` unpickles a ``.metadata`` file, and inherit the rest of the 

31load: planning, resharding, the replicated-shard broadcast and the reads themselves. 

32 

33Tensors are known by the names the files give them. Mapping those onto the names of a model, and 

34merging or splitting tensors laid out differently from it, is left to the layer above. 

35""" 

36import json 

37import os 

38import struct 

39from collections.abc import Iterator 

40from math import prod 

41from pathlib import Path 

42from typing import Any, Optional 

43 

44from hyper_parallel.core.distributed_checkpoint.filesystem_storage import FileSystemReader 

45from hyper_parallel.core.distributed_checkpoint.metadata import ( 

46 ChunkStorageMetadata, 

47 Metadata, 

48 MetadataIndex, 

49 TensorProperties, 

50 TensorStorageMetadata, 

51) 

52from hyper_parallel.core.distributed_checkpoint.storage import StorageInfo 

53from hyper_parallel.core.distributed_checkpoint.utils import dcp_timer_decorator 

54 

55SAFETENSORS_SUFFIX = ".safetensors" 

56SAFETENSORS_INDEX_SUFFIX = ".safetensors.index.json" 

57# torch's HuggingFaceStorageWriter records where in the whole tensor each tensor of a file starts: a 

58# JSON string under this key of the header's ``__metadata__``, mapping every tensor name in the file 

59# to ``{"saved_offsets": [...]}``. The format allows nothing but strings there, hence JSON in a string. 

60DCP_SHARDING_INFO_KEY = "DCP_SHARDING_INFO" 

61SAVED_OFFSETS_KEY = "saved_offsets" 

62 

63_SAFE_WEIGHTS_NAME = "model.safetensors" 

64_SAFE_WEIGHTS_INDEX_NAME = "model.safetensors.index.json" 

65# A Diffusers component directory names its weights after the pipeline component instead, with the 

66# same index layout; both stems are accepted, as resolve_checkpoint_index accepts both on the 

67# whole-tensor load path. 

68_DIFFUSERS_WEIGHTS_NAME = "diffusion_pytorch_model.safetensors" 

69_DIFFUSERS_WEIGHTS_INDEX_NAME = "diffusion_pytorch_model.safetensors.index.json" 

70_HEADER_METADATA_KEY = "__metadata__" 

71_HEADER_LENGTH_BYTES = 8 

72 

73# Every dtype code safetensors (0.8) reads into torch, with the dtype it is read as, spelled the 

74# way a DCP checkpoint records one: ``str(tensor.dtype)``. 

75_SAFETENSORS_DTYPES = { 

76 "BOOL": "torch.bool", 

77 "U8": "torch.uint8", 

78 "I8": "torch.int8", 

79 "U16": "torch.uint16", 

80 "I16": "torch.int16", 

81 "U32": "torch.uint32", 

82 "I32": "torch.int32", 

83 "U64": "torch.uint64", 

84 "I64": "torch.int64", 

85 "F8_E4M3": "torch.float8_e4m3fn", 

86 "F8_E4M3FNUZ": "torch.float8_e4m3fnuz", 

87 "F8_E5M2": "torch.float8_e5m2", 

88 "F8_E5M2FNUZ": "torch.float8_e5m2fnuz", 

89 "F8_E8M0": "torch.float8_e8m0fnu", 

90 "F16": "torch.float16", 

91 "BF16": "torch.bfloat16", 

92 "F32": "torch.float32", 

93 "F64": "torch.float64", 

94 "C64": "torch.complex64", 

95} 

96 

97 

98def _loads(document: Any, source: str) -> Any: 

99 """ 

100 Parse a JSON document, saying which one it was when it does not parse. 

101 

102 Args: 

103 document (Any): The text or bytes to parse. 

104 source (str): What the document is, for the error. 

105 

106 Returns: 

107 Any: The parsed document. 

108 

109 Raises: 

110 ValueError: If the document is not JSON. 

111 """ 

112 try: 

113 return json.loads(document) 

114 except (TypeError, ValueError) as e: 

115 raise ValueError(f"{source} is not valid JSON: {e}") from e 

116 

117 

118def _read_header(path: Path) -> dict[str, Any]: 

119 """ 

120 Read the JSON header a safetensors file opens with, and nothing past it. 

121 

122 The header is an eight-byte little-endian length followed by that many bytes of JSON. 

123 

124 Args: 

125 path (Path): The safetensors file. 

126 

127 Returns: 

128 dict[str, Any]: One entry per tensor, plus ``__metadata__`` when the writer left one. 

129 

130 Raises: 

131 ValueError: If the file is too short for the header it declares, or the header is not a 

132 JSON object. 

133 """ 

134 with open(path, "rb") as f: 

135 file_size = os.fstat(f.fileno()).st_size 

136 prefix = f.read(_HEADER_LENGTH_BYTES) 

137 header_length = struct.unpack("<Q", prefix)[0] if len(prefix) == _HEADER_LENGTH_BYTES else None 

138 if header_length is None or header_length > file_size - _HEADER_LENGTH_BYTES: 

139 raise ValueError(f"{path} is not a safetensors file: it is too short for its header.") 

140 header = _loads(f.read(header_length), f"The header of {path}") 

141 if not isinstance(header, dict): 

142 raise ValueError(f"The header of {path} is not a JSON object.") 

143 return header 

144 

145 

146def _sharding_info(header: dict[str, Any], path: Path) -> Optional[dict[str, Any]]: 

147 """ 

148 The offsets torch's Hugging Face writer recorded for the tensors of one file, if it did. 

149 

150 Args: 

151 header (dict[str, Any]): The header of the file. 

152 path (Path): The file, for the error. 

153 

154 Returns: 

155 Optional[dict[str, Any]]: ``{tensor name: {"saved_offsets": [...]}}``, or None for a file 

156 that records none, which is every file Hugging Face writes itself. 

157 

158 Raises: 

159 ValueError: If the recorded offsets are not a JSON object. 

160 """ 

161 extra = header.get(_HEADER_METADATA_KEY) 

162 if not isinstance(extra, dict) or DCP_SHARDING_INFO_KEY not in extra: 

163 return None 

164 info = _loads(extra[DCP_SHARDING_INFO_KEY], f"{DCP_SHARDING_INFO_KEY} of {path}") 

165 if not isinstance(info, dict): 

166 raise ValueError(f"{DCP_SHARDING_INFO_KEY} of {path} is not a JSON object.") 

167 return info 

168 

169 

170def _dtype_and_shape(entry: Any, key: str, path: Path) -> tuple[str, tuple[int, ...]]: 

171 """ 

172 The dtype, spelled as DCP spells it, and the shape of one tensor entry of a header. 

173 

174 Args: 

175 entry (Any): The header entry of the tensor. 

176 key (str): Name of the tensor, for the error. 

177 path (Path): The file, for the error. 

178 

179 Returns: 

180 tuple[str, tuple[int, ...]]: The dtype and the shape. 

181 

182 Raises: 

183 ValueError: If the entry has no valid shape, or a dtype safetensors does not read into torch. 

184 """ 

185 shape = entry.get("shape") if isinstance(entry, dict) else None 

186 if not isinstance(shape, list) or not all(isinstance(dim, int) and dim >= 0 for dim in shape): 

187 raise ValueError(f"Tensor {key!r} in {path} has no valid shape: {entry!r}.") 

188 code = entry.get("dtype") 

189 if not isinstance(code, str) or code not in _SAFETENSORS_DTYPES: 

190 raise ValueError( 

191 f"Tensor {key!r} in {path} has dtype {code!r}, which is none of {', '.join(_SAFETENSORS_DTYPES)}." 

192 ) 

193 return _SAFETENSORS_DTYPES[code], tuple(shape) 

194 

195 

196def _saved_offsets( 

197 sharding_info: Optional[dict[str, Any]], key: str, ndim: int, path: Path 

198) -> tuple[int, ...]: 

199 """ 

200 Where in the whole tensor the part of it stored under ``key`` in one file starts. 

201 

202 Args: 

203 sharding_info (Optional[dict[str, Any]]): The offsets the file records, as 

204 :func:`_sharding_info` returns them. 

205 key (str): Name of the tensor. 

206 ndim (int): Number of dimensions of the stored part. 

207 path (Path): The file, for the error. 

208 

209 Returns: 

210 tuple[int, ...]: The offsets, all zero for a file that records none. 

211 

212 Raises: 

213 ValueError: If the file records offsets but not a valid set for this tensor. Taking it to 

214 start at the origin instead could lay it over another shard of the same tensor. 

215 """ 

216 if sharding_info is None: 

217 return (0,) * ndim 

218 entry = sharding_info.get(key) 

219 offsets = entry.get(SAVED_OFFSETS_KEY) if isinstance(entry, dict) else None 

220 if (not isinstance(offsets, list) or len(offsets) != ndim 

221 or not all(isinstance(offset, int) and offset >= 0 for offset in offsets)): 

222 raise ValueError( 

223 f"{DCP_SHARDING_INFO_KEY} of {path} has no valid {SAVED_OFFSETS_KEY} for the " 

224 f"{ndim}-dimensional tensor {key!r}: {entry!r}." 

225 ) 

226 return tuple(offsets) 

227 

228 

229def _read_chunks(path: Path, sharded: bool) -> Iterator[tuple[str, str, ChunkStorageMetadata]]: 

230 """ 

231 Every tensor one safetensors file holds, as a chunk of the tensor its name stands for. 

232 

233 Args: 

234 path (Path): The safetensors file. 

235 sharded (bool): Whether the file is a shard written by torch, which has to record where 

236 each of its tensors starts. Otherwise every tensor in it has to be whole. 

237 

238 Yields: 

239 tuple[str, str, ChunkStorageMetadata]: Name, dtype, and where in the whole tensor it sits. 

240 

241 Raises: 

242 ValueError: If a shard records no offsets, or a file of whole tensors records a tensor as 

243 starting anywhere but the origin. 

244 """ 

245 header = _read_header(path) 

246 sharding_info = _sharding_info(header, path) 

247 if sharded and sharding_info is None: 

248 raise ValueError( 

249 f"{path} records no {DCP_SHARDING_INFO_KEY}, so it is not a shard written by torch's " 

250 f"HuggingFaceStorageWriter; read a Hugging Face checkpoint with HuggingFaceStorageReader." 

251 ) 

252 for key, entry in header.items(): 

253 if key == _HEADER_METADATA_KEY: 

254 continue 

255 dtype, shape = _dtype_and_shape(entry, key, path) 

256 offsets = _saved_offsets(sharding_info, key, len(shape), path) 

257 if not sharded and any(offsets): 

258 raise ValueError( 

259 f"Tensor {key!r} in {path} is the shard at offsets {offsets} of a larger tensor; read a " 

260 f"directory of shards written by torch with TorchShardedSafetensorsReader." 

261 ) 

262 yield key, dtype, ChunkStorageMetadata(offsets=offsets, sizes=shape) 

263 

264 

265def _tensor_size(key: str, chunks: list[ChunkStorageMetadata]) -> tuple[int, ...]: 

266 """ 

267 The size of the tensor a set of chunks makes up, checking that they make up exactly that. 

268 

269 Args: 

270 key (str): Name of the tensor, for the error. 

271 chunks (list[ChunkStorageMetadata]): Every chunk of it, no two at the same offsets. 

272 

273 Returns: 

274 tuple[int, ...]: The smallest size that holds every chunk. 

275 

276 Raises: 

277 ValueError: If the chunks differ in number of dimensions, overlap, or hold more or fewer 

278 elements than that size does: a file of the checkpoint is missing, or two chunks overlap. 

279 """ 

280 ndim = len(chunks[0].sizes) 

281 if any(len(chunk.sizes) != ndim for chunk in chunks): 

282 raise ValueError(f"The chunks of tensor {key!r} differ in number of dimensions.") 

283 size = tuple(max(chunk.offsets[dim] + chunk.sizes[dim] for chunk in chunks) for dim in range(ndim)) 

284 held = sum(prod(chunk.sizes) for chunk in chunks) 

285 if held != prod(size): 

286 raise ValueError( 

287 f"The chunks of tensor {key!r} hold {held} elements between them, where a tensor of size " 

288 f"{size} has {prod(size)}: a file of the checkpoint is missing, or two chunks overlap." 

289 ) 

290 occupied: list[ChunkStorageMetadata] = [] 

291 for chunk in chunks: 

292 if prod(chunk.sizes) == 0: 

293 continue 

294 for previous in occupied: 

295 if all( 

296 max(chunk.offsets[dim], previous.offsets[dim]) 

297 < min(chunk.offsets[dim] + chunk.sizes[dim], previous.offsets[dim] + previous.sizes[dim]) 

298 for dim in range(ndim) 

299 ): 

300 raise ValueError( 

301 f"The chunks of tensor {key!r} at offsets {previous.offsets} and {chunk.offsets} overlap." 

302 ) 

303 occupied.append(chunk) 

304 return size 

305 

306 

307def _describe_checkpoint(checkpoint_dir: Path, file_names: list[str], sharded: bool) -> Metadata: 

308 """ 

309 Build the metadata of a checkpoint out of the headers of its safetensors files. 

310 

311 Args: 

312 checkpoint_dir (Path): The checkpoint directory. 

313 file_names (list[str]): The files of the checkpoint, relative to ``checkpoint_dir``. 

314 sharded (bool): Whether the files are shards written by torch; see :func:`_read_chunks`. 

315 

316 Returns: 

317 Metadata: Size, dtype and chunks of every tensor, and the file each chunk is in. 

318 

319 Raises: 

320 ValueError: If a file is not of the kind ``sharded`` says, a header is malformed, or the 

321 chunks of one tensor do not fit together: the same chunk twice, chunks in different 

322 dtypes, or chunks that do not make up the whole tensor. 

323 """ 

324 chunks: dict[str, list[ChunkStorageMetadata]] = {} 

325 dtypes: dict[str, str] = {} 

326 storage_data: dict[MetadataIndex, StorageInfo] = {} 

327 for file_name in file_names: 

328 for key, dtype, chunk in _read_chunks(checkpoint_dir / file_name, sharded): 

329 index = MetadataIndex(fqn=key, offset=chunk.offsets) 

330 if index in storage_data: 

331 raise ValueError( 

332 f"Tensor {key!r} at offsets {chunk.offsets} is in both " 

333 f"{storage_data[index].relative_path} and {file_name}." 

334 ) 

335 if dtypes.setdefault(key, dtype) != dtype: 

336 raise ValueError(f"Tensor {key!r} is {dtype} in {file_name} but {dtypes[key]} in another file.") 

337 chunks.setdefault(key, []).append(chunk) 

338 storage_data[index] = StorageInfo(relative_path=file_name, offset=0, length=-1, tensor_key=key) 

339 state_dict_metadata = { 

340 key: TensorStorageMetadata( 

341 properties=TensorProperties(dtype=dtypes[key]), 

342 size=_tensor_size(key, key_chunks), 

343 chunks=key_chunks, 

344 ) 

345 for key, key_chunks in chunks.items() 

346 } 

347 return Metadata(state_dict_metadata=state_dict_metadata, storage_data=storage_data) 

348 

349 

350class HuggingFaceStorageReader(FileSystemReader): 

351 """ 

352 Storage reader for a Hugging Face checkpoint: whole tensors, each in exactly one file. 

353 

354 Pass it to :func:`load` in place of a checkpoint path:: 

355 

356 load(model.state_dict(), storage_reader=HuggingFaceStorageReader("/models/Qwen3-8B")) 

357 

358 The files read are the ones ``model.safetensors.index.json`` names, or ``model.safetensors`` 

359 alone when there is no index; a Diffusers component directory is read the same way under its 

360 ``diffusion_pytorch_model`` stem. Nothing else in the directory is read, such as a second copy of 

361 the weights in a file of another name. A file whose header records offsets the way torch's 

362 HuggingFaceStorageWriter does is read as long as every offset is zero: anything else is a shard 

363 of a larger tensor, and a directory of those is for :class:`TorchShardedSafetensorsReader`. 

364 

365 The state dict is filled by name, as from any DCP checkpoint: each of its keys has to name a 

366 tensor in the files, at the same global shape. Beyond that the target is free. A DTensor may 

367 be laid out any way, and each rank reads only its own slice of the file. The dtype may differ 

368 from the file's, and the copy into the target converts it. Ranks holding the same slice read 

369 it once and broadcast it, as :func:`load` does for any checkpoint. 

370 

371 A key the files do not have fails the load, unless the planner is 

372 ``StandardLoadPlanner(allow_partial_load=True)``. A model with tied weights needs that, since 

373 Hugging Face stores a tied tensor once. Quantized tensors are read as they are stored: an FP8 

374 weight arrives as FP8 values, and its scales are tensors of their own. 

375 """ 

376 

377 @dcp_timer_decorator 

378 def load_metadata(self, **kwargs: Any) -> Metadata: 

379 """ 

380 Describe the checkpoint from the headers of its safetensors files, and nothing past them. 

381 

382 Args: 

383 **kwargs (Any): Ignored. :func:`load` asks again with ``rank`` when a first ask finds 

384 nothing, and a Hugging Face checkpoint has no rank-local metadata to find instead. 

385 

386 Returns: 

387 Metadata: Size, dtype and file of every tensor. 

388 

389 Raises: 

390 FileNotFoundError: If the directory holds none of the known index or weights files, 

391 or a file the index names is not there. 

392 ValueError: If the index or a header is malformed, a dtype has no torch counterpart, a 

393 tensor is a shard of a larger one, or two files hold the same tensor. 

394 """ 

395 return _describe_checkpoint(self.checkpoint_dir, self._weight_files(), sharded=False) 

396 

397 def _weight_files(self) -> list[str]: 

398 """ 

399 Name the files that make up the checkpoint. 

400 

401 A Transformers checkpoint names its weights ``model.safetensors``, a Diffusers component 

402 directory ``diffusion_pytorch_model.safetensors``, each with an index of the same stem. Both 

403 stems are accepted, and an index of either stem names the files read. 

404 

405 Returns: 

406 list[str]: File names relative to the checkpoint directory, sorted. 

407 

408 Raises: 

409 FileNotFoundError: If the directory holds none of the known index or weights files. 

410 ValueError: If the index does not map tensor names to file names. 

411 """ 

412 for index_name in (_SAFE_WEIGHTS_INDEX_NAME, _DIFFUSERS_WEIGHTS_INDEX_NAME): 

413 index_path = self.checkpoint_dir / index_name 

414 if not index_path.is_file(): 

415 continue 

416 index = _loads(index_path.read_bytes(), str(index_path)) 

417 weight_map = index.get("weight_map") if isinstance(index, dict) else None 

418 if (not isinstance(weight_map, dict) or not weight_map 

419 or not all(isinstance(file_name, str) for file_name in weight_map.values())): 

420 raise ValueError(f"{index_path} has no weight_map mapping tensor names to file names.") 

421 return sorted(set(weight_map.values())) 

422 for weights_name in (_SAFE_WEIGHTS_NAME, _DIFFUSERS_WEIGHTS_NAME): 

423 if (self.checkpoint_dir / weights_name).is_file(): 

424 return [weights_name] 

425 raise FileNotFoundError( 

426 f"None of {_SAFE_WEIGHTS_INDEX_NAME}, {_DIFFUSERS_WEIGHTS_INDEX_NAME}, {_SAFE_WEIGHTS_NAME} or " 

427 f"{_DIFFUSERS_WEIGHTS_NAME} found in {self.checkpoint_dir}. A directory of shards written by " 

428 f"torch is read with TorchShardedSafetensorsReader." 

429 ) 

430 

431 

432class TorchShardedSafetensorsReader(FileSystemReader): 

433 """ 

434 Storage reader for the shards torch's ``HuggingFaceStorageWriter`` writes with ``save_distributed``. 

435 

436 Saving that way without consolidating, every rank writes its shard of each tensor to a file of 

437 its own, ``shard-00001-model-00001-of-00001.safetensors`` and so on, under the tensor's own 

438 name, and records in the file's header where in the whole tensor the shard sits. No index is 

439 written, since a tensor is spread over several files. torchtitan writes such a directory as the 

440 ``sharded`` directory of a checkpoint it saves in Hugging Face format, before consolidating it. 

441 

442 Every safetensors file in the directory is read, and every one has to record those offsets. 

443 The shards of a tensor are its chunks, and have to make up the whole tensor between them, 

444 leaving no gap and overlapping nowhere. A directory with an index holds whole tensors, and is 

445 for :class:`HuggingFaceStorageReader`. 

446 

447 Loading from it is as from any DCP checkpoint; see :class:`HuggingFaceStorageReader` for what 

448 the state dict may be. 

449 """ 

450 

451 @dcp_timer_decorator 

452 def load_metadata(self, **kwargs: Any) -> Metadata: 

453 """ 

454 Describe the checkpoint from the headers of its shard files, and nothing past them. 

455 

456 Args: 

457 **kwargs (Any): Ignored, as :meth:`HuggingFaceStorageReader.load_metadata` ignores them. 

458 

459 Returns: 

460 Metadata: Size, dtype and chunks of every tensor, and the file each chunk is in. 

461 

462 Raises: 

463 FileNotFoundError: If the directory holds no safetensors file. 

464 ValueError: If the directory has an index, a file records no offsets, a header is 

465 malformed, a dtype has no torch counterpart, or the shards of one tensor do not fit 

466 together: the same shard twice, shards in different dtypes, or shards that do not 

467 make up the whole tensor. 

468 """ 

469 indexes = sorted(path.name for path in self.checkpoint_dir.glob(f"*{SAFETENSORS_INDEX_SUFFIX}")) 

470 if indexes: 

471 raise ValueError( 

472 f"{self.checkpoint_dir} has {indexes[0]}, which a checkpoint of whole tensors has and one " 

473 f"of shards does not; read it with HuggingFaceStorageReader." 

474 ) 

475 files = sorted(path.name for path in self.checkpoint_dir.glob(f"*{SAFETENSORS_SUFFIX}")) 

476 if not files: 

477 raise FileNotFoundError(f"No *{SAFETENSORS_SUFFIX} file found in {self.checkpoint_dir}.") 

478 return _describe_checkpoint(self.checkpoint_dir, files, sharded=True)