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,24 @@
|
|
|
1
|
+
"""PhobosStream: Universal Zero-VRAM Video & Image Diffusion Streaming Engine.
|
|
2
|
+
|
|
3
|
+
Supports Apple Silicon (MLX), NVIDIA CUDA, AMD ROCm, Vulkan, and GGUF quantization.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
__version__ = "0.1.0"
|
|
7
|
+
__author__ = "Martian Academy"
|
|
8
|
+
|
|
9
|
+
from phobos_stream.types import (
|
|
10
|
+
BackendType,
|
|
11
|
+
GenerationConfig,
|
|
12
|
+
ModelArchitecture,
|
|
13
|
+
PipelineMetrics,
|
|
14
|
+
QuantPrecision,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"BackendType",
|
|
19
|
+
"GenerationConfig",
|
|
20
|
+
"ModelArchitecture",
|
|
21
|
+
"PipelineMetrics",
|
|
22
|
+
"QuantPrecision",
|
|
23
|
+
"__version__",
|
|
24
|
+
]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Model architecture adapters mapping safetensors weights to universal DiT blocks."""
|
|
2
|
+
|
|
3
|
+
from phobos_stream.adapters.base import BaseModelAdapter
|
|
4
|
+
from phobos_stream.adapters.cogvideo_adapter import CogVideoXAdapter
|
|
5
|
+
from phobos_stream.adapters.factory import get_adapter
|
|
6
|
+
from phobos_stream.adapters.flux_adapter import FluxAdapter
|
|
7
|
+
from phobos_stream.adapters.hunyuan_adapter import HunyuanAdapter
|
|
8
|
+
from phobos_stream.adapters.wan_adapter import WanAdapter
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"BaseModelAdapter",
|
|
12
|
+
"CogVideoXAdapter",
|
|
13
|
+
"FluxAdapter",
|
|
14
|
+
"HunyuanAdapter",
|
|
15
|
+
"WanAdapter",
|
|
16
|
+
"get_adapter",
|
|
17
|
+
]
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Base model adapter interface for Diffusion Transformer models."""
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
import hashlib
|
|
5
|
+
from typing import Any, Dict, Tuple
|
|
6
|
+
import numpy as np
|
|
7
|
+
from phobos_stream.backends.base import BaseBackend
|
|
8
|
+
from phobos_stream.models.dit_block import DiTBlockWeights
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class BaseModelAdapter(ABC):
|
|
12
|
+
"""Abstract adapter mapping model-specific safetensors weights to DiTBlockWeights."""
|
|
13
|
+
|
|
14
|
+
def __init__(
|
|
15
|
+
self,
|
|
16
|
+
backend: BaseBackend,
|
|
17
|
+
hidden_size: int = 4096,
|
|
18
|
+
allow_synthetic: bool = False,
|
|
19
|
+
) -> None:
|
|
20
|
+
self.backend = backend
|
|
21
|
+
self.hidden_size = hidden_size
|
|
22
|
+
self.allow_synthetic = allow_synthetic
|
|
23
|
+
self._synthetic_cache: Dict[Tuple[int, str, Tuple[int, ...]], Any] = {}
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
@abstractmethod
|
|
27
|
+
def architecture_name(self) -> str:
|
|
28
|
+
"""Name of the model architecture."""
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
def _synthesize_weight(self, block_id: int, suffix: str, shape: Tuple[int, ...]) -> Any:
|
|
32
|
+
"""Synthesize deterministic Xavier-scaled weight ONLY when `allow_synthetic=True`."""
|
|
33
|
+
cache_key = (block_id, suffix, shape)
|
|
34
|
+
if cache_key in self._synthetic_cache:
|
|
35
|
+
return self._synthetic_cache[cache_key]
|
|
36
|
+
|
|
37
|
+
if len(shape) == 1:
|
|
38
|
+
arr = np.ones(shape, dtype=np.float32)
|
|
39
|
+
else:
|
|
40
|
+
digest = hashlib.sha256(f"{self.architecture_name}:{block_id}:{suffix}".encode("utf-8")).digest()
|
|
41
|
+
seed = int.from_bytes(digest[:4], "little")
|
|
42
|
+
rng = np.random.default_rng(seed)
|
|
43
|
+
fan_in = shape[0]
|
|
44
|
+
fan_out = shape[1] if len(shape) > 1 else shape[0]
|
|
45
|
+
scale = float(np.sqrt(2.0 / max(1, fan_in + fan_out))) * 0.25
|
|
46
|
+
arr = (rng.standard_normal(size=shape) * scale).astype(np.float32)
|
|
47
|
+
|
|
48
|
+
tensor = self.backend.convert_from_numpy(arr)
|
|
49
|
+
self._synthetic_cache[cache_key] = tensor
|
|
50
|
+
return tensor
|
|
51
|
+
|
|
52
|
+
def resolve_tensor(
|
|
53
|
+
self,
|
|
54
|
+
raw_tensors: Dict[str, Any],
|
|
55
|
+
block_id: int,
|
|
56
|
+
prefix: str,
|
|
57
|
+
suffix: str,
|
|
58
|
+
default_shape: Tuple[int, ...],
|
|
59
|
+
) -> Any:
|
|
60
|
+
"""Look up a tensor by exact key or suffix match; raise KeyError if missing in strict mode."""
|
|
61
|
+
key = f"{prefix}{suffix}"
|
|
62
|
+
if key in raw_tensors:
|
|
63
|
+
return self.backend.convert_from_numpy(raw_tensors[key])
|
|
64
|
+
for k, v in raw_tensors.items():
|
|
65
|
+
if k.endswith(suffix) or suffix in k:
|
|
66
|
+
return self.backend.convert_from_numpy(v)
|
|
67
|
+
|
|
68
|
+
if not self.allow_synthetic:
|
|
69
|
+
raise KeyError(
|
|
70
|
+
f"Missing required weight tensor '{key}' for block {block_id} on architecture "
|
|
71
|
+
f"'{self.architecture_name}' (allow_synthetic=False)."
|
|
72
|
+
)
|
|
73
|
+
return self._synthesize_weight(block_id, suffix, default_shape)
|
|
74
|
+
|
|
75
|
+
@abstractmethod
|
|
76
|
+
def extract_block_weights(
|
|
77
|
+
self,
|
|
78
|
+
block_id: int,
|
|
79
|
+
raw_tensors: Dict[str, Any],
|
|
80
|
+
) -> DiTBlockWeights:
|
|
81
|
+
"""Translate raw model state dict tensors into normalized DiTBlockWeights."""
|
|
82
|
+
pass
|
|
83
|
+
|
|
84
|
+
def format_prompt_embeddings(self, text_tokens: Any) -> Any:
|
|
85
|
+
"""Format or project text encoder embeddings for cross-attention."""
|
|
86
|
+
return text_tokens
|
|
87
|
+
|
|
88
|
+
def compute_timestep_embedding(self, timestep: float, dim: int) -> Any:
|
|
89
|
+
"""Compute sinusoidal timestep embedding."""
|
|
90
|
+
half = max(1, dim // 2)
|
|
91
|
+
freqs = np.exp(-np.log(10000.0) * np.arange(0, half, dtype=np.float32) / half)
|
|
92
|
+
args = float(timestep) * 1000.0 * freqs
|
|
93
|
+
embedding = np.concatenate([np.cos(args), np.sin(args)], axis=-1)
|
|
94
|
+
if embedding.shape[0] < dim:
|
|
95
|
+
embedding = np.pad(embedding, (0, dim - embedding.shape[0]))
|
|
96
|
+
return self.backend.convert_from_numpy(embedding.astype(np.float32))
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Adapter for CogVideoX (5B / 2B) 3D Diffusion Transformer."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict
|
|
4
|
+
from phobos_stream.adapters.base import BaseModelAdapter
|
|
5
|
+
from phobos_stream.models.attention import AttentionWeights
|
|
6
|
+
from phobos_stream.models.dit_block import DiTBlockWeights, MLPWeights
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class CogVideoXAdapter(BaseModelAdapter):
|
|
10
|
+
"""Adapter for Tsinghua/Zhipu CogVideoX DiT models."""
|
|
11
|
+
|
|
12
|
+
@property
|
|
13
|
+
def architecture_name(self) -> str:
|
|
14
|
+
return "cogvideox"
|
|
15
|
+
|
|
16
|
+
def extract_block_weights(
|
|
17
|
+
self,
|
|
18
|
+
block_id: int,
|
|
19
|
+
raw_tensors: Dict[str, Any],
|
|
20
|
+
) -> DiTBlockWeights:
|
|
21
|
+
"""Map CogVideoX transformer_blocks tensors into normalized DiTBlockWeights."""
|
|
22
|
+
prefix = f"transformer_blocks.{block_id}."
|
|
23
|
+
dim = self.hidden_size
|
|
24
|
+
|
|
25
|
+
def get_t(suffix: str, shape):
|
|
26
|
+
return self.resolve_tensor(raw_tensors, block_id, prefix, suffix, shape)
|
|
27
|
+
|
|
28
|
+
self_attn = AttentionWeights(
|
|
29
|
+
q_proj=get_t("attn1.to_q.weight", (dim, dim)),
|
|
30
|
+
k_proj=get_t("attn1.to_k.weight", (dim, dim)),
|
|
31
|
+
v_proj=get_t("attn1.to_v.weight", (dim, dim)),
|
|
32
|
+
out_proj=get_t("attn1.to_out.0.weight", (dim, dim)),
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
cross_attn = AttentionWeights(
|
|
36
|
+
q_proj=get_t("attn2.to_q.weight", (dim, dim)),
|
|
37
|
+
k_proj=get_t("attn2.to_k.weight", (dim, dim)),
|
|
38
|
+
v_proj=get_t("attn2.to_v.weight", (dim, dim)),
|
|
39
|
+
out_proj=get_t("attn2.to_out.0.weight", (dim, dim)),
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
mlp = MLPWeights(
|
|
43
|
+
gate_proj=get_t("ff.net.0.proj.weight", (dim, dim * 4)),
|
|
44
|
+
up_proj=get_t("ff.net.1.proj.weight", (dim, dim * 4)),
|
|
45
|
+
down_proj=get_t("ff.net.2.weight", (dim * 4, dim)),
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
return DiTBlockWeights(
|
|
49
|
+
norm1_weight=get_t("norm1.weight", (dim,)),
|
|
50
|
+
self_attn=self_attn,
|
|
51
|
+
norm2_weight=get_t("norm2.weight", (dim,)),
|
|
52
|
+
cross_attn=cross_attn,
|
|
53
|
+
norm3_weight=get_t("norm3.weight", (dim,)),
|
|
54
|
+
mlp=mlp,
|
|
55
|
+
)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Adapter registry and auto-detection factory."""
|
|
2
|
+
|
|
3
|
+
from phobos_stream.adapters.base import BaseModelAdapter
|
|
4
|
+
from phobos_stream.adapters.cogvideo_adapter import CogVideoXAdapter
|
|
5
|
+
from phobos_stream.adapters.flux_adapter import FluxAdapter
|
|
6
|
+
from phobos_stream.adapters.hunyuan_adapter import HunyuanAdapter
|
|
7
|
+
from phobos_stream.adapters.wan_adapter import WanAdapter
|
|
8
|
+
from phobos_stream.backends.base import BaseBackend
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def get_adapter(
|
|
12
|
+
architecture: str,
|
|
13
|
+
backend: BaseBackend,
|
|
14
|
+
hidden_size: int = 4096,
|
|
15
|
+
allow_synthetic: bool = False,
|
|
16
|
+
) -> BaseModelAdapter:
|
|
17
|
+
"""Resolve and return model adapter for the given architecture."""
|
|
18
|
+
arch = architecture.lower()
|
|
19
|
+
if "wan" in arch or "lumina" in arch or "z_image" in arch or "z-image" in arch:
|
|
20
|
+
return WanAdapter(backend, hidden_size=hidden_size, allow_synthetic=allow_synthetic)
|
|
21
|
+
if "flux" in arch:
|
|
22
|
+
return FluxAdapter(backend, hidden_size=hidden_size, allow_synthetic=allow_synthetic)
|
|
23
|
+
if "hunyuan" in arch:
|
|
24
|
+
return HunyuanAdapter(backend, hidden_size=hidden_size, allow_synthetic=allow_synthetic)
|
|
25
|
+
if "cogvideo" in arch:
|
|
26
|
+
return CogVideoXAdapter(backend, hidden_size=hidden_size, allow_synthetic=allow_synthetic)
|
|
27
|
+
return WanAdapter(backend, hidden_size=hidden_size, allow_synthetic=allow_synthetic)
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Adapter for Black Forest Labs FLUX.1 (schnell / dev) DiT models."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict
|
|
4
|
+
from phobos_stream.adapters.base import BaseModelAdapter
|
|
5
|
+
from phobos_stream.models.attention import AttentionWeights
|
|
6
|
+
from phobos_stream.models.dit_block import DiTBlockWeights, MLPWeights
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class FluxAdapter(BaseModelAdapter):
|
|
10
|
+
"""Adapter for FLUX.1 12B DiT models (double and single stream blocks)."""
|
|
11
|
+
|
|
12
|
+
@property
|
|
13
|
+
def architecture_name(self) -> str:
|
|
14
|
+
return "flux"
|
|
15
|
+
|
|
16
|
+
def extract_block_weights(
|
|
17
|
+
self,
|
|
18
|
+
block_id: int,
|
|
19
|
+
raw_tensors: Dict[str, Any],
|
|
20
|
+
) -> DiTBlockWeights:
|
|
21
|
+
"""Map FLUX.1 double/single block tensors into normalized DiTBlockWeights."""
|
|
22
|
+
is_single = any("single_blocks." in k for k in raw_tensors)
|
|
23
|
+
prefix = f"single_blocks.{block_id}." if is_single else f"double_blocks.{block_id}."
|
|
24
|
+
dim = self.hidden_size
|
|
25
|
+
|
|
26
|
+
def get_t(suffix: str, shape):
|
|
27
|
+
return self.resolve_tensor(raw_tensors, block_id, prefix, suffix, shape)
|
|
28
|
+
|
|
29
|
+
if is_single:
|
|
30
|
+
self_attn = AttentionWeights(
|
|
31
|
+
q_proj=get_t("linear1.q.weight", (dim, dim)),
|
|
32
|
+
k_proj=get_t("linear1.k.weight", (dim, dim)),
|
|
33
|
+
v_proj=get_t("linear1.v.weight", (dim, dim)),
|
|
34
|
+
out_proj=get_t("linear2.proj.weight", (dim, dim)),
|
|
35
|
+
)
|
|
36
|
+
cross_attn = None
|
|
37
|
+
mlp = MLPWeights(
|
|
38
|
+
gate_proj=get_t("mlp.gate.weight", (dim, dim * 4)),
|
|
39
|
+
up_proj=get_t("mlp.up.weight", (dim, dim * 4)),
|
|
40
|
+
down_proj=get_t("linear2.mlp.weight", (dim * 4, dim)),
|
|
41
|
+
)
|
|
42
|
+
return DiTBlockWeights(
|
|
43
|
+
norm1_weight=get_t("modulation.lin.weight", (dim,)),
|
|
44
|
+
self_attn=self_attn,
|
|
45
|
+
norm2_weight=get_t("modulation.lin.weight", (dim,)),
|
|
46
|
+
cross_attn=cross_attn,
|
|
47
|
+
norm3_weight=get_t("modulation.lin.weight", (dim,)),
|
|
48
|
+
mlp=mlp,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
self_attn = AttentionWeights(
|
|
52
|
+
q_proj=get_t("img_attn.q_proj.weight", (dim, dim)),
|
|
53
|
+
k_proj=get_t("img_attn.k_proj.weight", (dim, dim)),
|
|
54
|
+
v_proj=get_t("img_attn.v_proj.weight", (dim, dim)),
|
|
55
|
+
out_proj=get_t("img_attn.proj.weight", (dim, dim)),
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
cross_attn = AttentionWeights(
|
|
59
|
+
q_proj=get_t("txt_attn.q_proj.weight", (dim, dim)),
|
|
60
|
+
k_proj=get_t("txt_attn.k_proj.weight", (dim, dim)),
|
|
61
|
+
v_proj=get_t("txt_attn.v_proj.weight", (dim, dim)),
|
|
62
|
+
out_proj=get_t("txt_attn.proj.weight", (dim, dim)),
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
mlp = MLPWeights(
|
|
66
|
+
gate_proj=get_t("img_mlp.0.weight", (dim, dim * 4)),
|
|
67
|
+
up_proj=get_t("img_mlp.1.weight", (dim, dim * 4)),
|
|
68
|
+
down_proj=get_t("img_mlp.2.weight", (dim * 4, dim)),
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
return DiTBlockWeights(
|
|
72
|
+
norm1_weight=get_t("img_mod.lin.weight", (dim,)),
|
|
73
|
+
self_attn=self_attn,
|
|
74
|
+
norm2_weight=get_t("txt_mod.lin.weight", (dim,)),
|
|
75
|
+
cross_attn=cross_attn,
|
|
76
|
+
norm3_weight=get_t("img_norm2.weight", (dim,)),
|
|
77
|
+
mlp=mlp,
|
|
78
|
+
)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Adapter for Tencent HunyuanVideo 13B Diffusion Transformer."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict
|
|
4
|
+
from phobos_stream.adapters.base import BaseModelAdapter
|
|
5
|
+
from phobos_stream.models.attention import AttentionWeights
|
|
6
|
+
from phobos_stream.models.dit_block import DiTBlockWeights, MLPWeights
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class HunyuanAdapter(BaseModelAdapter):
|
|
10
|
+
"""Adapter for HunyuanVideo 13B models."""
|
|
11
|
+
|
|
12
|
+
@property
|
|
13
|
+
def architecture_name(self) -> str:
|
|
14
|
+
return "hunyuan"
|
|
15
|
+
|
|
16
|
+
def extract_block_weights(
|
|
17
|
+
self,
|
|
18
|
+
block_id: int,
|
|
19
|
+
raw_tensors: Dict[str, Any],
|
|
20
|
+
) -> DiTBlockWeights:
|
|
21
|
+
"""Map HunyuanVideo double/single block tensors into normalized DiTBlockWeights."""
|
|
22
|
+
is_single = any("single_blocks." in k for k in raw_tensors)
|
|
23
|
+
prefix = f"single_blocks.{block_id}." if is_single else f"double_blocks.{block_id}."
|
|
24
|
+
dim = self.hidden_size
|
|
25
|
+
|
|
26
|
+
def get_t(suffix: str, shape):
|
|
27
|
+
return self.resolve_tensor(raw_tensors, block_id, prefix, suffix, shape)
|
|
28
|
+
|
|
29
|
+
self_attn = AttentionWeights(
|
|
30
|
+
q_proj=get_t("img_attn.q_proj.weight", (dim, dim)),
|
|
31
|
+
k_proj=get_t("img_attn.k_proj.weight", (dim, dim)),
|
|
32
|
+
v_proj=get_t("img_attn.v_proj.weight", (dim, dim)),
|
|
33
|
+
out_proj=get_t("img_attn.proj.weight", (dim, dim)),
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
cross_attn = None if is_single else AttentionWeights(
|
|
37
|
+
q_proj=get_t("txt_attn.q_proj.weight", (dim, dim)),
|
|
38
|
+
k_proj=get_t("txt_attn.k_proj.weight", (dim, dim)),
|
|
39
|
+
v_proj=get_t("txt_attn.v_proj.weight", (dim, dim)),
|
|
40
|
+
out_proj=get_t("txt_attn.proj.weight", (dim, dim)),
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
mlp = MLPWeights(
|
|
44
|
+
gate_proj=get_t("img_mlp.gate.weight", (dim, dim * 4)),
|
|
45
|
+
up_proj=get_t("img_mlp.up.weight", (dim, dim * 4)),
|
|
46
|
+
down_proj=get_t("img_mlp.down.weight", (dim * 4, dim)),
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
return DiTBlockWeights(
|
|
50
|
+
norm1_weight=get_t("img_norm1.weight", (dim,)),
|
|
51
|
+
self_attn=self_attn,
|
|
52
|
+
norm2_weight=get_t("txt_norm1.weight", (dim,)),
|
|
53
|
+
cross_attn=cross_attn,
|
|
54
|
+
norm3_weight=get_t("img_norm2.weight", (dim,)),
|
|
55
|
+
mlp=mlp,
|
|
56
|
+
)
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Adapter for Alibaba Wan2.1 (14B / 1.3B) and Lumina2 / Z-Image-Turbo DiT models."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict
|
|
4
|
+
from phobos_stream.adapters.base import BaseModelAdapter
|
|
5
|
+
from phobos_stream.models.attention import AttentionWeights
|
|
6
|
+
from phobos_stream.models.dit_block import DiTBlockWeights, MLPWeights
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class WanAdapter(BaseModelAdapter):
|
|
10
|
+
"""Adapter for Wan2.1 and Lumina2 / Z-Image-Turbo DiT models."""
|
|
11
|
+
|
|
12
|
+
@property
|
|
13
|
+
def architecture_name(self) -> str:
|
|
14
|
+
return "wan2.1"
|
|
15
|
+
|
|
16
|
+
def extract_block_weights(
|
|
17
|
+
self,
|
|
18
|
+
block_id: int,
|
|
19
|
+
raw_tensors: Dict[str, Any],
|
|
20
|
+
) -> DiTBlockWeights:
|
|
21
|
+
"""Map Wan2.1 or Lumina2/Z-Image-Turbo layer tensors into normalized DiTBlockWeights."""
|
|
22
|
+
dim = self.hidden_size
|
|
23
|
+
|
|
24
|
+
# Detect Lumina2 / Z-Image-Turbo fused QKV format ('layers.{block_id}.attention.qkv.weight')
|
|
25
|
+
lumina_qkv_key = f"layers.{block_id}.attention.qkv.weight"
|
|
26
|
+
if lumina_qkv_key in raw_tensors:
|
|
27
|
+
prefix = f"layers.{block_id}."
|
|
28
|
+
qkv = raw_tensors[lumina_qkv_key]
|
|
29
|
+
q_np, k_np, v_np = qkv[:dim], qkv[dim : 2 * dim], qkv[2 * dim : 3 * dim]
|
|
30
|
+
self_attn = AttentionWeights(
|
|
31
|
+
q_proj=self.backend.convert_from_numpy(q_np),
|
|
32
|
+
k_proj=self.backend.convert_from_numpy(k_np),
|
|
33
|
+
v_proj=self.backend.convert_from_numpy(v_np),
|
|
34
|
+
out_proj=self.resolve_tensor(raw_tensors, block_id, prefix, "attention.out.weight", (dim, dim)),
|
|
35
|
+
)
|
|
36
|
+
mlp = MLPWeights(
|
|
37
|
+
gate_proj=self.resolve_tensor(raw_tensors, block_id, prefix, "feed_forward.w1.weight", (dim * 2, dim)),
|
|
38
|
+
up_proj=self.resolve_tensor(raw_tensors, block_id, prefix, "feed_forward.w3.weight", (dim * 2, dim)),
|
|
39
|
+
down_proj=self.resolve_tensor(raw_tensors, block_id, prefix, "feed_forward.w2.weight", (dim, dim * 2)),
|
|
40
|
+
)
|
|
41
|
+
return DiTBlockWeights(
|
|
42
|
+
norm1_weight=self.resolve_tensor(raw_tensors, block_id, prefix, "attention_norm1.weight", (dim,)),
|
|
43
|
+
self_attn=self_attn,
|
|
44
|
+
norm2_weight=self.resolve_tensor(raw_tensors, block_id, prefix, "attention_norm2.weight", (dim,)),
|
|
45
|
+
cross_attn=None,
|
|
46
|
+
norm3_weight=self.resolve_tensor(raw_tensors, block_id, prefix, "ffn_norm1.weight", (dim,)),
|
|
47
|
+
mlp=mlp,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
prefix = f"blocks.{block_id}."
|
|
51
|
+
|
|
52
|
+
def get_t(suffix: str, shape):
|
|
53
|
+
return self.resolve_tensor(raw_tensors, block_id, prefix, suffix, shape)
|
|
54
|
+
|
|
55
|
+
self_attn = AttentionWeights(
|
|
56
|
+
q_proj=get_t("self_attn.q_proj.weight", (dim, dim)),
|
|
57
|
+
k_proj=get_t("self_attn.k_proj.weight", (dim, dim)),
|
|
58
|
+
v_proj=get_t("self_attn.v_proj.weight", (dim, dim)),
|
|
59
|
+
out_proj=get_t("self_attn.o_proj.weight", (dim, dim)),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
cross_attn = AttentionWeights(
|
|
63
|
+
q_proj=get_t("cross_attn.q_proj.weight", (dim, dim)),
|
|
64
|
+
k_proj=get_t("cross_attn.k_proj.weight", (dim, dim)),
|
|
65
|
+
v_proj=get_t("cross_attn.v_proj.weight", (dim, dim)),
|
|
66
|
+
out_proj=get_t("cross_attn.o_proj.weight", (dim, dim)),
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
mlp = MLPWeights(
|
|
70
|
+
gate_proj=get_t("ffn.gate_proj.weight", (dim, dim * 2)),
|
|
71
|
+
up_proj=get_t("ffn.up_proj.weight", (dim, dim * 2)),
|
|
72
|
+
down_proj=get_t("ffn.down_proj.weight", (dim * 2, dim)),
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
return DiTBlockWeights(
|
|
76
|
+
norm1_weight=get_t("norm1.weight", (dim,)),
|
|
77
|
+
self_attn=self_attn,
|
|
78
|
+
norm2_weight=get_t("norm2.weight", (dim,)),
|
|
79
|
+
cross_attn=cross_attn,
|
|
80
|
+
norm3_weight=get_t("norm3.weight", (dim,)),
|
|
81
|
+
mlp=mlp,
|
|
82
|
+
)
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Universal compute backends for PhobosStream."""
|
|
2
|
+
|
|
3
|
+
from phobos_stream.backends.base import BaseBackend
|
|
4
|
+
from phobos_stream.backends.factory import get_backend
|
|
5
|
+
from phobos_stream.backends.gguf_backend import GGUFBackend
|
|
6
|
+
|
|
7
|
+
__all__ = ["BaseBackend", "GGUFBackend", "get_backend"]
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Abstract base interface for execution backends (MLX, CUDA, ROCm, GGUF, CPU)."""
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
import contextlib
|
|
5
|
+
from typing import Any, Iterator, Optional, Sequence, Tuple
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class BaseBackend(ABC):
|
|
10
|
+
"""Universal compute backend interface."""
|
|
11
|
+
|
|
12
|
+
def __init__(self, device: str = "auto") -> None:
|
|
13
|
+
self.device = device
|
|
14
|
+
|
|
15
|
+
@property
|
|
16
|
+
@abstractmethod
|
|
17
|
+
def name(self) -> str:
|
|
18
|
+
"""Name of the backend."""
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
@abstractmethod
|
|
22
|
+
def zeros(self, shape: Tuple[int, ...], dtype: str = "float32") -> Any:
|
|
23
|
+
"""Create a zero tensor."""
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
@abstractmethod
|
|
27
|
+
def randn(self, shape: Tuple[int, ...], seed: Optional[int] = None, dtype: str = "float32") -> Any:
|
|
28
|
+
"""Create a normally distributed random tensor."""
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
@abstractmethod
|
|
32
|
+
def matmul(self, a: Any, b: Any) -> Any:
|
|
33
|
+
"""Perform matrix multiplication a @ b."""
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
def linear(self, x: Any, weight: Any, bias: Optional[Any] = None) -> Any:
|
|
37
|
+
"""Apply linear projection handling both (out, in) and (in, out) weight layouts."""
|
|
38
|
+
w_shape = weight.shape
|
|
39
|
+
x_last = x.shape[-1]
|
|
40
|
+
if len(w_shape) == 2:
|
|
41
|
+
if w_shape[0] == x_last and w_shape[1] != x_last:
|
|
42
|
+
out = self.matmul(x, weight)
|
|
43
|
+
else:
|
|
44
|
+
out = self.matmul(x, self.swapaxes(weight, -1, -2))
|
|
45
|
+
else:
|
|
46
|
+
out = self.matmul(x, weight)
|
|
47
|
+
|
|
48
|
+
if bias is not None:
|
|
49
|
+
out = out + bias
|
|
50
|
+
return out
|
|
51
|
+
|
|
52
|
+
def reshape(self, x: Any, shape: Tuple[int, ...]) -> Any:
|
|
53
|
+
"""Reshape a tensor."""
|
|
54
|
+
return x.reshape(*shape) if hasattr(x, "reshape") else np.reshape(x, shape)
|
|
55
|
+
|
|
56
|
+
def swapaxes(self, x: Any, axis1: int, axis2: int) -> Any:
|
|
57
|
+
"""Swap two axes of a tensor."""
|
|
58
|
+
if hasattr(x, "swapaxes"):
|
|
59
|
+
return x.swapaxes(axis1, axis2)
|
|
60
|
+
return np.swapaxes(x, axis1, axis2)
|
|
61
|
+
|
|
62
|
+
def concat(self, tensors: Sequence[Any], axis: int = 0) -> Any:
|
|
63
|
+
"""Concatenate tensors along `axis` on their native backend."""
|
|
64
|
+
if not tensors:
|
|
65
|
+
raise ValueError("concat requires at least one tensor.")
|
|
66
|
+
mod_name = type(tensors[0]).__module__
|
|
67
|
+
if "mlx" in mod_name:
|
|
68
|
+
import mlx.core as mx
|
|
69
|
+
|
|
70
|
+
return mx.concatenate(list(tensors), axis=axis)
|
|
71
|
+
if "torch" in mod_name:
|
|
72
|
+
import torch
|
|
73
|
+
|
|
74
|
+
return torch.cat(list(tensors), dim=axis)
|
|
75
|
+
return np.concatenate(list(tensors), axis=axis)
|
|
76
|
+
|
|
77
|
+
def split_two(self, tensor: Any, axis: int = 0) -> Tuple[Any, Any]:
|
|
78
|
+
"""Split an even-sized batch tensor into `(first_half, second_half)` along axis 0."""
|
|
79
|
+
if axis != 0:
|
|
80
|
+
raise ValueError("split_two expects axis=0 for batched conditioning.")
|
|
81
|
+
half = tensor.shape[0] // 2
|
|
82
|
+
return tensor[:half], tensor[half:]
|
|
83
|
+
|
|
84
|
+
def async_eval(self, *tensors: Any) -> None:
|
|
85
|
+
"""Schedule asynchronous evaluation of tensors (mlx_lm style pipeline)."""
|
|
86
|
+
pass
|
|
87
|
+
|
|
88
|
+
@contextlib.contextmanager
|
|
89
|
+
def wired_limit(self) -> Iterator[None]:
|
|
90
|
+
"""Context manager to lock recommended GPU working set size in unified memory."""
|
|
91
|
+
yield
|
|
92
|
+
|
|
93
|
+
@abstractmethod
|
|
94
|
+
def layer_norm(self, x: Any, weight: Any, bias: Optional[Any] = None, eps: float = 1e-5) -> Any:
|
|
95
|
+
"""Perform LayerNorm or RMSNorm."""
|
|
96
|
+
pass
|
|
97
|
+
|
|
98
|
+
@abstractmethod
|
|
99
|
+
def silu(self, x: Any) -> Any:
|
|
100
|
+
"""SiLU (Swish) activation function."""
|
|
101
|
+
pass
|
|
102
|
+
|
|
103
|
+
@abstractmethod
|
|
104
|
+
def scaled_dot_product_attention(
|
|
105
|
+
self,
|
|
106
|
+
q: Any,
|
|
107
|
+
k: Any,
|
|
108
|
+
v: Any,
|
|
109
|
+
scale: Optional[float] = None,
|
|
110
|
+
mask: Optional[Any] = None,
|
|
111
|
+
) -> Any:
|
|
112
|
+
"""Compute multi-head scaled dot product attention."""
|
|
113
|
+
pass
|
|
114
|
+
|
|
115
|
+
@abstractmethod
|
|
116
|
+
def convert_from_numpy(self, arr: np.ndarray, dtype: Optional[str] = None) -> Any:
|
|
117
|
+
"""Convert a numpy array to the backend's native tensor format."""
|
|
118
|
+
pass
|
|
119
|
+
|
|
120
|
+
@abstractmethod
|
|
121
|
+
def to_numpy(self, tensor: Any) -> np.ndarray:
|
|
122
|
+
"""Convert a backend native tensor to numpy."""
|
|
123
|
+
pass
|
|
124
|
+
|
|
125
|
+
@abstractmethod
|
|
126
|
+
def synchronize(self) -> None:
|
|
127
|
+
"""Wait for all pending GPU/Metal work to finish."""
|
|
128
|
+
pass
|
|
129
|
+
|
|
130
|
+
@abstractmethod
|
|
131
|
+
def empty_cache(self) -> None:
|
|
132
|
+
"""Reclaim unused memory caches."""
|
|
133
|
+
pass
|
|
134
|
+
|
|
135
|
+
@abstractmethod
|
|
136
|
+
def get_memory_allocated_mb(self) -> float:
|
|
137
|
+
"""Current active allocated memory in Megabytes."""
|
|
138
|
+
pass
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""NVIDIA CUDA and AMD ROCm PyTorch execution backend."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Optional, Tuple
|
|
4
|
+
import numpy as np
|
|
5
|
+
from phobos_stream.backends.base import BaseBackend
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
import torch
|
|
9
|
+
import torch.nn.functional as F
|
|
10
|
+
TORCH_AVAILABLE = True
|
|
11
|
+
except ImportError:
|
|
12
|
+
TORCH_AVAILABLE = False
|
|
13
|
+
torch = None
|
|
14
|
+
F = None
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class CUDABackend(BaseBackend):
|
|
18
|
+
"""PyTorch CUDA and ROCm GPU backend."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, device: str = "cuda:0") -> None:
|
|
21
|
+
super().__init__(device=device)
|
|
22
|
+
if not TORCH_AVAILABLE:
|
|
23
|
+
raise RuntimeError("PyTorch is not installed. Run: pip install torch")
|
|
24
|
+
if not torch.cuda.is_available():
|
|
25
|
+
raise RuntimeError("CUDA is not available on this machine.")
|
|
26
|
+
self.torch_device = torch.device(device)
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def name(self) -> str:
|
|
30
|
+
return "cuda"
|
|
31
|
+
|
|
32
|
+
def zeros(self, shape: Tuple[int, ...], dtype: str = "float32") -> Any:
|
|
33
|
+
torch_dtype = getattr(torch, dtype, torch.float32)
|
|
34
|
+
return torch.zeros(shape, dtype=torch_dtype, device=self.torch_device)
|
|
35
|
+
|
|
36
|
+
def randn(self, shape: Tuple[int, ...], seed: Optional[int] = None, dtype: str = "float32") -> Any:
|
|
37
|
+
generator = None
|
|
38
|
+
if seed is not None:
|
|
39
|
+
generator = torch.Generator(device=self.torch_device).manual_seed(seed)
|
|
40
|
+
torch_dtype = getattr(torch, dtype, torch.float32)
|
|
41
|
+
return torch.randn(shape, generator=generator, dtype=torch_dtype, device=self.torch_device)
|
|
42
|
+
|
|
43
|
+
def matmul(self, a: Any, b: Any) -> Any:
|
|
44
|
+
return torch.matmul(a, b)
|
|
45
|
+
|
|
46
|
+
def reshape(self, x: Any, shape: Tuple[int, ...]) -> Any:
|
|
47
|
+
return x.reshape(*shape)
|
|
48
|
+
|
|
49
|
+
def swapaxes(self, x: Any, axis1: int, axis2: int) -> Any:
|
|
50
|
+
return torch.swapaxes(x, axis1, axis2)
|
|
51
|
+
|
|
52
|
+
def layer_norm(self, x: Any, weight: Any, bias: Optional[Any] = None, eps: float = 1e-5) -> Any:
|
|
53
|
+
return F.layer_norm(x, normalized_shape=(x.shape[-1],), weight=weight, bias=bias, eps=eps)
|
|
54
|
+
|
|
55
|
+
def silu(self, x: Any) -> Any:
|
|
56
|
+
return F.silu(x)
|
|
57
|
+
|
|
58
|
+
def scaled_dot_product_attention(
|
|
59
|
+
self,
|
|
60
|
+
q: Any,
|
|
61
|
+
k: Any,
|
|
62
|
+
v: Any,
|
|
63
|
+
scale: Optional[float] = None,
|
|
64
|
+
mask: Optional[Any] = None,
|
|
65
|
+
) -> Any:
|
|
66
|
+
return F.scaled_dot_product_attention(q, k, v, attn_mask=mask, scale=scale)
|
|
67
|
+
|
|
68
|
+
def convert_from_numpy(self, arr: np.ndarray, dtype: Optional[str] = None) -> Any:
|
|
69
|
+
if not arr.flags["C_CONTIGUOUS"]:
|
|
70
|
+
arr = np.ascontiguousarray(arr)
|
|
71
|
+
t = torch.from_numpy(arr).to(self.torch_device)
|
|
72
|
+
if dtype is not None and hasattr(torch, dtype):
|
|
73
|
+
t = t.to(getattr(torch, dtype))
|
|
74
|
+
return t
|
|
75
|
+
|
|
76
|
+
def to_numpy(self, tensor: Any) -> np.ndarray:
|
|
77
|
+
return tensor.detach().cpu().numpy()
|
|
78
|
+
|
|
79
|
+
def synchronize(self) -> None:
|
|
80
|
+
torch.cuda.synchronize(self.torch_device)
|
|
81
|
+
|
|
82
|
+
def empty_cache(self) -> None:
|
|
83
|
+
torch.cuda.empty_cache()
|
|
84
|
+
|
|
85
|
+
def get_memory_allocated_mb(self) -> float:
|
|
86
|
+
return float(torch.cuda.memory_allocated(self.torch_device)) / (1024.0 * 1024.0)
|