Spaces:
Running on Zero
feat: real weights on MPS/CPU go to the local runner, chosen by the one device resolver; the tiny snapshot keeps the resident StageRunner
Browse filesOn a resolved mps or cpu device with no LTX25_MODEL_SNAPSHOT_DIR override,
`pipelines.get_pipeline` returns `local_runtime.build_local_runner(...)` with:
- the workflow kind and the resolved device;
- the device's dtype (bf16 on MPS; fp32 by default on the CPU);
- the pinned snapshot directory;
- LTX25_TRANSFORMER_GGUF, an optional .gguf file checked at startup;
- LTX25_RESIDENCY, staged or resident (staged by default on macOS, resident elsewhere).
A snapshot override keeps the resident StageRunner the tiny tier uses, and CUDA
is untouched. An explicit device="mps" is checked against the MPS self-test
before the local runner is built, just as the resolved path is. The startup
report gains a runner line: StageRunner on CUDA or for an override; otherwise
the local runner, its residency, and whether the transformer comes from the
GGUF file or from the snapshot's safetensors.
pipelines imports local_runtime at module scope, which is safe because
local_runtime reads pipelines' attributes only at call time. So `import app`
loads local_runtime and memory, and both are registered as startup-only in the
reachability spec, as is device in the architecture and plan lists. That turns
test_no_package_module_is_reached_by_nothing green. A spec drives generate()
through its default factory on a resolved cpu device with a fake
build_local_runner and pins every argument of the call; others pin the MPS
arguments, the override path and the CUDA path.
Files changed (8)
17 unmodified lines1819202122238 unmodified lines323334353637383917 unmodified lines57585960616232 unmodified lines959697989910096 unmodified lines19719819920020120227 unmodified lines23023123223323423546 unmodified lines28228328428517 unmodified linesfrom __future__ import annotationsimport osfrom dataclasses import dataclassfrom . import model_files8 unmodified lines"ENV_LORA_MAX_GB","ENV_MODEL_SNAPSHOT_DIR","ENV_MPS_SELF_TEST","ENV_QUANTIZATION","MPS_SELF_TEST_CHOICES","QUANTIZATION_CHOICES","ENV_OUTPUT_DIR","ENV_OUTPUT_RETENTION_GB",17 unmodified linesENV_CPU_DTYPE = "LTX25_CPU_DTYPE"ENV_MODEL_SNAPSHOT_DIR = "LTX25_MODEL_SNAPSHOT_DIR"ENV_MPS_SELF_TEST = "LTX25_MPS_SELF_TEST"#: ``auto`` passes no ``size`` and the platform then allocates its default,#: ``large`` (47.375 GiB measured). ZeroGPU does NOT promote by itself: its32 unmodified linesDEFAULT_MPS_SELF_TEST = "enforce"MPS_SELF_TEST_CHOICES = ("enforce", "warn")#: The prompt enhancer (PLAN §3.5), loaded lazily by ``enhance.py`` on first use#: inside the GPU worker and then KEPT for the life of that worker -- freeing it#: per call cost a measured +30.78 s every time. A variable rather than a96 unmodified linesreturn pathdef _number(name: str, default: float, *, minimum: float, integer: bool = False):raw = os.environ.get(name)if raw is None or raw == "":27 unmodified linescpu_dtype: str = DEFAULT_CPU_DTYPEmodel_snapshot_dir: str | None = Nonemps_self_test: str = DEFAULT_MPS_SELF_TEST@propertydef lora_max_bytes(self) -> int:46 unmodified linescpu_dtype=_choice(ENV_CPU_DTYPE, DEFAULT_CPU_DTYPE, CPU_DTYPE_CHOICES),model_snapshot_dir=_snapshot_dir(ENV_MODEL_SNAPSHOT_DIR),mps_self_test=_choice(ENV_MPS_SELF_TEST, DEFAULT_MPS_SELF_TEST, MPS_SELF_TEST_CHOICES),)17 unmodified lines181920212223248 unmodified lines333435363738394041424317 unmodified lines616263646566676832 unmodified lines10110210310410510610710810911011111296 unmodified lines20921021121221321421521621721821922022122222322422527 unmodified lines25325425525625725825926046 unmodified lines30730830931031131217 unmodified linesfrom __future__ import annotationsimport osimport sysfrom dataclasses import dataclassfrom . import model_files8 unmodified lines"ENV_LORA_MAX_GB","ENV_MODEL_SNAPSHOT_DIR","ENV_MPS_SELF_TEST","ENV_RESIDENCY","ENV_TRANSFORMER_GGUF","ENV_QUANTIZATION","MPS_SELF_TEST_CHOICES","RESIDENCY_CHOICES","QUANTIZATION_CHOICES","ENV_OUTPUT_DIR","ENV_OUTPUT_RETENTION_GB",17 unmodified linesENV_CPU_DTYPE = "LTX25_CPU_DTYPE"ENV_MODEL_SNAPSHOT_DIR = "LTX25_MODEL_SNAPSHOT_DIR"ENV_MPS_SELF_TEST = "LTX25_MPS_SELF_TEST"ENV_TRANSFORMER_GGUF = "LTX25_TRANSFORMER_GGUF"ENV_RESIDENCY = "LTX25_RESIDENCY"#: ``auto`` passes no ``size`` and the platform then allocates its default,#: ``large`` (47.375 GiB measured). ZeroGPU does NOT promote by itself: its32 unmodified linesDEFAULT_MPS_SELF_TEST = "enforce"MPS_SELF_TEST_CHOICES = ("enforce", "warn")#: How the local (mps/cpu) runner holds real weights: ``staged`` never keeps the#: text encoder and the transformer resident together; ``resident`` keeps both.#: Staged by default on macOS, where memory is shared with the GPU.DEFAULT_RESIDENCY = "staged" if sys.platform == "darwin" else "resident"RESIDENCY_CHOICES = ("staged", "resident")#: The prompt enhancer (PLAN §3.5), loaded lazily by ``enhance.py`` on first use#: inside the GPU worker and then KEPT for the life of that worker -- freeing it#: per call cost a measured +30.78 s every time. A variable rather than a96 unmodified linesreturn pathdef _gguf_file(name: str) -> str | None:"""A local ``.gguf`` transformer file for the local runner, or None."""raw = (os.environ.get(name) or "").strip()if not raw:return Nonepath = os.path.realpath(os.path.expanduser(raw))if not (os.path.isfile(path) and path.endswith(".gguf")):raise ConfigError(variable=name, value=raw, legal=("an existing .gguf file",))return pathdef _number(name: str, default: float, *, minimum: float, integer: bool = False):raw = os.environ.get(name)if raw is None or raw == "":27 unmodified linescpu_dtype: str = DEFAULT_CPU_DTYPEmodel_snapshot_dir: str | None = Nonemps_self_test: str = DEFAULT_MPS_SELF_TESTtransformer_gguf: str | None = Noneresidency: str = DEFAULT_RESIDENCY@propertydef lora_max_bytes(self) -> int:46 unmodified linescpu_dtype=_choice(ENV_CPU_DTYPE, DEFAULT_CPU_DTYPE, CPU_DTYPE_CHOICES),model_snapshot_dir=_snapshot_dir(ENV_MODEL_SNAPSHOT_DIR),mps_self_test=_choice(ENV_MPS_SELF_TEST, DEFAULT_MPS_SELF_TEST, MPS_SELF_TEST_CHOICES),transformer_gguf=_gguf_file(ENV_TRANSFORMER_GGUF),residency=_choice(ENV_RESIDENCY, DEFAULT_RESIDENCY, RESIDENCY_CHOICES),)
44 unmodified lines45464748495051914 unmodified lines966967968969970971972973974975976977978979551 unmodified lines15311532153315341535153679 unmodified lines16161617161816191620162144 unmodified linesfrom dataclasses import dataclassfrom types import MappingProxyTypefrom . import model_filesfrom .constraints import (DEFAULT_FRAME_RATE,DEFAULT_SPATIAL_COMPRESSION_RATIO,914 unmodified linesWith no ``device`` the process's resolved device is used, and a machine withno generation device (or an MPS torch that fails its self-test) is refusedbefore anything is loaded -- never a silent full load on the CPU."""if pipeline in _CACHE:return _CACHE[pipeline]if device is None:from . import device as device_moduledevice = device_module.current().require_generation()base = _base_pipeline(dtype=dtype, device=device)if pipeline == BASE_KIND:551 unmodified linesreturn {"bfloat16": "bf16", "float32": "fp32", "float16": "fp16"}.get(name, name)def precision_summary(resolution) -> str:"""What each component is loaded as, from the resolved configuration."""if resolution is None:79 unmodified linesf" config : {runtime_config.describe()}",f" device : {resolution.describe() if resolution is not None else 'unknown'}",f" precision : {precision_summary(resolution)}",f" weights cached : {found}/{expected_files} {unit}"+ (f" MISSING {len(missing_files)}" if missing_files else ""),f" snapshot on disk: {snapshot} ({source}; download set "44 unmodified lines45464748495051914 unmodified lines9669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000551 unmodified lines155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158879 unmodified lines166816691670167116721673167444 unmodified linesfrom dataclasses import dataclassfrom types import MappingProxyTypefrom . import local_runtime, model_filesfrom .constraints import (DEFAULT_FRAME_RATE,DEFAULT_SPATIAL_COMPRESSION_RATIO,914 unmodified linesWith no ``device`` the process's resolved device is used, and a machine withno generation device (or an MPS torch that fails its self-test) is refusedbefore anything is loaded -- never a silent full load on the CPU.On mps/cpu with real weights the local runner (``local_runtime``) isreturned; a ``LTX25_MODEL_SNAPSHOT_DIR`` override keeps the resident:class:`StageRunner`. CUDA is unchanged."""if pipeline in _CACHE:return _CACHE[pipeline]from . import device as device_moduleif device is None:device = device_module.current().require_generation()elif device == "mps":device_module.require_mps_numerics()if device in ("mps", "cpu") and _uses_local_runner():from .config import load_configfrom .preflight import snapshot_dirruntime_config = load_config()return local_runtime.build_local_runner(kind=pipeline,device=device,dtype=dtype or device_module.weight_dtype_for(device, runtime_config),snapshot_dir=snapshot_dir(),transformer_gguf=runtime_config.transformer_gguf,residency=runtime_config.residency,log=_log().info,)base = _base_pipeline(dtype=dtype, device=device)if pipeline == BASE_KIND:551 unmodified linesreturn {"bfloat16": "bf16", "float32": "fp32", "float16": "fp16"}.get(name, name)def _uses_local_runner() -> bool:"""Real weights on a local device go to the local runner; a snapshot override does not."""from .preflight import snapshot_overridereturn snapshot_override() is Nonedef runner_summary(resolution, runtime_config) -> str:"""Which runner generation will use here, and where the transformer comes from."""if resolution is None:return "unknown (no device resolved)"if resolution.device is None:return "none (UI only)"if resolution.device == "cuda":return "StageRunner, the pipeline built at startup and resident on CUDA"if not _uses_local_runner():return (f"StageRunner, resident on {resolution.device}; every component from "f"{runtime_config.model_snapshot_dir} (LTX25_MODEL_SNAPSHOT_DIR)")source = (f"the GGUF file {runtime_config.transformer_gguf} (LTX25_TRANSFORMER_GGUF)"if runtime_config.transformer_ggufelse "the pinned snapshot's safetensors")return (f"local runner, {runtime_config.residency} residency (LTX25_RESIDENCY), on "f"{resolution.device}; transformer from {source}")def precision_summary(resolution) -> str:"""What each component is loaded as, from the resolved configuration."""if resolution is None:79 unmodified linesf" config : {runtime_config.describe()}",f" device : {resolution.describe() if resolution is not None else 'unknown'}",f" precision : {precision_summary(resolution)}",f" runner : {runner_summary(resolution, runtime_config)}",f" weights cached : {found}/{expected_files} {unit}"+ (f" MISSING {len(missing_files)}" if missing_files else ""),f" snapshot on disk: {snapshot} ({source}; download set "
147 unmodified lines148149150151152153147 unmodified linesEXPECTED_MODULES = ("config.py","device.py","model_files.py","errors.py","constraints.py",147 unmodified lines148149150151152153154155147 unmodified linesEXPECTED_MODULES = ("config.py","device.py","local_runtime.py","memory.py","model_files.py","errors.py","constraints.py",
126 unmodified lines127128129130131132126 unmodified linesconfig.load_config()# --------------------------------------------------------------------------# the model-source override: optional, and validated loudly# --------------------------------------------------------------------------126 unmodified lines127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162126 unmodified linesconfig.load_config()def test_residency_defaults_to_staged_on_macos_and_resident_elsewhere(monkeypatch):import sysexpected = "staged" if sys.platform == "darwin" else "resident"assert config.load_config().residency == expectedfor value in ("staged", "resident"):monkeypatch.setenv(config.ENV_RESIDENCY, value)assert config.load_config().residency == valuemonkeypatch.setenv(config.ENV_RESIDENCY, "lazy")with pytest.raises(config.ConfigError):config.load_config()def test_a_gguf_transformer_is_optional_and_must_be_a_gguf_file(monkeypatch, tmp_path):assert config.load_config().transformer_gguf is Nonemonkeypatch.setenv(config.ENV_TRANSFORMER_GGUF, str(tmp_path / "missing.gguf"))with pytest.raises(config.ConfigError):config.load_config()other = tmp_path / "transformer.safetensors"other.write_bytes(b"")monkeypatch.setenv(config.ENV_TRANSFORMER_GGUF, str(other))with pytest.raises(config.ConfigError):config.load_config()gguf = tmp_path / "transformer-Q8_0.gguf"gguf.write_bytes(b"")monkeypatch.setenv(config.ENV_TRANSFORMER_GGUF, str(gguf))assert config.load_config().transformer_gguf == str(gguf.resolve())# --------------------------------------------------------------------------# the model-source override: optional, and validated loudly# --------------------------------------------------------------------------
179 unmodified lines1801811821831841851861871881891901911 unmodified line193194195196197198199179 unmodified linesassert "LTX25_DEVICE=mps" in message and "LTX25_DEVICE=cpu" in message, messagedef test_get_pipeline_uses_the_resolved_device(monkeypatch, no_cuda):monkeypatch.setenv(config.ENV_DEVICE, "cpu")seen = []monkeypatch.setattr(pipelines, "_base_pipeline", lambda **k: seen.append(k) or object())monkeypatch.setattr(pipelines, "derive_pipeline", lambda base, cls: base)monkeypatch.setitem(sys.modules, "diffusers", types.SimpleNamespace(LTX2Pipeline=object))pipelines.clear_cache()try:runner = pipelines.get_pipeline(pipeline="text2video")1 unmodified linepipelines.clear_cache()assert seen and seen[0]["device"] == "cpu", seenassert runner.device == "cpu"@pytest.fixture179 unmodified lines1801811821831841851861871881891901911921931941951961971981992002012022032041 unmodified line206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316179 unmodified linesassert "LTX25_DEVICE=mps" in message and "LTX25_DEVICE=cpu" in message, messagedef _override_snapshot(monkeypatch, tmp_path):(tmp_path / "model_index.json").write_text("{}")monkeypatch.setenv(config.ENV_MODEL_SNAPSHOT_DIR, str(tmp_path))def test_a_snapshot_override_keeps_the_resident_stage_runner(monkeypatch, no_cuda, tmp_path):from ltx25_studio import local_runtimemonkeypatch.setenv(config.ENV_DEVICE, "cpu")_override_snapshot(monkeypatch, tmp_path)seen = []monkeypatch.setattr(pipelines, "_base_pipeline", lambda **k: seen.append(k) or object())monkeypatch.setattr(pipelines, "derive_pipeline", lambda base, cls: base)monkeypatch.setitem(sys.modules, "diffusers", types.SimpleNamespace(LTX2Pipeline=object))monkeypatch.setattr(local_runtime,"build_local_runner",lambda **k: pytest.fail("dispatched to the local runner"),)pipelines.clear_cache()try:runner = pipelines.get_pipeline(pipeline="text2video")1 unmodified linepipelines.clear_cache()assert seen and seen[0]["device"] == "cpu", seenassert isinstance(runner, pipelines.StageRunner) and runner.device == "cpu"@pytest.fixturedef fake_local_runner(monkeypatch):"""``build_local_runner`` replaced by a recorder: no real weights anywhere."""from test_exports_contract import FakePipefrom ltx25_studio import local_runtimecalls = []def build(**kwargs):calls.append(kwargs)return FakePipe()monkeypatch.setattr(local_runtime, "build_local_runner", build)monkeypatch.setattr(pipelines, "_base_pipeline", lambda **k: pytest.fail("StageRunner built"))monkeypatch.delenv(config.ENV_MODEL_SNAPSHOT_DIR, raising=False)monkeypatch.setattr(generate_module, "_GPU_DISPATCH", None)pipelines.clear_cache()return callsdef test_generate_on_a_local_device_with_real_weights_uses_the_local_runner(monkeypatch, no_cuda, tmp_path, fake_local_runner):"""The seam the UI uses: generate() -> default factory -> get_pipeline -> dispatch."""from test_exports_contract import one_muxed_file_encoderfrom ltx25_studio import preflightgguf = tmp_path / "transformer-Q8_0.gguf"gguf.write_bytes(b"")monkeypatch.setenv(config.ENV_DEVICE, "cpu")monkeypatch.setenv(config.ENV_TRANSFORMER_GGUF, str(gguf))monkeypatch.setenv(config.ENV_RESIDENCY, "staged")result = generate_module.generate(mode="image_to_video",seed=7,width=64,height=64,num_frames=9,encoder=one_muxed_file_encoder,output_root=tmp_path / "out",retention_bytes=10**9,**inputs_for("image_to_video"),)assert result.output_path.is_file()assert len(fake_local_runner) == 1, fake_local_runnercall = dict(fake_local_runner[0])assert callable(call.pop("log"))assert call == {"kind": "condition","device": "cpu","dtype": "float32","snapshot_dir": preflight.snapshot_dir(),"transformer_gguf": str(gguf.resolve()),"residency": "staged",}def test_mps_dispatch_uses_bf16_and_the_snapshot_transformer(monkeypatch, no_cuda, fake_local_runner):monkeypatch.setattr(device, "host_has_mps", lambda: True)monkeypatch.setattr(device, "_MPS_SELF_TEST", _self_test())monkeypatch.setenv(config.ENV_DEVICE, "mps")monkeypatch.setenv(config.ENV_RESIDENCY, "resident")pipelines.get_pipeline(pipeline="text2video")call = fake_local_runner[0]assert (call["kind"], call["device"], call["dtype"]) == ("text2video", "mps", "bfloat16")assert call["transformer_gguf"] is None and call["residency"] == "resident"def test_an_explicit_mps_device_still_checks_numerics_before_the_local_runner(monkeypatch, fake_local_runner):monkeypatch.setattr(device, "_MPS_SELF_TEST", _self_test(sdpa=False))with pytest.raises(device.MpsNumericsError):pipelines.get_pipeline(pipeline="text2video", device="mps")assert not fake_local_runnerdef test_cuda_never_dispatches_to_the_local_runner(monkeypatch, tmp_path):from test_stage_graph_contract import install_fake_stackfrom ltx25_studio import local_runtimeinstall_fake_stack(monkeypatch, tmp_path)monkeypatch.setattr(local_runtime, "build_local_runner", lambda **k: pytest.fail("CUDA reached local_runtime"))pipelines.clear_cache()try:runner = pipelines.get_pipeline(pipeline="condition", device="cuda")finally:pipelines.clear_cache()assert isinstance(runner, pipelines.StageRunner) and runner.device == "cuda"@pytest.fixture
58 unmodified lines596061626364516 unmodified lines58158258358458558658 unmodified lines"ltx25_studio.errors","ltx25_studio.preflight","ltx25_studio.zerogpu","ltx25_studio.constraints","ltx25_studio.pipelines","ltx25_studio.conditioning",516 unmodified lines"bypassed offline by the injected pipeline_factory; exercised for real on the Space"),"ltx25_studio.preflight": "startup resource and version checks, by definition",}58 unmodified lines596061626364656667516 unmodified lines58458558658758858959059159259359458 unmodified lines"ltx25_studio.errors","ltx25_studio.preflight","ltx25_studio.zerogpu","ltx25_studio.device","ltx25_studio.local_runtime","ltx25_studio.memory","ltx25_studio.constraints","ltx25_studio.pipelines","ltx25_studio.conditioning",516 unmodified lines"bypassed offline by the injected pipeline_factory; exercised for real on the Space"),"ltx25_studio.preflight": "startup resource and version checks, by definition","ltx25_studio.local_runtime": ("imported by pipelines at module scope; runs only for a local mps/cpu generation with ""real weights, which the offline probe cannot make"),"ltx25_studio.memory": "the local runner's memory preflight; same reach as local_runtime",}
947 unmodified lines948949950951952953954947 unmodified linessnapshot.mkdir(parents=True)recorders = install_fake_stack(monkeypatch, snapshot)pipelines.get_pipeline(device="cpu")for name in ("LTX2LatentUpsamplerModel", "LTX2VideoDiffusionDecoderModel"):assert not recorders[name].calls, (947 unmodified lines948949950951952953954947 unmodified linessnapshot.mkdir(parents=True)recorders = install_fake_stack(monkeypatch, snapshot)pipelines.get_pipeline(device="cuda")for name in ("LTX2LatentUpsamplerModel", "LTX2VideoDiffusionDecoderModel"):assert not recorders[name].calls, (
200 unmodified lines201202203200 unmodified lineslines = [r.getMessage() for r in caplog.records if "spaces.GPU" in r.getMessage()]assert lines and "size=xlarge" in lines[0] and "180 s" in lines[0], lines200 unmodified lines201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253200 unmodified lineslines = [r.getMessage() for r in caplog.records if "spaces.GPU" in r.getMessage()]assert lines and "size=xlarge" in lines[0] and "180 s" in lines[0], lines# --------------------------------------------------------------------------# which runner a local device will use, and where the transformer comes from# --------------------------------------------------------------------------def _runner_line(monkeypatch, device_name):monkeypatch.setattr(zerogpu, "host_has_cuda", lambda: device_name == "cuda")monkeypatch.setattr(device, "host_has_mps", lambda: True)monkeypatch.setenv(config.ENV_DEVICE, device_name)runtime_config = config.load_config()report = pipelines.startup_report(runtime_config, missing_files=(), resolution=device.resolve(None, runtime_config))return next(line for line in report.splitlines() if line.strip().startswith("runner"))def test_a_local_device_with_real_weights_reports_the_local_runner_and_its_gguf(monkeypatch, tmp_path):gguf = tmp_path / "transformer-Q8_0.gguf"gguf.write_bytes(b"")monkeypatch.setenv(config.ENV_TRANSFORMER_GGUF, str(gguf))monkeypatch.setenv(config.ENV_RESIDENCY, "staged")line = _runner_line(monkeypatch, "mps")assert "local runner" in line and "staged" in line and str(gguf.resolve()) in line, linedef test_a_local_device_without_gguf_reads_the_transformer_from_the_snapshot(monkeypatch):line = _runner_line(monkeypatch, "cpu")assert "local runner" in line and "snapshot" in line, linedef test_a_snapshot_override_reports_the_resident_stage_runner(monkeypatch, tmp_path):(tmp_path / "model_index.json").write_text("{}")monkeypatch.setenv(config.ENV_MODEL_SNAPSHOT_DIR, str(tmp_path))line = _runner_line(monkeypatch, "cpu")assert "StageRunner" in line and str(tmp_path.resolve()) in line, linedef test_cuda_reports_the_startup_built_stage_runner(monkeypatch):line = _runner_line(monkeypatch, "cuda")assert "StageRunner" in line and "CUDA" in line, line