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,109 @@
|
|
|
1
|
+
"""Universal Diffusion Transformer (DiT) Block with SwiGLU & AdaLN support."""
|
|
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.attention import AttentionWeights, DiTAttention
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class MLPWeights:
|
|
11
|
+
"""Feed-Forward Network weights (Standard or SwiGLU)."""
|
|
12
|
+
|
|
13
|
+
gate_proj: Any
|
|
14
|
+
up_proj: Any
|
|
15
|
+
down_proj: Any
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class DiTBlockWeights:
|
|
20
|
+
"""All weights required to execute a single DiT block."""
|
|
21
|
+
|
|
22
|
+
norm1_weight: Any
|
|
23
|
+
self_attn: AttentionWeights
|
|
24
|
+
norm2_weight: Any
|
|
25
|
+
cross_attn: Optional[AttentionWeights]
|
|
26
|
+
norm3_weight: Any
|
|
27
|
+
mlp: MLPWeights
|
|
28
|
+
ada_scale: Optional[Any] = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class DiTBlock:
|
|
32
|
+
"""Universal Diffusion Transformer layer block."""
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
hidden_size: int,
|
|
37
|
+
num_heads: int,
|
|
38
|
+
backend: BaseBackend,
|
|
39
|
+
has_cross_attn: bool = True,
|
|
40
|
+
) -> None:
|
|
41
|
+
self.hidden_size = hidden_size
|
|
42
|
+
self.backend = backend
|
|
43
|
+
self.self_attn_module = DiTAttention(hidden_size, num_heads, backend)
|
|
44
|
+
self.has_cross_attn = has_cross_attn
|
|
45
|
+
if has_cross_attn:
|
|
46
|
+
self.cross_attn_module = DiTAttention(hidden_size, num_heads, backend)
|
|
47
|
+
|
|
48
|
+
def _apply_timestep_modulation(
|
|
49
|
+
self,
|
|
50
|
+
normed_x: Any,
|
|
51
|
+
timestep_emb: Optional[Any],
|
|
52
|
+
ada_scale: Optional[Any],
|
|
53
|
+
) -> Any:
|
|
54
|
+
"""Modulate normalized activations with timestep embedding (AdaLN)."""
|
|
55
|
+
if timestep_emb is None:
|
|
56
|
+
return normed_x
|
|
57
|
+
|
|
58
|
+
t_cond = self.backend.silu(timestep_emb)
|
|
59
|
+
if ada_scale is not None:
|
|
60
|
+
t_cond = self.backend.linear(t_cond, ada_scale)
|
|
61
|
+
|
|
62
|
+
if len(t_cond.shape) == 1:
|
|
63
|
+
t_cond = self.backend.reshape(t_cond, (1, 1, -1))
|
|
64
|
+
elif len(t_cond.shape) == 2:
|
|
65
|
+
t_cond = self.backend.reshape(t_cond, (t_cond.shape[0], 1, -1))
|
|
66
|
+
|
|
67
|
+
# Scale & shift modulation when dimensions align
|
|
68
|
+
if t_cond.shape[-1] == self.hidden_size:
|
|
69
|
+
return normed_x * (1.0 + 0.1 * t_cond) + (0.05 * t_cond)
|
|
70
|
+
return normed_x
|
|
71
|
+
|
|
72
|
+
def forward(
|
|
73
|
+
self,
|
|
74
|
+
x: Any,
|
|
75
|
+
weights: DiTBlockWeights,
|
|
76
|
+
context: Optional[Any] = None,
|
|
77
|
+
timestep_emb: Optional[Any] = None,
|
|
78
|
+
cos: Optional[Any] = None,
|
|
79
|
+
sin: Optional[Any] = None,
|
|
80
|
+
) -> Any:
|
|
81
|
+
"""Forward pass through AdaLN Self-Attention, Cross-Attention, and SwiGLU MLP."""
|
|
82
|
+
# 1. Pre-norm + AdaLN Self-Attention
|
|
83
|
+
norm1 = self.backend.layer_norm(x, weights.norm1_weight)
|
|
84
|
+
norm1 = self._apply_timestep_modulation(norm1, timestep_emb, weights.ada_scale)
|
|
85
|
+
attn_out = self.self_attn_module.forward(
|
|
86
|
+
norm1,
|
|
87
|
+
weights.self_attn,
|
|
88
|
+
context=None,
|
|
89
|
+
cos=cos,
|
|
90
|
+
sin=sin,
|
|
91
|
+
)
|
|
92
|
+
x = x + attn_out
|
|
93
|
+
|
|
94
|
+
# 2. Cross-Attention (Conditioning on prompt text embeddings)
|
|
95
|
+
if self.has_cross_attn and weights.cross_attn is not None and context is not None:
|
|
96
|
+
norm2 = self.backend.layer_norm(x, weights.norm2_weight)
|
|
97
|
+
cross_out = self.cross_attn_module.forward(norm2, weights.cross_attn, context=context)
|
|
98
|
+
x = x + cross_out
|
|
99
|
+
|
|
100
|
+
# 3. Feed-Forward MLP (SwiGLU) with AdaLN modulation
|
|
101
|
+
norm3 = self.backend.layer_norm(x, weights.norm3_weight)
|
|
102
|
+
norm3 = self._apply_timestep_modulation(norm3, timestep_emb, None)
|
|
103
|
+
gate = self.backend.silu(self.backend.linear(norm3, weights.mlp.gate_proj))
|
|
104
|
+
up = self.backend.linear(norm3, weights.mlp.up_proj)
|
|
105
|
+
mlp_intermediate = gate * up
|
|
106
|
+
mlp_out = self.backend.linear(mlp_intermediate, weights.mlp.down_proj)
|
|
107
|
+
|
|
108
|
+
x = x + mlp_out
|
|
109
|
+
return x
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""3D Spatio-Temporal Rotary Position Embedding (3D-RoPE) for Video/Image DiT."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Optional, Tuple
|
|
4
|
+
import numpy as np
|
|
5
|
+
from phobos_stream.backends.base import BaseBackend
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def rotate_half_pairs(x: Any) -> Any:
|
|
9
|
+
"""Rotate interleaved 2D coordinate pairs (x0, x1) -> (-x1, x0) across any backend."""
|
|
10
|
+
orig_shape = x.shape
|
|
11
|
+
x_even = x[..., 0::2]
|
|
12
|
+
x_odd = x[..., 1::2]
|
|
13
|
+
|
|
14
|
+
# Check backend tensor type dynamically
|
|
15
|
+
mod_name = type(x).__module__
|
|
16
|
+
if "mlx" in mod_name:
|
|
17
|
+
import mlx.core as mx
|
|
18
|
+
stacked = mx.stack([-x_odd, x_even], axis=-1)
|
|
19
|
+
return mx.reshape(stacked, orig_shape)
|
|
20
|
+
if "torch" in mod_name:
|
|
21
|
+
import torch
|
|
22
|
+
stacked = torch.stack([-x_odd, x_even], dim=-1)
|
|
23
|
+
return stacked.reshape(*orig_shape)
|
|
24
|
+
|
|
25
|
+
stacked = np.stack([-x_odd, x_even], axis=-1)
|
|
26
|
+
return stacked.reshape(orig_shape)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class RotaryEmbedding3D:
|
|
30
|
+
"""3D RoPE encoding temporal (T), height (H), and width (W) coordinates."""
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
dim: int,
|
|
35
|
+
theta: float = 10000.0,
|
|
36
|
+
backend: Optional[BaseBackend] = None,
|
|
37
|
+
) -> None:
|
|
38
|
+
self.dim = dim
|
|
39
|
+
self.theta = theta
|
|
40
|
+
self.backend = backend
|
|
41
|
+
|
|
42
|
+
def get_freqs_1d(self, length: int, dim_part: int) -> np.ndarray:
|
|
43
|
+
"""Compute 1D sinusoidal frequency grid."""
|
|
44
|
+
even_dim = max(2, (dim_part // 2) * 2)
|
|
45
|
+
freqs = 1.0 / (self.theta ** (np.arange(0, even_dim, 2, dtype=np.float32) / even_dim))
|
|
46
|
+
t = np.arange(length, dtype=np.float32)
|
|
47
|
+
grid = np.outer(t, freqs)
|
|
48
|
+
return grid
|
|
49
|
+
|
|
50
|
+
def compute_frequencies(self, t_len: int, h_len: int, w_len: int) -> Tuple[Any, Any]:
|
|
51
|
+
"""Compute 3D cos and sin tables for spatio-temporal video latents."""
|
|
52
|
+
# Divide dimension across T (1/4), H (3/8), W (3/8) while keeping each part even
|
|
53
|
+
d_t = max(2, ((self.dim // 4) // 2) * 2)
|
|
54
|
+
d_h = max(2, (((self.dim - d_t) // 2) // 2) * 2)
|
|
55
|
+
d_w = max(2, self.dim - d_t - d_h)
|
|
56
|
+
|
|
57
|
+
freq_t = self.get_freqs_1d(t_len, d_t)
|
|
58
|
+
freq_h = self.get_freqs_1d(h_len, d_h)
|
|
59
|
+
freq_w = self.get_freqs_1d(w_len, d_w)
|
|
60
|
+
|
|
61
|
+
grid_t = np.broadcast_to(freq_t[:, None, None, :], (t_len, h_len, w_len, freq_t.shape[-1]))
|
|
62
|
+
grid_h = np.broadcast_to(freq_h[None, :, None, :], (t_len, h_len, w_len, freq_h.shape[-1]))
|
|
63
|
+
grid_w = np.broadcast_to(freq_w[None, None, :, :], (t_len, h_len, w_len, freq_w.shape[-1]))
|
|
64
|
+
|
|
65
|
+
freqs_3d = np.concatenate([grid_t, grid_h, grid_w], axis=-1)
|
|
66
|
+
freqs_flat = freqs_3d.reshape(-1, freqs_3d.shape[-1])
|
|
67
|
+
|
|
68
|
+
cos = np.repeat(np.cos(freqs_flat), 2, axis=-1)[:, : self.dim].astype(np.float32)
|
|
69
|
+
sin = np.repeat(np.sin(freqs_flat), 2, axis=-1)[:, : self.dim].astype(np.float32)
|
|
70
|
+
|
|
71
|
+
if self.backend is not None:
|
|
72
|
+
return self.backend.convert_from_numpy(cos), self.backend.convert_from_numpy(sin)
|
|
73
|
+
return cos, sin
|
|
74
|
+
|
|
75
|
+
def apply_rotary_emb(self, x: Any, cos: Any, sin: Any) -> Any:
|
|
76
|
+
"""Apply rotary embedding to query or key tensor."""
|
|
77
|
+
return (x * cos) + ( self._rotate_half(x) * sin )
|
|
78
|
+
|
|
79
|
+
def _rotate_half(self, x: Any) -> Any:
|
|
80
|
+
"""Rotate interleaved 2D pairs (-x_odd, x_even) for standard rotary multiplication."""
|
|
81
|
+
return rotate_half_pairs(x)
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Generation pipeline, schedulers, and offloader orchestrators."""
|
|
2
|
+
|
|
3
|
+
from phobos_stream.pipeline.offloader import PipelineOffloader
|
|
4
|
+
from phobos_stream.pipeline.scheduler import FlowMatchingScheduler
|
|
5
|
+
from phobos_stream.pipeline.stream_engine import PhobosStreamEngine
|
|
6
|
+
|
|
7
|
+
__all__ = ["PhobosStreamEngine", "FlowMatchingScheduler", "PipelineOffloader"]
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""Stage-wise sequential offloader and block-by-block streaming coordinator."""
|
|
2
|
+
|
|
3
|
+
import gc
|
|
4
|
+
import hashlib
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
from typing import Any, Dict, Optional, Tuple
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from phobos_stream.adapters.base import BaseModelAdapter
|
|
12
|
+
from phobos_stream.backends.base import BaseBackend
|
|
13
|
+
from phobos_stream.models.dit_block import DiTBlock
|
|
14
|
+
from phobos_stream.storage.layout import ModelShardsManifest
|
|
15
|
+
from phobos_stream.storage.mmap_loader import MMapTensorLoader
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class PipelineOffloader:
|
|
19
|
+
"""Orchestrates stage-wise offloading and block-by-block NVMe shard streaming."""
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
manifest: ModelShardsManifest,
|
|
24
|
+
adapter: BaseModelAdapter,
|
|
25
|
+
backend: BaseBackend,
|
|
26
|
+
) -> None:
|
|
27
|
+
self.manifest = manifest
|
|
28
|
+
self.adapter = adapter
|
|
29
|
+
self.backend = backend
|
|
30
|
+
num_heads = (
|
|
31
|
+
max(1, manifest.hidden_size // 128)
|
|
32
|
+
if manifest.hidden_size >= 128
|
|
33
|
+
else max(1, manifest.hidden_size // 16)
|
|
34
|
+
)
|
|
35
|
+
self.dit_block_module = DiTBlock(
|
|
36
|
+
hidden_size=manifest.hidden_size,
|
|
37
|
+
num_heads=num_heads,
|
|
38
|
+
backend=backend,
|
|
39
|
+
)
|
|
40
|
+
self.total_bytes_streamed = 0
|
|
41
|
+
self._loader_cache: Dict[str, MMapTensorLoader] = {}
|
|
42
|
+
|
|
43
|
+
def _get_loader(self, filename: str) -> MMapTensorLoader:
|
|
44
|
+
"""Retrieve or open a cached zero-copy MMapTensorLoader for a shard file."""
|
|
45
|
+
if filename not in self._loader_cache:
|
|
46
|
+
self._loader_cache[filename] = MMapTensorLoader(Path(filename))
|
|
47
|
+
return self._loader_cache[filename]
|
|
48
|
+
|
|
49
|
+
def close(self) -> None:
|
|
50
|
+
"""Close all cached mmap loaders."""
|
|
51
|
+
for loader in self._loader_cache.values():
|
|
52
|
+
loader.close()
|
|
53
|
+
self._loader_cache.clear()
|
|
54
|
+
|
|
55
|
+
def encode_text_stage(self, prompt: str, max_seq_len: int = 77) -> Tuple[Any, float]:
|
|
56
|
+
"""Stage 1: Encode text prompt into token embeddings and release encoder memory."""
|
|
57
|
+
start = time.perf_counter()
|
|
58
|
+
dim = self.manifest.hidden_size
|
|
59
|
+
|
|
60
|
+
tokens = re.findall(r"[a-zA-Z0-9_]+|[^\s\w]", prompt.lower())[:max_seq_len]
|
|
61
|
+
if not tokens:
|
|
62
|
+
tokens = ["<bos>"]
|
|
63
|
+
|
|
64
|
+
emb_matrix = np.zeros((1, max_seq_len, dim), dtype=np.float32)
|
|
65
|
+
loaded_from_safetensors = False
|
|
66
|
+
|
|
67
|
+
if self.manifest.text_encoder_path and Path(self.manifest.text_encoder_path).exists():
|
|
68
|
+
with MMapTensorLoader(Path(self.manifest.text_encoder_path)) as te_loader:
|
|
69
|
+
for t_name in te_loader.get_tensor_names():
|
|
70
|
+
if any(tag in t_name for tag in ("embed_tokens", "wte", "shared", "token_embedding")):
|
|
71
|
+
meta = te_loader.header[t_name]
|
|
72
|
+
vocab_size, v_dim = int(meta["shape"][0]), int(meta["shape"][-1])
|
|
73
|
+
start_rel, _ = meta["data_offsets"]
|
|
74
|
+
row_bytes = v_dim * (2 if meta["dtype"] in ("BF16", "F16") else 4)
|
|
75
|
+
for idx, tok in enumerate(tokens):
|
|
76
|
+
tok_id = int.from_bytes(hashlib.md5(tok.encode("utf-8")).digest()[:4], "little") % vocab_size
|
|
77
|
+
row_start = te_loader.data_offset + int(start_rel) + (tok_id * row_bytes)
|
|
78
|
+
row_view = memoryview(te_loader.mmap_obj)[row_start : row_start + row_bytes]
|
|
79
|
+
if meta["dtype"] == "BF16":
|
|
80
|
+
vec = (np.frombuffer(row_view, dtype=np.uint16).astype(np.uint32) << 16).view(np.float32)
|
|
81
|
+
elif meta["dtype"] == "F16":
|
|
82
|
+
vec = np.frombuffer(row_view, dtype=np.float16).astype(np.float32)
|
|
83
|
+
else:
|
|
84
|
+
vec = np.frombuffer(row_view, dtype=np.float32).copy()
|
|
85
|
+
if v_dim >= dim:
|
|
86
|
+
emb_matrix[0, idx, :] = vec[:dim]
|
|
87
|
+
else:
|
|
88
|
+
emb_matrix[0, idx, :v_dim] = vec
|
|
89
|
+
loaded_from_safetensors = True
|
|
90
|
+
break
|
|
91
|
+
|
|
92
|
+
if not loaded_from_safetensors:
|
|
93
|
+
if not self.manifest.allow_synthetic:
|
|
94
|
+
raise FileNotFoundError(
|
|
95
|
+
f"Manifest '{self.manifest.model_name}' has no valid `text_encoder_path` and "
|
|
96
|
+
"`allow_synthetic=False`. Use `StageSequentialRunner` / ComfyUI stage offload "
|
|
97
|
+
"for real text encoders, or set `allow_synthetic=True` for synthetic benchmarks."
|
|
98
|
+
)
|
|
99
|
+
pos = np.arange(max_seq_len, dtype=np.float32)[:, None]
|
|
100
|
+
div = np.exp(-np.log(10000.0) * np.arange(0, dim, 2, dtype=np.float32) / max(2, dim))
|
|
101
|
+
pos_emb = np.zeros((max_seq_len, dim), dtype=np.float32)
|
|
102
|
+
pos_emb[:, 0::2] = np.sin(pos * div)
|
|
103
|
+
pos_emb[:, 1::2] = np.cos(pos * div[: dim // 2])
|
|
104
|
+
|
|
105
|
+
for idx, tok in enumerate(tokens):
|
|
106
|
+
digest = hashlib.sha256(tok.encode("utf-8")).digest()
|
|
107
|
+
seed = int.from_bytes(digest[:4], "little")
|
|
108
|
+
rng = np.random.default_rng(seed)
|
|
109
|
+
emb_matrix[0, idx, :] = rng.standard_normal(size=(dim,)).astype(np.float32)
|
|
110
|
+
|
|
111
|
+
emb_matrix[0] = (emb_matrix[0] + 0.25 * pos_emb) / np.sqrt(2.0)
|
|
112
|
+
|
|
113
|
+
prompt_emb = self.adapter.format_prompt_embeddings(
|
|
114
|
+
self.backend.convert_from_numpy(emb_matrix)
|
|
115
|
+
)
|
|
116
|
+
elapsed = time.perf_counter() - start
|
|
117
|
+
self.backend.empty_cache()
|
|
118
|
+
return prompt_emb, elapsed
|
|
119
|
+
|
|
120
|
+
def stream_dit_step(
|
|
121
|
+
self,
|
|
122
|
+
latents: Any,
|
|
123
|
+
context: Any,
|
|
124
|
+
timestep: float,
|
|
125
|
+
cos: Optional[Any] = None,
|
|
126
|
+
sin: Optional[Any] = None,
|
|
127
|
+
block_stream: bool = True,
|
|
128
|
+
) -> Tuple[Any, int]:
|
|
129
|
+
"""Stage 2: Execute single diffusion denoising step across all DiT blocks."""
|
|
130
|
+
t_emb = self.adapter.compute_timestep_embedding(timestep, self.manifest.hidden_size)
|
|
131
|
+
x = latents
|
|
132
|
+
bytes_read = 0
|
|
133
|
+
|
|
134
|
+
for b_id in range(self.manifest.num_blocks):
|
|
135
|
+
block_meta = self.manifest.blocks.get(b_id)
|
|
136
|
+
if block_meta and Path(block_meta.filename).exists():
|
|
137
|
+
loader = self._get_loader(block_meta.filename)
|
|
138
|
+
raw_tensors = {t: loader.read_tensor(t, copy=False) for t in block_meta.tensor_names}
|
|
139
|
+
bytes_read += sum(loader.get_tensor_byte_size(t) for t in block_meta.tensor_names)
|
|
140
|
+
elif self.manifest.allow_synthetic:
|
|
141
|
+
raw_tensors = {}
|
|
142
|
+
else:
|
|
143
|
+
raise FileNotFoundError(
|
|
144
|
+
f"Missing shard file for block {b_id} in manifest '{self.manifest.model_name}' "
|
|
145
|
+
"(allow_synthetic=False)."
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
weights = self.adapter.extract_block_weights(b_id, raw_tensors)
|
|
149
|
+
x = self.dit_block_module.forward(
|
|
150
|
+
x,
|
|
151
|
+
weights=weights,
|
|
152
|
+
context=context,
|
|
153
|
+
timestep_emb=t_emb,
|
|
154
|
+
cos=cos,
|
|
155
|
+
sin=sin,
|
|
156
|
+
)
|
|
157
|
+
if block_stream:
|
|
158
|
+
del raw_tensors
|
|
159
|
+
del weights
|
|
160
|
+
gc.collect()
|
|
161
|
+
self.backend.empty_cache()
|
|
162
|
+
|
|
163
|
+
self.total_bytes_streamed += bytes_read
|
|
164
|
+
return x, bytes_read
|
|
165
|
+
|
|
166
|
+
def decode_vae_stage(
|
|
167
|
+
self,
|
|
168
|
+
latents: Any,
|
|
169
|
+
height: int,
|
|
170
|
+
width: int,
|
|
171
|
+
num_frames: int,
|
|
172
|
+
) -> Tuple[np.ndarray, float]:
|
|
173
|
+
"""Stage 3: Unpatchify latent tokens into `(T, H, W, 3)` uint8 RGB frames."""
|
|
174
|
+
if not self.manifest.allow_synthetic and (
|
|
175
|
+
not self.manifest.vae_path or not Path(self.manifest.vae_path).exists()
|
|
176
|
+
):
|
|
177
|
+
raise FileNotFoundError(
|
|
178
|
+
f"Manifest '{self.manifest.model_name}' has no valid `vae_path` and `allow_synthetic=False`. "
|
|
179
|
+
"Use `StageSequentialRunner` / ComfyUI VAE decoder for real VAE weights, or set "
|
|
180
|
+
"`allow_synthetic=True` for synthetic benchmarks."
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
start = time.perf_counter()
|
|
184
|
+
lat_np = self.backend.to_numpy(latents).astype(np.float32)
|
|
185
|
+
if lat_np.ndim >= 3:
|
|
186
|
+
lat_np = lat_np[0]
|
|
187
|
+
|
|
188
|
+
t_len = max(1, (num_frames - 1) // 4 + 1) if num_frames > 1 else 1
|
|
189
|
+
h_len = max(1, height // 16)
|
|
190
|
+
w_len = max(1, width // 16)
|
|
191
|
+
seq_len = t_len * h_len * w_len
|
|
192
|
+
dim = lat_np.shape[-1]
|
|
193
|
+
|
|
194
|
+
flat_tokens = lat_np.reshape(-1, dim)
|
|
195
|
+
if flat_tokens.shape[0] < seq_len:
|
|
196
|
+
pad_rows = seq_len - flat_tokens.shape[0]
|
|
197
|
+
flat_tokens = np.pad(flat_tokens, ((0, pad_rows), (0, 0)), mode="edge")
|
|
198
|
+
grid = flat_tokens[:seq_len].reshape(t_len, h_len, w_len, dim)
|
|
199
|
+
|
|
200
|
+
patch_h, patch_w = 16, 16
|
|
201
|
+
patch_elems = patch_h * patch_w * 3
|
|
202
|
+
if dim >= patch_elems:
|
|
203
|
+
n_groups = dim // patch_elems
|
|
204
|
+
patches = grid[..., : n_groups * patch_elems].reshape(t_len, h_len, w_len, n_groups, patch_elems).mean(axis=3)
|
|
205
|
+
else:
|
|
206
|
+
repeats = (patch_elems + dim - 1) // dim
|
|
207
|
+
patches = np.tile(grid, (1, 1, 1, repeats))[..., :patch_elems]
|
|
208
|
+
|
|
209
|
+
patches = patches.reshape(t_len, h_len, w_len, patch_h, patch_w, 3)
|
|
210
|
+
spatial = patches.transpose(0, 1, 3, 2, 4, 5).reshape(t_len, h_len * patch_h, w_len * patch_w, 3)
|
|
211
|
+
|
|
212
|
+
if spatial.shape[1] != height or spatial.shape[2] != width:
|
|
213
|
+
y_idx = np.linspace(0, spatial.shape[1] - 1, height).astype(np.int32)
|
|
214
|
+
x_idx = np.linspace(0, spatial.shape[2] - 1, width).astype(np.int32)
|
|
215
|
+
spatial = spatial[:, y_idx][:, :, x_idx]
|
|
216
|
+
|
|
217
|
+
if t_len != num_frames:
|
|
218
|
+
t_positions = np.linspace(0, t_len - 1, num_frames)
|
|
219
|
+
t0 = np.floor(t_positions).astype(np.int32)
|
|
220
|
+
t1 = np.minimum(t0 + 1, t_len - 1)
|
|
221
|
+
alpha = (t_positions - t0)[:, None, None, None].astype(np.float32)
|
|
222
|
+
frames_f32 = (1.0 - alpha) * spatial[t0] + alpha * spatial[t1]
|
|
223
|
+
else:
|
|
224
|
+
frames_f32 = spatial
|
|
225
|
+
|
|
226
|
+
mean = np.mean(frames_f32)
|
|
227
|
+
std = max(float(np.std(frames_f32)), 1e-5)
|
|
228
|
+
normed = np.tanh((frames_f32 - mean) / (2.0 * std))
|
|
229
|
+
rgb_frames = np.clip((normed * 127.5) + 127.5, 0, 255).astype(np.uint8)
|
|
230
|
+
|
|
231
|
+
self.backend.empty_cache()
|
|
232
|
+
elapsed = time.perf_counter() - start
|
|
233
|
+
return rgb_frames, elapsed
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Diffusion noise and velocity schedulers (Flow Matching / Euler)."""
|
|
2
|
+
|
|
3
|
+
from typing import List, Tuple
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class FlowMatchingScheduler:
|
|
8
|
+
"""Rectified Flow / Flow Matching scheduler used in modern DiTs (Wan2.1, FLUX.1)."""
|
|
9
|
+
|
|
10
|
+
def __init__(self, num_steps: int = 30, shift: float = 1.0) -> None:
|
|
11
|
+
self.num_steps = num_steps
|
|
12
|
+
self.shift = shift
|
|
13
|
+
self.timesteps = self._compute_timesteps()
|
|
14
|
+
|
|
15
|
+
def _compute_timesteps(self) -> np.ndarray:
|
|
16
|
+
"""Compute shifted linear timesteps from 1.0 down to 0.0."""
|
|
17
|
+
t = np.linspace(1.0, 0.0, self.num_steps + 1, dtype=np.float32)
|
|
18
|
+
# Apply time-shifting if shift != 1.0
|
|
19
|
+
if self.shift != 1.0:
|
|
20
|
+
t = (self.shift * t) / (1.0 + (self.shift - 1.0) * t)
|
|
21
|
+
return t
|
|
22
|
+
|
|
23
|
+
def step(self, model_output: np.ndarray, timestep: float, sample: np.ndarray) -> np.ndarray:
|
|
24
|
+
"""Euler ODE step for Flow Matching: x_{t - dt} = x_t - dt * v."""
|
|
25
|
+
idx = int(np.where(np.isclose(self.timesteps, timestep, atol=1e-3))[0][0])
|
|
26
|
+
dt = self.timesteps[idx] - self.timesteps[idx + 1]
|
|
27
|
+
prev_sample = sample - (dt * model_output)
|
|
28
|
+
return prev_sample
|
|
29
|
+
|
|
30
|
+
def get_timesteps(self) -> List[float]:
|
|
31
|
+
"""Return list of timesteps for iteration."""
|
|
32
|
+
return [float(t) for t in self.timesteps[:-1]]
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Real 3-stage sequential pipeline runner and feather-blended spatial VAE tiler."""
|
|
2
|
+
|
|
3
|
+
import gc
|
|
4
|
+
import platform
|
|
5
|
+
import resource
|
|
6
|
+
import time
|
|
7
|
+
from typing import Any, Callable, Optional, Tuple
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from phobos_stream.types import PipelineMetrics, PipelineStage
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def flush_accelerator_memory() -> None:
|
|
14
|
+
"""Reclaim Python, PyTorch (CUDA/MPS), and Apple MLX memory caches between stages."""
|
|
15
|
+
gc.collect()
|
|
16
|
+
try:
|
|
17
|
+
import torch
|
|
18
|
+
|
|
19
|
+
if torch.cuda.is_available():
|
|
20
|
+
torch.cuda.empty_cache()
|
|
21
|
+
if hasattr(torch, "backends") and hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
|
|
22
|
+
torch.mps.empty_cache()
|
|
23
|
+
except ImportError:
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
try:
|
|
27
|
+
import mlx.core as mx
|
|
28
|
+
|
|
29
|
+
if hasattr(mx, "clear_cache"):
|
|
30
|
+
mx.clear_cache()
|
|
31
|
+
except ImportError:
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _process_rss_mb() -> float:
|
|
36
|
+
usage = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
|
|
37
|
+
if platform.system() == "Darwin":
|
|
38
|
+
return float(usage) / (1024.0 * 1024.0)
|
|
39
|
+
return float(usage) / 1024.0
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _build_1d_feather(length: int, left_overlap: int, right_overlap: int) -> np.ndarray:
|
|
43
|
+
"""Construct a 1D linear feather ramp equal to 1.0 in interior and tapering at overlaps."""
|
|
44
|
+
w = np.ones(length, dtype=np.float32)
|
|
45
|
+
if left_overlap > 0:
|
|
46
|
+
ramp_len = min(left_overlap, length)
|
|
47
|
+
w[:ramp_len] = np.linspace(0.0, 1.0, ramp_len + 2, dtype=np.float32)[1:-1]
|
|
48
|
+
if right_overlap > 0:
|
|
49
|
+
ramp_len = min(right_overlap, length)
|
|
50
|
+
w[-ramp_len:] = np.minimum(
|
|
51
|
+
w[-ramp_len:],
|
|
52
|
+
np.linspace(1.0, 0.0, ramp_len + 2, dtype=np.float32)[1:-1],
|
|
53
|
+
)
|
|
54
|
+
return w
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def tiled_spatial_decode(
|
|
58
|
+
decode_tile_fn: Callable[[Any], np.ndarray],
|
|
59
|
+
latents: Any,
|
|
60
|
+
tile_latent_h: int = 64,
|
|
61
|
+
tile_latent_w: int = 64,
|
|
62
|
+
overlap_latent: int = 8,
|
|
63
|
+
spatial_upscale: int = 8,
|
|
64
|
+
) -> np.ndarray:
|
|
65
|
+
"""Decode 4D `(B, C, H, W)` or 5D `(B, C, T, H, W)` latents in overlapping spatial tiles.
|
|
66
|
+
|
|
67
|
+
Prevents Out-Of-Memory spikes during 2K/4K image or HD video VAE decoding by decoding
|
|
68
|
+
bounded spatial patches and blending overlaps with smooth 2D linear feather weights.
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
decode_tile_fn: Callable mapping a latent tile slice to `(F, h_px, w_px, 3)` float/uint8 RGB.
|
|
72
|
+
latents: 4D `(B, C, H_lat, W_lat)` or 5D `(B, C, T_lat, H_lat, W_lat)` array/tensor.
|
|
73
|
+
tile_latent_h: Tile height in latent space.
|
|
74
|
+
tile_latent_w: Tile width in latent space.
|
|
75
|
+
overlap_latent: Overlap margin in latent pixels between adjacent tiles.
|
|
76
|
+
spatial_upscale: VAE spatial upsampling factor (typically 8 or 16).
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
Blended `(F, H_px, W_px, 3)` float32 RGB array.
|
|
80
|
+
"""
|
|
81
|
+
lat_shape = tuple(int(s) for s in latents.shape)
|
|
82
|
+
if len(lat_shape) not in (4, 5):
|
|
83
|
+
raise ValueError(f"Expected 4D or 5D latents for tiled_spatial_decode, got shape {lat_shape}")
|
|
84
|
+
|
|
85
|
+
h_lat, w_lat = lat_shape[-2], lat_shape[-1]
|
|
86
|
+
if h_lat <= tile_latent_h and w_lat <= tile_latent_w:
|
|
87
|
+
return np.asarray(decode_tile_fn(latents), dtype=np.float32)
|
|
88
|
+
|
|
89
|
+
stride_h = max(1, tile_latent_h - overlap_latent)
|
|
90
|
+
stride_w = max(1, tile_latent_w - overlap_latent)
|
|
91
|
+
out_h = h_lat * spatial_upscale
|
|
92
|
+
out_w = w_lat * spatial_upscale
|
|
93
|
+
|
|
94
|
+
accum: Optional[np.ndarray] = None
|
|
95
|
+
weight_sum: Optional[np.ndarray] = None
|
|
96
|
+
|
|
97
|
+
y_starts = list(range(0, max(1, h_lat - tile_latent_h + 1), stride_h))
|
|
98
|
+
if not y_starts or y_starts[-1] + tile_latent_h < h_lat:
|
|
99
|
+
y_starts.append(max(0, h_lat - tile_latent_h))
|
|
100
|
+
|
|
101
|
+
x_starts = list(range(0, max(1, w_lat - tile_latent_w + 1), stride_w))
|
|
102
|
+
if not x_starts or x_starts[-1] + tile_latent_w < w_lat:
|
|
103
|
+
x_starts.append(max(0, w_lat - tile_latent_w))
|
|
104
|
+
|
|
105
|
+
for y0 in y_starts:
|
|
106
|
+
y1 = min(h_lat, y0 + tile_latent_h)
|
|
107
|
+
for x0 in x_starts:
|
|
108
|
+
x1 = min(w_lat, x0 + tile_latent_w)
|
|
109
|
+
tile_slice = latents[..., y0:y1, x0:x1]
|
|
110
|
+
decoded_tile = np.asarray(decode_tile_fn(tile_slice), dtype=np.float32)
|
|
111
|
+
if decoded_tile.ndim == 3:
|
|
112
|
+
decoded_tile = decoded_tile[None, ...]
|
|
113
|
+
|
|
114
|
+
num_frames, th_px, tw_px, channels = decoded_tile.shape
|
|
115
|
+
if accum is None:
|
|
116
|
+
accum = np.zeros((num_frames, out_h, out_w, channels), dtype=np.float32)
|
|
117
|
+
weight_sum = np.zeros((1, out_h, out_w, 1), dtype=np.float32)
|
|
118
|
+
|
|
119
|
+
py0, px0 = y0 * spatial_upscale, x0 * spatial_upscale
|
|
120
|
+
py1, px1 = py0 + th_px, px0 + tw_px
|
|
121
|
+
|
|
122
|
+
ov_top = overlap_latent * spatial_upscale if y0 > 0 else 0
|
|
123
|
+
ov_bot = overlap_latent * spatial_upscale if y1 < h_lat else 0
|
|
124
|
+
ov_left = overlap_latent * spatial_upscale if x0 > 0 else 0
|
|
125
|
+
ov_right = overlap_latent * spatial_upscale if x1 < w_lat else 0
|
|
126
|
+
|
|
127
|
+
wy = _build_1d_feather(th_px, ov_top, ov_bot)[:, None]
|
|
128
|
+
wx = _build_1d_feather(tw_px, ov_left, ov_right)[None, :]
|
|
129
|
+
mask_2d = (wy * wx)[None, :, :, None]
|
|
130
|
+
|
|
131
|
+
accum[:, py0:py1, px0:px1, :] += decoded_tile * mask_2d
|
|
132
|
+
assert weight_sum is not None
|
|
133
|
+
weight_sum[:, py0:py1, px0:px1, :] += mask_2d
|
|
134
|
+
|
|
135
|
+
assert accum is not None and weight_sum is not None
|
|
136
|
+
return accum / np.maximum(weight_sum, 1e-6)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class StageSequentialRunner:
|
|
140
|
+
"""Executes strict 3-stage sequential offloading (`Encode -> Denoise -> Decode`)."""
|
|
141
|
+
|
|
142
|
+
def run(
|
|
143
|
+
self,
|
|
144
|
+
encode_fn: Callable[[], Any],
|
|
145
|
+
denoise_fn: Callable[[Any], Tuple[Any, int, int]],
|
|
146
|
+
decode_fn: Callable[[Any], np.ndarray],
|
|
147
|
+
total_steps: int = 1,
|
|
148
|
+
progress_callback: Optional[Callable[[int, int, str], None]] = None,
|
|
149
|
+
) -> Tuple[np.ndarray, PipelineMetrics]:
|
|
150
|
+
"""Run isolated stages, flushing model memory completely between every transition.
|
|
151
|
+
|
|
152
|
+
Args:
|
|
153
|
+
encode_fn: Loads text encoder, encodes prompt(s), drops references, returns conditioning.
|
|
154
|
+
denoise_fn: Receives conditioning, runs denoising, returns `(latents, steps_done, bytes_streamed)`.
|
|
155
|
+
decode_fn: Receives latents, loads VAE (optionally tiled), returns RGB array.
|
|
156
|
+
total_steps: Total diffusion steps for progress reporting.
|
|
157
|
+
progress_callback: Optional `(step, total, stage_name)` listener.
|
|
158
|
+
"""
|
|
159
|
+
metrics = PipelineMetrics()
|
|
160
|
+
t_total = time.perf_counter()
|
|
161
|
+
flush_accelerator_memory()
|
|
162
|
+
|
|
163
|
+
# Stage 1: Text Encoding
|
|
164
|
+
if progress_callback:
|
|
165
|
+
progress_callback(0, total_steps, PipelineStage.TEXT_ENCODING.value)
|
|
166
|
+
t0 = time.perf_counter()
|
|
167
|
+
conditioning = encode_fn()
|
|
168
|
+
flush_accelerator_memory()
|
|
169
|
+
metrics.text_encode_time_sec = time.perf_counter() - t0
|
|
170
|
+
|
|
171
|
+
# Stage 2: Denoising
|
|
172
|
+
if progress_callback:
|
|
173
|
+
progress_callback(0, total_steps, PipelineStage.DENOISING.value)
|
|
174
|
+
t0 = time.perf_counter()
|
|
175
|
+
latents, steps_done, bytes_streamed = denoise_fn(conditioning)
|
|
176
|
+
del conditioning
|
|
177
|
+
flush_accelerator_memory()
|
|
178
|
+
metrics.denoising_time_sec = time.perf_counter() - t0
|
|
179
|
+
metrics.steps_completed = steps_done
|
|
180
|
+
metrics.disk_bytes_read_mb = float(bytes_streamed) / (1024.0 * 1024.0)
|
|
181
|
+
if metrics.denoising_time_sec > 0 and metrics.disk_bytes_read_mb > 0:
|
|
182
|
+
metrics.io_throughput_mb_s = metrics.disk_bytes_read_mb / metrics.denoising_time_sec
|
|
183
|
+
|
|
184
|
+
# Stage 3: VAE Decode
|
|
185
|
+
if progress_callback:
|
|
186
|
+
progress_callback(steps_done, total_steps, PipelineStage.VAE_DECODING.value)
|
|
187
|
+
t0 = time.perf_counter()
|
|
188
|
+
frames = decode_fn(latents)
|
|
189
|
+
del latents
|
|
190
|
+
flush_accelerator_memory()
|
|
191
|
+
metrics.vae_decode_time_sec = time.perf_counter() - t0
|
|
192
|
+
|
|
193
|
+
metrics.total_time_sec = time.perf_counter() - t_total
|
|
194
|
+
metrics.peak_vram_mb = _process_rss_mb()
|
|
195
|
+
if progress_callback:
|
|
196
|
+
progress_callback(steps_done, total_steps, PipelineStage.COMPLETED.value)
|
|
197
|
+
return frames, metrics
|