Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio video: streamed mp4 byte-identical to the stock export on every render (cap libx264 at AVX2 on AVX-512 hosts) (#16030)

Daniel Han5a651b19f91d
diff --git a/studio/backend/core/inference/video_encode.py b/studio/backend/core/inference/video_encode.py
index 5ada88bff8f..3617a73be1e 100644
--- a/studio/backend/core/inference/video_encode.py
+++ b/studio/backend/core/inference/video_encode.py
@@ -5,16 +5,50 @@
from __future__ import annotations
+import functools
import os
+import platform
from typing import Any
FRAME_THREADS_ENV = "UNSLOTH_STUDIO_VIDEO_FRAME_THREADS"
+# Kill switch: "0" lets libx264 use its AVX-512 kernels again (output then depends on uninitialised heap memory).
+X264_ASM_CAP_ENV = "UNSLOTH_STUDIO_VIDEO_X264_ASM_CAP"
def frame_threads_enabled() -> bool:
return os.environ.get(FRAME_THREADS_ENV, "").strip().lower() not in ("0", "false", "no", "off")
[email protected]_cache(maxsize = 1)
+def _cpu_runs_x264_avx512() -> bool:
+ if platform.machine().lower() not in ("x86_64", "amd64", "x64"):
+ return False
+ try:
+ import numpy as np
+ core = getattr(np, "_core", None) or getattr(np, "core")
+ features = core._multiarray_umath.__cpu_features__
+ except Exception: # noqa: BLE001 - unknown CPU: keep libx264's own dispatch
+ return False
+ return all(features.get(name) for name in ("AVX512_SKX", "AVX2", "FMA3"))
+
+
+def x264_options() -> dict:
+ """libx264 options for both encode paths: its AVX-512 kernels (core 165, PyAV) read uninitialised heap memory, so
+ later encodes in a process are not reproducible; capping at AVX2 makes output depend only on the frames."""
+ if os.environ.get(X264_ASM_CAP_ENV, "").strip().lower() in ("0", "false", "no", "off"):
+ return {}
+ return {"x264-params": "asm=AVX2"} if _cpu_runs_x264_avx512() else {}
+
+
+def add_x264_stream(container: Any, fps: int, width: int, height: int) -> Any:
+ stream = container.add_stream("libx264", rate = int(fps), options = x264_options() or None)
+ stream.width = int(width)
+ stream.height = int(height)
+ stream.pix_fmt = "yuv420p"
+ stream.codec_context.thread_type = "FRAME"
+ return stream
+
+
def encode_x264(
video: Any,
fps: int,
@@ -39,11 +73,7 @@ def encode_x264(
return False
try:
with av.open(path, mode = "w", format = "mp4") as container:
- stream = container.add_stream("libx264", rate = int(fps))
- stream.width = int(frames.shape[2])
- stream.height = int(frames.shape[1])
- stream.pix_fmt = "yuv420p"
- stream.codec_context.thread_type = "FRAME"
+ stream = add_x264_stream(container, fps, frames.shape[2], frames.shape[1])
audio_stream = (
_prepare_audio_stream(container, audio_sample_rate) if audio is not None else None
)
diff --git a/studio/backend/core/inference/video_stream_encode.py b/studio/backend/core/inference/video_stream_encode.py
index 8d2a9404c89..c14babe86c9 100644
--- a/studio/backend/core/inference/video_stream_encode.py
+++ b/studio/backend/core/inference/video_stream_encode.py
@@ -270,11 +270,9 @@ class StreamEncode:
frames = host.numpy()
if container is None:
container = av.open(self.path, mode = "w", format = "mp4")
- stream = container.add_stream("libx264", rate = self.fps)
- stream.width = int(frames.shape[2])
- stream.height = int(frames.shape[1])
- stream.pix_fmt = "yuv420p"
- stream.codec_context.thread_type = "FRAME"
+ from .video_encode import add_x264_stream
+
+ stream = add_x264_stream(container, self.fps, frames.shape[2], frames.shape[1])
if self.audio_sample_rate is not None:
from diffusers.utils.export_utils import _prepare_audio_stream
self._audio_stream = _prepare_audio_stream(
diff --git a/studio/backend/tests/test_video_stream_encode_identity.py b/studio/backend/tests/test_video_stream_encode_identity.py
new file mode 100644
index 00000000000..a71cedae23c
--- /dev/null
+++ b/studio/backend/tests/test_video_stream_encode_identity.py
@@ -0,0 +1,120 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Streamed mp4 == stock export on every render in a process (libx264 AVX-512 heap reads); 208 px wide hits it."""
+
+from __future__ import annotations
+
+import threading
+
+import numpy as np
+import pytest
+
+torch = pytest.importorskip("torch")
+av = pytest.importorskip("av")
+pytest.importorskip("diffusers.utils.export_utils")
+
+from core.inference import video_encode as ve # noqa: E402
+from core.inference import video_stream_encode as vse # noqa: E402
+
+_H, _W, _N, _FPS, _RATE = 128, 208, 41, 24, 24000
+# seeds per render: the repeats must give the bytes of their first render
+_RENDERS = (0, 1, 2, 0, 1, 2)
+
+
+def _clip(seed: int):
+ g = np.random.default_rng(seed)
+ base = g.integers(0, 256, (_H // 8, _W // 8, 3), dtype = np.uint8).repeat(8, 0).repeat(8, 1)
+ return torch.from_numpy(np.stack([np.roll(base, 5 * i, axis = 1) for i in range(_N)]).copy())
+
+
+def _audio(seed: int):
+ g = torch.Generator().manual_seed(seed)
+ return (torch.rand(2, _RATE * _N // _FPS, generator = g) * 2 - 1) * 0.3
+
+
+class _Vae:
+ config = type("C", (), {"patch_size": None})()
+
+
+def _streamed(frames, audio):
+ rate = _RATE if audio is not None else None
+ session = vse.StreamEncode(_Vae(), None, _FPS, audio_sample_rate = rate)
+ session._decoded = True
+ pixels = frames.permute(0, 3, 1, 2).float() / 255
+ for start, stop in [(0, 1)] + [(i, i + 4) for i in range(1, _N, 4)]:
+ session._push_uint8(pixels[start:stop])
+ if audio is None:
+ return session.take(frames, _FPS)
+ return session.take(frames, _FPS, audio, _RATE)
+
+
+def _stock(frames, audio, path):
+ assert ve.encode_x264(frames, _FPS, str(path), audio, _RATE if audio is not None else None)
+ return path.read_bytes()
+
+
[email protected](autouse = True)
+def _defaults(monkeypatch):
+ for env in (ve.FRAME_THREADS_ENV, vse.STREAM_ENCODE_ENV):
+ monkeypatch.delenv(env, raising = False)
+
+
[email protected]("with_audio", [False, True])
+def test_streamed_mp4_is_the_stock_mp4_on_every_render(tmp_path, with_audio):
+ first: dict = {}
+ for render, seed in enumerate(_RENDERS):
+ frames = _clip(seed)
+ audio = _audio(seed) if with_audio else None
+ streamed = _streamed(frames, audio)
+ assert streamed is not None, vse.STATS["last"]
+ stock = _stock(frames, audio, tmp_path / f"stock_{render}.mp4")
+ assert (
+ streamed == stock
+ ), f"render {render} (seed {seed}): streamed mp4 is not the stock mp4"
+ assert (
+ first.setdefault(seed, stock) == stock
+ ), f"render {render}: seed {seed} encoded differently"
+
+
+def test_stock_export_does_not_depend_on_the_thread_or_history(tmp_path):
+ frames = _clip(0)
+ want = _stock(frames, None, tmp_path / "first.mp4")
+ for i in range(4):
+ _stock(_clip(i + 1), None, tmp_path / "other.mp4") # leave a different heap behind
+ got: list = []
+ worker = threading.Thread(
+ target = lambda: got.append(_stock(frames, None, tmp_path / "t.mp4"))
+ )
+ worker.start()
+ worker.join()
+ assert got == [want], f"pass {i}: the clip encoded on another thread differs"
+ assert _stock(frames, None, tmp_path / "again.mp4") == want, f"pass {i}: re-encode differs"
+
+
+def test_asm_cap_only_where_avx512_would_run(monkeypatch):
+ monkeypatch.delenv(ve.X264_ASM_CAP_ENV, raising = False)
+ monkeypatch.setattr(ve, "_cpu_runs_x264_avx512", lambda: True)
+ assert ve.x264_options() == {"x264-params": "asm=AVX2"}
+ for value in ("0", "false", "off"):
+ monkeypatch.setenv(ve.X264_ASM_CAP_ENV, value)
+ assert ve.x264_options() == {}
+ monkeypatch.delenv(ve.X264_ASM_CAP_ENV)
+ monkeypatch.setattr(ve, "_cpu_runs_x264_avx512", lambda: False)
+ assert ve.x264_options() == {}
+
+
+def test_both_paths_open_the_same_stream(monkeypatch, tmp_path):
+ opened: list = []
+ real = ve.add_x264_stream
+
+ def spy(container, fps, width, height):
+ stream = real(container, fps, width, height)
+ opened.append((int(fps), int(width), int(height), dict(stream.codec_context.options or {})))
+ return stream
+
+ monkeypatch.setattr(ve, "add_x264_stream", spy)
+ frames = _clip(3)
+ assert _streamed(frames, None) is not None
+ _stock(frames, None, tmp_path / "s.mp4")
+ assert len(opened) == 2 and opened[0] == opened[1]