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,401 @@
1
+ """Universal hook-based block streamer for PyTorch Diffusion Transformers & UNets."""
2
+
3
+ from enum import Enum
4
+ from pathlib import Path
5
+ from typing import Any, Dict, List, Optional, Sequence, Set, Tuple, Union
6
+
7
+ from phobos_stream.storage.mmap_loader import MMapTensorLoader
8
+
9
+
10
+ KNOWN_BLOCK_CONTAINERS: Set[str] = {
11
+ "blocks",
12
+ "layers",
13
+ "double_blocks",
14
+ "single_blocks",
15
+ "single_transformer_blocks",
16
+ "transformer_blocks",
17
+ "noise_refiner",
18
+ "context_refiner",
19
+ "joint_blocks",
20
+ "spatial_blocks",
21
+ "temporal_blocks",
22
+ "v_blocks",
23
+ }
24
+
25
+ STRIP_MODEL_PREFIXES: Tuple[str, ...] = (
26
+ "model.diffusion_model.",
27
+ "diffusion_model.",
28
+ "transformer.",
29
+ "unet.",
30
+ "model.",
31
+ )
32
+
33
+
34
+ class BlockStreamMode(str, Enum):
35
+ """Execution mode for transformer block memory management."""
36
+
37
+ STAGE_ONLY = "stage_only"
38
+ CPU_OFFLOAD = "cpu_offload"
39
+ MMAP_STREAM = "mmap_stream"
40
+
41
+
42
+ def _resolve_subattr(root: Any, dotted_path: str) -> Tuple[Any, str]:
43
+ """Return `(parent_module, leaf_attr_name)` for a dotted parameter/buffer path."""
44
+ parts = dotted_path.split(".")
45
+ cur = root
46
+ for part in parts[:-1]:
47
+ cur = getattr(cur, part)
48
+ return cur, parts[-1]
49
+
50
+
51
+ def _assign_tensor(root: Any, dotted_path: str, new_tensor: Any, is_param: bool) -> None:
52
+ """Assign a parameter or buffer tensor safely, including on `meta`-device skeletons."""
53
+ import torch.nn as nn
54
+
55
+ parent, leaf = _resolve_subattr(root, dotted_path)
56
+ if is_param:
57
+ existing = parent._parameters.get(leaf)
58
+ if existing is None or getattr(existing, "is_meta", False):
59
+ parent._parameters[leaf] = nn.Parameter(new_tensor, requires_grad=False)
60
+ else:
61
+ existing.data = new_tensor
62
+ else:
63
+ existing = parent._buffers.get(leaf)
64
+ if existing is None or getattr(existing, "is_meta", False):
65
+ parent._buffers[leaf] = new_tensor
66
+ else:
67
+ existing.data = new_tensor
68
+
69
+
70
+ def discover_block_modules(
71
+ root_module: Any,
72
+ block_attr_names: Optional[Sequence[str]] = None,
73
+ ) -> List[Tuple[str, Any]]:
74
+ """Discover ordered repeating transformer/UNet block modules inside a PyTorch model.
75
+
76
+ Uses a two-pass scan so inner helper `ModuleList` attributes (such as `to_out`)
77
+ inside an already-discovered block are never misclassified as top-level blocks.
78
+ """
79
+ import torch.nn as nn
80
+
81
+ target_names = set(block_attr_names) if block_attr_names else KNOWN_BLOCK_CONTAINERS
82
+ discovered: List[Tuple[str, Any]] = []
83
+ claimed_prefixes: List[str] = []
84
+
85
+ def _is_nested(mod_name: str) -> bool:
86
+ return any(mod_name == p or mod_name.startswith(f"{p}.") for p in claimed_prefixes)
87
+
88
+ # Pass 1: Known transformer/DiT block ModuleList names
89
+ for name, mod in root_module.named_modules():
90
+ if not name or _is_nested(name):
91
+ continue
92
+ leaf_name = name.split(".")[-1]
93
+ if isinstance(mod, nn.ModuleList) and leaf_name in target_names and len(mod) > 0:
94
+ claimed_prefixes.append(name)
95
+ for idx, child in enumerate(mod):
96
+ discovered.append((f"{name}.{idx}", child))
97
+
98
+ if discovered:
99
+ return discovered
100
+
101
+ # Pass 2 fallback: Homogeneous ModuleLists of length >= 2
102
+ for name, mod in root_module.named_modules():
103
+ if not name or _is_nested(name):
104
+ continue
105
+ if isinstance(mod, nn.ModuleList) and len(mod) >= 2:
106
+ child_types = {type(c) for c in mod}
107
+ if len(child_types) == 1:
108
+ claimed_prefixes.append(name)
109
+ for idx, child in enumerate(mod):
110
+ discovered.append((f"{name}.{idx}", child))
111
+
112
+ return discovered
113
+
114
+
115
+ class TorchBlockStreamer:
116
+ """Streams PyTorch DiT/UNet blocks one-by-one from pinned CPU RAM or `.safetensors` mmap.
117
+
118
+ Supports both pre-loaded models (`CPU_OFFLOAD`) and zero-RAM `meta`-device skeletons
119
+ (`MMAP_STREAM`), guaranteeing exact numerical equivalence with monolithic execution.
120
+ """
121
+
122
+ def __init__(
123
+ self,
124
+ model: Any,
125
+ compute_device: Union[str, Any] = "auto",
126
+ mode: BlockStreamMode = BlockStreamMode.CPU_OFFLOAD,
127
+ safetensors_paths: Optional[Sequence[Union[str, Path]]] = None,
128
+ block_attr_names: Optional[Sequence[str]] = None,
129
+ pin_memory: bool = True,
130
+ prefetch: bool = True,
131
+ ) -> None:
132
+ import torch
133
+
134
+ self.model = model
135
+ self._auto_device = str(compute_device) == "auto"
136
+ if self._auto_device:
137
+ if torch.cuda.is_available():
138
+ self.compute_device = torch.device("cuda:0")
139
+ elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
140
+ self.compute_device = torch.device("mps")
141
+ else:
142
+ self.compute_device = torch.device("cpu")
143
+ else:
144
+ self.compute_device = torch.device(compute_device)
145
+ self.mode = BlockStreamMode(mode)
146
+ self.safetensors_paths = [Path(p) for p in (safetensors_paths or [])]
147
+ self.block_attr_names = block_attr_names
148
+ self.pin_memory = pin_memory
149
+ self.prefetch = prefetch
150
+
151
+ self.blocks: List[Tuple[str, Any]] = []
152
+ self.bytes_streamed: int = 0
153
+ self.blocks_executed: int = 0
154
+
155
+ self._hooks: List[Any] = []
156
+ self._loaders: List[MMapTensorLoader] = []
157
+ self._cpu_shadow: Dict[int, List[Tuple[str, bool, Any]]] = {}
158
+ self._prefetch_cache: Dict[int, Dict[str, Any]] = {}
159
+ self._prefetch_stream: Optional[Any] = None
160
+ self._mmap_map: Dict[int, List[Tuple[str, bool, MMapTensorLoader, str, Any]]] = {}
161
+ self._attached = False
162
+
163
+ def _build_safetensors_index(self) -> Dict[str, Tuple[MMapTensorLoader, str]]:
164
+ if not self.safetensors_paths:
165
+ raise ValueError("MMAP_STREAM mode requires at least one `.safetensors` file path.")
166
+ index: Dict[str, Tuple[MMapTensorLoader, str]] = {}
167
+ for path in self.safetensors_paths:
168
+ loader = MMapTensorLoader(path)
169
+ self._loaders.append(loader)
170
+ for raw_key in loader.get_tensor_names():
171
+ index[raw_key] = (loader, raw_key)
172
+ for prefix in STRIP_MODEL_PREFIXES:
173
+ if raw_key.startswith(prefix):
174
+ stripped = raw_key[len(prefix) :]
175
+ index.setdefault(stripped, (loader, raw_key))
176
+ return index
177
+
178
+ @staticmethod
179
+ def _lookup_key(
180
+ st_index: Dict[str, Tuple[MMapTensorLoader, str]],
181
+ candidate: str,
182
+ ) -> Optional[Tuple[MMapTensorLoader, str]]:
183
+ resolved = st_index.get(candidate)
184
+ if resolved is not None:
185
+ return resolved
186
+ for prefix in STRIP_MODEL_PREFIXES:
187
+ if candidate.startswith(prefix) and candidate[len(prefix) :] in st_index:
188
+ return st_index[candidate[len(prefix) :]]
189
+ return None
190
+
191
+ @staticmethod
192
+ def _iter_module_tensors(mod: Any) -> List[Tuple[str, bool, Any]]:
193
+ """Yield `(rel_name, is_param, tensor)` for all parameters and persistent buffers."""
194
+ non_persistent: Set[str] = set()
195
+ for sub_prefix, sub_mod in mod.named_modules():
196
+ np_set = getattr(sub_mod, "_non_persistent_buffers_set", set())
197
+ for buf_name in np_set:
198
+ full_b = f"{sub_prefix}.{buf_name}" if sub_prefix else buf_name
199
+ non_persistent.add(full_b)
200
+
201
+ items: List[Tuple[str, bool, Any]] = [
202
+ (p_name, True, p) for p_name, p in mod.named_parameters(recurse=True)
203
+ ]
204
+ for b_name, buf in mod.named_buffers(recurse=True):
205
+ if b_name not in non_persistent and buf is not None:
206
+ items.append((b_name, False, buf))
207
+ return items
208
+
209
+ def attach(self) -> "TorchBlockStreamer":
210
+ """Attach pre/post forward hooks and offload or evict inactive block tensors."""
211
+ if self._attached or self.mode == BlockStreamMode.STAGE_ONLY:
212
+ return self
213
+
214
+ self.blocks = discover_block_modules(self.model, self.block_attr_names)
215
+ if not self.blocks:
216
+ raise ValueError("No repeating transformer/UNet block ModuleList found on model.")
217
+
218
+ block_prefixes = tuple(f"{pfx}." for pfx, _ in self.blocks)
219
+
220
+ if self.mode == BlockStreamMode.CPU_OFFLOAD:
221
+ for name, is_param, tensor_obj in self._iter_module_tensors(self.model):
222
+ if not name.startswith(block_prefixes) and tensor_obj.device != self.compute_device:
223
+ _assign_tensor(self.model, name, tensor_obj.data.to(self.compute_device), is_param)
224
+ self._setup_cpu_offload()
225
+ elif self.mode == BlockStreamMode.MMAP_STREAM:
226
+ self._setup_mmap_stream(block_prefixes)
227
+
228
+ self._attached = True
229
+ return self
230
+
231
+ def _setup_cpu_offload(self) -> None:
232
+ import torch
233
+
234
+ use_pin = self.pin_memory and self.compute_device.type == "cuda" and torch.cuda.is_available()
235
+ if self.prefetch and self.compute_device.type == "cuda" and torch.cuda.is_available():
236
+ self._prefetch_stream = torch.cuda.Stream(device=self.compute_device)
237
+
238
+ for idx, (_, blk) in enumerate(self.blocks):
239
+ shadow: List[Tuple[str, bool, Any]] = []
240
+ for rel_name, is_param, tensor_obj in self._iter_module_tensors(blk):
241
+ cpu_t = tensor_obj.data.detach().to("cpu")
242
+ if use_pin and not cpu_t.is_pinned():
243
+ cpu_t = cpu_t.pin_memory()
244
+ shadow.append((rel_name, is_param, cpu_t))
245
+ _assign_tensor(blk, rel_name, cpu_t, is_param)
246
+ self._cpu_shadow[idx] = shadow
247
+ self._register_cpu_hooks(idx, blk)
248
+
249
+ def _prefetch_cpu_block(self, idx: int) -> None:
250
+ import torch
251
+
252
+ if idx >= len(self.blocks) or idx in self._prefetch_cache or self._prefetch_stream is None:
253
+ return
254
+ with torch.cuda.stream(self._prefetch_stream):
255
+ self._prefetch_cache[idx] = {
256
+ rel_name: cpu_t.to(self.compute_device, non_blocking=True)
257
+ for rel_name, _, cpu_t in self._cpu_shadow[idx]
258
+ }
259
+
260
+ def _resolve_active_device(self, inputs: Any) -> Any:
261
+ """Match the incoming activation tensor's device dynamically when `compute_device='auto'`."""
262
+ import torch
263
+
264
+ if not self._auto_device:
265
+ return self.compute_device
266
+ stack = list(inputs) if isinstance(inputs, (tuple, list)) else [inputs]
267
+ for item in stack:
268
+ if isinstance(item, torch.Tensor):
269
+ return item.device
270
+ if isinstance(item, (tuple, list)):
271
+ for sub in item:
272
+ if isinstance(sub, torch.Tensor):
273
+ return sub.device
274
+ return self.compute_device
275
+
276
+ def _register_cpu_hooks(self, idx: int, blk: Any) -> None:
277
+ import torch
278
+
279
+ def _pre_hook(module: Any, _inputs: Any) -> None:
280
+ target_dev = self._resolve_active_device(_inputs)
281
+ if (
282
+ self._prefetch_stream is not None
283
+ and target_dev == self.compute_device
284
+ and idx in self._prefetch_cache
285
+ ):
286
+ torch.cuda.current_stream(self.compute_device).wait_stream(self._prefetch_stream)
287
+ dev_map = self._prefetch_cache.pop(idx)
288
+ else:
289
+ dev_map = {
290
+ rel_name: cpu_t.to(target_dev, non_blocking=(target_dev.type == "cuda"))
291
+ for rel_name, _, cpu_t in self._cpu_shadow[idx]
292
+ }
293
+
294
+ for rel_name, is_param, _ in self._cpu_shadow[idx]:
295
+ dev_t = dev_map[rel_name]
296
+ _assign_tensor(module, rel_name, dev_t, is_param)
297
+ self.bytes_streamed += dev_t.numel() * dev_t.element_size()
298
+
299
+ if self._prefetch_stream is not None and target_dev == self.compute_device:
300
+ self._prefetch_cpu_block(idx + 1)
301
+
302
+ def _post_hook(module: Any, _inputs: Any, _output: Any) -> None:
303
+ for rel_name, is_param, cpu_t in self._cpu_shadow[idx]:
304
+ _assign_tensor(module, rel_name, cpu_t, is_param)
305
+ self.blocks_executed += 1
306
+
307
+ self._hooks.append(blk.register_forward_pre_hook(_pre_hook))
308
+ self._hooks.append(blk.register_forward_hook(_post_hook))
309
+
310
+ def _setup_mmap_stream(self, block_prefixes: Tuple[str, ...]) -> None:
311
+ import torch
312
+
313
+ try:
314
+ st_index = self._build_safetensors_index()
315
+
316
+ # Materialize lightweight non-block stem/head layers once onto compute_device
317
+ for full_name, is_param, tensor_obj in self._iter_module_tensors(self.model):
318
+ if full_name.startswith(block_prefixes):
319
+ continue
320
+ resolved = self._lookup_key(st_index, full_name)
321
+ if resolved is not None:
322
+ loader, real_key = resolved
323
+ loaded = loader.read_torch_tensor(
324
+ real_key,
325
+ device=str(self.compute_device),
326
+ target_dtype=tensor_obj.dtype,
327
+ )
328
+ _assign_tensor(self.model, full_name, loaded, is_param)
329
+ elif getattr(tensor_obj, "is_meta", False):
330
+ raise KeyError(f"Missing non-block meta tensor '{full_name}' in safetensors index.")
331
+ elif tensor_obj.device != self.compute_device:
332
+ _assign_tensor(self.model, full_name, tensor_obj.data.to(self.compute_device), is_param)
333
+
334
+ # Index every repeating block and evict its tensors to 0-element placeholders
335
+ for idx, (blk_prefix, blk) in enumerate(self.blocks):
336
+ blk_entries: List[Tuple[str, bool, MMapTensorLoader, str, Any]] = []
337
+ for rel_name, is_param, tensor_obj in self._iter_module_tensors(blk):
338
+ candidate = f"{blk_prefix}.{rel_name}"
339
+ resolved = self._lookup_key(st_index, candidate)
340
+ if resolved is None:
341
+ raise KeyError(
342
+ f"Missing tensor '{candidate}' in safetensors files {[p.name for p in self.safetensors_paths]}."
343
+ )
344
+ loader, real_key = resolved
345
+ orig_dtype = tensor_obj.dtype
346
+ blk_entries.append((rel_name, is_param, loader, real_key, orig_dtype))
347
+ _assign_tensor(blk, rel_name, torch.empty(0, dtype=orig_dtype, device="cpu"), is_param)
348
+ self._mmap_map[idx] = blk_entries
349
+ self._register_mmap_hooks(idx, blk)
350
+ except Exception:
351
+ for loader in self._loaders:
352
+ loader.close()
353
+ self._loaders.clear()
354
+ raise
355
+
356
+ def _register_mmap_hooks(self, idx: int, blk: Any) -> None:
357
+ import torch
358
+
359
+ def _pre_hook(module: Any, _inputs: Any) -> None:
360
+ target_dev = self._resolve_active_device(_inputs)
361
+ for rel_name, is_param, loader, real_key, orig_dtype in self._mmap_map[idx]:
362
+ loaded = loader.read_torch_tensor(
363
+ real_key,
364
+ device=str(target_dev),
365
+ target_dtype=orig_dtype,
366
+ )
367
+ _assign_tensor(module, rel_name, loaded, is_param)
368
+ self.bytes_streamed += loader.get_tensor_byte_size(real_key)
369
+
370
+ def _post_hook(module: Any, _inputs: Any, _output: Any) -> None:
371
+ for rel_name, is_param, _, _, orig_dtype in self._mmap_map[idx]:
372
+ _assign_tensor(module, rel_name, torch.empty(0, dtype=orig_dtype, device="cpu"), is_param)
373
+ self.blocks_executed += 1
374
+
375
+ self._hooks.append(blk.register_forward_pre_hook(_pre_hook))
376
+ self._hooks.append(blk.register_forward_hook(_post_hook))
377
+
378
+ def detach(self, restore_cpu_weights: bool = True) -> None:
379
+ """Remove all forward hooks, restore CPU shadow weights if applicable, and close mmaps."""
380
+ for h in self._hooks:
381
+ h.remove()
382
+ self._hooks.clear()
383
+ self._prefetch_cache.clear()
384
+
385
+ if restore_cpu_weights and self._cpu_shadow:
386
+ for idx, (_, blk) in enumerate(self.blocks):
387
+ for rel_name, is_param, cpu_t in self._cpu_shadow.get(idx, []):
388
+ _assign_tensor(blk, rel_name, cpu_t, is_param)
389
+
390
+ self._cpu_shadow.clear()
391
+ self._mmap_map.clear()
392
+ for loader in self._loaders:
393
+ loader.close()
394
+ self._loaders.clear()
395
+ self._attached = False
396
+
397
+ def __enter__(self) -> "TorchBlockStreamer":
398
+ return self.attach()
399
+
400
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
401
+ self.detach()
phobos_stream/types.py ADDED
@@ -0,0 +1,79 @@
1
+ """Data models, enums, and schemas for PhobosStream."""
2
+
3
+ from enum import Enum
4
+ from typing import Any, Dict, List, Optional
5
+ from pydantic import BaseModel, Field
6
+
7
+
8
+ class BackendType(str, Enum):
9
+ """Supported execution backends."""
10
+
11
+ AUTO = "auto"
12
+ MLX = "mlx"
13
+ CUDA = "cuda"
14
+ ROCM = "rocm"
15
+ GGUF = "gguf"
16
+ CPU = "cpu"
17
+
18
+
19
+ class ModelArchitecture(str, Enum):
20
+ """Supported Diffusion Transformer architectures."""
21
+
22
+ WAN2_1 = "wan2.1"
23
+ FLUX = "flux"
24
+ HUNYUAN = "hunyuan"
25
+ COGVIDEOX = "cogvideox"
26
+ GENERIC_DIT = "generic_dit"
27
+
28
+
29
+ class QuantPrecision(str, Enum):
30
+ """Supported precision and quantization formats."""
31
+
32
+ FP16 = "fp16"
33
+ BF16 = "bf16"
34
+ FP8_E4M3 = "fp8_e4m3"
35
+ FP8_E5M2 = "fp8_e5m2"
36
+ Q8_0 = "q8_0"
37
+ Q4_K_M = "q4_k_m"
38
+ Q4_0 = "q4_0"
39
+
40
+
41
+ class PipelineStage(str, Enum):
42
+ """Current stage in the generation pipeline."""
43
+
44
+ IDLE = "idle"
45
+ TEXT_ENCODING = "text_encoding"
46
+ LATENT_INIT = "latent_init"
47
+ DENOISING = "denoising"
48
+ VAE_DECODING = "vae_decoding"
49
+ COMPLETED = "completed"
50
+ FAILED = "failed"
51
+
52
+
53
+ class GenerationConfig(BaseModel):
54
+ """Configuration for an image or video generation request."""
55
+
56
+ prompt: str = Field(..., description="Text prompt describing the desired video or image")
57
+ negative_prompt: Optional[str] = Field(default="", description="Negative prompt guidance")
58
+ height: int = Field(default=720, ge=128, le=2160, description="Height in pixels")
59
+ width: int = Field(default=1280, ge=128, le=3840, description="Width in pixels")
60
+ num_frames: int = Field(default=49, ge=1, le=240, description="Number of video frames (1 for image)")
61
+ fps: int = Field(default=24, ge=8, le=60, description="Frames per second for output video")
62
+ steps: int = Field(default=30, ge=1, le=100, description="Diffusion denoising steps")
63
+ guidance_scale: float = Field(default=6.0, ge=1.0, le=20.0, description="CFG guidance scale")
64
+ seed: int = Field(default=42, description="Random seed for reproducible noise")
65
+ block_stream: bool = Field(default=True, description="Enable block-by-block disk streaming")
66
+ precision: QuantPrecision = Field(default=QuantPrecision.BF16, description="Working precision")
67
+
68
+
69
+ class PipelineMetrics(BaseModel):
70
+ """Performance telemetry and telemetry tracking."""
71
+
72
+ total_time_sec: float = 0.0
73
+ text_encode_time_sec: float = 0.0
74
+ denoising_time_sec: float = 0.0
75
+ vae_decode_time_sec: float = 0.0
76
+ peak_vram_mb: float = 0.0
77
+ disk_bytes_read_mb: float = 0.0
78
+ io_throughput_mb_s: float = 0.0
79
+ steps_completed: int = 0
@@ -0,0 +1,154 @@
1
+ Metadata-Version: 2.5
2
+ Name: phobos-stream
3
+ Version: 0.2.0
4
+ Summary: Universal Zero-VRAM Video & Image Diffusion Streaming Engine (MLX • CUDA • MPS • ROCm • GGUF)
5
+ Project-URL: Homepage, https://github.com/martianacademy/phobos-stream
6
+ Project-URL: Repository, https://github.com/martianacademy/phobos-stream
7
+ Project-URL: Issues, https://github.com/martianacademy/phobos-stream/issues
8
+ Author-email: Martian Academy <research@martian.academy>
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: comfyui,diffusion,dit,flux,mlx,mmap,offloading,wan2.1,zero-vram
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: click>=8.1.0
23
+ Requires-Dist: fastapi>=0.115.0
24
+ Requires-Dist: mlx>=0.22.0; sys_platform == 'darwin' and platform_machine == 'arm64'
25
+ Requires-Dist: numpy>=1.26.0
26
+ Requires-Dist: pydantic>=2.8.0
27
+ Requires-Dist: safetensors>=0.4.5
28
+ Requires-Dist: tqdm>=4.66.0
29
+ Requires-Dist: uvicorn>=0.30.0
30
+ Provides-Extra: cuda
31
+ Requires-Dist: torch>=2.4.0; extra == 'cuda'
32
+ Provides-Extra: dev
33
+ Requires-Dist: httpx>=0.27.0; extra == 'dev'
34
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
35
+ Provides-Extra: gguf
36
+ Requires-Dist: gguf>=0.10.0; extra == 'gguf'
37
+ Description-Content-Type: text/markdown
38
+
39
+ # <img src="assets/icon.png" width="42" align="top" alt="PhobosStream Icon" /> PhobosStream
40
+
41
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
42
+ [![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-brightgreen.svg)](https://www.python.org/)
43
+ [![Backends](https://img.shields.io/badge/Backends-MLX%20•%20CUDA%20•%20MPS%20•%20ROCm%20•%20GGUF-purple.svg)]()
44
+ [![Tests Passing](https://img.shields.io/badge/Tests-27%20Passing-success.svg)]()
45
+
46
+ **PhobosStream** is a universal zero-VRAM diffusion streaming engine designed to run massive **12B–20B+ Video and Image Diffusion Transformers (DiTs)** — including **Alibaba Wan2.1 (14B)**, **Black Forest Labs FLUX.1 (12B)**, **Lumina2 / Z-Image-Turbo**, and **Tencent HunyuanVideo (13B)** — on consumer hardware without Out-Of-Memory (OOM) crashes.
47
+
48
+ By combining **3-Stage Sequential Offloading** (`Text Encoder -> DiT -> Tiled VAE`) with **Hook-Based Zero-Copy `mmap` Block-by-Block Streaming** (`TorchBlockStreamer` & `MLXBlockStreamer`), PhobosStream cuts Peak GPU Memory on a real **19.5 GB BF16 pipeline from 26.45 GB down to 1.25–1.60 GB (93.9%–95.3% VRAM reduction)** with **zero quantization quality loss**.
49
+
50
+ ---
51
+
52
+ ## 📊 Verified Empirical Benchmarks (Real 19.5 GB Model Suite)
53
+
54
+ *Measured end-to-end on Apple Silicon Metal GPU across isolated fresh subprocesses (`scripts/benchmark_real_phobos_optimization.py`) using `qwen_3_4b.safetensors` (7.5 GB, 36 layers) + `z_image_turbo_bf16.safetensors` (11.7 GB, 34 blocks) + `ae.safetensors` (320 MB) at `1024 × 1024`, `8 steps`, `seed=42`:*
55
+
56
+ | Execution Mode | Peak Metal GPU Memory | VRAM Saved | Active Resident Weights | Denoising (`Per Step`) | Total Wall Time | Visual Quality |
57
+ | :--- | :---: | :---: | :---: | :---: | :---: | :--- |
58
+ | **1. Monolithic Baseline** *(All 3 in GPU RAM)* | **26,445.0 MB** | `0.0%` | 19,637.5 MB | `36.80 s` (`4.60 s`) | `41.97 s` | Reference BF16 |
59
+ | **2. Phobos 3-Stage Offload (BF16)** | **12,906.4 MB** | **`51.2%`** | 11,742.5 MB | `44.14 s` (`5.52 s`) | `46.99 s` | Lossless BF16 (`32.68 dB` PSNR vs non-strip VAE) |
60
+ | **3. Phobos 3-Stage + Q4 Quantized** | **4,814.7 MB** | **`81.8%`** | 3,310.4 MB | `66.89 s` (`8.36 s`) | `69.72 s` | 4-bit Quantized (`19.25 dB` PSNR) |
61
+ | **4. Phobos Zero-VRAM Block-Stream (Full BF16)** | **1,601.0 MB** *(DiT: **1,248.2 MB**)* | **`93.9%`** *(DiT: **95.3%**)* | **23.2 MB** (`91.6 MB` active) | `71.45 s` (`8.93 s`) | `75.04 s` | **Bit-Exact BF16 (`0.0000 px` diff vs Stage-Offload)** |
62
+
63
+ ### Key Architectural Mechanisms
64
+ 1. **Native BF16/FP16 Zero-Copy `mmap` (`MMapTensorLoader`)**: Slices tensor byte-ranges directly from `.safetensors` on NVMe SSD into native `torch.bfloat16` (`read_torch_tensor`) and `mlx.core.bfloat16` (`read_mlx_array`) without expanding weights to FP32 in host RAM.
65
+ 2. **Hook-Based Per-Block Streaming (`TorchBlockStreamer` & `MLXBlockStreamer`)**:
66
+ - **PyTorch (`CUDA` / `MPS` / `ROCm` / `CPU`)**: Supports `cpu_offload` (read-only pinned CPU shadow + async CUDA prefetch stream, zero GPU→CPU writeback) and `mmap_stream` (zero-RAM `torch.device("meta")` skeleton support + immediate 0-element parameter eviction after each block).
67
+ - **Apple Silicon (`MLX`)**: Enforces `mx.eval` boundaries per transformer block so MLX lazy graphs never accumulate multi-GB block weights simultaneously in unified memory.
68
+ 3. **3-Stage Sequential Offloading & Tiled VAE (`StageSequentialRunner`)**: Isolates Text Encoder, DiT, and spatial-feather-blended Tiled/Strip VAE stages with explicit accelerator cache reclamation between stages, plus single-pass batched Classifier-Free Guidance (cutting disk reads per CFG step by 50%).
69
+
70
+ ---
71
+
72
+ ## 🏛️ System Architecture
73
+
74
+ ```mermaid
75
+ flowchart TD
76
+ subgraph STAGE1["Stage 1: Text Encoding"]
77
+ P["User Prompt"] --> TE["Qwen / T5-XXL / DualCLIP"]
78
+ TE --> EMB["Conditioning Tensor (~2–5 MB)"]
79
+ TE -.->|"Immediate Unload + Cache Flush"| FREE1["Text Encoder Freed"]
80
+ end
81
+
82
+ subgraph STAGE2["Stage 2: Hook-Streamed DiT Denoising"]
83
+ EMB --> DIT["TorchBlockStreamer / MLXBlockStreamer"]
84
+ NVME[("NVMe SSD (.safetensors mmap)")] ==>|"Stream Active Block N (~360 MB)"| BLK["Native DiT Block Forward"]
85
+ BLK -.->|"Eval + Evict Block N to 0 Bytes"| NVME
86
+ BLK --> ODE["Batched CFG + Flow Matching Step"]
87
+ end
88
+
89
+ subgraph STAGE3["Stage 3: Tiled / Strip VAE Reconstruction"]
90
+ ODE --> VAE["Feather-Blended Tiled / Strip VAE"]
91
+ VAE --> OUT["PNG Image / H.264 MP4 Video"]
92
+ end
93
+ ```
94
+
95
+ ---
96
+
97
+ ## ⚡ Quick Start
98
+
99
+ ### 1. Installation
100
+
101
+ ```bash
102
+ git clone https://github.com/martianacademy/phobos-stream.git
103
+ cd phobos-stream
104
+
105
+ uv venv --python 3.12
106
+ source .venv/bin/activate
107
+ uv pip install -e ".[dev]"
108
+ ```
109
+
110
+ ### 2. Run Test Suite (27 Unit & Integration Tests)
111
+
112
+ ```bash
113
+ pytest -v
114
+ ```
115
+
116
+ ### 3. Python API: Hook Any Real PyTorch DiT in 4 Lines
117
+
118
+ ```python
119
+ import torch
120
+ from phobos_stream.streaming import BlockStreamMode, TorchBlockStreamer
121
+
122
+ with torch.device("meta"):
123
+ model = MyDiffusionTransformer().to(torch.bfloat16)
124
+
125
+ with TorchBlockStreamer(
126
+ model,
127
+ compute_device="auto",
128
+ mode=BlockStreamMode.MMAP_STREAM,
129
+ safetensors_paths=["model_bf16.safetensors"],
130
+ ):
131
+ output = model(latents, timestep, context)
132
+ ```
133
+
134
+ ### 4. Launch OpenAI / Sora-Compatible REST & WebSocket API
135
+
136
+ ```bash
137
+ phobos-stream serve --port 8088 --manifest-path shards/manifest.json --backend auto
138
+ ```
139
+
140
+ ---
141
+
142
+ ## 🎨 ComfyUI Custom Node Extension (`ComfyUI-PhobosStream`)
143
+
144
+ **ComfyUI-PhobosStream** is registered in **ComfyUI-Manager** ([standalone repository](https://github.com/martianacademy/ComfyUI-PhobosStream)) and works out-of-the-box with zero unpublished dependencies:
145
+
146
+ * **`🚀 Phobos Zero-VRAM 2K/4K & Video Pipeline`**: 3-stage sequential offloader supporting single & `DualCLIPLoader`, dynamic 4-ch/16-ch 4D image and 5D video latents (`Wan2.1`, `HunyuanVideo`, `FLUX`, `Lumina2`, `SDXL`), `VAEDecodeTiled`, and per-block streaming.
147
+ * **`🔌 PhobosStream Block-Streamer (Any MODEL)`**: Drop-in `MODEL -> MODEL` hook patcher (`cpu_offload` / `mmap_stream`) compatible with standard ComfyUI workflows (LoRAs, ControlNet, WanVideo, FLUX).
148
+ * **`🌌 PhobosStream Model Loader`**, **`⚡ PhobosStream Diffusion Sampler`**, and **`🎞️ PhobosStream Tiled VAE Decoder`**.
149
+
150
+ ---
151
+
152
+ ## 📜 License
153
+
154
+ MIT License — free for commercial and personal use.