Spaces:
Running on Zero
fix: the enhancer's nine-minute wall — the rewrite moves onto the GPU it was priced for
Browse filesPrompt enhancement shipped in the web process, on the CPU, to stay out of
ZeroGPU's packing window. The disk half of that argument was researched,
checked against the packer's source, and is correct. The latency half was
never measured. On the live Space, text_to_video at 256x256x9:
enhance OFF 15.38 s
enhance ON, cold 654.15 s (+638.8)
enhance ON, warm 553.45 s (+538.1)
The cold/warm split isolates it: the 2.46 GB fetch is 88 s and the weights
load in under a second, so the download is not the cost. ~538 s is the CPU
decode of 600 greedy tokens, about 0.9 s/token. The "1-2 s" that justified
the CPU placement was a GPU number applied to a CPU placement — 600 tokens
in 2 s is 300 tok/s, which no CPU does on a 5B-parameter model.
"Where does it run" has two axes, disk and latency. One was optimised and
the other was never measured. That is the transferable part and it is
written into PLAN §3.5, UI_DESIGN and enhance.py rather than into this
message alone.
The move, and why the disk argument survives it intact:
* enhance_if_requested() drops BELOW the dispatch branch in generate(), so
on a Space it runs inside the @spaces.GPU worker. Packing fires once per
container at demo.launch() over cuda_aliases registered during module
scope; the forked worker has already run torch.unpatch(), so .to("cuda")
there is a real H2D copy that is never packed. pipelines.py already does
this for the stage-2 upsampler and decoder. The enhancer stays ~2.5 GB in
the HF cache, out of the snapshot and out of preload_from_hub, and gets
CUDA speed: ~1-2 s against ~85 s for a generation, under 5% overhead.
* ENHANCER_DEVICE = "cpu" becomes enhancer_device(), resolved per call. The
constant was right for the web process, where probing torch.cuda is the
blocked lazy init that hangs; inside the worker CUDA is already up.
* The position also earns two properties for free: it is past get_mode and
_validated, so "everything cheap first" now covers enhancement with no
duplicated validation to keep in step, and it is above the pipeline
factory, so a failed enhancement still costs no model load.
The prefetch, in the same commit because without it the move bills a
download:
* enhance.prefetch() pulls the weights via huggingface_hub.snapshot_download
at startup — a download only. It constructs no torch tensors, so there is
nothing in cuda_aliases for torch.pack() to capture; files on disk are not
packable state. snapshot_download rather than a per-file allow-list
because LTX25_PROMPT_ENHANCER_REPO is a real lever and any hardcoded list
would be wrong the moment someone points it at the bf16 build.
* Daemon thread, best-effort by contract: it may not block demo.launch() and
may not fail startup. A Space whose prefetch failed still starts, still
serves un-enhanced runs, and pays the download on its first enhanced run.
* A user who generates mid-prefetch is safe: huggingface_hub takes a
cross-process WeakFileLock per blob, so the worker waits for the in-flight
fetch rather than racing it.
* LTX25_PREFETCH_ENHANCER=0 declines the ~2.5 GB for a deploy that will
never enable enhancement — it lands while demo.launch() is packing, the
window ZEROGPU_DISK_CAP_GB is measured against.
Carried over, and now enforced rather than assumed:
* estimate_duration adds ENHANCE_DURATION_SECONDS (120) when the toggle is
set. Sized for the DEGRADED case: the prefetch is explicitly allowed to
fail, so the estimator may not assume it succeeded. A run killed at the
reservation boundary would be self-inflicted.
* _with_notes is deleted. The rewrite note now originates inside the worker
and rides home in GenerationResult.warnings like every other note; pinned
by a new fork-boundary test. PromptEnhancementError already crosses intact
via test_errors_fork_boundary's programmatic discovery.
* `enhancer` joins the dispatch payload. It did not need forwarding while
enhancement ran before the branch; dropping it now means an injected seam
silently stops being used and the worker reaches for real Gemma. Caught by
the suite, fixed, and pinned — including a test that reads the payload
keys off a live dispatch instead of retyping them.
* enhance.py joins PLAN §7.1 and the reachability lists. The unconditional
call was a convention; it is now a test that fails if anyone gates it on
the toggle.
* /on_generate signature untouched. All four §3.5 knobs untouched.
The UI gives up "costs no quota" to stop implying "costs only time": the
caption, the running message and the docs all now say a second or two of
GPU rather than a wait before the slot.
Gate green at 2518 passed / 17 skipped, from a 2495 / 17 baseline.
- README.md +18 -6
- app.py +27 -0
- docs/PLAN.md +65 -5
- docs/UI_DESIGN.md +16 -5
- ltx25_studio/config.py +47 -2
- ltx25_studio/enhance.py +247 -64
- ltx25_studio/generate.py +52 -63
- ltx25_studio/ui/fields.py +2 -2
- ltx25_studio/ui/handlers.py +3 -3
- ltx25_studio/ui/render.py +14 -10
- ltx25_studio/zerogpu.py +27 -0
- tests/test_architecture.py +1 -0
- tests/test_enhance.py +430 -40
- tests/test_module_reachability.py +26 -2
- tests/test_request_fork_boundary.py +83 -0
|
@@ -188,12 +188,24 @@ you supply a reference frame — and then generates from the rewrite. The prompt
|
|
| 188 |
sent is printed in the run report, because an enhancer that silently swaps your prompt is
|
| 189 |
worse than none.
|
| 190 |
|
| 191 |
-
**It costs
|
| 192 |
-
(2.49 GB, public, ungated), loaded on the
|
| 193 |
-
|
| 194 |
-
22B transformer.
|
| 195 |
-
|
| 196 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
|
| 198 |
There is deliberately **no seed control** for it. LTX-2.5 enhancement decodes greedily, so
|
| 199 |
`prompt_enhancement_seed` changes nothing — an advertised lever attached to nothing is a
|
|
|
|
| 188 |
sent is printed in the run report, because an enhancer that silently swaps your prompt is
|
| 189 |
worse than none.
|
| 190 |
|
| 191 |
+
**It costs a second or two of quota.** The enhancer is
|
| 192 |
+
`google/gemma-4-E2B-it-qat-mobile-transformers` (2.49 GB, public, ungated), loaded on the
|
| 193 |
+
**GPU inside the run's own reservation** and freed again in the same call, so it never
|
| 194 |
+
coexists with the 22B transformer. Point `LTX25_PROMPT_ENHANCER_REPO` at
|
| 195 |
+
`google/gemma-4-E2B-it` for the 10.28 GB bf16 build instead.
|
| 196 |
+
|
| 197 |
+
> ⚠️ **It used to cost no quota at all, and that was the problem.** The rewrite first ran on
|
| 198 |
+
> the CPU in the web process, outside the metered window, which made it genuinely free of
|
| 199 |
+
> GPU-seconds — and took **+538 s of wall-clock**, measured, for a 600-token greedy decode at
|
| 200 |
+
> ~0.9 s/token. On the GPU the same decode is ~1-2 s against ~85 s for a real generation:
|
| 201 |
+
> under 5% overhead instead of a nine-minute wait. The full accounting, including why moving
|
| 202 |
+
> it to CUDA does *not* put it back into ZeroGPU's disk budget, is in PLAN §3.5.
|
| 203 |
+
|
| 204 |
+
The weights are prefetched into the Hub cache at startup on a background thread, so the first
|
| 205 |
+
enhanced run in a container does not pay the 88 s download inside its reservation. It is
|
| 206 |
+
best-effort: if the prefetch fails the Space still starts, un-enhanced runs are unaffected,
|
| 207 |
+
and the first enhanced run is merely slow. Set `LTX25_PREFETCH_ENHANCER=0` to decline the
|
| 208 |
+
~2.5 GB of startup download on a deploy that will never turn enhancement on.
|
| 209 |
|
| 210 |
There is deliberately **no seed control** for it. LTX-2.5 enhancement decodes greedily, so
|
| 211 |
`prompt_enhancement_seed` changes nothing — an advertised lever attached to nothing is a
|
|
@@ -27,6 +27,7 @@ except ImportError: # local development, where ZeroGPU does not exist
|
|
| 27 |
|
| 28 |
spaces = _zerogpu_bootstrap.local_spaces_stub()
|
| 29 |
|
|
|
|
| 30 |
from ltx25_studio import generate as generate_module
|
| 31 |
from ltx25_studio import outputs, pipelines, preflight, zerogpu
|
| 32 |
from ltx25_studio.config import load_config
|
|
@@ -98,6 +99,32 @@ if WILL_USE_GPU:
|
|
| 98 |
pipelines.get_pipeline(pipeline="condition", device="cuda")
|
| 99 |
pipelines.get_pipeline(pipeline="text2video", device="cuda")
|
| 100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
# `size` is filtered against the installed spaces signature: the platform pins
|
| 102 |
# its own version and lags PyPI, and passing an unknown kwarg raises TypeError
|
| 103 |
# at import, which on a Space looks like a mysterious startup failure.
|
|
|
|
| 27 |
|
| 28 |
spaces = _zerogpu_bootstrap.local_spaces_stub()
|
| 29 |
|
| 30 |
+
from ltx25_studio import enhance as enhance_module
|
| 31 |
from ltx25_studio import generate as generate_module
|
| 32 |
from ltx25_studio import outputs, pipelines, preflight, zerogpu
|
| 33 |
from ltx25_studio.config import load_config
|
|
|
|
| 99 |
pipelines.get_pipeline(pipeline="condition", device="cuda")
|
| 100 |
pipelines.get_pipeline(pipeline="text2video", device="cuda")
|
| 101 |
|
| 102 |
+
# The prompt enhancer's WEIGHTS, into the HF cache, on a daemon thread.
|
| 103 |
+
#
|
| 104 |
+
# Enhancement runs inside the `@spaces.GPU` worker now (see enhance.py for the
|
| 105 |
+
# measurement that moved it there), which means the 88 s Hub fetch would be
|
| 106 |
+
# BILLED on the first enhanced call in every container -- ~176 GPU-seconds spent
|
| 107 |
+
# downloading a file. Pulling it here spends that on wall-clock nobody is
|
| 108 |
+
# waiting on instead.
|
| 109 |
+
#
|
| 110 |
+
# ⚠️ It must not be in the packing window, and it is not: `snapshot_download`
|
| 111 |
+
# writes blobs and constructs no torch tensors, so there is nothing registered
|
| 112 |
+
# in `cuda_aliases` for the `torch.pack()` at `demo.launch()` to capture. Files
|
| 113 |
+
# on disk are not packable state. This is what lets the weights be resident
|
| 114 |
+
# before the first request without the enhancer re-entering the disk budget the
|
| 115 |
+
# original web-process placement was chosen to protect.
|
| 116 |
+
#
|
| 117 |
+
# ⚠️ It must not delay readiness, and it does not: the thread is a daemon, so a
|
| 118 |
+
# fetch still in flight blocks neither `demo.launch()` below nor process exit. A
|
| 119 |
+
# failure is logged and swallowed -- the Space still starts, un-enhanced
|
| 120 |
+
# generations are untouched, and the first enhanced run merely pays the download
|
| 121 |
+
# itself. Degraded, not broken.
|
| 122 |
+
#
|
| 123 |
+
# CONFIG.prefetch_enhancer exists for the deploy that will never turn
|
| 124 |
+
# enhancement on and would rather keep the ~2.5 GB of disk; see config.py.
|
| 125 |
+
if WILL_USE_GPU and CONFIG.prefetch_enhancer:
|
| 126 |
+
enhance_module.start_prefetch(token=os.environ.get("HF_TOKEN"))
|
| 127 |
+
|
| 128 |
# `size` is filtered against the installed spaces signature: the platform pins
|
| 129 |
# its own version and lags PyPI, and passing an unknown kwarg raises TypeError
|
| 130 |
# at import, which on a Space looks like a mysterious startup failure.
|
|
@@ -545,15 +545,73 @@ are plain torch with no CUDA or kernel dependency, which is what lets it run on
|
|
| 545 |
`Gemma4ForConditionalGeneration` must be named explicitly. `LTX25_PROMPT_ENHANCER_REPO`
|
| 546 |
selects the repo; the bf16 build is one environment variable away.
|
| 547 |
|
| 548 |
-
**What ships.** `ltx25_studio/enhance.py`, called from `generate()` **
|
| 549 |
-
branch** — i.e.
|
| 550 |
-
|
| 551 |
-
freed inside one call, so it never coexists with the 22B transformer. What it costs is
|
| 552 |
-
**wall-clock**, and the UI caption says so rather than implying the feature is free. Failure
|
| 553 |
raises `PromptEnhancementError` naming the repository and the reason; it never falls through
|
| 554 |
to the original prompt while the UI implies enhancement happened, and the prompt that was
|
| 555 |
actually sent is quoted in the run report.
|
| 556 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 557 |
The settings, unchanged from what this section banked in advance and now imported from
|
| 558 |
upstream rather than restated: `prompt_max_new_tokens=600`, **greedy decoding**
|
| 559 |
(`do_sample=False, no_repeat_ngram_size=5`), `prompt_enhancement_seed` **inert under greedy
|
|
@@ -1261,6 +1319,8 @@ ltx25_studio/
|
|
| 1261 |
modes.py # §3.3 registry: 11 UI modes as data over the 4 real workflows
|
| 1262 |
generate.py # §7.4 stage graph. OWNS the never-empty invariant (§5.3) and the
|
| 1263 |
# per-run output directory
|
|
|
|
|
|
|
| 1264 |
outputs.py # mux video+audio, single-track export, 20 GB oldest-first eviction
|
| 1265 |
lora/
|
| 1266 |
inspect.py # header-only safetensors parse; metadata + convention detection
|
|
|
|
| 545 |
`Gemma4ForConditionalGeneration` must be named explicitly. `LTX25_PROMPT_ENHANCER_REPO`
|
| 546 |
selects the repo; the bf16 build is one environment variable away.
|
| 547 |
|
| 548 |
+
**What ships.** `ltx25_studio/enhance.py`, called from `generate()` **below the dispatch
|
| 549 |
+
branch** — i.e. inside the `@spaces.GPU` worker, on the GPU, within the metered window. It is
|
| 550 |
+
loaded and freed inside one call, so it never coexists with the 22B transformer. Failure
|
|
|
|
|
|
|
| 551 |
raises `PromptEnhancementError` naming the repository and the reason; it never falls through
|
| 552 |
to the original prompt while the UI implies enhancement happened, and the prompt that was
|
| 553 |
actually sent is quoted in the run report.
|
| 554 |
|
| 555 |
+
> ⚠️ **That placement is itself a correction, and the reason is the transferable part.**
|
| 556 |
+
> Enhancement first shipped **in the web process, on the CPU**, and the argument for it was
|
| 557 |
+
> the disk argument above: run it outside the module-scope import phase and never move it to
|
| 558 |
+
> CUDA, and ZeroGPU can never pack it. That argument was researched, checked against the
|
| 559 |
+
> packer's source, and is **correct** — it is restated intact below, because it survives.
|
| 560 |
+
>
|
| 561 |
+
> What it was not was complete. Measured on the live Space, `text_to_video` at 256x256x9 —
|
| 562 |
+
> the cheapest configuration that exists here:
|
| 563 |
+
>
|
| 564 |
+
> | run | wall |
|
| 565 |
+
> |---|---|
|
| 566 |
+
> | enhance OFF | 15.38 s |
|
| 567 |
+
> | enhance ON, cold | 654.15 s (+638.8) |
|
| 568 |
+
> | enhance ON, warm | 553.45 s (+538.1) |
|
| 569 |
+
>
|
| 570 |
+
> The cold/warm split isolates it. The 2.46 GB fetch takes 88 s and the weights load in under
|
| 571 |
+
> a second, so the download is **not** the cost: ~538 s is the CPU decode of 600 greedy
|
| 572 |
+
> tokens, about **0.9 s/token**. The number that justified the CPU placement was "1-2 s" — a
|
| 573 |
+
> *GPU* figure applied to a *CPU* placement. 600 tokens in 2 s is 300 tok/s, which no CPU
|
| 574 |
+
> does on a 5B-parameter model.
|
| 575 |
+
>
|
| 576 |
+
> **"Where does it run" has two axes — disk and latency — and only one of them was
|
| 577 |
+
> optimised.** The disk axis was reasoned about carefully and got the right answer. The
|
| 578 |
+
> latency axis was never measured at all, so a nine-minute wall shipped priced at two
|
| 579 |
+
> seconds. A placement decision that answers one axis and is silent on the other is half a
|
| 580 |
+
> decision, and the missing half is the one the user experiences. **This is the lesson that
|
| 581 |
+
> should outlive the feature**: when a component moves for a resource reason, state what it
|
| 582 |
+
> costs on *every* axis, and measure the ones you did not choose it for.
|
| 583 |
+
|
| 584 |
+
**✅ The disk argument survives the move, and that is why the move is affordable.** Packing
|
| 585 |
+
fires once per container at `demo.launch()`, over `cuda_aliases` registered during the
|
| 586 |
+
module-scope import phase. Inside a `@spaces.GPU` call the forked worker has already run
|
| 587 |
+
`torch.unpatch()` (`wrappers.py:147`), so a `.to("cuda")` there is a real H2D copy that is
|
| 588 |
+
**never packed** — the in-repo precedent is `pipelines.py`, which moves the stage-2 upsampler
|
| 589 |
+
and diffusion decoder to CUDA inside the worker for exactly this reason. The enhancer stays
|
| 590 |
+
~2.5 GB in the HF cache, out of the snapshot and out of `preload_from_hub`, and gets CUDA
|
| 591 |
+
speed: ~1-2 s of billed wall against ~85 s for a real generation, **under 5% overhead** where
|
| 592 |
+
the CPU placement was +3500%.
|
| 593 |
+
|
| 594 |
+
**What that costs, and what now pays for it.** Enhancement is inside the reservation, so
|
| 595 |
+
`zerogpu.estimate_duration` adds `ENHANCE_DURATION_SECONDS` when the toggle is set — an
|
| 596 |
+
enhanced run killed at the reservation boundary would be a self-inflicted wound — and the UI
|
| 597 |
+
caption gives up "costs no quota" to be honest about "no longer costs nine minutes".
|
| 598 |
+
|
| 599 |
+
**And the download is prefetched, because it would otherwise be billed.** Without it the
|
| 600 |
+
first enhanced call in each container spends the 88 s Hub fetch *inside* the metered window:
|
| 601 |
+
~176 GPU-seconds to move a file. `enhance.prefetch` pulls the weights into the HF cache at
|
| 602 |
+
startup via `huggingface_hub.snapshot_download` — a **download only**, constructing no torch
|
| 603 |
+
tensors, so there is nothing registered in `cuda_aliases` for `torch.pack()` to capture and
|
| 604 |
+
the disk argument is untouched. `snapshot_download` rather than a per-file allow-list because
|
| 605 |
+
`LTX25_PROMPT_ENHANCER_REPO` is a real lever: any filename list we hardcoded would be wrong
|
| 606 |
+
the moment an operator pointed it at the bf16 build. It runs on a **daemon thread** and is
|
| 607 |
+
**best-effort by contract** — it may never block `demo.launch()` and may never fail startup.
|
| 608 |
+
A Space whose prefetch failed still starts, still serves un-enhanced generations, and merely
|
| 609 |
+
pays the download on its first enhanced run: degraded, not broken. Which is also why the
|
| 610 |
+
reservation increment is sized for the download rather than for the decode.
|
| 611 |
+
`LTX25_PREFETCH_ENHANCER=0` declines the ~2.5 GB for a deploy that will never enable
|
| 612 |
+
enhancement — it lands while `demo.launch()` is packing, which is the window
|
| 613 |
+
`ZEROGPU_DISK_CAP_GB` is measured against.
|
| 614 |
+
|
| 615 |
The settings, unchanged from what this section banked in advance and now imported from
|
| 616 |
upstream rather than restated: `prompt_max_new_tokens=600`, **greedy decoding**
|
| 617 |
(`do_sample=False, no_repeat_ngram_size=5`), `prompt_enhancement_seed` **inert under greedy
|
|
|
|
| 1319 |
modes.py # §3.3 registry: 11 UI modes as data over the 4 real workflows
|
| 1320 |
generate.py # §7.4 stage graph. OWNS the never-empty invariant (§5.3) and the
|
| 1321 |
# per-run output directory
|
| 1322 |
+
enhance.py # §3.5 — the Gemma prompt rewrite. Loaded and freed inside one
|
| 1323 |
+
# call, INSIDE the @spaces.GPU worker; startup weight prefetch
|
| 1324 |
outputs.py # mux video+audio, single-track export, 20 GB oldest-first eviction
|
| 1325 |
lora/
|
| 1326 |
inspect.py # header-only safetensors parse; metadata + convention detection
|
|
@@ -200,11 +200,22 @@ sidecar file and the Space log only. The seed line now says what the seed is for
|
|
| 200 |
for the bf16 `google/gemma-4-E2B-it`. Checked against the Hub, not assumed. The
|
| 201 |
bf16 build is still one environment variable away for anyone who wants it.
|
| 202 |
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
worker never
|
| 207 |
-
the
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
|
| 209 |
⚠️ **What the user must be able to see is the prompt that was actually sent.**
|
| 210 |
The box still shows what they typed; without the run report quoting the
|
|
|
|
| 200 |
for the bf16 `google/gemma-4-E2B-it`. Checked against the Hub, not assumed. The
|
| 201 |
bf16 build is still one environment variable away for anyone who wants it.
|
| 202 |
|
| 203 |
+
⚠️ **It ran in the WEB process for zero GPU-seconds, and that was wrong.**
|
| 204 |
+
The caption said so, the tests asserted it, and the claim was true: the
|
| 205 |
+
request crossing the ZeroGPU fork already carried the rewritten prompt and the
|
| 206 |
+
worker never enhanced. What nobody measured was what the user waited through.
|
| 207 |
+
On the live Space, `text_to_video` 256x256x9 went from **15.38 s** to
|
| 208 |
+
**553.45 s warm** — the 88 s download is not the cost, the CPU decode of 600
|
| 209 |
+
greedy tokens at ~0.9 s/token is. "Costs no quota — only time" turned out to
|
| 210 |
+
mean nine minutes.
|
| 211 |
+
|
| 212 |
+
✅ **It now runs on the GPU, inside the reservation**, at ~1-2 s against ~85 s
|
| 213 |
+
for a real generation. The caption gives up "free" to stop implying "fast",
|
| 214 |
+
and the running message no longer says the wait happens before a slot is
|
| 215 |
+
reserved, because it does not. **The lesson is the one worth keeping: "where
|
| 216 |
+
does it run" has two axes, disk and latency, and this build optimised one and
|
| 217 |
+
never measured the other.** A control whose cost is stated on one axis only is
|
| 218 |
+
the same shape as an inert lever — it speaks, and what it says is incomplete.
|
| 219 |
|
| 220 |
⚠️ **What the user must be able to see is the prompt that was actually sent.**
|
| 221 |
The box still shows what they typed; without the run report quoting the
|
|
@@ -30,6 +30,7 @@ __all__ = [
|
|
| 30 |
"QUANTIZATION_CHOICES",
|
| 31 |
"ENV_OUTPUT_DIR",
|
| 32 |
"ENV_OUTPUT_RETENTION_GB",
|
|
|
|
| 33 |
"ENV_PROMPT_ENHANCER_REPO",
|
| 34 |
"ENV_ZEROGPU_SIZE",
|
| 35 |
"RuntimeConfig",
|
|
@@ -44,6 +45,7 @@ ENV_OUTPUT_DIR = "LTX25_OUTPUT_DIR"
|
|
| 44 |
ENV_LORA_MAX_GB = "LTX25_LORA_MAX_GB"
|
| 45 |
ENV_QUANTIZATION = "LTX25_QUANTIZATION"
|
| 46 |
ENV_PROMPT_ENHANCER_REPO = "LTX25_PROMPT_ENHANCER_REPO"
|
|
|
|
| 47 |
|
| 48 |
#: ``auto`` means "do not pass ``size`` at all". ZeroGPU promotes us to xlarge
|
| 49 |
#: by itself once packed weights exceed its 42.00 GiB threshold, and passing the
|
|
@@ -100,8 +102,8 @@ QUANTIZATION_CHOICES = ("bf16", "int8")
|
|
| 100 |
#: ``quantization_config.quant_method == "gemma"``, which ``transformers``
|
| 101 |
#: >= 5.15.1 (already the floor in requirements.txt) registers as
|
| 102 |
#: ``GemmaQuantizer``; the unpacking layers it installs are plain torch, with no
|
| 103 |
-
#: CUDA or kernel dependency,
|
| 104 |
-
#: the
|
| 105 |
#:
|
| 106 |
#: ⚠️ Its ``config.json`` has **no** ``architectures`` key, so ``AutoModel*``
|
| 107 |
#: cannot dispatch on it. ``enhance.py`` therefore names
|
|
@@ -111,6 +113,28 @@ QUANTIZATION_CHOICES = ("bf16", "int8")
|
|
| 111 |
#: Set this to ``google/gemma-4-E2B-it`` for the bf16 build.
|
| 112 |
DEFAULT_PROMPT_ENHANCER_REPO = "google/gemma-4-E2B-it-qat-mobile-transformers"
|
| 113 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
def _choice(name: str, default: str, allowed: tuple[str, ...]) -> str:
|
| 116 |
raw = os.environ.get(name)
|
|
@@ -122,6 +146,25 @@ def _choice(name: str, default: str, allowed: tuple[str, ...]) -> str:
|
|
| 122 |
return value
|
| 123 |
|
| 124 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
def _number(name: str, default: float, *, minimum: float, integer: bool = False):
|
| 126 |
raw = os.environ.get(name)
|
| 127 |
if raw is None or raw == "":
|
|
@@ -150,6 +193,7 @@ class RuntimeConfig:
|
|
| 150 |
lora_max_gb: float
|
| 151 |
quantization: str = DEFAULT_QUANTIZATION
|
| 152 |
prompt_enhancer_repo: str = DEFAULT_PROMPT_ENHANCER_REPO
|
|
|
|
| 153 |
|
| 154 |
@property
|
| 155 |
def lora_max_bytes(self) -> int:
|
|
@@ -195,4 +239,5 @@ def load_config() -> RuntimeConfig:
|
|
| 195 |
# refusal that cannot see whether the repo exists either.
|
| 196 |
prompt_enhancer_repo=(os.environ.get(ENV_PROMPT_ENHANCER_REPO) or "").strip()
|
| 197 |
or DEFAULT_PROMPT_ENHANCER_REPO,
|
|
|
|
| 198 |
)
|
|
|
|
| 30 |
"QUANTIZATION_CHOICES",
|
| 31 |
"ENV_OUTPUT_DIR",
|
| 32 |
"ENV_OUTPUT_RETENTION_GB",
|
| 33 |
+
"ENV_PREFETCH_ENHANCER",
|
| 34 |
"ENV_PROMPT_ENHANCER_REPO",
|
| 35 |
"ENV_ZEROGPU_SIZE",
|
| 36 |
"RuntimeConfig",
|
|
|
|
| 45 |
ENV_LORA_MAX_GB = "LTX25_LORA_MAX_GB"
|
| 46 |
ENV_QUANTIZATION = "LTX25_QUANTIZATION"
|
| 47 |
ENV_PROMPT_ENHANCER_REPO = "LTX25_PROMPT_ENHANCER_REPO"
|
| 48 |
+
ENV_PREFETCH_ENHANCER = "LTX25_PREFETCH_ENHANCER"
|
| 49 |
|
| 50 |
#: ``auto`` means "do not pass ``size`` at all". ZeroGPU promotes us to xlarge
|
| 51 |
#: by itself once packed weights exceed its 42.00 GiB threshold, and passing the
|
|
|
|
| 102 |
#: ``quantization_config.quant_method == "gemma"``, which ``transformers``
|
| 103 |
#: >= 5.15.1 (already the floor in requirements.txt) registers as
|
| 104 |
#: ``GemmaQuantizer``; the unpacking layers it installs are plain torch, with no
|
| 105 |
+
#: CUDA or kernel dependency, so the checkpoint runs on either device -- which is
|
| 106 |
+
#: what let the enhancer start on the CPU and what lets it run on the GPU now.
|
| 107 |
#:
|
| 108 |
#: ⚠️ Its ``config.json`` has **no** ``architectures`` key, so ``AutoModel*``
|
| 109 |
#: cannot dispatch on it. ``enhance.py`` therefore names
|
|
|
|
| 113 |
#: Set this to ``google/gemma-4-E2B-it`` for the bf16 build.
|
| 114 |
DEFAULT_PROMPT_ENHANCER_REPO = "google/gemma-4-E2B-it-qat-mobile-transformers"
|
| 115 |
|
| 116 |
+
#: Fetch the enhancer's weights into the HF cache **at startup**, so the first
|
| 117 |
+
#: enhanced generation in a container does not pay the download.
|
| 118 |
+
#:
|
| 119 |
+
#: **On by default, because the alternative is billed.** Enhancement now runs
|
| 120 |
+
#: inside the ``@spaces.GPU`` worker (§3.5), so without a prefetch the first
|
| 121 |
+
#: enhanced call in each container spends the measured **88 s** Hub fetch inside
|
| 122 |
+
#: the metered reservation -- roughly 176 GPU-seconds, at the xlarge multiplier,
|
| 123 |
+
#: to download a file. Defaulting this off would make the prefetch a feature
|
| 124 |
+
#: nobody gets, which is the inert-lever shape pointed the other way.
|
| 125 |
+
#:
|
| 126 |
+
#: ⚠️ **Why it is switchable at all: disk.** The prefetch is ~2.5 GB for the QAT
|
| 127 |
+
#: default, and it lands while ``demo.launch()`` is packing -- the exact window
|
| 128 |
+
#: ``pipelines.ZEROGPU_DISK_CAP_GB`` is measured against, where the int8 packing
|
| 129 |
+
#: peak already sits at 133.4-137.4 GB. An operator who knows this deploy will
|
| 130 |
+
#: never enable enhancement can decline to spend that headroom, and gets the
|
| 131 |
+
#: un-prefetched behaviour back: still working, just slower on first use.
|
| 132 |
+
DEFAULT_PREFETCH_ENHANCER = True
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
_TRUE = frozenset({"1", "true", "yes", "on"})
|
| 136 |
+
_FALSE = frozenset({"0", "false", "no", "off"})
|
| 137 |
+
|
| 138 |
|
| 139 |
def _choice(name: str, default: str, allowed: tuple[str, ...]) -> str:
|
| 140 |
raw = os.environ.get(name)
|
|
|
|
| 146 |
return value
|
| 147 |
|
| 148 |
|
| 149 |
+
def _flag(name: str, default: bool) -> bool:
|
| 150 |
+
"""A boolean environment variable, validated as loudly as every other one.
|
| 151 |
+
|
| 152 |
+
``bool(os.environ.get(name))`` would read ``"0"``, ``"false"`` and ``"no"``
|
| 153 |
+
as **true** -- an operator who set the variable to turn something off would
|
| 154 |
+
turn it on and get no complaint. So the accepted spellings are enumerated
|
| 155 |
+
and anything else raises, naming them.
|
| 156 |
+
"""
|
| 157 |
+
raw = os.environ.get(name)
|
| 158 |
+
if raw is None or raw == "":
|
| 159 |
+
return default
|
| 160 |
+
value = raw.strip().lower()
|
| 161 |
+
if value in _TRUE:
|
| 162 |
+
return True
|
| 163 |
+
if value in _FALSE:
|
| 164 |
+
return False
|
| 165 |
+
raise ConfigError(variable=name, value=raw, legal=tuple(sorted(_TRUE | _FALSE)))
|
| 166 |
+
|
| 167 |
+
|
| 168 |
def _number(name: str, default: float, *, minimum: float, integer: bool = False):
|
| 169 |
raw = os.environ.get(name)
|
| 170 |
if raw is None or raw == "":
|
|
|
|
| 193 |
lora_max_gb: float
|
| 194 |
quantization: str = DEFAULT_QUANTIZATION
|
| 195 |
prompt_enhancer_repo: str = DEFAULT_PROMPT_ENHANCER_REPO
|
| 196 |
+
prefetch_enhancer: bool = DEFAULT_PREFETCH_ENHANCER
|
| 197 |
|
| 198 |
@property
|
| 199 |
def lora_max_bytes(self) -> int:
|
|
|
|
| 239 |
# refusal that cannot see whether the repo exists either.
|
| 240 |
prompt_enhancer_repo=(os.environ.get(ENV_PROMPT_ENHANCER_REPO) or "").strip()
|
| 241 |
or DEFAULT_PROMPT_ENHANCER_REPO,
|
| 242 |
+
prefetch_enhancer=_flag(ENV_PREFETCH_ENHANCER, DEFAULT_PREFETCH_ENHANCER),
|
| 243 |
)
|
|
@@ -1,43 +1,84 @@
|
|
| 1 |
"""Prompt enhancement: the user's line, rewritten by Gemma, before any GPU work.
|
| 2 |
|
| 3 |
-
PLAN §3.5.
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
**
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
**Upstream's shape, not our invention.** ``diffusers.pipelines.ltx2`` already
|
| 43 |
owns this: :func:`clean_response`, :func:`_pad_inputs_for_attention_alignment`
|
|
@@ -47,7 +88,7 @@ and :func:`_prepare_enhance_image` are imported rather than reimplemented, and
|
|
| 47 |
``LTX2Pipeline.enhance_prompt``, and it is a fix rather than a divergence:
|
| 48 |
upstream calls ``torch.manual_seed(seed)`` before generating. Decoding here is
|
| 49 |
**greedy** (``do_sample=False``), so that seed changes nothing about the output
|
| 50 |
-
|
| 51 |
own seeded generator is drawn from. Reseeding it would make an enhanced run
|
| 52 |
irreproducible for no benefit at all, which is why there is no seed control for
|
| 53 |
enhancement and no ``manual_seed`` call here (PLAN §3.5 banked the same finding).
|
|
@@ -67,12 +108,14 @@ from .errors import PromptEnhancementError
|
|
| 67 |
logger = logging.getLogger(__name__)
|
| 68 |
|
| 69 |
__all__ = [
|
| 70 |
-
"ENHANCER_DEVICE",
|
| 71 |
"GENERATION_KWARGS",
|
| 72 |
"MAX_NEW_TOKENS",
|
| 73 |
"enhance",
|
| 74 |
"enhance_if_requested",
|
|
|
|
| 75 |
"enhancer_repo_id",
|
|
|
|
|
|
|
| 76 |
]
|
| 77 |
|
| 78 |
#: ``GEMMA4_PROMPT_ENHANCEMENT_CONFIG.max_new_tokens`` upstream, and the number
|
|
@@ -86,11 +129,6 @@ MAX_NEW_TOKENS = 600
|
|
| 86 |
#: no seed for it. See the module docstring.
|
| 87 |
GENERATION_KWARGS = {"do_sample": False, "no_repeat_ngram_size": 5}
|
| 88 |
|
| 89 |
-
#: Where the enhancer lives, start to finish. See the module docstring for why
|
| 90 |
-
#: this is a constant and not a configuration knob.
|
| 91 |
-
ENHANCER_DEVICE = "cpu"
|
| 92 |
-
|
| 93 |
-
|
| 94 |
def enhancer_repo_id() -> str:
|
| 95 |
"""The Hub repo the enhancer is loaded from, from the runtime config."""
|
| 96 |
from .config import load_config
|
|
@@ -98,6 +136,129 @@ def enhancer_repo_id() -> str:
|
|
| 98 |
return load_config().prompt_enhancer_repo
|
| 99 |
|
| 100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
def enhance_if_requested(request, *, enhancer=None) -> tuple[str | None, tuple[str, ...]]:
|
| 102 |
"""The whole decision, as ``(prompt or None, notes)``.
|
| 103 |
|
|
@@ -159,20 +320,30 @@ def enhance(prompt: str, *, image=None, repo_id: str | None = None, loader=None)
|
|
| 159 |
repo_id = repo_id or enhancer_repo_id()
|
| 160 |
load = loader if loader is not None else _load_enhancer
|
| 161 |
model, processor = load(repo_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
try:
|
| 163 |
-
return _rewrite(
|
|
|
|
|
|
|
| 164 |
finally:
|
| 165 |
# Locals are dropped HERE, in the frame that owns the only references,
|
| 166 |
-
# so the enhancer is gone before the caller returns and
|
| 167 |
-
#
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
del model, processor
|
| 170 |
gc.collect()
|
| 171 |
if on_cuda:
|
| 172 |
-
#
|
| 173 |
-
#
|
| 174 |
-
#
|
| 175 |
-
#
|
| 176 |
import torch
|
| 177 |
|
| 178 |
torch.cuda.empty_cache()
|
|
@@ -258,10 +429,12 @@ def _load_enhancer(repo_id: str):
|
|
| 258 |
except Exception as exc:
|
| 259 |
raise PromptEnhancementError(repo_id=repo_id, reason=repr(exc)) from exc
|
| 260 |
|
| 261 |
-
# `.eval()` and an explicit device, in that order. The device is
|
| 262 |
-
# rather than inherited
|
| 263 |
-
#
|
| 264 |
-
|
|
|
|
|
|
|
| 265 |
|
| 266 |
|
| 267 |
def _system_prompts():
|
|
@@ -278,7 +451,7 @@ def _system_prompts():
|
|
| 278 |
return LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT, LTX2_5_I2V_DEFAULT_SYSTEM_PROMPT
|
| 279 |
|
| 280 |
|
| 281 |
-
def _rewrite(model, processor, *, prompt: str, image, repo_id: str) -> str:
|
| 282 |
"""One greedy generation, in the shape ``LTX2Pipeline.enhance_prompt`` uses."""
|
| 283 |
try:
|
| 284 |
import torch
|
|
@@ -325,8 +498,11 @@ def _rewrite(model, processor, *, prompt: str, image, repo_id: str) -> str:
|
|
| 325 |
template = processor.tokenizer.apply_chat_template(
|
| 326 |
messages, tokenize=False, add_generation_prompt=True
|
| 327 |
)
|
|
|
|
|
|
|
|
|
|
| 328 |
model_inputs = processor(text=template, images=enhance_image, return_tensors="pt").to(
|
| 329 |
-
|
| 330 |
)
|
| 331 |
pad_token_id = processor.tokenizer.pad_token_id
|
| 332 |
model_inputs = _pad_inputs_for_attention_alignment(
|
|
@@ -351,11 +527,18 @@ def _rewrite(model, processor, *, prompt: str, image, repo_id: str) -> str:
|
|
| 351 |
return clean_response(decoded[0])
|
| 352 |
|
| 353 |
|
| 354 |
-
def
|
| 355 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
try:
|
| 357 |
for parameter in model.parameters():
|
| 358 |
-
return parameter.device.type == "cuda"
|
| 359 |
except Exception: # noqa: BLE001 -- a fake model in a test has no parameters
|
| 360 |
-
return
|
| 361 |
-
return
|
|
|
|
| 1 |
"""Prompt enhancement: the user's line, rewritten by Gemma, before any GPU work.
|
| 2 |
|
| 3 |
+
PLAN §3.5.
|
| 4 |
+
|
| 5 |
+
**Where this runs, and why it moved.** Inside the ``@spaces.GPU`` worker, on the
|
| 6 |
+
GPU, immediately after validation and before the transformer is built. It did
|
| 7 |
+
not start there. It shipped in the *web* process, on the CPU, deliberately --
|
| 8 |
+
and that placement was correct about the thing it was reasoning about and wrong
|
| 9 |
+
about the thing it never measured.
|
| 10 |
+
|
| 11 |
+
⛔ **The web-process placement, and the measurement that ended it.** On the live
|
| 12 |
+
Space, ``text_to_video`` at 256x256x9 -- the cheapest configuration that exists
|
| 13 |
+
here::
|
| 14 |
+
|
| 15 |
+
enhance OFF 15.38 s
|
| 16 |
+
enhance ON, cold 654.15 s (+638.8)
|
| 17 |
+
enhance ON, warm 553.45 s (+538.1)
|
| 18 |
+
|
| 19 |
+
The cold/warm split is what isolates the cause. The 2.46 GB Hub fetch takes
|
| 20 |
+
88 s and the weights load in under a second, so the **download is not the
|
| 21 |
+
cost**: ~538 s of the ~554 s warm figure is the CPU decode of 600 greedy tokens,
|
| 22 |
+
about **0.9 s/token**. The estimate that justified running it on the CPU was
|
| 23 |
+
"1-2 s" -- a *GPU* number applied to a *CPU* placement. 600 tokens in 2 s is
|
| 24 |
+
300 tok/s, which no CPU does on a 5B-parameter model. Nine minutes of wall-clock
|
| 25 |
+
were priced at two seconds because nobody put a stopwatch on the placement they
|
| 26 |
+
had chosen.
|
| 27 |
+
|
| 28 |
+
**The transferable lesson, which should outlive this feature: "where does it
|
| 29 |
+
run" has two axes -- disk and latency -- and only one of them was optimised.**
|
| 30 |
+
The disk argument was researched, written down, checked against the packer's
|
| 31 |
+
source and proved correct. The latency argument was never taken. A placement
|
| 32 |
+
decision that answers one axis and is silent on the other is not a decision, it
|
| 33 |
+
is half of one, and the half that is missing is the half that reaches the user.
|
| 34 |
+
|
| 35 |
+
✅ **The disk argument survives the move intact, and that is the crux.** Moving
|
| 36 |
+
to CUDA inside the worker does NOT put the enhancer back in the packer's way:
|
| 37 |
+
|
| 38 |
+
* ZeroGPU packing fires exactly **once per container**, via ``torch.pack()`` at
|
| 39 |
+
``demo.launch()`` (``spaces/zero/__init__.py:32``), and packs only tensors
|
| 40 |
+
registered in ``cuda_aliases`` during the module-scope import phase.
|
| 41 |
+
* Inside a ``@spaces.GPU`` call the forked worker has already run
|
| 42 |
+
``torch.unpatch()`` (``wrappers.py:147``), so ``.to("cuda")`` there is a real
|
| 43 |
+
H2D copy that is **never packed**.
|
| 44 |
+
* In-repo precedent already shipping: ``pipelines.py`` moves the stage-2
|
| 45 |
+
upsampler and diffusion decoder to CUDA inside the worker for the same reason.
|
| 46 |
+
|
| 47 |
+
So the enhancer stays ~2.5 GB in the HF cache, never packed, never in the
|
| 48 |
+
snapshot, never in ``preload_from_hub`` -- and it gets CUDA speed. The cost is
|
| 49 |
+
~1-2 s of billed wall per enhanced generation, against ~85 s for a real
|
| 50 |
+
generation: under 5% overhead, where the CPU placement was **+3500%**.
|
| 51 |
+
|
| 52 |
+
**What it now costs, and who is told.** Enhancement is inside the metered
|
| 53 |
+
window, so ``zerogpu.estimate_duration`` adds
|
| 54 |
+
:data:`~ltx25_studio.zerogpu.ENHANCE_DURATION_SECONDS` to the reservation when
|
| 55 |
+
the toggle is set, and the UI caption says the run costs a little quota rather
|
| 56 |
+
than none. An enhanced run that got killed at the reservation boundary would be
|
| 57 |
+
a self-inflicted wound.
|
| 58 |
+
|
| 59 |
+
**Prefetch, so the download is never billed.** :func:`prefetch` pulls the
|
| 60 |
+
weights into the HF cache at startup, on the CPU, as a **download only** -- see
|
| 61 |
+
its docstring for why that cannot enter the packing window. Without it the first
|
| 62 |
+
enhanced call in each container spends 88 s of *billed GPU time* on a file
|
| 63 |
+
transfer. It is best-effort by construction: a Space whose prefetch failed still
|
| 64 |
+
starts and still serves un-enhanced generations, and its first enhanced call is
|
| 65 |
+
merely slow.
|
| 66 |
+
|
| 67 |
+
**Loaded per call and freed in the same call**, and the claim that buys is worth
|
| 68 |
+
stating precisely rather than generously. It is *not* "the enhancer never
|
| 69 |
+
coexists with the transformer": inside the worker the transformer has already
|
| 70 |
+
been restored to VRAM before this runs, so for the length of the rewrite they
|
| 71 |
+
are both resident. What is true, and what matters, is that the enhancer is
|
| 72 |
+
**gone before denoising starts** -- ``enhance()`` frees it in the same frame
|
| 73 |
+
that loaded it, and ``generate()`` calls it above the pipeline factory -- so the
|
| 74 |
+
memory peak, which is denoising activations, never also carries 2.5 GB of Gemma.
|
| 75 |
+
A cached singleton would hold that 2.5 GB across every subsequent generation for
|
| 76 |
+
the sake of the minority of runs that enable it.
|
| 77 |
+
|
| 78 |
+
The free path (``del`` + ``gc.collect()`` + ``torch.cuda.empty_cache()``) is
|
| 79 |
+
guarded on the model's **own** parameter device rather than on
|
| 80 |
+
``torch.cuda.is_available()``, so a run that never touched CUDA never
|
| 81 |
+
initialises it.
|
| 82 |
|
| 83 |
**Upstream's shape, not our invention.** ``diffusers.pipelines.ltx2`` already
|
| 84 |
owns this: :func:`clean_response`, :func:`_pad_inputs_for_attention_alignment`
|
|
|
|
| 88 |
``LTX2Pipeline.enhance_prompt``, and it is a fix rather than a divergence:
|
| 89 |
upstream calls ``torch.manual_seed(seed)`` before generating. Decoding here is
|
| 90 |
**greedy** (``do_sample=False``), so that seed changes nothing about the output
|
| 91 |
+
-- it only reseeds the global RNG, which in this app is the stream the video's
|
| 92 |
own seeded generator is drawn from. Reseeding it would make an enhanced run
|
| 93 |
irreproducible for no benefit at all, which is why there is no seed control for
|
| 94 |
enhancement and no ``manual_seed`` call here (PLAN §3.5 banked the same finding).
|
|
|
|
| 108 |
logger = logging.getLogger(__name__)
|
| 109 |
|
| 110 |
__all__ = [
|
|
|
|
| 111 |
"GENERATION_KWARGS",
|
| 112 |
"MAX_NEW_TOKENS",
|
| 113 |
"enhance",
|
| 114 |
"enhance_if_requested",
|
| 115 |
+
"enhancer_device",
|
| 116 |
"enhancer_repo_id",
|
| 117 |
+
"prefetch",
|
| 118 |
+
"start_prefetch",
|
| 119 |
]
|
| 120 |
|
| 121 |
#: ``GEMMA4_PROMPT_ENHANCEMENT_CONFIG.max_new_tokens`` upstream, and the number
|
|
|
|
| 129 |
#: no seed for it. See the module docstring.
|
| 130 |
GENERATION_KWARGS = {"do_sample": False, "no_repeat_ngram_size": 5}
|
| 131 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
def enhancer_repo_id() -> str:
|
| 133 |
"""The Hub repo the enhancer is loaded from, from the runtime config."""
|
| 134 |
from .config import load_config
|
|
|
|
| 136 |
return load_config().prompt_enhancer_repo
|
| 137 |
|
| 138 |
|
| 139 |
+
def enhancer_device() -> str:
|
| 140 |
+
"""``"cuda"`` where there is a GPU to use, ``"cpu"`` where there is not.
|
| 141 |
+
|
| 142 |
+
**Resolved per call rather than fixed at import**, because the answer
|
| 143 |
+
differs by *process*, not by deployment. This used to be the constant
|
| 144 |
+
``ENHANCER_DEVICE = "cpu"``, and the reasoning behind that constant was
|
| 145 |
+
sound for where the call then lived: probing ``torch.cuda`` from the web
|
| 146 |
+
process is the blocked lazy CUDA init ``app.py``'s docstring warns about,
|
| 147 |
+
which *hangs* with no error. The call now runs inside the ``@spaces.GPU``
|
| 148 |
+
worker, past ``torch.unpatch()``, where CUDA is already initialised and the
|
| 149 |
+
probe is free -- so the constant would today be pinning the enhancer to the
|
| 150 |
+
slow device for a reason that no longer applies. See the module docstring
|
| 151 |
+
for the measurement that moved it.
|
| 152 |
+
|
| 153 |
+
Never raises. A host with no torch, or a torch built without CUDA, answers
|
| 154 |
+
``"cpu"`` and the enhancement still runs -- slowly, which is the correct
|
| 155 |
+
outcome for a machine that has nothing faster.
|
| 156 |
+
"""
|
| 157 |
+
try:
|
| 158 |
+
import torch
|
| 159 |
+
|
| 160 |
+
if torch.cuda.is_available():
|
| 161 |
+
return "cuda"
|
| 162 |
+
except Exception: # noqa: BLE001 -- no torch, or no CUDA build; both mean cpu
|
| 163 |
+
return "cpu"
|
| 164 |
+
return "cpu"
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def prefetch(repo_id: str | None = None, *, token=None) -> str | None:
|
| 168 |
+
"""Pull the enhancer's weights into the HF cache. **A download, nothing more.**
|
| 169 |
+
|
| 170 |
+
Returns the snapshot directory, or ``None`` if the fetch did not succeed.
|
| 171 |
+
**Never raises** -- see "best-effort" below.
|
| 172 |
+
|
| 173 |
+
⚠️ **Why this cannot enter the ZeroGPU packing window, since the next reader
|
| 174 |
+
will worry about exactly that.** Packing captures tensors registered in
|
| 175 |
+
``cuda_aliases`` while the module scope runs -- i.e. things that called
|
| 176 |
+
``.to("cuda")`` before ``demo.launch()``. ``snapshot_download`` constructs
|
| 177 |
+
**no torch tensors at all**: it resolves a file list over HTTP and writes
|
| 178 |
+
blobs to ``~/.cache/huggingface/hub``. There is nothing for ``torch.pack()``
|
| 179 |
+
to see, on CUDA or otherwise. Files on disk are not packable state; only
|
| 180 |
+
alias registrations are. This is what lets the weights be present before the
|
| 181 |
+
first request without the enhancer ever entering the disk budget the
|
| 182 |
+
web-process placement was originally chosen to protect.
|
| 183 |
+
|
| 184 |
+
**Why ``snapshot_download`` and not the two alternatives.**
|
| 185 |
+
|
| 186 |
+
* Not ``from_pretrained`` at startup. That would do the job *and* build a
|
| 187 |
+
live 2.5 GB model object during the module-scope import phase -- the exact
|
| 188 |
+
window this build has been burned in -- and hold it in RAM for the
|
| 189 |
+
container's life to save a sub-second load. The prefetch must move bytes,
|
| 190 |
+
not construct models.
|
| 191 |
+
* Not ``hf_hub_download`` per file, the ``preflight.ensure_weights`` idiom.
|
| 192 |
+
That needs a filename allow-list, and this repo is **configurable**
|
| 193 |
+
(``LTX25_PROMPT_ENHANCER_REPO``): any list we hardcoded would be wrong the
|
| 194 |
+
moment an operator pointed it at the bf16 build, which has a different
|
| 195 |
+
file layout. ``snapshot_download`` resolves the file list from the Hub
|
| 196 |
+
itself, which is the property that makes it correct under a repo we do not
|
| 197 |
+
control. It fetches the repo as-is -- no ``allow_patterns``, deliberately:
|
| 198 |
+
a pattern that guessed wrong would skip the weights and leave a prefetch
|
| 199 |
+
that "succeeded" and cached nothing, which is worse than fetching a little
|
| 200 |
+
extra.
|
| 201 |
+
|
| 202 |
+
**Best-effort, and that is a contract.** Startup must not fail, and
|
| 203 |
+
readiness must not wait, because the enhancer could not be fetched -- an
|
| 204 |
+
un-enhanced generation is unaffected by any of this. A failed prefetch
|
| 205 |
+
degrades the first enhanced call to paying the download inside its
|
| 206 |
+
reservation, which is what happened before the prefetch existed. Degraded,
|
| 207 |
+
not broken. So every failure is logged and swallowed here.
|
| 208 |
+
|
| 209 |
+
**What happens if a user presses Generate while this is still running**, the
|
| 210 |
+
obvious question and the reassuring answer: ``huggingface_hub`` takes a
|
| 211 |
+
cross-process ``WeakFileLock`` on a per-blob ``{etag}.lock`` before writing,
|
| 212 |
+
so the worker's ``from_pretrained`` blocks on the same lock rather than
|
| 213 |
+
racing it or corrupting the cache. The worker waits for the in-flight fetch
|
| 214 |
+
and then loads the completed file. That wait is inside the reservation,
|
| 215 |
+
which is the other reason ``ENHANCE_DURATION_SECONDS`` is sized for a whole
|
| 216 |
+
download rather than for a decode.
|
| 217 |
+
"""
|
| 218 |
+
repo_id = repo_id or enhancer_repo_id()
|
| 219 |
+
try:
|
| 220 |
+
from huggingface_hub import snapshot_download
|
| 221 |
+
|
| 222 |
+
path = snapshot_download(repo_id=repo_id, token=token)
|
| 223 |
+
except Exception as exc: # noqa: BLE001 -- see "best-effort" above
|
| 224 |
+
logger.warning(
|
| 225 |
+
"prompt-enhancer prefetch failed for %r (%r). The Space is unaffected: "
|
| 226 |
+
"un-enhanced generations run normally, and the first enhanced run will pay "
|
| 227 |
+
"the download inside its own GPU reservation.",
|
| 228 |
+
repo_id,
|
| 229 |
+
exc,
|
| 230 |
+
)
|
| 231 |
+
return None
|
| 232 |
+
logger.info("prompt-enhancer weights cached at %s", path)
|
| 233 |
+
return str(path)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def start_prefetch(repo_id: str | None = None, *, token=None):
|
| 237 |
+
"""Run :func:`prefetch` on a daemon thread. Returns it, already started.
|
| 238 |
+
|
| 239 |
+
**A thread because readiness is the requirement.** The fetch is ~88 s for
|
| 240 |
+
the QAT default and ``app.py`` calls this before ``demo.launch()``; doing it
|
| 241 |
+
inline would hold the Space unavailable for a minute and a half to prepare
|
| 242 |
+
an optional feature. A daemon thread cannot keep the process alive at exit
|
| 243 |
+
either, so a prefetch still in flight when the Space stops does not delay
|
| 244 |
+
the stop.
|
| 245 |
+
|
| 246 |
+
The thread does pure network and disk I/O and touches no torch, so it adds
|
| 247 |
+
nothing to the packing window it runs alongside -- see :func:`prefetch`.
|
| 248 |
+
"""
|
| 249 |
+
import threading
|
| 250 |
+
|
| 251 |
+
thread = threading.Thread(
|
| 252 |
+
target=prefetch,
|
| 253 |
+
args=(repo_id,),
|
| 254 |
+
kwargs={"token": token},
|
| 255 |
+
name="ltx25-enhancer-prefetch",
|
| 256 |
+
daemon=True,
|
| 257 |
+
)
|
| 258 |
+
thread.start()
|
| 259 |
+
return thread
|
| 260 |
+
|
| 261 |
+
|
| 262 |
def enhance_if_requested(request, *, enhancer=None) -> tuple[str | None, tuple[str, ...]]:
|
| 263 |
"""The whole decision, as ``(prompt or None, notes)``.
|
| 264 |
|
|
|
|
| 320 |
repo_id = repo_id or enhancer_repo_id()
|
| 321 |
load = loader if loader is not None else _load_enhancer
|
| 322 |
model, processor = load(repo_id)
|
| 323 |
+
# Read off the MODEL rather than re-probing: the inputs must land wherever
|
| 324 |
+
# the weights actually did, and an injected test loader that moved nothing
|
| 325 |
+
# answers "cpu" without anyone having to tell it to.
|
| 326 |
+
device = _model_device(model)
|
| 327 |
try:
|
| 328 |
+
return _rewrite(
|
| 329 |
+
model, processor, prompt=prompt, image=image, repo_id=repo_id, device=device
|
| 330 |
+
)
|
| 331 |
finally:
|
| 332 |
# Locals are dropped HERE, in the frame that owns the only references,
|
| 333 |
+
# so the enhancer is gone before the caller returns -- and `generate()`
|
| 334 |
+
# calls this above the pipeline factory, so it is gone before denoising
|
| 335 |
+
# starts. That is the honest version of the claim: inside the worker the
|
| 336 |
+
# transformer is already VRAM-resident while the rewrite runs, so the
|
| 337 |
+
# two do overlap. What must not happen is 2.5 GB of Gemma still being
|
| 338 |
+
# held at the memory peak, which is the activations.
|
| 339 |
+
on_cuda = device == "cuda"
|
| 340 |
del model, processor
|
| 341 |
gc.collect()
|
| 342 |
if on_cuda:
|
| 343 |
+
# Guarded on the model's OWN device rather than on
|
| 344 |
+
# `torch.cuda.is_available()`: a parameter can only be on CUDA if
|
| 345 |
+
# CUDA was already initialised, so this never initialises it. See
|
| 346 |
+
# the module docstring.
|
| 347 |
import torch
|
| 348 |
|
| 349 |
torch.cuda.empty_cache()
|
|
|
|
| 429 |
except Exception as exc:
|
| 430 |
raise PromptEnhancementError(repo_id=repo_id, reason=repr(exc)) from exc
|
| 431 |
|
| 432 |
+
# `.eval()` and an explicit device, in that order. The device is STATED
|
| 433 |
+
# rather than inherited: a global default device deciding where 2.5 GB of
|
| 434 |
+
# Gemma lands is exactly the kind of action-at-a-distance that made the
|
| 435 |
+
# original CPU pin necessary. It is now resolved rather than hardcoded --
|
| 436 |
+
# see `enhancer_device`.
|
| 437 |
+
return model.eval().to(enhancer_device()), processor
|
| 438 |
|
| 439 |
|
| 440 |
def _system_prompts():
|
|
|
|
| 451 |
return LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT, LTX2_5_I2V_DEFAULT_SYSTEM_PROMPT
|
| 452 |
|
| 453 |
|
| 454 |
+
def _rewrite(model, processor, *, prompt: str, image, repo_id: str, device: str) -> str:
|
| 455 |
"""One greedy generation, in the shape ``LTX2Pipeline.enhance_prompt`` uses."""
|
| 456 |
try:
|
| 457 |
import torch
|
|
|
|
| 498 |
template = processor.tokenizer.apply_chat_template(
|
| 499 |
messages, tokenize=False, add_generation_prompt=True
|
| 500 |
)
|
| 501 |
+
# The tensors follow the MODEL. Moving one and not the other is a real
|
| 502 |
+
# failure mode and a silent one on a CPU-only host, where both happen to
|
| 503 |
+
# be right by accident.
|
| 504 |
model_inputs = processor(text=template, images=enhance_image, return_tensors="pt").to(
|
| 505 |
+
device
|
| 506 |
)
|
| 507 |
pad_token_id = processor.tokenizer.pad_token_id
|
| 508 |
model_inputs = _pad_inputs_for_attention_alignment(
|
|
|
|
| 527 |
return clean_response(decoded[0])
|
| 528 |
|
| 529 |
|
| 530 |
+
def _model_device(model) -> str:
|
| 531 |
+
"""The device the model's parameters are actually on. Never initialises CUDA.
|
| 532 |
+
|
| 533 |
+
Asked of the model rather than of ``torch``, which is what makes it safe: a
|
| 534 |
+
parameter can only report ``cuda`` if CUDA was already initialised to put it
|
| 535 |
+
there, so reading this can never be the thing that initialises it. A model
|
| 536 |
+
with no parameters -- every fake in the test suite -- answers ``"cpu"``,
|
| 537 |
+
which is also the honest answer for a load that never moved anything.
|
| 538 |
+
"""
|
| 539 |
try:
|
| 540 |
for parameter in model.parameters():
|
| 541 |
+
return "cuda" if parameter.device.type == "cuda" else "cpu"
|
| 542 |
except Exception: # noqa: BLE001 -- a fake model in a test has no parameters
|
| 543 |
+
return "cpu"
|
| 544 |
+
return "cpu"
|
|
@@ -149,8 +149,10 @@ class GenerationRequest:
|
|
| 149 |
min_seconds: float = 1.0
|
| 150 |
max_seconds: float = 5.0
|
| 151 |
#: Rewrite ``prompt`` with the Gemma enhancer before generating (PLAN §3.5).
|
| 152 |
-
#: Off by default. Handled
|
| 153 |
-
#:
|
|
|
|
|
|
|
| 154 |
#: No companion seed field: LTX-2.5 enhancement decodes greedily, so a seed
|
| 155 |
#: for it would be an inert lever, and this build has found seven of those.
|
| 156 |
enhance_prompt: bool = False
|
|
@@ -764,22 +766,6 @@ def _require_artifact(candidate, *, mode: str, run_dir: Path, track: str = "") -
|
|
| 764 |
return path
|
| 765 |
|
| 766 |
|
| 767 |
-
def _with_notes(result: GenerationResult, notes: tuple[str, ...]) -> GenerationResult:
|
| 768 |
-
"""Carry the web process's notes onto a result the GPU worker built.
|
| 769 |
-
|
| 770 |
-
Prompt enhancement happens before dispatch, so its note is known on this
|
| 771 |
-
side of the fork while the result that has to carry it is built on the
|
| 772 |
-
other. Rather than teach the worker about a decision it played no part in,
|
| 773 |
-
the note is grafted on when the worker's result comes back.
|
| 774 |
-
|
| 775 |
-
A no-op when there is nothing to add -- which is every run with the toggle
|
| 776 |
-
off, i.e. the default -- so the un-enhanced path is untouched by this.
|
| 777 |
-
"""
|
| 778 |
-
if not notes:
|
| 779 |
-
return result
|
| 780 |
-
return replace(result, warnings=tuple(result.warnings) + notes)
|
| 781 |
-
|
| 782 |
-
|
| 783 |
def generate(
|
| 784 |
request: GenerationRequest | None = None,
|
| 785 |
*,
|
|
@@ -799,68 +785,71 @@ def generate(
|
|
| 799 |
``enhancer`` is the third injected seam, alongside ``pipeline_factory`` and
|
| 800 |
``encoder``: a callable taking ``(prompt, image=...)`` and returning the
|
| 801 |
rewritten prompt. It is consulted only when the request asks for
|
| 802 |
-
enhancement, and only
|
|
|
|
| 803 |
"""
|
| 804 |
if request is None:
|
| 805 |
request = GenerationRequest(**params)
|
| 806 |
elif params:
|
| 807 |
request = replace(request, **params)
|
| 808 |
|
| 809 |
-
# --- prompt enhancement, HERE and nowhere else -------------------------
|
| 810 |
-
# Above the dispatch branch on purpose, and guarded on the worker flag
|
| 811 |
-
# rather than on whether a dispatch is registered, which gives one placement
|
| 812 |
-
# three properties at once:
|
| 813 |
-
#
|
| 814 |
-
# * on a Space it runs in the WEB process, so an enhanced run reserves and
|
| 815 |
-
# bills exactly the same GPU-seconds as an unenhanced one;
|
| 816 |
-
# * the request that crosses the fork already carries the rewritten
|
| 817 |
-
# prompt, so the worker needs to know nothing about any of this;
|
| 818 |
-
# * a direct caller with no dispatch registered (local dev, the tests, the
|
| 819 |
-
# reachability probe) gets identical behaviour in-process.
|
| 820 |
-
#
|
| 821 |
-
# Called unconditionally -- `enhance_if_requested` returns immediately when
|
| 822 |
-
# the toggle is off -- so `enhance.py` is executed on every generation and
|
| 823 |
-
# cannot become a module that only a non-default checkbox reaches.
|
| 824 |
-
enhancement_notes: tuple[str, ...] = ()
|
| 825 |
-
if not _IN_GPU_WORKER.get():
|
| 826 |
-
if request.enhance_prompt:
|
| 827 |
-
# "Everything cheap first" -- the rule the block below states, which
|
| 828 |
-
# has to be restated HERE because enhancement now runs above it. A
|
| 829 |
-
# 2.5 GB load plus a CPU decode is a model load by any reading, and
|
| 830 |
-
# an unknown mode or an illegal frame count must not pay for one
|
| 831 |
-
# before failing. `_validated` is pure, so running it again below
|
| 832 |
-
# costs nothing and cannot disagree with itself.
|
| 833 |
-
modes.get_mode(request.mode)
|
| 834 |
-
_validated(request)
|
| 835 |
-
|
| 836 |
-
from . import enhance as enhance_module
|
| 837 |
-
|
| 838 |
-
enhanced, enhancement_notes = enhance_module.enhance_if_requested(
|
| 839 |
-
request, enhancer=enhancer
|
| 840 |
-
)
|
| 841 |
-
if enhanced is not None:
|
| 842 |
-
request = replace(request, prompt=enhanced)
|
| 843 |
-
|
| 844 |
# Route through the ZeroGPU entrypoint when one is registered and we are not
|
| 845 |
# already inside the worker. Without this the UI calls straight through and
|
| 846 |
# no generation ever reserves a GPU slot.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 847 |
dispatch = _GPU_DISPATCH
|
| 848 |
if dispatch is not None and not _IN_GPU_WORKER.get():
|
| 849 |
-
return
|
| 850 |
-
|
| 851 |
-
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
),
|
| 857 |
-
enhancement_notes,
|
| 858 |
)
|
| 859 |
|
| 860 |
# --- everything cheap first: unknown mode and illegal geometry must not
|
| 861 |
# --- cost a model load.
|
| 862 |
spec = modes.get_mode(request.mode)
|
| 863 |
request = _validated(request)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 864 |
seed = _resolve_seed(request.seed)
|
| 865 |
|
| 866 |
run_id = uuid.uuid4().hex[:12]
|
|
|
|
| 149 |
min_seconds: float = 1.0
|
| 150 |
max_seconds: float = 5.0
|
| 151 |
#: Rewrite ``prompt`` with the Gemma enhancer before generating (PLAN §3.5).
|
| 152 |
+
#: Off by default. Handled INSIDE the GPU worker, so it costs a little
|
| 153 |
+
#: billed time -- ~1-2 s, which ``zerogpu.estimate_duration`` reserves for.
|
| 154 |
+
#: It ran on the CPU in the web process for free until that was measured at
|
| 155 |
+
#: +538 s; see ``enhance.py`` and the call site below.
|
| 156 |
#: No companion seed field: LTX-2.5 enhancement decodes greedily, so a seed
|
| 157 |
#: for it would be an inert lever, and this build has found seven of those.
|
| 158 |
enhance_prompt: bool = False
|
|
|
|
| 766 |
return path
|
| 767 |
|
| 768 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 769 |
def generate(
|
| 770 |
request: GenerationRequest | None = None,
|
| 771 |
*,
|
|
|
|
| 785 |
``enhancer`` is the third injected seam, alongside ``pipeline_factory`` and
|
| 786 |
``encoder``: a callable taking ``(prompt, image=...)`` and returning the
|
| 787 |
rewritten prompt. It is consulted only when the request asks for
|
| 788 |
+
enhancement, and only on the side of the fork that does the work -- which is
|
| 789 |
+
the GPU worker wherever there is one.
|
| 790 |
"""
|
| 791 |
if request is None:
|
| 792 |
request = GenerationRequest(**params)
|
| 793 |
elif params:
|
| 794 |
request = replace(request, **params)
|
| 795 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 796 |
# Route through the ZeroGPU entrypoint when one is registered and we are not
|
| 797 |
# already inside the worker. Without this the UI calls straight through and
|
| 798 |
# no generation ever reserves a GPU slot.
|
| 799 |
+
#
|
| 800 |
+
# `enhancer` joins `pipeline_factory` and `encoder` here, and it did not have
|
| 801 |
+
# to before: enhancement used to be consumed on THIS side of the branch, so
|
| 802 |
+
# dropping the seam was correct. Now that it runs in the worker, a dropped
|
| 803 |
+
# `enhancer` means an injected seam silently stops being used the moment a
|
| 804 |
+
# dispatch is registered -- the caller passes a fake, the worker ignores it
|
| 805 |
+
# and reaches for 2.5 GB of real Gemma instead. All three are None on the
|
| 806 |
+
# live path, which is what keeps the payload picklable.
|
| 807 |
dispatch = _GPU_DISPATCH
|
| 808 |
if dispatch is not None and not _IN_GPU_WORKER.get():
|
| 809 |
+
return dispatch(
|
| 810 |
+
request=request,
|
| 811 |
+
pipeline_factory=pipeline_factory,
|
| 812 |
+
encoder=encoder,
|
| 813 |
+
enhancer=enhancer,
|
| 814 |
+
output_root=output_root,
|
| 815 |
+
retention_bytes=retention_bytes,
|
|
|
|
|
|
|
| 816 |
)
|
| 817 |
|
| 818 |
# --- everything cheap first: unknown mode and illegal geometry must not
|
| 819 |
# --- cost a model load.
|
| 820 |
spec = modes.get_mode(request.mode)
|
| 821 |
request = _validated(request)
|
| 822 |
+
|
| 823 |
+
# --- prompt enhancement, HERE and nowhere else -------------------------
|
| 824 |
+
# BELOW the dispatch branch, so on a Space this executes inside the
|
| 825 |
+
# `@spaces.GPU` worker. That placement is a correction, and the reason is
|
| 826 |
+
# measured rather than argued: on the CPU in the web process the 600-token
|
| 827 |
+
# greedy decode took ~538 s, against ~1-2 s on the GPU. See `enhance.py`'s
|
| 828 |
+
# docstring for the numbers and for why moving it to CUDA does NOT put the
|
| 829 |
+
# enhancer back into the ZeroGPU packing window.
|
| 830 |
+
#
|
| 831 |
+
# Three properties come from this one line's position:
|
| 832 |
+
#
|
| 833 |
+
# * it is past `get_mode` and `_validated`, so "everything cheap first"
|
| 834 |
+
# covers it for free -- a request with an unknown mode or an illegal
|
| 835 |
+
# frame count is refused before a 2.5 GB load, with no duplicated
|
| 836 |
+
# validation to keep in step;
|
| 837 |
+
# * it is above the pipeline factory, so a failed enhancement never first
|
| 838 |
+
# spends a model load it is going to throw away;
|
| 839 |
+
# * the note it produces is built on the same side of the fork as the
|
| 840 |
+
# GenerationResult that carries it, so it rides home in
|
| 841 |
+
# `warnings` like every other note instead of being grafted on
|
| 842 |
+
# afterwards.
|
| 843 |
+
#
|
| 844 |
+
# Called unconditionally -- `enhance_if_requested` returns immediately when
|
| 845 |
+
# the toggle is off -- so `enhance.py` is executed on every generation and
|
| 846 |
+
# cannot become a module that only a non-default checkbox reaches.
|
| 847 |
+
from . import enhance as enhance_module
|
| 848 |
+
|
| 849 |
+
enhanced, enhancement_notes = enhance_module.enhance_if_requested(request, enhancer=enhancer)
|
| 850 |
+
if enhanced is not None:
|
| 851 |
+
request = replace(request, prompt=enhanced)
|
| 852 |
+
|
| 853 |
seed = _resolve_seed(request.seed)
|
| 854 |
|
| 855 |
run_id = uuid.uuid4().hex[:12]
|
|
@@ -410,8 +410,8 @@ FIELDS: tuple[Field, ...] = (
|
|
| 410 |
info=(
|
| 411 |
"Rewrites your line into a full LTX-2.5 caption first, using the model's own "
|
| 412 |
"system prompt — image-aware when you supply a conditioning frame. It runs on the "
|
| 413 |
-
"
|
| 414 |
-
"The prompt actually sent is reported with the run."
|
| 415 |
),
|
| 416 |
group="prompt",
|
| 417 |
default=False,
|
|
|
|
| 410 |
info=(
|
| 411 |
"Rewrites your line into a full LTX-2.5 caption first, using the model's own "
|
| 412 |
"system prompt — image-aware when you supply a conditioning frame. It runs on the "
|
| 413 |
+
"GPU inside this run's reservation, so it adds a second or two of quota rather "
|
| 414 |
+
"than a separate wait. The prompt actually sent is reported with the run."
|
| 415 |
),
|
| 416 |
group="prompt",
|
| 417 |
default=False,
|
|
@@ -361,9 +361,9 @@ def on_generate_start(mode_id: str, enhance_prompt: Any = False) -> str:
|
|
| 361 |
"""Fires the instant the button is pressed, so the UI is never silent.
|
| 362 |
|
| 363 |
Takes the enhance toggle as well as the mode because the two produce
|
| 364 |
-
genuinely different first steps: with enhancement on, the
|
| 365 |
-
|
| 366 |
-
|
| 367 |
"""
|
| 368 |
try:
|
| 369 |
return render.running(modes.get_mode(mode_id), enhancing=bool(enhance_prompt))
|
|
|
|
| 361 |
"""Fires the instant the button is pressed, so the UI is never silent.
|
| 362 |
|
| 363 |
Takes the enhance toggle as well as the mode because the two produce
|
| 364 |
+
genuinely different first steps: with enhancement on, the reservation opens
|
| 365 |
+
on a Gemma prompt rewrite rather than on denoising. Defaulted so a caller
|
| 366 |
+
that only knows the mode still gets a correct message.
|
| 367 |
"""
|
| 368 |
try:
|
| 369 |
return render.running(modes.get_mode(mode_id), enhancing=bool(enhance_prompt))
|
|
@@ -461,19 +461,23 @@ def running(mode: Any, *, enhancing: bool = False) -> str:
|
|
| 461 |
"""Shown the moment the button is pressed, so the UI is never silent.
|
| 462 |
|
| 463 |
``enhancing`` changes the message because it changes what happens **first**.
|
| 464 |
-
With the toggle on, the run
|
| 465 |
-
|
| 466 |
-
message
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 470 |
"""
|
| 471 |
if enhancing:
|
| 472 |
return (
|
| 473 |
-
f"⏳ **Enhancing your prompt — {mode.label}.** Rewriting it with Gemma on the
|
| 474 |
-
f"first
|
| 475 |
-
f"
|
| 476 |
-
f"sent is reported with the result."
|
| 477 |
)
|
| 478 |
return (
|
| 479 |
f"⏳ **Running — {mode.label}.** Reserving a ZeroGPU slot, then loading, denoising and "
|
|
|
|
| 461 |
"""Shown the moment the button is pressed, so the UI is never silent.
|
| 462 |
|
| 463 |
``enhancing`` changes the message because it changes what happens **first**.
|
| 464 |
+
With the toggle on, the run reserves its slot and then spends the first
|
| 465 |
+
couple of seconds of it rewriting the prompt rather than denoising. A
|
| 466 |
+
message describing something other than what is happening, right where the
|
| 467 |
+
user is waiting for it, is the same class of small lie as a hidden control.
|
| 468 |
+
|
| 469 |
+
⚠️ This copy said "on the CPU ... costs no quota — only time" until the
|
| 470 |
+
placement it described was measured: the CPU rewrite took ~538 s, so the
|
| 471 |
+
"only time" it cost was nine minutes. Enhancement now runs on the GPU inside
|
| 472 |
+
the reservation. It is no longer free, and it is no longer slow, and the
|
| 473 |
+
caption has to give up the first claim to be honest about the second.
|
| 474 |
"""
|
| 475 |
if enhancing:
|
| 476 |
return (
|
| 477 |
+
f"⏳ **Enhancing your prompt — {mode.label}.** Rewriting it with Gemma on the GPU "
|
| 478 |
+
f"first, inside this run's own reservation — a second or two of quota, not a "
|
| 479 |
+
f"separate wait. The generation starts straight after it, and the prompt that was "
|
| 480 |
+
f"actually sent is reported with the result."
|
| 481 |
)
|
| 482 |
return (
|
| 483 |
f"⏳ **Running — {mode.label}.** Reserving a ZeroGPU slot, then loading, denoising and "
|
|
@@ -79,6 +79,7 @@ __all__ = [
|
|
| 79 |
"check_mmap_backed",
|
| 80 |
"backing_file",
|
| 81 |
"estimate_duration",
|
|
|
|
| 82 |
"LORA_DURATION_SECONDS",
|
| 83 |
"gpu_decorator_kwargs",
|
| 84 |
"host_has_cuda",
|
|
@@ -295,6 +296,23 @@ def will_use_gpu(spaces_module) -> bool:
|
|
| 295 |
#: share one injection walk.
|
| 296 |
LORA_DURATION_SECONDS = 60
|
| 297 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
|
| 299 |
def _request_field(params, name):
|
| 300 |
"""Read a field from the call as the LIVE dispatch actually shapes it.
|
|
@@ -346,6 +364,15 @@ def estimate_duration(**params) -> int:
|
|
| 346 |
# injection walk happen once, before any denoising, so their cost is
|
| 347 |
# additive -- it does not scale with the refinement chain.
|
| 348 |
seconds = int(seconds) + LORA_DURATION_SECONDS
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 349 |
return int(seconds)
|
| 350 |
|
| 351 |
|
|
|
|
| 79 |
"check_mmap_backed",
|
| 80 |
"backing_file",
|
| 81 |
"estimate_duration",
|
| 82 |
+
"ENHANCE_DURATION_SECONDS",
|
| 83 |
"LORA_DURATION_SECONDS",
|
| 84 |
"gpu_decorator_kwargs",
|
| 85 |
"host_has_cuda",
|
|
|
|
| 296 |
#: share one injection walk.
|
| 297 |
LORA_DURATION_SECONDS = 60
|
| 298 |
|
| 299 |
+
#: Reservation headroom for a run with prompt enhancement on, in seconds.
|
| 300 |
+
#:
|
| 301 |
+
#: **Sized for the DEGRADED case, not the happy one.** The enhancement itself is
|
| 302 |
+
#: a 600-token greedy decode, ~1-2 s on the GPU. What this number is really
|
| 303 |
+
#: covering is the first enhanced call in a container whose startup prefetch did
|
| 304 |
+
#: not finish or did not succeed: that call pays the measured **88 s** Hub fetch
|
| 305 |
+
#: inside its own reservation. ``enhance.prefetch`` is explicitly best-effort --
|
| 306 |
+
#: it must never block readiness or fail startup -- so "the prefetch worked" is
|
| 307 |
+
#: not something the estimator is allowed to assume.
|
| 308 |
+
#:
|
| 309 |
+
#: 120 covers 88 s of download, a sub-second load and the decode, with headroom.
|
| 310 |
+
#: The asymmetry in the module docstring decides the rounding: reservation and
|
| 311 |
+
#: billing are different meters, so an over-generous request costs
|
| 312 |
+
#: schedulability and nothing at all in billing, while an under-generous one
|
| 313 |
+
#: kills the run at the boundary after the user has already waited through it.
|
| 314 |
+
ENHANCE_DURATION_SECONDS = 120
|
| 315 |
+
|
| 316 |
|
| 317 |
def _request_field(params, name):
|
| 318 |
"""Read a field from the call as the LIVE dispatch actually shapes it.
|
|
|
|
| 364 |
# injection walk happen once, before any denoising, so their cost is
|
| 365 |
# additive -- it does not scale with the refinement chain.
|
| 366 |
seconds = int(seconds) + LORA_DURATION_SECONDS
|
| 367 |
+
if _request_field(params, "enhance_prompt"):
|
| 368 |
+
# Additive for the same reason, and it genuinely has to be here: prompt
|
| 369 |
+
# enhancement used to run in the WEB process, outside the reservation
|
| 370 |
+
# entirely, and this estimator had nothing to say about it. It now runs
|
| 371 |
+
# INSIDE the worker (see `enhance.py`), so the time it takes is billed
|
| 372 |
+
# time -- and a reservation that does not know that gets the run killed
|
| 373 |
+
# at the boundary, which is a self-inflicted wound rather than a
|
| 374 |
+
# platform limit.
|
| 375 |
+
seconds = int(seconds) + ENHANCE_DURATION_SECONDS
|
| 376 |
return int(seconds)
|
| 377 |
|
| 378 |
|
|
@@ -155,6 +155,7 @@ EXPECTED_MODULES = (
|
|
| 155 |
"audio.py",
|
| 156 |
"modes.py",
|
| 157 |
"generate.py",
|
|
|
|
| 158 |
"outputs.py",
|
| 159 |
"lora/inspect.py",
|
| 160 |
"lora/validate.py",
|
|
|
|
| 155 |
"audio.py",
|
| 156 |
"modes.py",
|
| 157 |
"generate.py",
|
| 158 |
+
"enhance.py",
|
| 159 |
"outputs.py",
|
| 160 |
"lora/inspect.py",
|
| 161 |
"lora/validate.py",
|
|
@@ -25,6 +25,7 @@ and it moves **no weights** — repository metadata only.
|
|
| 25 |
|
| 26 |
from __future__ import annotations
|
| 27 |
|
|
|
|
| 28 |
import os
|
| 29 |
import sys
|
| 30 |
import types
|
|
@@ -271,18 +272,30 @@ def test_an_illegal_request_is_refused_before_the_enhancer_is_loaded():
|
|
| 271 |
|
| 272 |
|
| 273 |
# --------------------------------------------------------------------------
|
| 274 |
-
# the placement:
|
| 275 |
# --------------------------------------------------------------------------
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
"""
|
| 287 |
seen: list = []
|
| 288 |
|
|
@@ -307,30 +320,35 @@ def test_enhancement_happens_before_the_gpu_entrypoint_is_dispatched_to(tmp_path
|
|
| 307 |
)
|
| 308 |
|
| 309 |
assert len(seam.calls) == 1, (
|
| 310 |
-
f"the enhancer ran {len(seam.calls)} times;
|
| 311 |
-
f"
|
| 312 |
)
|
| 313 |
-
assert seen and seen[0].prompt ==
|
| 314 |
-
"the request that crossed the dispatch boundary
|
|
|
|
|
|
|
| 315 |
)
|
| 316 |
assert any(REWRITTEN in note for note in result.warnings), (
|
| 317 |
-
"the note is computed
|
| 318 |
-
"without
|
| 319 |
)
|
| 320 |
|
| 321 |
|
| 322 |
-
def
|
| 323 |
-
"""
|
|
|
|
| 324 |
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
|
|
|
|
|
|
| 328 |
"""
|
| 329 |
seam = Recorder()
|
| 330 |
monkeypatch.setattr(enhance_module, "enhance", seam)
|
| 331 |
token = generate_module._IN_GPU_WORKER.set(True)
|
| 332 |
try:
|
| 333 |
-
generate_module.generate(
|
| 334 |
a_request(enhance_prompt=True),
|
| 335 |
pipeline_factory=factory_for(FakePipe()),
|
| 336 |
encoder=good_encoder,
|
|
@@ -339,7 +357,44 @@ def test_the_gpu_worker_never_enhances(tmp_path, monkeypatch):
|
|
| 339 |
)
|
| 340 |
finally:
|
| 341 |
generate_module._IN_GPU_WORKER.reset(token)
|
| 342 |
-
assert seam.calls == []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
|
| 344 |
|
| 345 |
# --------------------------------------------------------------------------
|
|
@@ -396,10 +451,16 @@ def test_the_toggle_is_hidden_for_modes_that_discard_the_prompt():
|
|
| 396 |
def test_the_wait_announces_itself_as_a_prompt_rewrite_not_a_gpu_reservation():
|
| 397 |
"""The generic running message says "reserving a ZeroGPU slot".
|
| 398 |
|
| 399 |
-
With enhancement on that is not
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 403 |
"""
|
| 404 |
from ltx25_studio.ui import handlers
|
| 405 |
|
|
@@ -407,7 +468,25 @@ def test_the_wait_announces_itself_as_a_prompt_rewrite_not_a_gpu_reservation():
|
|
| 407 |
enhancing = handlers.on_generate_start("text_to_video", True)
|
| 408 |
assert plain != enhancing
|
| 409 |
assert "quota" in plain
|
| 410 |
-
assert "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 411 |
|
| 412 |
|
| 413 |
def test_the_status_panel_shows_the_prompt_that_was_actually_sent(tmp_path, monkeypatch):
|
|
@@ -566,6 +645,18 @@ def upstream(monkeypatch):
|
|
| 566 |
return types.SimpleNamespace(prepared=prepared)
|
| 567 |
|
| 568 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 569 |
def loader_for(model, processor):
|
| 570 |
def _loader(repo_id):
|
| 571 |
return model, processor
|
|
@@ -605,25 +696,54 @@ def test_decoding_is_greedy_and_bounded_at_the_planned_length(upstream):
|
|
| 605 |
assert kwargs["no_repeat_ngram_size"] == 5
|
| 606 |
|
| 607 |
|
| 608 |
-
def
|
| 609 |
-
"""
|
|
|
|
| 610 |
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
enhancer back in the ZeroGPU packer's way, which is the whole cost argument.
|
| 614 |
"""
|
| 615 |
-
assert enhance_module.ENHANCER_DEVICE == "cpu"
|
| 616 |
model, processor = FakeModel(), FakeProcessor()
|
| 617 |
enhance_module.enhance(ORIGINAL, repo_id="org/enhancer", loader=loader_for(model, processor))
|
| 618 |
-
# The tensors follow the model. Both are asserted because moving one and not
|
| 619 |
-
# the other is a real failure mode -- and a silent one on a CPU-only host.
|
| 620 |
assert processor.calls, "the processor was never called"
|
| 621 |
assert model.generate_kwargs, "the model never generated"
|
| 622 |
|
| 623 |
|
| 624 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 625 |
"""Stated rather than inherited: a global default device must not be able to
|
| 626 |
-
|
| 627 |
transformers = types.ModuleType("transformers")
|
| 628 |
model, processor = FakeModel(), FakeProcessor()
|
| 629 |
transformers.AutoProcessor = types.SimpleNamespace(
|
|
@@ -633,11 +753,70 @@ def test_the_loaded_model_is_put_on_the_cpu_and_into_eval_mode(monkeypatch):
|
|
| 633 |
from_pretrained=lambda repo_id, **kwargs: model
|
| 634 |
)
|
| 635 |
monkeypatch.setitem(sys.modules, "transformers", transformers)
|
|
|
|
| 636 |
|
| 637 |
loaded, _ = enhance_module._load_enhancer("org/enhancer")
|
| 638 |
assert loaded is model
|
| 639 |
assert model.evaluated is True
|
| 640 |
-
assert model.moved_to == "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 641 |
|
| 642 |
|
| 643 |
def test_the_model_is_freed_before_the_call_returns(upstream):
|
|
@@ -698,6 +877,217 @@ def test_a_transformers_too_old_to_know_gemma_4_says_so(monkeypatch):
|
|
| 698 |
assert "5.15.1" in message, "the message must name the version floor it needs"
|
| 699 |
|
| 700 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 701 |
# --------------------------------------------------------------------------
|
| 702 |
# nothing at import time, nothing in the packing window
|
| 703 |
# --------------------------------------------------------------------------
|
|
|
|
| 25 |
|
| 26 |
from __future__ import annotations
|
| 27 |
|
| 28 |
+
import builtins
|
| 29 |
import os
|
| 30 |
import sys
|
| 31 |
import types
|
|
|
|
| 272 |
|
| 273 |
|
| 274 |
# --------------------------------------------------------------------------
|
| 275 |
+
# the placement: INSIDE the GPU worker, past the fork, on the GPU
|
| 276 |
# --------------------------------------------------------------------------
|
| 277 |
+
#
|
| 278 |
+
# ⚠️ These two tests are inversions of the pair that shipped here, and the pair
|
| 279 |
+
# they replace was not wrong about its own subject. It asserted that the request
|
| 280 |
+
# crossing the fork already carried the rewritten prompt, because enhancement
|
| 281 |
+
# ran in the WEB process where it cost no GPU-seconds. That was true, it was
|
| 282 |
+
# tested, and it was measured at +538 s of user-visible wall-clock: a 600-token
|
| 283 |
+
# greedy decode on a CPU. The cost argument was sound on the axis it considered
|
| 284 |
+
# (disk, quota) and silent on the one that reached the user (latency).
|
| 285 |
+
#
|
| 286 |
+
# So the property being pinned flips: what must be true now is that the enhancer
|
| 287 |
+
# runs on the far side of the dispatch, exactly once, and that its note still
|
| 288 |
+
# reaches the user -- which is a harder guarantee than before, because the note
|
| 289 |
+
# now has to cross the fork inside GenerationResult.warnings rather than being
|
| 290 |
+
# grafted on afterwards.
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def test_enhancement_happens_inside_the_gpu_worker(tmp_path, monkeypatch):
|
| 294 |
+
"""The placement, as an assertion, pointed at where it now lives.
|
| 295 |
+
|
| 296 |
+
Enhancement is GPU work in the metered window, so the request crossing the
|
| 297 |
+
fork must still carry the ORIGINAL prompt -- the rewrite happens on the
|
| 298 |
+
other side -- and the enhancer must run exactly once, inside.
|
| 299 |
"""
|
| 300 |
seen: list = []
|
| 301 |
|
|
|
|
| 320 |
)
|
| 321 |
|
| 322 |
assert len(seam.calls) == 1, (
|
| 323 |
+
f"the enhancer ran {len(seam.calls)} times; the call is unconditional but must still "
|
| 324 |
+
f"rewrite exactly once per generation"
|
| 325 |
)
|
| 326 |
+
assert seen and seen[0].prompt == ORIGINAL, (
|
| 327 |
+
"the request that crossed the dispatch boundary already carried the rewrite, so "
|
| 328 |
+
"enhancement is still happening in the web process -- which is the ~538 s CPU decode "
|
| 329 |
+
"this move exists to end"
|
| 330 |
)
|
| 331 |
assert any(REWRITTEN in note for note in result.warnings), (
|
| 332 |
+
"the note is now computed INSIDE the worker, so it has to survive the return leg in "
|
| 333 |
+
"GenerationResult.warnings; without that the user never sees which prompt ran"
|
| 334 |
)
|
| 335 |
|
| 336 |
|
| 337 |
+
def test_the_gpu_worker_is_where_enhancement_actually_runs(tmp_path, monkeypatch):
|
| 338 |
+
"""The same property from the other side: a request arriving inside the
|
| 339 |
+
worker with the toggle set IS enhanced there.
|
| 340 |
|
| 341 |
+
This is the exact inverse of ``test_the_gpu_worker_never_enhances``, which
|
| 342 |
+
stood here and asserted ``seam.calls == []``. Keeping a worker-side guard at
|
| 343 |
+
all is the point -- without one, a future re-hoist of the call above the
|
| 344 |
+
dispatch branch would silently restore the CPU placement and nothing would
|
| 345 |
+
fail.
|
| 346 |
"""
|
| 347 |
seam = Recorder()
|
| 348 |
monkeypatch.setattr(enhance_module, "enhance", seam)
|
| 349 |
token = generate_module._IN_GPU_WORKER.set(True)
|
| 350 |
try:
|
| 351 |
+
result = generate_module.generate(
|
| 352 |
a_request(enhance_prompt=True),
|
| 353 |
pipeline_factory=factory_for(FakePipe()),
|
| 354 |
encoder=good_encoder,
|
|
|
|
| 357 |
)
|
| 358 |
finally:
|
| 359 |
generate_module._IN_GPU_WORKER.reset(token)
|
| 360 |
+
assert [call["prompt"] for call in seam.calls] == [ORIGINAL]
|
| 361 |
+
assert any(REWRITTEN in note for note in result.warnings)
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def test_the_injected_enhancer_survives_the_dispatch(tmp_path, monkeypatch):
|
| 365 |
+
"""The seam has to cross the branch, or it stops being a seam.
|
| 366 |
+
|
| 367 |
+
``generate()`` forwards ``pipeline_factory`` and ``encoder`` to the
|
| 368 |
+
entrypoint; ``enhancer`` did not need forwarding while enhancement happened
|
| 369 |
+
before the branch. It does now, and the failure mode of forgetting is quiet
|
| 370 |
+
and expensive: the caller passes a fake, the worker ignores it, and reaches
|
| 371 |
+
for 2.5 GB of real Gemma over the network instead. Caught exactly this way.
|
| 372 |
+
"""
|
| 373 |
+
forwarded: list = []
|
| 374 |
+
|
| 375 |
+
def dispatch(**kwargs):
|
| 376 |
+
forwarded.append(kwargs)
|
| 377 |
+
token = generate_module._IN_GPU_WORKER.set(True)
|
| 378 |
+
try:
|
| 379 |
+
return generate_module.generate(**kwargs)
|
| 380 |
+
finally:
|
| 381 |
+
generate_module._IN_GPU_WORKER.reset(token)
|
| 382 |
+
|
| 383 |
+
monkeypatch.setattr(generate_module, "_GPU_DISPATCH", dispatch)
|
| 384 |
+
seam = Recorder()
|
| 385 |
+
generate_module.generate(
|
| 386 |
+
a_request(enhance_prompt=True),
|
| 387 |
+
pipeline_factory=factory_for(FakePipe()),
|
| 388 |
+
encoder=good_encoder,
|
| 389 |
+
enhancer=seam,
|
| 390 |
+
output_root=tmp_path,
|
| 391 |
+
retention_bytes=10**9,
|
| 392 |
+
)
|
| 393 |
+
assert forwarded and forwarded[0]["enhancer"] is seam, (
|
| 394 |
+
"the dispatch payload dropped `enhancer`, so the injected seam is unused on any host "
|
| 395 |
+
"with an entrypoint registered"
|
| 396 |
+
)
|
| 397 |
+
assert seam.calls, "the worker never consulted the injected enhancer"
|
| 398 |
|
| 399 |
|
| 400 |
# --------------------------------------------------------------------------
|
|
|
|
| 451 |
def test_the_wait_announces_itself_as_a_prompt_rewrite_not_a_gpu_reservation():
|
| 452 |
"""The generic running message says "reserving a ZeroGPU slot".
|
| 453 |
|
| 454 |
+
With enhancement on that is not the whole story -- the first seconds of the
|
| 455 |
+
reservation go on rewriting the prompt rather than denoising. A status line
|
| 456 |
+
describing something other than what is happening, exactly where the user is
|
| 457 |
+
waiting for it, is the same small lie as a hidden control.
|
| 458 |
+
|
| 459 |
+
⚠️ This test used to require the words "no quota" and "CPU" in the enhanced
|
| 460 |
+
message, and both were true of the placement it was written for. Both are
|
| 461 |
+
now false, so asserting them would pin a lie in place. The enhanced message
|
| 462 |
+
must still DIFFER and must still name the rewrite -- that part was never
|
| 463 |
+
about where it ran.
|
| 464 |
"""
|
| 465 |
from ltx25_studio.ui import handlers
|
| 466 |
|
|
|
|
| 468 |
enhancing = handlers.on_generate_start("text_to_video", True)
|
| 469 |
assert plain != enhancing
|
| 470 |
assert "quota" in plain
|
| 471 |
+
assert "Enhancing your prompt" in enhancing
|
| 472 |
+
assert "no quota" not in enhancing, (
|
| 473 |
+
"the enhanced message still tells the user enhancement is free. It runs inside the "
|
| 474 |
+
"reservation now and is billed like the rest of the run."
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def test_no_user_facing_copy_still_says_enhancement_is_free():
|
| 479 |
+
"""The claim is gone from every surface, not just the one under test.
|
| 480 |
+
|
| 481 |
+
Three places said it -- the field caption, the running message and the
|
| 482 |
+
module that answers "where does this run" -- and a correction that lands on
|
| 483 |
+
two of three leaves the user reading the old promise wherever it survived.
|
| 484 |
+
"""
|
| 485 |
+
from ltx25_studio.ui import fields
|
| 486 |
+
|
| 487 |
+
caption = fields.field_by_key("enhance_prompt").info
|
| 488 |
+
assert "NO extra GPU quota" not in caption and "costs a wait" not in caption, caption
|
| 489 |
+
assert "GPU" in caption, "the caption no longer says where the rewrite runs"
|
| 490 |
|
| 491 |
|
| 492 |
def test_the_status_panel_shows_the_prompt_that_was_actually_sent(tmp_path, monkeypatch):
|
|
|
|
| 645 |
return types.SimpleNamespace(prepared=prepared)
|
| 646 |
|
| 647 |
|
| 648 |
+
def _guard(target: str, replacement):
|
| 649 |
+
"""An ``__import__`` that fails for exactly one module and defers otherwise."""
|
| 650 |
+
real = builtins.__import__
|
| 651 |
+
|
| 652 |
+
def _import(name, *args, **kwargs):
|
| 653 |
+
if name == target:
|
| 654 |
+
return replacement(name, *args, **kwargs)
|
| 655 |
+
return real(name, *args, **kwargs)
|
| 656 |
+
|
| 657 |
+
return _import
|
| 658 |
+
|
| 659 |
+
|
| 660 |
def loader_for(model, processor):
|
| 661 |
def _loader(repo_id):
|
| 662 |
return model, processor
|
|
|
|
| 696 |
assert kwargs["no_repeat_ngram_size"] == 5
|
| 697 |
|
| 698 |
|
| 699 |
+
def test_the_inputs_follow_the_model_onto_whatever_device_it_landed_on(upstream):
|
| 700 |
+
"""Moving the model and not the tensors is a real failure mode, and a
|
| 701 |
+
**silent** one on a CPU-only host -- where both are right by accident.
|
| 702 |
|
| 703 |
+
Read off the model rather than re-probing torch, so an injected loader that
|
| 704 |
+
moved nothing still gets coherent inputs.
|
|
|
|
| 705 |
"""
|
|
|
|
| 706 |
model, processor = FakeModel(), FakeProcessor()
|
| 707 |
enhance_module.enhance(ORIGINAL, repo_id="org/enhancer", loader=loader_for(model, processor))
|
|
|
|
|
|
|
| 708 |
assert processor.calls, "the processor was never called"
|
| 709 |
assert model.generate_kwargs, "the model never generated"
|
| 710 |
|
| 711 |
|
| 712 |
+
def test_the_device_is_resolved_rather_than_pinned_to_the_cpu(monkeypatch):
|
| 713 |
+
"""``ENHANCER_DEVICE = "cpu"`` used to be a module constant, and the
|
| 714 |
+
reasoning behind it was correct for where the call then lived: probing
|
| 715 |
+
``torch.cuda`` from the web process is the blocked lazy init that *hangs*.
|
| 716 |
+
|
| 717 |
+
The call now runs inside the ``@spaces.GPU`` worker, past ``torch.unpatch``,
|
| 718 |
+
where CUDA is already up. A constant would pin a 5B-parameter model to the
|
| 719 |
+
device that took 0.9 s/token, for a reason that no longer applies -- so the
|
| 720 |
+
device is a resolution, and it answers "cuda" when there is one.
|
| 721 |
+
"""
|
| 722 |
+
assert not hasattr(enhance_module, "ENHANCER_DEVICE"), (
|
| 723 |
+
"the CPU pin is back as a constant; enhancement runs on the GPU now"
|
| 724 |
+
)
|
| 725 |
+
|
| 726 |
+
torch = types.ModuleType("torch")
|
| 727 |
+
torch.cuda = types.SimpleNamespace(is_available=lambda: True)
|
| 728 |
+
monkeypatch.setitem(sys.modules, "torch", torch)
|
| 729 |
+
assert enhance_module.enhancer_device() == "cuda"
|
| 730 |
+
|
| 731 |
+
torch.cuda = types.SimpleNamespace(is_available=lambda: False)
|
| 732 |
+
assert enhance_module.enhancer_device() == "cpu"
|
| 733 |
+
|
| 734 |
+
|
| 735 |
+
def test_a_host_without_torch_resolves_to_the_cpu_rather_than_raising(monkeypatch):
|
| 736 |
+
"""The probe must never be the thing that breaks a run. A machine with no
|
| 737 |
+
torch, or a torch built without CUDA, enhances slowly -- which is the honest
|
| 738 |
+
answer for a machine that has nothing faster."""
|
| 739 |
+
broken = types.ModuleType("torch") # no `.cuda` attribute at all
|
| 740 |
+
monkeypatch.setitem(sys.modules, "torch", broken)
|
| 741 |
+
assert enhance_module.enhancer_device() == "cpu"
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
def test_the_loaded_model_is_put_on_the_resolved_device_and_into_eval_mode(monkeypatch):
|
| 745 |
"""Stated rather than inherited: a global default device must not be able to
|
| 746 |
+
decide where 2.5 GB of Gemma lands behind this module's back."""
|
| 747 |
transformers = types.ModuleType("transformers")
|
| 748 |
model, processor = FakeModel(), FakeProcessor()
|
| 749 |
transformers.AutoProcessor = types.SimpleNamespace(
|
|
|
|
| 753 |
from_pretrained=lambda repo_id, **kwargs: model
|
| 754 |
)
|
| 755 |
monkeypatch.setitem(sys.modules, "transformers", transformers)
|
| 756 |
+
monkeypatch.setattr(enhance_module, "enhancer_device", lambda: "cuda")
|
| 757 |
|
| 758 |
loaded, _ = enhance_module._load_enhancer("org/enhancer")
|
| 759 |
assert loaded is model
|
| 760 |
assert model.evaluated is True
|
| 761 |
+
assert model.moved_to == "cuda", (
|
| 762 |
+
"the load ignored the resolved device, so the enhancer stays on the CPU inside the "
|
| 763 |
+
"worker and the move buys nothing"
|
| 764 |
+
)
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
def test_the_freed_model_releases_vram_when_it_was_on_the_gpu(monkeypatch):
|
| 768 |
+
"""``empty_cache`` matters now in a way it did not on the CPU: the other
|
| 769 |
+
tenant is the 22B transformer, and it is in the same VRAM.
|
| 770 |
+
|
| 771 |
+
Guarded on the MODEL's own device, never on ``torch.cuda.is_available()`` --
|
| 772 |
+
a parameter can only report cuda if CUDA was already initialised to put it
|
| 773 |
+
there, so reading it can never be what initialises it.
|
| 774 |
+
"""
|
| 775 |
+
emptied: list = []
|
| 776 |
+
torch = types.ModuleType("torch")
|
| 777 |
+
|
| 778 |
+
class _NoGrad:
|
| 779 |
+
def __enter__(self):
|
| 780 |
+
return self
|
| 781 |
+
|
| 782 |
+
def __exit__(self, *exc):
|
| 783 |
+
return False
|
| 784 |
+
|
| 785 |
+
torch.no_grad = _NoGrad
|
| 786 |
+
torch.cuda = types.SimpleNamespace(empty_cache=lambda: emptied.append(True))
|
| 787 |
+
monkeypatch.setitem(sys.modules, "torch", torch)
|
| 788 |
+
for name in ("diffusers", "diffusers.pipelines", "diffusers.pipelines.ltx2"):
|
| 789 |
+
monkeypatch.setitem(sys.modules, name, types.ModuleType(name))
|
| 790 |
+
enhancement = types.ModuleType("diffusers.pipelines.ltx2.prompt_enhancement")
|
| 791 |
+
enhancement.clean_response = lambda text: text.strip()
|
| 792 |
+
enhancement._pad_inputs_for_attention_alignment = lambda inputs, pad_token_id=0: inputs
|
| 793 |
+
enhancement._prepare_enhance_image = lambda image, long_side=896: image
|
| 794 |
+
monkeypatch.setitem(sys.modules, enhancement.__name__, enhancement)
|
| 795 |
+
utils = types.ModuleType("diffusers.pipelines.ltx2.utils")
|
| 796 |
+
utils.LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT = T2V_SYSTEM_PROMPT
|
| 797 |
+
utils.LTX2_5_I2V_DEFAULT_SYSTEM_PROMPT = I2V_SYSTEM_PROMPT
|
| 798 |
+
monkeypatch.setitem(sys.modules, utils.__name__, utils)
|
| 799 |
+
|
| 800 |
+
class OnCuda(FakeModel):
|
| 801 |
+
def parameters(self):
|
| 802 |
+
yield types.SimpleNamespace(device=types.SimpleNamespace(type="cuda"))
|
| 803 |
+
|
| 804 |
+
enhance_module.enhance(
|
| 805 |
+
ORIGINAL, repo_id="org/enhancer", loader=loader_for(OnCuda(), FakeProcessor())
|
| 806 |
+
)
|
| 807 |
+
assert emptied == [True], (
|
| 808 |
+
"a GPU-resident enhancer was dropped without emptying the CUDA cache, so its ~2.5 GB "
|
| 809 |
+
"can still be held when the transformer needs the VRAM"
|
| 810 |
+
)
|
| 811 |
+
|
| 812 |
+
|
| 813 |
+
def test_a_cpu_enhancer_never_touches_torch_cuda_at_all(upstream):
|
| 814 |
+
"""The other half of the same guard. ``upstream``'s fake torch has no
|
| 815 |
+
``.cuda`` attribute, so any unguarded ``torch.cuda.empty_cache()`` on the
|
| 816 |
+
free path raises AttributeError and this fails."""
|
| 817 |
+
model, processor = FakeModel(), FakeProcessor() # FakeParameter reports "cpu"
|
| 818 |
+
enhance_module.enhance(ORIGINAL, repo_id="org/enhancer", loader=loader_for(model, processor))
|
| 819 |
+
assert model.generate_kwargs, "the model never generated"
|
| 820 |
|
| 821 |
|
| 822 |
def test_the_model_is_freed_before_the_call_returns(upstream):
|
|
|
|
| 877 |
assert "5.15.1" in message, "the message must name the version floor it needs"
|
| 878 |
|
| 879 |
|
| 880 |
+
# --------------------------------------------------------------------------
|
| 881 |
+
# the prefetch: a download, at startup, that can fail without consequence
|
| 882 |
+
# --------------------------------------------------------------------------
|
| 883 |
+
#
|
| 884 |
+
# Enhancement is inside the metered window now, so the 88 s Hub fetch would be
|
| 885 |
+
# BILLED on the first enhanced call in every container -- ~176 GPU-seconds to
|
| 886 |
+
# move a file. The prefetch spends that at startup instead. Three properties
|
| 887 |
+
# make it safe to do that, and each is a test below: it downloads and does not
|
| 888 |
+
# construct, it cannot fail the Space, and it cannot delay readiness.
|
| 889 |
+
|
| 890 |
+
|
| 891 |
+
def _hub(monkeypatch, downloaded, *, boom=None):
|
| 892 |
+
"""A fake ``huggingface_hub`` whose ``snapshot_download`` is observable."""
|
| 893 |
+
hub = types.ModuleType("huggingface_hub")
|
| 894 |
+
|
| 895 |
+
def snapshot_download(*, repo_id, token=None, **kwargs):
|
| 896 |
+
downloaded.append({"repo_id": repo_id, "token": token, **kwargs})
|
| 897 |
+
if boom is not None:
|
| 898 |
+
raise boom
|
| 899 |
+
return f"/cache/models--{repo_id.replace('/', '--')}/snapshots/deadbeef"
|
| 900 |
+
|
| 901 |
+
hub.snapshot_download = snapshot_download
|
| 902 |
+
monkeypatch.setitem(sys.modules, "huggingface_hub", hub)
|
| 903 |
+
return hub
|
| 904 |
+
|
| 905 |
+
|
| 906 |
+
def test_the_prefetch_downloads_the_configured_repository(monkeypatch):
|
| 907 |
+
downloaded: list = []
|
| 908 |
+
_hub(monkeypatch, downloaded)
|
| 909 |
+
monkeypatch.setattr(enhance_module, "enhancer_repo_id", lambda: "org/enhancer")
|
| 910 |
+
|
| 911 |
+
path = enhance_module.prefetch(token="hf_secret")
|
| 912 |
+
assert downloaded == [{"repo_id": "org/enhancer", "token": "hf_secret"}]
|
| 913 |
+
assert path and "org--enhancer" in path
|
| 914 |
+
|
| 915 |
+
|
| 916 |
+
def test_the_prefetch_follows_the_repo_lever_rather_than_a_hardcoded_name(monkeypatch):
|
| 917 |
+
"""``LTX25_PROMPT_ENHANCER_REPO`` points the enhancer at any Hub repo, so a
|
| 918 |
+
prefetch that fetched a constant would warm the cache for a model this run
|
| 919 |
+
is never going to load -- paying the disk twice and the download twice."""
|
| 920 |
+
downloaded: list = []
|
| 921 |
+
_hub(monkeypatch, downloaded)
|
| 922 |
+
monkeypatch.setenv(config_module.ENV_PROMPT_ENHANCER_REPO, "google/gemma-4-E2B-it")
|
| 923 |
+
|
| 924 |
+
enhance_module.prefetch()
|
| 925 |
+
assert downloaded[0]["repo_id"] == "google/gemma-4-E2B-it"
|
| 926 |
+
|
| 927 |
+
|
| 928 |
+
def test_the_prefetch_constructs_no_model_and_no_tensor(monkeypatch):
|
| 929 |
+
"""**The whole disk argument, as an assertion.**
|
| 930 |
+
|
| 931 |
+
ZeroGPU packs tensors registered in ``cuda_aliases`` while the module scope
|
| 932 |
+
runs. A prefetch that called ``from_pretrained`` would build a real model
|
| 933 |
+
during exactly that window; a prefetch that only writes blobs cannot be
|
| 934 |
+
packed, because files on disk are not packable state. So: no transformers,
|
| 935 |
+
no torch, no ``from_pretrained`` -- reaching for any of them raises here.
|
| 936 |
+
"""
|
| 937 |
+
downloaded: list = []
|
| 938 |
+
_hub(monkeypatch, downloaded)
|
| 939 |
+
|
| 940 |
+
for forbidden in ("torch", "transformers"):
|
| 941 |
+
module = types.ModuleType(forbidden)
|
| 942 |
+
|
| 943 |
+
def _explode(*args, **kwargs):
|
| 944 |
+
raise AssertionError(
|
| 945 |
+
"the prefetch touched the model stack; it must move bytes, not build models"
|
| 946 |
+
)
|
| 947 |
+
|
| 948 |
+
module.__getattr__ = _explode
|
| 949 |
+
monkeypatch.setitem(sys.modules, forbidden, module)
|
| 950 |
+
|
| 951 |
+
assert enhance_module.prefetch("org/enhancer") is not None
|
| 952 |
+
assert downloaded, "nothing was downloaded"
|
| 953 |
+
|
| 954 |
+
|
| 955 |
+
def test_a_failed_prefetch_is_not_fatal_and_says_what_it_costs(monkeypatch, caplog):
|
| 956 |
+
"""A Space that cannot reach the Hub at startup must still start.
|
| 957 |
+
|
| 958 |
+
The degraded outcome is one slow first enhanced call, not a dead Space and
|
| 959 |
+
not a dead un-enhanced path -- so this swallows, and the log has to say so,
|
| 960 |
+
because a silent swallow reads as a prefetch that worked.
|
| 961 |
+
"""
|
| 962 |
+
_hub(monkeypatch, [], boom=OSError("connection reset by peer"))
|
| 963 |
+
with caplog.at_level("WARNING"):
|
| 964 |
+
assert enhance_module.prefetch("org/enhancer") is None
|
| 965 |
+
logged = caplog.text
|
| 966 |
+
assert "org/enhancer" in logged and "connection reset by peer" in logged
|
| 967 |
+
assert "un-enhanced" in logged, "the log does not say what still works"
|
| 968 |
+
|
| 969 |
+
|
| 970 |
+
def test_a_missing_huggingface_hub_is_not_fatal_either(monkeypatch):
|
| 971 |
+
"""Import failure is a failure like any other on this path."""
|
| 972 |
+
|
| 973 |
+
def _no_hub(name, *args, **kwargs):
|
| 974 |
+
raise ImportError("no huggingface_hub here")
|
| 975 |
+
|
| 976 |
+
monkeypatch.delitem(sys.modules, "huggingface_hub", raising=False)
|
| 977 |
+
monkeypatch.setattr(builtins, "__import__", _guard("huggingface_hub", _no_hub))
|
| 978 |
+
assert enhance_module.prefetch("org/enhancer") is None
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
def test_the_prefetch_runs_on_a_daemon_thread_so_readiness_never_waits(monkeypatch):
|
| 982 |
+
"""``app.py`` calls this before ``demo.launch()``. The fetch is ~88 s; doing
|
| 983 |
+
it inline would hold the Space unavailable for a minute and a half to
|
| 984 |
+
prepare an optional feature. A daemon thread also cannot keep the process
|
| 985 |
+
alive at exit, so a fetch still in flight does not delay a stop."""
|
| 986 |
+
downloaded: list = []
|
| 987 |
+
_hub(monkeypatch, downloaded)
|
| 988 |
+
|
| 989 |
+
thread = enhance_module.start_prefetch("org/enhancer", token="hf_secret")
|
| 990 |
+
assert thread.daemon is True, "a non-daemon prefetch can hold the process open at exit"
|
| 991 |
+
thread.join(timeout=10)
|
| 992 |
+
assert not thread.is_alive()
|
| 993 |
+
assert downloaded == [{"repo_id": "org/enhancer", "token": "hf_secret"}]
|
| 994 |
+
|
| 995 |
+
|
| 996 |
+
def test_a_thrown_prefetch_never_escapes_the_thread(monkeypatch):
|
| 997 |
+
"""An exception on a thread would not reach ``app.py`` anyway -- it would
|
| 998 |
+
print a traceback into the Space log and look like a startup crash. It is
|
| 999 |
+
handled at the source instead."""
|
| 1000 |
+
_hub(monkeypatch, [], boom=RuntimeError("hub is down"))
|
| 1001 |
+
thread = enhance_module.start_prefetch("org/enhancer")
|
| 1002 |
+
thread.join(timeout=10)
|
| 1003 |
+
assert not thread.is_alive()
|
| 1004 |
+
|
| 1005 |
+
|
| 1006 |
+
def test_app_gates_the_prefetch_on_the_config_flag_and_on_gpu_capability():
|
| 1007 |
+
"""~2.5 GB of startup download and disk, declinable.
|
| 1008 |
+
|
| 1009 |
+
It lands while ``demo.launch()`` is packing -- the window
|
| 1010 |
+
``ZEROGPU_DISK_CAP_GB`` is measured against -- so a deploy that will never
|
| 1011 |
+
enable enhancement can keep the headroom. Read off app.py's source because
|
| 1012 |
+
importing it a second time cannot re-run its module scope.
|
| 1013 |
+
"""
|
| 1014 |
+
import ast
|
| 1015 |
+
|
| 1016 |
+
source = (PACKAGE_ROOT.parent / "app.py").read_text()
|
| 1017 |
+
tree = ast.parse(source)
|
| 1018 |
+
guarded = [
|
| 1019 |
+
node
|
| 1020 |
+
for node in ast.walk(tree)
|
| 1021 |
+
if isinstance(node, ast.If) and "start_prefetch" in ast.dump(node)
|
| 1022 |
+
]
|
| 1023 |
+
assert guarded, "app.py calls start_prefetch unconditionally, or not at all"
|
| 1024 |
+
test = ast.dump(guarded[0].test)
|
| 1025 |
+
assert "prefetch_enhancer" in test, "the config flag does not gate the prefetch"
|
| 1026 |
+
assert "WILL_USE_GPU" in test, (
|
| 1027 |
+
"a laptop with no GPU downloads 2.5 GB on every `python app.py`; the weight fetch "
|
| 1028 |
+
"next to it is gated on capability for exactly this reason"
|
| 1029 |
+
)
|
| 1030 |
+
|
| 1031 |
+
|
| 1032 |
+
def test_the_prefetch_flag_is_on_by_default_and_switchable(monkeypatch):
|
| 1033 |
+
"""Default ON, because the alternative is billed: without a prefetch the
|
| 1034 |
+
first enhanced call in each container spends the download inside its own
|
| 1035 |
+
reservation. A prefetch nobody gets by default would be the inert-lever
|
| 1036 |
+
shape pointed the other way."""
|
| 1037 |
+
monkeypatch.delenv(config_module.ENV_PREFETCH_ENHANCER, raising=False)
|
| 1038 |
+
assert config_module.load_config().prefetch_enhancer is True
|
| 1039 |
+
|
| 1040 |
+
monkeypatch.setenv(config_module.ENV_PREFETCH_ENHANCER, "0")
|
| 1041 |
+
assert config_module.load_config().prefetch_enhancer is False
|
| 1042 |
+
monkeypatch.setenv(config_module.ENV_PREFETCH_ENHANCER, "false")
|
| 1043 |
+
assert config_module.load_config().prefetch_enhancer is False
|
| 1044 |
+
monkeypatch.setenv(config_module.ENV_PREFETCH_ENHANCER, "on")
|
| 1045 |
+
assert config_module.load_config().prefetch_enhancer is True
|
| 1046 |
+
|
| 1047 |
+
|
| 1048 |
+
def test_an_unparseable_prefetch_flag_raises_rather_than_guessing(monkeypatch):
|
| 1049 |
+
"""``bool(os.environ.get(...))`` reads "0", "false" and "no" as TRUE. An
|
| 1050 |
+
operator turning the prefetch off would turn it on and get no complaint,
|
| 1051 |
+
which is the silent-misconfiguration class config.py exists to refuse."""
|
| 1052 |
+
from ltx25_studio.errors import ConfigError
|
| 1053 |
+
|
| 1054 |
+
monkeypatch.setenv(config_module.ENV_PREFETCH_ENHANCER, "maybe")
|
| 1055 |
+
with pytest.raises(ConfigError) as caught:
|
| 1056 |
+
config_module.load_config()
|
| 1057 |
+
message = str(caught.value)
|
| 1058 |
+
assert config_module.ENV_PREFETCH_ENHANCER in message and "maybe" in message
|
| 1059 |
+
|
| 1060 |
+
|
| 1061 |
+
# --------------------------------------------------------------------------
|
| 1062 |
+
# the reservation: enhancement is billed now, so it must be reserved for
|
| 1063 |
+
# --------------------------------------------------------------------------
|
| 1064 |
+
|
| 1065 |
+
|
| 1066 |
+
def test_an_enhanced_run_reserves_more_than_an_unenhanced_one():
|
| 1067 |
+
"""The self-inflicted wound this prevents: enhancement moved inside the
|
| 1068 |
+
metered window and the estimator did not follow, so the run gets killed at
|
| 1069 |
+
the reservation boundary doing work the app itself asked for."""
|
| 1070 |
+
from ltx25_studio import zerogpu
|
| 1071 |
+
|
| 1072 |
+
plain = zerogpu.estimate_duration(request=a_request())
|
| 1073 |
+
enhanced = zerogpu.estimate_duration(request=a_request(enhance_prompt=True))
|
| 1074 |
+
assert enhanced == plain + zerogpu.ENHANCE_DURATION_SECONDS
|
| 1075 |
+
assert zerogpu.ENHANCE_DURATION_SECONDS >= 88, (
|
| 1076 |
+
"the increment does not cover the measured 88 s Hub fetch. The prefetch is "
|
| 1077 |
+
"best-effort by contract, so the estimator may not assume it succeeded"
|
| 1078 |
+
)
|
| 1079 |
+
|
| 1080 |
+
|
| 1081 |
+
def test_the_increment_is_additive_rather_than_scaled_by_stage_2():
|
| 1082 |
+
"""The rewrite happens once, before any denoising, so its cost does not grow
|
| 1083 |
+
with the refinement chain -- the same reasoning as LORA_DURATION_SECONDS."""
|
| 1084 |
+
from ltx25_studio import zerogpu
|
| 1085 |
+
|
| 1086 |
+
staged = zerogpu.estimate_duration(request=a_request(enable_stage_2=True))
|
| 1087 |
+
both = zerogpu.estimate_duration(request=a_request(enable_stage_2=True, enhance_prompt=True))
|
| 1088 |
+
assert both == staged + zerogpu.ENHANCE_DURATION_SECONDS
|
| 1089 |
+
|
| 1090 |
+
|
| 1091 |
# --------------------------------------------------------------------------
|
| 1092 |
# nothing at import time, nothing in the packing window
|
| 1093 |
# --------------------------------------------------------------------------
|
|
@@ -65,6 +65,7 @@ PLAN_MODULES = (
|
|
| 65 |
"ltx25_studio.audio",
|
| 66 |
"ltx25_studio.modes",
|
| 67 |
"ltx25_studio.generate",
|
|
|
|
| 68 |
"ltx25_studio.outputs",
|
| 69 |
"ltx25_studio.lora.inspect",
|
| 70 |
"ltx25_studio.lora.validate",
|
|
@@ -88,6 +89,16 @@ LAZY_MODULES = {
|
|
| 88 |
"ltx25_studio/generate.py",
|
| 89 |
"_apply_loras(), on every run whose request stages an adapter",
|
| 90 |
),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
# Both reached through the package __init__: ui/handlers.py does
|
| 92 |
# `from ..lora import validate_lora` on an upload and generate.py does
|
| 93 |
# `from .lora import apply`, either of which executes lora/__init__.py and
|
|
@@ -470,10 +481,23 @@ def run_generation(tmp_path, **overrides):
|
|
| 470 |
|
| 471 |
@pytest.mark.parametrize(
|
| 472 |
"module",
|
| 473 |
-
[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 474 |
)
|
| 475 |
def test_the_module_runs_during_a_real_generation(module, tmp_path):
|
| 476 |
-
"""These
|
| 477 |
ran = executed_package_files(lambda: run_generation(tmp_path))
|
| 478 |
assert module_file(module) in ran, (
|
| 479 |
f"{module} never executed during a complete generate() call. It is imported, so a "
|
|
|
|
| 65 |
"ltx25_studio.audio",
|
| 66 |
"ltx25_studio.modes",
|
| 67 |
"ltx25_studio.generate",
|
| 68 |
+
"ltx25_studio.enhance",
|
| 69 |
"ltx25_studio.outputs",
|
| 70 |
"ltx25_studio.lora.inspect",
|
| 71 |
"ltx25_studio.lora.validate",
|
|
|
|
| 89 |
"ltx25_studio/generate.py",
|
| 90 |
"_apply_loras(), on every run whose request stages an adapter",
|
| 91 |
),
|
| 92 |
+
# Note the "unconditionally" and the "every": the toggle is off by default,
|
| 93 |
+
# but the CALL is not conditional on it. `enhance_if_requested` returns
|
| 94 |
+
# immediately when the flag is clear, which is what keeps this module on the
|
| 95 |
+
# executed path of a default run rather than on the path of a checkbox
|
| 96 |
+
# almost nobody ticks. See test_the_module_runs_during_a_real_generation.
|
| 97 |
+
"ltx25_studio.enhance": (
|
| 98 |
+
"ltx25_studio/generate.py",
|
| 99 |
+
"enhance_if_requested(), called unconditionally on every generation, inside the "
|
| 100 |
+
"GPU worker wherever there is one",
|
| 101 |
+
),
|
| 102 |
# Both reached through the package __init__: ui/handlers.py does
|
| 103 |
# `from ..lora import validate_lora` on an upload and generate.py does
|
| 104 |
# `from .lora import apply`, either of which executes lora/__init__.py and
|
|
|
|
| 481 |
|
| 482 |
@pytest.mark.parametrize(
|
| 483 |
"module",
|
| 484 |
+
[
|
| 485 |
+
"ltx25_studio.modes",
|
| 486 |
+
"ltx25_studio.constraints",
|
| 487 |
+
"ltx25_studio.outputs",
|
| 488 |
+
# `enhance` is on this list even though the toggle is off by default,
|
| 489 |
+
# and that is the point rather than an oversight. `generate()` calls
|
| 490 |
+
# `enhance_if_requested` unconditionally and it returns immediately when
|
| 491 |
+
# the toggle is off, precisely so the module is not one that only a
|
| 492 |
+
# non-default checkbox reaches -- the state four of this build's
|
| 493 |
+
# blockers shipped in. Gating the call on the flag would be the obvious
|
| 494 |
+
# tidy-up and would put the module straight back into that class, with
|
| 495 |
+
# nothing failing. This is what fails.
|
| 496 |
+
"ltx25_studio.enhance",
|
| 497 |
+
],
|
| 498 |
)
|
| 499 |
def test_the_module_runs_during_a_real_generation(module, tmp_path):
|
| 500 |
+
"""These are on the path of every single run, with no conditions on it."""
|
| 501 |
ran = executed_package_files(lambda: run_generation(tmp_path))
|
| 502 |
assert module_file(module) in ran, (
|
| 503 |
f"{module} never executed during a complete generate() call. It is imported, so a "
|
|
@@ -30,6 +30,7 @@ from __future__ import annotations
|
|
| 30 |
|
| 31 |
import dataclasses
|
| 32 |
import pickle
|
|
|
|
| 33 |
from types import MappingProxyType
|
| 34 |
|
| 35 |
from conftest import (
|
|
@@ -150,6 +151,11 @@ def test_the_full_dispatch_payload_pickles_with_every_input_kind_at_once(tmp_pat
|
|
| 150 |
"request": request,
|
| 151 |
"pipeline_factory": None,
|
| 152 |
"encoder": None,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
"output_root": None,
|
| 154 |
"retention_bytes": None,
|
| 155 |
}
|
|
@@ -158,6 +164,83 @@ def test_the_full_dispatch_payload_pickles_with_every_input_kind_at_once(tmp_pat
|
|
| 158 |
assert back["request"].prompt == request.prompt
|
| 159 |
|
| 160 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
def test_the_result_crossing_back_pickles(tmp_path):
|
| 162 |
"""The OK direction of the return leg: a GenerationResult is what the
|
| 163 |
worker puts on the res queue for a successful run."""
|
|
|
|
| 30 |
|
| 31 |
import dataclasses
|
| 32 |
import pickle
|
| 33 |
+
from pathlib import Path
|
| 34 |
from types import MappingProxyType
|
| 35 |
|
| 36 |
from conftest import (
|
|
|
|
| 151 |
"request": request,
|
| 152 |
"pipeline_factory": None,
|
| 153 |
"encoder": None,
|
| 154 |
+
# Joined the payload when prompt enhancement moved into the worker: the
|
| 155 |
+
# seam has to reach the side that now uses it. None on the live path,
|
| 156 |
+
# which is what keeps this dict picklable at all -- a real callable here
|
| 157 |
+
# would be a local function and would die at dispatch.
|
| 158 |
+
"enhancer": None,
|
| 159 |
"output_root": None,
|
| 160 |
"retention_bytes": None,
|
| 161 |
}
|
|
|
|
| 164 |
assert back["request"].prompt == request.prompt
|
| 165 |
|
| 166 |
|
| 167 |
+
def test_the_dispatch_payload_matches_what_generate_actually_sends(tmp_path, monkeypatch):
|
| 168 |
+
"""The list above is a claim about the live call. Check it against the call.
|
| 169 |
+
|
| 170 |
+
A hand-written payload drifts silently: ``enhancer`` was added to the real
|
| 171 |
+
dispatch and this file would have gone on pinning the old five-key shape,
|
| 172 |
+
proving that a dict nobody sends still pickles. So the keys are read off an
|
| 173 |
+
actual ``generate()`` dispatch rather than retyped.
|
| 174 |
+
"""
|
| 175 |
+
captured: list = []
|
| 176 |
+
|
| 177 |
+
def dispatch(**kwargs):
|
| 178 |
+
captured.append(kwargs)
|
| 179 |
+
token = generate_module._IN_GPU_WORKER.set(True)
|
| 180 |
+
try:
|
| 181 |
+
return generate_module.generate(**kwargs)
|
| 182 |
+
finally:
|
| 183 |
+
generate_module._IN_GPU_WORKER.reset(token)
|
| 184 |
+
|
| 185 |
+
monkeypatch.setattr(generate_module, "_GPU_DISPATCH", dispatch)
|
| 186 |
+
from test_generate import FakePipe, factory_for, good_encoder
|
| 187 |
+
|
| 188 |
+
generate_module.generate(
|
| 189 |
+
generate_module.GenerationRequest(mode="text_to_video", prompt="a lighthouse", seed=7),
|
| 190 |
+
pipeline_factory=factory_for(FakePipe()),
|
| 191 |
+
encoder=good_encoder,
|
| 192 |
+
output_root=tmp_path,
|
| 193 |
+
retention_bytes=10**9,
|
| 194 |
+
)
|
| 195 |
+
assert captured, "generate() never dispatched"
|
| 196 |
+
sent = set(captured[0])
|
| 197 |
+
assert sent == {
|
| 198 |
+
"request",
|
| 199 |
+
"pipeline_factory",
|
| 200 |
+
"encoder",
|
| 201 |
+
"enhancer",
|
| 202 |
+
"output_root",
|
| 203 |
+
"retention_bytes",
|
| 204 |
+
}, (
|
| 205 |
+
f"the live dispatch payload is {sorted(sent)}; the pickle test above covers a "
|
| 206 |
+
f"different shape and is no longer testing the real call"
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def test_the_prompt_enhancement_note_crosses_back_inside_the_result():
|
| 211 |
+
"""The return leg for a note that is now built on the far side.
|
| 212 |
+
|
| 213 |
+
Enhancement used to run in the web process, so its note was grafted onto the
|
| 214 |
+
worker's result after the fact by a helper that no longer exists. It now
|
| 215 |
+
originates INSIDE the worker, which means the only way the user ever reads
|
| 216 |
+
which prompt was actually sent is if the note survives the res queue in
|
| 217 |
+
``GenerationResult.warnings``.
|
| 218 |
+
|
| 219 |
+
It is a plain ``str``, so this is cheap -- but the LoRA report was "obviously
|
| 220 |
+
fine" too, right up until ``MappingProxyType`` killed the first staged
|
| 221 |
+
generation on the Space at 2.05 s. The cost of checking is one assert.
|
| 222 |
+
"""
|
| 223 |
+
from ltx25_studio import enhance as enhance_module
|
| 224 |
+
|
| 225 |
+
rewritten = "A weathered stone lighthouse stands on a basalt outcrop as dense fog rolls in."
|
| 226 |
+
note = enhance_module._rewrite_note(rewritten)
|
| 227 |
+
result = generate_module.GenerationResult(
|
| 228 |
+
output_path=Path("/tmp/run-abc/video.mp4"),
|
| 229 |
+
run_id="abc123",
|
| 230 |
+
run_dir=Path("/tmp/run-abc"),
|
| 231 |
+
mode="text_to_video",
|
| 232 |
+
seed=7,
|
| 233 |
+
warnings=(note,),
|
| 234 |
+
)
|
| 235 |
+
back = pickle.loads(pickle.dumps(result))
|
| 236 |
+
assert back == result
|
| 237 |
+
assert back.warnings[0] == note
|
| 238 |
+
assert rewritten in back.warnings[0], (
|
| 239 |
+
"the note crossed the fork without the rewritten prompt in it, so the user is told a "
|
| 240 |
+
"substitution happened and never told what it was"
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
def test_the_result_crossing_back_pickles(tmp_path):
|
| 245 |
"""The OK direction of the return leg: a GenerationResult is what the
|
| 246 |
worker puts on the res queue for a successful run."""
|