_dduf.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import json
  2. import logging
  3. import mmap
  4. import os
  5. import shutil
  6. import zipfile
  7. from collections.abc import Generator, Iterable
  8. from contextlib import contextmanager
  9. from dataclasses import dataclass, field
  10. from pathlib import Path
  11. from typing import Any
  12. from ..errors import DDUFCorruptedFileError, DDUFExportError, DDUFInvalidEntryNameError
  13. logger = logging.getLogger(__name__)
  14. DDUF_ALLOWED_ENTRIES = {
  15. # Allowed file extensions in a DDUF file
  16. ".json",
  17. ".model",
  18. ".safetensors",
  19. ".txt",
  20. }
  21. DDUF_FOLDER_REQUIRED_ENTRIES = {
  22. # Each folder must contain at least one of these entries
  23. "config.json",
  24. "tokenizer_config.json",
  25. "preprocessor_config.json",
  26. "scheduler_config.json",
  27. }
  28. @dataclass
  29. class DDUFEntry:
  30. """Object representing a file entry in a DDUF file.
  31. See [`read_dduf_file`] for how to read a DDUF file.
  32. Attributes:
  33. filename (str):
  34. The name of the file in the DDUF archive.
  35. offset (int):
  36. The offset of the file in the DDUF archive.
  37. length (int):
  38. The length of the file in the DDUF archive.
  39. dduf_path (str):
  40. The path to the DDUF archive (for internal use).
  41. """
  42. filename: str
  43. length: int
  44. offset: int
  45. dduf_path: Path = field(repr=False)
  46. @contextmanager
  47. def as_mmap(self) -> Generator[bytes, None, None]:
  48. """Open the file as a memory-mapped file.
  49. Useful to load safetensors directly from the file.
  50. Example:
  51. ```py
  52. >>> import safetensors.torch
  53. >>> with entry.as_mmap() as mm:
  54. ... tensors = safetensors.torch.load(mm)
  55. ```
  56. """
  57. with self.dduf_path.open("rb") as f:
  58. with mmap.mmap(f.fileno(), length=0, access=mmap.ACCESS_READ) as mm:
  59. yield mm[self.offset : self.offset + self.length]
  60. def read_text(self, encoding: str = "utf-8") -> str:
  61. """Read the file as text.
  62. Useful for '.txt' and '.json' entries.
  63. Example:
  64. ```py
  65. >>> import json
  66. >>> index = json.loads(entry.read_text())
  67. ```
  68. """
  69. with self.dduf_path.open("rb") as f:
  70. f.seek(self.offset)
  71. return f.read(self.length).decode(encoding=encoding)
  72. def read_dduf_file(dduf_path: os.PathLike | str) -> dict[str, DDUFEntry]:
  73. """
  74. Read a DDUF file and return a dictionary of entries.
  75. Only the metadata is read, the data is not loaded in memory.
  76. Args:
  77. dduf_path (`str` or `os.PathLike`):
  78. The path to the DDUF file to read.
  79. Returns:
  80. `dict[str, DDUFEntry]`:
  81. A dictionary of [`DDUFEntry`] indexed by filename.
  82. Raises:
  83. - [`DDUFCorruptedFileError`]: If the DDUF file is corrupted (i.e. doesn't follow the DDUF format).
  84. Example:
  85. ```python
  86. >>> import json
  87. >>> import safetensors.torch
  88. >>> from huggingface_hub import read_dduf_file
  89. # Read DDUF metadata
  90. >>> dduf_entries = read_dduf_file("FLUX.1-dev.dduf")
  91. # Returns a mapping filename <> DDUFEntry
  92. >>> dduf_entries["model_index.json"]
  93. DDUFEntry(filename='model_index.json', offset=66, length=587)
  94. # Load model index as JSON
  95. >>> json.loads(dduf_entries["model_index.json"].read_text())
  96. {'_class_name': 'FluxPipeline', '_diffusers_version': '0.32.0.dev0', '_name_or_path': 'black-forest-labs/FLUX.1-dev', ...
  97. # Load VAE weights using safetensors
  98. >>> with dduf_entries["vae/diffusion_pytorch_model.safetensors"].as_mmap() as mm:
  99. ... state_dict = safetensors.torch.load(mm)
  100. ```
  101. """
  102. entries = {}
  103. dduf_path = Path(dduf_path)
  104. logger.info(f"Reading DDUF file {dduf_path}")
  105. with zipfile.ZipFile(str(dduf_path), "r") as zf:
  106. for info in zf.infolist():
  107. logger.debug(f"Reading entry {info.filename}")
  108. if info.compress_type != zipfile.ZIP_STORED:
  109. raise DDUFCorruptedFileError("Data must not be compressed in DDUF file.")
  110. try:
  111. _validate_dduf_entry_name(info.filename)
  112. except DDUFInvalidEntryNameError as e:
  113. raise DDUFCorruptedFileError(f"Invalid entry name in DDUF file: {info.filename}") from e
  114. offset = _get_data_offset(zf, info)
  115. entries[info.filename] = DDUFEntry(
  116. filename=info.filename, offset=offset, length=info.file_size, dduf_path=dduf_path
  117. )
  118. # Consistency checks on the DDUF file
  119. if "model_index.json" not in entries:
  120. raise DDUFCorruptedFileError("Missing required 'model_index.json' entry in DDUF file.")
  121. index = json.loads(entries["model_index.json"].read_text())
  122. _validate_dduf_structure(index, entries.keys())
  123. logger.info(f"Done reading DDUF file {dduf_path}. Found {len(entries)} entries")
  124. return entries
  125. def export_entries_as_dduf(dduf_path: str | os.PathLike, entries: Iterable[tuple[str, str | Path | bytes]]) -> None:
  126. """Write a DDUF file from an iterable of entries.
  127. This is a lower-level helper than [`export_folder_as_dduf`] that allows more flexibility when serializing data.
  128. In particular, you don't need to save the data on disk before exporting it in the DDUF file.
  129. Args:
  130. dduf_path (`str` or `os.PathLike`):
  131. The path to the DDUF file to write.
  132. entries (`Iterable[tuple[str, Union[str, Path, bytes]]]`):
  133. An iterable of entries to write in the DDUF file. Each entry is a tuple with the filename and the content.
  134. The filename should be the path to the file in the DDUF archive.
  135. The content can be a string or a pathlib.Path representing a path to a file on the local disk or directly the content as bytes.
  136. Raises:
  137. - [`DDUFExportError`]: If anything goes wrong during the export (e.g. invalid entry name, missing 'model_index.json', etc.).
  138. Example:
  139. ```python
  140. # Export specific files from the local disk.
  141. >>> from huggingface_hub import export_entries_as_dduf
  142. >>> export_entries_as_dduf(
  143. ... dduf_path="stable-diffusion-v1-4-FP16.dduf",
  144. ... entries=[ # List entries to add to the DDUF file (here, only FP16 weights)
  145. ... ("model_index.json", "path/to/model_index.json"),
  146. ... ("vae/config.json", "path/to/vae/config.json"),
  147. ... ("vae/diffusion_pytorch_model.fp16.safetensors", "path/to/vae/diffusion_pytorch_model.fp16.safetensors"),
  148. ... ("text_encoder/config.json", "path/to/text_encoder/config.json"),
  149. ... ("text_encoder/model.fp16.safetensors", "path/to/text_encoder/model.fp16.safetensors"),
  150. ... # ... add more entries here
  151. ... ]
  152. ... )
  153. ```
  154. ```python
  155. # Export state_dicts one by one from a loaded pipeline
  156. >>> from diffusers import DiffusionPipeline
  157. >>> from typing import Generator, Tuple
  158. >>> import safetensors.torch
  159. >>> from huggingface_hub import export_entries_as_dduf
  160. >>> pipe = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
  161. ... # ... do some work with the pipeline
  162. >>> def as_entries(pipe: DiffusionPipeline) -> Generator[tuple[str, bytes], None, None]:
  163. ... # Build a generator that yields the entries to add to the DDUF file.
  164. ... # The first element of the tuple is the filename in the DDUF archive (must use UNIX separator!). The second element is the content of the file.
  165. ... # Entries will be evaluated lazily when the DDUF file is created (only 1 entry is loaded in memory at a time)
  166. ... yield "vae/config.json", pipe.vae.to_json_string().encode()
  167. ... yield "vae/diffusion_pytorch_model.safetensors", safetensors.torch.save(pipe.vae.state_dict())
  168. ... yield "text_encoder/config.json", pipe.text_encoder.config.to_json_string().encode()
  169. ... yield "text_encoder/model.safetensors", safetensors.torch.save(pipe.text_encoder.state_dict())
  170. ... # ... add more entries here
  171. >>> export_entries_as_dduf(dduf_path="stable-diffusion-v1-4.dduf", entries=as_entries(pipe))
  172. ```
  173. """
  174. logger.info(f"Exporting DDUF file '{dduf_path}'")
  175. filenames = set()
  176. index = None
  177. with zipfile.ZipFile(str(dduf_path), "w", zipfile.ZIP_STORED) as archive:
  178. for filename, content in entries:
  179. if filename in filenames:
  180. raise DDUFExportError(f"Can't add duplicate entry: {filename}")
  181. filenames.add(filename)
  182. if filename == "model_index.json":
  183. try:
  184. index = json.loads(_load_content(content).decode())
  185. except json.JSONDecodeError as e:
  186. raise DDUFExportError("Failed to parse 'model_index.json'.") from e
  187. try:
  188. filename = _validate_dduf_entry_name(filename)
  189. except DDUFInvalidEntryNameError as e:
  190. raise DDUFExportError(f"Invalid entry name: {filename}") from e
  191. logger.debug(f"Adding entry '{filename}' to DDUF file")
  192. _dump_content_in_archive(archive, filename, content)
  193. # Consistency checks on the DDUF file
  194. if index is None:
  195. raise DDUFExportError("Missing required 'model_index.json' entry in DDUF file.")
  196. try:
  197. _validate_dduf_structure(index, filenames)
  198. except DDUFCorruptedFileError as e:
  199. raise DDUFExportError("Invalid DDUF file structure.") from e
  200. logger.info(f"Done writing DDUF file {dduf_path}")
  201. def export_folder_as_dduf(dduf_path: str | os.PathLike, folder_path: str | os.PathLike) -> None:
  202. """
  203. Export a folder as a DDUF file.
  204. AUses [`export_entries_as_dduf`] under the hood.
  205. Args:
  206. dduf_path (`str` or `os.PathLike`):
  207. The path to the DDUF file to write.
  208. folder_path (`str` or `os.PathLike`):
  209. The path to the folder containing the diffusion model.
  210. Example:
  211. ```python
  212. >>> from huggingface_hub import export_folder_as_dduf
  213. >>> export_folder_as_dduf(dduf_path="FLUX.1-dev.dduf", folder_path="path/to/FLUX.1-dev")
  214. ```
  215. """
  216. folder_path = Path(folder_path)
  217. def _iterate_over_folder() -> Iterable[tuple[str, Path]]:
  218. for path in Path(folder_path).glob("**/*"):
  219. if not path.is_file():
  220. continue
  221. if path.suffix not in DDUF_ALLOWED_ENTRIES:
  222. logger.debug(f"Skipping file '{path}' (file type not allowed)")
  223. continue
  224. path_in_archive = path.relative_to(folder_path)
  225. if len(path_in_archive.parts) >= 3:
  226. logger.debug(f"Skipping file '{path}' (nested directories not allowed)")
  227. continue
  228. yield path_in_archive.as_posix(), path
  229. export_entries_as_dduf(dduf_path, _iterate_over_folder())
  230. def _dump_content_in_archive(archive: zipfile.ZipFile, filename: str, content: str | os.PathLike | bytes) -> None:
  231. with archive.open(filename, "w", force_zip64=True) as archive_fh:
  232. if isinstance(content, (str, Path)):
  233. content_path = Path(content)
  234. with content_path.open("rb") as content_fh:
  235. shutil.copyfileobj(content_fh, archive_fh, 1024 * 1024 * 8) # type: ignore[misc]
  236. elif isinstance(content, bytes):
  237. archive_fh.write(content)
  238. else:
  239. raise DDUFExportError(f"Invalid content type for {filename}. Must be str, Path or bytes.")
  240. def _load_content(content: str | Path | bytes) -> bytes:
  241. """Load the content of an entry as bytes.
  242. Used only for small checks (not to dump content into archive).
  243. """
  244. if isinstance(content, (str, Path)):
  245. return Path(content).read_bytes()
  246. elif isinstance(content, bytes):
  247. return content
  248. else:
  249. raise DDUFExportError(f"Invalid content type. Must be str, Path or bytes. Got {type(content)}.")
  250. def _validate_dduf_entry_name(entry_name: str) -> str:
  251. if "." + entry_name.split(".")[-1] not in DDUF_ALLOWED_ENTRIES:
  252. raise DDUFInvalidEntryNameError(f"File type not allowed: {entry_name}")
  253. if "\\" in entry_name:
  254. raise DDUFInvalidEntryNameError(f"Entry names must use UNIX separators ('/'). Got {entry_name}.")
  255. entry_name = entry_name.strip("/")
  256. if entry_name.count("/") > 1:
  257. raise DDUFInvalidEntryNameError(f"DDUF only supports 1 level of directory. Got {entry_name}.")
  258. return entry_name
  259. def _validate_dduf_structure(index: Any, entry_names: Iterable[str]) -> None:
  260. """
  261. Consistency checks on the DDUF file structure.
  262. Rules:
  263. - The 'model_index.json' entry is required and must contain a dictionary.
  264. - Each folder name must correspond to an entry in 'model_index.json'.
  265. - Each folder must contain at least a config file ('config.json', 'tokenizer_config.json', 'preprocessor_config.json', 'scheduler_config.json').
  266. Args:
  267. index (Any):
  268. The content of the 'model_index.json' entry.
  269. entry_names (Iterable[str]):
  270. The list of entry names in the DDUF file.
  271. Raises:
  272. - [`DDUFCorruptedFileError`]: If the DDUF file is corrupted (i.e. doesn't follow the DDUF format).
  273. """
  274. if not isinstance(index, dict):
  275. raise DDUFCorruptedFileError(f"Invalid 'model_index.json' content. Must be a dictionary. Got {type(index)}.")
  276. dduf_folders = {entry.split("/")[0] for entry in entry_names if "/" in entry}
  277. for folder in dduf_folders:
  278. if folder not in index:
  279. raise DDUFCorruptedFileError(f"Missing required entry '{folder}' in 'model_index.json'.")
  280. if not any(f"{folder}/{required_entry}" in entry_names for required_entry in DDUF_FOLDER_REQUIRED_ENTRIES):
  281. raise DDUFCorruptedFileError(
  282. f"Missing required file in folder '{folder}'. Must contains at least one of {DDUF_FOLDER_REQUIRED_ENTRIES}."
  283. )
  284. def _get_data_offset(zf: zipfile.ZipFile, info: zipfile.ZipInfo) -> int:
  285. """
  286. Calculate the data offset for a file in a ZIP archive.
  287. Args:
  288. zf (`zipfile.ZipFile`):
  289. The opened ZIP file. Must be opened in read mode.
  290. info (`zipfile.ZipInfo`):
  291. The file info.
  292. Returns:
  293. int: The offset of the file data in the ZIP archive.
  294. """
  295. if zf.fp is None:
  296. raise DDUFCorruptedFileError("ZipFile object must be opened in read mode.")
  297. # Step 1: Get the local file header offset
  298. header_offset = info.header_offset
  299. # Step 2: Read the local file header
  300. zf.fp.seek(header_offset)
  301. local_file_header = zf.fp.read(30) # Fixed-size part of the local header
  302. if len(local_file_header) < 30:
  303. raise DDUFCorruptedFileError("Incomplete local file header.")
  304. # Step 3: Parse the header fields to calculate the start of file data
  305. # Local file header: https://en.wikipedia.org/wiki/ZIP_(file_format)#File_headers
  306. filename_len = int.from_bytes(local_file_header[26:28], "little")
  307. extra_field_len = int.from_bytes(local_file_header[28:30], "little")
  308. # Data offset is after the fixed header, filename, and extra fields
  309. data_offset = header_offset + 30 + filename_len + extra_field_len
  310. return data_offset