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,429 @@
|
|
|
1
|
+
"""ComfyUI custom node definitions for PhobosStream zero-VRAM streaming & stage offloading."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any, Dict, Optional, Tuple
|
|
5
|
+
|
|
6
|
+
from phobos_stream.integrations.comfyui.comfy_runtime import (
|
|
7
|
+
COMFY_NATIVE_AVAILABLE,
|
|
8
|
+
comfy_nodes,
|
|
9
|
+
decode_comfy_vae_smart,
|
|
10
|
+
free_comfy_memory,
|
|
11
|
+
get_comfy_filenames,
|
|
12
|
+
run_comfy_stage_offloaded_pipeline,
|
|
13
|
+
to_comfy_image_tensor,
|
|
14
|
+
attach_streamer_to_comfy_model,
|
|
15
|
+
)
|
|
16
|
+
from phobos_stream.pipeline.stream_engine import PhobosStreamEngine
|
|
17
|
+
from phobos_stream.storage.layout import ModelShardsManifest
|
|
18
|
+
from phobos_stream.types import BackendType, GenerationConfig
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
CLIP_TYPE_CHOICES = [
|
|
22
|
+
"lumina2",
|
|
23
|
+
"wan",
|
|
24
|
+
"flux",
|
|
25
|
+
"sd3",
|
|
26
|
+
"sdxl",
|
|
27
|
+
"hunyuan_video",
|
|
28
|
+
"cogvideox",
|
|
29
|
+
"ltxv",
|
|
30
|
+
"qwen_image",
|
|
31
|
+
"stable_diffusion",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class PhobosStreamLoaderNode:
|
|
36
|
+
"""ComfyUI Node: Configures PhobosStream zero-VRAM stage offloader & block-streaming engine."""
|
|
37
|
+
|
|
38
|
+
@classmethod
|
|
39
|
+
def INPUT_TYPES(cls) -> Dict[str, Any]:
|
|
40
|
+
unet_list = get_comfy_filenames("diffusion_models", ["z_image_turbo_bf16.safetensors"])
|
|
41
|
+
clip_list = get_comfy_filenames("text_encoders", ["qwen_3_4b.safetensors"])
|
|
42
|
+
clip2_list = ["none"] + clip_list
|
|
43
|
+
vae_list = get_comfy_filenames("vae", ["ae.safetensors"])
|
|
44
|
+
|
|
45
|
+
return {
|
|
46
|
+
"required": {
|
|
47
|
+
"model_name": ("STRING", {"default": "wan2.1-14b"}),
|
|
48
|
+
"architecture": (["wan2.1", "flux", "hunyuan", "cogvideox", "lumina2"], {"default": "wan2.1"}),
|
|
49
|
+
"backend": (["auto", "mlx", "cuda", "gguf", "cpu"], {"default": "auto"}),
|
|
50
|
+
"num_blocks": ("INT", {"default": 30, "min": 1, "max": 80}),
|
|
51
|
+
"hidden_size": ("INT", {"default": 3840, "min": 64, "max": 8192, "step": 64}),
|
|
52
|
+
},
|
|
53
|
+
"optional": {
|
|
54
|
+
"manifest_path": ("STRING", {"default": ""}),
|
|
55
|
+
"unet_name": (unet_list, {"default": unet_list[0]}),
|
|
56
|
+
"weight_dtype": (["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2"], {"default": "default"}),
|
|
57
|
+
"clip_name": (clip_list, {"default": clip_list[0]}),
|
|
58
|
+
"clip_name2": (clip2_list, {"default": "none"}),
|
|
59
|
+
"clip_type": (CLIP_TYPE_CHOICES, {"default": "lumina2"}),
|
|
60
|
+
"vae_name": (vae_list, {"default": vae_list[0]}),
|
|
61
|
+
"aura_shift": ("FLOAT", {"default": 3.0, "min": 0.0, "max": 12.0, "step": 0.1}),
|
|
62
|
+
"block_stream_mode": (["stage_only", "cpu_offload", "mmap_stream"], {"default": "stage_only"}),
|
|
63
|
+
"use_comfy_stage_offload": ("BOOLEAN", {"default": True}),
|
|
64
|
+
"allow_synthetic": ("BOOLEAN", {"default": False}),
|
|
65
|
+
},
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
RETURN_TYPES = ("PHOBOS_MODEL",)
|
|
69
|
+
RETURN_NAMES = ("phobos_model",)
|
|
70
|
+
FUNCTION = "load_model"
|
|
71
|
+
CATEGORY = "PhobosStream"
|
|
72
|
+
|
|
73
|
+
def load_model(
|
|
74
|
+
self,
|
|
75
|
+
model_name: str,
|
|
76
|
+
architecture: str,
|
|
77
|
+
backend: str,
|
|
78
|
+
num_blocks: int,
|
|
79
|
+
hidden_size: int,
|
|
80
|
+
manifest_path: str = "",
|
|
81
|
+
unet_name: str = "z_image_turbo_bf16.safetensors",
|
|
82
|
+
weight_dtype: str = "default",
|
|
83
|
+
clip_name: str = "qwen_3_4b.safetensors",
|
|
84
|
+
clip_name2: str = "none",
|
|
85
|
+
clip_type: str = "lumina2",
|
|
86
|
+
vae_name: str = "ae.safetensors",
|
|
87
|
+
aura_shift: float = 3.0,
|
|
88
|
+
block_stream_mode: str = "stage_only",
|
|
89
|
+
use_comfy_stage_offload: bool = True,
|
|
90
|
+
allow_synthetic: bool = False,
|
|
91
|
+
) -> Tuple[Dict[str, Any]]:
|
|
92
|
+
if manifest_path and Path(manifest_path).exists():
|
|
93
|
+
manifest = ModelShardsManifest.load(Path(manifest_path))
|
|
94
|
+
if allow_synthetic:
|
|
95
|
+
manifest.allow_synthetic = True
|
|
96
|
+
else:
|
|
97
|
+
manifest = ModelShardsManifest(
|
|
98
|
+
model_name=model_name,
|
|
99
|
+
architecture=architecture,
|
|
100
|
+
num_blocks=num_blocks,
|
|
101
|
+
hidden_size=hidden_size,
|
|
102
|
+
allow_synthetic=allow_synthetic,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
stage_offload_active = bool(use_comfy_stage_offload and COMFY_NATIVE_AVAILABLE)
|
|
106
|
+
engine: Optional[PhobosStreamEngine] = None
|
|
107
|
+
if not stage_offload_active:
|
|
108
|
+
engine = PhobosStreamEngine(manifest=manifest, backend_type=BackendType(backend))
|
|
109
|
+
|
|
110
|
+
return (
|
|
111
|
+
{
|
|
112
|
+
"engine": engine,
|
|
113
|
+
"manifest": manifest,
|
|
114
|
+
"backend": backend,
|
|
115
|
+
"unet_name": unet_name,
|
|
116
|
+
"weight_dtype": weight_dtype,
|
|
117
|
+
"clip_name": clip_name,
|
|
118
|
+
"clip_name2": "" if clip_name2 == "none" else clip_name2,
|
|
119
|
+
"clip_type": clip_type,
|
|
120
|
+
"vae_name": vae_name,
|
|
121
|
+
"aura_shift": aura_shift,
|
|
122
|
+
"block_stream_mode": block_stream_mode,
|
|
123
|
+
"use_comfy_stage_offload": stage_offload_active,
|
|
124
|
+
},
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class PhobosBlockStreamPatcherNode:
|
|
129
|
+
"""ComfyUI Node: Attaches per-block CPU-offload or zero-RAM mmap streaming hooks to ANY ComfyUI MODEL."""
|
|
130
|
+
|
|
131
|
+
@classmethod
|
|
132
|
+
def INPUT_TYPES(cls) -> Dict[str, Any]:
|
|
133
|
+
return {
|
|
134
|
+
"required": {
|
|
135
|
+
"model": ("MODEL",),
|
|
136
|
+
"mode": (["cpu_offload", "mmap_stream"], {"default": "cpu_offload"}),
|
|
137
|
+
},
|
|
138
|
+
"optional": {
|
|
139
|
+
"safetensors_path": ("STRING", {"default": ""}),
|
|
140
|
+
},
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
RETURN_TYPES = ("MODEL",)
|
|
144
|
+
RETURN_NAMES = ("model",)
|
|
145
|
+
FUNCTION = "patch_model"
|
|
146
|
+
CATEGORY = "PhobosStream"
|
|
147
|
+
|
|
148
|
+
def patch_model(
|
|
149
|
+
self,
|
|
150
|
+
model: Any,
|
|
151
|
+
mode: str = "cpu_offload",
|
|
152
|
+
safetensors_path: str = "",
|
|
153
|
+
) -> Tuple[Any]:
|
|
154
|
+
patched = model.clone() if hasattr(model, "clone") else model
|
|
155
|
+
streamer = attach_streamer_to_comfy_model(
|
|
156
|
+
comfy_model=patched,
|
|
157
|
+
block_stream_mode=mode,
|
|
158
|
+
unet_name=safetensors_path.strip(),
|
|
159
|
+
)
|
|
160
|
+
setattr(patched, "_phobos_block_streamer", streamer)
|
|
161
|
+
return (patched,)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class PhobosStreamSamplerNode:
|
|
165
|
+
"""ComfyUI Node: Executes 3-stage offloaded or block-streamed image & video diffusion."""
|
|
166
|
+
|
|
167
|
+
@classmethod
|
|
168
|
+
def INPUT_TYPES(cls) -> Dict[str, Any]:
|
|
169
|
+
return {
|
|
170
|
+
"required": {
|
|
171
|
+
"phobos_model": ("PHOBOS_MODEL",),
|
|
172
|
+
"prompt": (
|
|
173
|
+
"STRING",
|
|
174
|
+
{
|
|
175
|
+
"multiline": True,
|
|
176
|
+
"default": "A hyper-detailed futuristic Martian base on red crater landscape, glowing domes, starry galaxy background, 8k photorealistic",
|
|
177
|
+
},
|
|
178
|
+
),
|
|
179
|
+
"negative_prompt": ("STRING", {"multiline": True, "default": ""}),
|
|
180
|
+
"width": ("INT", {"default": 1280, "min": 128, "max": 3840, "step": 16}),
|
|
181
|
+
"height": ("INT", {"default": 720, "min": 128, "max": 2160, "step": 16}),
|
|
182
|
+
"num_frames": ("INT", {"default": 1, "min": 1, "max": 241, "step": 1}),
|
|
183
|
+
"steps": ("INT", {"default": 8, "min": 1, "max": 100}),
|
|
184
|
+
"guidance_scale": ("FLOAT", {"default": 1.0, "min": 1.0, "max": 20.0, "step": 0.5}),
|
|
185
|
+
"seed": ("INT", {"default": 42, "min": 0, "max": 0xFFFFFFFFFFFFFFFF}),
|
|
186
|
+
},
|
|
187
|
+
"optional": {
|
|
188
|
+
"sampler_name": (["res_multistep", "euler", "euler_ancestral", "uni_pc", "dpmpp_2m"], {"default": "res_multistep"}),
|
|
189
|
+
"scheduler": (["simple", "normal", "karras", "sgm_uniform", "beta"], {"default": "simple"}),
|
|
190
|
+
"use_tiled_vae": ("BOOLEAN", {"default": True}),
|
|
191
|
+
},
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
RETURN_TYPES = ("IMAGE", "PHOBOS_LATENT")
|
|
195
|
+
RETURN_NAMES = ("images", "latents")
|
|
196
|
+
FUNCTION = "sample"
|
|
197
|
+
CATEGORY = "PhobosStream"
|
|
198
|
+
|
|
199
|
+
def sample(
|
|
200
|
+
self,
|
|
201
|
+
phobos_model: Optional[Dict[str, Any]] = None,
|
|
202
|
+
prompt: str = "",
|
|
203
|
+
negative_prompt: str = "",
|
|
204
|
+
width: int = 1280,
|
|
205
|
+
height: int = 720,
|
|
206
|
+
num_frames: int = 1,
|
|
207
|
+
steps: int = 8,
|
|
208
|
+
guidance_scale: float = 1.0,
|
|
209
|
+
seed: int = 42,
|
|
210
|
+
sampler_name: str = "res_multistep",
|
|
211
|
+
scheduler: str = "simple",
|
|
212
|
+
use_tiled_vae: bool = True,
|
|
213
|
+
aether_model: Optional[Dict[str, Any]] = None,
|
|
214
|
+
) -> Tuple[Any, Dict[str, Any]]:
|
|
215
|
+
model_bundle = phobos_model if phobos_model is not None else aether_model
|
|
216
|
+
if model_bundle is None:
|
|
217
|
+
raise ValueError("A valid PHOBOS_MODEL dict must be provided.")
|
|
218
|
+
|
|
219
|
+
if model_bundle.get("use_comfy_stage_offload") and COMFY_NATIVE_AVAILABLE:
|
|
220
|
+
decoded_image, latent_bundle = run_comfy_stage_offloaded_pipeline(
|
|
221
|
+
unet_name=model_bundle.get("unet_name", "z_image_turbo_bf16.safetensors"),
|
|
222
|
+
clip_name=model_bundle.get("clip_name", "qwen_3_4b.safetensors"),
|
|
223
|
+
clip_type=model_bundle.get("clip_type", "lumina2"),
|
|
224
|
+
vae_name=model_bundle.get("vae_name", "ae.safetensors"),
|
|
225
|
+
prompt=prompt,
|
|
226
|
+
negative_prompt=negative_prompt,
|
|
227
|
+
width=width,
|
|
228
|
+
height=height,
|
|
229
|
+
num_frames=num_frames,
|
|
230
|
+
steps=steps,
|
|
231
|
+
cfg=guidance_scale,
|
|
232
|
+
seed=seed,
|
|
233
|
+
sampler_name=sampler_name,
|
|
234
|
+
scheduler=scheduler,
|
|
235
|
+
aura_shift=float(model_bundle.get("aura_shift", 3.0)),
|
|
236
|
+
clip_name2=model_bundle.get("clip_name2", ""),
|
|
237
|
+
weight_dtype=model_bundle.get("weight_dtype", "default"),
|
|
238
|
+
block_stream_mode=model_bundle.get("block_stream_mode", "stage_only"),
|
|
239
|
+
use_tiled_vae=use_tiled_vae,
|
|
240
|
+
)
|
|
241
|
+
return (decoded_image, latent_bundle)
|
|
242
|
+
|
|
243
|
+
engine: Optional[PhobosStreamEngine] = model_bundle.get("engine")
|
|
244
|
+
if engine is None:
|
|
245
|
+
manifest = model_bundle["manifest"]
|
|
246
|
+
backend = model_bundle.get("backend", "auto")
|
|
247
|
+
engine = PhobosStreamEngine(manifest=manifest, backend_type=BackendType(backend))
|
|
248
|
+
model_bundle["engine"] = engine
|
|
249
|
+
|
|
250
|
+
config = GenerationConfig(
|
|
251
|
+
prompt=prompt,
|
|
252
|
+
negative_prompt=negative_prompt,
|
|
253
|
+
width=width,
|
|
254
|
+
height=height,
|
|
255
|
+
num_frames=num_frames,
|
|
256
|
+
steps=steps,
|
|
257
|
+
guidance_scale=guidance_scale,
|
|
258
|
+
seed=seed,
|
|
259
|
+
)
|
|
260
|
+
rgb_frames, raw_latents, _ = engine.generate_with_latents(config)
|
|
261
|
+
image_out = to_comfy_image_tensor(rgb_frames)
|
|
262
|
+
latent_dict = {
|
|
263
|
+
"samples": raw_latents,
|
|
264
|
+
"rgb_frames": rgb_frames,
|
|
265
|
+
"width": width,
|
|
266
|
+
"height": height,
|
|
267
|
+
"num_frames": num_frames,
|
|
268
|
+
}
|
|
269
|
+
return (image_out, latent_dict)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
class PhobosStreamVAEDecodeNode:
|
|
273
|
+
"""ComfyUI Node: Decodes PhobosStream image/video latents with tiled VAE & immediate offload."""
|
|
274
|
+
|
|
275
|
+
@classmethod
|
|
276
|
+
def INPUT_TYPES(cls) -> Dict[str, Any]:
|
|
277
|
+
return {
|
|
278
|
+
"required": {
|
|
279
|
+
"latents": ("PHOBOS_LATENT",),
|
|
280
|
+
"phobos_model": ("PHOBOS_MODEL",),
|
|
281
|
+
},
|
|
282
|
+
"optional": {
|
|
283
|
+
"use_tiled_vae": ("BOOLEAN", {"default": True}),
|
|
284
|
+
},
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
RETURN_TYPES = ("IMAGE",)
|
|
288
|
+
RETURN_NAMES = ("images",)
|
|
289
|
+
FUNCTION = "decode"
|
|
290
|
+
CATEGORY = "PhobosStream"
|
|
291
|
+
|
|
292
|
+
def decode(
|
|
293
|
+
self,
|
|
294
|
+
latents: Dict[str, Any],
|
|
295
|
+
phobos_model: Optional[Dict[str, Any]] = None,
|
|
296
|
+
use_tiled_vae: bool = True,
|
|
297
|
+
aether_model: Optional[Dict[str, Any]] = None,
|
|
298
|
+
) -> Tuple[Any]:
|
|
299
|
+
if "decoded_image" in latents and latents["decoded_image"] is not None:
|
|
300
|
+
return (latents["decoded_image"],)
|
|
301
|
+
|
|
302
|
+
if "comfy_latent" in latents and COMFY_NATIVE_AVAILABLE and comfy_nodes is not None:
|
|
303
|
+
model_bundle = phobos_model if phobos_model is not None else aether_model or {}
|
|
304
|
+
vae_name = latents.get("vae_name") or model_bundle.get("vae_name", "ae.safetensors")
|
|
305
|
+
free_comfy_memory()
|
|
306
|
+
vae, = comfy_nodes.VAELoader().load_vae(vae_name)
|
|
307
|
+
try:
|
|
308
|
+
decoded_image = decode_comfy_vae_smart(vae, latents["comfy_latent"], use_tiled_vae=use_tiled_vae)
|
|
309
|
+
finally:
|
|
310
|
+
del vae
|
|
311
|
+
free_comfy_memory()
|
|
312
|
+
return (decoded_image,)
|
|
313
|
+
|
|
314
|
+
model_bundle = phobos_model if phobos_model is not None else aether_model
|
|
315
|
+
raw_samples = latents["samples"]
|
|
316
|
+
if (
|
|
317
|
+
model_bundle is not None
|
|
318
|
+
and model_bundle.get("engine") is not None
|
|
319
|
+
and hasattr(raw_samples, "ndim")
|
|
320
|
+
and raw_samples.ndim == 3
|
|
321
|
+
and raw_samples.shape[-1] != 3
|
|
322
|
+
):
|
|
323
|
+
engine: PhobosStreamEngine = model_bundle["engine"]
|
|
324
|
+
latent_tensor = engine.backend.convert_from_numpy(raw_samples)
|
|
325
|
+
rgb_frames, _ = engine.offloader.decode_vae_stage(
|
|
326
|
+
latents=latent_tensor,
|
|
327
|
+
height=latents.get("height", 480),
|
|
328
|
+
width=latents.get("width", 720),
|
|
329
|
+
num_frames=latents.get("num_frames", 1),
|
|
330
|
+
)
|
|
331
|
+
elif "rgb_frames" in latents:
|
|
332
|
+
rgb_frames = latents["rgb_frames"]
|
|
333
|
+
else:
|
|
334
|
+
rgb_frames = raw_samples
|
|
335
|
+
|
|
336
|
+
return (to_comfy_image_tensor(rgb_frames),)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
class PhobosStageOffloadPipelineNode:
|
|
340
|
+
"""All-in-One ComfyUI Node: 3-stage sequential offloading (`Text -> DiT -> VAE`) for 2K/4K & Video."""
|
|
341
|
+
|
|
342
|
+
@classmethod
|
|
343
|
+
def INPUT_TYPES(cls) -> Dict[str, Any]:
|
|
344
|
+
unet_list = get_comfy_filenames("diffusion_models", ["z_image_turbo_bf16.safetensors"])
|
|
345
|
+
clip_list = get_comfy_filenames("text_encoders", ["qwen_3_4b.safetensors"])
|
|
346
|
+
clip2_list = ["none"] + clip_list
|
|
347
|
+
vae_list = get_comfy_filenames("vae", ["ae.safetensors"])
|
|
348
|
+
|
|
349
|
+
return {
|
|
350
|
+
"required": {
|
|
351
|
+
"unet_name": (unet_list, {"default": unet_list[0]}),
|
|
352
|
+
"clip_name": (clip_list, {"default": clip_list[0]}),
|
|
353
|
+
"clip_type": (CLIP_TYPE_CHOICES, {"default": "lumina2"}),
|
|
354
|
+
"vae_name": (vae_list, {"default": vae_list[0]}),
|
|
355
|
+
"prompt": (
|
|
356
|
+
"STRING",
|
|
357
|
+
{
|
|
358
|
+
"multiline": True,
|
|
359
|
+
"default": "A hyper-detailed futuristic Martian base on red crater landscape, glowing domes, starry galaxy background, 8k photorealistic",
|
|
360
|
+
},
|
|
361
|
+
),
|
|
362
|
+
"negative_prompt": ("STRING", {"multiline": True, "default": ""}),
|
|
363
|
+
"width": ("INT", {"default": 2048, "min": 128, "max": 3840, "step": 16}),
|
|
364
|
+
"height": ("INT", {"default": 1152, "min": 128, "max": 2160, "step": 16}),
|
|
365
|
+
"steps": ("INT", {"default": 8, "min": 1, "max": 100}),
|
|
366
|
+
"cfg": ("FLOAT", {"default": 1.0, "min": 1.0, "max": 20.0, "step": 0.5}),
|
|
367
|
+
"aura_shift": ("FLOAT", {"default": 3.0, "min": 0.0, "max": 12.0, "step": 0.1}),
|
|
368
|
+
"sampler_name": (["res_multistep", "euler", "euler_ancestral", "uni_pc", "dpmpp_2m"], {"default": "res_multistep"}),
|
|
369
|
+
"scheduler": (["simple", "normal", "karras", "sgm_uniform", "beta"], {"default": "simple"}),
|
|
370
|
+
"seed": ("INT", {"default": 42, "min": 0, "max": 0xFFFFFFFFFFFFFFFF}),
|
|
371
|
+
},
|
|
372
|
+
"optional": {
|
|
373
|
+
"num_frames": ("INT", {"default": 1, "min": 1, "max": 241, "step": 1}),
|
|
374
|
+
"clip_name2": (clip2_list, {"default": "none"}),
|
|
375
|
+
"weight_dtype": (["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2"], {"default": "default"}),
|
|
376
|
+
"block_stream_mode": (["stage_only", "cpu_offload", "mmap_stream"], {"default": "stage_only"}),
|
|
377
|
+
"use_tiled_vae": ("BOOLEAN", {"default": True}),
|
|
378
|
+
},
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
RETURN_TYPES = ("IMAGE",)
|
|
382
|
+
RETURN_NAMES = ("images",)
|
|
383
|
+
FUNCTION = "generate_offloaded"
|
|
384
|
+
CATEGORY = "PhobosStream"
|
|
385
|
+
|
|
386
|
+
def generate_offloaded(
|
|
387
|
+
self,
|
|
388
|
+
unet_name: str,
|
|
389
|
+
clip_name: str,
|
|
390
|
+
clip_type: str,
|
|
391
|
+
vae_name: str,
|
|
392
|
+
prompt: str,
|
|
393
|
+
negative_prompt: str,
|
|
394
|
+
width: int,
|
|
395
|
+
height: int,
|
|
396
|
+
steps: int,
|
|
397
|
+
cfg: float,
|
|
398
|
+
aura_shift: float,
|
|
399
|
+
sampler_name: str,
|
|
400
|
+
scheduler: str,
|
|
401
|
+
seed: int,
|
|
402
|
+
num_frames: int = 1,
|
|
403
|
+
clip_name2: str = "none",
|
|
404
|
+
weight_dtype: str = "default",
|
|
405
|
+
block_stream_mode: str = "stage_only",
|
|
406
|
+
use_tiled_vae: bool = True,
|
|
407
|
+
) -> Tuple[Any]:
|
|
408
|
+
decoded_image, _ = run_comfy_stage_offloaded_pipeline(
|
|
409
|
+
unet_name=unet_name,
|
|
410
|
+
clip_name=clip_name,
|
|
411
|
+
clip_type=clip_type,
|
|
412
|
+
vae_name=vae_name,
|
|
413
|
+
prompt=prompt,
|
|
414
|
+
negative_prompt=negative_prompt,
|
|
415
|
+
width=width,
|
|
416
|
+
height=height,
|
|
417
|
+
num_frames=num_frames,
|
|
418
|
+
steps=steps,
|
|
419
|
+
cfg=cfg,
|
|
420
|
+
seed=seed,
|
|
421
|
+
sampler_name=sampler_name,
|
|
422
|
+
scheduler=scheduler,
|
|
423
|
+
aura_shift=aura_shift,
|
|
424
|
+
clip_name2="" if clip_name2 == "none" else clip_name2,
|
|
425
|
+
weight_dtype=weight_dtype,
|
|
426
|
+
block_stream_mode=block_stream_mode,
|
|
427
|
+
use_tiled_vae=use_tiled_vae,
|
|
428
|
+
)
|
|
429
|
+
return (decoded_image,)
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Image (PNG) and Video (MP4) encoding utilities for PhobosStream."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import shutil
|
|
5
|
+
import struct
|
|
6
|
+
import subprocess
|
|
7
|
+
import zlib
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def encode_png_bytes(rgb_frame: np.ndarray) -> bytes:
|
|
12
|
+
"""Encode a `(H, W, 3)` uint8 RGB image array into standard PNG bytes.
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
rgb_frame: 3D `(H, W, 3)` uint8 RGB array.
|
|
16
|
+
|
|
17
|
+
Returns:
|
|
18
|
+
Valid PNG binary payload.
|
|
19
|
+
"""
|
|
20
|
+
arr = np.ascontiguousarray(rgb_frame, dtype=np.uint8)
|
|
21
|
+
if arr.ndim != 3 or arr.shape[2] != 3:
|
|
22
|
+
raise ValueError(f"Expected (H, W, 3) RGB array for PNG encoding, got shape {arr.shape}")
|
|
23
|
+
|
|
24
|
+
height, width, _ = arr.shape
|
|
25
|
+
scanlines = np.hstack([np.zeros((height, 1), dtype=np.uint8), arr.reshape(height, width * 3)])
|
|
26
|
+
compressed = zlib.compress(scanlines.tobytes(), level=6)
|
|
27
|
+
|
|
28
|
+
def _make_chunk(chunk_type: bytes, data: bytes) -> bytes:
|
|
29
|
+
crc = zlib.crc32(chunk_type + data) & 0xFFFFFFFF
|
|
30
|
+
return struct.pack(">I", len(data)) + chunk_type + data + struct.pack(">I", crc)
|
|
31
|
+
|
|
32
|
+
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
|
33
|
+
return (
|
|
34
|
+
b"\x89PNG\r\n\x1a\n"
|
|
35
|
+
+ _make_chunk(b"IHDR", ihdr)
|
|
36
|
+
+ _make_chunk(b"IDAT", compressed)
|
|
37
|
+
+ _make_chunk(b"IEND", b"")
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def save_rgb_png(rgb_frame: np.ndarray, path: Path) -> Path:
|
|
42
|
+
"""Write a `(H, W, 3)` uint8 RGB image to disk as a PNG file."""
|
|
43
|
+
out_path = Path(path)
|
|
44
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
45
|
+
out_path.write_bytes(encode_png_bytes(rgb_frame))
|
|
46
|
+
return out_path
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def save_rgb_mp4(rgb_frames: np.ndarray, path: Path, fps: int = 24) -> Path:
|
|
50
|
+
"""Encode `(T, H, W, 3)` uint8 RGB frames into a standards-compliant MP4 video.
|
|
51
|
+
|
|
52
|
+
Uses `ffmpeg` (`libx264`, `yuv420p`, `+faststart`) when installed on PATH,
|
|
53
|
+
with automatic fallback to OpenCV (`cv2.VideoWriter` with `mp4v`).
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
rgb_frames: `(T, H, W, 3)` or `(H, W, 3)` RGB array (`uint8` or float `[0, 1]`).
|
|
57
|
+
path: Target `.mp4` output path.
|
|
58
|
+
fps: Playback frame rate in frames per second.
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
Resolved output `.mp4` path.
|
|
62
|
+
"""
|
|
63
|
+
frames = np.asarray(rgb_frames)
|
|
64
|
+
if frames.ndim == 3:
|
|
65
|
+
frames = frames[None, ...]
|
|
66
|
+
if frames.ndim != 4 or frames.shape[-1] != 3:
|
|
67
|
+
raise ValueError(f"Expected (T, H, W, 3) RGB frames for MP4 encoding, got shape {frames.shape}")
|
|
68
|
+
|
|
69
|
+
if frames.dtype != np.uint8:
|
|
70
|
+
if np.issubdtype(frames.dtype, np.floating) and float(frames.max()) <= 1.0:
|
|
71
|
+
frames = np.clip(frames * 255.0, 0.0, 255.0).astype(np.uint8)
|
|
72
|
+
else:
|
|
73
|
+
frames = np.clip(frames, 0, 255).astype(np.uint8)
|
|
74
|
+
frames = np.ascontiguousarray(frames)
|
|
75
|
+
|
|
76
|
+
out_path = Path(path)
|
|
77
|
+
if out_path.suffix.lower() != ".mp4":
|
|
78
|
+
out_path = out_path.with_suffix(".mp4")
|
|
79
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
80
|
+
|
|
81
|
+
_, height, width, _ = frames.shape
|
|
82
|
+
ffmpeg_bin = shutil.which("ffmpeg")
|
|
83
|
+
if ffmpeg_bin:
|
|
84
|
+
cmd = [
|
|
85
|
+
ffmpeg_bin,
|
|
86
|
+
"-y",
|
|
87
|
+
"-loglevel",
|
|
88
|
+
"error",
|
|
89
|
+
"-f",
|
|
90
|
+
"rawvideo",
|
|
91
|
+
"-vcodec",
|
|
92
|
+
"rawvideo",
|
|
93
|
+
"-pix_fmt",
|
|
94
|
+
"rgb24",
|
|
95
|
+
"-s",
|
|
96
|
+
f"{width}x{height}",
|
|
97
|
+
"-r",
|
|
98
|
+
str(max(1, int(fps))),
|
|
99
|
+
"-i",
|
|
100
|
+
"-",
|
|
101
|
+
"-vf",
|
|
102
|
+
"pad=ceil(iw/2)*2:ceil(ih/2)*2",
|
|
103
|
+
"-c:v",
|
|
104
|
+
"libx264",
|
|
105
|
+
"-preset",
|
|
106
|
+
"ultrafast",
|
|
107
|
+
"-crf",
|
|
108
|
+
"18",
|
|
109
|
+
"-pix_fmt",
|
|
110
|
+
"yuv420p",
|
|
111
|
+
"-movflags",
|
|
112
|
+
"+faststart",
|
|
113
|
+
str(out_path),
|
|
114
|
+
]
|
|
115
|
+
proc = subprocess.run(cmd, input=frames.tobytes(), capture_output=True, check=False)
|
|
116
|
+
if proc.returncode == 0 and out_path.exists() and out_path.stat().st_size > 0:
|
|
117
|
+
return out_path
|
|
118
|
+
|
|
119
|
+
# Fallback to OpenCV VideoWriter if ffmpeg is absent or lacks libx264
|
|
120
|
+
try:
|
|
121
|
+
import cv2 # type: ignore
|
|
122
|
+
except ImportError as exc:
|
|
123
|
+
raise RuntimeError(
|
|
124
|
+
"Neither a working 'ffmpeg' binary with libx264 nor 'opencv-python' is available to encode MP4."
|
|
125
|
+
) from exc
|
|
126
|
+
|
|
127
|
+
even_w = width + (width % 2)
|
|
128
|
+
even_h = height + (height % 2)
|
|
129
|
+
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
|
130
|
+
writer = cv2.VideoWriter(str(out_path), fourcc, float(max(1, int(fps))), (even_w, even_h))
|
|
131
|
+
if not writer.isOpened():
|
|
132
|
+
raise RuntimeError(f"OpenCV VideoWriter failed to open output path: {out_path}")
|
|
133
|
+
|
|
134
|
+
try:
|
|
135
|
+
for frame in frames:
|
|
136
|
+
if even_h != height or even_w != width:
|
|
137
|
+
frame = np.pad(frame, ((0, even_h - height), (0, even_w - width), (0, 0)), mode="edge")
|
|
138
|
+
bgr = frame[:, :, ::-1].copy()
|
|
139
|
+
writer.write(bgr)
|
|
140
|
+
finally:
|
|
141
|
+
writer.release()
|
|
142
|
+
|
|
143
|
+
if not out_path.exists() or out_path.stat().st_size == 0:
|
|
144
|
+
raise RuntimeError(f"Failed to write non-empty MP4 video to {out_path}")
|
|
145
|
+
return out_path
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""DiT model blocks, attention, and position embeddings."""
|
|
2
|
+
|
|
3
|
+
from phobos_stream.models.attention import AttentionWeights, DiTAttention
|
|
4
|
+
from phobos_stream.models.dit_block import DiTBlock, DiTBlockWeights, MLPWeights
|
|
5
|
+
from phobos_stream.models.rotary import RotaryEmbedding3D
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"AttentionWeights",
|
|
9
|
+
"DiTAttention",
|
|
10
|
+
"DiTBlock",
|
|
11
|
+
"DiTBlockWeights",
|
|
12
|
+
"MLPWeights",
|
|
13
|
+
"RotaryEmbedding3D",
|
|
14
|
+
]
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Universal Self-Attention and Cross-Attention for Diffusion Transformers."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Any, Optional
|
|
5
|
+
from phobos_stream.backends.base import BaseBackend
|
|
6
|
+
from phobos_stream.models.rotary import rotate_half_pairs
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class AttentionWeights:
|
|
11
|
+
"""Weight tensors for a single attention layer."""
|
|
12
|
+
|
|
13
|
+
q_proj: Any
|
|
14
|
+
k_proj: Any
|
|
15
|
+
v_proj: Any
|
|
16
|
+
out_proj: Any
|
|
17
|
+
q_bias: Optional[Any] = None
|
|
18
|
+
k_bias: Optional[Any] = None
|
|
19
|
+
v_bias: Optional[Any] = None
|
|
20
|
+
out_bias: Optional[Any] = None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class DiTAttention:
|
|
24
|
+
"""Multi-Head Self-Attention and Cross-Attention module."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, hidden_size: int, num_heads: int, backend: BaseBackend) -> None:
|
|
27
|
+
self.hidden_size = hidden_size
|
|
28
|
+
self.num_heads = max(1, num_heads)
|
|
29
|
+
self.head_dim = hidden_size // self.num_heads
|
|
30
|
+
self.backend = backend
|
|
31
|
+
|
|
32
|
+
def forward(
|
|
33
|
+
self,
|
|
34
|
+
x: Any,
|
|
35
|
+
weights: AttentionWeights,
|
|
36
|
+
context: Optional[Any] = None,
|
|
37
|
+
cos: Optional[Any] = None,
|
|
38
|
+
sin: Optional[Any] = None,
|
|
39
|
+
) -> Any:
|
|
40
|
+
"""Execute multi-head attention forward pass.
|
|
41
|
+
|
|
42
|
+
If context is provided, performs Cross-Attention (Q from x, K/V from context).
|
|
43
|
+
Otherwise performs Self-Attention with 3D-RoPE.
|
|
44
|
+
"""
|
|
45
|
+
batch_size, seq_q, _ = x.shape
|
|
46
|
+
|
|
47
|
+
# Linear projection for Q (handles both (out, in) and (in, out) weight layouts)
|
|
48
|
+
q = self.backend.linear(x, weights.q_proj, weights.q_bias)
|
|
49
|
+
|
|
50
|
+
# Determine K, V source
|
|
51
|
+
kv_src = context if context is not None else x
|
|
52
|
+
seq_kv = kv_src.shape[1]
|
|
53
|
+
k = self.backend.linear(kv_src, weights.k_proj, weights.k_bias)
|
|
54
|
+
v = self.backend.linear(kv_src, weights.v_proj, weights.v_bias)
|
|
55
|
+
|
|
56
|
+
# Apply 3D-RoPE when self-attending
|
|
57
|
+
if cos is not None and sin is not None and context is None:
|
|
58
|
+
q = (q * cos) + (rotate_half_pairs(q) * sin)
|
|
59
|
+
k = (k * cos) + (rotate_half_pairs(k) * sin)
|
|
60
|
+
|
|
61
|
+
# Split heads: (B, Seq, Hidden) -> (B, NumHeads, Seq, HeadDim)
|
|
62
|
+
q = self.backend.swapaxes(
|
|
63
|
+
self.backend.reshape(q, (batch_size, seq_q, self.num_heads, self.head_dim)),
|
|
64
|
+
1,
|
|
65
|
+
2,
|
|
66
|
+
)
|
|
67
|
+
k = self.backend.swapaxes(
|
|
68
|
+
self.backend.reshape(k, (batch_size, seq_kv, self.num_heads, self.head_dim)),
|
|
69
|
+
1,
|
|
70
|
+
2,
|
|
71
|
+
)
|
|
72
|
+
v = self.backend.swapaxes(
|
|
73
|
+
self.backend.reshape(v, (batch_size, seq_kv, self.num_heads, self.head_dim)),
|
|
74
|
+
1,
|
|
75
|
+
2,
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
# Multi-head scaled dot-product attention
|
|
79
|
+
scale = 1.0 / (self.head_dim ** 0.5)
|
|
80
|
+
attn_out = self.backend.scaled_dot_product_attention(q, k, v, scale=scale)
|
|
81
|
+
|
|
82
|
+
# Merge heads: (B, NumHeads, Seq_Q, HeadDim) -> (B, Seq_Q, Hidden)
|
|
83
|
+
attn_merged = self.backend.reshape(
|
|
84
|
+
self.backend.swapaxes(attn_out, 1, 2),
|
|
85
|
+
(batch_size, seq_q, self.hidden_size),
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
# Output projection
|
|
89
|
+
out = self.backend.linear(attn_merged, weights.out_proj, weights.out_bias)
|
|
90
|
+
return out
|