dumpsterpanda 0.3.0__tar.gz → 0.3.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/PKG-INFO +4 -4
  2. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/README.md +3 -3
  3. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/pyproject.toml +1 -1
  4. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/__init__.py +1 -1
  5. dumpsterpanda-0.3.2/src/trash_panda/common/__init__.py +4 -0
  6. dumpsterpanda-0.3.2/src/trash_panda/common/from_transformers.py +57 -0
  7. dumpsterpanda-0.3.2/src/trash_panda/common/hub.py +89 -0
  8. {dumpsterpanda-0.3.0/src/trash_panda/diffusers → dumpsterpanda-0.3.2/src/trash_panda/common}/meta.py +14 -0
  9. dumpsterpanda-0.3.2/src/trash_panda/common/names.py +201 -0
  10. dumpsterpanda-0.3.2/src/trash_panda/common/prepare.py +63 -0
  11. {dumpsterpanda-0.3.0/src/trash_panda/diffusers → dumpsterpanda-0.3.2/src/trash_panda/common}/weights.py +1 -23
  12. dumpsterpanda-0.3.2/src/trash_panda/diffusers/__init__.py +5 -0
  13. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/diffusers/hub.py +11 -72
  14. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/diffusers/pipeline.py +40 -43
  15. dumpsterpanda-0.3.2/src/trash_panda/diffusers/renames.py +39 -0
  16. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/diffusers/stages.py +10 -5
  17. dumpsterpanda-0.3.2/src/trash_panda/diffusers/weights.py +29 -0
  18. dumpsterpanda-0.3.2/src/trash_panda/transformers/__init__.py +5 -0
  19. dumpsterpanda-0.3.2/src/trash_panda/transformers/model.py +124 -0
  20. dumpsterpanda-0.3.2/src/trash_panda/transformers/source.py +58 -0
  21. dumpsterpanda-0.3.0/src/trash_panda/diffusers/__init__.py +0 -5
  22. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/LICENSE +0 -0
  23. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/cli/__init__.py +0 -0
  24. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/cli/app.py +0 -0
  25. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/cli/config.py +0 -0
  26. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/cli/hardware.py +0 -0
  27. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/cli/info.py +0 -0
  28. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/cli/names.py +0 -0
  29. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/cli/plan.py +0 -0
  30. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/cli/trace.py +0 -0
  31. {dumpsterpanda-0.3.0/src/trash_panda/diffusers → dumpsterpanda-0.3.2/src/trash_panda/common}/shim.py +0 -0
  32. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/offload/__init__.py +0 -0
  33. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/offload/blocks.py +0 -0
  34. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/offload/checkpoint.py +0 -0
  35. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/offload/config.py +0 -0
  36. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/offload/coordinator.py +0 -0
  37. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/offload/depth.py +0 -0
  38. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/offload/early.py +0 -0
  39. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/offload/formats.py +0 -0
  40. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/offload/hardware.py +0 -0
  41. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/offload/hooks.py +0 -0
  42. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/offload/loader.py +0 -0
  43. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/offload/measure.py +0 -0
  44. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/offload/order_file.py +0 -0
  45. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/offload/planner.py +0 -0
  46. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/offload/report.py +0 -0
  47. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/offload/stage.py +0 -0
  48. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/offload/trace.py +0 -0
  49. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/paths.py +0 -0
  50. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/ui/__init__.py +0 -0
  51. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/ui/load.py +0 -0
  52. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/ui/server.py +0 -0
  53. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/ui/static/app.js +0 -0
  54. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/ui/static/bars.js +0 -0
  55. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/ui/static/data.js +0 -0
  56. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/ui/static/files.js +0 -0
  57. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/ui/static/index.html +0 -0
  58. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/ui/static/memory.js +0 -0
  59. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/ui/static/memorychart.js +0 -0
  60. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/ui/static/package.json +0 -0
  61. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/ui/static/panels.js +0 -0
  62. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/ui/static/style.css +0 -0
  63. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/ui/static/svg.js +0 -0
  64. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/ui/static/timeline.js +0 -0
  65. {dumpsterpanda-0.3.0 → dumpsterpanda-0.3.2}/src/trash_panda/ui/static/usage.js +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dumpsterpanda
3
- Version: 0.3.0
3
+ Version: 0.3.2
4
4
  Summary: Run models bigger than your GPU: layer-by-layer weight streaming across GPU, RAM and disk.
5
5
  License: AGPL-3.0-only
6
6
  License-File: LICENSE
@@ -144,10 +144,10 @@ VAE) run in stages, one at a time, with no other setup:
144
144
 
145
145
  ```python
146
146
  from diffusers import StableDiffusionXLPipeline
147
- from trash_panda.diffusers import TrashPandaPipeline
147
+ from trash_panda.diffusers import TrashPandaDiffusionPipeline
148
148
 
149
- pipe = TrashPandaPipeline.from_pretrained(StableDiffusionXLPipeline, "stabilityai/stable-diffusion-xl-base-1.0",
150
- variant="fp16") # or a folder: "/models/sdxl-base"
149
+ pipe = TrashPandaDiffusionPipeline.from_pretrained(StableDiffusionXLPipeline, "stabilityai/stable-diffusion-xl-base-1.0",
150
+ variant="fp16") # or a folder: "/models/sdxl-base"
151
151
  image = pipe("a raccoon in a yellow raincoat").images[0]
152
152
  ```
153
153
 
@@ -116,10 +116,10 @@ VAE) run in stages, one at a time, with no other setup:
116
116
 
117
117
  ```python
118
118
  from diffusers import StableDiffusionXLPipeline
119
- from trash_panda.diffusers import TrashPandaPipeline
119
+ from trash_panda.diffusers import TrashPandaDiffusionPipeline
120
120
 
121
- pipe = TrashPandaPipeline.from_pretrained(StableDiffusionXLPipeline, "stabilityai/stable-diffusion-xl-base-1.0",
122
- variant="fp16") # or a folder: "/models/sdxl-base"
121
+ pipe = TrashPandaDiffusionPipeline.from_pretrained(StableDiffusionXLPipeline, "stabilityai/stable-diffusion-xl-base-1.0",
122
+ variant="fp16") # or a folder: "/models/sdxl-base"
123
123
  image = pipe("a raccoon in a yellow raincoat").images[0]
124
124
  ```
125
125
 
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "dumpsterpanda"
3
- version = "0.3.0"
3
+ version = "0.3.2"
4
4
  description = "Run models bigger than your GPU: layer-by-layer weight streaming across GPU, RAM and disk."
5
5
  authors = ["yla382"]
6
6
  readme = "README.md"
@@ -1,6 +1,6 @@
1
1
  """trash-panda: run models bigger than your GPU by streaming weights across GPU, RAM and disk."""
2
2
 
3
- __version__ = "0.3.0"
3
+ __version__ = "0.3.2"
4
4
 
5
5
  # The offload API is imported lazily so that `import trash_panda` works even where torch is not installed yet.
6
6
  _OFFLOAD_NAMES = (
@@ -0,0 +1,4 @@
1
+ """What the wrappers for diffusers pipelines and for transformers models have in common: building a model without its weights
2
+ (`meta`), making a placeholder say its dtype and device (`shim`), finding the weight files of a folder (`weights`) and the
3
+ folder of a repo of the Hugging Face Hub (`hub`), and pairing the names in a weight file with the names of a model (`names`,
4
+ with the rules of transformers in `from_transformers`). It imports no model library until one is needed."""
@@ -0,0 +1,57 @@
1
+ """What transformers itself would do to the keys of a weight file: its own renaming rules for a model.
2
+
3
+ A file that an older version of `transformers` saved can name its layers differently from the model that the installed
4
+ version builds (version 5 dropped the `text_model.` level of CLIP, and nested the language model of multimodal models under
5
+ `language_model`). transformers translates the names in its own loader, which trash-panda does not use, so the same rules
6
+ are asked for here and applied to the names of the file. transformers is imported when library_renames() is called."""
7
+
8
+ from __future__ import annotations
9
+
10
+ import warnings
11
+ from types import SimpleNamespace
12
+ from typing import Any, Dict, Iterable, Tuple
13
+
14
+
15
+ def _transformers_library() -> SimpleNamespace:
16
+ from transformers.conversion_mapping import get_model_conversion_mapping
17
+ from transformers.core_model_loading import WeightConverter, WeightRenaming, rename_source_key
18
+
19
+ return SimpleNamespace(get_model_conversion_mapping=get_model_conversion_mapping, WeightConverter=WeightConverter,
20
+ WeightRenaming=WeightRenaming, rename_source_key=rename_source_key)
21
+
22
+
23
+ def library_renames(model, file_keys: Iterable[str], library: Any = None) -> Tuple[Dict[str, str], Dict[str, str]]:
24
+ """What transformers itself would do to the keys of a file that its loader reads into `model`:
25
+ ({file key: new name} for the keys it renames, {file key: pattern} for the keys it would convert, which means fuse or
26
+ split tensors: renaming cannot do that).
27
+
28
+ The model's rules come from `get_model_conversion_mapping(model)`; each key goes through `rename_source_key()`, which
29
+ applies every renaming, then at most one converter, then adds or takes off `base_model_prefix` according to the names
30
+ that the model has. When the key is not a name of the model after that but was one before, it is left as it was, as the
31
+ loader does. These are functions of transformers that other code uses too, but they are not a public API, so when they
32
+ are missing or fail a warning says so and the result is empty: the caller goes on with the prefix rule.
33
+
34
+ `library` is what has the four names of transformers used here, for tests."""
35
+ try:
36
+ lib = library or _transformers_library()
37
+ mapping = lib.get_model_conversion_mapping(model)
38
+ renamings = [t for t in mapping if isinstance(t, lib.WeightRenaming)]
39
+ converters = [t for t in mapping if isinstance(t, lib.WeightConverter)]
40
+ meta = model.state_dict()
41
+ prefix = getattr(model, "base_model_prefix", None)
42
+ renamed: Dict[str, str] = {}
43
+ converted: Dict[str, str] = {}
44
+ for key in file_keys:
45
+ new, pattern = lib.rename_source_key(key, renamings, converters, prefix, meta)
46
+ if new not in meta and key in meta:
47
+ new, pattern = lib.rename_source_key(key, [], [], prefix, meta)
48
+ if pattern is not None:
49
+ converted[key] = pattern
50
+ elif new != key:
51
+ renamed[key] = new
52
+ return renamed, converted
53
+ except Exception as err: # functions of another library that are not a public API
54
+ warnings.warn(f"trash-panda: the renaming rules of transformers could not be used for {type(model).__name__} "
55
+ f"({type(err).__name__}: {err}); only the names the model has, and a differing first part of a name, "
56
+ "are paired", UserWarning, stacklevel=2)
57
+ return {}, {}
@@ -0,0 +1,89 @@
1
+ """Getting the folder of a model: a folder on disk, or a repository of the Hugging Face Hub fetched into its cache.
2
+
3
+ resolve_folder("sd3-medium/", select) # a folder: used as it is
4
+ resolve_folder("owner/name", select) # a repo id: the files that `select` picks are fetched
5
+
6
+ A repo holds the same weights in several formats and variants, and most of them are never read, so what is fetched is chosen
7
+ by a function that knows the kind of repo (a diffusers pipeline, a transformers model): see trash_panda.diffusers.hub and
8
+ trash_panda.transformers.source. `huggingface_hub` is imported when a repo is fetched, not before."""
9
+
10
+ from __future__ import annotations
11
+
12
+ import glob
13
+ import re
14
+ from pathlib import Path
15
+ from typing import Callable, List, Optional, Sequence, Union
16
+
17
+ _REPO_ID = re.compile(r"^[A-Za-z0-9][\w.\-]*/[A-Za-z0-9][\w.\-]*$", re.ASCII) # owner/name: letters, digits, _ - .
18
+ _WEIGHT_SUFFIXES = (".bin", ".ckpt", ".pt", ".pth", ".onnx", ".onnx_data", ".msgpack", ".h5", ".gguf", ".pb", ".tflite", ".ot")
19
+ _NEVER = (".md", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".mp4") # never needed to run a model
20
+
21
+
22
+ def is_repo_id(text: str) -> bool:
23
+ """True for the form of a Hub repo id: `owner/name`."""
24
+ return bool(_REPO_ID.match(str(text)))
25
+
26
+
27
+ class _HubClient:
28
+ """What is asked of the Hub: the names of the files of a repo, and a download of some of them."""
29
+
30
+ def list_files(self, repo_id: str, revision: Optional[str], token: Optional[str]) -> List[str]:
31
+ from huggingface_hub import HfApi
32
+
33
+ return list(HfApi(token=token).list_repo_files(repo_id, revision=revision))
34
+
35
+ def download(self, repo_id: str, files: Optional[Sequence[str]], revision: Optional[str], token: Optional[str],
36
+ cache_dir: Union[None, str, Path], local_files_only: bool) -> str:
37
+ from huggingface_hub import snapshot_download
38
+
39
+ patterns = None if files is None else [glob.escape(file) for file in files]
40
+ return snapshot_download(repo_id, revision=revision, token=token, cache_dir=cache_dir, allow_patterns=patterns,
41
+ local_files_only=local_files_only)
42
+
43
+
44
+ def _default_client() -> _HubClient:
45
+ try:
46
+ import huggingface_hub # noqa: F401
47
+ except ImportError:
48
+ raise ImportError("fetching a pipeline from the Hugging Face Hub needs huggingface_hub: "
49
+ "pip install huggingface_hub (or give a folder on disk)") from None
50
+ return _HubClient()
51
+
52
+
53
+ def resolve_folder(source: Union[str, Path], select: Callable[[Sequence[str], Optional[str]], List[str]], *,
54
+ hub: Optional[bool] = None, variant: Optional[str] = None, revision: Optional[str] = None,
55
+ token: Optional[str] = None, cache_dir: Union[None, str, Path] = None, local_files_only: bool = False,
56
+ client=None, make_client: Optional[Callable[[], object]] = None) -> Path:
57
+ """The folder that `source` names: `source` itself when it is a folder, else the repo of that name fetched into the Hub
58
+ cache. `select(files, variant)` gives the files of the repo that are needed, from the repo's list of file names.
59
+
60
+ hub None decides by looking: an existing folder is used, and what has the form `owner/name` is a repo id. True is a
61
+ repo id even if a folder of that name exists; False is a folder and nothing else.
62
+ variant passed to `select`, which picks which weights are fetched
63
+ revision, token, cache_dir as for the Hub: a branch or commit, a login token (default: the one that is logged in
64
+ or in HF_TOKEN) for gated models, and where the cache is (default: the Hub's)
65
+ local_files_only do not go online: the snapshot that is in the cache already, whole
66
+ client what talks to the Hub, for tests; `make_client` makes one when it is needed and none is given (default:
67
+ one that uses huggingface_hub)"""
68
+ path = Path(source)
69
+ if hub is False or (hub is None and path.is_dir()):
70
+ if not path.is_dir():
71
+ raise ValueError(f"{source} is not a folder (hub=False was given)")
72
+ return path
73
+ if not is_repo_id(str(source)):
74
+ what = "a repo id of the form owner/name" if hub else "a folder or a repo id of the form owner/name"
75
+ raise ValueError(f"{source!r} is not {what}")
76
+ repo_id = str(source)
77
+ client = client or (make_client or _default_client)()
78
+ try:
79
+ if local_files_only:
80
+ files = None
81
+ else:
82
+ files = select(client.list_files(repo_id, revision, token), variant)
83
+ print(f"trash-panda: fetching {len(files)} files of {repo_id} (the ones in the cache are not fetched again)")
84
+ return Path(client.download(repo_id, files, revision, token, cache_dir, local_files_only))
85
+ except ValueError:
86
+ raise
87
+ except Exception as err:
88
+ raise OSError(f"could not get {repo_id} from the Hugging Face Hub: {err}. If it is a folder on disk, check the "
89
+ "path or pass hub=False") from err
@@ -49,6 +49,20 @@ def empty_weights():
49
49
  nn.Module.register_parameter = register
50
50
 
51
51
 
52
+ def build_empty(model_class: type, config) -> nn.Module:
53
+ """A model of transformers built from its config with empty_weights(), and in evaluation mode, as `from_pretrained()`
54
+ leaves a model (dropout is off: a T5 would otherwise drop activations in every call). `model_class` is a model class
55
+ (`_from_config`) or an auto class (`from_config`)."""
56
+ with empty_weights():
57
+ if hasattr(model_class, "_from_config"):
58
+ model = model_class._from_config(config)
59
+ elif hasattr(model_class, "from_config"):
60
+ model = model_class.from_config(config)
61
+ else:
62
+ raise TypeError(f"cannot build {model_class.__name__} from a config: it has neither `_from_config` nor `from_config`")
63
+ return model.eval()
64
+
65
+
52
66
  def buffers_to_keep(model: nn.Module, checkpoint: Union[str, Checkpoint], key_map=None) -> List[str]:
53
67
  """The names of the buffers of `model` that hold their values (they are not on the meta device) and that the
54
68
  checkpoint has no tensor for. Give them to stream_load() or stage() as `skip_prefixes=` so that they are not required,
@@ -0,0 +1,201 @@
1
+ """Pairing the names in a weight file with the names of a model (a transformers model, or a diffusers one).
2
+
3
+ A file that an older version of a library saved can name its layers differently from the model that the installed version
4
+ builds (`transformers` 5 dropped the `text_model.` level of CLIP, and diffusers renamed the attention layers of its VAE).
5
+ The library translates the names in its own loader, which trash-panda does not use. So the names are paired here, in this
6
+ order:
7
+
8
+ 1. the name is the model's own;
9
+ 2. the translation that the library would apply (from_transformers.library_renames() for transformers, and for
10
+ diffusers the hook of the model, see trash_panda.diffusers.renames), given as `renames`;
11
+ 3. when that is not available (another version of the library), a first part of the name that the file or the model has
12
+ and the other does not;
13
+ 4. a `key_map` that the caller gives goes before all of them.
14
+
15
+ Then the pairing is checked before anything is loaded: each weight of the model is filled by one tensor of the file, of the
16
+ same shape, and a tensor that the library would have to fuse or split (a conversion that renaming cannot do) is reported.
17
+ The functions work on dictionaries of names and shapes and import neither torch nor a model library; pair_model() reads a
18
+ model and a weight file and asks the rules of a library (a `renamer`, see from_transformers.py and
19
+ trash_panda.diffusers.renames) for the renames."""
20
+
21
+ from __future__ import annotations
22
+
23
+ from dataclasses import dataclass, field
24
+ from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union
25
+
26
+ Shape = Tuple[int, ...]
27
+
28
+
29
+ class NameMismatch(ValueError):
30
+ """The names of a file and of a model cannot be paired exactly. The message lists what is wrong."""
31
+
32
+
33
+ @dataclass
34
+ class Pairing:
35
+ """Which tensor of the file fills which weight of the model.
36
+
37
+ `names` has every file key that fills a weight, with that weight's name; `renamed` is the part of it where the two
38
+ names differ, which is what a `key_map` needs. `unused` are file keys that fill nothing (the model does not have the
39
+ weight: a tied copy, an old buffer), `optional` the buffers of the model that the file does not have."""
40
+
41
+ names: Dict[str, str] = field(default_factory=dict)
42
+ renamed: Dict[str, str] = field(default_factory=dict)
43
+ unused: List[str] = field(default_factory=list)
44
+ optional: List[str] = field(default_factory=list)
45
+
46
+ def key_map(self) -> Optional[Dict[str, str]]:
47
+ """What stream_load() and plan() take as `key_map`, or None when no name has to change."""
48
+ return dict(self.renamed) or None
49
+
50
+ def summary(self) -> str:
51
+ shown = ", ".join(f"{old} -> {new}" for old, new in list(self.renamed.items())[:2])
52
+ more = f", and {len(self.renamed) - 2} more" if len(self.renamed) > 2 else ""
53
+ text = f"{len(self.names)} tensors paired"
54
+ if self.renamed:
55
+ text += f", {len(self.renamed)} of them under another name (e.g. {shown}{more})"
56
+ if self.unused:
57
+ text += f"; {len(self.unused)} tensors of the file fill nothing (e.g. {self.unused[0]})"
58
+ return text
59
+
60
+
61
+ def _few(items: Iterable[Any], count: int = 3) -> str:
62
+ items = list(items)
63
+ return ", ".join(str(item) for item in items[:count]) + (f" and {len(items) - count} more" if len(items) > count else "")
64
+
65
+
66
+ def _prefix_rename(name: str, known: Iterable[str]) -> str:
67
+ """The name with a first part taken off that the model does not have, or put on that it has and the file does not.
68
+ Used only when the library's own translation is not available."""
69
+ known = set(known)
70
+ if name in known:
71
+ return name
72
+ _, _, rest = name.partition(".")
73
+ if rest in known:
74
+ return rest
75
+ prefixes = {n.split(".", 1)[0] for n in known if "." in n}
76
+ for prefix in sorted(prefixes):
77
+ if f"{prefix}.{name}" in known:
78
+ return f"{prefix}.{name}"
79
+ return name
80
+
81
+
82
+ def pair_names(model_shapes: Mapping[str, Shape], file_shapes: Mapping[str, Shape], *,
83
+ optional_shapes: Optional[Mapping[str, Shape]] = None, ties: Sequence[Sequence[str]] = (),
84
+ renames: Optional[Mapping[str, str]] = None, converted: Optional[Mapping[str, str]] = None,
85
+ key_map: Union[None, Mapping[str, str], Callable[[str], str]] = None) -> Pairing:
86
+ """Pair the tensors of a file with the weights of a model, and check the pairing.
87
+
88
+ model_shapes {name: shape} of the weights that the file has to fill (`named_parameters()`)
89
+ file_shapes {key: shape} of the tensors in the file
90
+ optional_shapes the same for what the file may lack: the buffers
91
+ ties groups of names that hold one parameter (`tied_parameters()`). `named_parameters()` lists a tied weight
92
+ once, so a file key under another name of the group fills that one
93
+ renames {file key: name} that the library gives (library_renames()); converted: {file key: pattern} that it cannot
94
+ key_map the caller's own: a dict or a function from a file key to a name; it goes first
95
+
96
+ Raises NameMismatch, with every problem listed, when a weight of the model is not filled, a tensor has another shape
97
+ than its weight, two tensors fill one weight, or a tensor would have to be converted."""
98
+ optional_shapes = optional_shapes or {}
99
+ renames = renames or {}
100
+ converted = converted or {}
101
+ known = {**optional_shapes, **model_shapes}
102
+ canonical: Dict[str, str] = {}
103
+ for group in ties:
104
+ main = next((n for n in group if n in model_shapes), group[0])
105
+ for name in group:
106
+ canonical[name] = main
107
+ wanted = set(known) | set(canonical)
108
+
109
+ claims: Dict[str, List[Tuple[str, bool]]] = {} # weight -> [(file key, found through a tied name)]
110
+ unused: List[str] = []
111
+ for key in sorted(file_shapes):
112
+ if key in converted:
113
+ continue
114
+ target = key
115
+ if key_map is not None:
116
+ target = key_map(key) if callable(key_map) else key_map.get(key, key)
117
+ if target not in wanted:
118
+ target = renames[key] if renames.get(key) in wanted else _prefix_rename(target, wanted)
119
+ if target not in wanted:
120
+ unused.append(key)
121
+ continue
122
+ via_tie = target in canonical and canonical[target] != target
123
+ claims.setdefault(canonical.get(target, target), []).append((key, via_tie))
124
+
125
+ problems: List[str] = []
126
+ if converted:
127
+ problems.append(f"{len(converted)} tensors of the file need a conversion that renaming cannot do (the library fuses or "
128
+ f"splits them), e.g. {_few(f'{k} ({p})' for k, p in converted.items())}")
129
+ paired: Dict[str, str] = {}
130
+ mismatched: List[str] = []
131
+ ambiguous: List[str] = []
132
+ for name, found in sorted(claims.items()):
133
+ direct = [key for key, via_tie in found if not via_tie]
134
+ winners = direct or [key for key, _ in found[:1]]
135
+ if len(direct) > 1:
136
+ ambiguous.append(f"{name} <- {_few(direct)}")
137
+ continue
138
+ unused.extend(key for key, _ in found if key not in winners) # copies under another name of a tie
139
+ key = winners[0]
140
+ if tuple(file_shapes[key]) != tuple(known[name]):
141
+ mismatched.append(f"{name} {tuple(known[name])} <- {key} {tuple(file_shapes[key])}")
142
+ paired[key] = name
143
+ if mismatched:
144
+ problems.append(f"{len(mismatched)} tensors have another shape than their weight, e.g. {_few(mismatched, 2)}")
145
+ if ambiguous:
146
+ problems.append(f"{len(ambiguous)} weights are filled by more than one tensor, e.g. {_few(ambiguous, 2)}")
147
+ missing = [n for n in model_shapes if n not in claims]
148
+ if missing:
149
+ problems.append(f"{len(missing)} model weights are not in the file, e.g. {_few(missing)}")
150
+ if problems:
151
+ raise NameMismatch("the names of the weight file do not fit the model: " + "; ".join(problems) +
152
+ ". Pass key_map= to name the tensors yourself.")
153
+ return Pairing(names=paired, renamed={k: n for k, n in paired.items() if k != n}, unused=sorted(unused),
154
+ optional=sorted(n for n in optional_shapes if n not in claims))
155
+
156
+
157
+ Renamer = Callable[[Any, Sequence[str]], Tuple[Dict[str, str], Dict[str, str]]]
158
+
159
+
160
+ def pair_model(model, path, *, key_map=None, renamer: Optional[Renamer] = None) -> Pairing:
161
+ """The Pairing of the weight file at `path` with `model`, checked (see pair_names()); raises NameMismatch otherwise.
162
+
163
+ `renamer(model, file_keys)` gives the renames of the model's own library as ({file key: name}, {file key: pattern of a
164
+ conversion that renaming cannot do}): from_transformers.library_renames() for a transformers model, and for a diffusers
165
+ model what diffusers_renames() returns with no conversions. Without one only the model's own names, and a differing first
166
+ part of a name, are paired."""
167
+ from ..offload.checkpoint import Checkpoint
168
+ from .meta import tied_parameters
169
+
170
+ ck = Checkpoint(path)
171
+ keys = ck.keys()
172
+ renames, converted = renamer(model, keys) if renamer is not None else ({}, {})
173
+ return pair_names(
174
+ {n: tuple(p.shape) for n, p in model.named_parameters()}, {k: tuple(ck.info(k).shape) for k in keys},
175
+ optional_shapes={n: tuple(b.shape) for n, b in model.named_buffers()}, ties=tied_parameters(model),
176
+ renames=renames, converted=converted, key_map=key_map)
177
+
178
+
179
+ _UNSUPPORTED_SUFFIXES = {
180
+ ".weight_scale_inv": "fp8 with block-wise scales (`weight_scale_inv`)",
181
+ ".qweight": "GPTQ or AWQ quantization",
182
+ ".qzeros": "GPTQ or AWQ quantization",
183
+ ".absmax": "bitsandbytes quantization",
184
+ ".quant_map": "bitsandbytes quantization",
185
+ ".comfy_quant": "ComfyUI quantization (`comfy_quant`)",
186
+ }
187
+
188
+
189
+ def check_supported(file_keys: Iterable[str], quantization_config: Any = None) -> None:
190
+ """Stop with a clear message for weights in a format that trash-panda does not read yet: only ordinary float weights
191
+ (fp32, fp16, bf16) and fp8 with or without a scale per weight are. Raises NotImplementedError."""
192
+ if quantization_config:
193
+ method = quantization_config.get("quant_method") if isinstance(quantization_config, dict) else \
194
+ getattr(quantization_config, "quant_method", None)
195
+ raise NotImplementedError(f"this model is quantized ({method or 'quantization_config'}): trash-panda reads float "
196
+ "weights (fp32, fp16, bf16) and fp8 with a scale per weight, not other formats yet")
197
+ for key in file_keys:
198
+ for suffix, what in _UNSUPPORTED_SUFFIXES.items():
199
+ if key.endswith(suffix):
200
+ raise NotImplementedError(f"{key!r} is {what}: trash-panda reads float weights (fp32, fp16, bf16) and fp8 "
201
+ "with a scale per weight, not this format yet")
@@ -0,0 +1,63 @@
1
+ """Getting a model ready to load: everything that is done with the model before its weights are read.
2
+
3
+ `prepare_model()` takes a model that was built without weights (see meta.build_empty()) and the weight file, pairs and checks
4
+ the names, finds the buffers the file has nothing for and the weights that are tied, and makes the model say its dtype and
5
+ device. The result, a `Prepared`, is what `stream_load()` needs: the wrapper for one transformers model loads it at once
6
+ (trash_panda.transformers.model), and the wrapper for a diffusers pipeline hands it to its stages, which load it when the
7
+ pipeline first calls the component and give it back when the next one starts."""
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from typing import Any, Dict, List, Optional, Union
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+
18
+ from ..offload.checkpoint import Checkpoint
19
+ from .meta import buffers_to_keep, tied_parameters
20
+ from .names import Pairing, Renamer, pair_model
21
+ from .shim import shim_module
22
+
23
+
24
+ @dataclass
25
+ class Prepared:
26
+ """A model that is ready to load.
27
+
28
+ `model` is the placeholder (parameters on the meta device, real buffers, dtype and device shimmed), `path` the weight
29
+ file or its index, `key_map` what stream_load() takes to pair the names (None when no name differs), `kept` the buffers
30
+ that the file has nothing for (give them to stream_load() as `skip_prefixes`, and place them on the device after the
31
+ load), `ties` the groups of tied weights, `pairing` what the pairing found (None when the file already had every weight
32
+ and the pairing was not run), and `folder` the model's folder when it is known."""
33
+
34
+ model: nn.Module
35
+ path: Path
36
+ key_map: Optional[Dict[str, str]] = None
37
+ kept: List[str] = field(default_factory=list)
38
+ ties: List[List[str]] = field(default_factory=list)
39
+ pairing: Optional[Pairing] = None
40
+ folder: Optional[Path] = None
41
+ device: Optional[torch.device] = None
42
+ dtype: Optional[torch.dtype] = None
43
+
44
+
45
+ def prepare_model(model: nn.Module, path: Union[str, Path], *, device: torch.device, dtype: torch.dtype, key_map: Any = None,
46
+ renamer: Optional[Renamer] = None, always_pair: bool = True, folder: Optional[Path] = None) -> Prepared:
47
+ """The Prepared of `model` and the weights at `path`: `device` and `dtype` are where the model runs and the dtype its
48
+ blocks are expanded to (what `model.device` and `model.dtype` answer).
49
+
50
+ The names are paired and checked (pair_model(): `renamer` gives the renames of the model's library, `key_map` is the
51
+ caller's own and goes first), and a NameMismatch lists what does not fit. With `always_pair=False`, a file that already
52
+ has every parameter of the model under its own name is not paired, as long as no `key_map` is given: the check is skipped
53
+ and the renamer is not called, which saves building a copy of a large model for nothing."""
54
+ path = Path(path)
55
+ complete = not always_pair and key_map is None and \
56
+ {n for n, _ in model.named_parameters()} <= set(Checkpoint(path).keys())
57
+ pairing = None if complete else pair_model(model, path, key_map=key_map, renamer=renamer)
58
+ names = pairing.key_map() if pairing is not None else None
59
+ kept = buffers_to_keep(model, path, names)
60
+ ties = tied_parameters(model)
61
+ shim_module(model, device, dtype)
62
+ return Prepared(model=model, path=path, key_map=names, kept=kept, ties=ties, pairing=pairing, folder=folder,
63
+ device=device, dtype=dtype)
@@ -12,10 +12,9 @@ index to read is chosen here and handed to Checkpoint() by name."""
12
12
 
13
13
  from __future__ import annotations
14
14
 
15
- import json
16
15
  import re
17
16
  from pathlib import Path
18
- from typing import Dict, List, Optional, Sequence, Tuple, Union
17
+ from typing import List, Optional, Sequence, Union
19
18
 
20
19
  STEMS = ("diffusion_pytorch_model", "model") # the file names of a diffusers component and of a transformers model
21
20
  _OTHER_FORMATS = (".bin", ".pt", ".pth", ".ckpt", ".gguf")
@@ -82,24 +81,3 @@ def find_weights(folder: Union[str, Path], variant: Optional[str] = None, stems:
82
81
  if other:
83
82
  raise FileNotFoundError(f"no safetensors weights in {path}: only safetensors are read, and the folder has {other[:3]}")
84
83
  raise FileNotFoundError(f"no safetensors weights in {path}: looked for {', '.join(stems)}")
85
-
86
-
87
- def read_model_index(folder: Union[str, Path]) -> Dict[str, Tuple[str, str]]:
88
- """The components of a diffusers pipeline folder: {name: (library, class name)}, in the order of `model_index.json`.
89
-
90
- Only the entries that have a folder of their own are listed, so an entry that is null (a component the pipeline was
91
- saved without) and the keys that start with an underscore (`_class_name`, `_diffusers_version`) are left out. A
92
- component with no weights, such as a tokenizer or a scheduler, is listed too: ask find_weights() for the ones that
93
- are models."""
94
- folder = Path(folder)
95
- try:
96
- index = json.loads((folder / "model_index.json").read_text(encoding="utf-8"))
97
- except FileNotFoundError:
98
- raise FileNotFoundError(f"no model_index.json in {folder}: it is not a diffusers pipeline folder") from None
99
- found: Dict[str, Tuple[str, str]] = {}
100
- for name, entry in index.items():
101
- if name.startswith("_") or not isinstance(entry, (list, tuple)) or len(entry) != 2 or not all(entry):
102
- continue
103
- if (folder / name).is_dir():
104
- found[name] = (entry[0], entry[1])
105
- return found
@@ -0,0 +1,5 @@
1
+ """Running diffusers pipelines with trash-panda. It imports nothing from diffusers or transformers until it needs them."""
2
+
3
+ from .pipeline import TrashPandaDiffusionPipeline, TrashPandaPipeline
4
+
5
+ __all__ = ["TrashPandaDiffusionPipeline", "TrashPandaPipeline"]
@@ -3,29 +3,20 @@
3
3
  resolve_source("sd3-medium/") # a folder: used as it is
4
4
  resolve_source("stabilityai/stable-diffusion-3-...") # a repo id: fetched, then the folder in the cache
5
5
 
6
- Only the files that are needed are fetched. A repo holds the same weights in several formats and variants, and most of
7
- them are never read: the weights of a component are taken as safetensors, one variant of them, and the single-file
8
- checkpoints at the top of a repo are left out. A component that has no safetensors keeps the files it has, because
9
- diffusers loads those the normal way. `huggingface_hub` is imported when a repo is fetched, not before."""
6
+ Only the files that are needed are fetched (select_files()). A repo holds the same weights in several formats and variants,
7
+ and most of them are never read: the weights of a component are taken as safetensors, one variant of them, and the
8
+ single-file checkpoints at the top of a repo are left out. A component that has no safetensors keeps the files it has,
9
+ because diffusers loads those the normal way. The folder and the Hub are handled in trash_panda.common.hub."""
10
10
 
11
11
  from __future__ import annotations
12
12
 
13
- import glob
14
13
  import re
15
14
  from collections import defaultdict
16
15
  from pathlib import Path
17
16
  from typing import Dict, List, Optional, Sequence, Union
18
17
 
19
- from .weights import STEMS
20
-
21
- _REPO_ID = re.compile(r"^[A-Za-z0-9][\w.\-]*/[A-Za-z0-9][\w.\-]*$", re.ASCII) # owner/name: letters, digits, _ - .
22
- _WEIGHT_SUFFIXES = (".bin", ".ckpt", ".pt", ".pth", ".onnx", ".onnx_data", ".msgpack", ".h5", ".gguf", ".pb", ".tflite", ".ot")
23
- _NEVER = (".md", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".mp4") # never needed to run a pipeline
24
-
25
-
26
- def is_repo_id(text: str) -> bool:
27
- """True for the form of a Hub repo id: `owner/name`."""
28
- return bool(_REPO_ID.match(str(text)))
18
+ from ..common.hub import _NEVER, _WEIGHT_SUFFIXES, _default_client, _HubClient, is_repo_id, resolve_folder # noqa: F401
19
+ from ..common.weights import STEMS
29
20
 
30
21
 
31
22
  def _safetensors_variant(name: str):
@@ -90,64 +81,12 @@ def select_files(files: Sequence[str], variant: Optional[str] = None) -> List[st
90
81
  return sorted(set(chosen))
91
82
 
92
83
 
93
- class _HubClient:
94
- """What is asked of the Hub: the names of the files of a repo, and a download of some of them."""
95
-
96
- def list_files(self, repo_id: str, revision: Optional[str], token: Optional[str]) -> List[str]:
97
- from huggingface_hub import HfApi
98
-
99
- return list(HfApi(token=token).list_repo_files(repo_id, revision=revision))
100
-
101
- def download(self, repo_id: str, files: Optional[Sequence[str]], revision: Optional[str], token: Optional[str],
102
- cache_dir: Union[None, str, Path], local_files_only: bool) -> str:
103
- from huggingface_hub import snapshot_download
104
-
105
- patterns = None if files is None else [glob.escape(file) for file in files]
106
- return snapshot_download(repo_id, revision=revision, token=token, cache_dir=cache_dir, allow_patterns=patterns,
107
- local_files_only=local_files_only)
108
-
109
-
110
- def _default_client() -> _HubClient:
111
- try:
112
- import huggingface_hub # noqa: F401
113
- except ImportError:
114
- raise ImportError("fetching a pipeline from the Hugging Face Hub needs huggingface_hub: "
115
- "pip install huggingface_hub (or give a folder on disk)") from None
116
- return _HubClient()
117
-
118
-
119
84
  def resolve_source(source: Union[str, Path], *, hub: Optional[bool] = None, variant: Optional[str] = None,
120
85
  revision: Optional[str] = None, token: Optional[str] = None, cache_dir: Union[None, str, Path] = None,
121
86
  local_files_only: bool = False, client=None) -> Path:
122
87
  """The folder of the pipeline `source` names: `source` itself when it is a folder, else the repo of that name fetched
123
- into the Hub cache.
124
-
125
- hub None decides by looking: an existing folder is used, and what has the form `owner/name` is a repo id. True is a
126
- repo id even if a folder of that name exists; False is a folder and nothing else.
127
- variant picks which weights are fetched (see select_files())
128
- revision, token, cache_dir as for the Hub: a branch or commit, a login token (default: the one that is logged in
129
- or in HF_TOKEN) for gated models, and where the cache is (default: the Hub's)
130
- local_files_only do not go online: the snapshot that is in the cache already, whole
131
- client what talks to the Hub, for tests"""
132
- path = Path(source)
133
- if hub is False or (hub is None and path.is_dir()):
134
- if not path.is_dir():
135
- raise ValueError(f"{source} is not a folder (hub=False was given)")
136
- return path
137
- if not is_repo_id(str(source)):
138
- what = "a repo id of the form owner/name" if hub else "a folder or a repo id of the form owner/name"
139
- raise ValueError(f"{source!r} is not {what}")
140
- repo_id = str(source)
141
- client = client or _default_client()
142
- try:
143
- if local_files_only:
144
- files = None
145
- else:
146
- files = select_files(client.list_files(repo_id, revision, token), variant)
147
- print(f"trash-panda: fetching {len(files)} files of {repo_id} (the ones in the cache are not fetched again)")
148
- return Path(client.download(repo_id, files, revision, token, cache_dir, local_files_only))
149
- except ValueError:
150
- raise
151
- except Exception as err:
152
- raise OSError(f"could not get {repo_id} from the Hugging Face Hub: {err}. If it is a folder on disk, check the "
153
- "path or pass hub=False") from err
88
+ into the Hub cache (see trash_panda.common.hub.resolve_folder() for the arguments). The files that are fetched are
89
+ those of select_files(). `client` is what talks to the Hub, for tests."""
90
+ return resolve_folder(source, select_files, hub=hub, variant=variant, revision=revision, token=token,
91
+ cache_dir=cache_dir, local_files_only=local_files_only, client=client,
92
+ make_client=lambda: _default_client()) # looked up here, so a test can replace it