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,661 @@
1
+ """Native FLUX.1 block execution, deterministic flow Euler, and VAE decode.
2
+
3
+ Text-only, batch-one inference over the native ``FluxTransformer2DModel`` stepped one
4
+ projection / joint (double) block / single block / readout at a time, followed by the
5
+ native ``FlowMatchEulerDiscreteScheduler`` update and the native ``AutoencoderKL`` decode.
6
+
7
+ FLUX.1 carries two text conditioners: a T5-XXL sequence (``encoder_hidden_states``) and a
8
+ CLIP pooled vector (``pooled_projections``). ``schnell`` has no guidance embedding;
9
+ guidance-distilled variants (``dev``) gate a guidance embedding on
10
+ ``transformer.config.guidance_embeds``. Weights may execute resident on the device or, via
11
+ adapter-owned block-streamed residency, from host memory one native module at a time — see
12
+ :mod:`saturn.adapters._residency`.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import platform
18
+ from collections.abc import Mapping
19
+ from typing import Any
20
+
21
+ import diffusers
22
+ import torch
23
+ from diffusers import FlowMatchEulerDiscreteScheduler, FluxTransformer2DModel
24
+
25
+ from ..contracts import ExecutionPoint, SlotSpec, SurfaceManifest, TransitionSpec
26
+ from ..core import Adapter, Session
27
+ from ..numerics import check_numeric_environment, live_numeric_environment
28
+ from ..values import clone, digest, identity
29
+ from ._residency import BlockResidency
30
+
31
+
32
+ def _stable_configuration(value: Any, *, key: str = "") -> Any:
33
+ if isinstance(value, Mapping):
34
+ return {name: _stable_configuration(item, key=name) for name, item in value.items()}
35
+ if isinstance(value, (tuple, list)):
36
+ items = [_stable_configuration(item) for item in value]
37
+ return sorted(items) if key == "_use_default_values" else items
38
+ return value
39
+
40
+
41
+ def _tensor_guards(module: Any, *, prefix: str = "") -> tuple[tuple[Any, ...], ...]:
42
+ return tuple(
43
+ (
44
+ f"{prefix}{name}",
45
+ id(value),
46
+ value._version,
47
+ value.data_ptr(),
48
+ value.untyped_storage().data_ptr(),
49
+ )
50
+ for name, value in (*module.named_parameters(), *module.named_buffers())
51
+ )
52
+
53
+
54
+ class Flux1Adapter(Adapter):
55
+ def __init__(
56
+ self,
57
+ transformer,
58
+ scheduler,
59
+ *,
60
+ pipeline=None,
61
+ granularity="block",
62
+ residency="resident",
63
+ device=None,
64
+ pin_host=False,
65
+ ):
66
+ if not isinstance(transformer, FluxTransformer2DModel):
67
+ raise ValueError("expected a native FluxTransformer2DModel")
68
+ if not isinstance(scheduler, FlowMatchEulerDiscreteScheduler):
69
+ raise ValueError("expected flow Euler scheduler")
70
+ if scheduler.config.stochastic_sampling:
71
+ raise ValueError("stochastic flow is outside this deterministic closure")
72
+ if granularity not in {"block", "operation"}:
73
+ raise ValueError("granularity must be 'block' or 'operation'")
74
+ self.model = transformer.eval()
75
+ self.granularity = granularity
76
+ self.pipeline = pipeline
77
+ self.dtype = next(transformer.parameters()).dtype
78
+ if residency == "streamed":
79
+ target = (
80
+ device if device is not None else ("cuda" if torch.cuda.is_available() else "cpu")
81
+ )
82
+ self._residency = BlockResidency(target, mode="streamed", pin_host=pin_host)
83
+ else:
84
+ target = device if device is not None else next(transformer.parameters()).device
85
+ self._residency = BlockResidency(target, mode="resident")
86
+ self._residency.place(transformer)
87
+ self.device = self._residency.device
88
+ self.guidance_embeds = bool(transformer.config.guidance_embeds)
89
+ self.rope_axes = len(transformer.config.axes_dims_rope)
90
+ self.scheduler_config = dict(scheduler.config)
91
+ self.joint_layers = len(transformer.transformer_blocks)
92
+ self.single_layers = len(transformer.single_transformer_blocks)
93
+ if not self.joint_layers or not self.single_layers:
94
+ raise ValueError("both joint and single blocks are required")
95
+ configuration = {"model": dict(transformer.config), "scheduler": self.scheduler_config}
96
+ if pipeline is not None:
97
+ configuration["vae"] = identity(pipeline.vae, dict(pipeline.vae.config))
98
+ configuration_manifest = {
99
+ "model": dict(transformer.config),
100
+ "scheduler": self.scheduler_config,
101
+ "vae": None if pipeline is None else dict(pipeline.vae.config),
102
+ }
103
+ self._configuration_fingerprint = digest(_stable_configuration(configuration_manifest))
104
+ self.model_identity = identity(transformer, _stable_configuration(configuration))
105
+ self._frozen_versions = _tensor_guards(transformer, prefix="transformer.") + (
106
+ () if pipeline is None else _tensor_guards(pipeline.vae, prefix="vae.")
107
+ )
108
+ self.execution = {
109
+ "family": "flux1",
110
+ "adapter": "native-boundary-v2",
111
+ "granularity": granularity,
112
+ "dtype": str(self.dtype),
113
+ "device": {"type": self.device.type, "index": self.device.index},
114
+ "batch": {"size": 1, "reference_images": False},
115
+ "environment_versions": {
116
+ "torch": torch.__version__,
117
+ "diffusers": diffusers.__version__,
118
+ "python": platform.python_version(),
119
+ },
120
+ "model_program": (
121
+ "project->joint_block[*]->single_block[*]->norm/proj_readout->flow_commit"
122
+ ),
123
+ "kernel": {
124
+ "transformer": "FluxTransformer2DModel",
125
+ "scheduler": "FlowMatchEulerDiscreteScheduler",
126
+ },
127
+ "numeric_scope": {
128
+ "inference_mode": True,
129
+ "autocast": False,
130
+ "stochastic_sampling": False,
131
+ **live_numeric_environment(),
132
+ "tensor_layout": "state-slot-bound-stride",
133
+ },
134
+ "guidance_embeds": self.guidance_embeds,
135
+ "reference_images": False,
136
+ "residency": self._residency.to_dict(),
137
+ "parity": "same-program-exact",
138
+ }
139
+
140
+ @classmethod
141
+ def from_pipeline(
142
+ cls,
143
+ pipeline,
144
+ *,
145
+ granularity="block",
146
+ residency="resident",
147
+ device=None,
148
+ pin_host=False,
149
+ ):
150
+ from diffusers import FluxPipeline
151
+
152
+ if not isinstance(pipeline, FluxPipeline):
153
+ raise ValueError("only the native FluxPipeline (FLUX.1) is supported")
154
+ if any(hasattr(module, "_hf_hook") for module in pipeline.transformer.modules()):
155
+ raise ValueError(
156
+ "remove accelerate offload hooks before wrapping; block-streamed residency "
157
+ "is adapter-owned (pass residency='streamed')"
158
+ )
159
+ return cls(
160
+ pipeline.transformer,
161
+ pipeline.scheduler,
162
+ pipeline=pipeline,
163
+ granularity=granularity,
164
+ residency=residency,
165
+ device=device,
166
+ pin_host=pin_host,
167
+ )
168
+
169
+ @classmethod
170
+ def tiny(
171
+ cls,
172
+ seed=7,
173
+ *,
174
+ granularity="block",
175
+ guidance=False,
176
+ residency="resident",
177
+ device=None,
178
+ pin_host=False,
179
+ ):
180
+ with torch.random.fork_rng():
181
+ torch.manual_seed(seed)
182
+ model = FluxTransformer2DModel(
183
+ in_channels=8,
184
+ num_layers=2,
185
+ num_single_layers=2,
186
+ attention_head_dim=16,
187
+ num_attention_heads=2,
188
+ joint_attention_dim=24,
189
+ pooled_projection_dim=16,
190
+ guidance_embeds=guidance,
191
+ axes_dims_rope=(4, 6, 6),
192
+ )
193
+ return cls(
194
+ model,
195
+ FlowMatchEulerDiscreteScheduler(),
196
+ granularity=granularity,
197
+ residency=residency,
198
+ device=device,
199
+ pin_host=pin_host,
200
+ )
201
+
202
+ def _verify_frozen_model(self):
203
+ current = _tensor_guards(self.model, prefix="transformer.") + (
204
+ () if self.pipeline is None else _tensor_guards(self.pipeline.vae, prefix="vae.")
205
+ )
206
+ if current != self._frozen_versions:
207
+ raise ValueError(
208
+ "model parameters or buffers changed after adapter identity was frozen; "
209
+ "rewrap the model in a new adapter"
210
+ )
211
+
212
+ def validate_execution(self):
213
+ self._verify_frozen_model()
214
+ configuration_manifest = {
215
+ "model": dict(self.model.config),
216
+ "scheduler": self.scheduler_config,
217
+ "vae": None if self.pipeline is None else dict(self.pipeline.vae.config),
218
+ }
219
+ if digest(_stable_configuration(configuration_manifest)) != self._configuration_fingerprint:
220
+ raise ValueError(
221
+ "model configuration changed after adapter identity was frozen; rewrap"
222
+ )
223
+ check_numeric_environment(self.execution["numeric_scope"])
224
+
225
+ def session(
226
+ self, *, latent, conditioning, pooled, img_ids, txt_ids, timesteps, sigmas, guidance=None
227
+ ):
228
+ self.validate_execution()
229
+ if self.guidance_embeds and guidance is None:
230
+ raise ValueError("guidance-distilled FLUX.1 requires a guidance scale")
231
+ if not self.guidance_embeds and guidance is not None:
232
+ raise ValueError("this FLUX.1 transformer has no guidance embedding")
233
+ return Session(
234
+ self,
235
+ {
236
+ "latent": latent.to(self.device, self.dtype),
237
+ "conditioning": conditioning.to(self.device, self.dtype),
238
+ "pooled": pooled.to(self.device, self.dtype),
239
+ "img_ids": img_ids.to(self.device),
240
+ "txt_ids": txt_ids.to(self.device),
241
+ "timesteps": timesteps.to(self.device),
242
+ "sigmas": sigmas.to(self.device),
243
+ "guidance": None if guidance is None else float(guidance),
244
+ "step": 0,
245
+ "phase": "project",
246
+ "cursor": 0,
247
+ "context": None,
248
+ "text": None,
249
+ "image": None,
250
+ "noise_prediction": None,
251
+ },
252
+ )
253
+
254
+ def boundary(self, state):
255
+ prefix = f"diffusion-step:{state['step']}"
256
+ phase, cursor = state["phase"], state["cursor"]
257
+ if self.granularity == "operation":
258
+ if phase == "joint":
259
+ return f"{prefix}/joint:{cursor}"
260
+ if phase == "single":
261
+ return f"{prefix}/single:{cursor}"
262
+ return f"{prefix}/{phase}"
263
+ if phase == "joint" and cursor:
264
+ return f"{prefix}/after:joint.{cursor - 1}"
265
+ if phase == "single":
266
+ return f"{prefix}/after:single.{cursor - 1}"
267
+ return f"{prefix}/{phase}"
268
+
269
+ def point(self, state):
270
+ phase, cursor = state["phase"], state["cursor"]
271
+ operator = phase
272
+ index = cursor if phase in {"joint", "single"} else None
273
+ next_operation = {
274
+ "project": "native_input_projection",
275
+ "readout": "norm_and_projection",
276
+ "scheduler": "flow_scheduler_commit",
277
+ }.get(phase, f"{phase}_block.{cursor}")
278
+ return ExecutionPoint(
279
+ family="flux1",
280
+ logical_step=state["step"],
281
+ phase=phase,
282
+ operator=operator,
283
+ index=index,
284
+ edge="before",
285
+ next_operation=next_operation,
286
+ local_clock=cursor,
287
+ )
288
+
289
+ def transition(self, state):
290
+ phase, cursor = state["phase"], state["cursor"]
291
+ if phase == "project":
292
+ reads = (
293
+ "timesteps",
294
+ "step",
295
+ "img_ids",
296
+ "txt_ids",
297
+ "latent",
298
+ "conditioning",
299
+ "pooled",
300
+ "guidance",
301
+ )
302
+ writes = ("context", "image", "text", "phase")
303
+ elif phase in {"joint", "single"} and (phase == "joint" or cursor < self.single_layers):
304
+ reads = ("context", "image", "text", "phase", "cursor")
305
+ writes = ("image", "text", "phase", "cursor")
306
+ elif self.granularity == "operation" and phase == "readout":
307
+ reads, writes = ("image", "context"), ("noise_prediction", "phase")
308
+ else:
309
+ reads = (
310
+ "noise_prediction",
311
+ "image",
312
+ "context",
313
+ "latent",
314
+ "timesteps",
315
+ "sigmas",
316
+ "step",
317
+ )
318
+ writes = (
319
+ "latent",
320
+ "step",
321
+ "phase",
322
+ "cursor",
323
+ "text",
324
+ "image",
325
+ "context",
326
+ "noise_prediction",
327
+ )
328
+ return TransitionSpec(
329
+ self.point(state).next_operation,
330
+ reads,
331
+ writes,
332
+ consumer="native-flux-suffix",
333
+ footprint="declared",
334
+ )
335
+
336
+ def surface(self, state):
337
+ def tensor_schema(value, *, optional=False):
338
+ if value is None:
339
+ return {"kind": "tensor", "optional": optional}
340
+ return {
341
+ "kind": "tensor",
342
+ "shape": list(value.shape),
343
+ "stride": list(value.stride()),
344
+ "dtype": str(value.dtype),
345
+ "device": str(value.device),
346
+ "optional": optional,
347
+ }
348
+
349
+ slots = []
350
+ definitions = (
351
+ ("latent", "carrier", state["phase"] == "project", "flow_scheduler", "transformer"),
352
+ ("conditioning", "conditioning", state["phase"] == "project", "caller", "transformer"),
353
+ ("pooled", "conditioning", state["phase"] == "project", "caller", "transformer"),
354
+ ("img_ids", "address", False, "caller", "rope"),
355
+ ("txt_ids", "address", False, "caller", "rope"),
356
+ ("timesteps", "schedule", False, "caller", "transformer_and_scheduler"),
357
+ ("sigmas", "schedule", False, "caller", "scheduler"),
358
+ (
359
+ "text",
360
+ "carrier",
361
+ state["phase"] in {"joint", "single"},
362
+ "native_block",
363
+ "native_suffix",
364
+ ),
365
+ (
366
+ "image",
367
+ "carrier",
368
+ state["phase"] in {"joint", "single"},
369
+ "native_block",
370
+ "native_suffix",
371
+ ),
372
+ ("noise_prediction", "derived", False, "norm_and_projection", "flow_scheduler"),
373
+ )
374
+ for name, role, writable, producer, consumer in definitions:
375
+ if name in {"conditioning", "pooled"} and state["phase"] != "project":
376
+ writable = True
377
+ slots.append(
378
+ SlotSpec(
379
+ name,
380
+ role=role,
381
+ writable=writable,
382
+ producer=producer,
383
+ consumer=consumer,
384
+ invalidates=(),
385
+ schema=tensor_schema(state[name], optional=state[name] is None),
386
+ )
387
+ )
388
+ slots.extend(
389
+ (
390
+ SlotSpec(
391
+ "guidance",
392
+ role="schedule",
393
+ producer="caller",
394
+ consumer="transformer",
395
+ schema=(
396
+ {"kind": "scalar", "type": "none"}
397
+ if state["guidance"] is None
398
+ else {"kind": "scalar", "type": "float"}
399
+ ),
400
+ ),
401
+ SlotSpec(
402
+ "context",
403
+ role="closure",
404
+ producer="project",
405
+ consumer="native_suffix",
406
+ schema={"kind": "tensor_mapping", "optional": state["context"] is None},
407
+ ),
408
+ SlotSpec(
409
+ "step",
410
+ role="clock",
411
+ producer="flow_scheduler",
412
+ consumer="runtime",
413
+ schema={"kind": "integer", "minimum": 0, "maximum": len(state["timesteps"])},
414
+ ),
415
+ SlotSpec(
416
+ "phase",
417
+ role="clock",
418
+ producer="runtime",
419
+ consumer="runtime",
420
+ schema={
421
+ "kind": "enum",
422
+ "values": ["project", "joint", "single", "readout", "scheduler"],
423
+ },
424
+ ),
425
+ SlotSpec(
426
+ "cursor",
427
+ role="clock",
428
+ producer="native_block",
429
+ consumer="runtime",
430
+ schema={"kind": "integer", "minimum": 0},
431
+ ),
432
+ )
433
+ )
434
+ return SurfaceManifest(
435
+ slots=tuple(slots),
436
+ state_schema="saturn-pub-flux1-state-v1",
437
+ consumer="native-flux1-suffix",
438
+ horizon="native-diffusion-suffix",
439
+ )
440
+
441
+ def addresses(self, state):
442
+ slots = ("latent", "conditioning", "pooled")
443
+ return slots + (("text", "image") if state["text"] is not None else ())
444
+
445
+ def validate(self, state: Mapping[str, Any]):
446
+ self._verify_frozen_model()
447
+ expected_keys = {
448
+ "latent",
449
+ "conditioning",
450
+ "pooled",
451
+ "img_ids",
452
+ "txt_ids",
453
+ "timesteps",
454
+ "sigmas",
455
+ "guidance",
456
+ "step",
457
+ "phase",
458
+ "cursor",
459
+ "context",
460
+ "text",
461
+ "image",
462
+ "noise_prediction",
463
+ }
464
+ if set(state) != expected_keys:
465
+ raise ValueError("FLUX.1 state schema keys differ from the execution contract")
466
+ latent, conditioning, pooled = state["latent"], state["conditioning"], state["pooled"]
467
+ for tensor, dimension in (
468
+ (latent, self.model.config.in_channels),
469
+ (conditioning, self.model.config.joint_attention_dim),
470
+ ):
471
+ if tensor.ndim != 3 or tensor.shape[0] != 1 or tensor.shape[-1] != dimension:
472
+ raise ValueError("invalid FLUX.1 input geometry")
473
+ if tensor.dtype != self.dtype or tensor.device != self.device:
474
+ raise ValueError("FLUX.1 input dtype/device mismatch")
475
+ if (
476
+ pooled.ndim != 2
477
+ or pooled.shape[0] != 1
478
+ or pooled.shape[-1] != self.model.config.pooled_projection_dim
479
+ or pooled.dtype != self.dtype
480
+ or pooled.device != self.device
481
+ ):
482
+ raise ValueError("invalid FLUX.1 pooled projection")
483
+ for name, length in (("img_ids", latent.shape[1]), ("txt_ids", conditioning.shape[1])):
484
+ if tuple(state[name].shape) != (1, length, self.rope_axes):
485
+ raise ValueError("invalid FLUX.1 position IDs")
486
+ if state[name].device != self.device or not torch.isfinite(state[name]).all():
487
+ raise ValueError("invalid FLUX.1 position ID dtype/device/value")
488
+ steps = len(state["timesteps"])
489
+ if not steps or state["sigmas"].shape != (steps + 1,):
490
+ raise ValueError("invalid flow schedule geometry")
491
+ for name in ("timesteps", "sigmas"):
492
+ if state[name].device != self.device or state[name].dtype != torch.float32:
493
+ raise ValueError("flow schedule dtype/device mismatch")
494
+ guidance = state["guidance"]
495
+ if self.guidance_embeds:
496
+ if type(guidance) is not float:
497
+ raise ValueError("guidance-distilled FLUX.1 requires a float guidance scale")
498
+ elif guidance is not None:
499
+ raise ValueError("this FLUX.1 transformer has no guidance embedding")
500
+ if type(state["step"]) is not int or not 0 <= state["step"] <= steps:
501
+ raise ValueError("invalid flow step cursor")
502
+ phase, cursor = state["phase"], state["cursor"]
503
+ allowed_phases = {"project", "joint", "single"}
504
+ if self.granularity == "operation":
505
+ allowed_phases |= {"readout", "scheduler"}
506
+ if phase not in allowed_phases or type(cursor) is not int:
507
+ raise ValueError("invalid block cursor")
508
+ if phase == "project":
509
+ if cursor != 0 or any(state[name] is not None for name in ("text", "image", "context")):
510
+ raise ValueError("invalid projection closure")
511
+ else:
512
+ limit = self.joint_layers if phase == "joint" else self.single_layers
513
+ zero_single = phase == "single" and not cursor and self.granularity != "operation"
514
+ if (
515
+ not 0 <= cursor <= limit
516
+ or zero_single
517
+ or (phase in {"readout", "scheduler"} and not cursor)
518
+ ):
519
+ raise ValueError("invalid block cursor")
520
+ if state["step"] == steps or not isinstance(state["context"], dict):
521
+ raise ValueError("missing live transformer closure")
522
+ if set(state["context"]) != {"temb", "rope"}:
523
+ raise ValueError("incomplete transformer closure")
524
+ width = self.model.config.num_attention_heads * self.model.config.attention_head_dim
525
+ for name, length in (("text", conditioning.shape[1]), ("image", latent.shape[1])):
526
+ value = state[name]
527
+ if value is None or tuple(value.shape) != (1, length, width):
528
+ raise ValueError("invalid route geometry")
529
+ if value.dtype != self.dtype or value.device != self.device:
530
+ raise ValueError("route dtype/device mismatch")
531
+ prediction = state["noise_prediction"]
532
+ if prediction is not None and (
533
+ prediction.shape != latent.shape
534
+ or prediction.dtype != self.dtype
535
+ or prediction.device != self.device
536
+ or not torch.isfinite(prediction).all()
537
+ ):
538
+ raise ValueError("invalid FLUX.1 readout prediction")
539
+ if (phase == "scheduler") != (prediction is not None):
540
+ raise ValueError("FLUX.1 prediction exists only at the scheduler boundary")
541
+
542
+ def finite(value):
543
+ if isinstance(value, torch.Tensor) and not torch.isfinite(value).all():
544
+ raise ValueError("non-finite FLUX.1 state")
545
+ if isinstance(value, Mapping):
546
+ for item in value.values():
547
+ finite(item)
548
+ elif isinstance(value, (tuple, list)):
549
+ for item in value:
550
+ finite(item)
551
+
552
+ finite(state)
553
+
554
+ def write(self, state, writes, invalidates):
555
+ if invalidates:
556
+ raise ValueError("FLUX.1 closure must remain complete")
557
+ if state["phase"] in {"readout", "scheduler"}:
558
+ raise ValueError("readout and scheduler boundaries are read-only")
559
+ allowed = (
560
+ {"latent", "conditioning", "pooled"}
561
+ if state["phase"] == "project"
562
+ else {"text", "image"}
563
+ )
564
+ if not set(writes) <= allowed:
565
+ raise ValueError("write would invalidate the captured transformer closure")
566
+ if state["step"] == len(state["timesteps"]):
567
+ raise ValueError("completed trajectories are read-only")
568
+ return super().write(state, writes, ())
569
+
570
+ @torch.inference_mode()
571
+ def advance(self, state):
572
+ self.validate(state)
573
+ if state["step"] == len(state["timesteps"]):
574
+ raise ValueError("trajectory already complete")
575
+ out, model, run = clone(state), self.model, self._residency.run
576
+ phase, cursor = out["phase"], out["cursor"]
577
+ if phase == "project":
578
+ # Match the native forward exactly: the pipeline passes timestep/1000 in the
579
+ # model dtype and the forward multiplies by 1000 again before embedding.
580
+ timestep = out["timesteps"][out["step"]].expand(1).to(self.dtype) / 1000
581
+ timestep = timestep.to(self.dtype) * 1000
582
+ if self.guidance_embeds:
583
+ guidance = torch.full([1], out["guidance"], device=self.device, dtype=torch.float32)
584
+ guidance = guidance.to(self.dtype) * 1000
585
+ temb = run(model.time_text_embed, timestep, guidance, out["pooled"])
586
+ else:
587
+ temb = run(model.time_text_embed, timestep, out["pooled"])
588
+ ids = torch.cat((out["txt_ids"][0], out["img_ids"][0]), dim=0)
589
+ out["context"] = {"temb": temb, "rope": run(model.pos_embed, ids)}
590
+ out["image"] = run(model.x_embedder, out["latent"])
591
+ out["text"] = run(model.context_embedder, out["conditioning"])
592
+ out["phase"] = "joint"
593
+ elif phase == "joint" and cursor < self.joint_layers:
594
+ context = out["context"]
595
+ out["text"], out["image"] = run(
596
+ model.transformer_blocks[cursor],
597
+ hidden_states=out["image"],
598
+ encoder_hidden_states=out["text"],
599
+ temb=context["temb"],
600
+ image_rotary_emb=context["rope"],
601
+ joint_attention_kwargs=None,
602
+ )
603
+ out["cursor"] += 1
604
+ if self.granularity == "operation" and out["cursor"] == self.joint_layers:
605
+ out["phase"], out["cursor"] = "single", 0
606
+ elif phase == "joint" or cursor < self.single_layers:
607
+ index = 0 if phase == "joint" else cursor
608
+ context = out["context"]
609
+ out["text"], out["image"] = run(
610
+ model.single_transformer_blocks[index],
611
+ hidden_states=out["image"],
612
+ encoder_hidden_states=out["text"],
613
+ temb=context["temb"],
614
+ image_rotary_emb=context["rope"],
615
+ joint_attention_kwargs=None,
616
+ )
617
+ out["phase"], out["cursor"] = "single", index + 1
618
+ if self.granularity == "operation" and out["cursor"] == self.single_layers:
619
+ out["phase"] = "readout"
620
+ elif self.granularity == "operation" and phase == "readout":
621
+ out["noise_prediction"] = run(
622
+ model.proj_out, run(model.norm_out, out["image"], out["context"]["temb"])
623
+ )
624
+ out["phase"] = "scheduler"
625
+ else:
626
+ noise = out["noise_prediction"]
627
+ if noise is None:
628
+ noise = run(
629
+ model.proj_out, run(model.norm_out, out["image"], out["context"]["temb"])
630
+ )
631
+ scheduler = FlowMatchEulerDiscreteScheduler.from_config(self.scheduler_config)
632
+ scheduler.timesteps, scheduler.sigmas = out["timesteps"], out["sigmas"]
633
+ scheduler.set_begin_index(out["step"])
634
+ out["latent"] = scheduler.step(
635
+ noise, out["timesteps"][out["step"]], out["latent"], return_dict=False
636
+ )[0]
637
+ out["step"] += 1
638
+ out["phase"], out["cursor"] = "project", 0
639
+ out["text"], out["image"], out["context"] = None, None, None
640
+ out["noise_prediction"] = None
641
+ return out
642
+
643
+ def finish(self, session):
644
+ if session.adapter is not self:
645
+ raise ValueError("session belongs to another adapter")
646
+ while session._state["step"] < len(session._state["timesteps"]):
647
+ session.continue_()
648
+
649
+ @torch.inference_mode()
650
+ def decode(self, session, *, height, width):
651
+ if self.pipeline is None or session.adapter is not self:
652
+ raise ValueError("decode requires a native pipeline and its own session")
653
+ if session._state["step"] != len(session._state["timesteps"]):
654
+ raise ValueError("decode requires a completed trajectory")
655
+ pipe = self.pipeline
656
+ latent = pipe._unpack_latents(session.read("latent"), height, width, pipe.vae_scale_factor)
657
+ latent = (latent / pipe.vae.config.scaling_factor) + pipe.vae.config.shift_factor
658
+ pixels = pipe.vae.decode(latent.to(next(pipe.vae.parameters()).device), return_dict=False)[
659
+ 0
660
+ ]
661
+ return pipe.image_processor.postprocess(pixels, output_type="pil")[0]