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.
- phobos_stream/__init__.py +24 -0
- phobos_stream/adapters/__init__.py +17 -0
- phobos_stream/adapters/base.py +96 -0
- phobos_stream/adapters/cogvideo_adapter.py +55 -0
- phobos_stream/adapters/factory.py +27 -0
- phobos_stream/adapters/flux_adapter.py +78 -0
- phobos_stream/adapters/hunyuan_adapter.py +56 -0
- phobos_stream/adapters/wan_adapter.py +82 -0
- phobos_stream/backends/__init__.py +7 -0
- phobos_stream/backends/base.py +138 -0
- phobos_stream/backends/cuda_backend.py +86 -0
- phobos_stream/backends/factory.py +39 -0
- phobos_stream/backends/gguf_backend.py +176 -0
- phobos_stream/backends/mlx_backend.py +183 -0
- phobos_stream/cli.py +184 -0
- phobos_stream/integrations/__init__.py +1 -0
- phobos_stream/integrations/comfyui/__init__.py +35 -0
- phobos_stream/integrations/comfyui/comfy_runtime.py +336 -0
- phobos_stream/integrations/comfyui/nodes.py +429 -0
- phobos_stream/media/__init__.py +5 -0
- phobos_stream/media/video_writer.py +145 -0
- phobos_stream/models/__init__.py +14 -0
- phobos_stream/models/attention.py +90 -0
- phobos_stream/models/dit_block.py +109 -0
- phobos_stream/models/rotary.py +81 -0
- phobos_stream/pipeline/__init__.py +7 -0
- phobos_stream/pipeline/offloader.py +233 -0
- phobos_stream/pipeline/scheduler.py +32 -0
- phobos_stream/pipeline/stage_runner.py +197 -0
- phobos_stream/pipeline/stream_engine.py +144 -0
- phobos_stream/pipelines/__init__.py +8 -0
- phobos_stream/pipelines/mlx_zimage.py +347 -0
- phobos_stream/pipelines/mlx_zimage_blocks.py +235 -0
- phobos_stream/pipelines/mlx_zimage_vae.py +98 -0
- phobos_stream/server/__init__.py +17 -0
- phobos_stream/server/app.py +192 -0
- phobos_stream/server/schemas.py +55 -0
- phobos_stream/server/ws_progress.py +36 -0
- phobos_stream/storage/__init__.py +7 -0
- phobos_stream/storage/layout.py +105 -0
- phobos_stream/storage/mmap_loader.py +194 -0
- phobos_stream/storage/sharder.py +137 -0
- phobos_stream/streaming/__init__.py +15 -0
- phobos_stream/streaming/mlx_block_streamer.py +159 -0
- phobos_stream/streaming/torch_block_streamer.py +401 -0
- phobos_stream/types.py +79 -0
- phobos_stream-0.2.0.dist-info/METADATA +154 -0
- phobos_stream-0.2.0.dist-info/RECORD +51 -0
- phobos_stream-0.2.0.dist-info/WHEEL +4 -0
- phobos_stream-0.2.0.dist-info/entry_points.txt +2 -0
- phobos_stream-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
"""ComfyUI runtime bridge: 3-stage sequential offloading, dynamic 4D/5D latents, DualCLIP, and block streaming."""
|
|
2
|
+
|
|
3
|
+
import gc
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from phobos_stream.streaming import BlockStreamMode, TorchBlockStreamer
|
|
10
|
+
|
|
11
|
+
try:
|
|
12
|
+
import torch
|
|
13
|
+
|
|
14
|
+
TORCH_AVAILABLE = True
|
|
15
|
+
except ImportError:
|
|
16
|
+
TORCH_AVAILABLE = False
|
|
17
|
+
torch = None # type: ignore
|
|
18
|
+
|
|
19
|
+
COMFY_NATIVE_AVAILABLE = False
|
|
20
|
+
try:
|
|
21
|
+
import folder_paths # type: ignore
|
|
22
|
+
import comfy.model_management as comfy_mm # type: ignore
|
|
23
|
+
import nodes as comfy_nodes # type: ignore
|
|
24
|
+
|
|
25
|
+
# Optional user-configured shared model folder via environment variable (no hardcoded personal paths)
|
|
26
|
+
_extra_models_env = os.environ.get("PHOBOS_EXTRA_MODELS_DIR", "").strip()
|
|
27
|
+
if _extra_models_env:
|
|
28
|
+
_extra_root = Path(_extra_models_env).expanduser()
|
|
29
|
+
if _extra_root.exists():
|
|
30
|
+
for _cat in ("diffusion_models", "text_encoders", "vae", "checkpoints", "loras"):
|
|
31
|
+
_cat_dir = _extra_root / _cat
|
|
32
|
+
if _cat_dir.exists():
|
|
33
|
+
folder_paths.add_model_folder_path(_cat, str(_cat_dir))
|
|
34
|
+
COMFY_NATIVE_AVAILABLE = True
|
|
35
|
+
except Exception:
|
|
36
|
+
folder_paths = None
|
|
37
|
+
comfy_mm = None
|
|
38
|
+
comfy_nodes = None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
DUAL_CLIP_TYPES = {
|
|
42
|
+
"flux",
|
|
43
|
+
"sd3",
|
|
44
|
+
"sdxl",
|
|
45
|
+
"hunyuan_video",
|
|
46
|
+
"hunyuan_image",
|
|
47
|
+
"hunyuan_video_15",
|
|
48
|
+
"hidream",
|
|
49
|
+
"ltxv",
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def free_comfy_memory() -> None:
|
|
54
|
+
"""Unload all active ComfyUI models and flush CUDA/MPS/MLX/CPU caches between stages."""
|
|
55
|
+
if COMFY_NATIVE_AVAILABLE and comfy_mm is not None:
|
|
56
|
+
try:
|
|
57
|
+
comfy_mm.unload_all_models()
|
|
58
|
+
comfy_mm.soft_empty_cache()
|
|
59
|
+
except Exception:
|
|
60
|
+
pass
|
|
61
|
+
gc.collect()
|
|
62
|
+
if TORCH_AVAILABLE and torch is not None:
|
|
63
|
+
if hasattr(torch, "backends") and hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
|
|
64
|
+
try:
|
|
65
|
+
torch.mps.empty_cache()
|
|
66
|
+
except Exception:
|
|
67
|
+
pass
|
|
68
|
+
elif torch.cuda.is_available():
|
|
69
|
+
torch.cuda.empty_cache()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def get_comfy_filenames(category: str, fallback: List[str]) -> List[str]:
|
|
73
|
+
"""Query ComfyUI `folder_paths` safely with a deterministic fallback list."""
|
|
74
|
+
if COMFY_NATIVE_AVAILABLE and folder_paths is not None:
|
|
75
|
+
try:
|
|
76
|
+
found = folder_paths.get_filename_list(category)
|
|
77
|
+
if found:
|
|
78
|
+
return list(found)
|
|
79
|
+
except Exception:
|
|
80
|
+
pass
|
|
81
|
+
return list(fallback)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def to_comfy_image_tensor(rgb_frames: Any) -> Any:
|
|
85
|
+
"""Normalize `(T, H, W, 3)` or 5D `(B, T, H, W, 3)` output into ComfyUI 4D float32 `[0, 1]` IMAGE."""
|
|
86
|
+
if TORCH_AVAILABLE and torch is not None and isinstance(rgb_frames, torch.Tensor):
|
|
87
|
+
t = rgb_frames
|
|
88
|
+
if t.ndim == 5:
|
|
89
|
+
b, f, h, w, c = t.shape
|
|
90
|
+
t = t.reshape(b * f, h, w, c)
|
|
91
|
+
elif t.ndim == 3:
|
|
92
|
+
t = t.unsqueeze(0)
|
|
93
|
+
return t.float()
|
|
94
|
+
|
|
95
|
+
arr = np.asarray(rgb_frames)
|
|
96
|
+
if arr.dtype == np.uint8:
|
|
97
|
+
img_np = arr.astype(np.float32) / 255.0
|
|
98
|
+
else:
|
|
99
|
+
img_np = np.clip(arr.astype(np.float32), 0.0, 1.0)
|
|
100
|
+
|
|
101
|
+
if img_np.ndim == 5:
|
|
102
|
+
b, f, h, w, c = img_np.shape
|
|
103
|
+
img_np = img_np.reshape(b * f, h, w, c)
|
|
104
|
+
elif img_np.ndim == 3:
|
|
105
|
+
img_np = np.expand_dims(img_np, axis=0)
|
|
106
|
+
elif img_np.ndim == 2:
|
|
107
|
+
img_np = np.repeat(img_np[None, :, :, None], 3, axis=-1)
|
|
108
|
+
|
|
109
|
+
if TORCH_AVAILABLE and torch is not None:
|
|
110
|
+
return torch.from_numpy(img_np)
|
|
111
|
+
return img_np
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def build_empty_comfy_latent(
|
|
115
|
+
active_model: Any,
|
|
116
|
+
width: int,
|
|
117
|
+
height: int,
|
|
118
|
+
num_frames: int = 1,
|
|
119
|
+
batch_size: int = 1,
|
|
120
|
+
) -> Dict[str, Any]:
|
|
121
|
+
"""Build an exact 4D image or 5D video latent dict matching `active_model`'s `latent_format`."""
|
|
122
|
+
if not TORCH_AVAILABLE or torch is None:
|
|
123
|
+
raise RuntimeError("PyTorch is required to allocate ComfyUI latent tensors.")
|
|
124
|
+
|
|
125
|
+
latent_fmt = None
|
|
126
|
+
if hasattr(active_model, "get_model_object"):
|
|
127
|
+
try:
|
|
128
|
+
latent_fmt = active_model.get_model_object("latent_format")
|
|
129
|
+
except Exception:
|
|
130
|
+
latent_fmt = None
|
|
131
|
+
|
|
132
|
+
channels = int(getattr(latent_fmt, "latent_channels", 16))
|
|
133
|
+
latent_dims = int(getattr(latent_fmt, "latent_dimensions", 3 if num_frames > 1 else 2))
|
|
134
|
+
sp_ratio = int(getattr(latent_fmt, "spacial_downscale_ratio", 8))
|
|
135
|
+
tp_ratio = int(getattr(latent_fmt, "temporal_downscale_ratio", 4 if latent_dims == 3 else 1))
|
|
136
|
+
|
|
137
|
+
h_lat = max(1, int(height) // max(1, sp_ratio))
|
|
138
|
+
w_lat = max(1, int(width) // max(1, sp_ratio))
|
|
139
|
+
|
|
140
|
+
if latent_dims == 3 or int(num_frames) > 1:
|
|
141
|
+
t_lat = max(1, (max(1, int(num_frames)) - 1) // max(1, tp_ratio) + 1)
|
|
142
|
+
samples = torch.zeros([batch_size, channels, t_lat, h_lat, w_lat], device="cpu", dtype=torch.float32)
|
|
143
|
+
else:
|
|
144
|
+
samples = torch.zeros([batch_size, channels, h_lat, w_lat], device="cpu", dtype=torch.float32)
|
|
145
|
+
|
|
146
|
+
return {"samples": samples, "downscale_ratio_spacial": sp_ratio}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def load_comfy_clip(clip_name: str, clip_type: str, clip_name2: str = "") -> Any:
|
|
150
|
+
"""Load single CLIP/T5/Qwen via `CLIPLoader` or dual encoders via `DualCLIPLoader`."""
|
|
151
|
+
if not COMFY_NATIVE_AVAILABLE or comfy_nodes is None:
|
|
152
|
+
raise RuntimeError("ComfyUI runtime is not loaded.")
|
|
153
|
+
|
|
154
|
+
second = (clip_name2 or "").strip()
|
|
155
|
+
if second and second != "none" and hasattr(comfy_nodes, "DualCLIPLoader"):
|
|
156
|
+
dual_type = clip_type if clip_type in DUAL_CLIP_TYPES else "flux"
|
|
157
|
+
clip, = comfy_nodes.DualCLIPLoader().load_clip(clip_name, second, dual_type)
|
|
158
|
+
return clip
|
|
159
|
+
|
|
160
|
+
clip, = comfy_nodes.CLIPLoader().load_clip(clip_name, clip_type)
|
|
161
|
+
return clip
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def decode_comfy_vae_smart(
|
|
165
|
+
vae: Any,
|
|
166
|
+
sampled_latent: Dict[str, Any],
|
|
167
|
+
use_tiled_vae: bool = True,
|
|
168
|
+
tile_size: int = 512,
|
|
169
|
+
overlap: int = 64,
|
|
170
|
+
) -> Any:
|
|
171
|
+
"""Decode ComfyUI latents using tiled VAE when beneficial to avoid 2K/4K/Video OOMs."""
|
|
172
|
+
if not COMFY_NATIVE_AVAILABLE or comfy_nodes is None:
|
|
173
|
+
raise RuntimeError("ComfyUI runtime is not loaded.")
|
|
174
|
+
|
|
175
|
+
samples = sampled_latent.get("samples")
|
|
176
|
+
is_large_or_video = False
|
|
177
|
+
if samples is not None and hasattr(samples, "shape"):
|
|
178
|
+
is_large_or_video = len(samples.shape) == 5 or max(int(samples.shape[-1]), int(samples.shape[-2])) >= 192
|
|
179
|
+
|
|
180
|
+
if (use_tiled_vae or is_large_or_video) and hasattr(comfy_nodes, "VAEDecodeTiled"):
|
|
181
|
+
try:
|
|
182
|
+
decoded, = comfy_nodes.VAEDecodeTiled().decode(
|
|
183
|
+
vae=vae,
|
|
184
|
+
samples=sampled_latent,
|
|
185
|
+
tile_size=tile_size,
|
|
186
|
+
overlap=overlap,
|
|
187
|
+
temporal_size=64,
|
|
188
|
+
temporal_overlap=8,
|
|
189
|
+
)
|
|
190
|
+
return to_comfy_image_tensor(decoded)
|
|
191
|
+
except Exception:
|
|
192
|
+
pass
|
|
193
|
+
|
|
194
|
+
decoded, = comfy_nodes.VAEDecode().decode(vae, sampled_latent)
|
|
195
|
+
return to_comfy_image_tensor(decoded)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def attach_streamer_to_comfy_model(
|
|
199
|
+
comfy_model: Any,
|
|
200
|
+
block_stream_mode: str = "cpu_offload",
|
|
201
|
+
unet_name: str = "",
|
|
202
|
+
) -> Optional[TorchBlockStreamer]:
|
|
203
|
+
"""Attach `TorchBlockStreamer` onto a ComfyUI `ModelPatcher`'s underlying `diffusion_model`."""
|
|
204
|
+
mode = BlockStreamMode(block_stream_mode)
|
|
205
|
+
if mode == BlockStreamMode.STAGE_ONLY:
|
|
206
|
+
return None
|
|
207
|
+
|
|
208
|
+
diff_mod = None
|
|
209
|
+
if hasattr(comfy_model, "get_model_object"):
|
|
210
|
+
try:
|
|
211
|
+
diff_mod = comfy_model.get_model_object("diffusion_model")
|
|
212
|
+
except Exception:
|
|
213
|
+
diff_mod = None
|
|
214
|
+
if diff_mod is None and hasattr(comfy_model, "model"):
|
|
215
|
+
diff_mod = getattr(comfy_model.model, "diffusion_model", comfy_model.model)
|
|
216
|
+
if diff_mod is None:
|
|
217
|
+
diff_mod = comfy_model
|
|
218
|
+
|
|
219
|
+
st_paths: List[Path] = []
|
|
220
|
+
if mode == BlockStreamMode.MMAP_STREAM:
|
|
221
|
+
if unet_name and Path(unet_name).exists():
|
|
222
|
+
st_paths.append(Path(unet_name))
|
|
223
|
+
elif unet_name and COMFY_NATIVE_AVAILABLE and folder_paths is not None:
|
|
224
|
+
resolved = folder_paths.get_full_path("diffusion_models", unet_name)
|
|
225
|
+
if resolved:
|
|
226
|
+
st_paths.append(Path(resolved))
|
|
227
|
+
|
|
228
|
+
streamer = TorchBlockStreamer(
|
|
229
|
+
model=diff_mod,
|
|
230
|
+
compute_device="auto",
|
|
231
|
+
mode=mode,
|
|
232
|
+
safetensors_paths=st_paths,
|
|
233
|
+
)
|
|
234
|
+
streamer.attach()
|
|
235
|
+
return streamer
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def run_comfy_stage_offloaded_pipeline(
|
|
239
|
+
unet_name: str,
|
|
240
|
+
clip_name: str,
|
|
241
|
+
clip_type: str,
|
|
242
|
+
vae_name: str,
|
|
243
|
+
prompt: str,
|
|
244
|
+
negative_prompt: str,
|
|
245
|
+
width: int,
|
|
246
|
+
height: int,
|
|
247
|
+
steps: int,
|
|
248
|
+
cfg: float,
|
|
249
|
+
seed: int,
|
|
250
|
+
num_frames: int = 1,
|
|
251
|
+
sampler_name: str = "res_multistep",
|
|
252
|
+
scheduler: str = "simple",
|
|
253
|
+
aura_shift: float = 3.0,
|
|
254
|
+
clip_name2: str = "",
|
|
255
|
+
weight_dtype: str = "default",
|
|
256
|
+
block_stream_mode: str = "stage_only",
|
|
257
|
+
use_tiled_vae: bool = True,
|
|
258
|
+
) -> Tuple[Any, Dict[str, Any]]:
|
|
259
|
+
"""Execute strict 3-stage sequential offloading in ComfyUI (`Text -> DiT -> VAE`)."""
|
|
260
|
+
if not COMFY_NATIVE_AVAILABLE or comfy_nodes is None:
|
|
261
|
+
raise RuntimeError("ComfyUI runtime is not loaded.")
|
|
262
|
+
|
|
263
|
+
free_comfy_memory()
|
|
264
|
+
|
|
265
|
+
# Stage 1: Load Text Encoder(s), encode conditioning, and immediately unload
|
|
266
|
+
clip = load_comfy_clip(clip_name=clip_name, clip_type=clip_type, clip_name2=clip_name2)
|
|
267
|
+
positive, = comfy_nodes.CLIPTextEncode().encode(clip, prompt)
|
|
268
|
+
if negative_prompt and negative_prompt.strip() and cfg > 1.0:
|
|
269
|
+
negative, = comfy_nodes.CLIPTextEncode().encode(clip, negative_prompt)
|
|
270
|
+
else:
|
|
271
|
+
negative, = comfy_nodes.ConditioningZeroOut().zero_out(positive)
|
|
272
|
+
del clip
|
|
273
|
+
free_comfy_memory()
|
|
274
|
+
|
|
275
|
+
# Stage 2: Load Diffusion Transformer / UNet, optionally attach block streamer, sample, unload
|
|
276
|
+
model, = comfy_nodes.UNETLoader().load_unet(unet_name, weight_dtype)
|
|
277
|
+
if aura_shift > 0:
|
|
278
|
+
try:
|
|
279
|
+
from comfy_extras.nodes_model_advanced import ModelSamplingAuraFlow # type: ignore
|
|
280
|
+
|
|
281
|
+
active_model, = ModelSamplingAuraFlow().patch_aura(model, aura_shift)
|
|
282
|
+
except Exception:
|
|
283
|
+
active_model = model
|
|
284
|
+
else:
|
|
285
|
+
active_model = model
|
|
286
|
+
|
|
287
|
+
latent = build_empty_comfy_latent(
|
|
288
|
+
active_model=active_model,
|
|
289
|
+
width=width,
|
|
290
|
+
height=height,
|
|
291
|
+
num_frames=num_frames,
|
|
292
|
+
)
|
|
293
|
+
streamer: Optional[TorchBlockStreamer] = None
|
|
294
|
+
try:
|
|
295
|
+
if block_stream_mode != BlockStreamMode.STAGE_ONLY.value:
|
|
296
|
+
streamer = attach_streamer_to_comfy_model(
|
|
297
|
+
active_model,
|
|
298
|
+
block_stream_mode=block_stream_mode,
|
|
299
|
+
unet_name=unet_name,
|
|
300
|
+
)
|
|
301
|
+
sampled_latent, = comfy_nodes.KSampler().sample(
|
|
302
|
+
model=active_model,
|
|
303
|
+
seed=seed,
|
|
304
|
+
steps=steps,
|
|
305
|
+
cfg=cfg,
|
|
306
|
+
sampler_name=sampler_name,
|
|
307
|
+
scheduler=scheduler,
|
|
308
|
+
positive=positive,
|
|
309
|
+
negative=negative,
|
|
310
|
+
latent_image=latent,
|
|
311
|
+
denoise=1.0,
|
|
312
|
+
)
|
|
313
|
+
finally:
|
|
314
|
+
if streamer is not None:
|
|
315
|
+
streamer.detach(restore_cpu_weights=False)
|
|
316
|
+
del active_model, model, positive, negative
|
|
317
|
+
free_comfy_memory()
|
|
318
|
+
|
|
319
|
+
# Stage 3: Load VAE, decode (tiled when appropriate), and immediately unload
|
|
320
|
+
vae, = comfy_nodes.VAELoader().load_vae(vae_name)
|
|
321
|
+
try:
|
|
322
|
+
decoded_image = decode_comfy_vae_smart(vae, sampled_latent, use_tiled_vae=use_tiled_vae)
|
|
323
|
+
finally:
|
|
324
|
+
del vae
|
|
325
|
+
free_comfy_memory()
|
|
326
|
+
|
|
327
|
+
latent_bundle = {
|
|
328
|
+
"samples": sampled_latent["samples"],
|
|
329
|
+
"comfy_latent": sampled_latent,
|
|
330
|
+
"decoded_image": decoded_image,
|
|
331
|
+
"vae_name": vae_name,
|
|
332
|
+
"width": width,
|
|
333
|
+
"height": height,
|
|
334
|
+
"num_frames": num_frames,
|
|
335
|
+
}
|
|
336
|
+
return decoded_image, latent_bundle
|