Skip to content

Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.

release(v4.19.15): H3 Flex (Pika H3 Flex on Mac), as a preview

mrbizarro95715236293b
diff --git a/README.md b/README.md
index a6b91b5..92f5182 100644
--- a/README.md
+++ b/README.md
@@ -18,7 +18,7 @@ It runs **LTX-2.5** and **MiniMax H3 (Hailuo H3)** for text-to-video and image-t
and is built on Apple's MLX: no CUDA, no cloud GPU, no API key, no credits and no watermark.
Your prompts, pictures and videos never leave your Mac.
-**Current release: v4.19.14.** Made by Mr Bizarro.
+**Current release: v4.19.15.** Made by Mr Bizarro.
## Why Phosphene
@@ -46,6 +46,7 @@ Works from 16 GB of memory.
MiniMax H3, also called Hailuo H3, makes scenes where people talk, with lips that match their voices.
Use keyframes, extend a shot, lip-sync, or **Add sound** to give a silent clip its own soundscape.
+**New, preview:** Pika H3 Flex, Pika Labs' six-step H3, as a Speed choice: about 2.2× faster than Best at the same size. As far as we know, the first Mac port.
About 75 GB, one click from the Pinokio sidebar, from 36 GB of memory.
Its licence excludes the EU, UK, South Korea and US.
@@ -219,6 +220,7 @@ Contributors are credited in the release notes. See CONTRIBUTING.md.
- Lightricks for LTX-Video 2.x, and @dgrauet for ltx-2-mlx, the MLX port Phosphene builds on.
- MiniMax for Hailuo H3, and Apple ML research for MLX.
- LightX2V for lightx2v v1.3, the adapter for Best on High; TaoLive (TaoMate-H3) and @kijai for the 3-step Fast adapter.
+- Pika Labs (Mellis, Inc.) for Pika H3 Flex, a MiniMax H3 Model Derivative, downloaded from Pika's own Hugging Face repo at a pinned revision and converted on your Mac. Powered by MiniMax H3.
- Black Forest Labs for FLUX 3 Klein, and mflux-community for its MLX conversions.
- @filipstrand for mflux; Multimodal Art Projection for YuE2 and @vanch007 for its MLX port.
- mlx-community for Gemma on MLX, and @cocktailpeanut for Pinokio.
diff --git a/VERSION b/VERSION
index 5f89740..fc77e3b 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-4.19.14
+4.19.15
diff --git a/docs/ANALYTICS.md b/docs/ANALYTICS.md
index 4ad1321..c1dcdea 100644
--- a/docs/ANALYTICS.md
+++ b/docs/ANALYTICS.md
@@ -223,7 +223,7 @@ including image and training jobs.
| `lora_kinds` | string | `"style"` | Closed vocabulary: `none` / `style` / `character` / `mixed` |
| `character_used` | bool | `true` | A cast character drove this render |
| `audio_mode` | string | `"joint"` | `joint` / `none` (external audio replaces the generated track) / `a2v_dub` / `h3_native` |
-| `h3_sampler` | string | `"v13"` | 4.19.11 — H3 renders only: which sampler ran. **Closed vocabulary**: `best` (the full sampler), `fast`, `turbo`, `v13` (lightx2v v1.3 on Best at High). Keeps the timing lanes apart, which `steps` alone cannot |
+| `h3_sampler` | string | `"v13"` | 4.19.11 — H3 renders only: which sampler ran. **Closed vocabulary**: `best` (the full sampler), `fast`, `turbo`, `v13` (lightx2v v1.3 on Best at High), `flex` (Pika H3 Flex, its six-step re-noise sampler). Keeps the timing lanes apart, which `steps` alone cannot |
| `first_render` | bool | `true` | Present once per install, on its first successful render ever — the activation funnel without a join |
| `gpu_steps` | string | `"short"` | 4.17.5 — present only when the render ran in **short GPU steps** (one Metal op per command buffer), the path a macOS GPU-watchdog kill switches a setting to. Closed vocabulary: `short`. Absent = default steps. Answers "does the short path stop the watchdog loop" |
| `watchdog_retry` | bool | `true` | 4.17.5 — present only when a GPU-watchdog kill was re-run inside the same job (once, on short steps). On `render_completed` it means the retry saved the render |
diff --git a/docs/CHANGELOG_4.19.15.md b/docs/CHANGELOG_4.19.15.md
new file mode 100644
index 0000000..a3507de
--- /dev/null
+++ b/docs/CHANGELOG_4.19.15.md
@@ -0,0 +1,27 @@
+# Phosphene 4.19.15
+
+- New in the engine picker: **H3 Flex (preview)**, right next to Hailuo H3. Try Pika Labs' faster version of H3, running natively on Apple Silicon with Phosphene's own code. As far as we know, this is the first Mac port.
+- **About 2.2x faster than Best at the same size.** On an M4 Max with 64 GB, a 5-second clip takes about 5 minutes at Draft (640x384) or 16 minutes at High (1024x576). Best took 36.5 minutes on the same High shot and seed.
+- Start with a sentence using **Text-to-video**, or a first-frame image using **Image-to-video**. Dialogue and sound are included, just like normal H3.
+- Pick **H3 Flex** in the engine picker at the top. If its 2.8 GB adapter is not on your Mac yet, the same click downloads it from Pika's own Hugging Face page and prepares it on your Mac; the picker shows the progress. You need Hailuo H3 installed (if it isn't, the picker offers it first).
+- **We're sharing this preview early so you can try it.** Tell us what breaks through GitHub issues or comments on the Pinokio post. We'll fix problems fast.
+- Fixed: a build newer than the public release no longer offers the older release as an "update".
+- A small update for **Best at High**: its existing speed-up now uses the setting it was trained for, following an update to H3.
+
+## Known limits
+
+- A 15-second clip joins three 5-second pieces. Details can change in later pieces: a dog's breed or a sofa's colour, for example.
+- Full size (1344x768) runs; full timing to come. One test pass suggested about 37 minutes per 5-second clip.
+- Pika's second mode, which transfers a reference or motion into a video, is not included yet.
+
+**Tip:** Name every person who should stay in the scene in your prompt. The model drops people the prompt doesn't mention. This happens in Pika's own sitcom showcase too.
+
+## Credits
+
+Phosphene is a free, open-source Mac app by Mr Bizarro.
+
+**Powered by MiniMax H3.** Pika H3 Flex is by Pika Labs (Mellis, Inc.). The weights are a MiniMax H3 Model Derivative under the MiniMax H3 Community License. Pika's code is Apache-2.0.
+
+Mac weights on Hugging Face: [Mrbizarro/Pika-H3-Flex-MLX](https://huggingface.co/Mrbizarro/Pika-H3-Flex-MLX) (the converted MLX adapter, with credits and licence). The app itself downloads from Pika's Hugging Face page at a fixed version, never re-hosted by us. Phosphene converts the file on your Mac and marks it as modified with a modification notice. MiniMax H3's licence excludes the EU, UK, South Korea and US, as it already does for H3 in Phosphene.
+
+In Pinokio, press Update, then restart Phosphene.
diff --git a/docs/H3_ENGINE.md b/docs/H3_ENGINE.md
index 92370a0..375de97 100644
--- a/docs/H3_ENGINE.md
+++ b/docs/H3_ENGINE.md
@@ -486,6 +486,53 @@ Both digests are checked; a corrupt or partial build is deleted, never
renamed into place. `test_h3_v13.py` pins script↔panel parity, the re-layout
against an independent reference, the job rules, the argv and the prices.
+### Pika H3 Flex: Pika Labs' six-step H3, natively on Apple Silicon (2026-10-30)
+
+**Pika H3 Flex running natively on Apple Silicon (MLX) — the first Mac port we know of.**
+Pika Labs released [Pika H3 Flex](https://huggingface.co/Pika-Labs/Pika-H3-Flex)
+on 2026-10-29 for NVIDIA only (H100 80 GB, `--cpu-offload` for 768p/15 s). It is
+not a new base model: a rank-128 LoRA (alpha 128) on MiniMax H3, base revision
+`42ed227` — whose transformer shards are byte-identical (LFS sha256) to the
+release this pack's pruned/Q8 DiT was built from — plus the sampler it was
+distilled for. Phosphene implements that method in its own MLX code; nothing
+of Pika's code is copied.
+
+| piece | what |
+|---|---|
+| sampler | runner `--pika-flex` = `--sampler renoise --sigma-knots 1000,750,500,250,100,40,0 --video-shift 12 --audio-shift 3` (6 forwards). Each forward predicts `x0 = x_t + sigma*v`; the next state is `x0` re-noised to the next knot with fresh noise (not an Euler blend); the terminal knot is 0. Engine commit `bef6d03` on `phosphene/v4.19.15` (`MiniMaxH3RenoiseScheduler`, `tests/test_pika_flex.py`). |
+| adapter | `scripts/fetch_h3_flex.py` downloads Pika's `fl2va/adapter.safetensors` (float32, sha256 `8ed6115d…`, 2,767,274,120 B) at revision `0ddf55ad` with Pika's LICENSE, NOTICE and manifest, then builds `pika_h3_flex_fl2va_phosphene.safetensors` (sha256 `c71f527d…`, 1,956,166,104 B, deterministic): q/k/v fused block-diagonal in the DiT's per-head order, fc1 halves swapped to `[gate; value]`, float32 to bfloat16 round-to-nearest-even (Pika's own loader runs the adapter in bf16), alpha == rank so no fold. The metadata declares per-head rows and carries the licence notice and a modification notice (Licence III.2). |
+| panel | the third Speed pill, **✧ Pika Flex (preview)** (`h3_flex=1`, a preview since 4.19.15), never a default. Text and Image, every 5 s-window cell (Draft, Standard, High, Native; chained lengths too); it wins over Fast, Turbo, v1.3 and a Steps pin. The note under the switch and the sidecar's `flex` block carry the credit and "Powered by MiniMax H3". `POST /h3/flex/install` builds it (licence-gated like H3). Hidden until the runner has `--pika-flex`. |
+
+Measured on the M4 Max 64 GB, Q8 DiT (2026-10-30):
+
+| shape | forwards | per forward | wall | peak |
+|---|---:|---:|---:|---:|
+| Draft 640×384, 5 s (124 f), Text | 6 | 40.8 s | 301 s | 24.0 GiB denoise / 25.7 run |
+| same prompt + seed, base H3 at 9 points (prompt cached) | 8 | 39.2 s | 358 s | 22.2 GiB denoise |
+| High 1024×576, 5 s, Image | 6 | 143 s | 976 s | 26.6 GiB denoise / 27.2 run |
+| same shot + seed, base H3 Best (16 points) | 15 | 139 s | 2190 s | 24.8 GiB denoise |
+| High 1024×576, 15 s (3 chained 5 s windows, 17-frame carried context), Image | 3 × 6 | 143 / 172 / 172 s | 3293–3304 s | 27.3 GiB |
+| Native 1344×768, 5 s, Image (stopped after forward 1: disk) | 6 | 340 s | ~37 min projected | — |
+
+On the High 5 s A/B (same first frame, prompt, seed) Flex took 16.3 min against
+the full sampler's 36.5 min (2.2×) for a clip of the same staging and quality.
+Chained 15 s keeps each 5 s window as good as a single one, but windows 2-3 can
+drift on set and supporting characters (the sitcom chain changed the dog and the
+sofa; the table-tennis chain held). Pika's own 15 s showcases are ONE dense pass
+at 1344×768, which on a Mac is the dense 15 s cell Flex does not take yet.
+
+The adapter costs ~4% per forward (runtime low-rank matmul) and ~1.8 GiB.
+"Run" peak is the Q8 text encoder phase, which the prompt cache skips. Whisper reads the
+scripted lines back verbatim on both test clips. Ref2VA is not offered: Pika's
+Ref2VA adapter targets the separate Ref2VA trunk (`transformer_ref`, ~20 GB as
+Q8), which this pack does not carry.
+
+**Licence.** The adapter is a MiniMax H3 Model Derivative (copyright Mellis,
+Inc.) under the MiniMax H3 Community License — same territory exclusion (US,
+EU, UK, KR), AUP, "MiniMax H3" shown in the UI (IV.2), the NOTICE text with any
+distribution (III.4). Pika's code is Apache-2.0 (`LICENSE-CODE`). Phosphene
+never re-hosts the weights; each Mac fetches Pika's original.
+
### Chained windows (v3.4.1)
Window *N*'s **last decoded frame** becomes window *N+1*'s first-frame keyframe
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index be9fe76..7bb47e1 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -5348,7 +5348,12 @@ def _check_remote_once() -> None:
_local_v = (_VERSION_STATE.get("local_version") or "").strip()
same_release = bool(more and remote_version and _local_v
and remote_version.strip() == _local_v)
- if same_release:
+ # 4.19.15: a build NEWER than public main (a release between its version
+ # bump and its public tag, every beta install) was offered public main as
+ # an "update" - a downgrade ("Phosphene 4.19.14 is out - you're on
+ # 4.19.15"). Only a strictly greater remote VERSION is an update.
+ local_is_newer = _version_is_newer(_local_v, remote_version)
+ if same_release or local_is_newer:
behind_by, more, ahead = 0, False, []
# The maintainer broadcast rides the same 30-min cadence. Failures and
# absence read as "no message" — _fetch_broadcast never raises.
@@ -5360,12 +5365,33 @@ def _check_remote_once() -> None:
_VERSION_STATE["behind_by"] = behind_by
_VERSION_STATE["behind_more_than"] = more
_VERSION_STATE["local_unlisted_same_release"] = same_release
+ _VERSION_STATE["local_newer_than_remote"] = local_is_newer
_VERSION_STATE["commits_ahead"] = ahead
_VERSION_STATE["checked_ts"] = time.time()
_VERSION_STATE["error"] = None
_VERSION_STATE["broadcast"] = broadcast
+def _version_tuple(v) -> tuple[int, ...] | None:
+ """'4.19.15' -> (4, 19, 15). None for anything that is not dotted digits
+ (a missing VERSION file, a 'Y1.NNN' label from before semver)."""
+ parts = str(v or "").strip().lstrip("vV").split(".")
+ if not parts or not all(p.isdigit() for p in parts):
+ return None
+ return tuple(int(p) for p in parts)
+
+
+def _version_is_newer(local, remote) -> bool:
+ """True when LOCAL is strictly newer than REMOTE (numeric, per part:
+ 4.19.15 > 4.19.14 and 4.10.0 > 4.9.9). Unparseable -> False, so the
+ commit-based answer stands."""
+ lt, rt = _version_tuple(local), _version_tuple(remote)
+ if lt is None or rt is None:
+ return False
+ width = max(len(lt), len(rt))
+ return lt + (0,) * (width - len(lt)) > rt + (0,) * (width - len(rt))
+
+
def version_check_loop() -> None:
"""Daemon thread entry: detect local state once, then poll the remote
every _VERSION_POLL_INTERVAL_SEC. First poll happens after a 30s
@@ -9282,6 +9308,67 @@ H3_V13_CREDIT = ("lightx2v v1.3 by LightX2V (ModelTC). Code: Apache-2.0; "
H3_V13_MEASURED_ETA: dict[tuple[str, str, str], tuple[float, str]] = {
("high", "5s", "t2v"): (14.5, "~15 min"),
}
+
+# ---- Pika H3 Flex: Pika Labs' six-step H3 student, natively on Apple Silicon --
+# Pika H3 Flex running natively on Apple Silicon (MLX) - the first Mac port we know of.
+# Pika Labs released it 2026-10-29 for NVIDIA only (H100 80 GB): a rank-128
+# LoRA on MiniMax H3 (base revision 42ed227, the same transformer weights this
+# pack runs) plus the sampler it was distilled for - six forwards at the base
+# knots 1000,750,500,250,100,40,0, video shift 12, audio shift 3, and a
+# "re-noise" step (predict the clean clip, re-noise it to the next knot with
+# fresh noise) instead of Euler. Phosphene's own MLX code runs it: the runner's
+# `--pika-flex` preset is the sampler, scripts/fetch_h3_flex.py builds the
+# adapter on this Mac. FL2VA only (Text and Image); Pika's Ref2VA adapter needs
+# the separate Ref2VA trunk this pack does not carry.
+#
+# THE FILE. Phosphene does not host it (an H3 Model Derivative, MiniMax H3
+# Community License; Pika's code is Apache-2.0). The fetch script downloads
+# the original from Pika's repo at a pinned commit + digest, with Pika's
+# LICENSE and NOTICE, and re-lays it out for the runner (per-head qkv, fc1
+# halves, float32 -> bfloat16, alpha == rank so no fold). The pins below MUST
+# match that script; test_h3_flex.py holds them together.
+#
+# Display requirements: the MiniMax H3 licence (IV.2) asks that "MiniMax H3"
+# be shown in the UI of a product that uses it, and encourages "Powered by
+# MiniMax H3" (III.3a); H3_FLEX_CREDIT carries both names wherever Flex shows.
+H3_FLEX_REPO = "Pika-Labs/Pika-H3-Flex"
+H3_FLEX_SOURCE_REVISION = "0ddf55ad7067ca1e76812253bd7b4600df87f759"
+H3_FLEX_SOURCE_FILE = "fl2va/adapter.safetensors"
+H3_FLEX_SOURCE_URL = ("https://huggingface.co/" + H3_FLEX_REPO + "/resolve/"
+ + H3_FLEX_SOURCE_REVISION + "/" + H3_FLEX_SOURCE_FILE)
+H3_FLEX_SOURCE_SHA256 = "8ed6115d647ab11c1b38d04e63c4c6e1594128ae312f7b5635cd50563b7b9327"
+H3_FLEX_SOURCE_BYTES = 2767274120
+H3_FLEX_FILE = "pika_h3_flex_fl2va_phosphene.safetensors"
+H3_FLEX_SHA256 = "c71f527d0092dd43d368a20223d4aec41e7a1cca6abecdc457d54cee785f0327"
+H3_FLEX_BYTES = 1956166104
+H3_FLEX_DIRNAME = "pika-h3-flex"
+H3_FLEX_STEPS = 7 # knots incl. the terminal 0 -> 6 forwards
+H3_FLEX_FORWARDS = H3_FLEX_STEPS - 1
+H3_FLEX_RUNNER_FLAG = "--pika-flex"
+# A forward with the runtime rank-128 adapter costs about what v1.3's does.
+H3_FLEX_FORWARD_COST = 1.03
+H3_FLEX_MODES = ("t2v", "i2v")
+H3_FLEX_DOWNLOAD_GB = 2.8
+# Free disk the build needs: the 2.8 GB source plus the 2.0 GB result while
+# both exist, plus a margin so a render's swap never meets a full disk.
+H3_FLEX_DISK_NEED_GB = 7.0
+H3_FLEX_LICENSE = "MiniMax H3 Community License"
+H3_FLEX_CODE_LICENSE = "Apache-2.0"
+H3_FLEX_NAME = "Pika H3 Flex"
+H3_FLEX_LABEL = "Pika H3 Flex (preview) · 6 steps"
+H3_FLEX_CREDIT = ("Pika H3 Flex by Pika Labs (Mellis, Inc.), running natively on "
+ "Apple Silicon (MLX) in Phosphene. Powered by MiniMax H3. "
+ "Weights: MiniMax H3 Community License; Pika code: Apache-2.0.")
+H3_FLEX_NOTICE = ("MiniMax H3 is licensed under the MiniMax H3 Community License "
+ "Agreement, Copyright © 2026 MiniMax. All Rights Reserved.")
+# End-to-end wall clocks, M4 Max 64 GB, keyed (quality, length, mode); filled
+# from the port's validation renders (PM hub notes/flex-port-2026-10-30.md).
+# 2026-10-30: Draft 640x384 5 s 301 s (6 x 40.8 s); High 1024x576 5 s 976 s
+# (6 x 143 s, decode 92 s, peak 27.2 GiB on the Q8 DiT).
+H3_FLEX_MEASURED_ETA: dict[tuple[str, str, str], tuple[float, str]] = {
+ ("draft", "5s", "t2v"): (5.0, "~5 min"),
+ ("high", "5s", "t2v"): (16.3, "~16 min"),
+}
# Upscale & Face Fix (1 refine step from the clip, ×2) after a 5 s render, by
# source canvas. 640×384 → 1280×768 measured 2.5–2.8 min; 1024×576 measured
# 8.2–9.9 min (panel history, 2026-09-16/17); 768×448 is interpolated between
@@ -9910,6 +9997,7 @@ def _job_fleet_baseline_min(job: dict) -> tuple[str, float] | None:
# the full sampler's, or its ~2.3x speed would read as a fast Mac.
hit = fleet_estimate_range("h3", "t2v", key, cell["frames"],
speed="fast" if fast else
+ "flex" if p.get("h3_flex") else
"v13" if p.get("h3_v13") else "best")
else:
if str(p.get("schedule_preset") or "").strip().lower() == "fast":
@@ -11168,6 +11256,20 @@ def _build_h3_tiers() -> dict[str, dict]:
v13 = {"v13_min": round(v_min, 2), "v13_eta": v_eta,
"v13_measured": v_meas, "v13_steps": H3_V13_STEPS,
"v13_forwards": windows * H3_V13_FORWARDS}
+ # Pika H3 Flex prices every cell it renders on (h3_cell_takes_flex):
+ # 6 forwards at about v1.3's per-forward cost.
+ flex = {}
+ if not ln["dense"] and not q.get("fast_hd"):
+ f_min = h3_estimate_minutes(
+ w, h, window_frames, windows, H3_FLEX_FORWARDS) * H3_FLEX_FORWARD_COST
+ f_eta, f_meas = _fmt_eta(f_min), False
+ hit = H3_FLEX_MEASURED_ETA.get((q["key"], ln["key"], "t2v"))
+ if hit:
+ f_min, f_meas = hit[0] * hw, True
+ f_eta = hit[1] if hw == 1.0 else _fmt_eta(f_min)
+ flex = {"flex_min": round(f_min, 2), "flex_eta": f_eta,
+ "flex_measured": f_meas, "flex_steps": H3_FLEX_STEPS,
+ "flex_forwards": windows * H3_FLEX_FORWARDS}
spec = f"{w}×{h} · {frames}f"
if windows > 1:
spec += f" · {windows}×5s"
@@ -11221,6 +11323,7 @@ def _build_h3_tiers() -> dict[str, dict]:
"offered": bool(q["offered"] and ln["offered"]),
**tristep,
**v13,
+ **flex,
}
# Owner ruling (2026-09-29): real fleet ranges where there are
# enough of them, one per speed this cell actually offers (H3's
@@ -12603,6 +12706,8 @@ def job_recipe_minutes(params: dict, *, calibration: bool = False) -> tuple[str,
else cell.get("tristep_min"))
elif p.get("h3_turbo"):
minutes = cell.get("turbo_min")
+ elif p.get("h3_flex") and cell.get("flex_min") is not None:
+ minutes = cell.get("flex_min")
elif p.get("h3_v13") and cell.get("v13_min") is not None:
# lightx2v v1.3 on Best at High: its own measured number, so a
# 15-minute recipe never calibrates against the 33-minute one.
@@ -14828,6 +14933,181 @@ def _h3_install_tristep(push_log, download_fn=None) -> dict:
"bytes": H3_TRISTEP_BYTES, "license": H3_TRISTEP_LICENSE}
+# ---- Pika H3 Flex — resolver, argv, status, fetch ------------------------------
+def h3_supports_flex() -> bool:
+ """Whether the INSTALLED runner has the Flex sampler (`--pika-flex`) and
+ stacks adapters. The built file's qkv rows are already per head, so the
+ runner must also be one that never re-orders a `--lora` itself."""
+ return (h3_supports_lora_stack() and _h3_runner_has_flag(H3_FLEX_RUNNER_FLAG)
+ and _h3_runner_has_flag("--lora-qkv-permute"))
+
+
+def h3_cell_takes_flex(cell: dict) -> bool:
+ """Every chained/single 5 s-window cell. The dense single pass and Fast HD
+ keep their own recipes (never rendered on Flex)."""
+ return not bool(cell.get("dense")) and not bool(cell.get("fast_hd"))
+
+
+def _h3_flex_dir() -> Path:
+ """Beside the other weight components, like Turbo's folder."""
+ for root in _h3_model_roots():
+ if _h3_holds_dit(root):
+ return root / H3_FLEX_DIRNAME
+ return H3_MODELS / H3_FLEX_DIRNAME
+
+
+def h3_flex_paths() -> dict:
+ """The built Flex adapter, if it is on disk at its exact size. No glob: the
+ upstream float32 source must never be read as the adapter."""
+ directory = _h3_flex_dir()
+ candidate = directory / H3_FLEX_FILE
+ try:
+ ok = candidate.is_file() and candidate.stat().st_size == H3_FLEX_BYTES
+ except OSError:
+ ok = False
+ if ok:
+ return {"dir": directory, "lora": candidate, "files_ok": True, "missing": []}
+ return {"dir": directory, "lora": None, "files_ok": False,
+ "missing": [f"adapter ({H3_FLEX_FILE}, built from a "
+ f"~{H3_FLEX_DOWNLOAD_GB} GB download)"]}
+
+
+def h3_flex_argv(paths: dict | None = None) -> list[str]:
+ """The runner argv fragment: the Flex sampler preset (which owns `--steps`)
+ and the adapter at 1.0 (alpha == rank)."""
+ resolved = paths or h3_flex_paths()
+ if not resolved.get("files_ok") or resolved.get("lora") is None:
+ raise RuntimeError("the Pika H3 Flex adapter is not available")
+ return [H3_FLEX_RUNNER_FLAG, "--lora", f"{resolved['lora']}:1.0"]
+
+
+_h3_flex_dl_lock = threading.Lock()
+_h3_flex_dl_state: dict = {"status": "idle", "mb": 0, "total_mb": 0, "error": None}
+
+
+def _set_h3_flex_dl(**kw) -> None:
+ with _h3_flex_dl_lock:
+ _h3_flex_dl_state.clear()
+ _h3_flex_dl_state.update(kw)
+
+
+def h3_flex_status() -> dict:
+ """/status + BOOT block for Flex: can the runner take it, is the file here."""
+ supported = h3_supports_flex()
+ paths = h3_flex_paths()
+ downloaded = bool(paths["files_ok"])
+ return {
+ "available": bool(supported and downloaded),
+ "supported": supported,
+ "downloaded": downloaded,
+ "reason": ("runner_too_old" if not supported
+ else "not_downloaded" if not downloaded else "ok"),
+ "steps": H3_FLEX_STEPS,
+ "forwards": H3_FLEX_FORWARDS,
+ "modes": list(H3_FLEX_MODES),
+ "download_gb": H3_FLEX_DOWNLOAD_GB,
+ "disk_need_gb": H3_FLEX_DISK_NEED_GB,
+ "repo": H3_FLEX_REPO,
+ "license": H3_FLEX_LICENSE,
+ "code_license": H3_FLEX_CODE_LICENSE,
+ "name": H3_FLEX_NAME,
+ "label": H3_FLEX_LABEL,
+ "credit": H3_FLEX_CREDIT,
+ "notice": H3_FLEX_NOTICE,
+ "adapter": str(paths["lora"]) if paths["lora"] else None,
+ "install_available": bool(supported),
+ "installing": _h3_flex_dl_state.get("status") in ("downloading", "building"),
+ "download": dict(_h3_flex_dl_state),
+ }
+
+
+def _h3_flex_fetch_bg(target_dir, push_log, runner=None) -> None:
+ """Run scripts/fetch_h3_flex.py (download from Pika's repo with its
+ LICENSE + NOTICE, verify, re-lay out, verify, rename). The script owns
+ every digest and the resume; this only relays its progress. It needs
+ numpy, which the panel's own interpreter carries."""
+ total_mb = H3_FLEX_SOURCE_BYTES // (1 << 20)
+ cmd = [sys.executable, str(ROOT / "scripts" / "fetch_h3_flex.py"),
+ "--dir", str(target_dir)]
+ try:
+ push_log(f"[h3:flex] fetching {H3_FLEX_SOURCE_FILE} from {H3_FLEX_REPO} @ "
+ f"{H3_FLEX_SOURCE_REVISION[:7]} (~{total_mb} MB, {H3_FLEX_LICENSE})")
+ proc = (runner or subprocess.Popen)(
+ cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
+ errors="replace", env=_h3_v13_fetch_env())
+ tail: list[str] = []
+ for line in proc.stdout:
+ line = line.rstrip()
+ if line.startswith("PROGRESS "):
+ try:
+ done = int(line.split()[1])
+ except (IndexError, ValueError):
+ continue
+ _set_h3_flex_dl(status="downloading", mb=done // (1 << 20),
+ total_mb=total_mb, error=None)
+ continue
+ if line.startswith("building "):
+ _set_h3_flex_dl(status="building", mb=total_mb, total_mb=total_mb,
+ error=None)
+ if line:
+ tail = (tail + [line])[-4:]
+ push_log(f"[h3:flex] {line}")
+ rc = proc.wait()
+ if rc != 0 or not h3_flex_paths()["files_ok"]:
+ raise RuntimeError(" / ".join(tail[-2:]) or f"exit {rc}")
+ push_log(f"[h3:flex] adapter installed -> {Path(target_dir) / H3_FLEX_FILE}")
+ _set_h3_flex_dl(status="done", mb=total_mb, total_mb=total_mb, error=None)
+ except Exception as e: # noqa: BLE001
+ _set_h3_flex_dl(status="error", mb=0, total_mb=total_mb, error=str(e)[:200])
+ push_log(f"[h3:flex] FAILED: {e}")
+
+
+def _h3_install_flex(push_log, fetch_fn=None) -> dict:
+ """On-demand fetch + local build of the Pika H3 Flex adapter (one at a time)."""
+ paths = h3_paths()
+ if paths["missing"]:
+ return {"ok": False,
+ "error": "Pika H3 Flex is an add-on to the Hailuo H3 pack, and "
+ "H3 isn't fully installed yet: " + "; ".join(paths["missing"])}
+ if not h3_supports_flex():
+ return {"ok": False,
+ "error": _dist.say(
+ "This Hailuo H3 runner predates Pika H3 Flex (its six-step "
+ "sampler). Run 'Update Hailuo H3 runner' from the Phosphene "
+ "sidebar in Pinokio - your weights stay.",
+ "This Hailuo H3 runner predates Pika H3 Flex. Updating the "
+ "runner isn't available in the Mac app yet.")}
+ resolved = h3_flex_paths()
+ target = resolved["dir"]
+ if resolved["files_ok"]:
+ return {"ok": True, "started": False, "already_installed": True,
+ "dir": str(target)}
+ try:
+ target.mkdir(parents=True, exist_ok=True)
+ free_gb = shutil.disk_usage(target).free / 1e9
+ except OSError:
+ free_gb = None
+ if free_gb is not None and free_gb < H3_FLEX_DISK_NEED_GB:
+ return {"ok": False,
+ "error": f"Pika H3 Flex needs about {H3_FLEX_DISK_NEED_GB:g} GB free "
+ f"to prepare (2.8 GB download, 2 GB when ready). This "
+ f"disk has {free_gb:.1f} GB free."}
+ with _h3_flex_dl_lock:
+ if _h3_flex_dl_state.get("status") in ("downloading", "building"):
+ return {"ok": False,
+ "error": "a Pika H3 Flex download is already active"}
+ _h3_flex_dl_state.clear()
+ _h3_flex_dl_state.update(status="downloading", mb=0,
+ total_mb=H3_FLEX_SOURCE_BYTES // (1 << 20), error=None)
+ fn = fetch_fn or _h3_flex_fetch_bg
+ threading.Thread(target=fn, args=(target, push_log), daemon=True,
+ name="h3-flex-fetch").start()
+ return {"ok": True, "started": True, "dir": str(target),
+ "source": H3_FLEX_SOURCE_URL, "sha256": H3_FLEX_SOURCE_SHA256,
+ "bytes": H3_FLEX_SOURCE_BYTES, "license": H3_FLEX_LICENSE,
+ "credit": H3_FLEX_CREDIT}
+
+
# ---- lightx2v v1.3 (Best at High) — resolver, argv, status, fetch ------------
def h3_supports_video_shift() -> bool:
"""Whether the INSTALLED runner takes `--video-shift` (v1.3's own shift 6;
@@ -16915,6 +17195,17 @@ def h3_status() -> dict:
"name": H3_V13_NAME, "label": H3_V13_LABEL, "credit": H3_V13_CREDIT,
"adapter": None, "install_available": False, "installing": False,
"download": {}, "dir": str(_h3_turbo_dir()), "missing": []}),
+ # Pika H3 Flex — a Speed choice of its own. Same three-cause shape.
+ "flex": (h3_flex_status() if available else
+ {"available": False, "supported": False, "downloaded": False,
+ "reason": "h3_" + paths["reason"], "steps": H3_FLEX_STEPS,
+ "forwards": H3_FLEX_FORWARDS, "modes": list(H3_FLEX_MODES),
+ "download_gb": H3_FLEX_DOWNLOAD_GB,
+ "disk_need_gb": H3_FLEX_DISK_NEED_GB, "repo": H3_FLEX_REPO,
+ "license": H3_FLEX_LICENSE, "code_license": H3_FLEX_CODE_LICENSE,
+ "name": H3_FLEX_NAME, "label": H3_FLEX_LABEL, "credit": H3_FLEX_CREDIT,
+ "notice": H3_FLEX_NOTICE, "adapter": None, "install_available": False,
+ "installing": False, "download": {}}),
# User LoRAs — the CivitAI lane. A separate block from `turbo` for the
# same reason turbo is separate from `first_frame`: "you can't pick a
# LoRA" has three unrelated causes (H3 absent / runner predates --lora
@@ -19943,6 +20234,7 @@ def _analytics_render_event(job: dict) -> None:
if engine == "h3":
props["h3_sampler"] = ("fast" if p.get("h3_tristep") else
"turbo" if p.get("h3_turbo") else
+ "flex" if p.get("h3_flex") else
"v13" if p.get("h3_v13") else "best")
# 4.17.5: did this render run in short GPU steps (the Metal watchdog
# path), and did a watchdog kill get re-run inside the same job?
@@ -33108,6 +33400,11 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
# sampler, as a Steps pin does.
_h3_v13_off = (f("h3_v13", "") or "").strip().lower() in ("0", "false", "off", "no")
_h3_v13 = False
+ # Pika H3 Flex: an explicit Speed choice ("1"), never a default. When it
+ # can run it wins over Fast, Turbo, v1.3 and a Steps pin (it owns its own
+ # six-step ladder); where it cannot, the render says so and falls back.
+ _h3_flex_want = (f("h3_flex", "") or "").strip().lower() in ("1", "true", "on", "yes")
+ _h3_flex = False
# Which of the runner's ONE adapter slots this render spends. H3's
# `--lora` is a single path (`default=None`, not `action="append"` — see
# scripts/generate_staged.py), so a user LoRA and Turbo are mutually
@@ -33227,7 +33524,29 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
# adapter is built. Never with Fast or Turbo, never under a Steps pin
# (the pin IS the way to ask for the full sampler), never where it
# was not validated (other canvases, the dense pass, media modes).
- if (not _h3_v13_off and not _h3_tristep and not _h3_turbo and not _h3_steps
+ if _h3_flex_want and h3_available():
+ _fcell = H3_TIERS[_h3_tier]
+ _fst = h3_flex_status()
+ if mode_in not in H3_FLEX_MODES:
+ push(f"{H3_FLEX_NAME} renders Text and Image - this mode keeps "
+ "its own sampler.")
+ elif not h3_cell_takes_flex(_fcell):
+ push(f"{H3_FLEX_NAME} runs on 5 s windows (single or chained) - "
+ f"rendering {_fcell['label']} on its own sampler.")
+ elif not _fst["available"]:
+ push(f"{H3_FLEX_NAME} requested but " + (
+ "this H3 runner has no --pika-flex sampler - update the H3 "
+ "runner." if not _fst["supported"] else
+ "its adapter isn't downloaded yet.") + " Rendering without it.")
+ else:
+ _h3_flex = True
+ if _h3_tristep or _h3_turbo or _h3_steps:
+ push(f"{H3_FLEX_NAME} runs its own {H3_FLEX_FORWARDS}-step "
+ "ladder - Fast, Turbo and any Steps pin are off for this render.")
+ _h3_tristep = _h3_turbo = _h3_clean_sound = False
+ _h3_steps = 0
+ if (not _h3_flex and not _h3_v13_off and not _h3_tristep and not _h3_turbo
+ and not _h3_steps
and mode_in in H3_V13_MODES and h3_available()
and h3_cell_takes_v13(H3_TIERS[_h3_tier])
and h3_v13_status()["available"]):
@@ -33370,6 +33689,8 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
# lightx2v v1.3 on Best at High, resolved above. SAME allowlist
# trap: leave it out and Best silently renders the full sampler.
"h3_v13": _h3_v13,
+ # Pika H3 Flex, resolved above. SAME allowlist trap.
+ "h3_flex": _h3_flex,
# Which of H3's ONE adapter slots this render spends: "turbo"
# (default) or "user". SAME allowlist trap as every key in this
# dict — leave `h3_lora_slot` out and the Turbo-vs-LoRA control
@@ -33666,6 +33987,7 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
# branches on WHY the count is what it is).
job["params"]["steps"] = int(
H3_TRISTEP_STEPS if _h3_tristep else
+ H3_FLEX_STEPS if _h3_flex else
H3_V13_STEPS if _h3_v13 else
h3_turbo_steps() if _h3_turbo else (_h3_steps or _tier_cfg["steps"]))
job["params"]["h3_chain_windows"] = int(_tier_cfg.get("chain_windows") or 1)
@@ -36720,6 +37042,35 @@ def run_h3_job_inner(job: dict) -> None:
f"under Best, or get it from the Speed row.")
steps = H3_V13_STEPS
+ # ---- Pika H3 Flex (6 forwards, re-noise sampler) ----------------------
+ # Pika H3 Flex running natively on Apple Silicon (MLX). make_job resolved
+ # it; re-check here (a queued job outlives the file) and never stack it
+ # with another step-distillation adapter.
+ flex = bool(p.get("h3_flex"))
+ flex_paths: dict = {}
+ if flex and (tristep or turbo or v13 or not h3_cell_takes_flex(tier)
+ or mode not in H3_FLEX_MODES):
+ flex = False
+ p["h3_flex"] = False
+ push(f"[h3] {H3_FLEX_NAME} runs on Text and Image, alone - "
+ f"this render keeps its own sampler.")
+ if flex:
+ if not h3_supports_flex():
+ raise RuntimeError(
+ f"{H3_FLEX_NAME} needs the runner's six-step sampler: "
+ + _h3_runner_behind(H3_FLEX_RUNNER_FLAG, paths["runner"],
+ "Or pick Fast or Best under Speed."))
+ flex_paths = h3_flex_paths()
+ if not flex_paths["files_ok"]:
+ raise RuntimeError(
+ f"The {H3_FLEX_NAME} adapter isn't on disk: "
+ + "; ".join(flex_paths["missing"])
+ + f". Expected under {flex_paths['dir']} - pick Fast or Best "
+ f"under Speed, or get it from the Speed row.")
+ steps = H3_FLEX_STEPS
+ push(f"[h3] {H3_FLEX_NAME}: Pika Labs' six-step H3 student, running "
+ f"natively on Apple Silicon (MLX). Powered by MiniMax H3.")
+
# First-frame conditioning (Image mode). The flag landed on the runner
# after the first public branch, so probe the INSTALLED script rather than
# assuming; an older pack renders Text fine and must fail here with a
@@ -37041,6 +37392,10 @@ def run_h3_job_inner(job: dict) -> None:
# 4.19.12 it was passed as trained and its q/k/v update landed on
# the wrong heads.
cmd += h3_v13_argv(v13_paths, shift=v13_shift)
+ if flex:
+ # The sampler preset (re-noise, knots 1000..40,0, shifts 12/3) and the
+ # adapter at 1.0; qkv rows already per head, so no runner re-order.
+ cmd += h3_flex_argv(flex_paths)
if user_lora is not None and (not turbo or h3_supports_lora_stack()):
# The SAME flag Turbo rides. On a stacking runner every `--lora` is one
# more adapter on the same base layers, Turbo first; on the single-slot
@@ -37175,6 +37530,7 @@ def run_h3_job_inner(job: dict) -> None:
_load_eta_seed_min = (
(tier.get("tristep_min") if tristep and tier.get("tristep_min") is not None
else tier.get("v13_min") if v13 and tier.get("v13_min") is not None
+ else tier.get("flex_min") if flex and tier.get("flex_min") is not None
else tier.get("eta_min")) or 0.0)
_load_eta_seed = max(0.0, float(_load_eta_seed_min)) * 60.0
# H3-04: what one denoise forward SHOULD cost on this Mac, at this
@@ -37407,7 +37763,7 @@ def run_h3_job_inner(job: dict) -> None:
# card had no way to show this before) and, when the
# render is running meaningfully slower than even
# that speed's own estimate, why and what would help.
- "h3_speed": ("fast" if tristep else "best"),
+ "h3_speed": ("fast" if tristep else "flex" if flex else "best"),
"h3_pace_warning": _pace_note,
"denoise_step": last_step,
"denoise_total": total_steps,
@@ -37674,6 +38030,7 @@ def run_h3_job_inner(job: dict) -> None:
"h3_tristep": tristep,
# And for lightx2v v1.3 on Best at High.
"h3_v13": v13,
+ "h3_flex": flex,
"width": width, "height": height, "frames": frames, "steps": steps,
"seed_used": seed,
# The user's OWN reference, not the canvas crop made from it: the
@@ -37759,6 +38116,25 @@ def run_h3_job_inner(job: dict) -> None:
"forwards": H3_V13_FORWARDS,
"video_shift": float(H3_V13_VIDEO_SHIFT) if v13_shift else 12.0}
if v13 else None),
+ # Pika H3 Flex provenance + the licence's notice text, so a clip
+ # carries "Powered by MiniMax H3" and its terms wherever it goes.
+ "flex": ({"lora": str(flex_paths["lora"]),
+ "name": H3_FLEX_NAME,
+ "repo": H3_FLEX_REPO,
+ "revision": H3_FLEX_SOURCE_REVISION,
+ "source_file": H3_FLEX_SOURCE_FILE,
+ "source_sha256": H3_FLEX_SOURCE_SHA256,
+ "sha256": H3_FLEX_SHA256,
+ "license": H3_FLEX_LICENSE,
+ "code_license": H3_FLEX_CODE_LICENSE,
+ "credit": H3_FLEX_CREDIT,
+ "notice": H3_FLEX_NOTICE,
+ "sampler": "renoise",
+ "knots": [1000, 750, 500, 250, 100, 40, 0],
+ "video_shift": 12.0, "audio_shift": 3.0,
+ "scale": 1.0, "steps": steps,
+ "forwards": H3_FLEX_FORWARDS}
+ if flex else None),
# The fast 3-step sampler's provenance: which file, where it came from,
# under what license, and the schedule the runner actually ran.
"tristep": ({"lora": str(tristep_paths["lora"]),
diff --git a/panel/routes_image.py b/panel/routes_image.py
index b44490f..aff6ccd 100644
--- a/panel/routes_image.py
+++ b/panel/routes_image.py
@@ -467,6 +467,23 @@ def post_h3_v13_install(h, path, qs, ctype) -> None:
h._json(result, 202)
+
+# ====== Hailuo H3 · Pika H3 Flex (a Speed choice) — fetch Pika's original FL2VA
+# adapter + LICENSE + NOTICE (pinned revision + sha256) and build the runner
+# layout locally. Pika H3 Flex running natively on Apple Silicon (MLX).
+@post("/h3/flex/install")
+def post_h3_flex_install(h, path, qs, ctype) -> None:
+ P.h3_status_invalidate()
+ # An H3 Model Derivative: the same licence screen as H3 itself.
+ _lic = P.licence_refusal_for("h3")
+ if _lic:
+ h._json(_lic, 451); return
+ result = P._h3_install_flex(P.push)
+ if not result.get("ok"):
+ h._json(result, 409 if "active" in result.get("error", "") else 400)
+ return
+ h._json(result, 202)
+
# Image-engine config (pluggable: mock | bfl).
@post("/agent/image/config")
def post_agent_image_config(h, path, qs, ctype) -> None:
diff --git a/scripts/fetch_h3_flex.py b/scripts/fetch_h3_flex.py
new file mode 100644
index 0000000..54a836d
--- /dev/null
+++ b/scripts/fetch_h3_flex.py
@@ -0,0 +1,419 @@
+#!/usr/bin/env python3
+"""Build Pika H3 Flex's FL2VA adapter for Phosphene's MLX H3 runner, on THIS Mac.
+
+Pika H3 Flex running natively on Apple Silicon (MLX) - first Mac port.
+
+Pika H3 Flex (Pika Labs / Mellis, Inc., released 2026-10-29) is a rank-128 LoRA
+on MiniMax H3 plus the six-forward "re-noise" sampler it was distilled for. Pika
+ships it for NVIDIA GPUs only; Phosphene runs it on the Mac with its own MLX
+code (the runner's `--pika-flex` sampler preset) and this adapter build.
+
+Phosphene does not host the adapter. It is a MiniMax H3 Model Derivative under
+the MiniMax H3 Community License, so - like fetch_h3_v13.py - the panel fetches
+the ORIGINAL file from Pika's Hugging Face repo at a pinned commit and SHA-256,
+together with Pika's LICENSE and NOTICE, and re-lays the adapter out locally
+into the layout the runner's `--lora` loader applies as-is (no runner flags):
+
+ * the split diffusers q/k/v adapters become ONE block-diagonal adapter whose B
+ rows are written in the DiT's own fused-qkv order, per head
+ (heads, 3, head_dim) - the base checkpoint stores qkv_proj that way;
+ * diffusers' `ff.net.0.proj` rows are [value; gate]; the runner's fc1 reads
+ [gate; value], so the two halves of B swap;
+ * the source is float32; the result is bfloat16 (round to nearest even),
+ which is the precision Pika's own loader runs the adapter at
+ (its `apply_lora` casts every lora_ parameter to bf16). alpha == rank
+ (128/128), so no scale is folded.
+
+The build is deterministic (sorted keys, fixed metadata), so every Mac makes
+the same bytes; ASSET_SHA256 pins them. The result carries a modification
+notice in its metadata, as the licence's Section III.2 asks of modified files.
+
+Needs numpy (the panel's and the H3 runner's interpreters both have it).
+"""
+from __future__ import annotations
+
+import argparse
+import fcntl
+import hashlib
+import json
+import os
+import re
+import struct
+import sys
+import urllib.request
+from pathlib import Path
+
+# ---- the upstream release (fetched, never re-hosted) ------------------------
+SOURCE_REPO = "Pika-Labs/Pika-H3-Flex"
+SOURCE_REVISION = "0ddf55ad7067ca1e76812253bd7b4600df87f759"
+SOURCE_FILE = "fl2va/adapter.safetensors"
+SOURCE_SHA256 = "8ed6115d647ab11c1b38d04e63c4c6e1594128ae312f7b5635cd50563b7b9327"
+SOURCE_BYTES = 2767274120
+# Small files that travel with the adapter: the release's own sampling manifest
+# and its licence + notice (the MiniMax H3 licence asks that the NOTICE text
+# accompany the model, and that recipients get the licence).
+SIDE_FILES = {
+ "fl2va/manifest.json": "7d06377f04a3e822f5f21ad72501312da25101976218bde37b12a2171746a8a5",
+ "LICENSE": "59b99642b95ea21630e311198ddbfffbfe05aadba0c2f5d884cbdf4efcc90f44",
+ "NOTICE": "8fc52805a4f8d034f853b5ed494574e37f292def5cdd326d22547afa2658527b",
+}
+BASE_REPO = "MiniMaxAI/MiniMax-H3"
+BASE_REVISION = "42ed227ee7df40d41602854ae760620d6eb651fe"
+
+
+def source_url(name: str) -> str:
+ return f"https://huggingface.co/{SOURCE_REPO}/resolve/{SOURCE_REVISION}/{name}"
+
+
+# ---- the result, built locally ------------------------------------------------
+ASSET_NAME = "pika_h3_flex_fl2va_phosphene.safetensors"
+ASSET_SHA256 = "c71f527d0092dd43d368a20223d4aec41e7a1cca6abecdc457d54cee785f0327"
+ASSET_BYTES = 1956166104
+
+# The DiT's attention shape (H3 FL2VA: 56 heads x 128) and the release's rank.
+HEADS = 56
+HEAD_DIM = 128
+RANK = 128
+ALPHA = 128
+
+MODIFICATION_NOTICE = (
+ "Modified by Phosphene (Mr Bizarro) in 2026: Pika H3 Flex FL2VA adapter re-laid out "
+ "for the MLX H3 runner (fused per-head qkv, SwiGLU halves swapped, float32 -> bfloat16). "
+ "Original: Copyright (c) 2026 Mellis, Inc. Model Derivative of MiniMax H3, distributed "
+ "under the MiniMax H3 Community License Agreement."
+)
+METADATA = {
+ "converted_from": f"{SOURCE_REPO}@{SOURCE_REVISION}:{SOURCE_FILE}",
+ "source_sha256": SOURCE_SHA256,
+ "base_model": f"{BASE_REPO}@{BASE_REVISION}",
+ "license": "MiniMax H3 Community License Agreement (H3 Model Derivative); Pika code Apache-2.0",
+ "notice": "MiniMax H3 is licensed under the MiniMax H3 Community License Agreement, "
+ "Copyright (c) 2026 MiniMax. All Rights Reserved.",
+ "modification_notice": MODIFICATION_NOTICE,
+ "fc1_layout": "[gate;value]",
+ "qkv_layout": "per-head (heads,3,head_dim), the DiT's own order; apply with no permute",
+ "lora_alpha": str(ALPHA),
+ "source_rank": str(RANK),
+ "qkv_fused_rank": str(3 * RANK),
+ "sampler": "renoise; knots 1000,750,500,250,100,40,0; video shift 12; audio shift 3",
+ "phosphene_runner_flags": "--pika-flex --lora <this file>:1.0",
+}
+
+_SRC_A = ".lora_A.default.weight"
+_SRC_B = ".lora_B.default.weight"
+
+
+def _plain(text) -> str:
+ """An exception's text with Pinokio's two stop words defused."""
+ return re.sub(r"(?i)errno ", "errno-", re.sub(r"(?i)error:", "problem -", str(text)))
+
+
+def file_sha256(path: Path) -> str:
+ h = hashlib.sha256()
+ with open(path, "rb") as fh:
+ for chunk in iter(lambda: fh.read(1 << 20), b""):
+ h.update(chunk)
+ return h.hexdigest()
+
+
+def _prefixes() -> list[tuple[str, str]]:
+ return ([(f"transformer_blocks.{i}", f"blocks.{i}") for i in range(50)]
+ + [(f"token_refiner.refiner_blocks.{i}", f"token_refiner.blocks.{i}")
+ for i in range(2)])
+
+
+class Source:
+ """Random access to the float32 matrices of a safetensors file."""
+
+ def __init__(self, path: Path):
+ import numpy as np
+ self.np = np
+ with open(path, "rb") as fh:
+ (n,) = struct.unpack("<Q", fh.read(8))
+ header = json.loads(fh.read(n))
+ self.meta = header.pop("__metadata__", {}) or {}
+ self.base = 8 + n
+ self.tensors = header
+ self.mm = np.memmap(path, dtype=np.uint8, mode="r")
+
+ def shape(self, key: str) -> list[int]:
+ return list(self.tensors[key]["shape"])
+
+ def read(self, key: str):
+ """The matrix as float32 numpy, finite-checked."""
+ np = self.np
+ t = self.tensors[key]
+ if t["dtype"] != "F32" or len(t["shape"]) != 2:
+ raise ValueError(f"{key}: expected a 2-D F32 matrix, got {t['dtype']} {t['shape']}")
+ a, b = t["data_offsets"]
+ raw = self.mm[self.base + a:self.base + b]
+ if raw.size != b - a:
+ raise ValueError(f"{key}: source is truncated")
+ arr = raw.view("<f4").reshape(t["shape"])
+ if not np.isfinite(arr).all():
+ raise ValueError(f"{key}: inf/NaN in the source")
+ return arr
+
+
+def to_bf16(arr):
+ """float32 -> bfloat16 bits (uint16), round to nearest, ties to even."""
+ np = sys.modules["numpy"]
+ u = np.ascontiguousarray(arr, dtype="<f4").view("<u4").astype(np.uint64)
+ rounded = (u + 0x7FFF + ((u >> 16) & 1)) >> 16
+ return rounded.astype("<u2")
+
+
+def plan_tensors(src: Source) -> dict:
+ """{output key: (shape, make_uint16_array)}; one block's tensors in memory at a time."""
+ np = src.np
+ plan: dict = {}
+ used: set = set()
+
+ def pair(prefix: str) -> tuple[list[int], list[int]]:
+ sa, sb = src.shape(prefix + _SRC_A), src.shape(prefix + _SRC_B)
+ if sa[0] != RANK or sb[1] != RANK:
+ raise ValueError(f"{prefix}: expected rank {RANK}, got A{sa} B{sb}")
+ used.update((prefix + _SRC_A, prefix + _SRC_B))
+ return sa, sb
+
+ for s, d in _prefixes():
+ qkv = [f"{s}.attn.{p}" for p in ("to_q", "to_k", "to_v")]
+ shapes = [pair(p) for p in qkv]
+ if len({(tuple(a), tuple(b)) for a, b in shapes}) != 1:
+ raise ValueError(f"{s}.attn: q/k/v shapes disagree: {shapes}")
+ (_rank, in_cols), (out_rows, _r) = shapes[0]
+ if out_rows != HEADS * HEAD_DIM:
+ raise ValueError(f"{s}.attn: q rows {out_rows} != {HEADS} heads x {HEAD_DIM}")
+
+ def qkv_a(qkv=qkv):
+ # A stacks [A_q; A_k; A_v]: rank 3*RANK over the shared input.
+ return to_bf16(np.concatenate([src.read(p + _SRC_A) for p in qkv], axis=0))
+
+ def qkv_b(qkv=qkv, out_rows=out_rows):
+ # Block-diagonal B, rows in the DiT's fused order: head h -> its q rows, k rows,
+ # v rows; q's rows only see A_q's rank slice, and so on.
+ out = np.zeros((HEADS, 3, HEAD_DIM, 3 * RANK), dtype=np.float32)
+ for j, p in enumerate(qkv):
+ b = src.read(p + _SRC_B).reshape(HEADS, HEAD_DIM, RANK)
+ out[:, j, :, j * RANK:(j + 1) * RANK] = b
+ return to_bf16(out.reshape(3 * out_rows, 3 * RANK))
+
+ plan[f"{d}.attn.qkv_proj.lora_A.weight"] = ([3 * RANK, in_cols], qkv_a)
+ plan[f"{d}.attn.qkv_proj.lora_B.weight"] = ([3 * out_rows, 3 * RANK], qkv_b)
+
+ for sp, dp in (("attn.to_out.0", "attn.out_proj"),
+ ("ff.net.0.proj", "mlp.fc1"),
+ ("ff.net.2", "mlp.fc2")):
+ p = f"{s}.{sp}"
+ sa, sb = pair(p)
+ if dp == "mlp.fc1" and sb[0] % 2:
+ raise ValueError(f"{p}: SwiGLU B has an odd row count {sb}")
+
+ def a_arr(p=p):
+ return to_bf16(src.read(p + _SRC_A))
+
+ def b_arr(p=p, swap=(dp == "mlp.fc1")):
+ b = src.read(p + _SRC_B)
+ if swap:
+ half = b.shape[0] // 2
+ b = np.concatenate([b[half:], b[:half]], axis=0)
+ return to_bf16(b)
+
+ plan[f"{d}.{dp}.lora_A.weight"] = (sa, a_arr)
+ plan[f"{d}.{dp}.lora_B.weight"] = (sb, b_arr)
+ unused = sorted(set(src.tensors) - used)
+ if unused:
+ raise ValueError(f"source has {len(unused)} tensors this layout does not use, e.g. {unused[:3]}")
+ return plan
+
+
+def convert(source: Path, write) -> None:
+ """Re-lay the source out, calling write(bytes) in order. Tensors are stored in
+ sorted-name order so the bytes never depend on a hash-map order."""
+ plan = plan_tensors(Source(source))
+ keys = sorted(plan)
+ header: dict = {"__metadata__": METADATA}
+ off = 0
+ for k in keys:
+ shape = plan[k][0]
+ n = shape[0] * shape[1] * 2
+ header[k] = {"data_offsets": [off, off + n], "dtype": "BF16", "shape": shape}
+ off += n
+ blob = json.dumps(header, separators=(",", ":"), sort_keys=True).encode()
+ blob += b" " * (-len(blob) % 8) # 8-byte aligned tensor data
+ write(struct.pack("<Q", len(blob)))
+ write(blob)
+ for k in keys:
+ shape, make = plan[k]
+ data = make()
+ if tuple(data.shape) != (shape[0], shape[1]) and data.size != shape[0] * shape[1]:
+ raise ValueError(f"internal: {k} has shape {data.shape} for {shape}")
+ write(data.tobytes())
+
+
+def _download(url: str, dest: Path, want_bytes: int | None, want_sha: str, label: str) -> int:
+ """Fetch `url` to `dest` (resuming), then check the digest. 0 when verified."""
+ have = dest.stat().st_size if dest.is_file() else 0
+ if want_bytes is not None and have > want_bytes:
+ dest.unlink()
+ have = 0
+ if want_bytes is None or have < want_bytes:
+ headers = {"User-Agent": "Phosphene"}
+ token = (os.environ.get("HF_TOKEN") or "").strip()
+ if token:
+ headers["Authorization"] = f"Bearer {token}"
+ if have:
+ headers["Range"] = f"bytes={have}-"
+ print(f"resuming {label} at {have // (1 << 20)} MB", flush=True)
+ else:
+ size = f" (~{want_bytes // (1 << 20)} MB)" if want_bytes else ""
+ print(f"downloading {label} from {SOURCE_REPO}{size}", flush=True)
+ req = urllib.request.Request(url, headers=headers)
+ written = have
+ try:
+ with urllib.request.urlopen(req, timeout=60) as resp, \
+ open(dest, "ab" if have else "wb") as fh:
+ if have and resp.status != 206:
+ fh.seek(0)
+ fh.truncate()
+ written = 0
+ step = 64 << 20
+ mark = written + step
+ while True:
+ chunk = resp.read(1 << 20)
+ if not chunk:
+ break
+ fh.write(chunk)
+ written += len(chunk)
+ if want_bytes and written >= mark:
+ print(f"PROGRESS {written} {want_bytes}", flush=True)
+ mark += step
+ except Exception as exc: # noqa: BLE001
+ print(f"FLEX FETCH FAILED ({label}) at {written // (1 << 20)} MB: {_plain(exc)} "
+ "(partial kept for resume; the panel offers a retry)", file=sys.stderr)
+ return 1
+ if want_bytes is not None and written != want_bytes:
+ print(f"FLEX FETCH INCOMPLETE ({label}): {written} of {want_bytes} bytes "
+ "(partial kept for resume)", file=sys.stderr)
+ return 1
+ if file_sha256(dest) != want_sha:
+ dest.unlink()
+ print(f"FLEX DIGEST MISMATCH ({label}) - download discarded; the panel offers a retry",
+ file=sys.stderr)
+ return 1
+ return 0
+
+
+def build(source: Path, target: Path) -> int:
+ partial = target.with_suffix(target.suffix + ".partial")
+ print(f"building {ASSET_NAME} on this Mac (re-layout + float32 -> bfloat16)", flush=True)
+ h = hashlib.sha256()
+ try:
+ with open(partial, "wb") as out:
+ def write(b: bytes) -> None:
+ out.write(b)
+ h.update(b)
+ convert(source, write)
+ except Exception as exc: # noqa: BLE001
+ try:
+ partial.unlink(missing_ok=True)
+ except OSError:
+ pass
+ print(f"FLEX BUILD FAILED: {_plain(exc)} (the panel offers a retry)", file=sys.stderr)
+ return 1
+ size = partial.stat().st_size
+ digest = h.hexdigest()
+ if ASSET_SHA256 and (size != ASSET_BYTES or digest != ASSET_SHA256):
+ partial.unlink(missing_ok=True)
+ print(f"FLEX BUILD MISMATCH: {size} bytes, sha256 {digest[:12]} "
+ f"(want {ASSET_BYTES}, {ASSET_SHA256[:12]}) - nothing installed", file=sys.stderr)
+ return 1
+ partial.replace(target)
+ print(f"built {target.name}: {size} bytes, sha256 {digest}", flush=True)
+ return 0
+
+
+def licence_accepted(state_dir: Path) -> bool:
+ """Whether the MiniMax H3 licence is accepted in Phosphene (the same marker
+ scripts/pinokio/h3_licence_gate.sh and the panel read)."""
+ gate = Path(__file__).resolve().parent / "pinokio" / "h3_licence_gate.sh"
+ m = re.search(r'^H3_LICENCE_VERSION="([^"]+)"', gate.read_text(), re.M) if gate.is_file() else None
+ if not m:
+ return any(state_dir.glob("licence-h3-*.accepted"))
+ return (state_dir / f"licence-h3-{m.group(1)}.accepted").is_file()
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ ap.add_argument("--dir", required=True, help="target directory (the H3 pack's pika-h3-flex/)")
+ ap.add_argument("--source", default=None,
+ help="use this already-downloaded upstream fl2va/adapter.safetensors")
+ ap.add_argument("--keep-source", action="store_true",
+ help="keep the 2.8 GB upstream file after a good build")
+ ap.add_argument("--licence-state", default=None,
+ help="Phosphene's state dir: skip (exit 0) unless the H3 licence is accepted there")
+ args = ap.parse_args()
+
+ if args.licence_state and not licence_accepted(Path(args.licence_state)):
+ print("Pika H3 Flex skipped: accept the MiniMax H3 licence in Phosphene first.")
+ return 0
+ target_dir = Path(args.dir)
+ target_dir.mkdir(parents=True, exist_ok=True)
+ lock_fh = open(target_dir / ".pika_h3_flex.lock", "w")
+ try:
+ fcntl.flock(lock_fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError:
+ print("FLEX FETCH BUSY: another Pika H3 Flex download is running for this folder",
+ file=sys.stderr)
+ return 1
+
+ # Licence + notice + the release's sampling manifest, beside the adapter.
+ for name, sha in SIDE_FILES.items():
+ dest = target_dir / ("pika_" + name.replace("/", "_"))
+ if dest.is_file() and file_sha256(dest) == sha:
+ continue
+ rc = _download(source_url(name), dest, None, sha, name)
+ if rc:
+ return rc
+
+ target = target_dir / ASSET_NAME
+ if target.is_file():
+ if not ASSET_BYTES or target.stat().st_size == ASSET_BYTES:
+ print(f"Pika H3 Flex adapter already present: {target}")
+ return 0
+ print(f"REFUSING: {target} exists with unexpected size {target.stat().st_size} "
+ f"(want {ASSET_BYTES}). Move it aside and re-run.", file=sys.stderr)
+ return 1
+
+ if args.source:
+ source = Path(args.source)
+ if (not source.is_file() or source.stat().st_size != SOURCE_BYTES
+ or file_sha256(source) != SOURCE_SHA256):
+ print(f"REFUSING: {source} is not the pinned upstream {SOURCE_FILE}", file=sys.stderr)
+ return 1
+ own_source = False
+ else:
+ source = target_dir / "pika_fl2va_adapter.safetensors.download"
+ rc = _download(source_url(SOURCE_FILE), source, SOURCE_BYTES, SOURCE_SHA256, SOURCE_FILE)
+ if rc:
+ return rc
+ own_source = True
+
+ rc = build(source, target)
+ if rc:
+ return rc
+ if own_source and not args.keep_source:
+ source.unlink(missing_ok=True)
+ print(f"Pika H3 Flex adapter ready: {target}")
+ return 0
+
+
+if __name__ == "__main__":
+ try:
+ sys.exit(main())
+ except SystemExit:
+ raise
+ except BaseException as exc: # noqa: BLE001
+ print(f"FLEX FETCH FAILED: {_plain(type(exc).__name__)} {_plain(exc)} "
+ "(the panel offers a retry)", file=sys.stderr)
+ sys.exit(1)
diff --git a/scripts/fleet_timings_build.py b/scripts/fleet_timings_build.py
index c05cc79..a3bb58a 100644
--- a/scripts/fleet_timings_build.py
+++ b/scripts/fleet_timings_build.py
@@ -123,10 +123,12 @@ def _sql_literal(s: str) -> str:
# ran (`h3_sampler`); `steps` cannot (7 points is v1.3, Turbo AND a Best
# pinned to 7), so an event without it - every version before 4.19.11, none of
# which ran v1.3 - falls back to the old rule: <= 5 points Fast, else Best.
-# Turbo gets a lane of its own that no price reads.
+# Turbo gets a lane of its own that no price reads, and so does Pika H3 Flex
+# (also 7 points) until it has receipts of its own.
_SPEED_EXPR = (
"multiIf(properties.engine != 'h3', '', "
"properties.h3_sampler = 'v13', 'v13', "
+ "properties.h3_sampler = 'flex', 'flex', "
"properties.h3_sampler = 'fast', 'fast', "
"properties.h3_sampler = 'turbo', 'turbo', "
"properties.h3_sampler = 'best', 'best', "
diff --git a/scripts/pinokio/h3_checkout.sh b/scripts/pinokio/h3_checkout.sh
index 8ee4b40..123250e 100755
--- a/scripts/pinokio/h3_checkout.sh
+++ b/scripts/pinokio/h3_checkout.sh
@@ -36,8 +36,8 @@
# keeps its H3 step optional: scripts/post_update.sh runs this file through
# `defang`, which turns the FATAL line into a WARN and never ends the Update.
set -u
-H3_PIN_SHA="3f6c75c09ccfa336a8c211b787d6a2350d83ef7a"
-H3_PIN_REF="phosphene/v4.19.0"
+H3_PIN_SHA="bef6d03c5545fe9dc38400ad2c52edd958e3b2d4"
+H3_PIN_REF="phosphene/v4.19.15"
H3_LOCAL_BRANCH="phosphene-pinned"
H3_URL="https://github.com/mrbizarro/minimax-h3-mlx.git"
H3_DIR="${1:-}"
diff --git a/webapp/docs/hailuo-h3.md b/webapp/docs/hailuo-h3.md
index 49ce428..4c769d1 100644
--- a/webapp/docs/hailuo-h3.md
+++ b/webapp/docs/hailuo-h3.md
@@ -107,6 +107,19 @@ On **High**, **Best** can use **lightx2v v1.3**, an adapter by LightX2V. In our
- **Use the old Best:** choose a **Steps** count under Best to use the full sampler.
- **Credit and licence:** lightx2v v1.3 is by [LightX2V](https://huggingface.co/lightx2v/Minimax-h3-Turbo). Code: Apache-2.0. Weights: MiniMax H3 Community License, the same as H3.
+## H3 Flex (preview) {#flex}
+
+**H3 Flex** is Pika H3 Flex by Pika Labs: a six-step version of H3, about 2.2× faster than Best at the same size. It is a **preview**: new on Mac, so tell us how it goes.
+
+- **Pick it:** choose **H3 Flex** in the engine picker at the top, right after Hailuo H3.
+- **Get it:** if its adapter is not on your Mac yet, the same click downloads it (2.8 GB, from Pika's own Hugging Face page at a fixed version) and prepares it on your Mac. The picker shows the progress. You need Hailuo H3 installed; if it isn't, the picker offers H3 first.
+- **What it makes:** Text and Image (first frame), with dialogue and sound, on every 5-second length (10 s and 15 s are 5 s pieces joined, and later pieces can drift).
+- **Times on an M4 Max, 64 GB, per 5 s:** Draft about 5 minutes, High about 16 minutes (Best: 36.5 minutes on the same shot). Full size (1344×768) runs; its timing is still to come.
+- **Tip:** name every person who should stay in the scene. Flex drops people the prompt doesn't mention.
+- **Back to H3's own Fast / Best:** pick **Hailuo H3** in the picker.
+
+Powered by MiniMax H3. Pika H3 Flex by Pika Labs (Mellis, Inc.): the weights are a MiniMax H3 Model Derivative under the MiniMax H3 Community License; Pika's code is Apache-2.0. Phosphene converts the file on your Mac and marks it as modified. Mac weights are also on Hugging Face: [Mrbizarro/Pika-H3-Flex-MLX](https://huggingface.co/Mrbizarro/Pika-H3-Flex-MLX).
+
## How long it takes {#times}
Each quality and length option shows an estimated time for your Mac, based on completed videos from similar Macs. The table shows median times from Phosphene's anonymous usage counts: half finished sooner and half took longer. A dash means there are too few completed videos to give a time.
diff --git a/webapp/index.html b/webapp/index.html
index 908d8c3..ef7c89c 100644
--- a/webapp/index.html
+++ b/webapp/index.html
@@ -1310,6 +1310,8 @@
re-resolves it (Draft/Standard/High only, never with Turbo). In
the make_job allowlist. -->
<input type="hidden" name="h3_tristep" id="h3_tristep" value="0">
+ <!-- Pika H3 Flex (a Speed choice): "1" when the third pill renders. -->
+ <input type="hidden" name="h3_flex" id="h3_flex" value="0">
<!-- Which of H3's ONE adapter slots this render spends. Its runner's
`--lora` takes a single path (default=None, not append), so Turbo
and a picked LoRA cannot both run and something has to choose.
@@ -1371,7 +1373,7 @@
<span class="qs-name">Speed</span>
<span class="qs-meta">Fast: ~4&times; quicker, a touch softer &middot; Best: sharpest faces, much slower</span>
</div>
- <div class="pill-group cols-2 h3-speed-group" id="h3SpeedGroup">
+ <div class="pill-group cols-3 h3-speed-group" id="h3SpeedGroup">
<button type="button" class="pill-btn" data-h3-speed="fast"
title="About 4× faster than Best, a touch softer on fine detail — great for drafts and most shots.">
<span>⚡ Fast</span><span class="sub" id="h3SpeedFastSub"></span>
@@ -1380,8 +1382,21 @@
title="This shape's full sampler — sharpest faces and detail, the slower, most careful render.">
<span>✦ Best</span><span class="sub" id="h3SpeedBestSub"></span>
</button>
+ <!-- Pika H3 Flex running natively on Apple Silicon (MLX): Pika
+ Labs' six-step H3 student on our own MLX sampler. -->
+ <button type="button" class="pill-btn" data-h3-speed="flex"
+ title="Pika H3 Flex (preview): Pika Labs' six-step version of H3, running natively on your Mac. New - feedback welcome. Powered by MiniMax H3.">
+ <span>✧ Pika Flex (preview)</span><span class="sub" id="h3SpeedFlexSub"></span>
+ </button>
</div>
<div class="h3-turbo-note" id="h3SpeedNote" hidden></div>
+ <!-- Pika H3 Flex: credit + "Powered by MiniMax H3" while it is
+ the choice, the one click that gets it before then
+ (_h3RenderFlexNote). -->
+ <div class="h3-turbo-note h3-flex-note" id="h3FlexNote" hidden>
+ <span id="h3FlexNoteText"></span>
+ <button type="button" class="ghost-btn h3-flex-get" id="h3FlexGet" hidden></button>
+ </div>
<!-- lightx2v v1.3 on Best at High: credit once it is in, the
one click that gets it before then (_h3RenderV13Note). -->
<div class="h3-turbo-note h3-v13-note" id="h3V13Note" hidden>
diff --git a/webapp/js/characters.js b/webapp/js/characters.js
index ac94749..f50a590 100644
--- a/webapp/js/characters.js
+++ b/webapp/js/characters.js
@@ -4404,7 +4404,9 @@ function updateShotSetupSummary() {
}
let fast = false;
try { fast = h3TriStepOn(cell); } catch (_) {}
- parts.push(fast ? 'Fast' : 'Best');
+ let flex = false;
+ try { flex = !fast && typeof h3FlexOn === 'function' && h3FlexOn(cell); } catch (_) {}
+ parts.push(fast ? 'Fast' : (flex ? 'Pika H3 Flex' : 'Best'));
const st = (document.getElementById('h3_steps') || {}).value || 'auto';
if (st !== 'auto') parts.push(st + ' steps');
// Priced by the engine module's own helper, so the line can never
diff --git a/webapp/js/engines.js b/webapp/js/engines.js
index ba3b42f..2a640f2 100644
--- a/webapp/js/engines.js
+++ b/webapp/js/engines.js
@@ -382,11 +382,23 @@ function _h3V13Mode() {
const m = (document.getElementById('mode') || {}).value || 't2v';
return m === 't2v' || m === 'i2v';
}
+// Pika H3 Flex (Pika Labs' six-step H3 student, running natively on Apple
+// Silicon): the third Speed choice. Text and Image, every 5 s-window cell the
+// server prices (cell.flex_min); never a default — only when picked.
+function h3FlexState() {
+ return (H3 && H3.flex) || { available: false, supported: false, downloaded: false };
+}
+function h3FlexOn(cell) {
+ cell = cell || h3CurrentCell();
+ return !!(cell && cell.flex_min != null && _h3V13Mode()
+ && h3FlexState().available && h3SpeedPref() === 'flex');
+}
// Would THIS cell's Best render on v1.3, as things stand?
function h3V13On(cell, opts) {
cell = cell || h3CurrentCell();
if (!cell || cell.v13_min == null) return false;
opts = opts || {};
+ if (opts.flex == null && typeof h3FlexOn === 'function' && h3FlexOn(cell)) return false;
const fast = (opts.fast != null) ? opts.fast : h3TriStepOn(cell);
if (fast) return false;
const ov = (opts.steps != null) ? String(opts.steps)
@@ -397,10 +409,12 @@ function h3V13On(cell, opts) {
function h3SpeedPref() {
let v = null;
try { v = localStorage.getItem('phos_h3_speed'); } catch (e) {}
- return v === 'best' ? 'best' : 'fast';
+ return (v === 'best' || v === 'flex') ? v : 'fast';
}
function _h3SetSpeedPref(v) {
- try { localStorage.setItem('phos_h3_speed', v === 'best' ? 'best' : 'fast'); } catch (e) {}
+ try {
+ localStorage.setItem('phos_h3_speed', (v === 'best' || v === 'flex') ? v : 'fast');
+ } catch (e) {}
}
function _h3IsI2V() {
return ((document.getElementById('mode') || {}).value || 't2v') === 'i2v';
@@ -442,7 +456,10 @@ function h3CellEtaMin(cell, opts) {
const fast = (opts.fast != null) ? opts.fast : h3TriStepOn(cell);
if (fast && cell.tristep_min != null) return _h3TriStepMin(cell);
if (opts.turbo) return cell.turbo_min;
- if (h3V13On(cell, { fast: false, steps: opts.steps })) return cell.v13_min;
+ const flexOn = (opts.flex != null) ? opts.flex
+ : (typeof h3FlexOn === 'function' && h3FlexOn(cell));
+ if (flexOn && cell.flex_min != null) return cell.flex_min;
+ if (h3V13On(cell, { fast: false, steps: opts.steps, flex: false })) return cell.v13_min;
const ov = (opts.steps != null) ? String(opts.steps)
: ((document.getElementById('h3_steps') || {}).value || 'auto');
if (ov !== 'auto' && /^\d+$/.test(ov)) {
@@ -479,9 +496,12 @@ function h3CellEta(cell, opts) {
const fast = (opts.fast != null) ? opts.fast : h3TriStepOn(cell);
if (fast && cell.tristep_min != null) return _h3TriStepEta(cell);
if (opts.turbo) return cell.turbo_eta;
+ const flexOn = (opts.flex != null) ? opts.flex
+ : (typeof h3FlexOn === 'function' && h3FlexOn(cell));
+ if (flexOn && cell.flex_eta) return cell.flex_eta;
const ov = (document.getElementById('h3_steps') || {}).value || 'auto';
if (ov === 'auto' || !/^\d+$/.test(ov)) {
- if (h3V13On(cell, { fast: false })) {
+ if (h3V13On(cell, { fast: false, flex: false })) {
return (!_h3IsI2V() && cell.fleet_range_v13) ? cell.fleet_range_v13.eta_range : cell.v13_eta;
}
// Owner ruling (2026-09-29): Best's own real fleet range, same idea as
@@ -496,7 +516,21 @@ function h3CellEta(cell, opts) {
function h3SpeedSub(which) {
const cell = h3CurrentCell();
if (which === 'best') {
- return _h3EtaPlain(h3CellEta(cell, { fast: false })) || 'full steps';
+ return _h3EtaPlain(h3CellEta(cell, { fast: false, flex: false })) || 'full steps';
+ }
+ if (which === 'flex') {
+ const fx = h3FlexState();
+ if (!fx.supported) return 'update H3 runner';
+ if (!fx.downloaded) {
+ if (fx.installing) {
+ const d = fx.download || {};
+ return d.status === 'building' ? 'preparing…'
+ : 'installing ' + (d.mb || 0) + ' / ' + (d.total_mb || 2639) + ' MB';
+ }
+ return 'Install (' + (fx.download_gb || 2.8) + ' GB)';
+ }
+ if (!cell || cell.flex_min == null || !_h3V13Mode()) return 'not at this shape';
+ return _h3EtaPlain(h3CellEta(cell, { fast: false, flex: true })) || '6 steps';
}
const tri = h3TriStepState();
if (!tri.supported) return 'update H3 runner';
@@ -573,12 +607,109 @@ function renderH3Turbo() {
? (cell.label || 'This shape') + ' has no Fast pass yet — it always renders on Best.'
: '3 steps — about 4× faster, great for drafts and most shots.';
}
+ const flexBtn = document.querySelector('#h3SpeedGroup [data-h3-speed="flex"]');
+ const flexSub = document.getElementById('h3SpeedFlexSub');
+ const fx = h3FlexState();
+ if (flexSub) flexSub.textContent = h3SpeedSub('flex');
+ if (flexBtn) {
+ // Hidden where the runner cannot take it at all (an older pack); dashed
+ // until the adapter is in, like Fast.
+ // 4.19.15: H3 Flex is its own entry in the top engine picker (owner:
+ // "selected in the ticker, like we select H3"). One obvious way in, so the
+ // Speed pill stays hidden; the Speed row is H3's own Fast / Best again.
+ flexBtn.hidden = true;
+ flexBtn.classList.toggle('needs-download', !fx.available);
+ flexBtn.classList.toggle('cell-only-best',
+ fx.available && !!cell && (cell.flex_min == null || !_h3V13Mode()));
+ }
+ const group = document.getElementById('h3SpeedGroup');
+ if (group && flexBtn) {
+ group.classList.toggle('cols-3', !flexBtn.hidden);
+ group.classList.toggle('cols-2', flexBtn.hidden);
+ }
+ // While H3 Flex is the engine, Fast / Best do not apply: the row shows the
+ // Flex note (credit, download, progress) instead of two unlit pills.
+ const flexPicked = h3SpeedPref() === 'flex';
+ if (group) group.hidden = flexPicked;
+ const speedMeta = document.querySelector('#h3SpeedRow .qs-meta');
+ if (speedMeta) speedMeta.hidden = flexPicked;
+ const speedName = document.querySelector('#h3SpeedRow .qs-name');
+ if (speedName) speedName.textContent = flexPicked ? 'H3 Flex (preview)' : 'Speed';
_h3SyncSamplerTitles();
_h3ApplySpeed();
+ _h3RenderFlexNote();
+ _h3FlexPickerSync();
_h3RenderV13Note();
_h3SyncFaceFixEta();
}
+// The line under the switch for Pika H3 Flex: the credit (and "Powered by
+// MiniMax H3", which the H3 licence asks a product to show) while it is the
+// choice, the one click that gets it before then.
+function _h3RenderFlexNote() {
+ const box = document.getElementById('h3FlexNote');
+ if (!box) return;
+ const cell = h3CurrentCell();
+ const fx = h3FlexState();
+ const text = document.getElementById('h3FlexNoteText');
+ const btn = document.getElementById('h3FlexGet');
+ const show = h3SpeedPref() === 'flex' && !h3TriStepOn(cell);
+ box.hidden = !show;
+ if (!show || !text) return;
+ const name = fx.name || 'Pika H3 Flex';
+ const credit = 'By Pika Labs, running natively on your Mac. Powered by MiniMax H3 ('
+ + (fx.license || 'MiniMax H3 Community License') + ').';
+ // Preview (4.19.15): new on the Mac, so say so and ask for word back.
+ const preview = ' Preview: new on Mac, so tell us how it goes. Tip: name every person who should stay in the shot.';
+ let msg = '';
+ let canGet = false;
+ if (!fx.supported) {
+ msg = name + ' needs a newer H3 runner. ' + distText(
+ 'Click "Update Hailuo H3 runner" in the Pinokio sidebar. Your weights stay.',
+ 'Updating the runner isn\u2019t available in the Mac app yet.');
+ } else if (fx.installing) {
+ const d = fx.download || {};
+ msg = d.status === 'building' ? 'Preparing ' + name + ' on your Mac…'
+ : 'Downloading ' + name + ': ' + (d.mb || 0) + ' / ' + (d.total_mb || 2639) + ' MB';
+ } else if (!fx.downloaded) {
+ const e = (fx.download || {}).error;
+ msg = name + ': Pika Labs\u2019 six-step H3, about ' + _h3EtaPlain(cell && cell.flex_eta)
+ + ' here. ' + credit + preview + (e ? ' Last try failed: ' + e : '');
+ canGet = true;
+ } else if (h3FlexOn(cell)) {
+ msg = name + ' (' + (fx.forwards || 6) + ' steps). ' + credit + preview;
+ } else {
+ msg = name + ' renders Text and Image on 5-second windows; this shape uses Best.';
+ }
+ text.textContent = msg;
+ if (btn) {
+ btn.hidden = !canGet;
+ btn.textContent = 'Get it · ' + (fx.download_gb || 2.8) + ' GB';
+ }
+}
+async function h3FlexInstall() {
+ const toast = (m, kind) => { if (typeof phosToast === 'function') phosToast(m, { kind }); };
+ const btn = document.getElementById('h3FlexGet');
+ if (btn) btn.disabled = true;
+ try {
+ const r = await fetch('/h3/flex/install', { method: 'POST' });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(j.error || ('HTTP ' + r.status));
+ _h3SetSpeedPref('flex');
+ toast(j.already_installed ? 'Pika H3 Flex is already installed.'
+ : 'Downloading Pika H3 Flex from Pika Labs (2.8 GB), then preparing it on your Mac. '
+ + 'It switches on by itself when ready.', 'ok');
+ } catch (e) {
+ toast('Pika H3 Flex: ' + (e.message || 'failed'), 'danger');
+ } finally {
+ if (btn) btn.disabled = false;
+ }
+}
+{
+ const _flexBtn = document.getElementById('h3FlexGet');
+ if (_flexBtn) _flexBtn.onclick = (ev) => { ev.preventDefault(); h3FlexInstall(); };
+}
+
// The line under the switch for lightx2v v1.3 on High: what it is and who
// made it once it is in, the one click that gets it before then.
function _h3RenderV13Note() {
@@ -588,7 +719,9 @@ function _h3RenderV13Note() {
const v = h3V13State();
const text = document.getElementById('h3V13NoteText');
const btn = document.getElementById('h3V13Get');
- const show = !!(cell && cell.v13_min != null && _h3V13Mode() && !h3TriStepOn(cell));
+ // Not while Pika H3 Flex is the choice: its own note says what renders.
+ const show = !!(cell && cell.v13_min != null && _h3V13Mode() && !h3TriStepOn(cell)
+ && h3SpeedPref() !== 'flex');
box.hidden = !show;
if (!show || !text) return;
const name = v.name || 'lightx2v v1.3';
@@ -661,13 +794,16 @@ function _h3ApplySpeed() {
if (triIn) triIn.value = fastOn ? '1' : '0';
const tbIn = document.getElementById('h3_turbo');
if (tbIn) tbIn.value = '0';
+ const flexOn = !fastOn && typeof h3FlexOn === 'function' && h3FlexOn(cell);
+ const fxIn = document.getElementById('h3_flex');
+ if (fxIn) fxIn.value = flexOn ? '1' : '0';
// H3-13: the lit half used to be the PREFERENCE alone (pref === 'fast' &&
// tri.available), so Native and the single-pass 10s — cells with no Fast
// path at all (cell.tristep_min == null) — kept the Fast pill pink while
// the render that actually queued ran Best, 8-25x slower. fastOn already
// folds in per-cell availability (h3TriStepOn), so light whichever half
// is really about to render; the note below still explains why.
- const lit = fastOn ? 'fast' : 'best';
+ const lit = fastOn ? 'fast' : (flexOn ? 'flex' : 'best');
document.querySelectorAll('#h3SpeedGroup [data-h3-speed]').forEach(b =>
b.classList.toggle('active', b.dataset.h3Speed === lit));
const note = document.getElementById('h3SpeedNote');
@@ -699,6 +835,12 @@ function _h3ApplySpeed() {
// hasn't loaded yet.
if (s) s.value = (cell && cell.tristep_forwards != null)
? cell.tristep_forwards : (tri.steps ? tri.steps - 1 : 3);
+ } else if (flexOn && s && cell) {
+ // Flex owns its six-step ladder: a pinned Steps pill does not apply.
+ if (stIn && stIn.value !== 'auto' && typeof setH3Steps === 'function') {
+ try { setH3Steps('auto'); } catch (e) {}
+ }
+ s.value = (cell.flex_forwards != null) ? cell.flex_forwards : (h3FlexState().forwards || 6);
} else if (s && cell) {
const ov = (stIn || {}).value || 'auto';
s.value = (ov !== 'auto' && /^\d+$/.test(ov)) ? parseInt(ov, 10)
@@ -706,7 +848,7 @@ function _h3ApplySpeed() {
}
// Steps is a Best control: it only shows while Best is what renders.
const stepsRow = document.getElementById('h3StepsRow');
- if (stepsRow) stepsRow.hidden = fastOn;
+ if (stepsRow) stepsRow.hidden = fastOn || flexOn;
if (typeof renderH3LoraSlot === 'function') { try { renderH3LoraSlot(); } catch (e) {} }
} finally {
_h3SpeedBusy = false;
@@ -721,7 +863,7 @@ function _h3SpeedRepriced() {
// Set the speed ('fast' | 'best'). Remembered per browser.
function setH3Speed(v) {
- _h3SetSpeedPref(v === 'best' ? 'best' : 'fast');
+ _h3SetSpeedPref((v === 'best' || v === 'flex') ? v : 'fast');
_h3ApplySpeed();
_h3SpeedRepriced();
}
@@ -731,7 +873,7 @@ function setH3TriStep(on) { setH3Speed(on ? 'fast' : 'best'); }
// What a saved clip was made with, as this switch's value.
function h3SpeedOfParams(p) {
p = p || {};
- return (p.h3_tristep || p.h3_turbo) ? 'fast' : 'best';
+ return (p.h3_tristep || p.h3_turbo) ? 'fast' : (p.h3_flex ? 'flex' : 'best');
}
// H3-04: "Fast" / "Best", for any place that shows a submitted or running
// H3 job's params — the Now card, a queue row, the info modal. One
@@ -739,6 +881,7 @@ function h3SpeedOfParams(p) {
function h3JobSpeedLabel(p) {
if (!p || p.engine !== 'h3') return '';
if (h3SpeedOfParams(p) === 'fast') return 'Fast';
+ if (h3SpeedOfParams(p) === 'flex') return 'Pika H3 Flex';
return p.h3_v13 ? 'Best · lightx2v v1.3' : 'Best';
}
// "Hailuo H3 · Standard 10s" — the shape a submitted H3 job asked for,
@@ -755,6 +898,22 @@ function h3JobShapeLabel(p) {
// The Fast half: select it when ready; otherwise the one click that makes it
// ready (install the adapter, or say which update is needed).
async function h3SpeedClick(which) {
+ if (which === 'flex') {
+ const fx = h3FlexState();
+ if (fx.available) { setH3Speed('flex'); return; }
+ const toastF = (m, kind) => { if (typeof phosToast === 'function') phosToast(m, { kind }); };
+ if (!fx.supported) {
+ toastF(distText('Pika H3 Flex needs a newer Hailuo H3 runner. Run "Update Hailuo H3 runner" in the '
+ + 'Pinokio sidebar — your weights stay.',
+ 'Pika H3 Flex needs a newer Hailuo H3 runner. Updating the runner isn\u2019t available in the Mac app yet.'), 'danger');
+ return;
+ }
+ // Show the note (credit + the Get button) for the one explicit click.
+ _h3SetSpeedPref('flex');
+ _h3ApplySpeed();
+ _h3SpeedRepriced();
+ return;
+ }
if (which !== 'fast') { setH3Speed('best'); return; }
const tri = h3TriStepState();
if (tri.available) { setH3Speed('fast'); return; }
@@ -863,7 +1022,8 @@ function h3EstimateLine() {
return 'Fast HD · ' + cell.width + '×' + cell.height + ' → ' + cell.final_width + '×'
+ cell.final_height + ' ≈ ' + h3FmtEtaMin(m).replace(/^~/, '').replace(/ · batch$/, '');
}
- let txt = cell.quality_label + ' · ' + (fast ? 'Fast' : 'Best');
+ const flexLine = !fast && typeof h3FlexOn === 'function' && h3FlexOn(cell);
+ let txt = cell.quality_label + ' · ' + (fast ? 'Fast' : (flexLine ? 'Pika H3 Flex' : 'Best'));
if (h3FaceFixOn()) {
txt += ' + Face Fix';
if (cell.facefix_min == null) return txt;
@@ -1020,6 +1180,98 @@ document.addEventListener('keydown', (ev) => {
});
window.addEventListener('resize', () => closeEngineMenu({ returnFocus: false }));
+// ---- H3 Flex: its own entry in the engine picker (4.19.15, preview) --------
+// Not a server engine: it renders on H3 (engine=h3, h3_flex=1, the Flex
+// adapter + its six-step sampler), so every H3 gate, price and queue path
+// stays the one H3 already has. The picker shows it as a sibling of H3 so it
+// can be found, downloaded and chosen the way an engine is.
+const H3FLEX_ID = 'h3flex';
+function h3FlexPicked() {
+ return currentEngine() === 'h3' && h3SpeedPref() === 'flex';
+}
+// The entry, built from H3's own row (accent, mark, surfaces), or null when
+// this Mac's H3 runner cannot take Flex at all (an older H3 pack).
+function h3FlexPickerEntry() {
+ const h3e = engineById('h3');
+ if (!h3e || !engineRenderable(h3e)) return null;
+ const fx = h3FlexState();
+ const h3st = engineStatus(h3e);
+ if (h3st.available && !fx.supported && !fx.downloaded) return null;
+ return Object.assign({}, h3e, {
+ id: H3FLEX_ID, label: 'H3 Flex', generation: '', preview: true, virtual: true,
+ sublabel: 'Pika H3 Flex · preview',
+ tagline: "Pika Labs' six-step H3: about 2.2× faster than Best. Preview.",
+ });
+}
+// Its state, in the same words the menu uses for every engine.
+function h3FlexPickerStatus() {
+ const h3st = engineStatus(engineById('h3'));
+ const fx = h3FlexState();
+ const d = fx.download || {};
+ return {
+ capable: !!h3st.capable,
+ h3_ready: !!h3st.available,
+ available: !!(h3st.available && fx.available),
+ installing: !!fx.installing,
+ progress: fx.installing
+ ? (d.status === 'building' ? 'preparing'
+ : Math.min(99, Math.round(100 * (d.mb || 0) / (d.total_mb || 2639))) + '%')
+ : '',
+ error: d.error || '',
+ download_gb: fx.download_gb || 2.8,
+ };
+}
+function _h3FlexBadge(st, h3e) {
+ if (!st.h3_ready) return (h3e.install_size || '').replace(/^~/, '');
+ if (st.installing) return st.progress;
+ if (!st.available) return st.download_gb + ' GB';
+ return '';
+}
+function _h3FlexTooltip(st, h3e) {
+ const credit = ' By Pika Labs, running on your Mac. Powered by MiniMax H3.';
+ if (!st.h3_ready) return 'H3 Flex (preview) — needs Hailuo H3 first ('
+ + (h3e.install_size || '') + '); then its 2.8 GB adapter. Click to get them.' + credit;
+ if (st.installing) return 'H3 Flex (preview) — downloading and preparing (' + st.progress + ').' + credit;
+ if (!st.available) return 'H3 Flex (preview) — click to download it (' + st.download_gb
+ + ' GB from Pika Labs, prepared on your Mac).' + credit;
+ return "H3 Flex (preview) — Pika Labs' six-step H3, about 2.2× faster than Best." + credit;
+}
+// Picking it: H3 with the Flex sampler. Missing pieces download on the same
+// click: H3 itself through its own install card (Flex follows on the first
+// status tick that finds H3 ready), else the Flex adapter right here.
+function h3FlexPickerClick() {
+ const h3e = engineById('h3');
+ const st = h3FlexPickerStatus();
+ if (!h3e || !st.capable) return;
+ _h3SetSpeedPref('flex');
+ try { localStorage.setItem('phos_h3flex_wanted', '1'); } catch (e) {}
+ if (!st.h3_ready) { engineSegClick('h3'); return; }
+ if (!engineServesMode(h3e, currentMode)) return;
+ setEngine('h3');
+ if (typeof setH3Speed === 'function') setH3Speed('flex');
+ if (!st.available && !st.installing) h3FlexInstall();
+ renderEngineSwitch();
+}
+// Status ticks: redraw the picker when Flex's state moves, and finish what
+// a click on H3 Flex asked for once H3 itself has arrived.
+let _h3FlexPickerSig = '';
+function _h3FlexPickerSync() {
+ const st = h3FlexPickerStatus();
+ let wanted = false;
+ try { wanted = localStorage.getItem('phos_h3flex_wanted') === '1'; } catch (e) {}
+ if (wanted && st.available) { try { localStorage.removeItem('phos_h3flex_wanted'); } catch (e) {} }
+ if (wanted && st.h3_ready && !st.available && !st.installing && !st.error
+ && h3FlexState().supported && h3SpeedPref() === 'flex' && !window._h3FlexAutoAsked) {
+ window._h3FlexAutoAsked = true;
+ h3FlexInstall();
+ }
+ const sig = [st.h3_ready, st.available, st.installing, st.progress, h3SpeedPref()].join('|');
+ if (sig !== _h3FlexPickerSig) {
+ _h3FlexPickerSig = sig;
+ if (typeof renderEngineSwitch === 'function') { try { renderEngineSwitch(); } catch (e) {} }
+ }
+}
+
function renderEngineSwitch() {
renderLtxGenSwitch(); // the Remix-row switch; independent of the header row below
const box = document.getElementById('engineSwitch');
@@ -1030,9 +1282,17 @@ function renderEngineSwitch() {
if (div) div.hidden = !show;
if (!show) { box.innerHTML = ''; closeEngineMenu(); return; }
- const active = _currentSurface() === 'music' ? 'music' : currentEngine();
const surfaceMode = _currentSurface() === 'music' ? 'music' : currentMode;
const list = ENGINES.filter(engineRenderable);
+ // H3 Flex sits right after H3 (preview; see h3FlexPickerEntry).
+ // typeof: harnesses that lift renderEngineSwitch alone (test_music_engine) run without it.
+ const flexEntry = (typeof h3FlexPickerEntry === 'function') ? h3FlexPickerEntry() : null;
+ if (flexEntry) {
+ const at = list.findIndex(e => e.id === 'h3');
+ list.splice(at + 1, 0, flexEntry);
+ }
+ const active = _currentSurface() === 'music' ? 'music'
+ : (flexEntry && h3FlexPicked() ? 'h3flex' : currentEngine());
// ---- The trigger: the active engine, and nothing else ----
const act = list.find(e => e.id === active) || list[0];
@@ -1040,10 +1300,12 @@ function renderEngineSwitch() {
box.innerHTML = `<button type="button" class="eng-trigger" aria-haspopup="listbox"
aria-expanded="false"
style="--eng-accent:${escapeHtml(act.accent)};--eng-dim:${escapeHtml(act.accent_dim)};--eng-soft:${escapeHtml(act.accent_soft)}"
- title="${escapeHtml(_engineTooltip(act, engineStatus(act), engineServesMode(act, surfaceMode)))}">
+ title="${escapeHtml(act.virtual ? _h3FlexTooltip(h3FlexPickerStatus(), engineById('h3'))
+ : _engineTooltip(act, engineStatus(act), engineServesMode(act, surfaceMode)))}">
<span class="eng-mark"><svg class="ph" aria-hidden="true"><use href="#${escapeHtml(act.mark)}"/></svg></span>
<span class="eng-seg-name">${escapeHtml(act.label)}</span>${
- act.generation ? `<span class="eng-seg-gen">${escapeHtml(act.generation)}</span>` : ''}
+ act.generation ? `<span class="eng-seg-gen">${escapeHtml(act.generation)}</span>` : ''}${
+ act.preview ? '<span class="eng-badge eng-preview">preview</span>' : ''}
<svg class="ph eng-caret" aria-hidden="true"><use href="#ph-caret-down-bold"/></svg>
</button>`;
const t = box.querySelector('.eng-trigger');
@@ -1053,6 +1315,28 @@ function renderEngineSwitch() {
// ---- The menu: every engine, each stating its own state ----
const menu = _engineMenuEl();
menu.innerHTML = list.map(e => {
+ if (e.virtual) {
+ const fst = h3FlexPickerStatus();
+ const fBadge = _h3FlexBadge(fst, engineById('h3'));
+ const fOffer = !fst.available;
+ const fOk = engineServesMode(e, surfaceMode);
+ const fCls = 'eng-opt eng-opt-flex' + (e.id === active ? ' active' : '')
+ + (fOffer ? ' needs-install' : '') + (fst.available && !fOk ? ' inert' : '');
+ return `<button type="button" class="${fCls}" data-engine="${H3FLEX_ID}"
+ role="option" aria-selected="${e.id === active ? 'true' : 'false'}"
+ style="--eng-accent:${escapeHtml(e.accent)};--eng-dim:${escapeHtml(e.accent_dim)};--eng-soft:${escapeHtml(e.accent_soft)}"
+ title="${escapeHtml(_h3FlexTooltip(fst, engineById('h3')))}">
+ <span class="eng-mark"><svg class="ph" aria-hidden="true"><use href="#${escapeHtml(e.mark)}"/></svg></span>
+ <span class="eng-opt-body">
+ <span class="eng-opt-top">
+ <span class="eng-seg-name">${escapeHtml(e.label)}</span><span class="eng-badge eng-preview">preview</span>${
+ fBadge ? `<span class="eng-badge offer">${escapeHtml(fBadge)}</span>` : ''}
+ </span>
+ <span class="eng-opt-sub">${escapeHtml(e.tagline)}</span>
+ </span>${
+ e.id === active ? '<svg class="ph eng-tick" aria-hidden="true"><use href="#ph-check-bold"/></svg>' : ''}
+ </button>`;
+ }
const st = engineStatus(e);
const offer = !e.builtin && !st.announced && st.capable && !st.available;
const modeOk = engineServesMode(e, surfaceMode);
@@ -1101,7 +1385,15 @@ function renderEngineSwitch() {
menu.querySelectorAll('.eng-opt').forEach(b => {
b.onclick = () => {
closeEngineMenu();
+ if (b.dataset.engine === 'h3flex') { h3FlexPickerClick(); return; }
+ // Plain H3 from the picker means H3's own Speed, not Flex.
+ if (b.dataset.engine === 'h3' && h3SpeedPref() === 'flex'
+ && typeof setH3Speed === 'function') {
+ try { localStorage.removeItem('phos_h3flex_wanted'); } catch (e) {}
+ setH3Speed('fast');
+ }
engineSegClick(b.dataset.engine);
+ renderEngineSwitch();
};
});
@@ -2128,7 +2420,7 @@ Object.assign(globalThis, {
setH3Upscale, setH3FaceFixAfter, setH3Orientation, setH3Steps, h3TurboPillSub,
h3V13State, h3V13On,
renderH3Turbo, setH3Turbo, syncModeStripToEngine, renderEngineSwitch,
- setH3Speed, h3SpeedOfParams, h3EstimateLine, setH3TriStep, h3TriStepOn, h3TriStepState,
+ setH3Speed, h3SpeedOfParams, h3FlexOn, h3FlexState, h3EstimateLine, setH3TriStep, h3TriStepOn, h3TriStepState,
h3JobSpeedLabel, h3JobShapeLabel, ltxCellEtaBasis, h3CellEtaBasis,
// Published for the Shot setup summary (characters.js): a closed section has
// to price the shape it is hiding, and it must do it with the SAME numbers
diff --git a/webapp/js/queue.js b/webapp/js/queue.js
index 1786cbd..8353a79 100644
--- a/webapp/js/queue.js
+++ b/webapp/js/queue.js
@@ -163,7 +163,7 @@ function h3FinishFieldsFromSidecar(p, tierKey) {
// The Speed switch value the clip was made with (Fast = 3-step, or the
// retired Turbo; Best = the shape's full sampler). setH3Speed re-checks
// availability: a Fast clip on an install without the adapter lands on Best.
- h3_speed: (p.h3_tristep || p.h3_turbo) ? 'fast' : 'best',
+ h3_speed: (p.h3_tristep || p.h3_turbo) ? 'fast' : (p.h3_flex ? 'flex' : 'best'),
// The shot list carries over, and it is safe to: Finish means SAME LENGTH,
// higher quality, so the window count is identical by construction and
// entry i still means window i. Dropping it would silently finish a
@@ -955,13 +955,18 @@ function updateH3Availability(s) {
|| (((next.v13 || {}).available) !== ((H3.v13 || {}).available))
|| (((next.v13 || {}).supported) !== ((H3.v13 || {}).supported))
|| (((next.v13 || {}).download || {}).status !== ((H3.v13 || {}).download || {}).status)
+ // And for Pika H3 Flex (the third Speed choice).
+ || (((next.flex || {}).available) !== ((H3.flex || {}).available))
+ || (((next.flex || {}).supported) !== ((H3.flex || {}).supported))
+ || (((next.flex || {}).download || {}).status !== ((H3.flex || {}).download || {}).status)
|| ((next.tiers || []).length !== (H3.tiers || []).length);
// BOTH bindings, and they must stay the same object: the H3-specific code
// reads `H3` on nearly every line, the registry reads the probe map. A
// divergence here is a switcher showing "not installed" over a working
// engine (or worse, the reverse).
const _triDl = !!((next.tristep || {}).installing || (H3.tristep || {}).installing
- || (next.v13 || {}).installing || (H3.v13 || {}).installing);
+ || (next.v13 || {}).installing || (H3.v13 || {}).installing
+ || (next.flex || {}).installing || (H3.flex || {}).installing);
H3 = next;
window._ENGINE_PROBES.h3 = next;
// A running 3-step download prints its progress on the pill.
@@ -3890,7 +3895,8 @@ async function poll() {
// very first tick).
const isH3 = cur.engine === 'h3';
const h3Speed = isH3
- ? ((prog && prog.h3_speed) ? (prog.h3_speed === 'fast' ? 'Fast' : 'Best')
+ ? ((prog && prog.h3_speed) ? (prog.h3_speed === 'fast' ? 'Fast'
+ : prog.h3_speed === 'flex' ? 'Pika H3 Flex' : 'Best')
: (typeof h3JobSpeedLabel === 'function' ? h3JobSpeedLabel(cur) : ''))
: '';
const h3Shape = isH3 && typeof h3JobShapeLabel === 'function' ? h3JobShapeLabel(cur) : '';
diff --git a/webapp/style/panel.css b/webapp/style/panel.css
index c688ab6..eff634f 100644
--- a/webapp/style/panel.css
+++ b/webapp/style/panel.css
@@ -10582,6 +10582,14 @@
/* Inert = real but unreachable right now; still listed, visibly muted. */
.eng-opt.inert { opacity: .58; }
.eng-opt.needs-install .eng-badge.offer { color: var(--eng-accent, currentColor); }
+ /* H3 Flex (4.19.15) is a preview: a quiet tag beside its name, in the menu
+ and on the trigger, never louder than the engine's own offer badge. */
+ .eng-badge.eng-preview, body > header .eng-badge.eng-preview {
+ text-transform: lowercase; letter-spacing: .02em; font-weight: 500;
+ color: var(--eng-accent, var(--muted)); background: transparent;
+ border: 1px dashed var(--eng-soft, var(--ph-border-soft)); margin-left: 6px;
+ font-size: 11px; line-height: 1.2; padding: 1px 5px; border-radius: 5px;
+ }
body > header .engine-switch {
flex-shrink: 0;