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,235 @@
1
+ """Block-level MLX weight mapping, fused kernels, and per-block mmap execution for Z-Image."""
2
+
3
+ from typing import Any, List, Optional, Tuple, Union
4
+
5
+ from phobos_stream.storage.mmap_loader import MMapTensorLoader
6
+
7
+
8
+ def apply_mlx_rope_3d(x: Any, freqs_cis: Any) -> Any:
9
+ """Apply 3D Rotary Position Embedding across `(B, Seq, Heads, HeadDim)` in native dtype."""
10
+ import mlx.core as mx
11
+
12
+ dtype = x.dtype
13
+ b, seq_len, n_heads, head_dim = x.shape
14
+ x_pairs = x.reshape(b, seq_len, n_heads, head_dim // 2, 2)
15
+ fc = freqs_cis[None, :, None, :, :]
16
+ out_r = x_pairs[..., 0] * fc[..., 0] - x_pairs[..., 1] * fc[..., 1]
17
+ out_i = x_pairs[..., 0] * fc[..., 1] + x_pairs[..., 1] * fc[..., 0]
18
+ return mx.stack([out_r, out_i], axis=-1).reshape(b, seq_len, n_heads, head_dim).astype(dtype)
19
+
20
+
21
+ def map_zimage_transformer(
22
+ dit_path: Union[str, Any],
23
+ quantize_bits: Optional[int],
24
+ fuse_blocks: bool,
25
+ ) -> Tuple[Any, Any, Any, Any]:
26
+ """Load `z_image_turbo_bf16.safetensors` into MLX `ZImageTransformer` with optional QKV/W13 fusion."""
27
+ import mlx.core as mx
28
+ import mlx.nn as nn
29
+ from mlx.utils import tree_unflatten
30
+ from mflux.models.z_image.model.z_image_transformer.transformer import ZImageTransformer
31
+
32
+ raw_weights = mx.load(str(dit_path))
33
+ mapped: List[Tuple[str, Any]] = []
34
+ fused_qkv = {}
35
+ w1_map = {}
36
+ w3_map = {}
37
+
38
+ for k, v in raw_weights.items():
39
+ vb = v.astype(mx.bfloat16)
40
+ if k == "t_embedder.mlp.0.weight":
41
+ mapped.append(("t_embedder.linear1.weight", vb))
42
+ elif k == "t_embedder.mlp.0.bias":
43
+ mapped.append(("t_embedder.linear1.bias", vb))
44
+ elif k == "t_embedder.mlp.2.weight":
45
+ mapped.append(("t_embedder.linear2.weight", vb))
46
+ elif k == "t_embedder.mlp.2.bias":
47
+ mapped.append(("t_embedder.linear2.bias", vb))
48
+ elif k in ("x_embedder.weight", "x_embedder.bias"):
49
+ mapped.append((k.replace("x_embedder", "all_x_embedder.2-1"), vb))
50
+ elif k in ("final_layer.linear.weight", "final_layer.linear.bias"):
51
+ mapped.append((k.replace("final_layer", "all_final_layer.2-1"), vb))
52
+ elif k in ("final_layer.adaLN_modulation.1.weight", "final_layer.adaLN_modulation.1.bias"):
53
+ mapped.append((k.replace("final_layer.adaLN_modulation.1", "all_final_layer.2-1.adaLN_modulation.0"), vb))
54
+ elif k.endswith(".attention.qkv.weight"):
55
+ pfx = k[: -len(".attention.qkv.weight")]
56
+ if fuse_blocks and not quantize_bits:
57
+ fused_qkv[pfx] = vb
58
+ else:
59
+ dim = vb.shape[1]
60
+ mapped.extend([
61
+ (f"{pfx}.attention.to_q.weight", vb[:dim]),
62
+ (f"{pfx}.attention.to_k.weight", vb[dim : 2 * dim]),
63
+ (f"{pfx}.attention.to_v.weight", vb[2 * dim : 3 * dim]),
64
+ ])
65
+ elif k.endswith(".feed_forward.w1.weight") and fuse_blocks and not quantize_bits:
66
+ w1_map[k[: -len(".feed_forward.w1.weight")]] = vb
67
+ elif k.endswith(".feed_forward.w3.weight") and fuse_blocks and not quantize_bits:
68
+ w3_map[k[: -len(".feed_forward.w3.weight")]] = vb
69
+ elif k.endswith(".attention.out.weight"):
70
+ mapped.append((k.replace(".attention.out.weight", ".attention.to_out.0.weight"), vb))
71
+ elif k.endswith(".attention.q_norm.weight"):
72
+ mapped.append((k.replace(".attention.q_norm.weight", ".attention.norm_q.weight"), vb))
73
+ elif k.endswith(".attention.k_norm.weight"):
74
+ mapped.append((k.replace(".attention.k_norm.weight", ".attention.norm_k.weight"), vb))
75
+ else:
76
+ mapped.append((k, vb))
77
+ del raw_weights
78
+
79
+ tr = ZImageTransformer()
80
+ tr.set_float32(False)
81
+ tr.update(tree_unflatten(mapped))
82
+ del mapped
83
+
84
+ if quantize_bits in (4, 8):
85
+ nn.quantize(tr, group_size=64, bits=quantize_bits)
86
+ mx.eval(tr.parameters())
87
+ return tr, None, None, None
88
+ if not fuse_blocks:
89
+ mx.eval(tr.parameters())
90
+ return tr, None, None, None
91
+
92
+ def _pack(blk_mod: Any, pfx: str, has_adaln: bool) -> Tuple[Any, Any, Any, bool]:
93
+ qkv_t = mx.contiguous(fused_qkv.pop(pfx).T)
94
+ w13_t = mx.contiguous(mx.concatenate([w1_map.pop(pfx), w3_map.pop(pfx)], axis=0).T)
95
+ blk_mod.attention.to_q = blk_mod.attention.to_k = blk_mod.attention.to_v = None
96
+ blk_mod.feed_forward.w1 = blk_mod.feed_forward.w3 = None
97
+ return (blk_mod, qkv_t, w13_t, has_adaln)
98
+
99
+ nr = [_pack(tr.noise_refiner[i], f"noise_refiner.{i}", True) for i in range(2)]
100
+ cr = [_pack(tr.context_refiner[i], f"context_refiner.{i}", False) for i in range(2)]
101
+ ly = [_pack(tr.layers[i], f"layers.{i}", True) for i in range(30)]
102
+ mx.eval(tr.parameters(), *[b[1] for b in nr + cr + ly], *[b[2] for b in nr + cr + ly])
103
+ return tr, nr, cr, ly
104
+
105
+
106
+ def exec_fused_zimage_block(
107
+ blk_tuple: Tuple[Any, Any, Any, bool],
108
+ x: Any,
109
+ freqs: Any,
110
+ t_emb: Optional[Any],
111
+ ) -> Any:
112
+ """Execute a pre-fused QKV + W13 Z-Image block using unmasked Metal FlashAttention."""
113
+ import mlx.core as mx
114
+ import mlx.nn as nn
115
+ from mlx.core.fast import scaled_dot_product_attention
116
+
117
+ mod, qkv_t, w13_t, has_adaln = blk_tuple
118
+ b, seq_len, _ = x.shape
119
+ n_heads, head_dim, dim = mod.attention.n_heads, mod.attention.head_dim, mod.attention.dim
120
+ if has_adaln and t_emb is not None:
121
+ scale_msa, gate_msa, scale_mlp, gate_mlp = mx.split(
122
+ mx.expand_dims(mod.adaLN_modulation[0](t_emb), axis=1), 4, axis=2
123
+ )
124
+ norm1_x = mod.attention_norm1(x) * (1.0 + scale_msa)
125
+ else:
126
+ norm1_x = mod.attention_norm1(x)
127
+
128
+ q, k, v = mx.split(mx.matmul(norm1_x, qkv_t), 3, axis=-1)
129
+ q = apply_mlx_rope_3d(mod.attention.norm_q(q.reshape(b, seq_len, n_heads, head_dim)), freqs)
130
+ k = apply_mlx_rope_3d(mod.attention.norm_k(k.reshape(b, seq_len, n_heads, head_dim)), freqs)
131
+ v = (v * 0.25).reshape(b, seq_len, n_heads, head_dim)
132
+ attn = scaled_dot_product_attention(
133
+ mx.transpose(q, (0, 2, 1, 3)),
134
+ mx.transpose(k, (0, 2, 1, 3)),
135
+ mx.transpose(v, (0, 2, 1, 3)),
136
+ scale=mod.attention.scale,
137
+ mask=None,
138
+ )
139
+ attn = mod.attention.to_out[0](mx.transpose(attn, (0, 2, 1, 3)).reshape(b, seq_len, dim)) * 4.0
140
+
141
+ if has_adaln and t_emb is not None:
142
+ x = x + mx.tanh(gate_msa) * mod.attention_norm2(attn)
143
+ gate, up = mx.split(mx.matmul(mod.ffn_norm1(x) * (1.0 + scale_mlp), w13_t), 2, axis=-1)
144
+ ffn = mod.feed_forward.w2(nn.silu(gate) * up)
145
+ return x + mx.tanh(gate_mlp) * mod.ffn_norm2(ffn)
146
+ x = x + mod.attention_norm2(attn)
147
+ gate, up = mx.split(mx.matmul(mod.ffn_norm1(x), w13_t), 2, axis=-1)
148
+ ffn = mod.feed_forward.w2(nn.silu(gate) * up)
149
+ return x + mod.ffn_norm2(ffn)
150
+
151
+
152
+ def stream_single_zimage_block_mmap(
153
+ loader: MMapTensorLoader,
154
+ prefix: str,
155
+ x: Any,
156
+ freqs_cis: Any,
157
+ t_emb: Optional[Any],
158
+ has_adaln: bool,
159
+ ) -> Tuple[Any, int]:
160
+ """Stream 1 Z-Image DiT block via `MMapTensorLoader`, execute on Metal, evaluate, and evict."""
161
+ import mlx.core as mx
162
+ import mlx.nn as nn
163
+ from mlx.core.fast import rms_norm, scaled_dot_product_attention
164
+
165
+ b, seq_len, dim = x.shape
166
+ n_heads, head_dim = 30, 128
167
+ bytes_read = 0
168
+
169
+ def rd(suffix: str) -> Any:
170
+ nonlocal bytes_read
171
+ key = f"{prefix}.{suffix}"
172
+ bytes_read += loader.get_tensor_byte_size(key)
173
+ return loader.read_mlx_array(key, target_dtype=mx.bfloat16)
174
+
175
+ norm1_w = rd("attention_norm1.weight")
176
+ if has_adaln and t_emb is not None:
177
+ ada_w, ada_b = rd("adaLN_modulation.0.weight"), rd("adaLN_modulation.0.bias")
178
+ scale_msa, gate_msa, scale_mlp, gate_mlp = mx.split(
179
+ mx.expand_dims(mx.matmul(t_emb, ada_w.T) + ada_b, axis=1), 4, axis=2
180
+ )
181
+ del ada_w, ada_b
182
+ norm1_x = rms_norm(x, norm1_w, 1e-5) * (1.0 + scale_msa)
183
+ else:
184
+ norm1_x = rms_norm(x, norm1_w, 1e-5)
185
+ del norm1_w
186
+
187
+ qkv_w = rd("attention.qkv.weight")
188
+ q, k, v = mx.split(mx.matmul(norm1_x, qkv_w.T), 3, axis=-1)
189
+ del qkv_w, norm1_x
190
+
191
+ qn_w, kn_w = rd("attention.q_norm.weight"), rd("attention.k_norm.weight")
192
+ q = apply_mlx_rope_3d(rms_norm(q.reshape(b, seq_len, n_heads, head_dim), qn_w, 1e-5), freqs_cis)
193
+ k = apply_mlx_rope_3d(rms_norm(k.reshape(b, seq_len, n_heads, head_dim), kn_w, 1e-5), freqs_cis)
194
+ del qn_w, kn_w
195
+ v = (v * 0.25).reshape(b, seq_len, n_heads, head_dim)
196
+
197
+ attn = scaled_dot_product_attention(
198
+ mx.transpose(q, (0, 2, 1, 3)),
199
+ mx.transpose(k, (0, 2, 1, 3)),
200
+ mx.transpose(v, (0, 2, 1, 3)),
201
+ scale=head_dim ** -0.5,
202
+ mask=None,
203
+ )
204
+ del q, k, v
205
+ out_w = rd("attention.out.weight")
206
+ attn = mx.matmul(mx.transpose(attn, (0, 2, 1, 3)).reshape(b, seq_len, dim), out_w.T) * 4.0
207
+ del out_w
208
+
209
+ norm2_w, ffn1_w, ffn2_w = rd("attention_norm2.weight"), rd("ffn_norm1.weight"), rd("ffn_norm2.weight")
210
+ if has_adaln and t_emb is not None:
211
+ x = x + mx.tanh(gate_msa) * rms_norm(attn, norm2_w, 1e-5)
212
+ ffn_in = rms_norm(x, ffn1_w, 1e-5) * (1.0 + scale_mlp)
213
+ else:
214
+ x = x + rms_norm(attn, norm2_w, 1e-5)
215
+ ffn_in = rms_norm(x, ffn1_w, 1e-5)
216
+ del attn, norm2_w, ffn1_w
217
+
218
+ w1, w3 = rd("feed_forward.w1.weight"), rd("feed_forward.w3.weight")
219
+ hidden = nn.silu(mx.matmul(ffn_in, w1.T)) * mx.matmul(ffn_in, w3.T)
220
+ del w1, w3, ffn_in
221
+ w2 = rd("feed_forward.w2.weight")
222
+ ffn_out = mx.matmul(hidden, w2.T)
223
+ del w2, hidden
224
+
225
+ x = (
226
+ x + mx.tanh(gate_mlp) * rms_norm(ffn_out, ffn2_w, 1e-5)
227
+ if (has_adaln and t_emb is not None)
228
+ else x + rms_norm(ffn_out, ffn2_w, 1e-5)
229
+ )
230
+ del ffn_out, ffn2_w
231
+
232
+ mx.eval(x)
233
+ if hasattr(mx, "clear_cache"):
234
+ mx.clear_cache()
235
+ return x, bytes_read
@@ -0,0 +1,98 @@
1
+ """Apple Silicon MLX Strip-VAE weight mapper and decoder for BFL / Z-Image `ae.safetensors`."""
2
+
3
+ from pathlib import Path
4
+ from typing import Any, List, Tuple, Union
5
+ import numpy as np
6
+
7
+
8
+ def load_mlx_flux_vae(vae_path: Union[str, Path], low_memory: bool = True) -> Any:
9
+ """Load `ae.safetensors` decoder weights into an `mflux` VAE with optional strip decoding."""
10
+ import mlx.core as mx
11
+ from mlx.utils import tree_unflatten
12
+ from mflux.models.common.vae.block_decoder import VAEBlockDecoder
13
+ from mflux.models.z_image.model.z_image_vae.vae import VAE
14
+
15
+ raw_vae = mx.load(str(vae_path))
16
+ mapped: List[Tuple[str, Any]] = []
17
+
18
+ def _tr_conv(w: Any) -> Any:
19
+ return mx.transpose(w, (0, 2, 3, 1)) if w.ndim == 4 else w
20
+
21
+ for k, v in raw_vae.items():
22
+ if not k.startswith("decoder."):
23
+ continue
24
+ vb = v.astype(mx.bfloat16)
25
+ if k in ("decoder.conv_in.weight", "decoder.conv_out.weight"):
26
+ mapped.append((k.replace(".weight", ".conv.weight"), _tr_conv(vb)))
27
+ elif k in ("decoder.conv_in.bias", "decoder.conv_out.bias"):
28
+ mapped.append((k.replace(".bias", ".conv.bias"), vb))
29
+ elif k.startswith("decoder.norm_out."):
30
+ mapped.append((k.replace("decoder.norm_out.", "decoder.conv_norm_out.norm."), vb))
31
+ elif k.startswith("decoder.mid.block_"):
32
+ idx = int(k.split(".")[2].split("_")[1]) - 1
33
+ rest = ".".join(k.split(".")[3:])
34
+ mapped.append(
35
+ (
36
+ f"decoder.mid_block.resnets.{idx}.{rest}",
37
+ _tr_conv(vb) if rest.endswith(".weight") and vb.ndim == 4 else vb,
38
+ )
39
+ )
40
+ elif k.startswith("decoder.mid.attn_1."):
41
+ sub = k.removeprefix("decoder.mid.attn_1.")
42
+ if sub.startswith("norm."):
43
+ mapped.append((f"decoder.mid_block.attentions.0.group_{sub}", vb))
44
+ elif sub.startswith(("q.", "k.", "v.")):
45
+ qn, pt = sub.split(".")
46
+ val = vb.squeeze(-1).squeeze(-1) if vb.ndim == 4 else vb
47
+ mapped.append((f"decoder.mid_block.attentions.0.to_{qn}.{pt}", val))
48
+ elif sub.startswith("proj_out."):
49
+ pt = sub.split(".")[1]
50
+ val = vb.squeeze(-1).squeeze(-1) if vb.ndim == 4 else vb
51
+ mapped.append((f"decoder.mid_block.attentions.0.to_out.0.{pt}", val))
52
+ elif k.startswith("decoder.up."):
53
+ parts = k.split(".")
54
+ b_idx = 3 - int(parts[2])
55
+ if parts[3] == "block":
56
+ r_idx = int(parts[4])
57
+ rest = ".".join(parts[5:]).replace("nin_shortcut", "conv_shortcut")
58
+ mapped.append(
59
+ (
60
+ f"decoder.up_blocks.{b_idx}.resnets.{r_idx}.{rest}",
61
+ _tr_conv(vb) if rest.endswith(".weight") and vb.ndim == 4 else vb,
62
+ )
63
+ )
64
+ elif parts[3] == "upsample":
65
+ rest = ".".join(parts[4:])
66
+ mapped.append(
67
+ (
68
+ f"decoder.up_blocks.{b_idx}.upsamplers.0.{rest}",
69
+ _tr_conv(vb) if rest.endswith(".weight") and vb.ndim == 4 else vb,
70
+ )
71
+ )
72
+
73
+ del raw_vae
74
+ vae = VAE()
75
+ if low_memory:
76
+ vae.decode_mode = VAEBlockDecoder.LOW_MEMORY
77
+ vae.update(tree_unflatten(mapped))
78
+ mx.eval(vae.parameters())
79
+ return vae
80
+
81
+
82
+ def decode_mlx_latents_to_uint8(vae: Any, latents_unpacked: Any) -> np.ndarray:
83
+ """Decode unpacked MLX latents into an `(H, W, 3)` uint8 RGB array."""
84
+ import mlx.core as mx
85
+ from mflux.models.common.vae.vae_util import VAEUtil
86
+
87
+ decoded = VAEUtil.decode(vae=vae, latent=latents_unpacked, tiling_config=None)
88
+ mx.eval(decoded)
89
+ if decoded.ndim == 5:
90
+ decoded = decoded[0, :, 0, :, :]
91
+ elif decoded.ndim == 4:
92
+ decoded = decoded[0]
93
+ img_mx = mx.transpose(
94
+ mx.clip((decoded.astype(mx.float32) + 1.0) * 127.5, 0.0, 255.0).astype(mx.uint8),
95
+ (1, 2, 0),
96
+ )
97
+ mx.eval(img_mx)
98
+ return np.array(img_mx)
@@ -0,0 +1,17 @@
1
+ """FastAPI server and schemas for image/video generation."""
2
+
3
+ from phobos_stream.server.app import create_app
4
+ from phobos_stream.server.schemas import (
5
+ ImageGenerationRequest,
6
+ ImageGenerationResponse,
7
+ VideoGenerationRequest,
8
+ VideoGenerationResponse,
9
+ )
10
+
11
+ __all__ = [
12
+ "ImageGenerationRequest",
13
+ "ImageGenerationResponse",
14
+ "VideoGenerationRequest",
15
+ "VideoGenerationResponse",
16
+ "create_app",
17
+ ]
@@ -0,0 +1,192 @@
1
+ """FastAPI gateway exposing OpenAI/Sora compatible image & video generation APIs."""
2
+
3
+ import asyncio
4
+ import base64
5
+ from pathlib import Path
6
+ import time
7
+ from typing import Any, Dict, List, Optional
8
+ import uuid
9
+ from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
10
+ from fastapi.middleware.cors import CORSMiddleware
11
+ from fastapi.staticfiles import StaticFiles
12
+
13
+ from phobos_stream.adapters.factory import get_adapter
14
+ from phobos_stream.media import encode_png_bytes, save_rgb_mp4, save_rgb_png
15
+ from phobos_stream.pipeline.stream_engine import PhobosStreamEngine
16
+ from phobos_stream.server.schemas import (
17
+ GenerationData,
18
+ ImageGenerationRequest,
19
+ ImageGenerationResponse,
20
+ VideoGenerationRequest,
21
+ VideoGenerationResponse,
22
+ )
23
+ from phobos_stream.server.ws_progress import ProgressManager
24
+ from phobos_stream.storage.layout import ModelShardsManifest
25
+ from phobos_stream.types import BackendType, GenerationConfig
26
+
27
+
28
+ def create_app(
29
+ manifest: Optional[ModelShardsManifest] = None,
30
+ backend_type: BackendType = BackendType.AUTO,
31
+ output_dir: Optional[Path] = None,
32
+ allow_synthetic: bool = False,
33
+ ) -> FastAPI:
34
+ """Factory to create configured FastAPI service."""
35
+ app = FastAPI(
36
+ title="PhobosStream API Gateway",
37
+ description="Universal Zero-VRAM Video & Image Diffusion Streaming Engine",
38
+ version="0.1.0",
39
+ )
40
+
41
+ app.add_middleware(
42
+ CORSMiddleware,
43
+ allow_origins=["*"],
44
+ allow_credentials=True,
45
+ allow_methods=["*"],
46
+ allow_headers=["*"],
47
+ )
48
+
49
+ if manifest is None:
50
+ manifest = ModelShardsManifest(
51
+ model_name="wan2.1-streamed",
52
+ architecture="wan2.1",
53
+ num_blocks=4,
54
+ hidden_size=2048,
55
+ allow_synthetic=allow_synthetic,
56
+ )
57
+
58
+ out_dir = Path(output_dir) if output_dir else Path("outputs")
59
+ out_dir.mkdir(parents=True, exist_ok=True)
60
+ app.mount("/outputs", StaticFiles(directory=str(out_dir)), name="outputs")
61
+
62
+ engine = PhobosStreamEngine(manifest=manifest, backend_type=backend_type)
63
+ progress_manager = ProgressManager()
64
+
65
+ def _make_progress_cb() -> Any:
66
+ def _cb(step: int, total: int, stage: str) -> None:
67
+ if not progress_manager.active_connections:
68
+ return
69
+ try:
70
+ loop = asyncio.get_running_loop()
71
+ loop.create_task(progress_manager.broadcast_progress(step, total, stage))
72
+ except RuntimeError:
73
+ asyncio.run(progress_manager.broadcast_progress(step, total, stage))
74
+
75
+ return _cb
76
+
77
+ def _select_model_architecture(model_name: str) -> None:
78
+ if model_name and model_name.lower() != engine.manifest.architecture.lower():
79
+ engine.manifest.architecture = model_name.lower()
80
+ engine.adapter = get_adapter(
81
+ model_name,
82
+ engine.backend,
83
+ hidden_size=engine.manifest.hidden_size,
84
+ allow_synthetic=engine.manifest.allow_synthetic,
85
+ )
86
+ engine.offloader.adapter = engine.adapter
87
+
88
+ @app.get("/health")
89
+ def health_check() -> Dict[str, Any]:
90
+ return {
91
+ "status": "healthy",
92
+ "backend": engine.backend.name,
93
+ "architecture": manifest.architecture,
94
+ "num_blocks": str(manifest.num_blocks),
95
+ "allow_synthetic": manifest.allow_synthetic,
96
+ }
97
+
98
+ @app.get("/v1/models")
99
+ def list_models() -> Dict[str, Any]:
100
+ return {
101
+ "object": "list",
102
+ "data": [
103
+ {"id": "wan2.1", "object": "model", "type": "video", "owned_by": "phobos-stream"},
104
+ {"id": "flux-schnell", "object": "model", "type": "image", "owned_by": "phobos-stream"},
105
+ {"id": "hunyuan-video", "object": "model", "type": "video", "owned_by": "phobos-stream"},
106
+ {"id": "cogvideox", "object": "model", "type": "video", "owned_by": "phobos-stream"},
107
+ ],
108
+ }
109
+
110
+ @app.post("/v1/images/generations", response_model=ImageGenerationResponse)
111
+ def generate_image(req: ImageGenerationRequest) -> ImageGenerationResponse:
112
+ try:
113
+ dims = req.size.lower().split("x")
114
+ width, height = int(dims[0]), int(dims[1])
115
+ except Exception:
116
+ width, height = 1024, 1024
117
+
118
+ _select_model_architecture(req.model)
119
+ base_seed = req.seed if req.seed is not None else 42
120
+ results: List[GenerationData] = []
121
+
122
+ try:
123
+ for idx in range(req.n):
124
+ config = GenerationConfig(
125
+ prompt=req.prompt,
126
+ width=width,
127
+ height=height,
128
+ num_frames=1,
129
+ steps=req.steps,
130
+ seed=base_seed + idx,
131
+ )
132
+ rgb_frames, _ = engine.generate(config, progress_callback=_make_progress_cb())
133
+ png_bytes = encode_png_bytes(rgb_frames[0])
134
+ file_id = f"img_{uuid.uuid4().hex[:10]}.png"
135
+ (out_dir / file_id).write_bytes(png_bytes)
136
+
137
+ results.append(
138
+ GenerationData(
139
+ url=f"/outputs/{file_id}",
140
+ b64_json=base64.b64encode(png_bytes).decode("ascii"),
141
+ revised_prompt=req.prompt,
142
+ )
143
+ )
144
+ except (FileNotFoundError, KeyError, RuntimeError) as exc:
145
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
146
+
147
+ return ImageGenerationResponse(
148
+ created=int(time.time()),
149
+ data=results,
150
+ )
151
+
152
+ @app.post("/v1/videos/generations", response_model=VideoGenerationResponse)
153
+ def generate_video(req: VideoGenerationRequest) -> VideoGenerationResponse:
154
+ _select_model_architecture(req.model)
155
+ config = GenerationConfig(
156
+ prompt=req.prompt,
157
+ width=req.width,
158
+ height=req.height,
159
+ num_frames=req.num_frames,
160
+ fps=req.fps,
161
+ steps=req.steps,
162
+ seed=req.seed if req.seed is not None else 42,
163
+ )
164
+ try:
165
+ rgb_frames, metrics = engine.generate(config, progress_callback=_make_progress_cb())
166
+ except (FileNotFoundError, KeyError, RuntimeError) as exc:
167
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
168
+
169
+ gen_id = f"video_{uuid.uuid4().hex[:10]}"
170
+ save_rgb_mp4(rgb_frames, out_dir / f"{gen_id}.mp4", fps=req.fps)
171
+ save_rgb_png(rgb_frames[0], out_dir / f"{gen_id}.png")
172
+
173
+ return VideoGenerationResponse(
174
+ id=gen_id,
175
+ status="completed",
176
+ created=int(time.time()),
177
+ video_url=f"/outputs/{gen_id}.mp4",
178
+ total_time_sec=round(metrics.total_time_sec, 2),
179
+ peak_vram_mb=round(metrics.peak_vram_mb, 2),
180
+ io_throughput_mb_s=round(metrics.io_throughput_mb_s, 2),
181
+ )
182
+
183
+ @app.websocket("/ws/progress")
184
+ async def websocket_progress(websocket: WebSocket) -> None:
185
+ await progress_manager.connect(websocket)
186
+ try:
187
+ while True:
188
+ await websocket.receive_text()
189
+ except WebSocketDisconnect:
190
+ progress_manager.disconnect(websocket)
191
+
192
+ return app
@@ -0,0 +1,55 @@
1
+ """FastAPI Pydantic schemas for OpenAI-compatible Image & Video generation."""
2
+
3
+ from typing import Any, Dict, List, Optional
4
+ from pydantic import BaseModel, Field
5
+
6
+
7
+ class ImageGenerationRequest(BaseModel):
8
+ """OpenAI-compatible image generation request."""
9
+
10
+ prompt: str = Field(..., description="Text description of the desired image")
11
+ model: str = Field(default="flux", description="Model name (flux, wan2.1, hunyuan)")
12
+ n: int = Field(default=1, ge=1, le=4)
13
+ size: str = Field(default="1024x1024", description="Image resolution (e.g. 1024x1024, 768x1280)")
14
+ steps: int = Field(default=20, ge=1, le=100)
15
+ seed: Optional[int] = Field(default=42)
16
+
17
+
18
+ class VideoGenerationRequest(BaseModel):
19
+ """Video generation request."""
20
+
21
+ prompt: str = Field(..., description="Text description of the desired video")
22
+ model: str = Field(default="wan2.1", description="Model name (wan2.1, hunyuan, cogvideo)")
23
+ height: int = Field(default=720, ge=128, le=2160)
24
+ width: int = Field(default=1280, ge=128, le=3840)
25
+ num_frames: int = Field(default=49, ge=1, le=240)
26
+ fps: int = Field(default=24, ge=8, le=60)
27
+ steps: int = Field(default=30, ge=1, le=100)
28
+ seed: Optional[int] = Field(default=42)
29
+
30
+
31
+ class GenerationData(BaseModel):
32
+ """Output image/video data URL or base64 representation."""
33
+
34
+ url: Optional[str] = None
35
+ b64_json: Optional[str] = None
36
+ revised_prompt: Optional[str] = None
37
+
38
+
39
+ class ImageGenerationResponse(BaseModel):
40
+ """OpenAI-compatible image response."""
41
+
42
+ created: int
43
+ data: List[GenerationData]
44
+
45
+
46
+ class VideoGenerationResponse(BaseModel):
47
+ """Video generation response."""
48
+
49
+ id: str
50
+ status: str
51
+ created: int
52
+ video_url: str
53
+ total_time_sec: float
54
+ peak_vram_mb: float
55
+ io_throughput_mb_s: float
@@ -0,0 +1,36 @@
1
+ """WebSocket progress manager for live generation monitoring."""
2
+
3
+ from typing import List
4
+ import json
5
+ from fastapi import WebSocket
6
+
7
+
8
+ class ProgressManager:
9
+ """Broadcaster tracking active clients and broadcasting generation progress."""
10
+
11
+ def __init__(self) -> None:
12
+ self.active_connections: List[WebSocket] = []
13
+
14
+ async def connect(self, websocket: WebSocket) -> None:
15
+ await websocket.accept()
16
+ self.active_connections.append(websocket)
17
+
18
+ def disconnect(self, websocket: WebSocket) -> None:
19
+ if websocket in self.active_connections:
20
+ self.active_connections.remove(websocket)
21
+
22
+ async def broadcast_progress(self, step: int, total_steps: int, stage: str) -> None:
23
+ message = json.dumps({
24
+ "step": step,
25
+ "total_steps": total_steps,
26
+ "progress_percent": round((step / max(1, total_steps)) * 100, 1),
27
+ "stage": stage,
28
+ })
29
+ disconnected = []
30
+ for connection in self.active_connections:
31
+ try:
32
+ await connection.send_text(message)
33
+ except Exception:
34
+ disconnected.append(connection)
35
+ for dead in disconnected:
36
+ self.disconnect(dead)
@@ -0,0 +1,7 @@
1
+ """Storage, mmap loader, and sharding utilities."""
2
+
3
+ from phobos_stream.storage.layout import BlockMetadata, ModelShardsManifest
4
+ from phobos_stream.storage.mmap_loader import MMapTensorLoader
5
+ from phobos_stream.storage.sharder import DiffusionSharder
6
+
7
+ __all__ = ["BlockMetadata", "DiffusionSharder", "MMapTensorLoader", "ModelShardsManifest"]