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,39 @@
1
+ """Factory to dynamically instantiate the best available compute backend."""
2
+
3
+ import platform
4
+ from phobos_stream.backends.base import BaseBackend
5
+ from phobos_stream.backends.gguf_backend import GGUFBackend
6
+ from phobos_stream.types import BackendType
7
+
8
+
9
+ def get_backend(backend_type: BackendType = BackendType.AUTO, device: str = "auto") -> BaseBackend:
10
+ """Instantiate and return the appropriate execution backend."""
11
+ if backend_type == BackendType.MLX:
12
+ from phobos_stream.backends.mlx_backend import MLXBackend
13
+ return MLXBackend(device="gpu" if device == "auto" else device)
14
+
15
+ if backend_type in (BackendType.CUDA, BackendType.ROCM):
16
+ from phobos_stream.backends.cuda_backend import CUDABackend
17
+ return CUDABackend(device="cuda:0" if device == "auto" else device)
18
+
19
+ if backend_type in (BackendType.GGUF, BackendType.CPU):
20
+ return GGUFBackend(device="cpu" if device == "auto" else device)
21
+
22
+ # AUTO Detection
23
+ if platform.system() == "Darwin" and platform.machine() == "arm64":
24
+ try:
25
+ from phobos_stream.backends.mlx_backend import MLX_AVAILABLE, MLXBackend
26
+ if MLX_AVAILABLE:
27
+ return MLXBackend(device="gpu")
28
+ except Exception:
29
+ pass
30
+
31
+ try:
32
+ import torch
33
+ if torch.cuda.is_available():
34
+ from phobos_stream.backends.cuda_backend import CUDABackend
35
+ return CUDABackend(device="cuda:0")
36
+ except Exception:
37
+ pass
38
+
39
+ return GGUFBackend(device="cpu")
@@ -0,0 +1,176 @@
1
+ """Universal GGUF quantized tensor and CPU fallback backend."""
2
+
3
+ from pathlib import Path
4
+ import platform
5
+ import resource
6
+ from typing import Any, Dict, Optional, Tuple
7
+ import numpy as np
8
+ from phobos_stream.backends.base import BaseBackend
9
+
10
+ try:
11
+ import gguf # type: ignore
12
+ GGUF_AVAILABLE = True
13
+ except ImportError:
14
+ GGUF_AVAILABLE = False
15
+ gguf = None
16
+
17
+
18
+ class GGUFBackend(BaseBackend):
19
+ """CPU and quantized GGUF execution backend."""
20
+
21
+ def __init__(self, device: str = "cpu") -> None:
22
+ super().__init__(device=device)
23
+
24
+ @property
25
+ def name(self) -> str:
26
+ return "gguf"
27
+
28
+ def zeros(self, shape: Tuple[int, ...], dtype: str = "float32") -> Any:
29
+ np_dtype = getattr(np, dtype, np.float32)
30
+ return np.zeros(shape, dtype=np_dtype)
31
+
32
+ def randn(self, shape: Tuple[int, ...], seed: Optional[int] = None, dtype: str = "float32") -> Any:
33
+ rng = np.random.default_rng(seed)
34
+ np_dtype = getattr(np, dtype, np.float32)
35
+ return rng.standard_normal(size=shape).astype(np_dtype)
36
+
37
+ def matmul(self, a: Any, b: Any) -> Any:
38
+ return np.matmul(a, b)
39
+
40
+ def reshape(self, x: Any, shape: Tuple[int, ...]) -> Any:
41
+ return np.reshape(x, shape)
42
+
43
+ def swapaxes(self, x: Any, axis1: int, axis2: int) -> Any:
44
+ return np.swapaxes(x, axis1, axis2)
45
+
46
+ def layer_norm(self, x: Any, weight: Any, bias: Optional[Any] = None, eps: float = 1e-5) -> Any:
47
+ mean = np.mean(x, axis=-1, keepdims=True)
48
+ var = np.var(x, axis=-1, keepdims=True)
49
+ normed = (x - mean) / np.sqrt(var + eps)
50
+ out = normed * weight
51
+ if bias is not None:
52
+ out = out + bias
53
+ return out
54
+
55
+ def silu(self, x: Any) -> Any:
56
+ return x / (1.0 + np.exp(-np.clip(x, -50.0, 50.0)))
57
+
58
+ def scaled_dot_product_attention(
59
+ self,
60
+ q: Any,
61
+ k: Any,
62
+ v: Any,
63
+ scale: Optional[float] = None,
64
+ mask: Optional[Any] = None,
65
+ ) -> Any:
66
+ scale_val = scale if scale is not None else 1.0 / np.sqrt(q.shape[-1])
67
+ seq_q = q.shape[-2]
68
+ k_t = np.swapaxes(k, -1, -2)
69
+
70
+ # Flash-style query chunking for high-resolution (2K/4K) sequences to avoid O(N^2) memory spikes
71
+ chunk_size = 512
72
+ if seq_q > chunk_size and mask is None:
73
+ out = np.empty_like(q)
74
+ for start in range(0, seq_q, chunk_size):
75
+ end = min(start + chunk_size, seq_q)
76
+ q_chunk = q[..., start:end, :]
77
+ scores = np.matmul(q_chunk, k_t) * scale_val
78
+ exp_scores = np.exp(scores - np.max(scores, axis=-1, keepdims=True))
79
+ weights = exp_scores / np.sum(exp_scores, axis=-1, keepdims=True)
80
+ out[..., start:end, :] = np.matmul(weights, v)
81
+ return out
82
+
83
+ scores = np.matmul(q, k_t) * scale_val
84
+ if mask is not None:
85
+ scores = scores + mask
86
+ exp_scores = np.exp(scores - np.max(scores, axis=-1, keepdims=True))
87
+ weights = exp_scores / np.sum(exp_scores, axis=-1, keepdims=True)
88
+ return np.matmul(weights, v)
89
+
90
+ def quantize_q8_0(self, arr: np.ndarray) -> bytes:
91
+ """Quantize float32 tensor into GGUF Q8_0 block format (32 int8 + 1 fp16 scale)."""
92
+ flat = arr.astype(np.float32).ravel()
93
+ pad = (-len(flat)) % 32
94
+ if pad:
95
+ flat = np.pad(flat, (0, pad))
96
+ blocks = flat.reshape(-1, 32)
97
+ amax = np.max(np.abs(blocks), axis=1, keepdims=True)
98
+ d = (amax / 127.0).astype(np.float16)
99
+ d_f32 = d.astype(np.float32)
100
+ inv_d = np.where(d_f32 == 0, 0.0, 1.0 / d_f32)
101
+ qs = np.clip(np.round(blocks * inv_d), -127, 127).astype(np.int8)
102
+
103
+ n_blocks = blocks.shape[0]
104
+ raw = np.empty((n_blocks, 34), dtype=np.uint8)
105
+ raw[:, :2] = d.view(np.uint8).reshape(n_blocks, 2)
106
+ raw[:, 2:] = qs.view(np.uint8)
107
+ return raw.tobytes()
108
+
109
+ def dequantize_q8_0(self, data: bytes, n_elements: int) -> np.ndarray:
110
+ """Vectorized dequantization of Q8_0 block format (32 int8 + 1 f16 scale)."""
111
+ block_size = 34 # 2 bytes fp16 delta + 32 bytes int8
112
+ n_blocks = n_elements // 32
113
+ if n_blocks == 0:
114
+ return np.zeros(n_elements, dtype=np.float32)
115
+
116
+ raw = np.frombuffer(data, dtype=np.uint8, count=n_blocks * block_size).reshape(n_blocks, block_size)
117
+ scales = raw[:, :2].copy().view(np.float16).astype(np.float32) # (n_blocks, 1)
118
+ qs = raw[:, 2:].view(np.int8).astype(np.float32) # (n_blocks, 32)
119
+ return (qs * scales).reshape(-1)[:n_elements]
120
+
121
+ def dequantize_q4_0(self, data: bytes, n_elements: int) -> np.ndarray:
122
+ """Vectorized dequantization of Q4_0 block format (16 packed uint8 + 1 f16 scale)."""
123
+ block_size = 18 # 2 bytes fp16 delta + 16 bytes nibbles (32 x 4-bit)
124
+ n_blocks = n_elements // 32
125
+ if n_blocks == 0:
126
+ return np.zeros(n_elements, dtype=np.float32)
127
+
128
+ raw = np.frombuffer(data, dtype=np.uint8, count=n_blocks * block_size).reshape(n_blocks, block_size)
129
+ scales = raw[:, :2].copy().view(np.float16).astype(np.float32) # (n_blocks, 1)
130
+ nibbles = raw[:, 2:] # (n_blocks, 16)
131
+ low = (nibbles & 0x0F).astype(np.int8) - 8
132
+ high = (nibbles >> 4).astype(np.int8) - 8
133
+ qs = np.concatenate([low, high], axis=1).astype(np.float32)
134
+ return (qs * scales).reshape(-1)[:n_elements]
135
+
136
+ def load_gguf_tensors(self, file_path: Path) -> Dict[str, np.ndarray]:
137
+ """Load and dequantize tensors from a .gguf file when gguf package is available."""
138
+ if not GGUF_AVAILABLE:
139
+ raise RuntimeError("The 'gguf' package is required to read .gguf files.")
140
+ reader = gguf.GGUFReader(str(file_path))
141
+ tensors: Dict[str, np.ndarray] = {}
142
+ for tensor in reader.tensors:
143
+ shape = tuple(int(s) for s in reversed(tensor.shape))
144
+ n_elems = int(np.prod(shape))
145
+ t_type = getattr(tensor.tensor_type, "name", "")
146
+ if t_type == "Q8_0":
147
+ arr = self.dequantize_q8_0(bytes(tensor.data), n_elems).reshape(shape)
148
+ elif t_type == "Q4_0":
149
+ arr = self.dequantize_q4_0(bytes(tensor.data), n_elems).reshape(shape)
150
+ else:
151
+ arr = np.array(tensor.data, dtype=np.float32)
152
+ if arr.size == n_elems:
153
+ arr = arr.reshape(shape)
154
+ tensors[tensor.name] = arr
155
+ return tensors
156
+
157
+ def convert_from_numpy(self, arr: np.ndarray, dtype: Optional[str] = None) -> Any:
158
+ if dtype is not None and hasattr(np, dtype):
159
+ return arr.astype(getattr(np, dtype))
160
+ return np.asarray(arr, dtype=np.float32) if arr.dtype != np.float32 else arr
161
+
162
+ def to_numpy(self, tensor: Any) -> np.ndarray:
163
+ return np.asarray(tensor)
164
+
165
+ def synchronize(self) -> None:
166
+ pass
167
+
168
+ def empty_cache(self) -> None:
169
+ pass
170
+
171
+ def get_memory_allocated_mb(self) -> float:
172
+ """Report current process resident memory in MB."""
173
+ usage = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
174
+ if platform.system() == "Darwin":
175
+ return float(usage) / (1024.0 * 1024.0)
176
+ return float(usage) / 1024.0
@@ -0,0 +1,183 @@
1
+ """Apple Silicon Metal (MLX) backend with mlx_lm optimizations (wired_limit, async_eval, quantized_matmul)."""
2
+
3
+ import contextlib
4
+ from typing import Any, Iterator, Optional, Tuple
5
+ import numpy as np
6
+ from phobos_stream.backends.base import BaseBackend
7
+
8
+ try:
9
+ import mlx.core as mx
10
+ import mlx.core.fast as mxf
11
+ MLX_AVAILABLE = True
12
+ except ImportError:
13
+ MLX_AVAILABLE = False
14
+ mx = None
15
+ mxf = None
16
+
17
+
18
+ class MLXBackend(BaseBackend):
19
+ """High-performance Apple Silicon unified memory backend incorporating mlx_lm primitives."""
20
+
21
+ def __init__(
22
+ self,
23
+ device: str = "gpu",
24
+ quantize_bits: Optional[int] = None,
25
+ quantize_group_size: int = 64,
26
+ ) -> None:
27
+ super().__init__(device=device)
28
+ if not MLX_AVAILABLE:
29
+ raise RuntimeError("MLX is not installed or platform is not Apple Silicon.")
30
+ self.quantize_bits = quantize_bits
31
+ self.quantize_group_size = quantize_group_size
32
+ self.generation_stream = (
33
+ mx.new_thread_local_stream(mx.default_device())
34
+ if hasattr(mx, "new_thread_local_stream")
35
+ else mx.default_stream(mx.default_device())
36
+ )
37
+
38
+ @property
39
+ def name(self) -> str:
40
+ return "mlx"
41
+
42
+ @contextlib.contextmanager
43
+ def wired_limit(self) -> Iterator[None]:
44
+ """Pin Metal working set size using mlx_lm's maybe_set_recommended_wired_limit strategy."""
45
+ old_limit = None
46
+ if hasattr(mx, "device_info") and hasattr(mx, "set_wired_limit"):
47
+ try:
48
+ max_rec = mx.device_info().get("max_recommended_working_set_size")
49
+ if max_rec is not None:
50
+ old_limit = mx.set_wired_limit(max_rec)
51
+ except Exception:
52
+ old_limit = None
53
+ try:
54
+ yield
55
+ finally:
56
+ if old_limit is not None:
57
+ try:
58
+ mx.synchronize(self.generation_stream)
59
+ mx.set_wired_limit(old_limit)
60
+ except Exception:
61
+ pass
62
+
63
+ def async_eval(self, *tensors: Any) -> None:
64
+ """Asynchronously evaluate MLX computation graph without blocking CPU (mlx_lm style)."""
65
+ if hasattr(mx, "async_eval"):
66
+ mx.async_eval(*tensors)
67
+ else:
68
+ mx.eval(*tensors)
69
+
70
+ def zeros(self, shape: Tuple[int, ...], dtype: str = "float32") -> Any:
71
+ mlx_dtype = getattr(mx, dtype, mx.float32)
72
+ return mx.zeros(shape, dtype=mlx_dtype)
73
+
74
+ def randn(self, shape: Tuple[int, ...], seed: Optional[int] = None, dtype: str = "float32") -> Any:
75
+ if seed is not None:
76
+ mx.random.seed(seed)
77
+ mlx_dtype = getattr(mx, dtype, mx.float32)
78
+ return mx.random.normal(shape=shape, dtype=mlx_dtype)
79
+
80
+ def matmul(self, a: Any, b: Any) -> Any:
81
+ return mx.matmul(a, b)
82
+
83
+ def quantize_weight(self, weight: Any, bits: int = 8, group_size: int = 64) -> Tuple[Any, Any, Any]:
84
+ """Pack a 2D weight matrix (out_features, in_features) into MLX quantized format."""
85
+ q_res = mx.quantize(weight, group_size=group_size, bits=bits)
86
+ return (q_res[0], q_res[1], q_res[2])
87
+
88
+ def linear(self, x: Any, weight: Any, bias: Optional[Any] = None) -> Any:
89
+ """Execute linear layer supporting both dense and mlx_lm-style quantized (qweight, scales, biases) tuples/lists."""
90
+ if isinstance(weight, (tuple, list)) and len(weight) == 3:
91
+ qweight, scales, biases = weight
92
+ out = mx.quantized_matmul(
93
+ x,
94
+ qweight,
95
+ scales,
96
+ biases,
97
+ transpose=True,
98
+ group_size=self.quantize_group_size,
99
+ bits=self.quantize_bits or 8,
100
+ )
101
+ if bias is not None:
102
+ out = out + bias
103
+ return out
104
+ return super().linear(x, weight, bias)
105
+
106
+ def reshape(self, x: Any, shape: Tuple[int, ...]) -> Any:
107
+ return mx.reshape(x, shape)
108
+
109
+ def swapaxes(self, x: Any, axis1: int, axis2: int) -> Any:
110
+ return mx.swapaxes(x, axis1, axis2)
111
+
112
+ def layer_norm(self, x: Any, weight: Any, bias: Optional[Any] = None, eps: float = 1e-5) -> Any:
113
+ if hasattr(mxf, "layer_norm"):
114
+ try:
115
+ return mxf.layer_norm(x, weight, bias, eps=eps)
116
+ except Exception:
117
+ pass
118
+ mean = mx.mean(x, axis=-1, keepdims=True)
119
+ var = mx.var(x, axis=-1, keepdims=True)
120
+ normed = (x - mean) / mx.sqrt(var + eps)
121
+ out = normed * weight
122
+ if bias is not None:
123
+ out = out + bias
124
+ return out
125
+
126
+ def silu(self, x: Any) -> Any:
127
+ return x * mx.sigmoid(x)
128
+
129
+ def scaled_dot_product_attention(
130
+ self,
131
+ q: Any,
132
+ k: Any,
133
+ v: Any,
134
+ scale: Optional[float] = None,
135
+ mask: Optional[Any] = None,
136
+ ) -> Any:
137
+ scale_val = scale if scale is not None else 1.0 / (q.shape[-1] ** 0.5)
138
+ if q.ndim == 4 and hasattr(mxf, "scaled_dot_product_attention"):
139
+ try:
140
+ return mxf.scaled_dot_product_attention(q, k, v, scale=scale_val, mask=mask)
141
+ except Exception:
142
+ pass
143
+ scores = mx.matmul(q, mx.swapaxes(k, -1, -2)) * scale_val
144
+ if mask is not None:
145
+ scores = scores + mask
146
+ weights = mx.softmax(scores, axis=-1)
147
+ return mx.matmul(weights, v)
148
+
149
+ def convert_from_numpy(self, arr: np.ndarray, dtype: Optional[str] = None) -> Any:
150
+ if not arr.flags["C_CONTIGUOUS"]:
151
+ arr = np.ascontiguousarray(arr)
152
+ mlx_arr = mx.array(arr)
153
+ if dtype is not None and hasattr(mx, dtype):
154
+ mlx_arr = mlx_arr.astype(getattr(mx, dtype))
155
+ if (
156
+ self.quantize_bits in (4, 8)
157
+ and mlx_arr.ndim == 2
158
+ and mlx_arr.shape[-1] % self.quantize_group_size == 0
159
+ ):
160
+ return self.quantize_weight(mlx_arr, bits=self.quantize_bits, group_size=self.quantize_group_size)
161
+ return mlx_arr
162
+
163
+ def to_numpy(self, tensor: Any) -> np.ndarray:
164
+ mx.eval(tensor)
165
+ if tensor.dtype == mx.bfloat16:
166
+ tensor = tensor.astype(mx.float32)
167
+ return np.array(tensor)
168
+
169
+ def synchronize(self) -> None:
170
+ mx.eval()
171
+
172
+ def empty_cache(self) -> None:
173
+ if hasattr(mx, "clear_cache"):
174
+ mx.clear_cache()
175
+ elif hasattr(mx, "metal") and hasattr(mx.metal, "clear_cache"):
176
+ mx.metal.clear_cache()
177
+
178
+ def get_memory_allocated_mb(self) -> float:
179
+ if hasattr(mx, "get_active_memory"):
180
+ return float(mx.get_active_memory()) / (1024.0 * 1024.0)
181
+ elif hasattr(mx, "metal") and hasattr(mx.metal, "get_active_memory"):
182
+ return float(mx.metal.get_active_memory()) / (1024.0 * 1024.0)
183
+ return 0.0
phobos_stream/cli.py ADDED
@@ -0,0 +1,184 @@
1
+ """Command Line Interface (CLI) for PhobosStream."""
2
+
3
+ from pathlib import Path
4
+ from typing import Optional
5
+ import click
6
+ import uvicorn
7
+
8
+ from phobos_stream.media import save_rgb_mp4, save_rgb_png
9
+ from phobos_stream.pipeline.stream_engine import PhobosStreamEngine
10
+ from phobos_stream.server.app import create_app
11
+ from phobos_stream.storage.layout import ModelShardsManifest
12
+ from phobos_stream.storage.sharder import DiffusionSharder
13
+ from phobos_stream.types import BackendType, GenerationConfig
14
+
15
+
16
+ @click.group()
17
+ def main() -> None:
18
+ """PhobosStream: Universal Zero-VRAM Video & Image Diffusion Streaming Engine."""
19
+ pass
20
+
21
+
22
+ @main.command()
23
+ @click.option("--host", default="0.0.0.0", help="Host interface to bind")
24
+ @click.option("--port", default=8088, type=int, help="Port to listen on")
25
+ @click.option("--manifest-path", default=None, type=click.Path(exists=True), help="Path to manifest.json")
26
+ @click.option("--backend", default="auto", type=click.Choice(["auto", "mlx", "cuda", "gguf", "cpu"]))
27
+ @click.option("--allow-synthetic", is_flag=True, default=False, help="Allow synthetic benchmark weights when no manifest is set")
28
+ def serve(
29
+ host: str,
30
+ port: int,
31
+ manifest_path: Optional[str],
32
+ backend: str,
33
+ allow_synthetic: bool,
34
+ ) -> None:
35
+ """Launch the OpenAI/Sora-compatible HTTP & WebSocket API Gateway."""
36
+ manifest = ModelShardsManifest.load(Path(manifest_path)) if manifest_path else None
37
+ backend_type = BackendType(backend)
38
+ app = create_app(manifest=manifest, backend_type=backend_type, allow_synthetic=allow_synthetic)
39
+ click.echo(f"[*] Starting PhobosStream Gateway on http://{host}:{port} [Backend: {backend}]")
40
+ uvicorn.run(app, host=host, port=port)
41
+
42
+
43
+ @main.command()
44
+ @click.option("--prompt", required=True, help="Text description of the desired video or image")
45
+ @click.option("--negative-prompt", default="", help="Negative prompt for guidance")
46
+ @click.option("--video/--image", default=True, help="Generate video (default) or image")
47
+ @click.option("--height", default=480, type=int, help="Output height in pixels")
48
+ @click.option("--width", default=720, type=int, help="Output width in pixels")
49
+ @click.option("--frames", default=17, type=int, help="Number of video frames when --video is set")
50
+ @click.option("--fps", default=24, type=int, help="Video frame rate when --video is set")
51
+ @click.option("--steps", default=20, type=int, help="Denoising steps")
52
+ @click.option("--guidance-scale", default=6.0, type=float, help="Classifier-free guidance scale")
53
+ @click.option("--manifest-path", default=None, type=click.Path(exists=True), help="Path to shard manifest.json")
54
+ @click.option("--allow-synthetic", is_flag=True, default=False, help="Explicitly run synthetic benchmark mode without real weights")
55
+ @click.option("--output", "-o", default="outputs/generated.mp4", help="Output file path (.mp4 or .png)")
56
+ @click.option("--backend", default="auto", type=click.Choice(["auto", "mlx", "cuda", "gguf", "cpu"]))
57
+ def generate(
58
+ prompt: str,
59
+ negative_prompt: str,
60
+ video: bool,
61
+ height: int,
62
+ width: int,
63
+ frames: int,
64
+ fps: int,
65
+ steps: int,
66
+ guidance_scale: float,
67
+ manifest_path: Optional[str],
68
+ allow_synthetic: bool,
69
+ output: str,
70
+ backend: str,
71
+ ) -> None:
72
+ """Generate a video or image via zero-VRAM streaming and save to disk."""
73
+ if manifest_path:
74
+ manifest = ModelShardsManifest.load(Path(manifest_path))
75
+ if allow_synthetic:
76
+ manifest.allow_synthetic = True
77
+ elif allow_synthetic:
78
+ manifest = ModelShardsManifest(
79
+ model_name="wan2.1-synthetic-benchmark",
80
+ architecture="wan2.1",
81
+ num_blocks=4,
82
+ hidden_size=2048,
83
+ allow_synthetic=True,
84
+ )
85
+ else:
86
+ raise click.UsageError(
87
+ "Real generation requires `--manifest-path <path/to/manifest.json>` (or use ComfyUI / "
88
+ "`StageSequentialRunner`). Pass `--allow-synthetic` only for synthetic benchmarking."
89
+ )
90
+
91
+ engine = PhobosStreamEngine(manifest=manifest, backend_type=BackendType(backend))
92
+ config = GenerationConfig(
93
+ prompt=prompt,
94
+ negative_prompt=negative_prompt,
95
+ height=height,
96
+ width=width,
97
+ num_frames=frames if video else 1,
98
+ fps=fps,
99
+ steps=steps,
100
+ guidance_scale=guidance_scale,
101
+ )
102
+ click.echo(f"[*] Generating {'Video' if video else 'Image'} with PhobosStream...")
103
+ rgb_frames, metrics = engine.generate(
104
+ config,
105
+ progress_callback=lambda step, total, stage: click.echo(f"[{stage}] Step {step}/{total}"),
106
+ )
107
+
108
+ out_path = Path(output)
109
+ out_path.parent.mkdir(parents=True, exist_ok=True)
110
+ if video and rgb_frames.shape[0] > 1:
111
+ mp4_path = save_rgb_mp4(rgb_frames, out_path.with_suffix(".mp4"), fps=fps)
112
+ preview_path = save_rgb_png(rgb_frames[0], out_path.with_suffix(".png"))
113
+ click.echo(f"[+] Saved MP4 video {rgb_frames.shape} to {mp4_path} and preview to {preview_path}")
114
+ else:
115
+ png_path = save_rgb_png(rgb_frames[0], out_path.with_suffix(".png"))
116
+ click.echo(f"[+] Saved PNG image {rgb_frames[0].shape} to {png_path}")
117
+
118
+ click.echo(f"[+] Generation Completed in {metrics.total_time_sec:.2f}s!")
119
+ click.echo(f"[+] Peak Memory: {metrics.peak_vram_mb:.1f} MB | I/O Speed: {metrics.io_throughput_mb_s:.1f} MB/s")
120
+
121
+
122
+ @main.command()
123
+ @click.option("--model-dir", required=True, type=click.Path(exists=True), help="Directory or .safetensors file")
124
+ @click.option("--output-dir", default=None, type=click.Path(), help="Output directory for shards and manifest.json")
125
+ @click.option("--architecture", default="wan2.1", help="Model architecture (wan2.1, flux, hunyuan, cogvideox)")
126
+ @click.option("--hidden-size", default=4096, type=int, help="Transformer hidden dimension")
127
+ @click.option("--partition/--virtual", default=False, help="Physically split block files or write virtual manifest")
128
+ def shard(
129
+ model_dir: str,
130
+ output_dir: Optional[str],
131
+ architecture: str,
132
+ hidden_size: int,
133
+ partition: bool,
134
+ ) -> None:
135
+ """Index or physically shard safetensors weights for zero-copy block streaming."""
136
+ model_path = Path(model_dir)
137
+ out_path = (
138
+ Path(output_dir)
139
+ if output_dir
140
+ else (model_path.parent / "shards" if model_path.is_file() else model_path / "shards")
141
+ )
142
+ sharder = DiffusionSharder(model_dir=model_path, output_dir=out_path)
143
+ manifest = sharder.build_virtual_manifest(architecture=architecture, hidden_size=hidden_size)
144
+ if partition:
145
+ manifest_file = sharder.partition_to_disk(manifest)
146
+ else:
147
+ out_path.mkdir(parents=True, exist_ok=True)
148
+ manifest_file = out_path / "manifest.json"
149
+ manifest.save(manifest_file)
150
+ click.echo(f"[+] Indexed {manifest.num_blocks} blocks -> {manifest_file}")
151
+
152
+
153
+ @main.command()
154
+ @click.option("--steps", default=10, type=int, help="Benchmark denoising steps")
155
+ @click.option("--blocks", default=8, type=int, help="Simulated transformer blocks")
156
+ @click.option("--backend", default="auto", type=click.Choice(["auto", "mlx", "cuda", "gguf", "cpu"]))
157
+ def benchmark(steps: int, blocks: int, backend: str) -> None:
158
+ """Run an end-to-end synthetic streaming benchmark."""
159
+ manifest = ModelShardsManifest(
160
+ model_name="synthetic-dit",
161
+ architecture="wan2.1",
162
+ num_blocks=blocks,
163
+ hidden_size=2048,
164
+ allow_synthetic=True,
165
+ )
166
+ engine = PhobosStreamEngine(manifest=manifest, backend_type=BackendType(backend))
167
+ config = GenerationConfig(
168
+ prompt="A robotic cheetah sprinting through futuristic neon Tokyo at sunset",
169
+ num_frames=25,
170
+ steps=steps,
171
+ )
172
+ click.echo(f"[*] Running PhobosStream Synthetic Benchmark on backend [{engine.backend.name}]...")
173
+ rgb_frames, metrics = engine.generate(config)
174
+ click.echo("=" * 60)
175
+ click.echo(f"Output Shape: {rgb_frames.shape} (uint8 RGB)")
176
+ click.echo(f"Total Latency: {metrics.total_time_sec:.3f} s")
177
+ click.echo(f"Denoising Latency: {metrics.denoising_time_sec:.3f} s ({metrics.denoising_time_sec / steps:.3f} s/step)")
178
+ click.echo(f"Peak VRAM/RAM: {metrics.peak_vram_mb:.2f} MB")
179
+ click.echo(f"I/O Throughput: {metrics.io_throughput_mb_s:.2f} MB/s")
180
+ click.echo("=" * 60)
181
+
182
+
183
+ if __name__ == "__main__":
184
+ main()
@@ -0,0 +1 @@
1
+ """Third-party ecosystem integrations (ComfyUI, WebUI, Diffusers)."""
@@ -0,0 +1,35 @@
1
+ """ComfyUI Node Mappings for PhobosStream."""
2
+
3
+ from phobos_stream.integrations.comfyui.nodes import (
4
+ PhobosBlockStreamPatcherNode,
5
+ PhobosStageOffloadPipelineNode,
6
+ PhobosStreamLoaderNode,
7
+ PhobosStreamSamplerNode,
8
+ PhobosStreamVAEDecodeNode,
9
+ )
10
+
11
+ NODE_CLASS_MAPPINGS = {
12
+ "PhobosStreamLoader": PhobosStreamLoaderNode,
13
+ "PhobosBlockStreamPatcher": PhobosBlockStreamPatcherNode,
14
+ "PhobosStreamSampler": PhobosStreamSamplerNode,
15
+ "PhobosStreamVAEDecode": PhobosStreamVAEDecodeNode,
16
+ "PhobosStageOffloadPipeline": PhobosStageOffloadPipelineNode,
17
+ }
18
+
19
+ NODE_DISPLAY_NAME_MAPPINGS = {
20
+ "PhobosStreamLoader": "🌌 PhobosStream Model Loader (Zero-VRAM)",
21
+ "PhobosBlockStreamPatcher": "🔌 PhobosStream Block-Streamer (Any MODEL)",
22
+ "PhobosStreamSampler": "⚡ PhobosStream Diffusion Sampler (Stage-Offload)",
23
+ "PhobosStreamVAEDecode": "🎞️ PhobosStream Tiled VAE Decoder",
24
+ "PhobosStageOffloadPipeline": "🚀 Phobos Zero-VRAM 2K/4K & Video Pipeline",
25
+ }
26
+
27
+ __all__ = [
28
+ "NODE_CLASS_MAPPINGS",
29
+ "NODE_DISPLAY_NAME_MAPPINGS",
30
+ "PhobosBlockStreamPatcherNode",
31
+ "PhobosStageOffloadPipelineNode",
32
+ "PhobosStreamLoaderNode",
33
+ "PhobosStreamSamplerNode",
34
+ "PhobosStreamVAEDecodeNode",
35
+ ]