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