phobos-stream 0.2.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.
Files changed (51) hide show
  1. phobos_stream/__init__.py +24 -0
  2. phobos_stream/adapters/__init__.py +17 -0
  3. phobos_stream/adapters/base.py +96 -0
  4. phobos_stream/adapters/cogvideo_adapter.py +55 -0
  5. phobos_stream/adapters/factory.py +27 -0
  6. phobos_stream/adapters/flux_adapter.py +78 -0
  7. phobos_stream/adapters/hunyuan_adapter.py +56 -0
  8. phobos_stream/adapters/wan_adapter.py +82 -0
  9. phobos_stream/backends/__init__.py +7 -0
  10. phobos_stream/backends/base.py +138 -0
  11. phobos_stream/backends/cuda_backend.py +86 -0
  12. phobos_stream/backends/factory.py +39 -0
  13. phobos_stream/backends/gguf_backend.py +176 -0
  14. phobos_stream/backends/mlx_backend.py +183 -0
  15. phobos_stream/cli.py +184 -0
  16. phobos_stream/integrations/__init__.py +1 -0
  17. phobos_stream/integrations/comfyui/__init__.py +35 -0
  18. phobos_stream/integrations/comfyui/comfy_runtime.py +336 -0
  19. phobos_stream/integrations/comfyui/nodes.py +429 -0
  20. phobos_stream/media/__init__.py +5 -0
  21. phobos_stream/media/video_writer.py +145 -0
  22. phobos_stream/models/__init__.py +14 -0
  23. phobos_stream/models/attention.py +90 -0
  24. phobos_stream/models/dit_block.py +109 -0
  25. phobos_stream/models/rotary.py +81 -0
  26. phobos_stream/pipeline/__init__.py +7 -0
  27. phobos_stream/pipeline/offloader.py +233 -0
  28. phobos_stream/pipeline/scheduler.py +32 -0
  29. phobos_stream/pipeline/stage_runner.py +197 -0
  30. phobos_stream/pipeline/stream_engine.py +144 -0
  31. phobos_stream/pipelines/__init__.py +8 -0
  32. phobos_stream/pipelines/mlx_zimage.py +347 -0
  33. phobos_stream/pipelines/mlx_zimage_blocks.py +235 -0
  34. phobos_stream/pipelines/mlx_zimage_vae.py +98 -0
  35. phobos_stream/server/__init__.py +17 -0
  36. phobos_stream/server/app.py +192 -0
  37. phobos_stream/server/schemas.py +55 -0
  38. phobos_stream/server/ws_progress.py +36 -0
  39. phobos_stream/storage/__init__.py +7 -0
  40. phobos_stream/storage/layout.py +105 -0
  41. phobos_stream/storage/mmap_loader.py +194 -0
  42. phobos_stream/storage/sharder.py +137 -0
  43. phobos_stream/streaming/__init__.py +15 -0
  44. phobos_stream/streaming/mlx_block_streamer.py +159 -0
  45. phobos_stream/streaming/torch_block_streamer.py +401 -0
  46. phobos_stream/types.py +79 -0
  47. phobos_stream-0.2.0.dist-info/METADATA +154 -0
  48. phobos_stream-0.2.0.dist-info/RECORD +51 -0
  49. phobos_stream-0.2.0.dist-info/WHEEL +4 -0
  50. phobos_stream-0.2.0.dist-info/entry_points.txt +2 -0
  51. phobos_stream-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,144 @@
1
+ """Core diffusion streaming generation engine with batched CFG & mlx_lm pipeline optimizations."""
2
+
3
+ from typing import Callable, Optional, Tuple
4
+ import time
5
+ import numpy as np
6
+
7
+ from phobos_stream.adapters.factory import get_adapter
8
+ from phobos_stream.backends.factory import get_backend
9
+ from phobos_stream.models.rotary import RotaryEmbedding3D
10
+ from phobos_stream.pipeline.offloader import PipelineOffloader
11
+ from phobos_stream.pipeline.scheduler import FlowMatchingScheduler
12
+ from phobos_stream.storage.layout import ModelShardsManifest
13
+ from phobos_stream.types import BackendType, GenerationConfig, PipelineMetrics, PipelineStage
14
+
15
+
16
+ class PhobosStreamEngine:
17
+ """Universal Zero-VRAM Video and Image Generation Engine."""
18
+
19
+ def __init__(
20
+ self,
21
+ manifest: ModelShardsManifest,
22
+ backend_type: BackendType = BackendType.AUTO,
23
+ ) -> None:
24
+ self.manifest = manifest
25
+ self.backend = get_backend(backend_type)
26
+ self.adapter = get_adapter(
27
+ manifest.architecture,
28
+ self.backend,
29
+ hidden_size=manifest.hidden_size,
30
+ allow_synthetic=manifest.allow_synthetic,
31
+ )
32
+ self.offloader = PipelineOffloader(manifest, self.adapter, self.backend)
33
+ self.rotary = RotaryEmbedding3D(dim=manifest.hidden_size, backend=self.backend)
34
+
35
+ def generate(
36
+ self,
37
+ config: GenerationConfig,
38
+ progress_callback: Optional[Callable[[int, int, str], None]] = None,
39
+ ) -> Tuple[np.ndarray, PipelineMetrics]:
40
+ """Execute full video or image generation pipeline returning `(T, H, W, 3)` RGB frames."""
41
+ rgb_frames, _, metrics = self.generate_with_latents(config, progress_callback=progress_callback)
42
+ return rgb_frames, metrics
43
+
44
+ def generate_with_latents(
45
+ self,
46
+ config: GenerationConfig,
47
+ progress_callback: Optional[Callable[[int, int, str], None]] = None,
48
+ ) -> Tuple[np.ndarray, np.ndarray, PipelineMetrics]:
49
+ """Execute full pipeline and return decoded `(T, H, W, 3)` RGB frames and raw latents."""
50
+ metrics = PipelineMetrics()
51
+ start_total = time.perf_counter()
52
+
53
+ # 1. Text Encoding Stage
54
+ if progress_callback:
55
+ progress_callback(0, config.steps, PipelineStage.TEXT_ENCODING.value)
56
+ prompt_emb, t_enc_time = self.offloader.encode_text_stage(config.prompt)
57
+ neg_emb = None
58
+ if config.negative_prompt and config.guidance_scale > 1.0:
59
+ neg_emb, neg_time = self.offloader.encode_text_stage(config.negative_prompt)
60
+ t_enc_time += neg_time
61
+ metrics.text_encode_time_sec = t_enc_time
62
+
63
+ # 2. Latent Noise Initialization
64
+ if progress_callback:
65
+ progress_callback(0, config.steps, PipelineStage.LATENT_INIT.value)
66
+ t_len = max(1, (config.num_frames - 1) // 4 + 1) if config.num_frames > 1 else 1
67
+ h_len = max(1, config.height // 16)
68
+ w_len = max(1, config.width // 16)
69
+ seq_len = t_len * h_len * w_len
70
+
71
+ latents = self.backend.randn(
72
+ (1, seq_len, self.manifest.hidden_size),
73
+ seed=config.seed,
74
+ )
75
+ cos, sin = self.rotary.compute_frequencies(t_len=t_len, h_len=h_len, w_len=w_len)
76
+
77
+ # 3. Iterative Denoising Loop (Single-pass batched CFG halves shard disk I/O)
78
+ scheduler = FlowMatchingScheduler(num_steps=config.steps)
79
+ timesteps = scheduler.get_timesteps()
80
+
81
+ start_denoise = time.perf_counter()
82
+ total_io_bytes = 0
83
+ use_cfg = neg_emb is not None and config.guidance_scale > 1.0
84
+ batched_ctx = self.backend.concat([prompt_emb, neg_emb], axis=0) if use_cfg else prompt_emb
85
+
86
+ with self.backend.wired_limit():
87
+ for step_idx, t in enumerate(timesteps):
88
+ if progress_callback:
89
+ progress_callback(step_idx + 1, config.steps, PipelineStage.DENOISING.value)
90
+
91
+ if use_cfg:
92
+ batched_latents = self.backend.concat([latents, latents], axis=0)
93
+ batched_out, io_bytes = self.offloader.stream_dit_step(
94
+ latents=batched_latents,
95
+ context=batched_ctx,
96
+ timestep=t,
97
+ cos=cos,
98
+ sin=sin,
99
+ block_stream=config.block_stream,
100
+ )
101
+ total_io_bytes += io_bytes
102
+ cond_out, uncond_out = self.backend.split_two(batched_out, axis=0)
103
+ guided_out = uncond_out + float(config.guidance_scale) * (cond_out - uncond_out)
104
+ else:
105
+ guided_out, io_bytes = self.offloader.stream_dit_step(
106
+ latents=latents,
107
+ context=batched_ctx,
108
+ timestep=t,
109
+ cos=cos,
110
+ sin=sin,
111
+ block_stream=config.block_stream,
112
+ )
113
+ total_io_bytes += io_bytes
114
+
115
+ latents = scheduler.step(model_output=guided_out, timestep=t, sample=latents)
116
+ self.backend.async_eval(latents)
117
+ metrics.steps_completed = step_idx + 1
118
+
119
+ self.backend.synchronize()
120
+ metrics.denoising_time_sec = time.perf_counter() - start_denoise
121
+ final_latents_np = self.backend.to_numpy(latents)
122
+
123
+ # 4. VAE Latent Decode Stage
124
+ if progress_callback:
125
+ progress_callback(config.steps, config.steps, PipelineStage.VAE_DECODING.value)
126
+ rgb_frames, vae_time = self.offloader.decode_vae_stage(
127
+ latents=latents,
128
+ height=config.height,
129
+ width=config.width,
130
+ num_frames=config.num_frames,
131
+ )
132
+ metrics.vae_decode_time_sec = vae_time
133
+
134
+ # Final Telemetry
135
+ metrics.total_time_sec = time.perf_counter() - start_total
136
+ metrics.disk_bytes_read_mb = total_io_bytes / (1024.0 * 1024.0)
137
+ metrics.peak_vram_mb = self.backend.get_memory_allocated_mb()
138
+ if metrics.denoising_time_sec > 0:
139
+ metrics.io_throughput_mb_s = metrics.disk_bytes_read_mb / metrics.denoising_time_sec
140
+
141
+ if progress_callback:
142
+ progress_callback(config.steps, config.steps, PipelineStage.COMPLETED.value)
143
+
144
+ return rgb_frames, final_latents_np, metrics
@@ -0,0 +1,8 @@
1
+ """Production MLX model pipelines with 3-stage offloading and per-block mmap streaming."""
2
+
3
+ from phobos_stream.pipelines.mlx_zimage import (
4
+ MLXGenerationResult,
5
+ generate_zimage_mlx,
6
+ )
7
+
8
+ __all__ = ["MLXGenerationResult", "generate_zimage_mlx"]
@@ -0,0 +1,347 @@
1
+ """Real Apple Silicon Metal (MLX) Z-Image-Turbo pipeline with 3-stage & per-block mmap streaming."""
2
+
3
+ from dataclasses import dataclass
4
+ import gc
5
+ from pathlib import Path
6
+ import resource
7
+ import time
8
+ from typing import Any, Tuple, Union
9
+ import numpy as np
10
+
11
+ from phobos_stream.pipelines.mlx_zimage_blocks import (
12
+ exec_fused_zimage_block,
13
+ map_zimage_transformer,
14
+ stream_single_zimage_block_mmap,
15
+ )
16
+ from phobos_stream.pipelines.mlx_zimage_vae import decode_mlx_latents_to_uint8, load_mlx_flux_vae
17
+ from phobos_stream.storage.mmap_loader import MMapTensorLoader
18
+
19
+
20
+ @dataclass
21
+ class MLXGenerationResult:
22
+ """Image output and verified hardware telemetry for an MLX Z-Image generation run."""
23
+
24
+ image: np.ndarray
25
+ mode: str
26
+ wall_sec: float
27
+ load_sec: float
28
+ text_sec: float
29
+ denoise_sec: float
30
+ step_sec: float
31
+ vae_sec: float
32
+ peak_metal_mb: float
33
+ active_resident_mb: float
34
+ peak_rss_mb: float
35
+ streamed_gb: float
36
+
37
+
38
+ def _rss_mb() -> float:
39
+ return float(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) / (1024.0 * 1024.0)
40
+
41
+
42
+ def _flush_metal() -> None:
43
+ import mlx.core as mx
44
+
45
+ gc.collect()
46
+ if hasattr(mx, "clear_cache"):
47
+ mx.clear_cache()
48
+
49
+
50
+ def _tokenize_qwen_prompt(prompt: str, tokenizer_dir: Union[str, Path]) -> Tuple[np.ndarray, Any, int]:
51
+ import mlx.core as mx
52
+ from transformers import AutoTokenizer
53
+
54
+ hf_tok = AutoTokenizer.from_pretrained(str(tokenizer_dir), local_files_only=True)
55
+ formatted = hf_tok.apply_chat_template(
56
+ [{"role": "user", "content": prompt}],
57
+ tokenize=False,
58
+ add_generation_prompt=True,
59
+ enable_thinking=True,
60
+ )
61
+ enc = hf_tok(formatted, return_tensors="np", padding="max_length", max_length=512, truncation=True)
62
+ return enc["input_ids"], mx.array(enc["attention_mask"]), int(np.sum(enc["attention_mask"][0]))
63
+
64
+
65
+ def generate_zimage_mlx(
66
+ prompt: str,
67
+ qwen_path: Union[str, Path],
68
+ dit_path: Union[str, Path],
69
+ vae_path: Union[str, Path],
70
+ tokenizer_dir: Union[str, Path],
71
+ width: int = 1024,
72
+ height: int = 1024,
73
+ steps: int = 8,
74
+ seed: int = 42,
75
+ mode: str = "stage_offload",
76
+ verbose: bool = True,
77
+ ) -> MLXGenerationResult:
78
+ """Execute Z-Image-Turbo on Apple Metal in `monolithic`, `stage_offload`, `q4_stage_offload`, or `block_stream` mode."""
79
+ import mlx.core as mx
80
+ import mlx.nn as nn
81
+ from mlx.utils import tree_flatten, tree_unflatten
82
+ from mflux.models.common.config.config import Config
83
+ from mflux.models.common.config.model_config import ModelConfig
84
+ from mflux.models.z_image.latent_creator import ZImageLatentCreator
85
+ from mflux.models.z_image.model.z_image_text_encoder.text_encoder import TextEncoder
86
+ from mflux.models.z_image.model.z_image_transformer.transformer import ZImageTransformer
87
+
88
+ _flush_metal()
89
+ mx.reset_peak_memory()
90
+ t_total0 = time.perf_counter()
91
+ bytes_streamed = 0
92
+ cfg = Config(
93
+ width=width,
94
+ height=height,
95
+ guidance=0.0,
96
+ scheduler="linear",
97
+ model_config=ModelConfig.z_image_turbo(),
98
+ num_inference_steps=steps,
99
+ )
100
+
101
+ if mode == "monolithic":
102
+ t0 = time.perf_counter()
103
+ ids_np, mask_mx, num_valid = _tokenize_qwen_prompt(prompt, tokenizer_dir)
104
+ raw_q = mx.load(str(qwen_path))
105
+ te = TextEncoder()
106
+ te.update(tree_unflatten([(k.removeprefix("model."), v.astype(mx.bfloat16)) for k, v in raw_q.items() if k.startswith("model.")]))
107
+ del raw_q
108
+ mx.eval(te.parameters())
109
+ tr, _, _, _ = map_zimage_transformer(dit_path, quantize_bits=None, fuse_blocks=False)
110
+ vae = load_mlx_flux_vae(vae_path, low_memory=False)
111
+ active_res_mb = float(mx.get_active_memory()) / (1024.0 * 1024.0)
112
+ t_load = time.perf_counter() - t0
113
+
114
+ t_e0 = time.perf_counter()
115
+ cap_feats = te(mx.array(ids_np), mask_mx)[0, :num_valid, :].astype(mx.bfloat16)
116
+ mx.eval(cap_feats)
117
+ t_enc = time.perf_counter() - t_e0
118
+
119
+ latents = ZImageLatentCreator.create_noise(seed=seed, height=height, width=width)
120
+ mx.eval(latents, cfg.scheduler.sigmas)
121
+ t_d0 = time.perf_counter()
122
+ for t in cfg.time_steps:
123
+ sig = cfg.scheduler.sigmas[t].reshape((1,))
124
+ noise = tr(x=latents, timestep=mx.ones_like(sig) - sig, sigmas=cfg.scheduler.sigmas, cap_feats=cap_feats)
125
+ latents = cfg.scheduler.step(noise=noise, timestep=t, latents=latents)
126
+ mx.eval(latents)
127
+ t_den = time.perf_counter() - t_d0
128
+
129
+ t_v0 = time.perf_counter()
130
+ img_np = decode_mlx_latents_to_uint8(vae, ZImageLatentCreator.unpack_latents(latents, height, width))
131
+ t_vae = time.perf_counter() - t_v0
132
+ peak_mb = float(mx.get_peak_memory()) / (1024.0 * 1024.0)
133
+ del te, tr, vae
134
+
135
+ elif mode in ("stage_offload", "q4_stage_offload"):
136
+ q_bits = 4 if mode == "q4_stage_offload" else None
137
+ t_e0 = time.perf_counter()
138
+ ids_np, mask_mx, num_valid = _tokenize_qwen_prompt(prompt, tokenizer_dir)
139
+ raw_q = mx.load(str(qwen_path))
140
+ te = TextEncoder()
141
+ te.update(tree_unflatten([(k.removeprefix("model."), v.astype(mx.bfloat16)) for k, v in raw_q.items() if k.startswith("model.")]))
142
+ del raw_q
143
+ if q_bits:
144
+ nn.quantize(te, group_size=64, bits=q_bits)
145
+ mx.eval(te.parameters())
146
+ cap_feats = te(mx.array(ids_np), mask_mx)[0, :num_valid, :].astype(mx.bfloat16)
147
+ mx.eval(cap_feats)
148
+ del te, mask_mx
149
+ _flush_metal()
150
+ t_enc = time.perf_counter() - t_e0
151
+
152
+ t_l0 = time.perf_counter()
153
+ tr, fast_nr, fast_cr, fast_ly = map_zimage_transformer(dit_path, quantize_bits=q_bits, fuse_blocks=(q_bits is None))
154
+ t_load = time.perf_counter() - t_l0
155
+ active_res_mb = float(mx.get_active_memory()) / (1024.0 * 1024.0)
156
+
157
+ latents = ZImageLatentCreator.create_noise(seed=seed, height=height, width=width)
158
+ mx.eval(latents, cfg.scheduler.sigmas)
159
+ t_d0 = time.perf_counter()
160
+ if q_bits is None:
161
+ key = f"{tr.patch_size}-{tr.f_patch_size}"
162
+ _, cap_pad, x_sz, x_pos, c_pos, x_pm, c_pm = ZImageTransformer._patchify(latents, cap_feats, tr.patch_size, tr.f_patch_size)
163
+ x_fq, c_fq = tr.rope_embedder(x_pos), tr.rope_embedder(c_pos)
164
+ u_fq = mx.concatenate([x_fq, c_fq], axis=0)
165
+ c_emb = mx.expand_dims(mx.where(c_pm[:, None], tr.cap_pad_token, tr.cap_embedder[1](tr.cap_embedder[0](cap_pad))), axis=0)
166
+ for b_cr in fast_cr:
167
+ c_emb = exec_fused_zimage_block(b_cr, c_emb, c_fq, None)
168
+ mx.eval(c_emb, x_fq, u_fq)
169
+
170
+ pF, pH, pW = tr.f_patch_size, tr.patch_size, tr.patch_size
171
+ C, F, H, W = latents.shape
172
+ F_t, H_t, W_t = F // pF, H // pH, W // pW
173
+ ori_len, pad_len = F_t * H_t * W_t, (-(F_t * H_t * W_t)) % 32
174
+ for t in cfg.time_steps:
175
+ sig = cfg.scheduler.sigmas[t].reshape((1,))
176
+ t_emb = tr.t_embedder((mx.ones_like(sig) - sig).astype(mx.float32) * tr.t_scale).astype(mx.bfloat16)
177
+ flat = mx.transpose(latents.reshape(C, F_t, pF, H_t, pH, W_t, pW), (1, 3, 5, 2, 4, 6, 0)).reshape(ori_len, pF * pH * pW * C)
178
+ if pad_len > 0:
179
+ flat = mx.concatenate([flat, mx.repeat(flat[-1:], pad_len, axis=0)], axis=0)
180
+ x_emb = mx.expand_dims(mx.where(x_pm[:, None], tr.x_pad_token, tr.all_x_embedder[key](flat)), axis=0)
181
+ for b_nr in fast_nr:
182
+ x_emb = exec_fused_zimage_block(b_nr, x_emb, x_fq, t_emb)
183
+ x_len = x_emb.shape[1]
184
+ uni = mx.concatenate([x_emb, c_emb], axis=1)
185
+ for b_ly in fast_ly:
186
+ uni = exec_fused_zimage_block(b_ly, uni, u_fq, t_emb)
187
+ noise = -ZImageTransformer._unpatchify(tr.all_final_layer[key](uni, t_emb)[0, :x_len], x_sz, pH, pF, tr.out_channels)
188
+ latents = cfg.scheduler.step(noise=noise, timestep=t, latents=latents)
189
+ mx.eval(latents)
190
+ else:
191
+ for t in cfg.time_steps:
192
+ sig = cfg.scheduler.sigmas[t].reshape((1,))
193
+ noise = tr(x=latents, timestep=mx.ones_like(sig) - sig, sigmas=cfg.scheduler.sigmas, cap_feats=cap_feats)
194
+ latents = cfg.scheduler.step(noise=noise, timestep=t, latents=latents)
195
+ mx.eval(latents)
196
+ t_den = time.perf_counter() - t_d0
197
+ unpacked = ZImageLatentCreator.unpack_latents(latents, height, width)
198
+ mx.eval(unpacked)
199
+ del tr, fast_nr, fast_cr, fast_ly, cap_feats, latents
200
+ _flush_metal()
201
+
202
+ t_v0 = time.perf_counter()
203
+ vae = load_mlx_flux_vae(vae_path, low_memory=True)
204
+ img_np = decode_mlx_latents_to_uint8(vae, unpacked)
205
+ del vae, unpacked
206
+ _flush_metal()
207
+ t_vae = time.perf_counter() - t_v0
208
+ peak_mb = float(mx.get_peak_memory()) / (1024.0 * 1024.0)
209
+
210
+ elif mode == "block_stream":
211
+ t_load = 0.0
212
+ t_e0 = time.perf_counter()
213
+ ids_np, mask_mx, num_valid = _tokenize_qwen_prompt(prompt, tokenizer_dir)
214
+ with MMapTensorLoader(Path(qwen_path)) as q_loader:
215
+ view, _, emb_shape = q_loader.read_raw_slice("model.embed_tokens.weight")
216
+ rows_u16 = np.ascontiguousarray(np.frombuffer(view, dtype=np.uint16).reshape(emb_shape)[ids_np])
217
+ bytes_streamed += rows_u16.nbytes
218
+ hidden = mx.array(rows_u16).view(mx.bfloat16).astype(mx.float32)
219
+
220
+ te_shell = TextEncoder(num_hidden_layers=1)
221
+ te_shell.embed_tokens = None
222
+ single_layer = te_shell.layers[0]
223
+ pos_emb = te_shell.rotary_emb(hidden, mx.broadcast_to(mx.arange(512, dtype=mx.int32)[None, :], (1, 512)))
224
+ causal_mask = TextEncoder._get_causal_mask(mask_mx, 1, hidden, 512)
225
+ mx.eval(hidden, causal_mask)
226
+
227
+ l_keys = [k for k, _ in tree_flatten(single_layer.parameters())]
228
+ for l_idx in range(35):
229
+ leaves = []
230
+ for pk in l_keys:
231
+ st_k = f"model.layers.{l_idx}.{pk}"
232
+ bytes_streamed += q_loader.get_tensor_byte_size(st_k)
233
+ leaves.append((pk, q_loader.read_mlx_array(st_k, target_dtype=mx.bfloat16)))
234
+ single_layer.update(tree_unflatten(leaves))
235
+ mx.eval(single_layer.parameters())
236
+ del leaves
237
+ hidden = single_layer(hidden_states=hidden, attention_mask=causal_mask, position_embeddings=pos_emb)
238
+ mx.eval(hidden)
239
+ single_layer.update(tree_unflatten([(pk, mx.zeros((0,), dtype=mx.bfloat16)) for pk in l_keys]))
240
+ mx.eval(single_layer.parameters())
241
+ if hasattr(mx, "clear_cache"):
242
+ mx.clear_cache()
243
+
244
+ cap_feats = hidden[0, :num_valid, :].astype(mx.bfloat16)
245
+ mx.eval(cap_feats)
246
+ del te_shell, single_layer, hidden, causal_mask, pos_emb, mask_mx
247
+ _flush_metal()
248
+ t_enc = time.perf_counter() - t_e0
249
+
250
+ t_d0 = time.perf_counter()
251
+ with MMapTensorLoader(Path(dit_path)) as dit_loader:
252
+ stem = ZImageTransformer(n_layers=0, n_refiner_layers=0)
253
+ stem.set_float32(False)
254
+ stem_map = [
255
+ ("t_embedder.linear1.weight", "t_embedder.mlp.0.weight"),
256
+ ("t_embedder.linear1.bias", "t_embedder.mlp.0.bias"),
257
+ ("t_embedder.linear2.weight", "t_embedder.mlp.2.weight"),
258
+ ("t_embedder.linear2.bias", "t_embedder.mlp.2.bias"),
259
+ ("all_x_embedder.2-1.weight", "x_embedder.weight"),
260
+ ("all_x_embedder.2-1.bias", "x_embedder.bias"),
261
+ ("all_final_layer.2-1.linear.weight", "final_layer.linear.weight"),
262
+ ("all_final_layer.2-1.linear.bias", "final_layer.linear.bias"),
263
+ ("all_final_layer.2-1.adaLN_modulation.0.weight", "final_layer.adaLN_modulation.1.weight"),
264
+ ("all_final_layer.2-1.adaLN_modulation.0.bias", "final_layer.adaLN_modulation.1.bias"),
265
+ ("cap_embedder.0.weight", "cap_embedder.0.weight"),
266
+ ("cap_embedder.1.weight", "cap_embedder.1.weight"),
267
+ ("cap_embedder.1.bias", "cap_embedder.1.bias"),
268
+ ("x_pad_token", "x_pad_token"),
269
+ ("cap_pad_token", "cap_pad_token"),
270
+ ]
271
+ stem.update(tree_unflatten([(dk, dit_loader.read_mlx_array(sk, target_dtype=mx.bfloat16)) for dk, sk in stem_map]))
272
+ bytes_streamed += sum(dit_loader.get_tensor_byte_size(sk) for _, sk in stem_map)
273
+ mx.eval(stem.parameters())
274
+ active_res_mb = float(mx.get_active_memory()) / (1024.0 * 1024.0)
275
+
276
+ latents = ZImageLatentCreator.create_noise(seed=seed, height=height, width=width)
277
+ mx.eval(latents, cfg.scheduler.sigmas)
278
+ key = f"{stem.patch_size}-{stem.f_patch_size}"
279
+ _, cap_pad, x_sz, x_pos, c_pos, x_pm, c_pm = ZImageTransformer._patchify(latents, cap_feats, stem.patch_size, stem.f_patch_size)
280
+ x_fq, c_fq = stem.rope_embedder(x_pos), stem.rope_embedder(c_pos)
281
+ u_fq = mx.concatenate([x_fq, c_fq], axis=0)
282
+ c_emb = mx.expand_dims(mx.where(c_pm[:, None], stem.cap_pad_token, stem.cap_embedder[1](stem.cap_embedder[0](cap_pad))), axis=0)
283
+ for cr_i in range(2):
284
+ c_emb, br = stream_single_zimage_block_mmap(dit_loader, f"context_refiner.{cr_i}", c_emb, c_fq, None, False)
285
+ bytes_streamed += br
286
+ mx.eval(c_emb, x_fq, u_fq)
287
+
288
+ pF, pH, pW = stem.f_patch_size, stem.patch_size, stem.patch_size
289
+ C, F, H, W = latents.shape
290
+ F_t, H_t, W_t = F // pF, H // pH, W // pW
291
+ ori_len, pad_len = F_t * H_t * W_t, (-(F_t * H_t * W_t)) % 32
292
+
293
+ for s_i, t in enumerate(cfg.time_steps):
294
+ ts0 = time.perf_counter()
295
+ sig = cfg.scheduler.sigmas[t].reshape((1,))
296
+ t_emb = stem.t_embedder((mx.ones_like(sig) - sig).astype(mx.float32) * stem.t_scale).astype(mx.bfloat16)
297
+ flat = mx.transpose(latents.reshape(C, F_t, pF, H_t, pH, W_t, pW), (1, 3, 5, 2, 4, 6, 0)).reshape(ori_len, pF * pH * pW * C)
298
+ if pad_len > 0:
299
+ flat = mx.concatenate([flat, mx.repeat(flat[-1:], pad_len, axis=0)], axis=0)
300
+ x_emb = mx.expand_dims(mx.where(x_pm[:, None], stem.x_pad_token, stem.all_x_embedder[key](flat)), axis=0)
301
+ for nr_i in range(2):
302
+ x_emb, br = stream_single_zimage_block_mmap(dit_loader, f"noise_refiner.{nr_i}", x_emb, x_fq, t_emb, True)
303
+ bytes_streamed += br
304
+ x_len = x_emb.shape[1]
305
+ uni = mx.concatenate([x_emb, c_emb], axis=1)
306
+ for ly_i in range(30):
307
+ uni, br = stream_single_zimage_block_mmap(dit_loader, f"layers.{ly_i}", uni, u_fq, t_emb, True)
308
+ bytes_streamed += br
309
+ noise = -ZImageTransformer._unpatchify(stem.all_final_layer[key](uni, t_emb)[0, :x_len], x_sz, pH, pF, stem.out_channels)
310
+ latents = cfg.scheduler.step(noise=noise, timestep=t, latents=latents)
311
+ mx.eval(latents)
312
+ if verbose:
313
+ act_mb = float(mx.get_active_memory()) / (1024.0 * 1024.0)
314
+ pk_mb = float(mx.get_peak_memory()) / (1024.0 * 1024.0)
315
+ print(f" [block_stream step {s_i+1}/{steps}] {time.perf_counter()-ts0:.2f}s | Active Metal: {act_mb:.1f} MB | Peak Metal: {pk_mb:.1f} MB", flush=True)
316
+
317
+ unpacked = ZImageLatentCreator.unpack_latents(latents, height, width)
318
+ mx.eval(unpacked)
319
+ del stem, c_emb, cap_feats, latents
320
+ _flush_metal()
321
+ t_den = time.perf_counter() - t_d0
322
+
323
+ t_v0 = time.perf_counter()
324
+ vae = load_mlx_flux_vae(vae_path, low_memory=True)
325
+ img_np = decode_mlx_latents_to_uint8(vae, unpacked)
326
+ del vae, unpacked
327
+ _flush_metal()
328
+ t_vae = time.perf_counter() - t_v0
329
+ peak_mb = float(mx.get_peak_memory()) / (1024.0 * 1024.0)
330
+ else:
331
+ raise ValueError(f"Unsupported mode: {mode}")
332
+
333
+ wall = time.perf_counter() - t_total0
334
+ return MLXGenerationResult(
335
+ image=img_np,
336
+ mode=mode,
337
+ wall_sec=round(wall, 2),
338
+ load_sec=round(t_load, 2),
339
+ text_sec=round(t_enc, 2),
340
+ denoise_sec=round(t_den, 2),
341
+ step_sec=round(t_den / max(1, steps), 2),
342
+ vae_sec=round(t_vae, 2),
343
+ peak_metal_mb=round(peak_mb, 1),
344
+ active_resident_mb=round(active_res_mb, 1),
345
+ peak_rss_mb=round(_rss_mb(), 1),
346
+ streamed_gb=round(bytes_streamed / (1024.0 ** 3), 2),
347
+ )