techfreakworm commited on
Commit
0a4ddbb
·
unverified ·
1 Parent(s): f967e30

feat: every generation now reports its peak VRAM — allocated, reserved and total, split by phase

Browse files

Two decisions on this path were taken on VRAM grounds with no VRAM number
behind either of them.

The enhancer is loaded to CUDA, used, and freed on every call (f967e30),
because VRAM safety was required without measuring what it cost. It costs
+30.78 s per enhanced generation — 46.53 s against a 15.75 s baseline at
256x256x9 — which is almost exactly a 2.49 GB reload each time. The obvious
fix is residency. Nobody knows the headroom on this MIG partition, so the
obvious fix is also unpriced.

The VAE decode went tiled+framewise at cdb3211 after an NVML allocator
assert killed a 1216x704x121 render at the decode. That change was correct
and it stays. It is also the second unpriced VRAM decision in a row.

So: measure first. `_VramProbe` in generate.py, opened immediately below the
dispatch branch, closed just before the result is assembled.

WHAT IT REPORTS, and the point of reporting all three:

* `max_memory_allocated()` — what the run actually needed.
* `max_memory_reserved()` — what the caching allocator is holding, and
therefore what really bounds the next allocation.
* `get_device_properties(current_device()).total_memory` — what the
partition has.

Headroom is total minus RESERVED. Quoting allocated against total overstates
it by the whole of the allocator's slack, and conflating the two is how this
project has repeatedly measured the wrong quantity. A fourth figure rides
along: allocated at entry, which is what the int8 transformer is already
holding, so peak-minus-resident is roughly what the run itself cost.

PHASE ATTRIBUTION, ACHIEVED — enhancement and generation are separate
windows, not one whole-call number:

`split()` reads the peak and then resets, so each phase reports ITS OWN
window rather than "everything so far", and the whole-call figure is
recovered as the largest lap. That is exact rather than an approximation:
the maximum over two touching windows is the maximum of the two maxima. It
buys the split with no measurement object threaded through enhance.py or
pipelines.py — the reason the lead expected a whole-call number instead.

That split is the one that matters. It says whether the enhancer's 2.49 GB
is ADDITIVE to the transformer's peak or absorbed in slack the denoise was
going to hold anyway, which is exactly the question residency turns on. A
whole-call number cannot answer it. The enhancement lap is taken only when
the enhancer really ran: `enhanced is None` covers both "toggle off" and
"prompt was empty", and in neither case did a model load, so a lap there
would report the baseline under a label claiming a measurement happened.

The second lap is named `generation (model load through encode)` rather than
"diffusion", because that is what it spans. Closing it earlier would leave
anything CUDA-touching after the pipeline call in a window nobody reads, and
an unclosed window is silently missing from the whole-call maximum.

IT CROSSES THE FORK. The probe is opened inside the @spaces.GPU worker — it
has to be, the web process has no CUDA to measure — so the only channel home
is GenerationResult.warnings. Plain strings, and pinned as such in
test_request_fork_boundary.py alongside the enhancement note. "Obviously
fine" was wrong here once already: LoRAInspection's MappingProxyType fields
killed the first staged generation on the Space at 2.05 s, and a measurement
that dies at the fork would die on the flagship run — the only one expensive
enough to be worth instrumenting. A second test pins that the probe itself
never joins the result; it holds a live torch.cuda module reference.

LOG-ONLY. NEVER RAISES, NEVER GATES. There is no baseline yet, so there is
no threshold that could be right, and a wrong one breaks a working Space for
the sake of a diagnostic. Every method swallows its own failure and disables
the probe. The test scripts the exact failure this partition produces — the
NVML allocator assert, raised from inside the allocator bookkeeping the probe
reads — and asserts the generation still produces its file.

Also logged at INFO on every lap, not only returned, so a run that dies
before it can build a GenerationResult still leaves its numbers in the Space
log. An OOM is the run whose numbers we most want.

GUARDED ONCE. `self._cuda` is None off CUDA and every method returns
immediately, so the call sites in generate() are unconditional. Four
`if torch.cuda.is_available()` call sites is how a probe ends up
half-instrumented — a phase split on one box, a whole-call number on
another, and nothing saying which you are reading. On local MPS/CPU the
import of torch fails or is_available() is False and the run reads exactly
as it did before: not "reports zero", absent.

NO SYNCHRONIZE. reset_peak_memory_stats, max_memory_allocated,
max_memory_reserved, memory_allocated and get_device_properties all read
allocator bookkeeping on the host; none synchronises the stream, so none can
perturb the number it measures or the wall-clock it is measured against.
empty_cache would, and is not called. Pinned twice: the FakeCuda defines
neither, so reaching for one raises AttributeError, and a token scan of
generate.py catches an unreached branch the fake would miss.

Placed below `_validated`, so "everything cheap first" still holds — a
request refused for its geometry never constructs a probe or touches a
device, and there is a test for that too.

Gate green at 2531 passed / 17 skipped, from a 2518 / 17 baseline.

ltx25_studio/generate.py CHANGED
@@ -170,6 +170,10 @@ class GenerationResult:
170
  seed: int
171
  video_path: Path | None = None
172
  audio_path: Path | None = None
 
 
 
 
173
  warnings: tuple[str, ...] = ()
174
 
175
 
@@ -766,6 +770,153 @@ def _require_artifact(candidate, *, mode: str, run_dir: Path, track: str = "") -
766
  return path
767
 
768
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
769
  def generate(
770
  request: GenerationRequest | None = None,
771
  *,
@@ -820,6 +971,19 @@ def generate(
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
@@ -849,6 +1013,14 @@ def generate(
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
 
@@ -936,12 +1108,23 @@ def generate(
936
  written, spec=spec, mode=request.mode, run_dir=run_dir, notes=encoder_warnings
937
  )
938
 
 
 
 
 
 
 
939
  warnings = (
940
  enhancement_notes
941
  + _sweep(root, retention_bytes)
942
  + tuple(encoder_warnings)
943
  + audio_notes
944
  + size_notes
 
 
 
 
 
945
  )
946
 
947
  return GenerationResult(
 
170
  seed: int
171
  video_path: Path | None = None
172
  audio_path: Path | None = None
173
+ #: Everything the run wants to say out loud. Plain strings, because this
174
+ #: tuple is the ONLY channel from inside the ``@spaces.GPU`` worker back to
175
+ #: the user -- the enhancement note and the peak-VRAM figures are both built
176
+ #: on the far side of the fork and ride home here.
177
  warnings: tuple[str, ...] = ()
178
 
179
 
 
770
  return path
771
 
772
 
773
+ # --------------------------------------------------------------------------
774
+ # peak-VRAM instrumentation -- PLAN §7.3
775
+ # --------------------------------------------------------------------------
776
+
777
+ #: Every VRAM figure this build prints is a GiB, because that is the unit
778
+ #: ``scripts/host_matrix.py``, ``scripts/host_smoke.py`` and
779
+ #: ``docs/HINODE_HOST_SETUP.md`` already use. A report that mixes GB and GiB is
780
+ #: a report nobody can line up against the numbers already banked.
781
+ _GiB = 1024**3
782
+
783
+
784
+ class _VramProbe:
785
+ """Peak VRAM for one generation, split by phase. Inert wherever CUDA is not.
786
+
787
+ **Why this exists.** Two decisions on this path were taken on VRAM grounds
788
+ with no VRAM measurement behind them: the enhancer is loaded and freed on
789
+ every call for "VRAM safety" (+30.78 s of reload per enhanced generation),
790
+ and the VAE decode was pushed to tiled+framewise after a MIG allocator
791
+ assert that nobody has a headroom number for. Neither can be revisited
792
+ without knowing what the partition actually has. So every generation now
793
+ reports it.
794
+
795
+ **Three quantities, never conflated.** ``max_memory_allocated`` is what the
796
+ run needed; ``max_memory_reserved`` is what the caching allocator is holding
797
+ and therefore what actually bounds the next allocation; ``total_memory`` is
798
+ what the partition has. Headroom is ``total - reserved``, and a report that
799
+ quotes only ``allocated`` against ``total`` overstates it by the whole size
800
+ of the allocator's slack.
801
+
802
+ **Laps, not a running total.** :meth:`split` reads the peak and then resets,
803
+ so each phase reports *its own* window rather than "everything so far". The
804
+ whole-call figure is recovered as the largest lap, which is exact: the
805
+ maximum over two touching windows is the maximum of the two maxima. That is
806
+ what buys phase attribution without threading a measurement object through
807
+ ``enhance.py`` and ``pipelines.py``.
808
+
809
+ **Guarded once, here.** ``self._cuda`` is None off CUDA and every method
810
+ returns immediately, so the call sites in :func:`generate` stay
811
+ unconditional. The alternative -- ``if torch.cuda.is_available()`` at four
812
+ call sites -- is how a probe ends up half-instrumented, reporting a phase
813
+ split on one box and a whole-call number on another with nothing saying
814
+ which you are reading.
815
+
816
+ **Never raises, never gates.** There is no baseline yet, so there is no
817
+ threshold that could be right, and a wrong one would break a working Space
818
+ for a diagnostic. Every method swallows its own failure and disables the
819
+ probe; a generation that cannot be measured still runs.
820
+
821
+ **No synchronize.** ``reset_peak_memory_stats``, ``max_memory_allocated``,
822
+ ``max_memory_reserved``, ``memory_allocated`` and ``get_device_properties``
823
+ all read allocator bookkeeping on the host. None of them synchronises the
824
+ stream, so none of them can perturb the number they are measuring or the
825
+ wall-clock they are measured against. ``empty_cache`` would -- it is not
826
+ called here.
827
+ """
828
+
829
+ def __init__(self) -> None:
830
+ self._cuda = None
831
+ self._total = 0
832
+ self._resident = 0
833
+ self._laps: list[tuple[str, int, int]] = []
834
+ try:
835
+ import torch
836
+
837
+ if torch.cuda.is_available():
838
+ self._cuda = torch.cuda
839
+ except Exception: # no torch at all is the normal case in tests
840
+ self._cuda = None
841
+
842
+ def start(self) -> None:
843
+ """Open the first window, discarding whatever the worker did before us.
844
+
845
+ Reset FIRST: a forked ZeroGPU worker is reused across generations and
846
+ arrives carrying the previous run's peak, so a probe that only read
847
+ would report the largest run the container had ever served.
848
+ """
849
+ cuda = self._cuda
850
+ if cuda is None:
851
+ return
852
+ try:
853
+ cuda.reset_peak_memory_stats()
854
+ # `current_device()` rather than a hardcoded 0: identical on the
855
+ # single-device MIG partition this is aimed at, and correct anywhere
856
+ # the worker is not on device 0.
857
+ self._total = int(cuda.get_device_properties(cuda.current_device()).total_memory)
858
+ # What the transformer is already holding when the run enters the
859
+ # worker. Peak minus this is roughly what the run itself cost.
860
+ self._resident = int(cuda.memory_allocated())
861
+ except Exception as exc:
862
+ logger.debug("peak-VRAM probe could not start: %r", exc)
863
+ self._cuda = None
864
+
865
+ def split(self, phase: str) -> None:
866
+ """Close the current window as ``phase`` and open the next one."""
867
+ cuda = self._cuda
868
+ if cuda is None:
869
+ return
870
+ try:
871
+ allocated = int(cuda.max_memory_allocated())
872
+ reserved = int(cuda.max_memory_reserved())
873
+ cuda.reset_peak_memory_stats()
874
+ except Exception as exc:
875
+ logger.debug("peak-VRAM probe could not sample %r: %r", phase, exc)
876
+ self._cuda = None
877
+ return
878
+ self._laps.append((phase, allocated, reserved))
879
+ # Logged as well as returned: a run that dies before it can build a
880
+ # GenerationResult still leaves its numbers in the Space log, and an OOM
881
+ # is exactly the run whose numbers we most want.
882
+ logger.info(
883
+ "peak VRAM, %s: %.3f GiB allocated / %.3f GiB reserved of %.3f GiB total",
884
+ phase,
885
+ allocated / _GiB,
886
+ reserved / _GiB,
887
+ self._total / _GiB,
888
+ )
889
+
890
+ def notes(self) -> tuple[str, ...]:
891
+ """The laps as user-visible notes, for ``GenerationResult.warnings``.
892
+
893
+ Plain strings, because that tuple crosses the fork on the res queue and
894
+ the one thing this build has learned twice is that what crosses a fork
895
+ must be boring (``tests/test_request_fork_boundary.py``).
896
+
897
+ Empty off CUDA, so a local MPS or CPU run reads exactly as it did before
898
+ the probe existed.
899
+ """
900
+ if not self._laps:
901
+ return ()
902
+ lines = []
903
+ if len(self._laps) > 1:
904
+ lines += [
905
+ f"peak VRAM, {phase}: {allocated / _GiB:.3f} GiB allocated / "
906
+ f"{reserved / _GiB:.3f} GiB reserved."
907
+ for phase, allocated, reserved in self._laps
908
+ ]
909
+ allocated = max(lap[1] for lap in self._laps)
910
+ reserved = max(lap[2] for lap in self._laps)
911
+ lines.append(
912
+ f"peak VRAM, whole call: {allocated / _GiB:.3f} GiB allocated / "
913
+ f"{reserved / _GiB:.3f} GiB reserved of {self._total / _GiB:.3f} GiB total, "
914
+ f"with {self._resident / _GiB:.3f} GiB already resident on entry. Reserved is "
915
+ f"what bounds the next allocation; allocated is what the run itself needed."
916
+ )
917
+ return tuple(lines)
918
+
919
+
920
  def generate(
921
  request: GenerationRequest | None = None,
922
  *,
 
971
  spec = modes.get_mode(request.mode)
972
  request = _validated(request)
973
 
974
+ # --- peak-VRAM instrumentation, opened HERE ----------------------------
975
+ # Below the dispatch branch, so on a Space this is the first line of the
976
+ # `@spaces.GPU` worker's own work and the window covers everything the
977
+ # billed call does. Below `_validated` too, so "everything cheap first"
978
+ # still holds: a request with an illegal frame count is refused without
979
+ # even constructing a probe.
980
+ #
981
+ # Deliberately NOT above the dispatch: on the web-process side there is no
982
+ # CUDA to measure, and a probe opened there would report the fork's numbers
983
+ # as the run's.
984
+ probe = _VramProbe()
985
+ probe.start()
986
+
987
  # --- prompt enhancement, HERE and nowhere else -------------------------
988
  # BELOW the dispatch branch, so on a Space this executes inside the
989
  # `@spaces.GPU` worker. That placement is a correction, and the reason is
 
1013
  enhanced, enhancement_notes = enhance_module.enhance_if_requested(request, enhancer=enhancer)
1014
  if enhanced is not None:
1015
  request = replace(request, prompt=enhanced)
1016
+ # The split that answers the open question about this feature: is the
1017
+ # enhancer's ~2.49 GB *additive* to the transformer's peak, or absorbed
1018
+ # in allocator slack the denoise was going to hold anyway? One lap each
1019
+ # side and the two figures say which. Taken only when the enhancer
1020
+ # actually ran -- `enhanced is None` covers both "toggle off" and
1021
+ # "prompt was empty", and in neither case did a model load, so a lap
1022
+ # there would report the baseline under a label claiming otherwise.
1023
+ probe.split("prompt enhancement")
1024
 
1025
  seed = _resolve_seed(request.seed)
1026
 
 
1108
  written, spec=spec, mode=request.mode, run_dir=run_dir, notes=encoder_warnings
1109
  )
1110
 
1111
+ # The second lap: model load, denoise, decode and encode. Closed here
1112
+ # rather than at the pipeline call so nothing CUDA-touching falls into a
1113
+ # window that is never read -- the whole-call figure is only the largest
1114
+ # lap, so an unclosed window is silently missing from it.
1115
+ probe.split("generation (model load through encode)")
1116
+
1117
  warnings = (
1118
  enhancement_notes
1119
  + _sweep(root, retention_bytes)
1120
  + tuple(encoder_warnings)
1121
  + audio_notes
1122
  + size_notes
1123
+ # Last, because it is diagnostic rather than something the user has
1124
+ # to act on -- but present on every run, because the one flagship
1125
+ # generation that finally gives this build a headroom number is not
1126
+ # going to be the run somebody remembered to turn a flag on for.
1127
+ + probe.notes()
1128
  )
1129
 
1130
  return GenerationResult(
tests/test_generate.py CHANGED
@@ -1046,3 +1046,336 @@ def test_a_hub_staged_adapter_is_loaded_from_its_fetched_local_path(tmp_path):
1046
  assert pipe.loaded_from == [str(local), str(tmp_path / "uploaded.safetensors")], (
1047
  "a repo id must never reach load_lora_weights — the GPU window reads files only"
1048
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1046
  assert pipe.loaded_from == [str(local), str(tmp_path / "uploaded.safetensors")], (
1047
  "a repo id must never reach load_lora_weights — the GPU window reads files only"
1048
  )
1049
+
1050
+
1051
+ # --------------------------------------------------------------------------
1052
+ # peak-VRAM instrumentation
1053
+ # --------------------------------------------------------------------------
1054
+ #
1055
+ # Two decisions on this path were taken on VRAM grounds with no VRAM number
1056
+ # behind either. The enhancer is loaded and freed on every call for "VRAM
1057
+ # safety", which costs +30.78 s of reload per enhanced generation; the VAE
1058
+ # decode went tiled+framewise after a MIG allocator assert nobody has headroom
1059
+ # for. Both are unmeasured trades. Neither can be revisited until a real run
1060
+ # says what the partition has, so every generation now reports it.
1061
+ #
1062
+ # The spec below is deliberately about the *properties* rather than the prose:
1063
+ # the reset happens first, the three quantities never collapse into one, the
1064
+ # split is real, and none of it can take a run down.
1065
+
1066
+ _GiB = 1024**3
1067
+
1068
+
1069
+ class FakeCuda:
1070
+ """A ``torch.cuda`` answering only the calls the probe is allowed to make.
1071
+
1072
+ Anything the probe reaches for that is not defined here raises
1073
+ ``AttributeError`` -- which is how ``synchronize`` creeping onto the hot
1074
+ path is caught rather than argued about.
1075
+ """
1076
+
1077
+ def __init__(self, *, total, resident, allocated, reserved, available=True):
1078
+ self.calls: list = []
1079
+ self._total = total
1080
+ self._resident = resident
1081
+ self._allocated = list(allocated)
1082
+ self._reserved = list(reserved)
1083
+ self._available = available
1084
+
1085
+ def _next(self, values):
1086
+ # Sticky last value: a probe that samples more often than the test
1087
+ # scripted should report a plausible number, not blow up and disable
1088
+ # itself, or the test would be asserting on the wrong failure.
1089
+ return values.pop(0) if len(values) > 1 else values[0]
1090
+
1091
+ def is_available(self):
1092
+ return self._available
1093
+
1094
+ def current_device(self):
1095
+ self.calls.append("current_device")
1096
+ return 0
1097
+
1098
+ def get_device_properties(self, index):
1099
+ self.calls.append(("get_device_properties", index))
1100
+ return SimpleNamespace(total_memory=self._total)
1101
+
1102
+ def memory_allocated(self):
1103
+ self.calls.append("memory_allocated")
1104
+ return self._resident
1105
+
1106
+ def max_memory_allocated(self):
1107
+ self.calls.append("max_memory_allocated")
1108
+ return self._next(self._allocated)
1109
+
1110
+ def max_memory_reserved(self):
1111
+ self.calls.append("max_memory_reserved")
1112
+ return self._next(self._reserved)
1113
+
1114
+ def reset_peak_memory_stats(self):
1115
+ self.calls.append("reset_peak_memory_stats")
1116
+
1117
+
1118
+ class ExplodingCuda(FakeCuda):
1119
+ """Available, and broken in every direction. Nothing here may reach the user."""
1120
+
1121
+ def __init__(self):
1122
+ super().__init__(total=1, resident=1, allocated=[1], reserved=[1])
1123
+
1124
+ def _boom(self, *args, **kwargs):
1125
+ raise RuntimeError("NVML_SUCCESS == r INTERNAL ASSERT FAILED")
1126
+
1127
+ current_device = _boom
1128
+ get_device_properties = _boom
1129
+ memory_allocated = _boom
1130
+ max_memory_allocated = _boom
1131
+ max_memory_reserved = _boom
1132
+ reset_peak_memory_stats = _boom
1133
+
1134
+
1135
+ def install_fake_torch(monkeypatch, cuda):
1136
+ """Put a ``torch`` in ``sys.modules`` carrying ``cuda``, and nothing else it
1137
+ does not need. ``_seeded_generator`` also imports torch on this path, so the
1138
+ fake owes it a Generator; that is the whole surface."""
1139
+ import sys
1140
+ import types
1141
+
1142
+ torch = types.ModuleType("torch")
1143
+ torch.cuda = cuda
1144
+
1145
+ class _Generator:
1146
+ def __init__(self, device=None):
1147
+ self.device = device
1148
+
1149
+ def manual_seed(self, seed):
1150
+ self.seed = seed
1151
+ return self
1152
+
1153
+ torch.Generator = _Generator
1154
+ monkeypatch.setitem(sys.modules, "torch", torch)
1155
+ return cuda
1156
+
1157
+
1158
+ def a_cuda(**overrides):
1159
+ fields = {
1160
+ # A plausible MIG partition and a plausible flagship run: ~54 GiB of
1161
+ # int8 transformer already resident, a peak in the low seventies.
1162
+ "total": 79 * _GiB,
1163
+ "resident": 54 * _GiB,
1164
+ "allocated": [71 * _GiB],
1165
+ "reserved": [73 * _GiB],
1166
+ }
1167
+ fields.update(overrides)
1168
+ return FakeCuda(**fields)
1169
+
1170
+
1171
+ def vram_notes(result):
1172
+ return [w for w in result.warnings if w.startswith("peak VRAM")]
1173
+
1174
+
1175
+ def run_on(tmp_path, **overrides):
1176
+ return generate(
1177
+ a_request(**overrides),
1178
+ pipeline_factory=factory_for(FakePipe()),
1179
+ encoder=good_encoder,
1180
+ output_root=tmp_path,
1181
+ )
1182
+
1183
+
1184
+ def test_a_run_with_no_cuda_reports_no_vram_and_reads_exactly_as_before(tmp_path):
1185
+ """The offline gate runs on MPS and CPU. The probe must be invisible there.
1186
+
1187
+ Not "reports zero" -- absent. A local run that grew three lines of GiB
1188
+ figures about a device it does not have would be a probe leaking into the
1189
+ thing it measures.
1190
+ """
1191
+ result = run_on(tmp_path)
1192
+ assert vram_notes(result) == [], (
1193
+ "a box with no CUDA reported VRAM figures, so the probe is either "
1194
+ "inventing numbers or initialising a device that is not there"
1195
+ )
1196
+
1197
+
1198
+ def test_a_cuda_run_reports_allocated_and_reserved_and_total_without_conflating_them(
1199
+ tmp_path, monkeypatch
1200
+ ):
1201
+ """The three quantities, distinguishable, in one note.
1202
+
1203
+ ``allocated`` is what the run needed, ``reserved`` is what the caching
1204
+ allocator holds and therefore what actually bounds the next allocation, and
1205
+ ``total`` is what the partition has. Headroom is ``total - reserved``.
1206
+ Quoting ``allocated`` against ``total`` overstates it by the whole of the
1207
+ allocator's slack -- and measuring the wrong quantity is precisely the
1208
+ mistake this build keeps making.
1209
+ """
1210
+ install_fake_torch(monkeypatch, a_cuda())
1211
+ notes = vram_notes(run_on(tmp_path))
1212
+ assert len(notes) == 1, notes
1213
+ note = notes[0]
1214
+ for figure, quantity in (("71.000", "allocated"), ("73.000", "reserved"), ("79.000", "total")):
1215
+ assert f"{figure} GiB" in note, (
1216
+ f"the {quantity} figure is missing from {note!r}; all three have to be present "
1217
+ f"or the reader cannot tell which one they are looking at"
1218
+ )
1219
+ assert "54.000 GiB" in note, (
1220
+ "the resident-on-entry figure is missing, so nothing separates what the run "
1221
+ "cost from what the transformer was already holding"
1222
+ )
1223
+
1224
+
1225
+ def test_the_peak_is_reset_before_anything_is_read(tmp_path, monkeypatch):
1226
+ """A ZeroGPU worker is reused across generations and arrives carrying the
1227
+ previous run's peak. A probe that only reads reports the largest run the
1228
+ container ever served, and calls it this one."""
1229
+ cuda = install_fake_torch(monkeypatch, a_cuda())
1230
+ run_on(tmp_path)
1231
+ assert cuda.calls[0] == "reset_peak_memory_stats", (
1232
+ f"the first CUDA call of the run was {cuda.calls[0]!r}, not the reset — a reused "
1233
+ f"worker's stale peak is being reported as this run's"
1234
+ )
1235
+
1236
+
1237
+ def test_enhancement_and_generation_are_measured_as_separate_windows(tmp_path, monkeypatch):
1238
+ """The split that answers the actual open question.
1239
+
1240
+ The enhancer costs +30.78 s per enhanced generation because it is loaded and
1241
+ freed every call. Making it resident is only safe if its ~2.49 GB is *not*
1242
+ additive to the peak the denoise already reaches. One lap each side of the
1243
+ rewrite is what settles that, and a whole-call number cannot.
1244
+ """
1245
+ cuda = install_fake_torch(
1246
+ monkeypatch,
1247
+ a_cuda(allocated=[57 * _GiB, 71 * _GiB], reserved=[59 * _GiB, 73 * _GiB]),
1248
+ )
1249
+ result = generate(
1250
+ a_request(enhance_prompt=True),
1251
+ pipeline_factory=factory_for(FakePipe()),
1252
+ encoder=good_encoder,
1253
+ output_root=tmp_path,
1254
+ enhancer=lambda prompt, image=None: "a weathered stone lighthouse in dense fog",
1255
+ )
1256
+ notes = vram_notes(result)
1257
+ assert len(notes) == 3, f"expected a lap each side plus the whole call, got {notes}"
1258
+ assert "prompt enhancement" in notes[0] and "57.000 GiB" in notes[0]
1259
+ assert "generation" in notes[1] and "71.000 GiB" in notes[1]
1260
+ assert cuda.calls.count("reset_peak_memory_stats") == 3, (
1261
+ "each lap must reset after it reads, or every window reports 'everything so "
1262
+ "far' and the second phase is credited with the first phase's peak"
1263
+ )
1264
+
1265
+
1266
+ def test_the_whole_call_figure_is_the_largest_lap_not_the_last(tmp_path, monkeypatch):
1267
+ """Laps are windows, so the whole call is their maximum -- exactly, because
1268
+ the max over two touching windows is the max of the two maxima.
1269
+
1270
+ Scripted here with the *enhancement* lap higher than the generation lap,
1271
+ which is the case that catches a "just report the last sample" shortcut. It
1272
+ is also the case that would matter most: an enhancer that peaks above the
1273
+ denoise is an enhancer that cannot be made resident.
1274
+ """
1275
+ install_fake_torch(
1276
+ monkeypatch,
1277
+ a_cuda(allocated=[77 * _GiB, 71 * _GiB], reserved=[78 * _GiB, 73 * _GiB]),
1278
+ )
1279
+ result = generate(
1280
+ a_request(enhance_prompt=True),
1281
+ pipeline_factory=factory_for(FakePipe()),
1282
+ encoder=good_encoder,
1283
+ output_root=tmp_path,
1284
+ enhancer=lambda prompt, image=None: "a weathered stone lighthouse in dense fog",
1285
+ )
1286
+ whole = vram_notes(result)[-1]
1287
+ assert "whole call" in whole
1288
+ assert "77.000 GiB" in whole and "78.000 GiB" in whole, (
1289
+ f"the whole-call note is {whole!r}; it reported a later, smaller lap and so "
1290
+ f"understates the peak the partition actually had to hold"
1291
+ )
1292
+
1293
+
1294
+ def test_a_run_that_never_enhances_gets_one_window_and_no_phantom_phase(tmp_path, monkeypatch):
1295
+ """``enhance_prompt`` off means no model was loaded, so there is no
1296
+ enhancement phase to attribute. A lap there would report the baseline under
1297
+ a label claiming a measurement happened."""
1298
+ install_fake_torch(monkeypatch, a_cuda())
1299
+ notes = vram_notes(run_on(tmp_path))
1300
+ assert len(notes) == 1 and "whole call" in notes[0], notes
1301
+ assert not any("prompt enhancement" in n for n in notes)
1302
+
1303
+
1304
+ def test_enhancement_requested_on_an_empty_prompt_reports_no_enhancement_phase(
1305
+ tmp_path, monkeypatch
1306
+ ):
1307
+ """The other way the enhancer does not run. ``enhance_if_requested`` returns
1308
+ without loading anything when the prompt is blank, so the toggle being set
1309
+ is not evidence that a phase existed."""
1310
+ install_fake_torch(monkeypatch, a_cuda())
1311
+ result = generate(
1312
+ a_request(prompt=" ", enhance_prompt=True),
1313
+ pipeline_factory=factory_for(FakePipe()),
1314
+ encoder=good_encoder,
1315
+ output_root=tmp_path,
1316
+ enhancer=lambda prompt, image=None: pytest.fail(
1317
+ "the enhancer must not run on a blank prompt"
1318
+ ),
1319
+ )
1320
+ assert not any("prompt enhancement" in n for n in vram_notes(result))
1321
+
1322
+
1323
+ def test_a_probe_that_cannot_measure_never_takes_the_run_down(tmp_path, monkeypatch):
1324
+ """Log-only, and that is load-bearing rather than tidy.
1325
+
1326
+ There is no baseline yet, so there is no threshold that could be right, and
1327
+ a wrong one breaks a working Space for the sake of a diagnostic. The exact
1328
+ failure scripted here is the one this partition actually produces: the NVML
1329
+ allocator assert, raised from inside the allocator bookkeeping the probe
1330
+ reads.
1331
+ """
1332
+ install_fake_torch(monkeypatch, ExplodingCuda())
1333
+ result = run_on(tmp_path)
1334
+ assert Path(result.output_path).exists(), "a broken probe killed a good generation"
1335
+ assert vram_notes(result) == [], "a probe that could not measure reported anyway"
1336
+
1337
+
1338
+ def test_the_probe_does_not_synchronise_the_stream(tmp_path, monkeypatch):
1339
+ """A synchronize on the hot path would perturb both the number being
1340
+ measured and the wall-clock it is measured against -- and the wall-clock is
1341
+ the whole reason this instrumentation exists.
1342
+
1343
+ ``FakeCuda`` defines no ``synchronize`` and no ``empty_cache``, so reaching
1344
+ for either raises ``AttributeError`` and fails the run rather than passing
1345
+ quietly. The source check is the belt to that braces: an unreached branch
1346
+ would slip past the fake.
1347
+ """
1348
+ install_fake_torch(monkeypatch, a_cuda())
1349
+ run_on(tmp_path)
1350
+ tokens = set(code_tokens(PACKAGE_ROOT / "generate.py"))
1351
+ assert "synchronize" not in tokens and "empty_cache" not in tokens, (
1352
+ "generate.py synchronises or empties the cache on the generation path; both cost "
1353
+ "real time on every run to make a free measurement slightly tidier"
1354
+ )
1355
+
1356
+
1357
+ def test_the_vram_notes_are_plain_strings_because_they_cross_the_fork(tmp_path, monkeypatch):
1358
+ """They are built inside the ``@spaces.GPU`` worker and read in the web
1359
+ process, so they ride the res queue. ``tests/test_request_fork_boundary.py``
1360
+ owns the pickle proof; this pins the shape at the source."""
1361
+ install_fake_torch(monkeypatch, a_cuda())
1362
+ result = run_on(tmp_path)
1363
+ assert all(isinstance(w, str) for w in result.warnings)
1364
+ assert isinstance(result.warnings, tuple)
1365
+
1366
+
1367
+ def test_the_probe_is_opened_after_validation_so_a_bad_request_costs_nothing(tmp_path, monkeypatch):
1368
+ """Everything cheap first still holds. A request refused for its geometry
1369
+ must not first construct a probe and touch a device."""
1370
+ cuda = install_fake_torch(monkeypatch, a_cuda())
1371
+ with pytest.raises(LTXStudioError):
1372
+ generate(
1373
+ a_request(num_frames=120),
1374
+ pipeline_factory=factory_for(FakePipe()),
1375
+ encoder=good_encoder,
1376
+ output_root=tmp_path,
1377
+ )
1378
+ assert cuda.calls == [], (
1379
+ f"a request refused by validation still touched CUDA ({cuda.calls}); the probe is "
1380
+ f"above the cheap refusals"
1381
+ )
tests/test_request_fork_boundary.py CHANGED
@@ -256,3 +256,52 @@ def test_the_result_crossing_back_pickles(tmp_path):
256
  )
257
  back = pickle.loads(pickle.dumps(result))
258
  assert back == result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
  )
257
  back = pickle.loads(pickle.dumps(result))
258
  assert back == result
259
+
260
+
261
+ def test_the_peak_vram_notes_cross_back_inside_the_result():
262
+ """The return leg for numbers that only exist on the far side.
263
+
264
+ The probe is opened inside the ``@spaces.GPU`` worker -- it has to be, since
265
+ the web process has no CUDA to measure. So the only way a headroom figure
266
+ ever reaches a human is if it survives the res queue in
267
+ ``GenerationResult.warnings``.
268
+
269
+ That is why they are plain ``str`` and not a dataclass, a namedtuple or a
270
+ dict of ints. This file exists because "obviously fine" was wrong once
271
+ already: ``LoRAInspection``'s ``MappingProxyType`` fields killed the first
272
+ staged generation on the Space at 2.05 s. A measurement that dies at the
273
+ fork measures nothing, and it would die on the *flagship* run -- the one
274
+ expensive enough to be worth instrumenting.
275
+ """
276
+ notes = (
277
+ "peak VRAM, prompt enhancement: 57.000 GiB allocated / 59.000 GiB reserved.",
278
+ "peak VRAM, generation (model load through encode): 71.011 GiB allocated / "
279
+ "73.484 GiB reserved.",
280
+ "peak VRAM, whole call: 71.011 GiB allocated / 73.484 GiB reserved of 79.139 GiB "
281
+ "total, with 54.912 GiB already resident on entry. Reserved is what bounds the "
282
+ "next allocation; allocated is what the run itself needed.",
283
+ )
284
+ result = generate_module.GenerationResult(
285
+ output_path=Path("/tmp/run-abc/video.mp4"),
286
+ run_id="abc123",
287
+ run_dir=Path("/tmp/run-abc"),
288
+ mode="text_to_video",
289
+ seed=7,
290
+ warnings=notes,
291
+ )
292
+ back = pickle.loads(pickle.dumps(result))
293
+ assert back == result
294
+ assert back.warnings == notes, (
295
+ "the peak-VRAM notes did not survive the fork, so the one run big enough to "
296
+ "give this build a headroom number reports it to nobody"
297
+ )
298
+
299
+
300
+ def test_the_probe_the_worker_builds_is_never_itself_put_on_the_res_queue():
301
+ """Only its output crosses. The probe holds a live ``torch.cuda`` module
302
+ reference, which is exactly the kind of object that does not pickle -- and
303
+ the fix is that it never leaves the worker, not that it is made to."""
304
+ assert "probe" not in {f.name for f in dataclasses.fields(generate_module.GenerationResult)}, (
305
+ "GenerationResult grew a field holding the probe; it carries a module reference "
306
+ "and would die at the fork on every run"
307
+ )