idol-mlx 0.1.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.
idol_mlx/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Photo to 3D Gaussian splat on Apple Silicon with Idol + Idol Turbo (unofficial)."""
2
+
3
+ from .client import GenerationError, Idol, Progress
4
+ from .splat import Splat
5
+
6
+ __all__ = ["GenerationError", "Idol", "Progress", "Splat"]
7
+ __version__ = "0.1.0"
idol_mlx/cli.py ADDED
@@ -0,0 +1,313 @@
1
+ """idol-mlx: photo to 3D Gaussian splat on Apple Silicon."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import platform
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+
11
+ from rich.console import Console
12
+ from rich.progress import BarColumn, Progress, TaskProgressColumn, TextColumn, TimeElapsedColumn
13
+
14
+ from . import __version__, pack, server
15
+ from .client import GenerationError, Idol, check_settings
16
+ from .client import Progress as StageProgress
17
+ from .server import ServerError
18
+ from .turntable import TurntableError, check_turntable_tools, render_frames, write_animation
19
+
20
+ IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".webp", ".heic", ".bmp", ".tif", ".tiff"}
21
+
22
+ PRESETS = {
23
+ "fast": {"steps": 4, "guidance": 0.0, "gaussians": 65_536},
24
+ "default": {"steps": 5, "guidance": 0.0, "gaussians": 262_144},
25
+ "high": {"steps": 8, "guidance": 0.0, "gaussians": 262_144},
26
+ "original": {"steps": 50, "guidance": 3.0, "gaussians": 262_144},
27
+ }
28
+
29
+ STAGE_LABELS = {
30
+ "idol-preprocess": "preparing image",
31
+ "idol-matte": "removing background",
32
+ "idol-condition": "encoding image",
33
+ "idol-denoise": "denoising",
34
+ "idol-octree": "decoding octree",
35
+ "idol-gaussians": "decoding Gaussians",
36
+ }
37
+
38
+ console = Console()
39
+
40
+
41
+ def main(argv: list[str] | None = None) -> int:
42
+ argv = sys.argv[1:] if argv is None else argv
43
+ if argv[:1] == ["setup"]:
44
+ return _guarded(cmd_setup, _setup_parser().parse_args(argv[1:]))
45
+ if argv[:1] == ["uninstall"]:
46
+ return _guarded(cmd_uninstall, _uninstall_parser().parse_args(argv[1:]))
47
+ if argv[:1] == ["view"]:
48
+ return _guarded(cmd_view, _view_parser().parse_args(argv[1:]))
49
+ if argv[:1] == ["turntable"]:
50
+ return _guarded(cmd_turntable, _turntable_parser().parse_args(argv[1:]))
51
+ return _guarded(cmd_generate, _generate_parser().parse_args(argv))
52
+
53
+
54
+ def _guarded(command, args) -> int:
55
+ if platform.system() != "Darwin" or platform.machine() != "arm64":
56
+ console.print("[red]idol-mlx needs an Apple Silicon Mac.[/red] On NVIDIA GPUs, use Idol's own SDK.")
57
+ return 1
58
+ try:
59
+ return command(args)
60
+ except KeyboardInterrupt:
61
+ console.print("\nStopped.")
62
+ return 130
63
+ except (ServerError, GenerationError, TurntableError, ValueError, FileNotFoundError) as err:
64
+ console.print(f"[red]Error:[/red] {err}")
65
+ return 1
66
+
67
+
68
+ # ---------------------------------------------------------------- generate
69
+
70
+
71
+ def _generate_parser() -> argparse.ArgumentParser:
72
+ p = argparse.ArgumentParser(
73
+ prog="idol-mlx",
74
+ description="Turn a photo of an object into a 3D Gaussian splat, locally on Apple Silicon.",
75
+ epilog="Other commands: `idol-mlx view FILE.ply…` (open existing splats), "
76
+ "`idol-mlx turntable FILE.ply` (spinning GIF/MP4 of an existing splat), "
77
+ "`idol-mlx setup` (install everything without generating), `idol-mlx uninstall`.",
78
+ )
79
+ p.add_argument("inputs", nargs="+", type=Path, help="image files or folders of images")
80
+ p.add_argument("-o", "--output", type=Path, help="output folder (default: next to each image)")
81
+ p.add_argument("--format", choices=["ply", "glb"], default="ply", help="output format (default: ply)")
82
+ p.add_argument("--view", action="store_true", help="open the results in a browser viewer")
83
+ p.add_argument("--turntable", nargs="?", const="gif", choices=["gif", "mp4"],
84
+ help="also save a spinning animation of each result (default: gif)") # fmt: skip
85
+ preset = p.add_mutually_exclusive_group()
86
+ preset.add_argument("--fast", action="store_true", help="4 steps, 65k Gaussians (~12 s)")
87
+ preset.add_argument("--quality", choices=["high"], help="'high': 8 steps (~23 s)")
88
+ preset.add_argument("--original", action="store_true", help="base Idol, 50 steps + guidance (~3 min)")
89
+ p.add_argument("--steps", type=int, help="override the preset's step count")
90
+ p.add_argument("--gaussians", type=int, help="override the preset's Gaussian count (32768 to 1048576)")
91
+ p.add_argument("--seed", type=int, default=42, help="change for a different take (default: 42)")
92
+ p.add_argument("--mode", choices=["synthetic", "real"], default="synthetic",
93
+ help="'real' frames photographs more loosely (default: synthetic, for renders)") # fmt: skip
94
+ p.add_argument("--keep-server", action="store_true", help="leave mlx-serve running afterwards")
95
+ p.add_argument("--version", action="version", version=f"idol-mlx {__version__}")
96
+ return p
97
+
98
+
99
+ def cmd_generate(args: argparse.Namespace) -> int:
100
+ images = _collect_images(args.inputs)
101
+ preset_name = (
102
+ "original" if args.original else "fast" if args.fast else "high" if args.quality else "default"
103
+ )
104
+ settings = dict(PRESETS[preset_name])
105
+ if args.steps is not None:
106
+ settings["steps"] = args.steps
107
+ if args.gaussians is not None:
108
+ settings["gaussians"] = args.gaussians
109
+ check_settings(steps=settings["steps"], gaussians=settings["gaussians"], mode=args.mode)
110
+ if args.turntable:
111
+ check_turntable_tools(args.turntable)
112
+
113
+ _ensure_mlx_serve_installed(assume_yes=False)
114
+ if args.output:
115
+ args.output.mkdir(parents=True, exist_ok=True)
116
+
117
+ if args.original:
118
+ pack.ensure_base_pack(log=_log)
119
+ else:
120
+ pack.ensure_turbo_pack(log=_log)
121
+ with console.status("Starting mlx-serve…"):
122
+ idol = Idol(keep_server=args.keep_server, original=args.original)
123
+ written: list[Path] = []
124
+ spins: list[tuple[Path, bytes]] = []
125
+ try:
126
+ for image in images:
127
+ out_dir = args.output or image.parent
128
+ out_path = out_dir / f"{image.stem}.{args.format}"
129
+ started = time.monotonic()
130
+ splat = _generate_with_progress(idol, image, settings, args)
131
+ splat.save(out_path)
132
+ elapsed = time.monotonic() - started
133
+ console.print(
134
+ f"[green]✓[/green] {out_path} [dim]{len(splat):,} Gaussians · {elapsed:.1f} s[/dim]"
135
+ )
136
+ written.append(out_path)
137
+ if args.turntable:
138
+ spins.append((out_dir / f"{image.stem}.{args.turntable}", splat.to_ply()))
139
+ finally:
140
+ idol.close()
141
+
142
+ for spin_path, ply in spins: # after the server stops, so the browser has the GPU to itself
143
+ _render_turntable(ply, spin_path)
144
+
145
+ if args.view:
146
+ plys = [p for p in written if p.suffix == ".ply"]
147
+ if not plys:
148
+ console.print("The viewer shows .ply files; rerun without --format glb to view them.")
149
+ return 0
150
+ from .viewer import serve
151
+
152
+ serve(plys)
153
+ return 0
154
+
155
+
156
+ def _generate_with_progress(idol: Idol, image: Path, settings: dict, args: argparse.Namespace):
157
+ columns = (
158
+ TextColumn("[bold]{task.fields[name]}[/bold]"),
159
+ TextColumn("{task.description}", style="dim"),
160
+ BarColumn(bar_width=28),
161
+ TaskProgressColumn(),
162
+ TimeElapsedColumn(),
163
+ )
164
+ with Progress(*columns, console=console, transient=True) as bar:
165
+ task = bar.add_task("starting", total=None, name=image.name)
166
+
167
+ def on_progress(p: StageProgress) -> None:
168
+ label = STAGE_LABELS.get(p.stage, p.stage)
169
+ if p.stage == "idol-denoise":
170
+ label = f"denoising {p.step}/{p.total}"
171
+ bar.update(task, description=label, completed=p.step, total=p.total)
172
+
173
+ return idol.generate(image, seed=args.seed, mode=args.mode, on_progress=on_progress, **settings)
174
+
175
+
176
+ def _log(message: str) -> None:
177
+ console.print(f"[dim]•[/dim] {message}")
178
+
179
+
180
+ def _collect_images(inputs: list[Path]) -> list[Path]:
181
+ images: list[Path] = []
182
+ for path in inputs:
183
+ if path.is_dir():
184
+ found = sorted(p for p in path.iterdir() if p.suffix.lower() in IMAGE_SUFFIXES)
185
+ if not found:
186
+ raise FileNotFoundError(f"No images in {path}")
187
+ images.extend(found)
188
+ elif path.is_file():
189
+ images.append(path)
190
+ else:
191
+ raise FileNotFoundError(f"{path} doesn't exist")
192
+ return images
193
+
194
+
195
+ # ---------------------------------------------------------------- view / setup / uninstall
196
+
197
+
198
+ def _turntable_parser() -> argparse.ArgumentParser:
199
+ p = argparse.ArgumentParser(
200
+ prog="idol-mlx turntable",
201
+ description="Save a spinning animation of a .ply splat. Needs Google Chrome (or Chromium, Brave, Edge).",
202
+ )
203
+ p.add_argument("file", type=Path, help="a .ply splat")
204
+ p.add_argument("-o", "--output", type=Path, help="output .gif or .mp4 (default: FILE.gif)")
205
+ p.add_argument("--frames", type=int, default=72, help="frames per full turn (default: 72)")
206
+ p.add_argument("--size", type=int, default=640, help="width and height in pixels (default: 640)")
207
+ p.add_argument("--fps", type=int, default=18, help="frames per second (default: 18)")
208
+ return p
209
+
210
+
211
+ def cmd_turntable(args: argparse.Namespace) -> int:
212
+ if not args.file.is_file() or args.file.suffix.lower() != ".ply":
213
+ raise FileNotFoundError(f"{args.file} isn't a .ply file")
214
+ out_path = args.output or args.file.with_suffix(".gif")
215
+ check_turntable_tools(out_path.suffix.lstrip(".").lower())
216
+ _render_turntable(args.file.read_bytes(), out_path, frames=args.frames, size=args.size, fps=args.fps)
217
+ return 0
218
+
219
+
220
+ def _render_turntable(ply: bytes, out_path: Path, frames: int = 72, size: int = 640, fps: int = 18) -> None:
221
+ started = time.monotonic()
222
+ with Progress(
223
+ TextColumn("[bold]{task.fields[name]}[/bold]"),
224
+ TextColumn("rendering turntable", style="dim"),
225
+ BarColumn(bar_width=28),
226
+ TaskProgressColumn(),
227
+ console=console,
228
+ transient=True,
229
+ ) as bar:
230
+ task = bar.add_task("", total=frames, name=out_path.name)
231
+ images = render_frames(
232
+ ply, frames=frames, size=size, on_frame=lambda n, _: bar.update(task, completed=n)
233
+ )
234
+ write_animation(images, out_path, fps=fps)
235
+ elapsed = time.monotonic() - started
236
+ size_mb = out_path.stat().st_size / 1e6
237
+ console.print(
238
+ f"[green]✓[/green] {out_path} [dim]{frames} frames · {size_mb:.1f} MB · {elapsed:.1f} s[/dim]"
239
+ )
240
+
241
+
242
+ def _view_parser() -> argparse.ArgumentParser:
243
+ p = argparse.ArgumentParser(prog="idol-mlx view", description="Open .ply splats in a browser viewer.")
244
+ p.add_argument("files", nargs="+", type=Path, help=".ply files, or folders of them")
245
+ p.add_argument("--no-browser", action="store_true", help="print the URL instead of opening it")
246
+ return p
247
+
248
+
249
+ def cmd_view(args: argparse.Namespace) -> int:
250
+ from .viewer import serve
251
+
252
+ plys: list[Path] = []
253
+ for path in args.files:
254
+ if path.is_dir():
255
+ plys.extend(sorted(path.glob("*.ply")))
256
+ elif path.is_file() and path.suffix.lower() == ".ply":
257
+ plys.append(path)
258
+ else:
259
+ raise FileNotFoundError(f"{path} isn't a .ply file or a folder")
260
+ if not plys:
261
+ raise FileNotFoundError("No .ply files to show")
262
+ serve(plys, open_browser=not args.no_browser)
263
+ return 0
264
+
265
+
266
+ def _setup_parser() -> argparse.ArgumentParser:
267
+ p = argparse.ArgumentParser(
268
+ prog="idol-mlx setup", description="Install mlx-serve and build the Turbo pack."
269
+ )
270
+ p.add_argument("-y", "--yes", action="store_true", help="install mlx-serve without asking")
271
+ return p
272
+
273
+
274
+ def cmd_setup(args: argparse.Namespace) -> int:
275
+ _ensure_mlx_serve_installed(assume_yes=args.yes)
276
+ pack.ensure_turbo_pack(log=_log)
277
+ console.print("[green]Ready.[/green] Try: idol-mlx photo.jpg --view")
278
+ return 0
279
+
280
+
281
+ def _uninstall_parser() -> argparse.ArgumentParser:
282
+ p = argparse.ArgumentParser(
283
+ prog="idol-mlx uninstall", description="Remove the model packs idol-mlx added."
284
+ )
285
+ p.add_argument("--all", action="store_true", help="also remove the base Idol pack (~3 GB)")
286
+ return p
287
+
288
+
289
+ def cmd_uninstall(args: argparse.Namespace) -> int:
290
+ if pack.remove_turbo_pack():
291
+ console.print(f"Removed {pack.TURBO_DIR}")
292
+ if args.all and pack.remove_base_pack():
293
+ console.print(f"Removed {pack.BASE_DIR}")
294
+ console.print("mlx-serve itself stays installed; remove it with `brew uninstall mlx-serve`.")
295
+ return 0
296
+
297
+
298
+ def _ensure_mlx_serve_installed(assume_yes: bool) -> None:
299
+ if server.find_binary():
300
+ return
301
+ console.print("idol-mlx runs the model with [bold]mlx-serve[/bold], which isn't installed.")
302
+ console.print("It installs from its Homebrew tap: github.com/ddalcu/mlx-serve")
303
+ if not assume_yes:
304
+ answer = console.input("Install it now with Homebrew? [y/N] ").strip().lower()
305
+ if answer not in ("y", "yes"):
306
+ raise ServerError(
307
+ "mlx-serve is required. Install it with `idol-mlx setup` or from its GitHub page."
308
+ )
309
+ server.install_with_homebrew()
310
+
311
+
312
+ if __name__ == "__main__":
313
+ raise SystemExit(main())
idol_mlx/client.py ADDED
@@ -0,0 +1,155 @@
1
+ """Generate splats through mlx-serve's /v1/3d/generations endpoint."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import io
7
+ import json
8
+ import urllib.error
9
+ import urllib.request
10
+ from collections.abc import Callable
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Self
14
+
15
+ from PIL import Image
16
+
17
+ from . import pack
18
+ from .server import DEFAULT_URL, Server, ensure_server, rescan
19
+ from .splat import Splat
20
+
21
+ MIN_STEPS = 1
22
+ MAX_STEPS = 200
23
+ MIN_GAUSSIANS = 32_768
24
+ MAX_GAUSSIANS = 1_048_576
25
+ REQUEST_TIMEOUT_S = 1800
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Progress:
30
+ stage: str # e.g. "idol-denoise"
31
+ step: int
32
+ total: int
33
+
34
+
35
+ ProgressCallback = Callable[[Progress], None]
36
+
37
+
38
+ class GenerationError(RuntimeError):
39
+ pass
40
+
41
+
42
+ def check_settings(*, steps: int, gaussians: int, mode: str) -> None:
43
+ """Reject values mlx-serve would refuse, before any server or model work starts."""
44
+ if not MIN_STEPS <= steps <= MAX_STEPS:
45
+ raise ValueError(f"steps must be between {MIN_STEPS} and {MAX_STEPS}, got {steps}")
46
+ if not MIN_GAUSSIANS <= gaussians <= MAX_GAUSSIANS:
47
+ raise ValueError(
48
+ f"gaussians must be between {MIN_GAUSSIANS:,} and {MAX_GAUSSIANS:,}, got {gaussians:,}"
49
+ )
50
+ if mode not in ("synthetic", "real"):
51
+ raise ValueError(f"mode must be 'synthetic' or 'real', got {mode!r}")
52
+
53
+
54
+ class Idol:
55
+ """Image to Gaussian splat with Idol Turbo on a local mlx-serve.
56
+
57
+ >>> idol = Idol()
58
+ >>> idol.generate("photo.jpg").save("photo.ply")
59
+ """
60
+
61
+ def __init__(self, url: str = DEFAULT_URL, keep_server: bool = False, original: bool = False):
62
+ self.model = pack.BASE_MODEL_ID if original else pack.TURBO_MODEL_ID
63
+ if original:
64
+ pack.ensure_base_pack()
65
+ else:
66
+ pack.ensure_turbo_pack()
67
+ self.server: Server = ensure_server(url, keep_running=keep_server)
68
+ if not self.server.has_model(self.model):
69
+ rescan(self.server.url)
70
+ if not self.server.has_model(self.model):
71
+ raise GenerationError(f"mlx-serve at {self.server.url} doesn't list the model {self.model}")
72
+
73
+ def generate(
74
+ self,
75
+ image: str | Path | bytes | Image.Image,
76
+ *,
77
+ steps: int = 5,
78
+ guidance: float = 0.0,
79
+ gaussians: int = 262_144,
80
+ seed: int = 42,
81
+ mode: str = "synthetic",
82
+ on_progress: ProgressCallback | None = None,
83
+ ) -> Splat:
84
+ check_settings(steps=steps, gaussians=gaussians, mode=mode)
85
+ body = {
86
+ "model": self.model,
87
+ "image": base64.b64encode(_png_or_jpeg(image)).decode(),
88
+ "steps": steps,
89
+ "guidance_scale": guidance,
90
+ "num_gaussians": gaussians,
91
+ "seed": seed,
92
+ "mode": mode,
93
+ "geometry": "splat",
94
+ "stream": True,
95
+ }
96
+ request = urllib.request.Request(
97
+ f"{self.server.url}/v1/3d/generations",
98
+ data=json.dumps(body).encode(),
99
+ headers={"content-type": "application/json"},
100
+ )
101
+ try:
102
+ response = urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_S)
103
+ except urllib.error.HTTPError as err:
104
+ raise GenerationError(
105
+ f"mlx-serve refused the request ({err.code}): {_error_message(err)}"
106
+ ) from err
107
+
108
+ with response:
109
+ for raw in response:
110
+ line = raw.decode().strip()
111
+ if not line.startswith("data:"):
112
+ continue
113
+ event = json.loads(line[len("data:") :])
114
+ kind = event.get("type")
115
+ if kind == "progress" and on_progress:
116
+ on_progress(Progress(event["stage"], event["step"], event["total"]))
117
+ elif kind == "complete":
118
+ if event.get("format") != "glb":
119
+ raise GenerationError(f"Expected a GLB from mlx-serve, got {event.get('format')!r}")
120
+ return Splat.from_glb(base64.b64decode(event["data"]))
121
+ elif kind == "error":
122
+ raise GenerationError(f"mlx-serve failed: {event.get('message') or event}")
123
+ raise GenerationError("mlx-serve closed the stream before sending a result")
124
+
125
+ def close(self) -> None:
126
+ self.server.stop()
127
+
128
+ def __enter__(self) -> Self:
129
+ return self
130
+
131
+ def __exit__(self, *exc) -> None:
132
+ self.close()
133
+
134
+
135
+ def _png_or_jpeg(image: str | Path | bytes | Image.Image) -> bytes:
136
+ """mlx-serve decodes PNG and JPEG; anything else (WebP, HEIC, …) is converted to PNG first."""
137
+ if isinstance(image, Image.Image):
138
+ return _to_png(image)
139
+ data = image if isinstance(image, bytes) else Path(image).read_bytes()
140
+ if data[:8] == b"\x89PNG\r\n\x1a\n" or data[:3] == b"\xff\xd8\xff":
141
+ return data
142
+ return _to_png(Image.open(io.BytesIO(data)))
143
+
144
+
145
+ def _to_png(image: Image.Image) -> bytes:
146
+ buffer = io.BytesIO()
147
+ image.convert("RGBA" if "A" in image.getbands() else "RGB").save(buffer, format="PNG")
148
+ return buffer.getvalue()
149
+
150
+
151
+ def _error_message(err: urllib.error.HTTPError) -> str:
152
+ try:
153
+ return json.loads(err.read())["error"]["message"]
154
+ except (ValueError, KeyError, TypeError):
155
+ return str(err.reason)
idol_mlx/pack.py ADDED
@@ -0,0 +1,159 @@
1
+ """The model packs mlx-serve loads: the base 8-bit Idol pack, and the Turbo pack built from it.
2
+
3
+ The Turbo pack is the base pack with one file replaced: Idol's denoiser with Idol Turbo's high-noise ("slow") LoRA
4
+ expert merged into its weights (W' = W + alpha/rank * B @ A), then quantized exactly the way the base pack was.
5
+ To mlx-serve it is plain Idol, so it runs Turbo without adapter support.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import shutil
12
+ from collections.abc import Callable
13
+ from pathlib import Path
14
+
15
+ from huggingface_hub import hf_hub_download, snapshot_download
16
+
17
+ from .server import MODELS_DIR
18
+
19
+ BASE_REPO = "ddalcu/Idol-MLX-Serve-8bit"
20
+ IDOL_REPO = "speridlabs/idol"
21
+ TURBO_REPO = "speridlabs/idol-turbo"
22
+ TURBO_LORA_FILE = "idol_turbo_lora.safetensors"
23
+
24
+ BASE_MODEL_ID = "Idol-MLX-Serve-8bit"
25
+ TURBO_MODEL_ID = "Idol-Turbo"
26
+ BASE_DIR = MODELS_DIR / BASE_MODEL_ID
27
+ TURBO_DIR = MODELS_DIR / TURBO_MODEL_ID
28
+ MARKER = "idol-mlx.json"
29
+
30
+ LORA_RANK = 32
31
+ LORA_ALPHA = 128.0 # from idol-turbo's turbo.py
32
+ EXPERT = "slow"
33
+ GROUP_SIZE = 64
34
+ BITS = 8
35
+ BLOCK_PREFIXES = ("blocks.", "noise_refiner.", "context_refiner.")
36
+
37
+ Log = Callable[[str], None]
38
+
39
+
40
+ def turbo_ready() -> bool:
41
+ return (TURBO_DIR / MARKER).exists() and (TURBO_DIR / "denoiser.safetensors").exists()
42
+
43
+
44
+ def base_ready() -> bool:
45
+ return (BASE_DIR / "config.json").exists() and (BASE_DIR / "denoiser.safetensors").exists()
46
+
47
+
48
+ def ensure_base_pack(log: Log = print) -> Path:
49
+ if base_ready():
50
+ return BASE_DIR
51
+ log(f"Downloading the base Idol pack ({BASE_REPO}, about 3 GB, once)")
52
+ snapshot_download(BASE_REPO, local_dir=BASE_DIR)
53
+ return BASE_DIR
54
+
55
+
56
+ def ensure_turbo_pack(log: Log = print) -> Path:
57
+ """Build ~/.mlx-serve/models/Idol-Turbo if it isn't there yet. Safe to interrupt and rerun."""
58
+ if turbo_ready():
59
+ return TURBO_DIR
60
+ ensure_base_pack(log)
61
+
62
+ log(
63
+ f"Downloading Idol's full-precision denoiser ({IDOL_REPO}, 1.5 GB) and the Turbo adapter ({TURBO_REPO})"
64
+ )
65
+ denoiser_path = hf_hub_download(IDOL_REPO, "denoiser.safetensors")
66
+ lora_path = hf_hub_download(TURBO_REPO, TURBO_LORA_FILE)
67
+
68
+ log("Merging the Turbo adapter into the denoiser")
69
+ building = TURBO_DIR.with_name(TURBO_DIR.name + ".building")
70
+ shutil.rmtree(building, ignore_errors=True)
71
+ building.mkdir(parents=True)
72
+ layers = merge_and_quantize(Path(denoiser_path), Path(lora_path), building / "denoiser.safetensors")
73
+
74
+ for entry in BASE_DIR.iterdir():
75
+ if entry.name not in {"denoiser.safetensors", MARKER} and not entry.name.startswith("."):
76
+ (building / entry.name).symlink_to(entry.resolve())
77
+ (building / MARKER).write_text(
78
+ json.dumps(
79
+ {
80
+ "base": BASE_REPO,
81
+ "denoiser": IDOL_REPO,
82
+ "adapter": f"{TURBO_REPO}/{TURBO_LORA_FILE}",
83
+ "expert": EXPERT,
84
+ "merged_layers": layers,
85
+ "bits": BITS,
86
+ },
87
+ indent=2,
88
+ )
89
+ )
90
+ shutil.rmtree(TURBO_DIR, ignore_errors=True)
91
+ building.rename(TURBO_DIR)
92
+ log(f"Turbo pack ready at {TURBO_DIR}")
93
+ return TURBO_DIR
94
+
95
+
96
+ def merge_and_quantize(denoiser_path: Path, lora_path: Path, out_path: Path) -> int:
97
+ """Merge the slow LoRA expert into the denoiser and quantize it like mlx-serve's converter. Returns layers merged."""
98
+ import mlx.core as mx # Apple Silicon only; imported here so the rest of the package loads anywhere
99
+
100
+ weights = mx.load(str(denoiser_path))
101
+ lora = mx.load(str(lora_path))
102
+ scale = LORA_ALPHA / LORA_RANK
103
+
104
+ layers = sorted({key.rsplit(".", 1)[0] for key in lora if key.endswith(f".{EXPERT}_A")})
105
+ if not layers:
106
+ raise ValueError(f"No '{EXPERT}' LoRA expert found in {lora_path}")
107
+ for layer in layers:
108
+ name = f"{layer}.weight"
109
+ if name not in weights:
110
+ raise ValueError(f"The adapter targets {layer}, which the denoiser doesn't have")
111
+ base = weights[name]
112
+ delta = scale * (lora[f"{layer}.{EXPERT}_B"] @ lora[f"{layer}.{EXPERT}_A"])
113
+ if delta.shape != base.shape:
114
+ raise ValueError(f"Shape mismatch at {layer}: adapter {delta.shape}, weight {base.shape}")
115
+ weights[name] = (base.astype(mx.float32) + delta).astype(base.dtype)
116
+
117
+ mx.save_safetensors(str(out_path), quantize_blocks(weights), metadata={"format": "mlx"})
118
+ return len(layers)
119
+
120
+
121
+ def quantize_blocks(tensors: dict) -> dict:
122
+ """Same layout as mlx-serve's tests/convert_idol_weights.py: block Linears to affine 8-bit group 64 where the
123
+ input width allows (else float16), their biases to float16, everything else unchanged."""
124
+ import mlx.core as mx
125
+
126
+ def is_block_linear(name: str, shape) -> bool:
127
+ return name.endswith(".weight") and len(shape) == 2 and name.startswith(BLOCK_PREFIXES)
128
+
129
+ linear_bases = {k[: -len(".weight")] for k, v in tensors.items() if is_block_linear(k, v.shape)}
130
+ out = {}
131
+ for name, tensor in tensors.items():
132
+ base = name.rsplit(".", 1)[0]
133
+ if name.endswith(".weight") and base in linear_bases:
134
+ if tensor.shape[1] % GROUP_SIZE == 0:
135
+ q, scales, biases = mx.quantize(tensor.astype(mx.float32), group_size=GROUP_SIZE, bits=BITS)
136
+ out[name] = q
137
+ out[f"{base}.scales"] = scales.astype(mx.float16)
138
+ out[f"{base}.biases"] = biases.astype(mx.float16)
139
+ else:
140
+ out[name] = tensor.astype(mx.float16)
141
+ elif name.endswith(".bias") and base in linear_bases:
142
+ out[name] = tensor.astype(mx.float16)
143
+ else:
144
+ out[name] = tensor
145
+ return out
146
+
147
+
148
+ def remove_turbo_pack() -> bool:
149
+ if not TURBO_DIR.exists():
150
+ return False
151
+ shutil.rmtree(TURBO_DIR)
152
+ return True
153
+
154
+
155
+ def remove_base_pack() -> bool:
156
+ if not BASE_DIR.exists():
157
+ return False
158
+ shutil.rmtree(BASE_DIR)
159
+ return True