model-runtime 0.5.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,438 @@
1
+ """DDIM trajectories with explicit latent, scheduler, conditioning, and RNG closure."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import platform
6
+ from collections.abc import Mapping
7
+ from typing import Any
8
+
9
+ import diffusers
10
+ import torch
11
+ from diffusers import DDIMScheduler, UNet2DModel
12
+
13
+ from ..contracts import ExecutionPoint, SlotSpec, SurfaceManifest, TransitionSpec
14
+ from ..core import Adapter, Session
15
+ from ..numerics import check_numeric_environment, live_numeric_environment
16
+ from ..values import clone, digest, identity
17
+
18
+
19
+ def _stable_configuration(value: Any, *, key: str = "") -> Any:
20
+ if isinstance(value, Mapping):
21
+ return {name: _stable_configuration(item, key=name) for name, item in value.items()}
22
+ if isinstance(value, (tuple, list)):
23
+ items = [_stable_configuration(item) for item in value]
24
+ return sorted(items) if key == "_use_default_values" else items
25
+ return value
26
+
27
+
28
+ def _tensor_guards(module: Any, *, prefix: str = "") -> tuple[tuple[Any, ...], ...]:
29
+ return tuple(
30
+ (
31
+ f"{prefix}{name}",
32
+ id(value),
33
+ value._version,
34
+ value.data_ptr(),
35
+ value.untyped_storage().data_ptr(),
36
+ )
37
+ for name, value in (*module.named_parameters(), *module.named_buffers())
38
+ )
39
+
40
+
41
+ class DiffusionAdapter(Adapter):
42
+ def __init__(
43
+ self,
44
+ unet: Any,
45
+ scheduler: DDIMScheduler,
46
+ *,
47
+ decoder: Any = None,
48
+ scaling_factor: float = 1.0,
49
+ granularity: str = "step",
50
+ ):
51
+ if not isinstance(scheduler, DDIMScheduler):
52
+ raise ValueError(
53
+ "v1 supports DDIMScheduler only; stateful solvers need another adapter"
54
+ )
55
+ if granularity not in {"step", "operation"}:
56
+ raise ValueError("granularity must be 'step' or 'operation'")
57
+ self.model = unet.eval()
58
+ self.granularity = granularity
59
+ self.scheduler_config = dict(scheduler.config)
60
+ self.decoder = decoder
61
+ self.scaling_factor = scaling_factor
62
+ self.device = next(unet.parameters()).device
63
+ self.dtype = next(unet.parameters()).dtype
64
+ config = {
65
+ "unet": dict(unet.config),
66
+ "scheduler": self.scheduler_config,
67
+ "scaling_factor": scaling_factor,
68
+ }
69
+ if decoder is not None:
70
+ config["decoder"] = identity(decoder, dict(decoder.config))
71
+ configuration_manifest = {
72
+ "unet": dict(unet.config),
73
+ "scheduler": self.scheduler_config,
74
+ "scaling_factor": scaling_factor,
75
+ "decoder": None if decoder is None else dict(decoder.config),
76
+ }
77
+ self._configuration_fingerprint = digest(_stable_configuration(configuration_manifest))
78
+ self.model_identity = identity(unet, _stable_configuration(config))
79
+ self._frozen_versions = _tensor_guards(unet, prefix="unet.") + (
80
+ () if decoder is None else _tensor_guards(decoder, prefix="decoder.")
81
+ )
82
+ self.execution = {
83
+ "family": "diffusion-ddim",
84
+ "adapter": "native-boundary-v2",
85
+ "granularity": granularity,
86
+ "dtype": str(self.dtype),
87
+ "device": {"type": self.device.type, "index": self.device.index},
88
+ "batch": {"size": 1, "guidance": False},
89
+ "environment_versions": {
90
+ "torch": torch.__version__,
91
+ "diffusers": diffusers.__version__,
92
+ "python": platform.python_version(),
93
+ },
94
+ "model_program": "scale_model_input->unet_denoiser->ddim_scheduler_commit",
95
+ "kernel": {"denoiser": type(unet).__name__, "scheduler": "DDIMScheduler"},
96
+ "numeric_scope": {
97
+ "inference_mode": True,
98
+ "autocast": False,
99
+ "scheduler_history": "eta-zero-stateless",
100
+ **live_numeric_environment(),
101
+ "tensor_layout": "state-slot-bound-stride",
102
+ },
103
+ "eta": 0.0,
104
+ "parity": "same-program-exact",
105
+ }
106
+
107
+ @classmethod
108
+ def tiny(cls, seed: int = 7, *, granularity: str = "step") -> DiffusionAdapter:
109
+ with torch.random.fork_rng():
110
+ torch.manual_seed(seed)
111
+ unet = UNet2DModel(
112
+ sample_size=8,
113
+ in_channels=3,
114
+ out_channels=3,
115
+ layers_per_block=1,
116
+ block_out_channels=(8, 16),
117
+ down_block_types=("DownBlock2D", "DownBlock2D"),
118
+ up_block_types=("UpBlock2D", "UpBlock2D"),
119
+ norm_num_groups=4,
120
+ )
121
+ return cls(
122
+ unet,
123
+ DDIMScheduler(num_train_timesteps=32, clip_sample=False),
124
+ granularity=granularity,
125
+ )
126
+
127
+ @classmethod
128
+ def from_pipeline(cls, pipeline: Any, *, granularity: str = "step") -> DiffusionAdapter:
129
+ from diffusers import StableDiffusionPipeline
130
+
131
+ if not isinstance(pipeline, StableDiffusionPipeline):
132
+ raise ValueError(
133
+ "v1 supports StableDiffusionPipeline; SDXL/FLUX need separate adapters"
134
+ )
135
+ if not isinstance(pipeline.scheduler, DDIMScheduler):
136
+ raise ValueError("install DDIMScheduler.from_config(pipeline.scheduler.config) first")
137
+ return cls(
138
+ pipeline.unet,
139
+ pipeline.scheduler,
140
+ decoder=pipeline.vae,
141
+ scaling_factor=pipeline.vae.config.scaling_factor,
142
+ granularity=granularity,
143
+ )
144
+
145
+ def _verify_frozen_model(self) -> None:
146
+ current = _tensor_guards(self.model, prefix="unet.") + (
147
+ () if self.decoder is None else _tensor_guards(self.decoder, prefix="decoder.")
148
+ )
149
+ if current != self._frozen_versions:
150
+ raise ValueError(
151
+ "model parameters or buffers changed after adapter identity was frozen; "
152
+ "rewrap the model in a new adapter"
153
+ )
154
+
155
+ def validate_execution(self) -> None:
156
+ self._verify_frozen_model()
157
+ configuration_manifest = {
158
+ "unet": dict(self.model.config),
159
+ "scheduler": self.scheduler_config,
160
+ "scaling_factor": self.scaling_factor,
161
+ "decoder": None if self.decoder is None else dict(self.decoder.config),
162
+ }
163
+ if digest(_stable_configuration(configuration_manifest)) != self._configuration_fingerprint:
164
+ raise ValueError(
165
+ "model configuration changed after adapter identity was frozen; rewrap"
166
+ )
167
+ check_numeric_environment(self.execution["numeric_scope"])
168
+
169
+ def session(
170
+ self,
171
+ *,
172
+ steps: int = 4,
173
+ seed: int = 11,
174
+ latents: torch.Tensor | None = None,
175
+ conditioning: torch.Tensor | None = None,
176
+ ) -> Session:
177
+ self.validate_execution()
178
+ if isinstance(steps, bool) or not isinstance(steps, int) or steps < 1:
179
+ raise ValueError("steps must be positive")
180
+ scheduler = DDIMScheduler.from_config(self.scheduler_config)
181
+ scheduler.set_timesteps(steps, device=self.device)
182
+ generator = torch.Generator(device="cpu").manual_seed(seed)
183
+ if latents is None:
184
+ size = self.model.config.sample_size
185
+ size = (size, size) if isinstance(size, int) else size
186
+ latents = torch.randn((1, self.model.config.in_channels, *size), generator=generator)
187
+ state = {
188
+ "latent": latents.to(self.device, self.dtype),
189
+ "conditioning": (
190
+ None if conditioning is None else conditioning.to(self.device, self.dtype)
191
+ ),
192
+ "timesteps": scheduler.timesteps,
193
+ "step": 0,
194
+ "phase": "denoiser",
195
+ "noise_prediction": None,
196
+ "rng": generator.get_state(),
197
+ "inference_steps": steps,
198
+ }
199
+ return Session(self, state)
200
+
201
+ def boundary(self, state: Mapping[str, Any]) -> str:
202
+ if self.granularity == "operation":
203
+ return f"diffusion-step:{state['step']}/{state['phase']}"
204
+ return f"diffusion-step:{state['step']}"
205
+
206
+ def point(self, state: Mapping[str, Any]) -> ExecutionPoint:
207
+ return ExecutionPoint(
208
+ family="diffusion-ddim",
209
+ logical_step=state["step"],
210
+ phase=state["phase"],
211
+ operator="unet" if state["phase"] == "denoiser" else "ddim_scheduler",
212
+ edge="before",
213
+ next_operation=(
214
+ "native_unet_denoiser" if state["phase"] == "denoiser" else "ddim_scheduler_commit"
215
+ ),
216
+ local_clock=state["step"],
217
+ )
218
+
219
+ def transition(self, state: Mapping[str, Any]) -> TransitionSpec:
220
+ reads = ("latent", "step", "timesteps", "inference_steps")
221
+ if state["phase"] == "denoiser":
222
+ reads += ("conditioning",)
223
+ else:
224
+ reads += ("noise_prediction",)
225
+ writes = (
226
+ ("noise_prediction", "phase")
227
+ if self.granularity == "operation" and state["phase"] == "denoiser"
228
+ else ("latent", "noise_prediction", "phase", "step")
229
+ )
230
+ return TransitionSpec(
231
+ self.point(state).next_operation,
232
+ reads,
233
+ writes,
234
+ consumer="native-diffusion-suffix",
235
+ footprint="declared",
236
+ )
237
+
238
+ def surface(self, state: Mapping[str, Any]) -> SurfaceManifest:
239
+ def tensor_schema(value: torch.Tensor | None, *, optional: bool = False) -> dict[str, Any]:
240
+ if value is None:
241
+ return {"kind": "tensor", "optional": optional}
242
+ return {
243
+ "kind": "tensor",
244
+ "shape": list(value.shape),
245
+ "stride": list(value.stride()),
246
+ "dtype": str(value.dtype),
247
+ "device": str(value.device),
248
+ "optional": optional,
249
+ }
250
+
251
+ return SurfaceManifest(
252
+ slots=(
253
+ SlotSpec(
254
+ "latent",
255
+ role="carrier",
256
+ writable=state["phase"] == "denoiser",
257
+ producer="ddim_scheduler",
258
+ consumer="unet",
259
+ schema=tensor_schema(state["latent"]),
260
+ ),
261
+ SlotSpec(
262
+ "conditioning",
263
+ role="conditioning",
264
+ writable=state["phase"] == "denoiser" and state["conditioning"] is not None,
265
+ producer="caller",
266
+ consumer="unet",
267
+ schema=tensor_schema(state["conditioning"], optional=True),
268
+ ),
269
+ SlotSpec(
270
+ "noise_prediction",
271
+ role="derived",
272
+ producer="unet",
273
+ consumer="ddim_scheduler",
274
+ persistence="authoritative",
275
+ schema=tensor_schema(state["noise_prediction"], optional=True),
276
+ ),
277
+ SlotSpec(
278
+ "timesteps",
279
+ role="schedule",
280
+ producer="scheduler_setup",
281
+ consumer="unet_and_scheduler",
282
+ schema=tensor_schema(state["timesteps"]),
283
+ ),
284
+ SlotSpec(
285
+ "rng",
286
+ role="rng",
287
+ producer="session",
288
+ consumer="initial_latent",
289
+ schema=tensor_schema(state["rng"]),
290
+ ),
291
+ SlotSpec(
292
+ "step",
293
+ role="clock",
294
+ producer="ddim_scheduler",
295
+ consumer="runtime",
296
+ schema={"kind": "integer", "minimum": 0, "maximum": len(state["timesteps"])},
297
+ ),
298
+ SlotSpec(
299
+ "phase",
300
+ role="clock",
301
+ producer="runtime",
302
+ consumer="runtime",
303
+ schema={"kind": "enum", "values": ["denoiser", "scheduler"]},
304
+ ),
305
+ SlotSpec(
306
+ "inference_steps",
307
+ role="schedule",
308
+ producer="session",
309
+ consumer="scheduler_setup",
310
+ schema={"kind": "integer", "minimum": 1},
311
+ ),
312
+ ),
313
+ state_schema="saturn-pub-diffusion-ddim-state-v2",
314
+ consumer="native-ddim-suffix",
315
+ horizon="native-diffusion-suffix",
316
+ )
317
+
318
+ def addresses(self, state: Mapping[str, Any]) -> tuple[str, ...]:
319
+ return ("latent",) + (("conditioning",) if state["conditioning"] is not None else ())
320
+
321
+ def validate(self, state: Mapping[str, Any]) -> None:
322
+ self._verify_frozen_model()
323
+ expected_keys = {
324
+ "latent",
325
+ "conditioning",
326
+ "timesteps",
327
+ "step",
328
+ "phase",
329
+ "noise_prediction",
330
+ "rng",
331
+ "inference_steps",
332
+ }
333
+ if set(state) != expected_keys:
334
+ raise ValueError("diffusion state schema keys differ from the execution contract")
335
+ latent = state["latent"]
336
+ if (
337
+ latent.ndim != 4
338
+ or latent.shape[0] != 1
339
+ or latent.shape[1] != self.model.config.in_channels
340
+ or latent.device != self.device
341
+ ):
342
+ raise ValueError("invalid diffusion latent geometry")
343
+ if latent.dtype != self.dtype or not torch.isfinite(latent).all():
344
+ raise ValueError("invalid diffusion latent dtype or values")
345
+ scheduler = DDIMScheduler.from_config(self.scheduler_config)
346
+ scheduler.set_timesteps(state["inference_steps"])
347
+ if not torch.equal(state["timesteps"].cpu(), scheduler.timesteps):
348
+ raise ValueError("scheduler timesteps differ from the execution contract")
349
+ if type(state["step"]) is not int or not 0 <= state["step"] <= len(state["timesteps"]):
350
+ raise ValueError("invalid scheduler cursor")
351
+ if type(state["inference_steps"]) is not int or state["inference_steps"] < 1:
352
+ raise ValueError("invalid inference step count")
353
+ if state["phase"] not in {"denoiser", "scheduler"}:
354
+ raise ValueError("invalid diffusion operation phase")
355
+ if self.granularity == "step" and state["phase"] != "denoiser":
356
+ raise ValueError("step granularity cannot restore an operation boundary")
357
+ conditional = hasattr(self.model.config, "cross_attention_dim")
358
+ if conditional != (state["conditioning"] is not None):
359
+ raise ValueError("conditioning must match the UNet family")
360
+ if conditional and (
361
+ state["conditioning"].ndim != 3
362
+ or state["conditioning"].shape[0] != 1
363
+ or state["conditioning"].shape[-1] != self.model.config.cross_attention_dim
364
+ or state["conditioning"].dtype != self.dtype
365
+ or state["conditioning"].device != self.device
366
+ or not torch.isfinite(state["conditioning"]).all()
367
+ ):
368
+ raise ValueError("invalid conditioning")
369
+ prediction = state["noise_prediction"]
370
+ if prediction is not None and (
371
+ prediction.shape != latent.shape
372
+ or prediction.dtype != self.dtype
373
+ or prediction.device != self.device
374
+ or not torch.isfinite(prediction).all()
375
+ ):
376
+ raise ValueError("invalid denoiser prediction")
377
+ if (state["phase"] == "scheduler") != (prediction is not None):
378
+ raise ValueError("denoiser prediction exists only at the scheduler boundary")
379
+ if state["step"] == len(state["timesteps"]) and state["phase"] != "denoiser":
380
+ raise ValueError("completed trajectory cannot retain an uncommitted scheduler value")
381
+ if (
382
+ not isinstance(state["rng"], torch.Tensor)
383
+ or state["rng"].device.type != "cpu"
384
+ or state["rng"].dtype != torch.uint8
385
+ ):
386
+ raise ValueError("invalid RNG state")
387
+ torch.Generator().set_state(state["rng"])
388
+
389
+ def write(
390
+ self, state: Mapping[str, Any], writes: Mapping[str, Any], invalidates: tuple[str, ...]
391
+ ) -> Mapping[str, Any]:
392
+ if invalidates:
393
+ raise ValueError("each DDIM step recomputes its native dependencies")
394
+ if state["phase"] != "denoiser":
395
+ raise ValueError("scheduler boundaries are read-only; restore or commit first")
396
+ if "noise_prediction" in writes:
397
+ raise ValueError("denoiser predictions are derived native state")
398
+ return super().write(state, writes, ())
399
+
400
+ @torch.inference_mode()
401
+ def advance(self, state: Mapping[str, Any]) -> Mapping[str, Any]:
402
+ self.validate(state)
403
+ if state["step"] == len(state["timesteps"]):
404
+ raise ValueError("trajectory already complete")
405
+ out = clone(state)
406
+ scheduler = DDIMScheduler.from_config(self.scheduler_config)
407
+ scheduler.set_timesteps(state["inference_steps"], device=self.device)
408
+ latent = out["latent"].to(self.device)
409
+ timestep = scheduler.timesteps[out["step"]]
410
+ if out["phase"] == "denoiser":
411
+ kwargs = {}
412
+ if out["conditioning"] is not None:
413
+ kwargs["encoder_hidden_states"] = out["conditioning"].to(self.device, self.dtype)
414
+ noise = self.model(
415
+ scheduler.scale_model_input(latent, timestep), timestep, **kwargs
416
+ ).sample
417
+ else:
418
+ noise = out["noise_prediction"]
419
+ if self.granularity == "operation" and out["phase"] == "denoiser":
420
+ out["noise_prediction"] = noise
421
+ out["phase"] = "scheduler"
422
+ else:
423
+ out["latent"] = scheduler.step(noise, timestep, latent, eta=0.0).prev_sample
424
+ out["noise_prediction"] = None
425
+ out["phase"] = "denoiser"
426
+ out["step"] += 1
427
+ return out
428
+
429
+ @torch.inference_mode()
430
+ def decode(self, session: Session) -> torch.Tensor:
431
+ if session.adapter is not self or session._state["step"] != len(
432
+ session._state["timesteps"]
433
+ ):
434
+ raise ValueError("decode requires this adapter's completed trajectory")
435
+ latent = session.read("latent").to(self.device)
436
+ if self.decoder is not None:
437
+ latent = self.decoder.decode(latent / self.scaling_factor).sample
438
+ return (latent / 2 + 0.5).clamp(0, 1)