dumpsterpanda 0.2.3__tar.gz → 0.3.0__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.
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/PKG-INFO +18 -1
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/README.md +17 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/pyproject.toml +1 -1
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/__init__.py +1 -1
- dumpsterpanda-0.3.0/src/trash_panda/diffusers/__init__.py +5 -0
- dumpsterpanda-0.3.0/src/trash_panda/diffusers/hub.py +153 -0
- dumpsterpanda-0.3.0/src/trash_panda/diffusers/meta.py +128 -0
- dumpsterpanda-0.3.0/src/trash_panda/diffusers/pipeline.py +272 -0
- dumpsterpanda-0.3.0/src/trash_panda/diffusers/shim.py +46 -0
- dumpsterpanda-0.3.0/src/trash_panda/diffusers/stages.py +219 -0
- dumpsterpanda-0.3.0/src/trash_panda/diffusers/weights.py +105 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/offload/config.py +2 -1
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/offload/loader.py +17 -1
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/LICENSE +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/cli/__init__.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/cli/app.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/cli/config.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/cli/hardware.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/cli/info.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/cli/names.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/cli/plan.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/cli/trace.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/offload/__init__.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/offload/blocks.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/offload/checkpoint.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/offload/coordinator.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/offload/depth.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/offload/early.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/offload/formats.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/offload/hardware.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/offload/hooks.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/offload/measure.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/offload/order_file.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/offload/planner.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/offload/report.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/offload/stage.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/offload/trace.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/paths.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/ui/__init__.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/ui/load.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/ui/server.py +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/ui/static/app.js +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/ui/static/bars.js +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/ui/static/data.js +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/ui/static/files.js +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/ui/static/index.html +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/ui/static/memory.js +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/ui/static/memorychart.js +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/ui/static/package.json +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/ui/static/panels.js +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/ui/static/style.css +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/ui/static/svg.js +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/src/trash_panda/ui/static/timeline.js +0 -0
- {dumpsterpanda-0.2.3 → dumpsterpanda-0.3.0}/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
|
+
Version: 0.3.0
|
|
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
|
|
@@ -139,6 +139,22 @@ with co:
|
|
|
139
139
|
image = decode(vae, latents)
|
|
140
140
|
```
|
|
141
141
|
|
|
142
|
+
A `diffusers` pipeline, from the Hugging Face Hub or a folder. Its large components (text encoders, the denoiser, the
|
|
143
|
+
VAE) run in stages, one at a time, with no other setup:
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
from diffusers import StableDiffusionXLPipeline
|
|
147
|
+
from trash_panda.diffusers import TrashPandaPipeline
|
|
148
|
+
|
|
149
|
+
pipe = TrashPandaPipeline.from_pretrained(StableDiffusionXLPipeline, "stabilityai/stable-diffusion-xl-base-1.0",
|
|
150
|
+
variant="fp16") # or a folder: "/models/sdxl-base"
|
|
151
|
+
image = pipe("a raccoon in a yellow raincoat").images[0]
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
`diffusers` and `transformers` are not dependencies of trash-panda: install the ones your pipeline needs. Options
|
|
155
|
+
(`offload`, `order`, `plans`, `preload`, `compute_dtype`) are in the
|
|
156
|
+
[guide](https://yla382.github.io/trashpanda/guides/diffusers/).
|
|
157
|
+
|
|
142
158
|
## Command line
|
|
143
159
|
|
|
144
160
|
Look at a checkpoint without loading it. `plan` shows where each block would live on this machine, and `info` shows what is
|
|
@@ -199,6 +215,7 @@ The recording above is an example trace (made-up data, not a measurement).
|
|
|
199
215
|
* [Quick start](https://yla382.github.io/trashpanda/quickstart/): from install to a first run
|
|
200
216
|
* Guides: [running a stage](https://yla382.github.io/trashpanda/guides/running-a-stage/),
|
|
201
217
|
[running a pipeline](https://yla382.github.io/trashpanda/guides/running-a-pipeline/),
|
|
218
|
+
[running a diffusers pipeline](https://yla382.github.io/trashpanda/guides/diffusers/),
|
|
202
219
|
[storage dtype](https://yla382.github.io/trashpanda/guides/storage-dtype/) and the
|
|
203
220
|
[command line](https://yla382.github.io/trashpanda/guides/command-line/)
|
|
204
221
|
* [API reference](https://yla382.github.io/trashpanda/reference/): every public function and class, with its
|
|
@@ -111,6 +111,22 @@ with co:
|
|
|
111
111
|
image = decode(vae, latents)
|
|
112
112
|
```
|
|
113
113
|
|
|
114
|
+
A `diffusers` pipeline, from the Hugging Face Hub or a folder. Its large components (text encoders, the denoiser, the
|
|
115
|
+
VAE) run in stages, one at a time, with no other setup:
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
from diffusers import StableDiffusionXLPipeline
|
|
119
|
+
from trash_panda.diffusers import TrashPandaPipeline
|
|
120
|
+
|
|
121
|
+
pipe = TrashPandaPipeline.from_pretrained(StableDiffusionXLPipeline, "stabilityai/stable-diffusion-xl-base-1.0",
|
|
122
|
+
variant="fp16") # or a folder: "/models/sdxl-base"
|
|
123
|
+
image = pipe("a raccoon in a yellow raincoat").images[0]
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
`diffusers` and `transformers` are not dependencies of trash-panda: install the ones your pipeline needs. Options
|
|
127
|
+
(`offload`, `order`, `plans`, `preload`, `compute_dtype`) are in the
|
|
128
|
+
[guide](https://yla382.github.io/trashpanda/guides/diffusers/).
|
|
129
|
+
|
|
114
130
|
## Command line
|
|
115
131
|
|
|
116
132
|
Look at a checkpoint without loading it. `plan` shows where each block would live on this machine, and `info` shows what is
|
|
@@ -171,6 +187,7 @@ The recording above is an example trace (made-up data, not a measurement).
|
|
|
171
187
|
* [Quick start](https://yla382.github.io/trashpanda/quickstart/): from install to a first run
|
|
172
188
|
* Guides: [running a stage](https://yla382.github.io/trashpanda/guides/running-a-stage/),
|
|
173
189
|
[running a pipeline](https://yla382.github.io/trashpanda/guides/running-a-pipeline/),
|
|
190
|
+
[running a diffusers pipeline](https://yla382.github.io/trashpanda/guides/diffusers/),
|
|
174
191
|
[storage dtype](https://yla382.github.io/trashpanda/guides/storage-dtype/) and the
|
|
175
192
|
[command line](https://yla382.github.io/trashpanda/guides/command-line/)
|
|
176
193
|
* [API reference](https://yla382.github.io/trashpanda/reference/): every public function and class, with its
|
|
@@ -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
|
+
__version__ = "0.3.0"
|
|
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,153 @@
|
|
|
1
|
+
"""Getting the folder of a pipeline: a folder on disk, or a repository of the Hugging Face Hub fetched into its cache.
|
|
2
|
+
|
|
3
|
+
resolve_source("sd3-medium/") # a folder: used as it is
|
|
4
|
+
resolve_source("stabilityai/stable-diffusion-3-...") # a repo id: fetched, then the folder in the cache
|
|
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."""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import glob
|
|
14
|
+
import re
|
|
15
|
+
from collections import defaultdict
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Dict, List, Optional, Sequence, Union
|
|
18
|
+
|
|
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)))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _safetensors_variant(name: str):
|
|
32
|
+
"""(True, the variant or None) for a safetensors weight file or the index json of safetensors shards, else (False, None)."""
|
|
33
|
+
for stem in STEMS:
|
|
34
|
+
s = re.escape(stem)
|
|
35
|
+
for pattern in (rf"{s}\.(?P<v>[^.\-]+)(?:-\d{{5}}-of-\d{{5}})?\.safetensors", # a variant, whole or a shard of it
|
|
36
|
+
rf"{s}\.safetensors\.index\.(?P<v>[^.]+)\.json", # the index of a sharded variant
|
|
37
|
+
rf"{s}(?:-\d{{5}}-of-\d{{5}})?\.safetensors", # plain, whole or a shard
|
|
38
|
+
rf"{s}\.safetensors\.index\.json"): # the index of plain shards
|
|
39
|
+
match = re.fullmatch(pattern, name)
|
|
40
|
+
if match:
|
|
41
|
+
return True, (match.groupdict().get("v") or None)
|
|
42
|
+
if name.endswith(".safetensors") or re.fullmatch(r".+\.safetensors\.index(\.[^.]+)?\.json", name):
|
|
43
|
+
return True, None # another name: no variant
|
|
44
|
+
return False, None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _is_other_weight(name: str) -> bool:
|
|
48
|
+
return name.endswith(_WEIGHT_SUFFIXES) or bool(re.fullmatch(r".+\.(bin|ckpt|pt|pth)\.index(\.[^.]+)?\.json", name))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def select_files(files: Sequence[str], variant: Optional[str] = None) -> List[str]:
|
|
52
|
+
"""The files of a repo that a pipeline needs, from the repo's list of file names.
|
|
53
|
+
|
|
54
|
+
The small files all stay (configs, tokenizers, the scheduler) except pictures and notes. In each folder the
|
|
55
|
+
safetensors weights of `variant` stay (the plain ones if the folder has no such variant, as diffusers does), with
|
|
56
|
+
no other variant and no weights of another format. A folder with no safetensors keeps its other weights. Weights
|
|
57
|
+
at the top of the repo are left out: the components are in the folders.
|
|
58
|
+
|
|
59
|
+
Raises ValueError when a folder has only variants and none was asked for."""
|
|
60
|
+
by_folder: Dict[str, List[str]] = defaultdict(list)
|
|
61
|
+
for file in files:
|
|
62
|
+
folder, _, name = file.rpartition("/")
|
|
63
|
+
by_folder[folder].append(name)
|
|
64
|
+
chosen: List[str] = []
|
|
65
|
+
for folder, names in by_folder.items():
|
|
66
|
+
def full(name):
|
|
67
|
+
return f"{folder}/{name}" if folder else name
|
|
68
|
+
|
|
69
|
+
safe = [(name, _safetensors_variant(name)[1]) for name in names if _safetensors_variant(name)[0]]
|
|
70
|
+
others = [name for name in names if not _safetensors_variant(name)[0] and _is_other_weight(name)]
|
|
71
|
+
plain = [name for name, v in safe if v is None]
|
|
72
|
+
if folder == "":
|
|
73
|
+
weights = set(name for name, _ in safe) | set(others) # single-file checkpoints: not needed
|
|
74
|
+
elif safe:
|
|
75
|
+
if variant:
|
|
76
|
+
use = [name for name, v in safe if v == variant] or plain
|
|
77
|
+
else:
|
|
78
|
+
use = plain
|
|
79
|
+
if not plain:
|
|
80
|
+
raise ValueError(f"{folder}/ has only the variants {sorted({v for _, v in safe if v})} of its weights: "
|
|
81
|
+
"say which with variant=")
|
|
82
|
+
weights = set(name for name, _ in safe) | set(others)
|
|
83
|
+
chosen.extend(full(name) for name in use)
|
|
84
|
+
else:
|
|
85
|
+
weights = set() # no safetensors: its other weights stay
|
|
86
|
+
for name in names:
|
|
87
|
+
if name in weights or name.startswith(".") or name.lower().endswith(_NEVER) or name.upper().startswith("LICENSE"):
|
|
88
|
+
continue
|
|
89
|
+
chosen.append(full(name))
|
|
90
|
+
return sorted(set(chosen))
|
|
91
|
+
|
|
92
|
+
|
|
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
|
+
def resolve_source(source: Union[str, Path], *, hub: Optional[bool] = None, variant: Optional[str] = None,
|
|
120
|
+
revision: Optional[str] = None, token: Optional[str] = None, cache_dir: Union[None, str, Path] = None,
|
|
121
|
+
local_files_only: bool = False, client=None) -> Path:
|
|
122
|
+
"""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
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Building a model without its weights: the parameters on the meta device, the buffers real.
|
|
2
|
+
|
|
3
|
+
A buffer that the model works out while it is built (a rotary table, position ids) is not in a checkpoint, and on the meta
|
|
4
|
+
device it has no values. So the model is built with its parameters on the meta device and its buffers in memory
|
|
5
|
+
(`empty_weights()`), `buffers_to_keep()` names the buffers that the checkpoint has nothing for, and they are given to
|
|
6
|
+
`stream_load()` or `stage()` as `skip_prefixes`, so that they are neither loaded nor required. `place_buffers()` then moves
|
|
7
|
+
them to the compute device."""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections import defaultdict
|
|
12
|
+
from contextlib import contextmanager
|
|
13
|
+
from typing import Dict, List, Optional, Sequence, Union
|
|
14
|
+
|
|
15
|
+
import torch
|
|
16
|
+
import torch.nn as nn
|
|
17
|
+
|
|
18
|
+
from ..offload.checkpoint import Checkpoint, name_resolver
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@contextmanager
|
|
22
|
+
def empty_weights():
|
|
23
|
+
"""Build a model inside this block with its parameters on the meta device and its buffers as the code makes them.
|
|
24
|
+
|
|
25
|
+
with empty_weights():
|
|
26
|
+
model = MyModel(config).eval()
|
|
27
|
+
|
|
28
|
+
No weight is kept in memory, and stream_load() fills the parameters from the checkpoint. The buffers are made as
|
|
29
|
+
usual, which is the difference from `torch.device("meta")`: that puts the buffers on the meta device too, so a
|
|
30
|
+
buffer that the code works out while it builds the model has no values there. Built here, it holds its real value.
|
|
31
|
+
|
|
32
|
+
It works by replacing `torch.nn.Module.register_parameter` for the length of the block, so it also covers a
|
|
33
|
+
parameter that the code assigns as an attribute. The original is put back when the block ends, also when it raises.
|
|
34
|
+
The replacement is global while the block lasts, so do not build models on two threads at once inside it."""
|
|
35
|
+
register = nn.Module.register_parameter
|
|
36
|
+
|
|
37
|
+
def register_empty(module, name, param):
|
|
38
|
+
register(module, name, param)
|
|
39
|
+
made = module._parameters[name]
|
|
40
|
+
if made is not None and not made.is_meta:
|
|
41
|
+
kwargs = dict(made.__dict__)
|
|
42
|
+
kwargs["requires_grad"] = made.requires_grad
|
|
43
|
+
module._parameters[name] = type(made)(made.data.to("meta"), **kwargs)
|
|
44
|
+
|
|
45
|
+
nn.Module.register_parameter = register_empty
|
|
46
|
+
try:
|
|
47
|
+
yield
|
|
48
|
+
finally:
|
|
49
|
+
nn.Module.register_parameter = register
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def buffers_to_keep(model: nn.Module, checkpoint: Union[str, Checkpoint], key_map=None) -> List[str]:
|
|
53
|
+
"""The names of the buffers of `model` that hold their values (they are not on the meta device) and that the
|
|
54
|
+
checkpoint has no tensor for. Give them to stream_load() or stage() as `skip_prefixes=` so that they are not required,
|
|
55
|
+
and call place_buffers() after the load.
|
|
56
|
+
|
|
57
|
+
`key_map` is the one given to stream_load(), because a checkpoint name is matched to the model's name through it. A
|
|
58
|
+
name is used as a prefix by `skip_prefixes`, so if another entry of the model starts with one of these names and is
|
|
59
|
+
not one of them (`rope` and `rope_long.weight`), it would be skipped too: that raises a ValueError."""
|
|
60
|
+
ck = checkpoint if isinstance(checkpoint, Checkpoint) else Checkpoint(checkpoint)
|
|
61
|
+
entries = {n for n, _ in model.named_parameters()} | {n for n, _ in model.named_buffers()}
|
|
62
|
+
resolve = name_resolver(entries, key_map)
|
|
63
|
+
covered = {resolve(key) for key in ck.keys()}
|
|
64
|
+
names = sorted(n for n, b in model.named_buffers() if not b.is_meta and n not in covered)
|
|
65
|
+
kept = set(names)
|
|
66
|
+
for name in names:
|
|
67
|
+
clash = sorted(other for other in entries if other != name and other.startswith(name) and other not in kept)
|
|
68
|
+
if clash:
|
|
69
|
+
raise ValueError(f"skip_prefixes={name!r} would also skip {clash[:3]}: rename the buffer, or load it from the "
|
|
70
|
+
"checkpoint")
|
|
71
|
+
return names
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _locate(model: nn.Module, name: str):
|
|
75
|
+
"""(the module that holds the buffer, the buffer's own name in it)."""
|
|
76
|
+
owner_name, _, leaf = name.rpartition(".")
|
|
77
|
+
return model.get_submodule(owner_name), leaf
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def place_buffers(model: nn.Module, names: Sequence[str], device: Optional[Union[str, torch.device]] = None) -> None:
|
|
81
|
+
"""Move the buffers called `names` (from buffers_to_keep()) to `device`, keeping their dtype. A model that was loaded
|
|
82
|
+
with stream_load() has its other tensors on the compute device already, and a buffer left on the CPU would meet
|
|
83
|
+
them in the forward pass. Call it after the load."""
|
|
84
|
+
for name in names:
|
|
85
|
+
owner, leaf = _locate(model, name)
|
|
86
|
+
owner._buffers[leaf] = owner._buffers[leaf].to(device)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def save_buffers(model: nn.Module, names: Sequence[str]) -> Dict[str, torch.Tensor]:
|
|
90
|
+
"""Copies of the buffers called `names`, for restore_buffers(). release() leaves every buffer of a model on the meta
|
|
91
|
+
device, so a model that is loaded again after it needs the values that its kept buffers had when it was built."""
|
|
92
|
+
saved = {}
|
|
93
|
+
for name in names:
|
|
94
|
+
owner, leaf = _locate(model, name)
|
|
95
|
+
saved[name] = owner._buffers[leaf].detach().clone()
|
|
96
|
+
return saved
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def restore_buffers(model: nn.Module, saved: Dict[str, torch.Tensor]) -> None:
|
|
100
|
+
"""Put back the buffers that save_buffers() copied (as new copies, so what is kept stays as it was)."""
|
|
101
|
+
for name, tensor in saved.items():
|
|
102
|
+
owner, leaf = _locate(model, name)
|
|
103
|
+
owner._buffers[leaf] = tensor.clone()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def tied_parameters(model: nn.Module) -> List[List[str]]:
|
|
107
|
+
"""The groups of names that hold one and the same parameter: weights that the model ties together, such as the
|
|
108
|
+
embedding of a T5 (`shared.weight` and `encoder.embed_tokens.weight`) or an output layer that shares the embedding.
|
|
109
|
+
|
|
110
|
+
`named_parameters()` lists a tied weight under its first name only, so stream_load() fills that one, and the others
|
|
111
|
+
keep their empty placeholder: tie_parameters() puts the loaded weight under all of them. Call this on the model as it
|
|
112
|
+
was built, while the ties are there."""
|
|
113
|
+
groups: Dict[int, List[str]] = defaultdict(list)
|
|
114
|
+
for name, param in model.named_parameters(remove_duplicate=False):
|
|
115
|
+
groups[id(param)].append(name)
|
|
116
|
+
return [names for names in groups.values() if len(names) > 1]
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def tie_parameters(model: nn.Module, groups: Sequence[Sequence[str]]) -> None:
|
|
120
|
+
"""Make every name of a group hold one parameter again: the one that was loaded under one of them, or, when none
|
|
121
|
+
was loaded, the first one. release() gives each name its own empty parameter, which breaks the tie and makes the next
|
|
122
|
+
stream_load() ask the file for a weight that it holds once, so call this before a load as well as after it."""
|
|
123
|
+
for names in groups:
|
|
124
|
+
parameters = [model.get_parameter(n) for n in names]
|
|
125
|
+
shared = next((p for p in parameters if not p.is_meta), parameters[0])
|
|
126
|
+
for name in names:
|
|
127
|
+
owner, leaf = _locate(model, name)
|
|
128
|
+
owner._parameters[leaf] = shared
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"""A diffusers pipeline whose large components run in stages: `TrashPandaPipeline.from_pretrained(PipelineClass, folder)`.
|
|
2
|
+
|
|
3
|
+
pipe = TrashPandaPipeline.from_pretrained(StableDiffusion3Pipeline, "sd3-medium/", variant="fp16")
|
|
4
|
+
image = pipe("a raccoon").images[0]
|
|
5
|
+
|
|
6
|
+
The result is an instance of a subclass of `PipelineClass` (same name, same `isinstance` answers), so everything else of the
|
|
7
|
+
pipeline works as it does. Its large components (the models that its `model_cpu_offload_seq` names) are placeholders built
|
|
8
|
+
from their configs with no weights in memory: each one loads when the pipeline first calls it and is given back when the
|
|
9
|
+
next one starts, and all are given back when the call ends. See Stages. The small parts (tokenizers, the scheduler, the
|
|
10
|
+
components that are not staged) load the normal way.
|
|
11
|
+
|
|
12
|
+
The pipeline can be a folder on disk or a repo of the Hugging Face Hub (`"owner/name"`, fetched into the Hub's cache: see
|
|
13
|
+
resolve_source()). The staged components are read from safetensors weights. diffusers and transformers are imported when
|
|
14
|
+
they are needed, not before."""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import importlib
|
|
19
|
+
import warnings
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any, Dict, List, Mapping, Optional, Sequence, Union
|
|
22
|
+
|
|
23
|
+
import torch
|
|
24
|
+
import torch.nn as nn
|
|
25
|
+
|
|
26
|
+
from ..offload.checkpoint import Checkpoint
|
|
27
|
+
from ..offload.formats import parse_dtype
|
|
28
|
+
from .hub import resolve_source
|
|
29
|
+
from .meta import empty_weights
|
|
30
|
+
from .shim import shim_module
|
|
31
|
+
from .stages import Component, Stages
|
|
32
|
+
from .weights import find_weights, read_model_index
|
|
33
|
+
|
|
34
|
+
_STAGED_CLASSES: Dict[type, type] = {}
|
|
35
|
+
_PRELOAD_KEYS = ("ram", "vram")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _load_class(library: str, class_name: str):
|
|
39
|
+
"""The class `class_name` of `library`, or None when the library or the class cannot be imported."""
|
|
40
|
+
try:
|
|
41
|
+
cls = getattr(importlib.import_module(library), class_name, None)
|
|
42
|
+
except Exception: # a library that is not there, or one that fails while it imports the class
|
|
43
|
+
return None
|
|
44
|
+
return cls if isinstance(cls, type) else None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _is_model(cls) -> bool:
|
|
48
|
+
return isinstance(cls, type) and issubclass(cls, nn.Module)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _placeholder(cls: type, folder: Path) -> nn.Module:
|
|
52
|
+
"""The model of class `cls` built from the config in `folder`, with its parameters on the meta device and its buffers
|
|
53
|
+
real: a diffusers model (`load_config`, `from_config`) or a transformers model (`config_class`, `_from_config`)."""
|
|
54
|
+
if hasattr(cls, "load_config") and hasattr(cls, "from_config"):
|
|
55
|
+
config = cls.load_config(str(folder))
|
|
56
|
+
with empty_weights():
|
|
57
|
+
return cls.from_config(config)
|
|
58
|
+
config_class = getattr(cls, "config_class", None)
|
|
59
|
+
if config_class is not None and hasattr(cls, "_from_config"):
|
|
60
|
+
config = config_class.from_pretrained(str(folder))
|
|
61
|
+
with empty_weights():
|
|
62
|
+
return cls._from_config(config)
|
|
63
|
+
raise TypeError(f"cannot build {cls.__name__} from a config: it is neither a diffusers model (load_config and "
|
|
64
|
+
"from_config) nor a transformers model (config_class and _from_config)")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _key_map_for(module: nn.Module, path: Path):
|
|
68
|
+
"""A function from the keys of the weight file to the names the model uses, or None when the file has every weight of
|
|
69
|
+
the model under its own name.
|
|
70
|
+
|
|
71
|
+
A transformers model can name its layers with another prefix than the file that an older version saved: SDXL's first
|
|
72
|
+
text encoder has `text_model.embeddings...` in the file, and the model of transformers 5 has `embeddings...`. The
|
|
73
|
+
function takes off a first part that the model does not have, or puts on one that it has and the file does not, and
|
|
74
|
+
leaves every other key as it is."""
|
|
75
|
+
if {n for n, _ in module.named_parameters()} <= set(Checkpoint(path).keys()):
|
|
76
|
+
return None
|
|
77
|
+
wanted = {n for n, _ in module.named_parameters()} | {n for n, _ in module.named_buffers()}
|
|
78
|
+
prefixes = sorted({n.split(".", 1)[0] for n in wanted if "." in n})
|
|
79
|
+
|
|
80
|
+
def rename(key: str) -> str:
|
|
81
|
+
if key in wanted:
|
|
82
|
+
return key
|
|
83
|
+
_, _, rest = key.partition(".")
|
|
84
|
+
if rest in wanted: # the file has a prefix that the model does not
|
|
85
|
+
return rest
|
|
86
|
+
for prefix in prefixes:
|
|
87
|
+
if f"{prefix}.{key}" in wanted: # the model has a prefix that the file does not
|
|
88
|
+
return f"{prefix}.{key}"
|
|
89
|
+
return key
|
|
90
|
+
|
|
91
|
+
return rename
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _weights(folder: Path, variant: Optional[str]) -> Path:
|
|
95
|
+
"""The weights of a component. A variant that this component does not have gives its plain weights, as diffusers does."""
|
|
96
|
+
try:
|
|
97
|
+
return find_weights(folder, variant)
|
|
98
|
+
except FileNotFoundError as first:
|
|
99
|
+
if variant:
|
|
100
|
+
try:
|
|
101
|
+
return find_weights(folder, None)
|
|
102
|
+
except FileNotFoundError:
|
|
103
|
+
pass
|
|
104
|
+
raise first
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _declared_order(pipeline_class: type) -> List[str]:
|
|
108
|
+
seq = getattr(pipeline_class, "model_cpu_offload_seq", None)
|
|
109
|
+
return [name.strip() for name in seq.split("->")] if seq else []
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def staged_components(pipeline_class: type, folder: Union[str, Path], *, offload: Optional[Sequence[str]] = None,
|
|
113
|
+
order: Optional[Sequence[str]] = None, plans: Optional[Mapping[str, Mapping[str, Any]]] = None,
|
|
114
|
+
variant: Optional[str] = None, compute_dtype: Any = "bf16",
|
|
115
|
+
device: Union[None, str, torch.device] = None) -> Dict[str, Component]:
|
|
116
|
+
"""The components of the pipeline in `folder` that run in stages, in the order they run: {name: Component}.
|
|
117
|
+
|
|
118
|
+
A component that is a model (its class is an nn.Module, as the folder's `model_index.json` says) is a placeholder
|
|
119
|
+
here, built from its config. Without `offload` those are the models that the pipeline's `model_cpu_offload_seq` names
|
|
120
|
+
that have safetensors weights; a model without them is left to the normal loading, with a warning. With `offload`,
|
|
121
|
+
those names, and a name that cannot be staged is an error. `order` replaces `model_cpu_offload_seq`. `plans` maps a
|
|
122
|
+
name to the arguments of stage() for it (`resident_blocks`, `max_vram`, ...); `compute_dtype` is the default of them
|
|
123
|
+
all. The `dtype` and `device` of each placeholder are the dtype it is expanded to and `device`."""
|
|
124
|
+
folder = Path(folder)
|
|
125
|
+
if not folder.is_dir():
|
|
126
|
+
raise ValueError(f"{folder} is not a folder: only local pipeline folders are read for now")
|
|
127
|
+
index = read_model_index(folder)
|
|
128
|
+
plans = {name: dict(options) for name, options in (plans or {}).items()}
|
|
129
|
+
for what, names in (("order", order or ()), ("offload", offload or ()), ("plans", plans)):
|
|
130
|
+
unknown = [n for n in names if n not in index]
|
|
131
|
+
if unknown:
|
|
132
|
+
raise ValueError(f"{what} names {unknown}, which are not components of {folder}: they are {list(index)}")
|
|
133
|
+
models = {}
|
|
134
|
+
for name, (library, class_name) in index.items():
|
|
135
|
+
cls = _load_class(library, class_name)
|
|
136
|
+
if _is_model(cls):
|
|
137
|
+
models[name] = cls
|
|
138
|
+
seq = list(order) if order is not None else _declared_order(pipeline_class)
|
|
139
|
+
if offload is not None:
|
|
140
|
+
wanted = list(offload)
|
|
141
|
+
not_models = [n for n in wanted if n not in models]
|
|
142
|
+
if not_models:
|
|
143
|
+
raise ValueError(f"{not_models} cannot be staged: they are not models that can be built from a config "
|
|
144
|
+
f"({[index[n] for n in not_models]})")
|
|
145
|
+
else:
|
|
146
|
+
if not seq:
|
|
147
|
+
raise ValueError(f"{pipeline_class.__name__} does not say in which order its components run "
|
|
148
|
+
"(model_cpu_offload_seq): pass order=[...]")
|
|
149
|
+
wanted = [n for n in seq if n in models]
|
|
150
|
+
run_order = [n for n in seq if n in wanted] + [n for n in wanted if n not in seq]
|
|
151
|
+
device = torch.device(device) if device is not None else torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
152
|
+
|
|
153
|
+
components: Dict[str, Component] = {}
|
|
154
|
+
for name in run_order:
|
|
155
|
+
try:
|
|
156
|
+
path = _weights(folder / name, variant)
|
|
157
|
+
except FileNotFoundError as err:
|
|
158
|
+
if offload is not None:
|
|
159
|
+
raise
|
|
160
|
+
warnings.warn(f"trash-panda: {name} is left to the normal loading: {err}", UserWarning, stacklevel=3)
|
|
161
|
+
continue
|
|
162
|
+
options = plans.get(name, {})
|
|
163
|
+
options.setdefault("compute_dtype", compute_dtype)
|
|
164
|
+
module = _placeholder(models[name], folder / name)
|
|
165
|
+
shim_module(module, device, parse_dtype(options["compute_dtype"]) or torch.bfloat16)
|
|
166
|
+
components[name] = Component(module, path, key_map=_key_map_for(module, path), options=options)
|
|
167
|
+
if not components:
|
|
168
|
+
raise ValueError(f"no component of {folder} can be staged (the models are {list(models)})")
|
|
169
|
+
return components
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class StagedPipelineMixin:
|
|
173
|
+
"""What the pipeline class gets from TrashPandaPipeline.from_pretrained(): the staged call, and the methods of a
|
|
174
|
+
pipeline that would fight the stages. It has no `__init__`: the pipeline's own is used."""
|
|
175
|
+
|
|
176
|
+
_trash_panda_stages: Stages
|
|
177
|
+
|
|
178
|
+
@property
|
|
179
|
+
def stages(self) -> Stages:
|
|
180
|
+
"""The stages of this pipeline's components: `pipe.stages.plans`, `pipe.stages.active`."""
|
|
181
|
+
return self._trash_panda_stages
|
|
182
|
+
|
|
183
|
+
def __call__(self, *args, **kwargs):
|
|
184
|
+
with self._trash_panda_stages:
|
|
185
|
+
return super().__call__(*args, **kwargs)
|
|
186
|
+
|
|
187
|
+
def release(self) -> None:
|
|
188
|
+
"""Give back the component that is loaded. A call of the pipeline does it by itself when it ends; this is for what
|
|
189
|
+
was loaded by calling a component or a method such as `encode_prompt()` outside a call."""
|
|
190
|
+
self._trash_panda_stages.close()
|
|
191
|
+
|
|
192
|
+
def to(self, *args, **kwargs):
|
|
193
|
+
"""Moves the components that are not staged, and leaves the staged ones where trash-panda puts them."""
|
|
194
|
+
kwargs.pop("silence_dtype_warnings", None)
|
|
195
|
+
staged = self._trash_panda_stages.components
|
|
196
|
+
for name, module in self.components.items():
|
|
197
|
+
if name not in staged and isinstance(module, nn.Module):
|
|
198
|
+
module.to(*args, **kwargs)
|
|
199
|
+
warnings.warn(f"trash-panda: to() moved only the components that are not staged; {list(staged)} run where "
|
|
200
|
+
"trash-panda puts them", UserWarning, stacklevel=2)
|
|
201
|
+
return self
|
|
202
|
+
|
|
203
|
+
def _refuse_offloading(self, *args, **kwargs):
|
|
204
|
+
raise RuntimeError("this pipeline offloads its large components already: choose them with offload=, their order "
|
|
205
|
+
"with order= and their plans with plans= in TrashPandaPipeline.from_pretrained()")
|
|
206
|
+
|
|
207
|
+
enable_model_cpu_offload = _refuse_offloading
|
|
208
|
+
enable_sequential_cpu_offload = _refuse_offloading
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _staged_class(pipeline_class: type) -> type:
|
|
212
|
+
"""A subclass of `pipeline_class` with the mixin first. It keeps the name and the module of the original, because
|
|
213
|
+
diffusers writes the class name into the config of the pipeline and looks classes up by name."""
|
|
214
|
+
made = _STAGED_CLASSES.get(pipeline_class)
|
|
215
|
+
if made is None:
|
|
216
|
+
made = type(pipeline_class.__name__, (StagedPipelineMixin, pipeline_class),
|
|
217
|
+
{"__module__": pipeline_class.__module__, "__qualname__": pipeline_class.__qualname__,
|
|
218
|
+
"__doc__": pipeline_class.__doc__})
|
|
219
|
+
_STAGED_CLASSES[pipeline_class] = made
|
|
220
|
+
return made
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class TrashPandaPipeline:
|
|
224
|
+
"""Loads a diffusers pipeline so that its large components run in stages (see the module's description)."""
|
|
225
|
+
|
|
226
|
+
@classmethod
|
|
227
|
+
def from_pretrained(cls, pipeline_class: type, source: Union[str, Path], *, offload: Optional[Sequence[str]] = None,
|
|
228
|
+
order: Optional[Sequence[str]] = None, plans: Optional[Mapping[str, Mapping[str, Any]]] = None,
|
|
229
|
+
preload: Optional[Mapping[str, bool]] = None, variant: Optional[str] = None,
|
|
230
|
+
compute_dtype: Any = "bf16", device: Union[None, str, torch.device] = None,
|
|
231
|
+
hub: Optional[bool] = None, revision: Optional[str] = None, token: Optional[str] = None,
|
|
232
|
+
cache_dir: Union[None, str, Path] = None, local_files_only: bool = False, **kwargs):
|
|
233
|
+
"""The pipeline in `source`, an instance of a subclass of `pipeline_class`.
|
|
234
|
+
|
|
235
|
+
source a folder on disk, or a Hugging Face Hub repo id (`"owner/name"`) that is fetched into the Hub's cache,
|
|
236
|
+
the files that are needed only. A folder that exists is used as a folder
|
|
237
|
+
hub None decides as above; True means a repo id even if a folder of that name exists, False a folder only
|
|
238
|
+
revision, token, cache_dir, local_files_only for the Hub: a branch or commit, a login token for gated models
|
|
239
|
+
(default: the one that is logged in or in HF_TOKEN), the cache folder, and offline use (what is in the
|
|
240
|
+
cache already)
|
|
241
|
+
offload the components to stage (default: the models that the pipeline's `model_cpu_offload_seq` names)
|
|
242
|
+
order the order they run in (default: `model_cpu_offload_seq`)
|
|
243
|
+
plans {component: arguments of stage() for it}, such as `{"transformer": {"resident_blocks": 12}}`
|
|
244
|
+
preload what is prepared for the next component while one runs: `{"ram": False, "vram": True}`, which is the
|
|
245
|
+
default. `ram` reads its RAM tier into memory early (slow on a SATA drive, see the measurements),
|
|
246
|
+
`vram` loads its GPU blocks early into VRAM that is free
|
|
247
|
+
variant "fp16" and so on, for the staged components and for the others
|
|
248
|
+
compute_dtype, device the dtype the staged components are expanded to, and where they run (default: CUDA if
|
|
249
|
+
there is one)
|
|
250
|
+
**kwargs the other arguments of the pipeline's `from_pretrained()` (`torch_dtype`, `scheduler`, ...).
|
|
251
|
+
`low_cpu_mem_usage` is False unless you say otherwise: diffusers needs accelerate for it and prints a
|
|
252
|
+
warning without, and it concerns only what diffusers loads itself (the tokenizers, the scheduler and the
|
|
253
|
+
components that are not staged), not the staged models"""
|
|
254
|
+
preload = dict(preload or {})
|
|
255
|
+
unknown = [key for key in preload if key not in _PRELOAD_KEYS]
|
|
256
|
+
if unknown:
|
|
257
|
+
raise ValueError(f"preload has {unknown}; the keys are {list(_PRELOAD_KEYS)}")
|
|
258
|
+
folder = resolve_source(source, hub=hub, variant=variant, revision=revision, token=token, cache_dir=cache_dir,
|
|
259
|
+
local_files_only=local_files_only)
|
|
260
|
+
components = staged_components(pipeline_class, folder, offload=offload, order=order, plans=plans, variant=variant,
|
|
261
|
+
compute_dtype=compute_dtype, device=device)
|
|
262
|
+
given = [name for name in components if name in kwargs]
|
|
263
|
+
if given:
|
|
264
|
+
raise ValueError(f"{given} are given as arguments and are staged as well: leave them out of one of them")
|
|
265
|
+
if variant is not None:
|
|
266
|
+
kwargs["variant"] = variant
|
|
267
|
+
kwargs.setdefault("low_cpu_mem_usage", False) # diffusers wants accelerate for it, and the staged models do not use it
|
|
268
|
+
pipe = _staged_class(pipeline_class).from_pretrained(
|
|
269
|
+
str(folder), **{name: component.module for name, component in components.items()}, **kwargs)
|
|
270
|
+
pipe._trash_panda_stages = Stages(components, ram_preload=preload.get("ram", False),
|
|
271
|
+
vram_preload=preload.get("vram", True), device=device)
|
|
272
|
+
return pipe
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Making a placeholder say what a loaded model would say about its dtype and device.
|
|
2
|
+
|
|
3
|
+
A pipeline reads `model.dtype` and `model.device` to make its inputs (`latents.to(self.transformer.dtype)`). Those
|
|
4
|
+
properties look at the parameters, and a placeholder's parameters are on the meta device between stages, and while it is
|
|
5
|
+
loaded a model holds its weights in the dtype they were stored in (fp8, say), not the dtype they run in. So the placeholder
|
|
6
|
+
reports the dtype its blocks are expanded to and the device it runs on, whatever its parameters hold."""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import torch
|
|
11
|
+
import torch.nn as nn
|
|
12
|
+
|
|
13
|
+
_ORIGINAL = "_trash_panda_class"
|
|
14
|
+
_DEVICE = "_trash_panda_device"
|
|
15
|
+
_DTYPE = "_trash_panda_dtype"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def shim_module(module: nn.Module, device: torch.device, dtype: torch.dtype) -> None:
|
|
19
|
+
"""Make `module.dtype` give `dtype` and `module.device` give `device`.
|
|
20
|
+
|
|
21
|
+
The module becomes an instance of a subclass of its class that has the same name and the same `__module__`, so it is
|
|
22
|
+
still an instance of what it was, and a pipeline that records its class (diffusers writes it into the config) records
|
|
23
|
+
the original. Calling it again only changes the two values. unshim_module() puts the class back."""
|
|
24
|
+
if _ORIGINAL in module.__dict__:
|
|
25
|
+
module.__dict__[_DEVICE], module.__dict__[_DTYPE] = device, dtype
|
|
26
|
+
return
|
|
27
|
+
cls = module.__class__
|
|
28
|
+
attrs = {
|
|
29
|
+
"__module__": cls.__module__,
|
|
30
|
+
"__qualname__": cls.__qualname__,
|
|
31
|
+
"__doc__": cls.__doc__,
|
|
32
|
+
"dtype": property(lambda self: self.__dict__[_DTYPE]),
|
|
33
|
+
"device": property(lambda self: self.__dict__[_DEVICE]),
|
|
34
|
+
}
|
|
35
|
+
module.__dict__[_ORIGINAL] = cls
|
|
36
|
+
module.__dict__[_DEVICE], module.__dict__[_DTYPE] = device, dtype
|
|
37
|
+
module.__class__ = type(cls.__name__, (cls,), attrs)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def unshim_module(module: nn.Module) -> None:
|
|
41
|
+
"""Undo shim_module(): the module's class is its own again. Does nothing for a module that was not shimmed."""
|
|
42
|
+
cls = module.__dict__.pop(_ORIGINAL, None)
|
|
43
|
+
if cls is not None:
|
|
44
|
+
module.__class__ = cls
|
|
45
|
+
module.__dict__.pop(_DEVICE, None)
|
|
46
|
+
module.__dict__.pop(_DTYPE, None)
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""Running the components of a pipeline one at a time, each loading when it is first called.
|
|
2
|
+
|
|
3
|
+
A pipeline calls its models in its own order (a text encoder, a denoiser, a VAE), and nothing in it says when one is done.
|
|
4
|
+
Here every component is a placeholder: the real model class, built inside `empty_weights()`, so its parameters are on the
|
|
5
|
+
meta device. Its `forward`, `encode` and `decode` are wrapped. The first call of a component loads it (a stage of a
|
|
6
|
+
Coordinator: plan, load, hooks) and gives back the one that was loaded before it, which is the rule that diffusers' own
|
|
7
|
+
model offloading follows: a model is done when the next one starts.
|
|
8
|
+
|
|
9
|
+
stages = Stages({"text_encoder": Component(te, te_path), "transformer": Component(dit, dit_path)})
|
|
10
|
+
with stages:
|
|
11
|
+
embeds = te(tokens) # loads the text encoder
|
|
12
|
+
latents = dit(embeds) # gives the text encoder back, loads the transformer
|
|
13
|
+
# leaving the block gives the transformer back
|
|
14
|
+
|
|
15
|
+
The model objects stay the same ones the pipeline holds: only their weights come and go. Between stages their parameters
|
|
16
|
+
are on the meta device again, and their kept buffers (see buffers_to_keep()) are put back when they load again."""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import functools
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any, Dict, Mapping, Optional, Tuple, Union
|
|
24
|
+
|
|
25
|
+
import torch
|
|
26
|
+
import torch.nn as nn
|
|
27
|
+
|
|
28
|
+
from ..offload import Coordinator, Step
|
|
29
|
+
from .meta import buffers_to_keep, place_buffers, restore_buffers, save_buffers, tie_parameters, tied_parameters
|
|
30
|
+
|
|
31
|
+
METHODS = ("forward", "encode", "decode") # the entry points of a model that a pipeline calls
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class Component:
|
|
36
|
+
"""One model of a pipeline: the placeholder, built inside empty_weights(), and where its weights are.
|
|
37
|
+
|
|
38
|
+
`path` is a weight file or an index json (see find_weights()), `key_map` the one that stream_load() takes. `methods`
|
|
39
|
+
are the methods that start the component's stage when they are called: by default `forward`, `encode` and `decode`,
|
|
40
|
+
those that the module has. `options` are the arguments of stage() for this component: those of plan() such as
|
|
41
|
+
`resident_blocks` or `max_vram`, `skip_prefixes`, `overlap`."""
|
|
42
|
+
|
|
43
|
+
module: nn.Module
|
|
44
|
+
path: Union[str, Path]
|
|
45
|
+
key_map: Any = None
|
|
46
|
+
methods: Optional[Tuple[str, ...]] = None
|
|
47
|
+
options: Dict[str, Any] = field(default_factory=dict)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class _Placed:
|
|
51
|
+
"""What diffusers finds in `_hf_hook` of a component to know where its inputs go (`execution_device`). It has no
|
|
52
|
+
`pre_forward`, so that the hook of diffusers' own `@apply_forward_hook`, which calls it, does nothing here."""
|
|
53
|
+
|
|
54
|
+
def __init__(self, device: torch.device) -> None:
|
|
55
|
+
self.execution_device = device
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Stages:
|
|
59
|
+
"""The components of a pipeline, run one at a time in stages. Use it in a `with` block, or call close() when the
|
|
60
|
+
run is over: the component that is loaded then gives its memory back.
|
|
61
|
+
|
|
62
|
+
`components` maps a name to its Component, in the order the pipeline runs them: while a component runs, the next one
|
|
63
|
+
is prepared (see Coordinator). `ram_preload` and `vram_preload` are the flags of Coordinator.stage(). `device` is
|
|
64
|
+
where the components run (default: CUDA if there is one). A call to a component made outside a `with` block opens the
|
|
65
|
+
stages as well, and they stay open until close().
|
|
66
|
+
|
|
67
|
+
Only one component runs at a time. A component called while another is running (a ControlNet inside a transformer)
|
|
68
|
+
raises a RuntimeError, because loading it would give back the model that is running."""
|
|
69
|
+
|
|
70
|
+
def __init__(self, components: Mapping[str, Component], *, ram_preload: bool = True, vram_preload: bool = True,
|
|
71
|
+
device: Union[None, str, torch.device] = None) -> None:
|
|
72
|
+
if not components:
|
|
73
|
+
raise ValueError("Stages needs at least one component")
|
|
74
|
+
self.components: Dict[str, Component] = dict(components)
|
|
75
|
+
for name, component in self.components.items():
|
|
76
|
+
if isinstance(component.module.__dict__.get("_hf_hook"), _Placed):
|
|
77
|
+
raise ValueError(f"the component {name!r} is staged by another Stages already: detach() that one first")
|
|
78
|
+
self.device = torch.device(device) if device is not None else torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
79
|
+
self.plans: Dict[str, Any] = {} # the plan of each component, from its latest stage
|
|
80
|
+
self._flags = dict(ram_preload=ram_preload, vram_preload=vram_preload)
|
|
81
|
+
self._kept: Dict[str, list] = {} # buffers the checkpoint has nothing for, by component
|
|
82
|
+
self._saved: Dict[str, Dict[str, torch.Tensor]] = {}
|
|
83
|
+
self._ties: Dict[str, list] = {} # names that share one parameter (tied weights), by component
|
|
84
|
+
self._wrapped: Dict[str, Tuple[str, ...]] = {}
|
|
85
|
+
steps = []
|
|
86
|
+
for name, component in self.components.items():
|
|
87
|
+
kept = buffers_to_keep(component.module, component.path, component.key_map)
|
|
88
|
+
self._kept[name] = kept
|
|
89
|
+
self._saved[name] = save_buffers(component.module, kept)
|
|
90
|
+
self._ties[name] = tied_parameters(component.module)
|
|
91
|
+
options = dict(component.options)
|
|
92
|
+
options["skip_prefixes"] = tuple(options.get("skip_prefixes", ())) + tuple(kept)
|
|
93
|
+
if component.key_map is not None:
|
|
94
|
+
options.setdefault("key_map", component.key_map)
|
|
95
|
+
steps.append(Step(name, self._builder(name), component.path, **options))
|
|
96
|
+
self.coordinator = Coordinator(*steps)
|
|
97
|
+
self._opened = False
|
|
98
|
+
self._stage = None # the stage that is open: the context manager of co.stage()
|
|
99
|
+
self._active: Optional[str] = None # the component that is loaded
|
|
100
|
+
self._running: Optional[str] = None # the component whose method is running
|
|
101
|
+
self._depth = 0
|
|
102
|
+
for name, component in self.components.items():
|
|
103
|
+
self._wrap(name, component)
|
|
104
|
+
|
|
105
|
+
# -- the placeholders
|
|
106
|
+
|
|
107
|
+
def _builder(self, name: str):
|
|
108
|
+
"""What a Step calls to get the model: the placeholder itself, with its kept buffers back (release() took them)."""
|
|
109
|
+
component = self.components[name]
|
|
110
|
+
|
|
111
|
+
def build():
|
|
112
|
+
restore_buffers(component.module, self._saved[name])
|
|
113
|
+
tie_parameters(component.module, self._ties[name]) # release() broke the ties: the load needs them
|
|
114
|
+
return component.module
|
|
115
|
+
|
|
116
|
+
return build
|
|
117
|
+
|
|
118
|
+
def _wrap(self, name: str, component: Component) -> None:
|
|
119
|
+
module = component.module
|
|
120
|
+
names = component.methods
|
|
121
|
+
if names is None:
|
|
122
|
+
names = tuple(m for m in METHODS if callable(getattr(module, m, None)))
|
|
123
|
+
for method in names:
|
|
124
|
+
setattr(module, method, self._gated(name, getattr(module, method)))
|
|
125
|
+
module._hf_hook = _Placed(self.device)
|
|
126
|
+
self._wrapped[name] = tuple(names)
|
|
127
|
+
|
|
128
|
+
def _gated(self, name: str, inner):
|
|
129
|
+
@functools.wraps(inner)
|
|
130
|
+
def gated(*args, **kwargs):
|
|
131
|
+
self._begin(name)
|
|
132
|
+
try:
|
|
133
|
+
return inner(*args, **kwargs)
|
|
134
|
+
finally:
|
|
135
|
+
self._end()
|
|
136
|
+
|
|
137
|
+
return gated
|
|
138
|
+
|
|
139
|
+
def detach(self) -> None:
|
|
140
|
+
"""Give the components back as they were: close the stages and take the wrappers and `_hf_hook` off."""
|
|
141
|
+
self.close()
|
|
142
|
+
for name, methods in self._wrapped.items():
|
|
143
|
+
module = self.components[name].module
|
|
144
|
+
for method in methods:
|
|
145
|
+
module.__dict__.pop(method, None)
|
|
146
|
+
if isinstance(module.__dict__.get("_hf_hook"), _Placed):
|
|
147
|
+
del module.__dict__["_hf_hook"]
|
|
148
|
+
self._wrapped = {}
|
|
149
|
+
|
|
150
|
+
# -- the stages
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def active(self) -> Optional[str]:
|
|
154
|
+
"""The name of the component that is loaded, or None."""
|
|
155
|
+
return self._active
|
|
156
|
+
|
|
157
|
+
def _begin(self, name: str) -> None:
|
|
158
|
+
if self._running is not None and self._running != name:
|
|
159
|
+
raise RuntimeError(f"{name!r} was called while {self._running!r} was running. Components that run inside each "
|
|
160
|
+
"other cannot be staged: loading one would give back the model that is running")
|
|
161
|
+
self.activate(name)
|
|
162
|
+
self._running = name
|
|
163
|
+
self._depth += 1
|
|
164
|
+
|
|
165
|
+
def _end(self) -> None:
|
|
166
|
+
self._depth -= 1
|
|
167
|
+
if self._depth == 0:
|
|
168
|
+
self._running = None
|
|
169
|
+
|
|
170
|
+
def _open(self) -> None:
|
|
171
|
+
if not self._opened:
|
|
172
|
+
self.coordinator.__enter__()
|
|
173
|
+
self._opened = True
|
|
174
|
+
|
|
175
|
+
def activate(self, name: str) -> None:
|
|
176
|
+
"""Load component `name` if it is not the one that is loaded, giving back the one that was."""
|
|
177
|
+
if name not in self.components:
|
|
178
|
+
raise KeyError(f"no component named {name!r}; they are {list(self.components)}")
|
|
179
|
+
if self._active == name:
|
|
180
|
+
return
|
|
181
|
+
if self._running is not None:
|
|
182
|
+
raise RuntimeError(f"cannot load {name!r} while {self._running!r} is running")
|
|
183
|
+
self._leave()
|
|
184
|
+
self._open()
|
|
185
|
+
stage = self.coordinator.stage(name, **self._flags)
|
|
186
|
+
model, plan, _handle = stage.__enter__()
|
|
187
|
+
self._stage, self._active = stage, name
|
|
188
|
+
self.plans[name] = plan
|
|
189
|
+
try:
|
|
190
|
+
if model is not self.components[name].module:
|
|
191
|
+
raise RuntimeError(f"the stage of {name!r} gave another model than its placeholder")
|
|
192
|
+
place_buffers(model, self._kept[name], self.device)
|
|
193
|
+
tie_parameters(model, self._ties[name]) # stream_load() fills one name of a tied weight only
|
|
194
|
+
except BaseException:
|
|
195
|
+
self._leave()
|
|
196
|
+
raise
|
|
197
|
+
|
|
198
|
+
def _leave(self, error=(None, None, None)) -> None:
|
|
199
|
+
stage, self._stage, self._active = self._stage, None, None
|
|
200
|
+
if stage is not None:
|
|
201
|
+
stage.__exit__(*error)
|
|
202
|
+
|
|
203
|
+
def close(self, error=(None, None, None)) -> None:
|
|
204
|
+
"""Give back the component that is loaded and close the stages. Safe to call twice; the stages open again at the
|
|
205
|
+
next call of a component."""
|
|
206
|
+
try:
|
|
207
|
+
self._leave(error)
|
|
208
|
+
finally:
|
|
209
|
+
if self._opened:
|
|
210
|
+
self._opened = False
|
|
211
|
+
self.coordinator.__exit__(*error)
|
|
212
|
+
|
|
213
|
+
def __enter__(self) -> "Stages":
|
|
214
|
+
self._open()
|
|
215
|
+
return self
|
|
216
|
+
|
|
217
|
+
def __exit__(self, exc_type, exc, tb) -> bool:
|
|
218
|
+
self.close((exc_type, exc, tb))
|
|
219
|
+
return False
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Finding the weight files of a model in a Hugging Face style folder (a diffusers component or a transformers model).
|
|
2
|
+
|
|
3
|
+
A folder holds the weights under one of a few names, and a `variant` ("fp16", "ema") puts its name before the file type:
|
|
4
|
+
|
|
5
|
+
diffusion_pytorch_model.safetensors model.safetensors
|
|
6
|
+
diffusion_pytorch_model.fp16.safetensors model.fp16.safetensors
|
|
7
|
+
diffusion_pytorch_model.safetensors.index.json model.safetensors.index.json (sharded)
|
|
8
|
+
diffusion_pytorch_model.safetensors.index.fp16.json (sharded, a variant)
|
|
9
|
+
|
|
10
|
+
Checkpoint() given the folder would take every `.safetensors` file in it, the variants together, so the file or the
|
|
11
|
+
index to read is chosen here and handed to Checkpoint() by name."""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import re
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Dict, List, Optional, Sequence, Tuple, Union
|
|
19
|
+
|
|
20
|
+
STEMS = ("diffusion_pytorch_model", "model") # the file names of a diffusers component and of a transformers model
|
|
21
|
+
_OTHER_FORMATS = (".bin", ".pt", ".pth", ".ckpt", ".gguf")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _single(stem: str, variant: Optional[str]) -> str:
|
|
25
|
+
return f"{stem}.{variant}.safetensors" if variant else f"{stem}.safetensors"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _index(stem: str, variant: Optional[str]) -> str:
|
|
29
|
+
return f"{stem}.safetensors.index.{variant}.json" if variant else f"{stem}.safetensors.index.json"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _variants(names: Sequence[str], stems: Sequence[str]) -> List[str]:
|
|
33
|
+
"""The variants that the files of the folder are for: the part of a name between the stem and the file type."""
|
|
34
|
+
found = set()
|
|
35
|
+
for stem in stems:
|
|
36
|
+
s = re.escape(stem)
|
|
37
|
+
patterns = (
|
|
38
|
+
rf"{s}\.([^.]+?)-\d{{5}}-of-\d{{5}}\.safetensors", # a shard of a variant: before the next one, which it fits too
|
|
39
|
+
rf"{s}\.([^.]+)\.safetensors", # a single file of a variant
|
|
40
|
+
rf"{s}\.safetensors\.index\.([^.]+)\.json", # the index of a sharded variant
|
|
41
|
+
)
|
|
42
|
+
for name in names:
|
|
43
|
+
for pattern in patterns:
|
|
44
|
+
match = re.fullmatch(pattern, name)
|
|
45
|
+
if match:
|
|
46
|
+
found.add(match.group(1))
|
|
47
|
+
break
|
|
48
|
+
return sorted(found)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def find_weights(folder: Union[str, Path], variant: Optional[str] = None, stems: Sequence[str] = STEMS) -> Path:
|
|
52
|
+
"""The weight file of a model folder, or the index json of its shards: what to hand to Checkpoint() or stream_load().
|
|
53
|
+
|
|
54
|
+
`variant` is "fp16", "ema" and so on, or None for the plain weights. For each name in `stems` (a diffusers component
|
|
55
|
+
is `diffusion_pytorch_model`, a transformers model is `model`) a single file is looked for first and then the index
|
|
56
|
+
of a sharded model; both hold the same weights. A path that is a file already is returned as it is.
|
|
57
|
+
|
|
58
|
+
Raises FileNotFoundError when nothing matches, and says why: which variants the folder has, that only the plain weights
|
|
59
|
+
are there, or that the weights are in a format that is not read (only safetensors are)."""
|
|
60
|
+
path = Path(folder)
|
|
61
|
+
if path.is_file():
|
|
62
|
+
return path
|
|
63
|
+
if not path.is_dir():
|
|
64
|
+
raise FileNotFoundError(f"no weights: {path} is not a file or a folder")
|
|
65
|
+
variant = variant or None
|
|
66
|
+
names = sorted(p.name for p in path.iterdir() if p.is_file())
|
|
67
|
+
for stem in stems:
|
|
68
|
+
for name in (_single(stem, variant), _index(stem, variant)):
|
|
69
|
+
if name in names:
|
|
70
|
+
return path / name
|
|
71
|
+
|
|
72
|
+
available = _variants(names, stems)
|
|
73
|
+
plain = [n for stem in stems for n in (_single(stem, None), _index(stem, None)) if n in names]
|
|
74
|
+
if variant and available:
|
|
75
|
+
raise FileNotFoundError(f"no '{variant}' weights in {path}: the variants there are {available}")
|
|
76
|
+
if variant and plain:
|
|
77
|
+
raise FileNotFoundError(f"no '{variant}' weights in {path}: only the plain weights ({plain[0]}) are there, "
|
|
78
|
+
"so leave the variant out")
|
|
79
|
+
if available:
|
|
80
|
+
raise FileNotFoundError(f"no plain weights in {path}, only the variants {available}: pass variant=")
|
|
81
|
+
other = [n for n in names if n.endswith(_OTHER_FORMATS)]
|
|
82
|
+
if other:
|
|
83
|
+
raise FileNotFoundError(f"no safetensors weights in {path}: only safetensors are read, and the folder has {other[:3]}")
|
|
84
|
+
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
|
|
@@ -52,7 +52,8 @@ class Defaults:
|
|
|
52
52
|
find_blocks_min_blocks: int = 2 # ... and have at least this many blocks
|
|
53
53
|
|
|
54
54
|
# diagnostics
|
|
55
|
-
|
|
55
|
+
faulthandler: bool = True # turn faulthandler on when a model loads: a crash in native code then prints where (nothing is printed otherwise)
|
|
56
|
+
profile: bool = False # print where the prefetching spent its time
|
|
56
57
|
trace: bool = False # record the run in a trace file (docs/design/trace-format.md), in TRASH_PANDA_TRACE_DIR
|
|
57
58
|
|
|
58
59
|
|
|
@@ -12,6 +12,7 @@ Each tensor is read lazily from the checkpoint and placed according to its tier:
|
|
|
12
12
|
|
|
13
13
|
from __future__ import annotations
|
|
14
14
|
|
|
15
|
+
import faulthandler
|
|
15
16
|
import threading
|
|
16
17
|
import time
|
|
17
18
|
from collections import defaultdict
|
|
@@ -137,6 +138,20 @@ def _to_meta(model: nn.Module, name: str) -> None:
|
|
|
137
138
|
owner._parameters[leaf] = nn.Parameter(torch.empty_like(p, device="meta"), requires_grad=False)
|
|
138
139
|
|
|
139
140
|
|
|
141
|
+
def _enable_faulthandler() -> None:
|
|
142
|
+
"""Turn faulthandler on, so that a crash in native code (an access violation, a segmentation fault) prints the Python
|
|
143
|
+
traceback of every thread: where the process was when it died. Nothing is printed unless it crashes. It stays as it is
|
|
144
|
+
when it is on already (the user's own setting, `-X faulthandler`, PYTHONFAULTHANDLER=1), when TRASH_PANDA_FAULTHANDLER
|
|
145
|
+
turns it off, and when stderr has no file descriptor to write to (a notebook). A process that the system ends, as when
|
|
146
|
+
memory runs out, leaves no trace here: nothing runs in it then."""
|
|
147
|
+
if not config.current().faulthandler or faulthandler.is_enabled():
|
|
148
|
+
return
|
|
149
|
+
try:
|
|
150
|
+
faulthandler.enable(all_threads=True)
|
|
151
|
+
except (AttributeError, OSError, ValueError, RuntimeError):
|
|
152
|
+
pass
|
|
153
|
+
|
|
154
|
+
|
|
140
155
|
def stream_load(
|
|
141
156
|
model: nn.Module,
|
|
142
157
|
path,
|
|
@@ -174,7 +189,8 @@ def stream_load(
|
|
|
174
189
|
Returns a LoadReport (print it) and remembers the settings on the model for install_offload().
|
|
175
190
|
"""
|
|
176
191
|
began_all = time.perf_counter()
|
|
177
|
-
|
|
192
|
+
_enable_faulthandler()
|
|
193
|
+
tr = _trace.loading_model() # the trace of the model that this thread is loading, if one is recorded
|
|
178
194
|
device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
|
179
195
|
if plan is not None:
|
|
180
196
|
cdt, sdt = plan.compute_dtype, plan.storage_dtype
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|