laplacekit-diffusers 1.0.0__py3-none-any.whl

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.
@@ -0,0 +1,46 @@
1
+ r"""Laplace on denoisers from Hugging Face `diffusers`.
2
+
3
+ Give `laplace` a denoiser, its DDPM-family scheduler and the clean training samples:
4
+
5
+ ```python
6
+ post = lk.diffusers.laplace(unet, scheduler, loader, n_data=60_000)
7
+ eps = lk.predict_outputs(post, {"sample": x_t, "timestep": torch.tensor(t)})
8
+ eps.mean, eps.variance # the predicted noise and its variance per pixel
9
+ ```
10
+
11
+ A denoiser takes a noisy sample $x_t$ and a timestep $t$. It predicts the noise, the
12
+ velocity or the clean sample, whichever its scheduler's `prediction_type` names. For
13
+ each batch, `laplace` draws $t$ and the noise from the batch's generator, builds $x_t$
14
+ with the scheduler's `add_noise`, and fits a Gaussian likelihood with unit noise to the
15
+ target.
16
+ The model's outputs must have the target's shape, so a model that also predicts a
17
+ variance is refused. Flow-matching schedulers are not supported yet.
18
+
19
+ Code reaches this package as `lk.diffusers`, which imports it on first use.
20
+ """
21
+
22
+ from importlib import metadata
23
+
24
+ import laplacekit as lk
25
+ from laplacekit_diffusers.ddpm import laplace
26
+ from laplacekit_diffusers.denoiser import denoiser
27
+
28
+ __all__ = ["denoiser", "health", "laplace"]
29
+
30
+
31
+ def health() -> tuple[lk.HealthCheck, ...]:
32
+ """Check for `lk.health()` that `diffusers` is installed.
33
+
34
+ Returns:
35
+ One check, `ok` with the version when `diffusers` is installed and `error`
36
+ otherwise.
37
+ """
38
+
39
+ try:
40
+ return (lk.HealthCheck("diffusers", "ok", metadata.version("diffusers")),)
41
+ except metadata.PackageNotFoundError:
42
+ return (lk.HealthCheck("diffusers", "error", "not installed (required)"),)
43
+
44
+
45
+ plugin = lk.Plugin(supports=">=1.0,<2", health=health)
46
+ """The record behind the `laplacekit.plugins` entry point."""
@@ -0,0 +1,274 @@
1
+ """Laplace on a denoiser trained with a DDPM-family scheduler, and the checks of that scheduler."""
2
+
3
+ from abc import abstractmethod
4
+ from collections.abc import Callable, Iterable, Mapping
5
+ from typing import Any, Literal, Protocol, get_args, runtime_checkable
6
+
7
+ import torch
8
+ from torch import Tensor, nn
9
+ from typing_extensions import TypeIs
10
+
11
+ import laplacekit as lk
12
+ from laplacekit.core import Params, Selection, Subset
13
+ from laplacekit_diffusers.denoiser import denoiser
14
+
15
+ __all__ = ["laplace"]
16
+
17
+
18
+ _Prediction = Literal["epsilon", "v_prediction", "sample"]
19
+
20
+
21
+ _PREDICTIONS: tuple[_Prediction, ...] = get_args(_Prediction)
22
+
23
+
24
+ @runtime_checkable
25
+ class _HasConfig(Protocol):
26
+ @property
27
+ @abstractmethod
28
+ def config(self) -> Any: ...
29
+
30
+
31
+ @runtime_checkable
32
+ class _HasAddNoise(Protocol):
33
+ @abstractmethod
34
+ def add_noise(self, original_samples: Any, noise: Any, timesteps: Any, /) -> Any: ...
35
+
36
+
37
+ @runtime_checkable
38
+ class _HasGetVelocity(Protocol):
39
+ @abstractmethod
40
+ def get_velocity(self, sample: Any, noise: Any, timesteps: Any, /) -> Any: ...
41
+
42
+
43
+ @runtime_checkable
44
+ class _NoiseScheduler(_HasConfig, _HasAddNoise, Protocol):
45
+ """A DDPM-family scheduler, which has a config and `add_noise`."""
46
+
47
+
48
+ _MEMBERS: tuple[tuple[str, type], ...] = (
49
+ ("config", _HasConfig),
50
+ ("add_noise", _HasAddNoise),
51
+ )
52
+
53
+
54
+ _Velocity = Callable[[Tensor, Tensor, Tensor], Tensor]
55
+
56
+
57
+ def laplace(
58
+ unet: nn.Module,
59
+ scheduler: object,
60
+ data: Iterable[Tensor | Mapping[str, Tensor]],
61
+ *,
62
+ n_data: int | None = None,
63
+ subset: Subset | Params | Selection = lk.subsets.last_layer,
64
+ hessian_approx: lk.core.HessianApprox[Any] | None = None,
65
+ prior: lk.core.Prior = lk.priors.Isotropic(), # noqa: B008 # immutable
66
+ hyper_tuner: lk.core.HyperTuner | None = lk.MarginalLikelihood(), # noqa: B008 # immutable
67
+ generator: torch.Generator | None = None,
68
+ ) -> lk.LaplacePosterior[Any, Any]:
69
+ r"""Fit a Laplace approximation to a denoiser trained with a DDPM-family scheduler.
70
+
71
+ DDPM-family schedulers include `DDPMScheduler` and `DDIMScheduler`. For each batch,
72
+ the timestep $t$ is uniform over the training timesteps,
73
+ $\epsilon \sim \mathcal{N}(0, I)$, and $x_t$ is `scheduler.add_noise(x0, eps, t)`.
74
+ All of these are drawn from the batch's generator. The target depends on
75
+ `scheduler.config.prediction_type`. It is $\epsilon$ for `"epsilon"`,
76
+ `scheduler.get_velocity(x0, eps, t)` for `"v_prediction"`, and $x_0$ for `"sample"`.
77
+
78
+ The fit is `lk.laplace` with `denoiser(unet)`, that preparation of the batches, and
79
+ `Gaussian(sigma=1.0, event_dims=len(S))`, a Gaussian with fixed unit noise.
80
+
81
+ The scheduler, its `prediction_type` and its noise are checked before any data is
82
+ read. The noise must be variance-preserving,
83
+ $x_t = \sqrt{\bar\alpha_t}\, x_0 + \sqrt{1 - \bar\alpha_t}\, \epsilon$, which is
84
+ checked at three timesteps. One batch then goes through `unet` to check that the
85
+ output has the target's shape, so `data` is iterated once more than by `lk.laplace`.
86
+
87
+ Args:
88
+ unet: The denoiser, a `UNet2DModel` or any `diffusers` model with the same call.
89
+ scheduler: The noise scheduler. It needs `config` and `add_noise`, and also
90
+ `get_velocity` for `"v_prediction"`.
91
+ data: Batches of clean samples $x_0$, `[N, *S]`, or mappings that hold the clean
92
+ `"sample"` and conditioning entries (`class_labels`,
93
+ `encoder_hidden_states`, ...), which reach the model unchanged. A mapping
94
+ may not hold a `"timestep"`, since `laplace` draws it.
95
+ n_data: The number of examples, which is the size of the training set when `data`
96
+ is a subset of it.
97
+ subset: As in `lk.laplace`.
98
+ hessian_approx: As in `lk.laplace`.
99
+ prior: As in `lk.laplace`.
100
+ hyper_tuner: As in `lk.laplace`. The noise is fixed, so it tunes the prior
101
+ precision only.
102
+ generator: As in `lk.laplace`. It seeds the timesteps and the noise too.
103
+
104
+ Returns:
105
+ The posterior, as from `lk.laplace`.
106
+
107
+ Raises:
108
+ StructureError: Before any data, when the scheduler lacks `config` or
109
+ `add_noise` (as a flow-matching scheduler does), its `prediction_type` is
110
+ not `"epsilon"`, `"v_prediction"` or `"sample"`, it has `"v_prediction"`
111
+ without `get_velocity`, `num_train_timesteps` is not an int, or its noise is
112
+ not variance-preserving (as in `EulerDiscreteScheduler`). On the first
113
+ batch, when the output is not a tensor of the target's shape (as with a
114
+ model that predicts a variance). On any batch, when the batch is neither a
115
+ tensor nor a mapping with a tensor `"sample"`, it holds a `"timestep"`, or
116
+ `unet` does not return a `BaseOutput` with a `sample`. Otherwise as in
117
+ `lk.laplace`.
118
+ CapabilityError: As in `lk.laplace`.
119
+ ValueError: The data has no batches, or as in `lk.laplace`.
120
+ TypeError: `data` is a one-shot iterator, or as in `lk.laplace`.
121
+ """
122
+
123
+ sched, prediction, steps, velocity = _check_scheduler(scheduler)
124
+ fn = denoiser(unet)
125
+
126
+ src = lk.data.from_loader(
127
+ data, prepare=_prepare(sched, prediction, steps, velocity), n_data=n_data
128
+ )
129
+ # Only the shapes of this batch matter, so a fixed generator draws it.
130
+ first = next(iter(src(torch.Generator())), None)
131
+
132
+ if first is None:
133
+ raise ValueError("lk.diffusers.laplace: the data yielded no batches")
134
+
135
+ with torch.no_grad():
136
+ out = fn({}, first.inputs)
137
+
138
+ target = first.targets
139
+
140
+ if not isinstance(out, Tensor) or not isinstance(target, Tensor):
141
+ raise lk.StructureError("lk.diffusers.laplace needs tensor outputs and targets")
142
+
143
+ if out.shape != target.shape:
144
+ raise lk.StructureError(
145
+ f"lk.diffusers.laplace: the model's output {tuple(out.shape)} does not match the "
146
+ f"target {tuple(target.shape)}; models with learned variance "
147
+ f"(`out_channels == 2 * in_channels`) are not supported"
148
+ )
149
+
150
+ return lk.laplace(
151
+ fn,
152
+ src,
153
+ lk.Gaussian(sigma=1.0, event_dims=target.ndim - 1),
154
+ subset=subset,
155
+ hessian_approx=hessian_approx,
156
+ prior=prior,
157
+ hyper_tuner=hyper_tuner,
158
+ generator=generator,
159
+ )
160
+
161
+
162
+ def _check_scheduler(
163
+ scheduler: object,
164
+ ) -> tuple[_NoiseScheduler, _Prediction, int, _Velocity | None]:
165
+ if not isinstance(scheduler, _NoiseScheduler):
166
+ missing = [name for name, member in _MEMBERS if not isinstance(scheduler, member)]
167
+ # A scheduler without add_noise is most likely flow matching (`scale_noise`).
168
+ flow = "" if isinstance(scheduler, _HasAddNoise) else "; flow matching is not supported yet"
169
+
170
+ raise lk.StructureError(
171
+ f"lk.diffusers.laplace needs a DDPM-family scheduler with config and add_noise "
172
+ f"(DDPMScheduler, DDIMScheduler, ...); {type(scheduler).__name__} has no "
173
+ f"{', '.join(missing)}{flow}"
174
+ )
175
+
176
+ config = scheduler.config
177
+ prediction = config.get("prediction_type") if isinstance(config, Mapping) else None
178
+ steps = config.get("num_train_timesteps") if isinstance(config, Mapping) else None
179
+
180
+ if not _is_prediction(prediction):
181
+ allowed = ", ".join(repr(p) for p in _PREDICTIONS)
182
+
183
+ raise lk.StructureError(
184
+ f"lk.diffusers.laplace needs scheduler.config.prediction_type in {allowed}, got "
185
+ f"{prediction!r}"
186
+ )
187
+
188
+ velocity: _Velocity | None = None
189
+
190
+ if prediction == "v_prediction":
191
+ if not isinstance(scheduler, _HasGetVelocity):
192
+ raise lk.StructureError(
193
+ f"lk.diffusers.laplace: prediction_type 'v_prediction' needs "
194
+ f"scheduler.get_velocity; {type(scheduler).__name__} has none"
195
+ )
196
+
197
+ velocity = scheduler.get_velocity
198
+
199
+ if not isinstance(steps, int):
200
+ raise lk.StructureError(
201
+ f"lk.diffusers.laplace needs an int scheduler.config.num_train_timesteps, got {steps!r}"
202
+ )
203
+
204
+ # DDPM-family noise is variance-preserving: x_t = sqrt(abar_t) x0 + sqrt(1 - abar_t) eps.
205
+ # A scheduler with the same methods but another forward process (Euler's x0 + sigma eps)
206
+ # would give a fit against the wrong inputs.
207
+ t = torch.tensor([0, steps // 2, steps - 1])
208
+ one, zero = torch.ones(3, dtype=torch.float64), torch.zeros(3, dtype=torch.float64)
209
+ total = scheduler.add_noise(one, zero, t) ** 2 + scheduler.add_noise(zero, one, t) ** 2
210
+
211
+ if not torch.allclose(total, torch.ones_like(total), rtol=0, atol=1e-6):
212
+ raise lk.StructureError(
213
+ f"lk.diffusers.laplace needs a variance-preserving (DDPM-family) scheduler, where "
214
+ f"add_noise gives sqrt(abar_t) x0 + sqrt(1 - abar_t) eps; "
215
+ f"{type(scheduler).__name__} is not"
216
+ )
217
+
218
+ return scheduler, prediction, steps, velocity
219
+
220
+
221
+ def _prepare(
222
+ scheduler: _NoiseScheduler, prediction: _Prediction, steps: int, velocity: _Velocity | None
223
+ ) -> Callable[[Any, torch.Generator], lk.Batch]:
224
+ def prepare(raw: Any, generator: torch.Generator, /) -> lk.Batch:
225
+ x0, cond = _split(raw)
226
+
227
+ g = generator
228
+ t = torch.randint(0, steps, (len(x0),), generator=g, device=g.device).to(x0.device)
229
+ eps = torch.randn(x0.shape, generator=g, dtype=x0.dtype, device=g.device).to(x0.device)
230
+ x_t = scheduler.add_noise(x0, eps, t)
231
+
232
+ match prediction:
233
+ case "epsilon":
234
+ target = eps
235
+ case "v_prediction":
236
+ # `_check_scheduler` gives a velocity for every "v_prediction" scheduler.
237
+ assert velocity is not None
238
+ target = velocity(x0, eps, t)
239
+ case "sample":
240
+ target = x0
241
+
242
+ return lk.Batch({"sample": x_t, "timestep": t, **cond}, target)
243
+
244
+ return prepare
245
+
246
+
247
+ def _split(raw: Any) -> tuple[Tensor, dict[str, Any]]:
248
+ if isinstance(raw, Tensor):
249
+ return raw, {}
250
+
251
+ if isinstance(raw, Mapping):
252
+ if "sample" not in raw or not isinstance(raw["sample"], Tensor):
253
+ raise lk.StructureError(
254
+ f"lk.diffusers.laplace needs a tensor under 'sample' in each batch, got the "
255
+ f"keys {sorted(raw)}"
256
+ )
257
+
258
+ # The timestep is drawn from the batch's generator; a given one would replace it.
259
+ if "timestep" in raw:
260
+ raise lk.StructureError(
261
+ "lk.diffusers.laplace draws each batch's 'timestep' itself; remove the "
262
+ "'timestep' entry from the batch"
263
+ )
264
+
265
+ return raw["sample"], {k: v for k, v in raw.items() if k != "sample"}
266
+
267
+ raise lk.StructureError(
268
+ f"lk.diffusers.laplace needs batches of clean samples (a tensor) or mappings with a "
269
+ f"'sample', got {type(raw).__name__}"
270
+ )
271
+
272
+
273
+ def _is_prediction(x: object, /) -> TypeIs[_Prediction]:
274
+ return x in _PREDICTIONS
@@ -0,0 +1,68 @@
1
+ """Wrap a `diffusers` denoiser as a `ModelFn`."""
2
+
3
+ from collections.abc import Mapping
4
+
5
+ from diffusers.utils import BaseOutput
6
+ from torch import nn
7
+ from torch.func import functional_call
8
+
9
+ import laplacekit as lk
10
+ from laplacekit.core import (
11
+ Inputs,
12
+ Outputs,
13
+ Params,
14
+ )
15
+
16
+ __all__ = ["denoiser"]
17
+
18
+
19
+ _POSITIONAL = ("sample", "timestep")
20
+
21
+
22
+ def denoiser(unet: nn.Module, /) -> lk.core.ModelFn:
23
+ """Wrap a `diffusers` denoiser as a `ModelFn` that returns the output's `.sample`.
24
+
25
+ Args:
26
+ unet: The denoiser.
27
+
28
+ Returns:
29
+ A `ModelFn` whose `forward(params, inputs)` calls
30
+ `unet(inputs["sample"], inputs["timestep"], **rest)`, where `rest` holds the other
31
+ entries of `inputs` (`class_labels`, `encoder_hidden_states`, ...). The sample
32
+ and the timestep go in by position, because a DiT calls its first argument
33
+ `hidden_states`. Parameters missing from `params` stay fixed and are passed
34
+ detached. A call raises `StructureError` when the inputs are not a mapping, lack
35
+ `sample` or `timestep`, or the output is not a `BaseOutput` with a `sample`.
36
+ """
37
+
38
+ def forward(params: Params, inputs: Inputs) -> Outputs:
39
+ if not isinstance(inputs, Mapping):
40
+ raise lk.StructureError(
41
+ f"lk.diffusers.model needs inputs {{'sample', 'timestep', ...}}, got "
42
+ f"{type(inputs).__name__}"
43
+ )
44
+
45
+ missing = [k for k in _POSITIONAL if k not in inputs]
46
+
47
+ if missing:
48
+ raise lk.StructureError(f"lk.diffusers.model needs {', '.join(missing)} in the inputs")
49
+
50
+ # As in `ModelFn.from_module`: a tensor passed under one name reaches its other names
51
+ # through functional_call's tying, so none of its names goes into `fixed`.
52
+ passed = {id(p) for k, p in unet.named_parameters(remove_duplicate=False) if k in params}
53
+ fixed = {k: v.detach() for k, v in unet.named_parameters() if id(v) not in passed}
54
+ rest = {k: v for k, v in inputs.items() if k not in _POSITIONAL}
55
+
56
+ out = functional_call(
57
+ unet, {**fixed, **params}, (inputs["sample"], inputs["timestep"]), rest
58
+ )
59
+
60
+ if not isinstance(out, BaseOutput) or "sample" not in out:
61
+ raise lk.StructureError(
62
+ f"lk.diffusers.model needs a model that returns a diffusers BaseOutput with a "
63
+ f"`sample`, got {type(out).__name__}"
64
+ )
65
+
66
+ return out["sample"]
67
+
68
+ return lk.core.ModelFn(forward, unet)
File without changes
@@ -0,0 +1,10 @@
1
+ Metadata-Version: 2.4
2
+ Name: laplacekit-diffusers
3
+ Version: 1.0.0
4
+ Summary: Hugging Face diffusers presets for laplacekit: last-layer Laplace on denoisers with DDPM-family schedulers
5
+ Author: Agustinus Kristiadi
6
+ Author-email: Agustinus Kristiadi <agustinus@kristia.de>
7
+ License-Expression: MIT
8
+ Requires-Dist: laplacekit>=1.0,<2
9
+ Requires-Dist: diffusers>=0.43.0
10
+ Requires-Python: >=3.11
@@ -0,0 +1,8 @@
1
+ laplacekit_diffusers/__init__.py,sha256=yO9tH1oAzHOTdvfo0uHT3jm8NGHDo5ErDIXCSfRxGY4,1729
2
+ laplacekit_diffusers/ddpm.py,sha256=Fqy2MFEB3PZNR8ZPn67hKs9hwhKVMPvpYrEoVxb6CRU,10938
3
+ laplacekit_diffusers/denoiser.py,sha256=MktBotZ4yXmLiejMIaDNkS3tATfK957Yevj-GGe6zPo,2502
4
+ laplacekit_diffusers/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ laplacekit_diffusers-1.0.0.dist-info/WHEEL,sha256=-gI5GRFdiNNn2CFz-ptlExISMINC-k8bFxeojAlHbrM,81
6
+ laplacekit_diffusers-1.0.0.dist-info/entry_points.txt,sha256=ROV5D9PmSizXvKwUZhNFfGxTAmeY0tuThbeKjukNX0c,73
7
+ laplacekit_diffusers-1.0.0.dist-info/METADATA,sha256=3A8b87W2v_e6shGA7dtZAVyPgwxenh-RJE87uaya_f0,380
8
+ laplacekit_diffusers-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.10
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [laplacekit.plugins]
2
+ laplacekit_diffusers = laplacekit_diffusers:plugin
3
+