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,105 @@
1
+ """Storage layout and file path resolution for Diffusion models."""
2
+
3
+ from dataclasses import dataclass, field
4
+ from pathlib import Path
5
+ from typing import Any, Dict, List, Optional
6
+ import json
7
+
8
+
9
+ @dataclass
10
+ class BlockMetadata:
11
+ """Metadata for an individual DiT transformer block.
12
+
13
+ Attributes:
14
+ block_id: Sequential index of the transformer block in execution order.
15
+ filename: Path to the `.safetensors` shard containing this block's tensors.
16
+ tensor_names: Exact safetensors keys belonging to this block.
17
+ byte_size: Total raw byte footprint of all tensors in this block.
18
+ """
19
+
20
+ block_id: int
21
+ filename: str
22
+ tensor_names: List[str] = field(default_factory=list)
23
+ byte_size: int = 0
24
+
25
+
26
+ @dataclass
27
+ class ModelShardsManifest:
28
+ """Manifest describing partitioned or virtually indexed weights of a diffusion pipeline.
29
+
30
+ Attributes:
31
+ model_name: Human-readable model identifier.
32
+ architecture: Architecture family (e.g. 'wan2.1', 'flux', 'hunyuan', 'cogvideox').
33
+ num_blocks: Number of transformer blocks to execute per denoising step.
34
+ hidden_size: Hidden feature dimension of the transformer backbone.
35
+ text_encoder_path: Optional path to a `.safetensors` text encoder checkpoint.
36
+ vae_path: Optional path to a `.safetensors` VAE checkpoint.
37
+ blocks: Mapping from integer block_id to its BlockMetadata.
38
+ allow_synthetic: Explicit opt-in for synthetic benchmark/test weights when real
39
+ checkpoint files are absent. Defaults to False so production calls never
40
+ silently fabricate weights.
41
+ """
42
+
43
+ model_name: str
44
+ architecture: str
45
+ num_blocks: int
46
+ hidden_size: int
47
+ text_encoder_path: Optional[str] = None
48
+ vae_path: Optional[str] = None
49
+ blocks: Dict[int, BlockMetadata] = field(default_factory=dict)
50
+ allow_synthetic: bool = False
51
+
52
+ def to_dict(self) -> Dict[str, Any]:
53
+ """Serialize manifest metadata to a JSON-compatible dictionary."""
54
+ return {
55
+ "model_name": self.model_name,
56
+ "architecture": self.architecture,
57
+ "num_blocks": self.num_blocks,
58
+ "hidden_size": self.hidden_size,
59
+ "text_encoder_path": self.text_encoder_path,
60
+ "vae_path": self.vae_path,
61
+ "allow_synthetic": self.allow_synthetic,
62
+ "blocks": {
63
+ str(k): {
64
+ "block_id": v.block_id,
65
+ "filename": v.filename,
66
+ "tensor_names": v.tensor_names,
67
+ "byte_size": v.byte_size,
68
+ }
69
+ for k, v in self.blocks.items()
70
+ },
71
+ }
72
+
73
+ @classmethod
74
+ def from_dict(cls, data: Dict[str, Any]) -> "ModelShardsManifest":
75
+ """Reconstruct a ModelShardsManifest from a parsed JSON dictionary."""
76
+ blocks: Dict[int, BlockMetadata] = {}
77
+ for k, v in data.get("blocks", {}).items():
78
+ blocks[int(k)] = BlockMetadata(
79
+ block_id=int(v["block_id"]),
80
+ filename=str(v["filename"]),
81
+ tensor_names=list(v.get("tensor_names", [])),
82
+ byte_size=int(v.get("byte_size", 0)),
83
+ )
84
+ return cls(
85
+ model_name=str(data["model_name"]),
86
+ architecture=str(data["architecture"]),
87
+ num_blocks=int(data["num_blocks"]),
88
+ hidden_size=int(data["hidden_size"]),
89
+ text_encoder_path=data.get("text_encoder_path"),
90
+ vae_path=data.get("vae_path"),
91
+ blocks=blocks,
92
+ allow_synthetic=bool(data.get("allow_synthetic", False)),
93
+ )
94
+
95
+ def save(self, path: Path) -> None:
96
+ """Write manifest JSON to disk."""
97
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
98
+ with open(path, "w", encoding="utf-8") as f:
99
+ json.dump(self.to_dict(), f, indent=2)
100
+
101
+ @classmethod
102
+ def load(cls, path: Path) -> "ModelShardsManifest":
103
+ """Load manifest JSON from disk."""
104
+ with open(path, "r", encoding="utf-8") as f:
105
+ return cls.from_dict(json.load(f))
@@ -0,0 +1,194 @@
1
+ """Zero-copy memory-mapped tensor loader for Diffusion Transformer weights."""
2
+
3
+ import json
4
+ import mmap
5
+ import struct
6
+ from pathlib import Path
7
+ from typing import Any, Dict, List, Optional, Tuple
8
+ import numpy as np
9
+
10
+
11
+ DTYPE_MAP: Dict[str, Any] = {
12
+ "F64": np.float64,
13
+ "F32": np.float32,
14
+ "F16": np.float16,
15
+ "BF16": np.uint16,
16
+ "F8_E4M3": np.uint8,
17
+ "F8_E5M2": np.uint8,
18
+ "I64": np.int64,
19
+ "I32": np.int32,
20
+ "I16": np.int16,
21
+ "I8": np.int8,
22
+ "U64": np.uint64,
23
+ "U32": np.uint32,
24
+ "U16": np.uint16,
25
+ "U8": np.uint8,
26
+ "BOOL": np.bool_,
27
+ }
28
+
29
+
30
+ def _decode_fp8_e4m3(raw_u8: np.ndarray) -> np.ndarray:
31
+ """Vectorized conversion of 8-bit float (E4M3FN) bit patterns to float32."""
32
+ u = raw_u8.astype(np.uint32)
33
+ sign = (u >> 7) & 0x1
34
+ exp = (u >> 3) & 0xF
35
+ mant = u & 0x7
36
+
37
+ # Normal numbers: (-1)^sign * 2^(exp - 7) * (1 + mant / 8)
38
+ # Subnormal numbers (exp == 0): (-1)^sign * 2^(-6) * (mant / 8)
39
+ val = np.where(
40
+ exp == 0,
41
+ (mant.astype(np.float32) / 8.0) * (2.0 ** -6),
42
+ (1.0 + mant.astype(np.float32) / 8.0) * np.exp2(exp.astype(np.float32) - 7.0),
43
+ )
44
+ return np.where(sign == 1, -val, val).astype(np.float32)
45
+
46
+
47
+ def _decode_fp8_e5m2(raw_u8: np.ndarray) -> np.ndarray:
48
+ """Vectorized conversion of 8-bit float (E5M2) bit patterns to float32."""
49
+ u = raw_u8.astype(np.uint16)
50
+ fp16_bits = (u << 8).astype(np.uint16)
51
+ return fp16_bits.view(np.float16).astype(np.float32)
52
+
53
+
54
+ class MMapTensorLoader:
55
+ """Zero-copy mmap tensor reader supporting NumPy, PyTorch, and Apple MLX."""
56
+
57
+ def __init__(self, file_path: Path) -> None:
58
+ self.file_path = Path(file_path)
59
+ if not self.file_path.exists():
60
+ raise FileNotFoundError(f"Weight file not found: {self.file_path}")
61
+
62
+ self.file_obj = open(self.file_path, "rb")
63
+ self.fileno = self.file_obj.fileno()
64
+ self.mmap_obj = mmap.mmap(self.fileno, 0, access=mmap.ACCESS_READ)
65
+ self.header, self.data_offset = self._read_safetensors_header()
66
+
67
+ def _read_safetensors_header(self) -> Tuple[Dict[str, Any], int]:
68
+ """Parse safetensors 8-byte little-endian header and JSON metadata."""
69
+ self.mmap_obj.seek(0)
70
+ header_size_bytes = self.mmap_obj.read(8)
71
+ if len(header_size_bytes) < 8:
72
+ return {}, 0
73
+ header_size = struct.unpack("<Q", header_size_bytes)[0]
74
+ header_json = self.mmap_obj.read(header_size).decode("utf-8")
75
+ header = json.loads(header_json)
76
+ data_offset = 8 + header_size
77
+ return header, data_offset
78
+
79
+ def get_tensor_names(self) -> List[str]:
80
+ """List all tensor names present in this safetensors file."""
81
+ return [k for k in self.header.keys() if k != "__metadata__"]
82
+
83
+ def get_tensor_byte_size(self, name: str) -> int:
84
+ """Return the raw byte size of a tensor from header metadata."""
85
+ if name not in self.header:
86
+ raise KeyError(f"Tensor '{name}' not found in {self.file_path.name}")
87
+ start_rel, end_rel = self.header[name]["data_offsets"]
88
+ return int(end_rel - start_rel)
89
+
90
+ def read_raw_slice(self, name: str) -> Tuple[memoryview, str, Tuple[int, ...]]:
91
+ """Return zero-copy `(memoryview, safetensors_dtype, shape)` for `name`."""
92
+ if name not in self.header:
93
+ raise KeyError(f"Tensor '{name}' not found in {self.file_path.name}")
94
+
95
+ meta = self.header[name]
96
+ dtype_str = str(meta["dtype"])
97
+ if dtype_str not in DTYPE_MAP:
98
+ raise ValueError(f"Unsupported safetensors dtype '{dtype_str}' in {self.file_path.name}")
99
+
100
+ shape = tuple(int(dim) for dim in meta["shape"])
101
+ start_rel, end_rel = meta["data_offsets"]
102
+ abs_start = self.data_offset + int(start_rel)
103
+ abs_end = self.data_offset + int(end_rel)
104
+ return memoryview(self.mmap_obj)[abs_start:abs_end], dtype_str, shape
105
+
106
+ def read_tensor(self, name: str, copy: bool = False) -> np.ndarray:
107
+ """Slice tensor from mmap buffer as a NumPy array (decoding BF16/FP8 to float32)."""
108
+ tensor_bytes, dtype_str, shape = self.read_raw_slice(name)
109
+ dtype = DTYPE_MAP[dtype_str]
110
+ arr = np.frombuffer(tensor_bytes, dtype=dtype)
111
+
112
+ if dtype_str == "BF16":
113
+ arr = (arr.astype(np.uint32) << 16).view(np.float32)
114
+ elif dtype_str == "F8_E4M3":
115
+ arr = _decode_fp8_e4m3(arr)
116
+ elif dtype_str == "F8_E5M2":
117
+ arr = _decode_fp8_e5m2(arr)
118
+ elif copy:
119
+ arr = arr.copy()
120
+
121
+ return arr.reshape(shape)
122
+
123
+ def read_torch_tensor(
124
+ self,
125
+ name: str,
126
+ device: str = "cpu",
127
+ target_dtype: Optional[Any] = None,
128
+ ) -> Any:
129
+ """Materialize a PyTorch tensor in native precision without BF16->FP32 expansion."""
130
+ import torch
131
+
132
+ tensor_bytes, dtype_str, shape = self.read_raw_slice(name)
133
+ if dtype_str == "BF16":
134
+ raw_i16 = np.frombuffer(tensor_bytes, dtype=np.int16).copy().reshape(shape)
135
+ tensor = torch.from_numpy(raw_i16).view(torch.bfloat16)
136
+ elif dtype_str == "F16":
137
+ raw_f16 = np.frombuffer(tensor_bytes, dtype=np.float16).copy().reshape(shape)
138
+ tensor = torch.from_numpy(raw_f16)
139
+ elif dtype_str == "F32":
140
+ raw_f32 = np.frombuffer(tensor_bytes, dtype=np.float32).copy().reshape(shape)
141
+ tensor = torch.from_numpy(raw_f32)
142
+ elif dtype_str in ("F8_E4M3", "F8_E5M2"):
143
+ decoded = self.read_tensor(name, copy=False)
144
+ tensor = torch.from_numpy(decoded)
145
+ else:
146
+ tensor = torch.from_numpy(self.read_tensor(name, copy=True))
147
+
148
+ if target_dtype is not None and tensor.dtype != target_dtype:
149
+ tensor = tensor.to(dtype=target_dtype)
150
+
151
+ target_dev = torch.device(device)
152
+ if tensor.device != target_dev:
153
+ non_blocking = target_dev.type == "cuda"
154
+ tensor = tensor.to(device=target_dev, non_blocking=non_blocking)
155
+ return tensor
156
+
157
+ def read_mlx_array(self, name: str, target_dtype: Optional[Any] = None) -> Any:
158
+ """Materialize an Apple MLX array preserving native BF16/FP16 unified memory layout."""
159
+ import mlx.core as mx
160
+
161
+ tensor_bytes, dtype_str, shape = self.read_raw_slice(name)
162
+ if dtype_str == "BF16":
163
+ raw_u16 = np.frombuffer(tensor_bytes, dtype=np.uint16).reshape(shape)
164
+ arr = mx.array(raw_u16).view(mx.bfloat16)
165
+ elif dtype_str == "F16":
166
+ arr = mx.array(np.frombuffer(tensor_bytes, dtype=np.float16).reshape(shape))
167
+ elif dtype_str == "F32":
168
+ arr = mx.array(np.frombuffer(tensor_bytes, dtype=np.float32).reshape(shape))
169
+ else:
170
+ arr = mx.array(self.read_tensor(name, copy=False))
171
+
172
+ if target_dtype is not None and arr.dtype != target_dtype:
173
+ arr = arr.astype(target_dtype)
174
+ return arr
175
+
176
+ def read_all_tensors(self, copy: bool = False) -> Dict[str, np.ndarray]:
177
+ """Read all tensors in this file into a dictionary."""
178
+ return {name: self.read_tensor(name, copy=copy) for name in self.get_tensor_names()}
179
+
180
+ def close(self) -> None:
181
+ """Close mmap and file descriptors safely even if zero-copy views exist."""
182
+ if not self.mmap_obj.closed:
183
+ try:
184
+ self.mmap_obj.close()
185
+ except BufferError:
186
+ pass
187
+ if not self.file_obj.closed:
188
+ self.file_obj.close()
189
+
190
+ def __enter__(self) -> "MMapTensorLoader":
191
+ return self
192
+
193
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
194
+ self.close()
@@ -0,0 +1,137 @@
1
+ """Model sharder and virtual byte-range indexer for zero-copy streaming."""
2
+
3
+ from pathlib import Path
4
+ from typing import Dict, List, Optional, Tuple
5
+ import os
6
+ import safetensors.numpy
7
+ from phobos_stream.storage.layout import BlockMetadata, ModelShardsManifest
8
+ from phobos_stream.storage.mmap_loader import MMapTensorLoader
9
+
10
+
11
+ BLOCK_PREFIXES: Tuple[str, ...] = (
12
+ "transformer_blocks.",
13
+ "double_blocks.",
14
+ "single_blocks.",
15
+ "blocks.",
16
+ "layers.",
17
+ )
18
+
19
+
20
+ class DiffusionSharder:
21
+ """Partitions or virtual-indexes Diffusion Transformer weights."""
22
+
23
+ def __init__(self, model_dir: Path, output_dir: Optional[Path] = None) -> None:
24
+ self.model_dir = Path(model_dir)
25
+ self.output_dir = Path(output_dir) if output_dir else self.model_dir / "shards"
26
+
27
+ def build_virtual_manifest(
28
+ self,
29
+ architecture: str = "generic_dit",
30
+ hidden_size: int = 4096,
31
+ ) -> ModelShardsManifest:
32
+ """Create a zero-copy virtual manifest from existing monolithic safetensors."""
33
+ if self.model_dir.is_file() and self.model_dir.suffix == ".safetensors":
34
+ safetensor_files = [self.model_dir]
35
+ else:
36
+ safetensor_files = sorted(self.model_dir.glob("*.safetensors"))
37
+
38
+ if not safetensor_files:
39
+ raise FileNotFoundError(f"No safetensors found in {self.model_dir}")
40
+
41
+ blocks: Dict[int, BlockMetadata] = {}
42
+ single_blocks_temp: Dict[int, Tuple[str, List[str], int]] = {}
43
+ text_encoder_path: Optional[str] = None
44
+ vae_path: Optional[str] = None
45
+
46
+ for sf in safetensor_files:
47
+ fname = sf.name.lower()
48
+ if "text_encoder" in fname or "t5" in fname or "clip" in fname or "qwen" in fname:
49
+ text_encoder_path = str(sf.resolve())
50
+ elif "vae" in fname or fname == "ae.safetensors":
51
+ vae_path = str(sf.resolve())
52
+
53
+ with MMapTensorLoader(sf) as loader:
54
+ tensor_names = loader.get_tensor_names()
55
+ for t_name in tensor_names:
56
+ for prefix in BLOCK_PREFIXES:
57
+ if prefix in t_name:
58
+ parts = t_name.split(prefix, 1)[1].split(".")
59
+ if parts[0].isdigit():
60
+ raw_idx = int(parts[0])
61
+ t_bytes = loader.get_tensor_byte_size(t_name)
62
+ if prefix == "single_blocks.":
63
+ if raw_idx not in single_blocks_temp:
64
+ single_blocks_temp[raw_idx] = (str(sf.resolve()), [], 0)
65
+ fn, t_list, b_sz = single_blocks_temp[raw_idx]
66
+ t_list.append(t_name)
67
+ single_blocks_temp[raw_idx] = (fn, t_list, b_sz + t_bytes)
68
+ else:
69
+ if raw_idx not in blocks:
70
+ blocks[raw_idx] = BlockMetadata(
71
+ block_id=raw_idx,
72
+ filename=str(sf.resolve()),
73
+ tensor_names=[],
74
+ byte_size=0,
75
+ )
76
+ blocks[raw_idx].tensor_names.append(t_name)
77
+ blocks[raw_idx].byte_size += t_bytes
78
+ break
79
+
80
+ # Append single_blocks after double_blocks so they don't overwrite double_blocks[0..N]
81
+ if single_blocks_temp:
82
+ offset = (max(blocks.keys()) + 1) if blocks else 0
83
+ for raw_idx in sorted(single_blocks_temp.keys()):
84
+ fn, t_list, b_sz = single_blocks_temp[raw_idx]
85
+ b_id = offset + raw_idx
86
+ blocks[b_id] = BlockMetadata(
87
+ block_id=b_id,
88
+ filename=fn,
89
+ tensor_names=t_list,
90
+ byte_size=b_sz,
91
+ )
92
+
93
+ manifest = ModelShardsManifest(
94
+ model_name=self.model_dir.stem if self.model_dir.is_file() else self.model_dir.name,
95
+ architecture=architecture,
96
+ num_blocks=len(blocks) if blocks else 1,
97
+ hidden_size=hidden_size,
98
+ text_encoder_path=text_encoder_path,
99
+ vae_path=vae_path,
100
+ blocks=blocks,
101
+ )
102
+ return manifest
103
+
104
+ def partition_to_disk(self, manifest: ModelShardsManifest) -> Path:
105
+ """Physical sharding helper when offline partitioning is explicitly requested."""
106
+ self.output_dir.mkdir(parents=True, exist_ok=True)
107
+ blocks_dir = self.output_dir / "blocks"
108
+ blocks_dir.mkdir(exist_ok=True)
109
+
110
+ new_blocks: Dict[int, BlockMetadata] = {}
111
+ for b_id, meta in manifest.blocks.items():
112
+ with MMapTensorLoader(Path(meta.filename)) as loader:
113
+ block_tensors = {t_name: loader.read_tensor(t_name, copy=True) for t_name in meta.tensor_names}
114
+
115
+ shard_file = blocks_dir / f"block_{b_id:03d}.safetensors"
116
+ safetensors.numpy.save_file(block_tensors, str(shard_file))
117
+
118
+ new_blocks[b_id] = BlockMetadata(
119
+ block_id=b_id,
120
+ filename=str(shard_file.resolve()),
121
+ tensor_names=meta.tensor_names,
122
+ byte_size=os.path.getsize(shard_file),
123
+ )
124
+
125
+ partitioned_manifest = ModelShardsManifest(
126
+ model_name=manifest.model_name,
127
+ architecture=manifest.architecture,
128
+ num_blocks=manifest.num_blocks,
129
+ hidden_size=manifest.hidden_size,
130
+ text_encoder_path=manifest.text_encoder_path,
131
+ vae_path=manifest.vae_path,
132
+ blocks=new_blocks,
133
+ allow_synthetic=manifest.allow_synthetic,
134
+ )
135
+ manifest_path = self.output_dir / "manifest.json"
136
+ partitioned_manifest.save(manifest_path)
137
+ return manifest_path
@@ -0,0 +1,15 @@
1
+ """Hook-based block-by-block weight streaming for PyTorch and Apple MLX models."""
2
+
3
+ from phobos_stream.streaming.mlx_block_streamer import MLXBlockStreamer
4
+ from phobos_stream.streaming.torch_block_streamer import (
5
+ BlockStreamMode,
6
+ TorchBlockStreamer,
7
+ discover_block_modules,
8
+ )
9
+
10
+ __all__ = [
11
+ "BlockStreamMode",
12
+ "MLXBlockStreamer",
13
+ "TorchBlockStreamer",
14
+ "discover_block_modules",
15
+ ]
@@ -0,0 +1,159 @@
1
+ """Per-block `.safetensors` mmap weight streamer for Apple Silicon MLX models."""
2
+
3
+ from pathlib import Path
4
+ from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
5
+
6
+ from phobos_stream.storage.mmap_loader import MMapTensorLoader
7
+
8
+
9
+ class MLXBlockStreamer:
10
+ """Streams MLX transformer blocks one-by-one from `.safetensors` mmap on Apple Silicon.
11
+
12
+ On Unified Memory Macs, MLX evaluates computation graphs lazily by default; if all
13
+ blocks run without evaluation boundaries, MLX holds every block's weights in Metal
14
+ memory simultaneously. `MLXBlockStreamer` forces `mx.eval` at each block boundary
15
+ and immediately evicts the finished block's weight arrays back to `(0,)` placeholders.
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ blocks: Sequence[Any],
21
+ safetensors_paths: Sequence[Union[str, Path]],
22
+ block_prefix_template: str = "layers.{i}",
23
+ ) -> None:
24
+ if not safetensors_paths:
25
+ raise ValueError("MLXBlockStreamer requires at least one `.safetensors` path.")
26
+
27
+ self.blocks = list(blocks)
28
+ self.safetensors_paths = [Path(p) for p in safetensors_paths]
29
+ self.block_prefix_template = block_prefix_template
30
+ self.bytes_streamed: int = 0
31
+ self.blocks_executed: int = 0
32
+
33
+ self._loaders: List[MMapTensorLoader] = []
34
+ self._block_specs: Dict[int, List[Tuple[str, MMapTensorLoader, str, Any]]] = {}
35
+ self._closed = False
36
+
37
+ self._index_and_evict_all()
38
+
39
+ def _build_index(self) -> Dict[str, Tuple[MMapTensorLoader, str]]:
40
+ index: Dict[str, Tuple[MMapTensorLoader, str]] = {}
41
+ for path in self.safetensors_paths:
42
+ loader = MMapTensorLoader(path)
43
+ self._loaders.append(loader)
44
+ for key in loader.get_tensor_names():
45
+ index[key] = (loader, key)
46
+ for pfx in ("model.diffusion_model.", "diffusion_model.", "transformer.", "model."):
47
+ if key.startswith(pfx):
48
+ index.setdefault(key[len(pfx) :], (loader, key))
49
+ return index
50
+
51
+ def _index_and_evict_all(self) -> None:
52
+ import mlx.core as mx
53
+ from mlx.utils import tree_flatten, tree_unflatten
54
+
55
+ try:
56
+ st_index = self._build_index()
57
+ for idx, blk in enumerate(self.blocks):
58
+ prefix = self.block_prefix_template.format(i=idx)
59
+ flat_params = tree_flatten(blk.parameters())
60
+ specs: List[Tuple[str, MMapTensorLoader, str, Any]] = []
61
+ empty_leaves: List[Tuple[str, Any]] = []
62
+
63
+ for rel_key, arr in flat_params:
64
+ full_key = f"{prefix}.{rel_key}" if prefix else rel_key
65
+ if full_key not in st_index:
66
+ raise KeyError(
67
+ f"Missing MLX block weight '{full_key}' in {[p.name for p in self.safetensors_paths]}."
68
+ )
69
+ loader, real_key = st_index[full_key]
70
+ specs.append((rel_key, loader, real_key, arr.dtype))
71
+ empty_leaves.append((rel_key, mx.zeros((0,), dtype=arr.dtype)))
72
+
73
+ self._block_specs[idx] = specs
74
+ blk.update(tree_unflatten(empty_leaves))
75
+ mx.eval(blk.parameters())
76
+
77
+ if hasattr(mx, "clear_cache"):
78
+ mx.clear_cache()
79
+ except Exception:
80
+ self.close()
81
+ raise
82
+
83
+ def evict_block(self, block_idx: int) -> None:
84
+ """Replace a block's active MLX parameter arrays with 0-element placeholders."""
85
+ import mlx.core as mx
86
+ from mlx.utils import tree_unflatten
87
+
88
+ specs = self._block_specs[block_idx]
89
+ blk = self.blocks[block_idx]
90
+ empty_leaves = [(rel_key, mx.zeros((0,), dtype=orig_dtype)) for rel_key, _, _, orig_dtype in specs]
91
+ blk.update(tree_unflatten(empty_leaves))
92
+ mx.eval(blk.parameters())
93
+ if hasattr(mx, "clear_cache"):
94
+ mx.clear_cache()
95
+
96
+ def stream_block_call(self, block_idx: int, *args: Any, **kwargs: Any) -> Any:
97
+ """Materialize `block_idx` weights, execute its forward pass, evaluate, and evict."""
98
+ import mlx.core as mx
99
+ from mlx.utils import tree_flatten, tree_unflatten
100
+
101
+ if self._closed:
102
+ raise RuntimeError("MLXBlockStreamer is already closed.")
103
+
104
+ specs = self._block_specs[block_idx]
105
+ blk = self.blocks[block_idx]
106
+
107
+ loaded_leaves: List[Tuple[str, Any]] = []
108
+ bytes_this_block = 0
109
+ for rel_key, loader, real_key, orig_dtype in specs:
110
+ arr = loader.read_mlx_array(real_key, target_dtype=orig_dtype)
111
+ loaded_leaves.append((rel_key, arr))
112
+ bytes_this_block += loader.get_tensor_byte_size(real_key)
113
+
114
+ blk.update(tree_unflatten(loaded_leaves))
115
+ mx.eval(blk.parameters())
116
+ del loaded_leaves
117
+
118
+ out = blk(*args, **kwargs)
119
+ out_arrays = [v for _, v in tree_flatten(out) if isinstance(v, mx.array)]
120
+ if out_arrays:
121
+ mx.eval(*out_arrays)
122
+
123
+ self.bytes_streamed += bytes_this_block
124
+ self.blocks_executed += 1
125
+ self.evict_block(block_idx)
126
+ return out
127
+
128
+ def run_sequence(self, x: Any, *args: Any, **kwargs: Any) -> Any:
129
+ """Stream and execute all indexed blocks sequentially on input `x`."""
130
+ cur = x
131
+ for idx in range(len(self.blocks)):
132
+ cur = self.stream_block_call(idx, cur, *args, **kwargs)
133
+ return cur
134
+
135
+ def restore_all(self) -> None:
136
+ """Reload full weights into all MLX blocks from `.safetensors`."""
137
+ import mlx.core as mx
138
+ from mlx.utils import tree_unflatten
139
+
140
+ for idx, blk in enumerate(self.blocks):
141
+ leaves = [
142
+ (rel_key, loader.read_mlx_array(real_key, target_dtype=orig_dtype))
143
+ for rel_key, loader, real_key, orig_dtype in self._block_specs[idx]
144
+ ]
145
+ blk.update(tree_unflatten(leaves))
146
+ mx.eval(blk.parameters())
147
+
148
+ def close(self) -> None:
149
+ """Close all underlying `MMapTensorLoader` file handles."""
150
+ for loader in self._loaders:
151
+ loader.close()
152
+ self._loaders.clear()
153
+ self._closed = True
154
+
155
+ def __enter__(self) -> "MLXBlockStreamer":
156
+ return self
157
+
158
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
159
+ self.close()