diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c064a9..86587df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,48 @@ All notable changes to this project are documented here. The format follows ## [Unreleased] +## [0.2.3] - 2026-11-24 + +0.2.3 makes the Python model classes stop a run that goes over the memory limit, as `mlx-dfloat generate` already did. + +### Added + +- Every `generate_image` and `encode` call runs under a memory watchdog by default. It has a hard line (the ceiling: + physical memory minus 4 GiB unless you lower it) and a stop line 1 GiB below the hard line (physical memory minus + 5 GiB by default). Once the process passes the stop line, the call frees what it loaded and raises + `DFloatWatchdogError` at its next checkpoint, a place where the call can stop cleanly, such as between transformer + blocks. The error is exported from `mlx_dfloat`, is a `MemoryError` and carries the path of the record when one was + written. Your process keeps running. +- `mlx-dfloat generate` has no stop line and is unchanged: it ends at the hard line (exit 70) or at its time limit + (exit 71). +- `WatchdogConfig`, exported from `mlx_dfloat.mflux`, sets the lines (`ceiling`, `stop_margin`), an optional time limit + (`wall_budget`), the `grace` period and the folder for the record (`artifact_dir`, a string or a path). Values are in + bytes. `ceiling` can only be lower than physical memory minus 4 GiB; a higher one is refused when the call starts. + `stop_margin` must be above 0 and below `ceiling`. +- A `watchdog=` keyword on every model class. It takes a `WatchdogConfig` or `None`, and `None` turns the watchdog off. + Anything else is refused when the model is built. +- The record is a JSON file written with mode 0600. By default it goes in a private `mlx-dfloat` folder under the temp + directory, which is set to owner-only access; with `artifact_dir=` it goes in the folder you name. +- The watchdog needs `psutil`, which the `[mflux]` extra installs. + +### Behaviour of a trip + +- A memory trip has no grace period. The process ends only if memory reaches the hard line (exit 70), as the command + does. +- Memory the process already holds before the call counts toward both lines. A call that starts at or above the stop + line raises at once, before it does any work. +- Two stretches have no checkpoint: loading the text encoder together with the first prompt encoding (for ERNIE-Image with guidance, the prompt and the negative prompt are encoded together), and decoding the image. + A memory jump past both lines inside one of them ends the process at the hard line. If the call crossed the stop line + during the decode, the finished image is discarded and the call raises instead of returning it. +- There is no time limit by default. Set `wall_budget` in `WatchdogConfig` to add one. When it passes, the call raises at + the next checkpoint, and if none comes within `grace` seconds (10 by default) the process ends with exit 71. The same + grace applies if the watchdog cannot read memory: the process ends with exit 70 rather than run unwatched. +- These exits are immediate. Open files are not flushed and no cleanup handlers run. + +### Not yet checked + +- The abort has not yet been run on real weights on a Mac. The tests use small models and fake memory readings. + ## [0.2.2] - 2026-11-13 0.2.2 moves `mlx-dfloat[mflux]` to mflux 0.24 or newer, so it installs next to current mflux and the other mlx-* libraries. If @@ -424,7 +466,8 @@ The first release. - CI's mflux lane gets the Hub token for its test step only, so the three tokenizer tests against the gated FLUX.1 bases run there instead of skipping. -[Unreleased]: https://github.com/IonDen/mlx-dfloat/compare/v0.2.2...HEAD +[Unreleased]: https://github.com/IonDen/mlx-dfloat/compare/v0.2.3...HEAD +[0.2.3]: https://github.com/IonDen/mlx-dfloat/compare/v0.2.2...v0.2.3 [0.2.2]: https://github.com/IonDen/mlx-dfloat/compare/v0.2.1...v0.2.2 [0.2.1]: https://github.com/IonDen/mlx-dfloat/compare/v0.2.0...v0.2.1 [0.2.0]: https://github.com/IonDen/mlx-dfloat/compare/v0.1.0...v0.2.0 diff --git a/README.md b/README.md index 6c226e4..56672d1 100644 --- a/README.md +++ b/README.md @@ -303,9 +303,40 @@ image.save("lighthouse.png") FLUX.1-dev and FLUX.1-Krea-dev want more steps; the measured runs below used 20 steps and `guidance=3.5`. `base_path=` takes the `--base` value, and `fit_check=False` replaces `--no-fit-check` (see below). From Python, each `generate_image` call runs under the same memory caps as `mlx-dfloat generate` and puts MLX's limits back when it -returns; a wired limit your process already set is left alone. Only the `mlx-dfloat generate` command stops a run that -goes over the memory limit; the Python classes set memory caps but do not stop the process. Prefer the command on a Mac -near its memory limit. +returns; a wired limit your process already set is left alone. + +From 0.2.3, each call also runs under a memory watchdog. It has a hard line (the ceiling: physical memory minus 4 GiB +unless you lower it) and a stop line 1 GiB below the hard line (physical memory minus 5 GiB by default). Once the +process passes the stop line, the call raises `DFloatWatchdogError` at its next checkpoint. A checkpoint is a place where +the call can stop cleanly, such as between transformer blocks. The call frees what it loaded before it raises. The error +carries the path of the record when one was written, and your process keeps running. + +`mlx-dfloat generate` has no stop line. It ends at the hard line (exit code 70) or at its time limit (exit code 71). The +model classes use a watchdog built like the command's that also raises at the stop line. + +A memory trip has no grace period. The process ends only if memory reaches the hard line, with exit code 70 as the +command does. Memory the process already holds before the call counts toward both lines. A call that starts at or above +the stop line raises at once, before it does any work. + +Two stretches have no checkpoint: loading the text encoder together with the first prompt encoding (for ERNIE-Image with guidance, the prompt and the negative prompt are encoded together), and decoding the image. +If memory jumps past both lines inside one of them, the process ends at the hard line. If the call crossed the stop line +during the decode, the finished image is discarded and the call raises instead of returning it. + +There is no time limit unless you set `wall_budget=` in `WatchdogConfig`. If you do and the limit passes, the call raises +at its next checkpoint. If none comes within `grace` seconds (10 by default), the process ends with exit code 71. The +same grace applies when the watchdog cannot read memory: the process ends with exit code 70 rather than run unwatched. + +These exits are immediate. Open files are not flushed and no cleanup handlers run. + +To turn the watchdog off, pass `watchdog=None` to the model class. To move the lines, pass +`watchdog=WatchdogConfig(ceiling=..., stop_margin=...)`, with `WatchdogConfig` imported from `mlx_dfloat.mflux`. The +`watchdog=` keyword takes a `WatchdogConfig` or `None`, and the model class refuses anything else when you build it. +Values are in bytes. `ceiling` can only be lower than physical memory minus 4 GiB; a higher one is refused when the call +starts. `stop_margin` must be above 0 and below `ceiling`. `artifact_dir` takes a string or a path. + +The record is a JSON file written with mode 0600. By default it goes in a private `mlx-dfloat` folder under the temp +directory, which is set to owner-only access; with `artifact_dir=` it goes in the folder you name. The watchdog needs +`psutil`, which the `[mflux]` extra installs. Measured on an M1 Max at 1024², one image per model, with the commands under "Measured numbers": FLUX.1-schnell (4 steps, macOS 27.0.1, mflux 0.23.0) peaked at 19.77 GiB, FLUX.1-dev (20 steps, guidance 3.5) at 19.96 GiB and diff --git a/pyproject.toml b/pyproject.toml index c90ab2f..60c50eb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -202,6 +202,11 @@ omit = [ ] [tool.coverage.report] -exclude_lines = ["pragma: no cover", "if TYPE_CHECKING:", "@overload", "raise NotImplementedError"] +exclude_lines = [ + "pragma: no cover", "if TYPE_CHECKING:", "@overload", "raise NotImplementedError", + # scripts/prove_api_watchdog.py: the one function that builds a FLUX.2 Klein model on the GPU, never + # run by a test; the orchestrator around it is tested through a fake unit runner. + "^def run_unit\\(", +] show_missing = true fail_under = 85 diff --git a/scripts/_api_watchdog_proof.py b/scripts/_api_watchdog_proof.py new file mode 100644 index 0000000..59c8597 --- /dev/null +++ b/scripts/_api_watchdog_proof.py @@ -0,0 +1,278 @@ +"""The pure parts of the API watchdog's hardware proof: per-phase ceilings, unit verdicts and resume. + +Standard library only: ``python -m scripts.prove_api_watchdog --help`` and the orchestrator import this +without loading MLX or mflux. + +Units: U0 is the baseline generate, which also samples the watched memory per phase. U1-U4 each stop a +call in one phase (encode, set load, denoise, VAE decode) by a raise at a checkpoint; U5 sets the VAE +ceiling 64 MiB above its stop line, so the process ends by escalation (exit 70). U6 stops a call in set +load, reads the watched memory once the stopped call has cleaned up (it must be back under the stop +line, so the set and encoder pages were released), and then runs the baseline call again in the same +process, with its stop line 1 GiB over the baseline's overall peak: the weights reload and the image +completes under that line. + +The proof must end with exit 0 (every unit passes) before the release is tagged. +""" + +import threading +from collections.abc import Callable, Mapping +from pathlib import Path +from typing import Any + +UNITS = ("U0", "U1", "U2", "U3", "U4", "U5", "U6") +PHASE_OF = { + "U1": "encode", + "U2": "set_load", + "U3": "denoise", + "U4": "vae", + "U5": "vae", + "U6": "set_load", +} +"""The phase each stopping unit targets.""" + +_SET_LOAD_SITES = frozenset({"set_load_start", "set_group"}) +_SITES = { + "U1": frozenset({"encoder_loaded", "prompt_encoded"}), + "U2": _SET_LOAD_SITES, + "U3": frozenset({"block_start", "block_end"}), + "U4": frozenset({"call_end"}), + "U6": _SET_LOAD_SITES, +} +"""The checkpoints a unit's raise may stop at; U5 passes only by an exit.""" + +HEADROOM = 410 * 1024**2 +"""Bytes kept between a line and the peaks on either side of it: at least 0.4 GiB, since the committed +records of one recipe differ by about 0.3 GiB between runs.""" + +RETRY_HEADROOM = 1024**3 +"""Bytes between U6's retry line and the baseline's overall peak: 1 GiB, wider than the run-to-run spread +of the call-wide peak (up to 0.44 GiB between records), still under the stopped call's set groups (about +2.8 GiB), so a retained set trips it.""" + +_ORDER = ("encode", "set_load", "denoise", "vae") +_BOUNDARY = ("footprint_start", "mlx_peak", "footprint_end") +_EXIT_MEMORY = 70 + + +def _whole(record: Mapping[str, int]) -> int: + """Everything seen in or just after a phase: its boundary readings and its sampled peaks.""" + keys = (*_BOUNDARY, "watched_peak", "watched_after") + return max(record.get(key, 0) for key in keys) + + +def _own(phase: str, record: Mapping[str, int]) -> int: + """The phase's own peak. + + Set load leaves out its start and sampled peak: in the baseline it opens on the text encoder's + footprint, which a pre-encoded, settled unit no longer holds. + """ + if phase == "set_load": + return max(record.get("mlx_peak", 0), record.get("footprint_end", 0)) + return max(record.get(key, 0) for key in (*_BOUNDARY, "watched_peak")) + + +def ceilings_for( + peaks: Mapping[str, Any], + *, + stop_margin: int, + headroom: int = HEADROOM, + settled: int | None = None, +) -> dict[str, tuple[int, int] | None]: + """Per phase, the ``(ceiling, stop_margin)`` that stops a call inside that phase, or None. + + ``peaks`` is a baseline's ``model.report()["peaks"]``, optionally with ``watched_peak`` (the sampled + maximum of footprint and MLX active + cache while the phase ran) and ``watched_after`` (the same + between its end and the next phase) per phase; other entries (the ``label``) are ignored. + + ``hi`` is the phase's own peak; ``lo`` is the highest memory the stopping unit holds before the phase: + the call's start footprint for encode; for set load ``settled`` (the unit's reading after its + pre-encode settled), else the encode's start footprint as a planning value; for denoise and the VAE + decode everything seen in the earlier phases the pre-encoded unit runs (set load, then denoise). + + A raise is placed when the margin exceeds twice the headroom: the stop line sits half a margin under + ``hi``, the ceiling half a margin over it, so the peak crosses the line and stays under the ceiling by + more than the headroom. Set load is the exception: it has a checkpoint before every group read and then + a tail with none (the last group and the non-block decode), so its stop line sits mid-climb, halfway + between ``lo`` and ``hi``, with the ceiling one margin over it; the climb crosses the line with groups + still to read, and the raise comes at the next group's checkpoint. A smaller margin cannot hold the peak + under the ceiling, so the line is placed for an exit: the stop line and the ceiling are centred between + ``lo`` and ``hi``. Either way the stop line must clear ``lo`` by more than the headroom (and an exit's + ceiling must stay as far under ``hi``), else the phase is not isolable (None). None too when a needed + record is missing. + """ + records = {name: peaks[name] for name in _ORDER if isinstance(peaks.get(name), Mapping)} + ceilings: dict[str, tuple[int, int] | None] = {} + for phase in _ORDER: + ceilings[phase] = None + lo = _low(phase, records, settled) + if phase not in records or lo is None: + continue + hi = _own(phase, records[phase]) + if stop_margin > 2 * headroom: + stop = (lo + hi) // 2 if phase == "set_load" else hi - stop_margin // 2 + fits = stop > lo + headroom + else: + # Centred: the ceiling sits at least as far under hi as the stop line sits over lo. + stop = (lo + hi - stop_margin) // 2 + fits = stop > lo + headroom + if fits: + ceilings[phase] = (stop + stop_margin, stop_margin) + return ceilings + + +def retry_line( + peaks: Mapping[str, Any], *, stop_margin: int, headroom: int = RETRY_HEADROOM +) -> tuple[int, int] | None: + """The ``(ceiling, stop_margin)`` for U6's second call, or None when ``peaks`` holds no phase record. + + The stop line sits ``headroom`` (1 GiB by default) over the baseline's overall watched peak (every boundary + reading and sampled field of every phase), the ceiling one margin over it. A second call that still holds + the stopped call's memory when it reaches its decode peak climbs past that line and trips, so U6 fails. + """ + records = [peaks[name] for name in _ORDER if isinstance(peaks.get(name), Mapping)] + if not records: + return None + stop = max(_whole(record) for record in records) + headroom + return stop + stop_margin, stop_margin + + +def _low(phase: str, records: Mapping[str, Mapping[str, int]], settled: int | None) -> int | None: + if phase == "set_load" and settled is not None: + return settled + if phase in ("encode", "set_load"): + encode = records.get("encode") + return None if encode is None else encode["footprint_start"] + earlier = ("set_load",) if phase == "denoise" else ("set_load", "denoise") + if any(p not in records for p in earlier): + return None + return max(_whole(records[p]) for p in earlier) + + +class PhasePeaks: + """The watched memory's maximum per phase, and in the stretch after each phase before the next opens.""" + + def __init__(self) -> None: + """Start with no samples.""" + self.peaks: dict[str, dict[str, int]] = {} + self._last: str | None = None + + def add(self, phase: str | None, watched: int) -> None: + """Count one sample taken while ``phase`` was open (None between phases; before any phase it is dropped).""" + if phase is not None: + self._last, key = phase, "watched_peak" + elif self._last is not None: + phase, key = self._last, "watched_after" + else: + return + record = self.peaks.setdefault(phase, {}) + record[key] = max(record.get(key, 0), watched) + + def into(self, peaks: Mapping[str, Any]) -> dict[str, Any]: + """``peaks`` with each phase record joined by its sampled fields (a copy).""" + merged = {k: dict(v) if isinstance(v, Mapping) else v for k, v in peaks.items()} + for phase, fields in self.peaks.items(): + if isinstance(merged.get(phase), dict): + merged[phase].update(fields) + return merged + + +class PhaseSampler: + """Samples ``read()`` every ``interval`` seconds on a thread, charging each sample to ``phase()``.""" + + def __init__( + self, read: Callable[[], int], phase: Callable[[], str | None], *, interval: float = 0.05 + ) -> None: + """Bind the watched-memory reader and the open-phase reader; nothing runs until ``start``.""" + self.sampled = PhasePeaks() + self._read, self._phase, self._interval = read, phase, interval + self._stop = threading.Event() + self._thread = threading.Thread(target=self._run, daemon=True, name="proof-phase-sampler") + + def sample(self) -> None: + """Take one sample now.""" + self.sampled.add(self._phase(), self._read()) + + def _run(self) -> None: + while not self._stop.wait(self._interval): + self.sample() + + def start(self) -> "PhaseSampler": + """Start sampling.""" + self._thread.start() + return self + + def stop(self) -> None: + """Stop sampling and take a last sample.""" + self._stop.set() + self._thread.join(timeout=1) + self.sample() + + +def unit_verdict(unit: str, outcome: Mapping[str, Any]) -> str: + """``"pass"``, ``"fail"`` or ``"not isolable"`` for one unit's finished record. + + ``outcome`` holds the unit process's ``exit_code``, its own ``result`` (None if it wrote none) and the + abort ``artifact`` found in its record folder (None if none). U0 passes when it completed and saved its + image. U1-U4 pass only on a memory-reason ``DFloatWatchdogError`` raised in the unit's phase at one of + its sites (U4 at ``call_end``: the finished image is discarded). U5 passes only on exit 70 with + escalation ``"ceiling"`` in the VAE decode. U6 passes on U2's raise, then ``watched_after_abort`` (the + watched memory once the stopped call cleaned up) under its own stop line, then a completed retry. A + grace exit is a fail: after a memory trip it means the sampler died. A unit whose ceiling could not be + derived is ``"not isolable"``, which is never a pass. + + Raises: + ValueError: ``unit`` is not one of U0-U6. + """ + if unit not in UNITS: + raise ValueError(f"unknown unit {unit!r}; the units are {', '.join(UNITS)}") + result = outcome.get("result") or {} + code = outcome.get("exit_code") + if unit == "U0": + done = code == 0 and result.get("completed") is True and result.get("image_saved") is True + return "pass" if done else "fail" + if "ceiling" in result and result["ceiling"] is None: + return "not isolable" + phase = PHASE_OF[unit] + if unit in _SITES: + raised = result.get("raised") or {} + stopped = ( + code == 0 + and raised.get("type") == "DFloatWatchdogError" + and raised.get("reason") == "memory" + and raised.get("phase") == phase + and raised.get("site") in _SITES[unit] + ) + if unit == "U6": + stopped = ( + stopped + and _released(result) + and (result.get("retry") or {}).get("completed") is True + ) + return "pass" if stopped else "fail" + artifact = outcome.get("artifact") or {} + ended_by_ceiling = ( + code == _EXIT_MEMORY + and artifact.get("reason") == "memory" + and (artifact.get("context") or {}).get("phase") == phase + and artifact.get("escalation") == "ceiling" + ) + return "pass" if ended_by_ceiling else "fail" + + +def _released(result: Mapping[str, Any]) -> bool: + """Whether the watched memory after the stopped call's cleanup is under the stop line the unit armed.""" + after = result.get("watched_after_abort") + line = result.get("ceiling") + if type(after) is not int or not isinstance(line, list) or len(line) != 2: + return False + ceiling, margin = line + return after < ceiling - margin + + +def pending_units(out_dir: Path) -> list[str]: + """The units in order whose finished record ``/.json`` does not exist yet. + + The record is written atomically when a unit ends, so its presence means the unit finished; a + leftover temporary file or a unit's own outcome file does not count. + """ + return [unit for unit in UNITS if not (out_dir / f"{unit}.json").is_file()] diff --git a/scripts/prove_api_watchdog.py b/scripts/prove_api_watchdog.py new file mode 100644 index 0000000..e69f042 --- /dev/null +++ b/scripts/prove_api_watchdog.py @@ -0,0 +1,433 @@ +"""Hardware proof that the Python API's watchdog stops a FLUX.2 Klein 4B call in each phase. + +Seven units, each in its own process (1024², 4 steps, seed 42, one fixed prompt, every call with a wall +budget): + +- U0 generates one image with the default watchdog and keeps ``model.report()["peaks"]``, with the + watched peak sampled per phase; +- U1 builds a fresh model with the encode ceiling derived from U0; +- U2-U5 encode the prompt first and let memory settle, then set the set-load, denoise or VAE-decode line + as ``model.watchdog`` and generate; U2's line uses its own settled reading. U1-U4 pass only on a raise + at a checkpoint of their phase: U4 at ``call_end``, which discards the finished image; +- U5 is U4 with the ceiling only 64 MiB above the stop line, so the process ends by escalation (exit 70); +- U6 is U2, then a reading of the watched memory once the stopped call has cleaned up, which must be under + the stop line (the set and encoder pages were released), then the same call again with its stop line + 1 GiB over U0's overall watched peak, which must complete: memory still held when the retry reaches its + decode peak trips that line. + +The proof must exit 0 before the release is tagged. + +``--orchestrate`` runs the pending units in order, one subprocess each, and writes ``/.json`` the +moment a unit ends (atomically): its exit code, the unit's own outcome, the abort record from +``/-artifacts/``, the verdict, and the versions, macOS version, commit and dirty flag. A stopping +unit that fails (by the run-to-run spread of its peaks, say) is run once more in the same run: its first +``.json``, outcome and abort records move into ``/earlier//``, the second attempt decides, +and its record names the first under ``first_attempt``. U0 and a unit found not isolable are never run +twice. A re-run skips every unit whose JSON exists. A failed U0 is kept as ``U0-failed-.json`` and +the run stops, so the next run repeats it. A U0 whose peaks place no ceiling for some unit is kept as +``U0-not-isolable-.json`` with the reason, and the run stops the same way before any other unit. +``--unit`` runs one unit in this process; the model is built only there. + +Commit only the ``.json`` files: they embed the abort record with the home directory written as +``~``. The raw ``-artifacts/`` and ``earlier/`` folders are not scrubbed and stay out of a commit. + +Exit codes: 0 every unit passed; 2 the baseline failed or left a unit not isolable, or a unit is recorded +not isolable; else 1 a unit failed. A unit process exits 0 when its outcome is written, and 70 or 71 when +the watchdog ended it. + + python -m scripts.prove_api_watchdog --orchestrate --out DIR +""" + +import argparse +import datetime +import json +import os +import platform +import subprocess +import sys +import time +from collections.abc import Callable +from importlib import metadata +from pathlib import Path +from typing import Any + +# Run as a file, Python puts scripts/ (not the repository root) first on sys.path. +_REPO = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(_REPO)) + +try: + from scripts._api_watchdog_proof import ( + PHASE_OF, + UNITS, + PhaseSampler, + ceilings_for, + pending_units, + retry_line, + unit_verdict, + ) + + from mlx_dfloat._scrub import scrub_home + from mlx_dfloat.mflux import WatchdogConfig +except Exception as exc: # a broken environment is a tool error (2), never a unit verdict (1) + print( + f"error: cannot import the project modules ({exc}); run from a synced checkout", + file=sys.stderr, + ) + raise SystemExit(2) from exc + +UnitRunner = Callable[..., "subprocess.CompletedProcess[Any]"] +"""Runs one unit command, as ``subprocess.run(cmd, cwd=..., check=False)`` does.""" +MODEL = "flux2-klein-4b" +PROMPT = "A lighthouse on a rocky coast at dusk, waves breaking below, warm light in the windows" +SEED = 42 +STEPS = 4 +SIZE = 1024 +WALL_S = 600.0 +ESCALATION_MARGIN = 64 * 1024**2 # U5: the VAE decode cannot stop inside, so it reaches the ceiling + + +def _write_json(path: Path, data: object) -> None: + """Write ``data`` as JSON through a temporary file and a rename, so the file is whole or absent. + + The home directory is written as ``~`` (the records are committed); values JSON cannot hold, such as + a ``Path``, become text first, so they are scrubbed too. + """ + plain = json.loads(json.dumps(data, default=repr)) + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(json.dumps(scrub_home(plain, home=str(Path.home())), indent=1)) + tmp.replace(path) + + +def _read_json(path: Path) -> Any: + try: + return json.loads(path.read_text()) + except (OSError, ValueError): + return None + + +def _git(*args: str) -> str | None: + try: + run = subprocess.run( + ["git", "-C", str(_REPO), *args], capture_output=True, text=True, check=True + ) + except (OSError, subprocess.CalledProcessError): + return None + return run.stdout.strip() + + +def _version(dist: str) -> str | None: + try: + return metadata.version(dist) + except metadata.PackageNotFoundError: + return None + + +def _sysctl(name: str) -> str | None: + try: + run = subprocess.run(["sysctl", "-n", name], capture_output=True, text=True, check=True) + except (OSError, subprocess.CalledProcessError): + return None + return run.stdout.strip() + + +def provenance() -> dict[str, object]: + """Versions, hardware, date, commit and dirty flag (with the dirty files), without importing MLX or mflux.""" + status = _git("status", "--porcelain") + return { + "date": datetime.datetime.now(datetime.UTC).isoformat(timespec="seconds"), + "mlx": _version("mlx"), + "mflux": _version("mflux"), + "mlx_dfloat": _version("mlx-dfloat"), + "python": platform.python_version(), + "macos": platform.mac_ver()[0], + "hardware": { + "model": _sysctl("hw.model"), + "chip": _sysctl("machdep.cpu.brand_string"), + "memsize": _sysctl("hw.memsize"), + }, + "commit": _git("rev-parse", "HEAD"), + "dirty": None if status is None else bool(status), + "dirty_files": None if status is None else status.splitlines(), + } + + +def _latest_artifact(folder: Path) -> Any: + records = sorted(folder.glob("abort-*.json")) if folder.is_dir() else [] + return _read_json(records[-1]) if records else None + + +def _aside_folder(out: Path) -> Path: + """A new, empty ``/earlier/[-n]/`` folder: two set-asides never share one.""" + stamp = datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%S.%fZ") + (out / "earlier").mkdir(parents=True, exist_ok=True) + for n in range(1, 1000): + folder = out / "earlier" / (stamp if n == 1 else f"{stamp}-{n}") + try: + folder.mkdir() + except FileExistsError: + continue + return folder + raise RuntimeError(f"no free folder for {stamp} under {out / 'earlier'}") + + +def _set_aside(out: Path, unit: str, *, record: bool = False) -> Path | None: + """Move an attempt's outcome and abort records (and, with ``record``, its ``.json``) out of the way. + + Never deleted: they go into a new folder under ``/earlier/``, which is returned (None if nothing + was there to move). + """ + names = [f"{unit}.outcome.json", f"{unit}-artifacts"] + if record: + names.insert(0, f"{unit}.json") + leftovers = [out / name for name in names if (out / name).exists()] + if not leftovers: + return None + aside = _aside_folder(out) + for leftover in leftovers: + leftover.rename(aside / leftover.name) + return aside + + +def _not_isolable(peaks: Any) -> list[str]: + """The stopping units whose ceiling the baseline's ``peaks`` cannot place, derived as ``run_unit`` does.""" + peaks = peaks if isinstance(peaks, dict) else {} + default_margin = WatchdogConfig().stop_margin + blocked = [] + for unit, phase in PHASE_OF.items(): + margin = ESCALATION_MARGIN if unit == "U5" else default_margin + if ceilings_for(peaks, stop_margin=margin)[phase] is None: + blocked.append(unit) + return blocked + + +def _attempt( + out: Path, unit: str, *, model: str, wall: float, run: UnitRunner, facts: dict[str, object] +) -> dict[str, Any]: + """Run one unit process and return its record with the verdict (not yet written).""" + _set_aside(out, unit) + cmd = [sys.executable, "-m", "scripts.prove_api_watchdog", "--unit", unit] + cmd += ["--out", str(out), "--model", model, "--wall", str(wall)] + start = time.monotonic() + code = run(cmd, cwd=_REPO, check=False).returncode + record: dict[str, Any] = { + "unit": unit, + "model": model, + "exit_code": code, + "unit_s": time.monotonic() - start, + "result": _read_json(out / f"{unit}.outcome.json"), + "artifact": _latest_artifact(out / f"{unit}-artifacts"), + **facts, + } + record["verdict"] = unit_verdict(unit, record) + print(f"{unit}: {record['verdict']} (exit {code})", flush=True) + return record + + +def orchestrate(out: Path, *, model: str, wall: float, run: UnitRunner = subprocess.run) -> int: + """Run the pending units as subprocesses in order; write each unit's record as it ends. + + ``run`` starts one unit process (``subprocess.run`` by default). A stopping unit that fails is run once + more: its first record, outcome and abort records move into a new ``earlier//`` folder, the second + attempt's verdict decides, and its record names the first under ``first_attempt``. U0 and a unit found + not isolable are never run twice. + + Returns 0 when every unit passed, 2 when any unit is recorded not isolable (whenever it was found), else + 1 when one failed. A failed baseline, or one that leaves a unit not isolable, returns 2 at once: no other + unit runs and the baseline is kept as ``U0-failed-.json`` or ``U0-not-isolable-.json``, so + the next run repeats it. + """ + out.mkdir(parents=True, exist_ok=True) + facts = provenance() + for unit in pending_units(out): + record = _attempt(out, unit, model=model, wall=wall, run=run, facts=facts) + if unit != "U0" and record["verdict"] == "fail": + _write_json(out / f"{unit}.json", record) # on record before the second attempt + aside = _set_aside(out, unit, record=True) + assert aside is not None # the record was just written + record = _attempt(out, unit, model=model, wall=wall, run=run, facts=facts) + record["first_attempt"] = { + "record": (aside / f"{unit}.json").relative_to(out).as_posix(), + "verdict": "fail", + } + if unit == "U0" and record["verdict"] != "pass": + stamp = datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%SZ") + _write_json(out / f"U0-failed-{stamp}.json", record) + return 2 + if unit == "U0" and (blocked := _not_isolable((record["result"] or {}).get("peaks"))): + record["not_isolable"] = blocked + record["reason"] = ( + f"the baseline's peaks place no ceiling for {', '.join(blocked)}; " + "no other unit was run" + ) + print(f"U0: {record['reason']}", flush=True) + stamp = datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%SZ") + _write_json(out / f"U0-not-isolable-{stamp}.json", record) + return 2 + _write_json(out / f"{unit}.json", record) + verdicts = {u: (_read_json(out / f"{u}.json") or {}).get("verdict") for u in UNITS} + print(json.dumps(verdicts), flush=True) + if "not isolable" in verdicts.values(): + return 2 + return 0 if all(v == "pass" for v in verdicts.values()) else 1 + + +def run_unit(unit: str, out: Path, *, model: str, wall: float) -> int: + """Run one unit in this process; the only place a model is built. Never called by a test.""" + outcome_path = out / f"{unit}.outcome.json" + result: dict[str, Any] = {"unit": unit, "model": model, "raised": None} + result.update(completed=False, image_saved=False) + stop_margin = ESCALATION_MARGIN if unit == "U5" else WatchdogConfig().stop_margin + peaks: Any = None + ceiling: tuple[int, int] | None = None + if unit != "U0": + baseline = _read_json(out / "U0.json") or {} + if baseline.get("verdict") != "pass": + raise SystemExit(f"{unit}: no passed baseline at {out / 'U0.json'}; run U0 first") + peaks = baseline["result"]["peaks"] + # U2 and U6 place their final line after the settle below; this one is the plan. + ceiling = ceilings_for(peaks, stop_margin=stop_margin)[PHASE_OF[unit]] + result["ceiling"] = None if ceiling is None else list(ceiling) + # On record before the call, in case the call ends the process. + _write_json(outcome_path, result) + if unit != "U0" and ceiling is None: + return 0 + + from mlx_dfloat._memory_caps import install_memory_caps + from mlx_dfloat._watchdog import phys_footprint, read_counters, watched_memory + from mlx_dfloat.errors import DFloatWatchdogError + from mlx_dfloat.mflux._drain import drain + from mlx_dfloat.mflux.families import family_of + + def watched() -> int: + """The number the watchdog compares with its lines: max(footprint, MLX active + cache).""" + counters = read_counters() + return watched_memory( + footprint=counters.footprint, + mlx_active=counters.mlx_active, + mlx_cache=counters.mlx_cache, + )[0] + + def stopping(line: tuple[int, int]) -> WatchdogConfig: + ceiling_bytes, margin = line + return WatchdogConfig( + ceiling=ceiling_bytes, stop_margin=margin, wall_budget=wall, artifact_dir=artifacts + ) + + def raised(exc: DFloatWatchdogError) -> dict[str, Any]: + return { + "type": type(exc).__name__, + "reason": exc.reason, + "phase": exc.phase, + "site": exc.site, + "escalation": exc.record.get("escalation"), + "elapsed": exc.record.get("elapsed"), + "checkpoint_latency_s": exc.record.get("checkpoint_latency_s"), + "artifact": None if exc.artifact is None else str(exc.artifact), + } + + def generate() -> Any: + return pipe.generate_image( + seed=SEED, prompt=PROMPT, num_inference_steps=STEPS, height=SIZE, width=SIZE + ) + + result["caps_gb"] = list(install_memory_caps()) + artifacts = out / f"{unit}-artifacts" + default = WatchdogConfig(wall_budget=wall, artifact_dir=artifacts) + factory = family_of(model).load_model_class() + # U1: the text encoder loads lazily, so its whole climb lands in the one evaluation between + # `encoder_loaded` and `prompt_encoded`; the line sits under the encode's top and the call raises at + # `prompt_encoded`, its ceiling above the top. + pipe = factory(model, watchdog=stopping(ceiling) if unit == "U1" and ceiling else default) + if unit not in ("U0", "U1"): + pipe.encode(PROMPT) # pre-encoded: these units must not stop in encode + drain(phys_footprint) # settle: synchronize, clear, a kick, a 0.25 s poll of the footprint + result["settled"] = watched() + if unit in ("U2", "U6"): + line = ceilings_for(peaks, stop_margin=stop_margin, settled=result["settled"]) + ceiling = line[PHASE_OF[unit]] + result["ceiling"] = None if ceiling is None else list(ceiling) + _write_json(outcome_path, result) + if ceiling is None: + return 0 + pipe.watchdog = stopping(ceiling) + sampler = None + if unit == "U0": # the watched peak per phase, which the boundary readings can miss + sampler = PhaseSampler(watched, lambda: getattr(pipe, "open_phase", None)).start() + start = time.monotonic() + try: + image = generate() + except DFloatWatchdogError as exc: + result["raised"] = raised(exc) + result["record"] = exc.record + if unit == "U6": # the stopped call has cleaned up; its set and encoder pages must be gone + result["watched_after_abort"] = watched() + else: + result["completed"] = True + if unit == "U0": + png = out / "U0.png" + image.save(str(png), export_json_metadata=False, overwrite=True) + result["image_saved"] = png.is_file() + finally: + if sampler is not None: + sampler.stop() + result["call_s"] = time.monotonic() - start + if sampler is not None and result["completed"]: + result["peaks"] = sampler.sampled.into(pipe.report()["peaks"]) + if unit == "U6" and result["raised"] is not None: + _write_json(outcome_path, result) # the abort on record before the retry + # the baseline call again, in this process, under a line 1 GiB over U0's overall peak: memory still + # held when the retry reaches its decode peak trips it, so U6 fails + again = retry_line(peaks, stop_margin=WatchdogConfig().stop_margin) + result["retry_ceiling"] = None if again is None else list(again) + pipe.watchdog = default if again is None else stopping(again) + retry: dict[str, Any] = {"completed": False, "raised": None} + start = time.monotonic() + try: + generate() + except DFloatWatchdogError as exc: + retry["raised"] = raised(exc) + else: + retry["completed"] = True + retry["call_s"] = time.monotonic() - start + result["retry"] = retry + result["pid"] = os.getpid() + _write_json(outcome_path, result) + return 0 + + +def parse_args(argv: list[str] | None) -> argparse.Namespace: + """Parse the command line: one ``--unit`` or ``--orchestrate``, with ``--out``.""" + p = argparse.ArgumentParser( + prog="python -m scripts.prove_api_watchdog", + description="Prove on this Mac that the API watchdog stops a FLUX.2 Klein 4B call in each phase.", + ) + mode = p.add_mutually_exclusive_group(required=True) + mode.add_argument("--unit", choices=UNITS, help="run one unit in this process") + mode.add_argument( + "--orchestrate", action="store_true", help="run the pending units, one subprocess each" + ) + p.add_argument("--out", type=Path, required=True, help="folder for the unit records") + p.add_argument( + "--model", choices=(MODEL,), default=MODEL, help="the model (default %(default)s)" + ) + p.add_argument( + "--wall", + type=float, + default=WALL_S, + help="wall budget per call, seconds (default %(default)s)", + ) + return p.parse_args(argv) + + +def main(argv: list[str] | None = None, *, run: UnitRunner = subprocess.run) -> int: + """Run one unit or orchestrate them all.""" + args = parse_args(argv) + args.out = args.out.resolve() # the unit processes run from the repository root + if args.orchestrate: + return orchestrate(args.out, model=args.model, wall=args.wall, run=run) + args.out.mkdir(parents=True, exist_ok=True) + return run_unit(args.unit, args.out, model=args.model, wall=args.wall) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/verify_image.py b/scripts/verify_image.py index 9cf650f..ef7f363 100644 --- a/scripts/verify_image.py +++ b/scripts/verify_image.py @@ -485,7 +485,11 @@ def run_df11(args: argparse.Namespace, watchdog: Watchdog) -> dict[str, Any]: out_dir = args.out / "df11" out_dir.mkdir(parents=True, exist_ok=True) model = DFloatFlux1( - args.model, df11_path=args.df11, base_path=args.base, eval_policy=args.eval_policy + args.model, + df11_path=args.df11, + base_path=args.base, + eval_policy=args.eval_policy, + watchdog=None, ) capture = _LatentCapture() model.callbacks.register(capture) @@ -624,7 +628,11 @@ def run_df11_zimage(args: argparse.Namespace, watchdog: Watchdog) -> dict[str, A out_dir = args.out / "df11" out_dir.mkdir(parents=True, exist_ok=True) model = DFloatZImage( - args.model, df11_path=args.df11, base_path=args.base, eval_policy=args.eval_policy + args.model, + df11_path=args.df11, + base_path=args.base, + eval_policy=args.eval_policy, + watchdog=None, ) capture = _LatentCapture() model.callbacks.register(capture) @@ -781,7 +789,11 @@ def run_df11_flux2(args: argparse.Namespace, watchdog: Watchdog) -> dict[str, An out_dir = args.out / "df11" out_dir.mkdir(parents=True, exist_ok=True) model = DFloatFlux2Klein( - args.model, df11_path=args.df11, base_path=args.base, eval_policy=args.eval_policy + args.model, + df11_path=args.df11, + base_path=args.base, + eval_policy=args.eval_policy, + watchdog=None, ) capture = _LatentCapture() model.callbacks.register(capture) @@ -957,7 +969,11 @@ def run_df11_qwen21(args: argparse.Namespace, watchdog: Watchdog) -> dict[str, A out_dir = args.out / "df11" out_dir.mkdir(parents=True, exist_ok=True) model = DFloatQwenImage21( - args.model, df11_path=args.df11, base_path=args.base, eval_policy=args.eval_policy + args.model, + df11_path=args.df11, + base_path=args.base, + eval_policy=args.eval_policy, + watchdog=None, ) capture = _LatentCapture() model.callbacks.register(capture) @@ -1153,7 +1169,11 @@ def run_df11_ernie(args: argparse.Namespace, watchdog: Watchdog) -> dict[str, An out_dir = args.out / "df11" out_dir.mkdir(parents=True, exist_ok=True) model = DFloatErnieImage( - args.model, df11_path=args.df11, base_path=args.base, eval_policy=args.eval_policy + args.model, + df11_path=args.df11, + base_path=args.base, + eval_policy=args.eval_policy, + watchdog=None, ) capture = _LatentCapture() model.callbacks.register(capture) @@ -1305,7 +1325,11 @@ def run_df11_krea2(args: argparse.Namespace, watchdog: Watchdog) -> dict[str, An out_dir = args.out / "df11" out_dir.mkdir(parents=True, exist_ok=True) model = DFloatKrea2( - args.model, df11_path=args.df11, base_path=args.base, eval_policy=args.eval_policy + args.model, + df11_path=args.df11, + base_path=args.base, + eval_policy=args.eval_policy, + watchdog=None, ) capture = _LatentCapture() model.callbacks.register(capture) diff --git a/src/mlx_dfloat/__init__.py b/src/mlx_dfloat/__init__.py index b38b3e8..cbb7f07 100644 --- a/src/mlx_dfloat/__init__.py +++ b/src/mlx_dfloat/__init__.py @@ -11,6 +11,7 @@ DFloatResourceError, DFloatUnsupportedError, DFloatUntestedMfluxWarning, + DFloatWatchdogError, ) __all__ = [ @@ -23,5 +24,6 @@ "DFloatResourceError", "DFloatUnsupportedError", "DFloatUntestedMfluxWarning", + "DFloatWatchdogError", "__version__", ] diff --git a/src/mlx_dfloat/_guard.py b/src/mlx_dfloat/_guard.py new file mode 100644 index 0000000..e134012 --- /dev/null +++ b/src/mlx_dfloat/_guard.py @@ -0,0 +1,146 @@ +"""The call guard: which watchdog watches the running call, and the checkpoints that stop it. + +A watched call runs inside ``scope(watchdog)``, which makes the watchdog the active one for that +call's context and resets it on the way out, also after a raise. ``checkpoint(site)`` is called at +the boundaries where the main thread runs Python (a transformer block, a prompt's encode, a group +of the set load). It does nothing unless the active watchdog has tripped; then it stops the +watchdog's grace clock and raises ``DFloatWatchdogError`` naming the site. + +The watchdog is typed by a ``Protocol``, so this module does not import the watchdog's. +""" + +import contextlib +import contextvars +import typing + +from mlx_dfloat.errors import DFloatWatchdogError + +_GIB = 1024**3 + + +class _Flag(typing.Protocol): + def is_set(self) -> bool: ... + + +class GuardedWatchdog(typing.Protocol): + """What the guard reads and calls on a raise-mode watchdog.""" + + @property + def tripped(self) -> _Flag: + """Set once the stop line was crossed.""" + ... + + @property + def trip(self) -> dict[str, typing.Any] | None: + """The trip's record, or None before a trip.""" + ... + + @property + def artifact(self) -> typing.Any: + """The path the record was written to, or None.""" + ... + + @property + def ceiling(self) -> int: + """The ceiling in bytes.""" + ... + + def consume(self) -> None: + """Stop the grace clock.""" + ... + + def set_ceiling(self, ceiling: int) -> int: + """Replace the ceiling; return the previous one.""" + ... + + +_ACTIVE: contextvars.ContextVar[GuardedWatchdog | None] = contextvars.ContextVar( + "mlx_dfloat_watchdog", default=None +) + + +def active() -> GuardedWatchdog | None: + """The watchdog watching the running call, or None.""" + return _ACTIVE.get() + + +@contextlib.contextmanager +def scope(watchdog: GuardedWatchdog) -> typing.Iterator[None]: + """Make ``watchdog`` the active one for the block; the previous one is back afterward.""" + token = _ACTIVE.set(watchdog) + try: + yield + finally: + _ACTIVE.reset(token) + + +@contextlib.contextmanager +def tightened(ceiling: int | None) -> typing.Iterator[None]: + """Lower the active watchdog's ceiling to ``ceiling`` for the block, then restore it. + + Nothing changes when no watchdog is active, when ``ceiling`` is None, or when it is not + lower than the active one: the lower ceiling wins. + """ + watchdog = _ACTIVE.get() + if watchdog is None or ceiling is None or ceiling >= watchdog.ceiling: + yield + return + previous = watchdog.set_ceiling(ceiling) + try: + yield + finally: + watchdog.set_ceiling(previous) + + +def checkpoint(site: str) -> None: + """Raise if the active watchdog has tripped; a no-op otherwise. + + The ``encoder_loaded`` checkpoint runs before the text encoder's weights land: the encoder + loads lazily and its weights arrive in the first prompt's evaluation. So loading the encoder + and encoding the first prompt form one stretch with no checkpoint between them. + + Raises: + DFloatWatchdogError: The active watchdog tripped. Its grace clock is stopped first, so + the cleanup that follows the error cannot be ended by the clock. + """ + watchdog = _ACTIVE.get() + if watchdog is None or not watchdog.tripped.is_set(): + return + watchdog.consume() + raise error_for(watchdog, site) + + +def _gib(value: object) -> str: + return f"{value / _GIB:.2f} GiB" if isinstance(value, int | float) else "unread" + + +def _seconds(value: object) -> str: + return f"{value:.1f} s" if isinstance(value, int | float) else "unread" + + +def error_for(watchdog: GuardedWatchdog, site: str) -> DFloatWatchdogError: + """The error a checkpoint raises for ``watchdog``'s trip, stopped at ``site``.""" + record = dict(watchdog.trip or {}) + reason = str(record.get("reason")) + phase = (record.get("context") or {}).get("phase") + artifact = watchdog.artifact + where = f"record: {artifact}" if artifact is not None else "record not written" + if reason == "wall": + measured = ( + f"ran {_seconds(record.get('elapsed'))} against the wall budget of " + f"{_seconds(record.get('budget'))}" + ) + else: + measured = ( + f"watched {_gib(record.get('verdict_memory'))} against the stop line " + f"{_gib(record.get('stop_line'))}" + ) + message = f"the memory watchdog stopped the call at {site} ({reason}, phase {phase}): {measured}; {where}" + return DFloatWatchdogError( + message, + reason=reason, + phase=None if phase is None else str(phase), + site=site, + artifact=artifact, + record=record, + ) diff --git a/src/mlx_dfloat/_watchdog.py b/src/mlx_dfloat/_watchdog.py index 170e89f..787b1e5 100644 --- a/src/mlx_dfloat/_watchdog.py +++ b/src/mlx_dfloat/_watchdog.py @@ -18,15 +18,17 @@ until a sample has read MLX's counters. """ +import contextlib import ctypes import json import os import sys +import tempfile import threading import time from collections.abc import Callable, Mapping from pathlib import Path -from typing import Any +from typing import Any, Literal, NamedTuple import mlx.core as mx @@ -95,6 +97,29 @@ def phys_footprint() -> int: return int(info.ri_phys_footprint) +class Counters(NamedTuple): + """One reading of the four numbers a sample records, in bytes.""" + + footprint: int + rss: int + mlx_active: int + mlx_cache: int + + +def read_counters() -> Counters: + """Read this process's footprint, RSS, and MLX active and cache memory. + + Raises: + DFloatDependencyError: ``psutil`` is not installed. + """ + return Counters( + footprint=int(phys_footprint()), + rss=int(_psutil().Process().memory_info().rss), + mlx_active=int(mx.get_active_memory()), + mlx_cache=int(mx.get_cache_memory()), + ) + + def watched_memory(*, footprint: int, mlx_active: int, mlx_cache: int) -> tuple[int, str]: """The number the ceiling is enforced against and which counter produced it. @@ -107,15 +132,40 @@ def watched_memory(*, footprint: int, mlx_active: int, mlx_cache: int) -> tuple[ return (footprint, "footprint") if footprint >= mlx else (mlx, "mlx") -def verdict(*, memory: int, ceiling: int, elapsed: float, budget: float) -> str | None: - """Decide whether to abort: "memory", "wall", or None. ``memory`` is ``watched_memory``'s number.""" +def verdict(*, memory: int, ceiling: int, elapsed: float, budget: float | None) -> str | None: + """Decide whether to abort: "memory", "wall", or None. ``memory`` is ``watched_memory``'s number. + + A ``budget`` of None has no wall limit. + """ if memory > ceiling: return "memory" - if elapsed > budget: + if budget is not None and elapsed > budget: return "wall" return None +def _write_private(path: Path, text: str) -> None: + """Write ``text`` to ``path`` through a private temp file in the same folder, then rename it over ``path``. + + The temp file is created 0600 by ``tempfile.mkstemp``, and the rename replaces whatever sits at ``path`` + (a symlink included) without following it, so the write never reaches another file. The temp name starts + with a dot and ends in ``.tmp``, so it never matches the record's own name pattern. + + Raises: + OSError: the folder cannot be created, or the write or the rename failed (the temp file is removed). + """ + path.parent.mkdir(parents=True, exist_ok=True) + fd, temp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp") + try: + with os.fdopen(fd, "w") as handle: + handle.write(text) + Path(temp).replace(path) + except BaseException: + with contextlib.suppress(OSError): + Path(temp).unlink() + raise + + def default_ceiling() -> int: """Physical memory minus a 4 GiB reserve for the OS and other processes. @@ -126,20 +176,51 @@ def default_ceiling() -> int: class Watchdog: - """Background sampler that aborts the process with an honest artifact.""" + """Background sampler that aborts the process with an honest artifact. + + In raise mode a trip and an escalation can land on the same sample: one jump past both the + stop line and the ceiling (or a ``set_ceiling`` below the current number) trips and exits 70 + at once, so no checkpoint gets to raise. + """ def __init__( self, out_dir: Path, *, ceiling: int, - budget: float, + budget: float | None, interval: float = 0.05, context: Mapping[str, Any] | None = None, live_context: Mapping[str, Callable[[], Any]] | None = None, + counters: Callable[[], Counters] | None = None, + exit_process: Callable[[int], object] | None = None, + artifact_name: str = "abort.json", + mode: Literal["exit", "raise"] = "exit", + stop_margin: int = 0, + grace: float = 10.0, ) -> None: """Configure the ceiling (bytes), wall budget (seconds), poll interval and run context. + A ``budget`` of None has no wall limit and is recorded as ``null``. + + ``mode="exit"`` (the command's) ends the process at the first verdict. ``mode="raise"`` + trips instead at the stop line ``ceiling - stop_margin``: it writes the record, sets + ``trip``, ``artifact`` and ``tripped``, and keeps sampling. It then ends the process when + the watched number reaches ``ceiling`` (always 70: memory ends it, even after a wall + trip), with one line on stderr naming the record. ``grace`` is a second backstop for the + trips where no number holds the line: a wall trip, or any trip whose latest sample failed. + For those, the process also ends when ``consume()`` has not been called within ``grace`` + seconds (the trip's code: 71 after a wall trip, 70 otherwise). The seconds count from the + trip, except after a memory trip: there they count from the first failed sample, and start + over when a later sample reads memory again. A memory trip whose samples still read memory + never ends by grace, however long the stretch to the next checkpoint takes; it ends only at + ``ceiling``. + + ``counters`` reads the numbers each sample checks; None means ``read_counters``. + ``exit_process`` ends the process with the abort's code; None means the module's + ``_exit`` alias, looked up when the abort fires. The artifact is written to + ``out_dir / artifact_name``. + ``context`` (JSON-serialisable) is written verbatim under ``"context"`` in the abort artifact; None writes no ``"context"`` key. Each ``live_context`` reader is called when the abort fires and its value joins ``"context"`` under its key (a reader that raises @@ -163,7 +244,18 @@ def __init__( # Held while an abort is written: stop() waits for it, so no abort can land after the # caller has stopped the watchdog and written its own verdict. self._lock = threading.Lock() - self._thread = threading.Thread(target=self._run, daemon=True) + self._counters, self._exit_process = counters, exit_process + self.artifact_name = artifact_name + self.mode, self.stop_margin, self.grace = mode, stop_margin, grace + # Raise mode: set once, under the lock, when the stop line is first crossed. + self.tripped = threading.Event() + self.trip: dict[str, Any] | None = None + self.artifact: Path | None = None + self._trip_time: float | None = None + # Raise mode, after a trip: when the current run of failed samples began (None while live). + self._failed_since: float | None = None + self._consumed = False + self._thread = threading.Thread(target=self._run, daemon=True, name="mlx-dfloat-watchdog") self._start = time.monotonic() def start(self) -> "Watchdog": @@ -200,11 +292,9 @@ def _sample(self) -> tuple[str | None, dict[str, float | str | None]]: "verdict_counter": "none", } try: - footprint = int(phys_footprint()) + footprint, rss, active, cache = (self._counters or read_counters)() sample["footprint"] = footprint - sample["rss"] = int(self._psutil.Process().memory_info().rss) - active = int(mx.get_active_memory()) - cache = int(mx.get_cache_memory()) + sample["rss"] = rss sample["mlx_active"] = active sample["mlx_cache"] = cache memory, counter = watched_memory( @@ -217,7 +307,10 @@ def _sample(self) -> tuple[str | None, dict[str, float | str | None]]: self.peak_mlx = max(self.peak_mlx or 0, active + cache) self.peak_watched = max(self.peak_watched, memory) reason = verdict( - memory=memory, ceiling=self.ceiling, elapsed=elapsed, budget=self.budget + memory=memory, + ceiling=self.ceiling - self.stop_margin, + elapsed=elapsed, + budget=self.budget, ) except Exception: # a dead sampler must still abort, not run the job unwatched reason = "sample_error" @@ -225,11 +318,191 @@ def _sample(self) -> tuple[str | None, dict[str, float | str | None]]: def _run(self) -> None: while not self._stop.wait(self.interval): - reason, sample = self._sample() - if reason is not None: - self._fire(reason, sample) + if self.mode == "exit": + reason, sample = self._sample() + if reason is not None: + self._fire(reason, sample) + return + continue + try: + ended = self._raise_step() + except Exception as exc: # a dead sampler must never leave the call running unwatched + ended = self._fail_closed(exc) + if ended: return + def _raise_step(self) -> bool: + """One raise-mode sample: trip at the stop line, then the backstop. True once the process ended.""" + reason, sample = self._sample() + if self.trip is None and reason is not None: + self._trip(reason, sample) + return self.trip is not None and self._backstop(sample) + + def _fail_closed(self, exc: Exception) -> bool: + """Treat a raise-mode step that raised as a failed sample, after a trip. + + Without a trip yet, a ``sample_error`` trip is set here, with no record written (the record or + its write may be what raised), so the next checkpoint raises. The sample then counts as failed, + so the failed-sample grace ends the process (70) if the samples keep failing and no checkpoint + takes the trip. True once the process ended. + """ + failed: dict[str, float | str | None] = { + "footprint": 0, + "rss": 0, + "mlx_active": 0, + "mlx_cache": 0, + "elapsed": time.monotonic() - self._start, + "verdict_memory": None, + "verdict_counter": "none", + } + with self._lock: + if self._stop.is_set(): + return True # stopped: the caller owns the outcome + if self.trip is None: + self.trip = { + "reason": "sample_error", + **{ + key: failed[key] for key in ("elapsed", "verdict_memory", "verdict_counter") + }, + "ceiling": self.ceiling, + "budget": self.budget, + "stop_line": self.ceiling - self.stop_margin, + "mode": "raise", + "escalation": None, + "checkpoint_latency_s": None, + "loop_error": f"{type(exc).__name__}: {exc}", + } + self._trip_time = time.monotonic() + self.tripped.set() + try: + return self._backstop(failed) + except Exception: # the next step tries again; the loop itself never dies + return False + + def consume(self) -> None: + """Stop the grace clock: a checkpoint has taken the trip. A no-op before a trip. + + Records the time from the trip to this call as ``trip["checkpoint_latency_s"]``. The + ceiling check stays on until ``stop()``. + """ + with self._lock: + if self.trip is None or self._trip_time is None or self._consumed: + return + self._consumed = True + self.trip["checkpoint_latency_s"] = time.monotonic() - self._trip_time + + def set_ceiling(self, ceiling: int) -> int: + """Replace the ceiling (bytes), under the lock; returns the previous one.""" + with self._lock: + previous, self.ceiling = self.ceiling, ceiling + return previous + + def _record(self, reason: str, sample: dict[str, float | str | None]) -> dict[str, Any]: + """The abort record (exit mode's whole artifact). Called with ``_lock`` held.""" + record: dict[str, Any] = { + "reason": reason, + "footprint": sample["footprint"], + "peak_footprint": self.peak_footprint, + "ceiling": self.ceiling, + "elapsed": sample["elapsed"], + "budget": self.budget, + "rss": sample["rss"], + "mlx_active": sample["mlx_active"], + "mlx_cache": sample["mlx_cache"], + "verdict_memory": sample.get("verdict_memory"), + "verdict_counter": sample.get("verdict_counter", "none"), + "peak_watched": self.peak_watched, + "peak_mlx": self.peak_mlx, + } + if self.context is not None or self.live_context is not None: + record["context"] = {**(self.context or {}), **self._read_live()} + return record + + def _write(self, record: dict[str, Any]) -> Path | None: + """Write ``record`` to the artifact path; on failure note it in the record and return None.""" + try: + path = self.out_dir / self.artifact_name + _write_private(path, json.dumps(record, indent=1)) + except Exception as exc: # a failed write never costs the trip or the exit + record["artifact_error"] = f"{type(exc).__name__}: {exc}" + return None + return path + + def _trip(self, reason: str, sample: dict[str, float | str | None]) -> None: + with self._lock: + if self._stop.is_set(): + return # the caller already stopped us + record = self._record(reason, sample) + record.update( + stop_line=self.ceiling - self.stop_margin, + mode="raise", + escalation=None, + checkpoint_latency_s=None, + ) + self.artifact = self._write(record) + self.trip, self._trip_time = record, time.monotonic() + self.tripped.set() + + def _backstop(self, sample: dict[str, float | str | None]) -> bool: + """After a trip: escalate at the ceiling, or past grace with no checkpoint. True if ended. + + Grace applies only to a wall trip or when this sample failed: while the samples carry a + number, a memory trip ends the process at the ceiling and nowhere else. The grace clock + starts at the trip, except after a memory trip, where it starts at the first failed sample + and resets when a sample reads a number again. + """ + memory = sample["verdict_memory"] # None after a sample error: only grace applies + if isinstance(memory, (int, float)) and memory >= self.ceiling: + return self._escalate("ceiling") + now = time.monotonic() + if memory is not None: + self._failed_since = None # the sampler recovered: the failed-sample clock resets + elif self._failed_since is None: + self._failed_since = now + reason = None if self.trip is None else self.trip["reason"] + graced = memory is None or reason == "wall" + # After a memory trip the clock bounds how long a dead sampler runs unwatched, so it starts at + # the first failed sample; after a wall or sample-error trip it starts at the trip. + since = self._failed_since if reason == "memory" else self._trip_time + if graced and not self._consumed and since is not None and now - since > self.grace: + return self._escalate("grace") + return False + + def _escalate(self, escalation: str) -> bool: + with self._lock: + if self._stop.is_set() or self.trip is None: + return True # stopped: the caller owns the outcome + if escalation == "grace" and self._consumed: + return False # a checkpoint took the trip while this sample was read + record = {k: v for k, v in self.trip.items() if k != "artifact_error"} + record["escalation"] = escalation + # Memory ends the process at the ceiling, whatever tripped first; grace keeps the trip's code. + wall = escalation == "grace" and record["reason"] == "wall" + try: + path = self._write(record) + self.trip = record + if path is not None: + self.artifact = path + where = f"record: {path}" + else: + carried = json.dumps(record, default=repr) + where = f"record not written ({record['artifact_error']}): {carried}" + phase = (record.get("context") or {}).get("phase") + # The line names what ended the process: memory at the ceiling ends it whatever tripped first. + ended_by = ( + f"memory ceiling after a {record['reason']} trip" + if escalation == "ceiling" and record["reason"] != "memory" + else record["reason"] + ) + print( + f"mlx-dfloat: the memory watchdog ended the process ({ended_by}, phase {phase}); {where}", + file=sys.stderr, + flush=True, + ) + finally: + (self._exit_process or _exit)(EXIT_WALL if wall else EXIT_MEMORY) + return True + def _read_live(self) -> dict[str, Any]: values: dict[str, Any] = {} for key, read in (self.live_context or {}).items(): @@ -245,24 +518,8 @@ def _fire(self, reason: str, sample: dict[str, float | str | None]) -> None: return # the caller already stopped us and recorded its own result code = EXIT_WALL if reason == "wall" else EXIT_MEMORY try: - self.out_dir.mkdir(parents=True, exist_ok=True) - artifact: dict[str, Any] = { - "reason": reason, - "footprint": sample["footprint"], - "peak_footprint": self.peak_footprint, - "ceiling": self.ceiling, - "elapsed": sample["elapsed"], - "budget": self.budget, - "rss": sample["rss"], - "mlx_active": sample["mlx_active"], - "mlx_cache": sample["mlx_cache"], - "verdict_memory": sample.get("verdict_memory"), - "verdict_counter": sample.get("verdict_counter", "none"), - "peak_watched": self.peak_watched, - "peak_mlx": self.peak_mlx, - } - if self.context is not None or self.live_context is not None: - artifact["context"] = {**(self.context or {}), **self._read_live()} - (self.out_dir / "abort.json").write_text(json.dumps(artifact, indent=1)) + artifact = self._record(reason, sample) + _write_private(self.out_dir / self.artifact_name, json.dumps(artifact, indent=1)) finally: - _exit(code) # always exits, even if the artifact write above raised + # Always exits, even if the artifact write above raised. + (self._exit_process or _exit)(code) diff --git a/src/mlx_dfloat/errors.py b/src/mlx_dfloat/errors.py index fa86f6c..cb7e236 100644 --- a/src/mlx_dfloat/errors.py +++ b/src/mlx_dfloat/errors.py @@ -1,5 +1,10 @@ """Package-rooted exceptions for mlx-dfloat.""" +import functools +from collections.abc import Mapping +from pathlib import Path +from typing import Any + class DFloatError(Exception): """Base class for every error raised by mlx-dfloat.""" @@ -13,6 +18,48 @@ class DFloatResourceError(DFloatError, MemoryError): """A decode would need more memory than the configured budget allows.""" +class DFloatWatchdogError(DFloatResourceError): + """A watched call stopped at a checkpoint because the watchdog tripped. + + Attributes: + reason: ``"memory"``, ``"wall"`` or ``"sample_error"``. + phase: The phase the trip happened in, or None when no phase was running. + site: The checkpoint where the call stopped. + artifact: The abort record written to disk, or None when none was written. + record: The abort record's contents. + """ + + def __init__( + self, + message: str, + *, + reason: str, + phase: str | None, + site: str, + artifact: Path | None, + record: Mapping[str, Any], + ) -> None: + """Keep the trip's fields next to the message.""" + super().__init__(message) + self.reason = reason + self.phase = phase + self.site = site + self.artifact = artifact + self.record: dict[str, Any] = dict(record) + + def __reduce__(self) -> tuple[Any, ...]: + """Pickle with the keyword-only fields, which the default exception pickling drops.""" + rebuild = functools.partial( + type(self), + reason=self.reason, + phase=self.phase, + site=self.site, + artifact=self.artifact, + record=self.record, + ) + return (rebuild, self.args) + + class DFloatBackendError(DFloatError): """A decode backend is unavailable here or its kernel cannot run.""" @@ -47,4 +94,5 @@ class DFloatUntestedMfluxWarning(UserWarning): "DFloatResourceError", "DFloatUnsupportedError", "DFloatUntestedMfluxWarning", + "DFloatWatchdogError", ] diff --git a/src/mlx_dfloat/integrate/coverage.py b/src/mlx_dfloat/integrate/coverage.py index a74a6a5..c8fb817 100644 --- a/src/mlx_dfloat/integrate/coverage.py +++ b/src/mlx_dfloat/integrate/coverage.py @@ -7,6 +7,7 @@ import mlx.core as mx from mlx.utils import tree_flatten +from mlx_dfloat import _guard from mlx_dfloat._safetensors import TensorInfo from mlx_dfloat.errors import DFloatFormatError, DFloatIntegrationError from mlx_dfloat.format import DF11Checkpoint, MxGroup, load_group_mx @@ -27,7 +28,11 @@ def load_resident_set( missing = [n for n in wanted if n not in ckpt.groups] if missing: raise DFloatIntegrationError(f"not groups of the checkpoint: {missing}") - return {name: load_group_mx(ckpt.groups[name]) for name in wanted} + resident: dict[str, MxGroup] = {} + for name in wanted: + _guard.checkpoint("set_group") # before the read: a tripped load reads no further group + resident[name] = load_group_mx(ckpt.groups[name]) + return resident def extras_plan( diff --git a/src/mlx_dfloat/integrate/seam.py b/src/mlx_dfloat/integrate/seam.py index 7672ce2..1ab8b11 100644 --- a/src/mlx_dfloat/integrate/seam.py +++ b/src/mlx_dfloat/integrate/seam.py @@ -7,6 +7,7 @@ import mlx.core as mx +from mlx_dfloat import _guard from mlx_dfloat.errors import DFloatIntegrationError from mlx_dfloat.integrate.names import Shapes from mlx_dfloat.integrate.placeholders import PLACEHOLDER, get_attr_path @@ -185,6 +186,7 @@ def run_block( shape does not match the block. """ shapes = state.shapes[block_name] + _guard.checkpoint("block_start") # nothing assigned yet: the placeholders are in place before: BeforeBlock | None = getattr(state.provider, "before_block", None) if before is not None: args, kwargs = ((), {}) if inputs is None else inputs @@ -208,6 +210,7 @@ def run_block( out = run() t_encode_end = time.perf_counter() _seam_eval(state, out) + _guard.checkpoint("block_end") # inside the try: the finally restores the placeholders if state.tracer is not None: state.tracer.record( block_name, diff --git a/src/mlx_dfloat/mflux/__init__.py b/src/mlx_dfloat/mflux/__init__.py index b7422d2..42031b5 100644 --- a/src/mlx_dfloat/mflux/__init__.py +++ b/src/mlx_dfloat/mflux/__init__.py @@ -4,6 +4,7 @@ from typing import Any from mlx_dfloat.errors import DFloatDependencyError +from mlx_dfloat.mflux._watchconfig import WatchdogConfig def require_mflux() -> None: @@ -68,4 +69,4 @@ def __getattr__(name: str) -> Any: # The model classes stay out of __all__: a star-import must not need mflux; `mlx_dfloat.mflux.DFloatFlux1`, # `mlx_dfloat.mflux.DFloatZImage`, `mlx_dfloat.mflux.DFloatFlux2Klein`, `mlx_dfloat.mflux.DFloatQwenImage21`, # `mlx_dfloat.mflux.DFloatErnieImage` and `mlx_dfloat.mflux.DFloatKrea2` still work. -__all__ = ["DFloatModel", "require_mflux"] +__all__ = ["DFloatModel", "WatchdogConfig", "require_mflux"] diff --git a/src/mlx_dfloat/mflux/_drain.py b/src/mlx_dfloat/mflux/_drain.py new file mode 100644 index 0000000..71cf6ed --- /dev/null +++ b/src/mlx_dfloat/mflux/_drain.py @@ -0,0 +1,59 @@ +"""The drain an armed call runs after it frees memory, so the process footprint has fallen before the next sample. + +A buffer MLX releases leaves the process footprint only after the next GPU submission (about 20 ms with the GPU busy, +80-700 ms idle). An armed call's watchdog samples that footprint, so freed pages that linger can trip it at the next +checkpoint. The drain waits for the GPU, empties MLX's buffer pool, submits one tiny evaluation, and polls the footprint +until it has fallen at least ``FALL_BYTES`` below the first reading and then stopped falling, for at most ``budget_s`` +seconds (before that fall, a flat reading is the late release on an idle GPU and a smaller move is page-level noise, so +neither ends the poll); then it waits and empties the pool once more, since the tiny evaluation's own buffers reach the +pool when its command completes. +""" + +import math +import time +from collections.abc import Callable + +import mlx.core as mx + +POLL_S = 0.02 +# The smallest fall below the first reading that counts as the release. An idle footprint moves by a few pages +# (dips of 352 KiB and rises of 32 KiB were seen), far less than a released buffer. +FALL_BYTES = 1 << 20 +# Looked up at call time, so a test can record the waits. +_sleep: Callable[[float], object] = time.sleep + + +def _kick() -> None: + """One tiny GPU evaluation: the driver frees released buffers after the next command submission.""" + mx.eval(mx.zeros((1,)) + 0) + + +def drain( + read_footprint: Callable[[], int], + *, + budget_s: float = 0.25, + sleep: Callable[[float], object] | None = None, +) -> None: + """Wait for the GPU, empty the pool, kick, poll the footprint until its fall ends (``budget_s`` at most), then again. + + ``read_footprint`` returns the process footprint in bytes. The poll waits ``POLL_S`` seconds between readings. + Until a reading is at least ``FALL_BYTES`` below the first one, the poll goes on; after that, it ends at the first + reading that is not below the one before. It ends after ``budget_s`` seconds of waits in any case. ``sleep`` + replaces the module's sleep (``time.sleep``). + """ + wait = _sleep if sleep is None else sleep + mx.synchronize() + mx.clear_cache() + _kick() + first = last = read_footprint() + fell = False + for _ in range(math.floor(budget_s / POLL_S + 1e-9)): + wait(POLL_S) + now = read_footprint() + if fell and now >= last: + break + if first - now >= FALL_BYTES: + fell = True + last = now + mx.synchronize() + mx.clear_cache() diff --git a/src/mlx_dfloat/mflux/_pipeline.py b/src/mlx_dfloat/mflux/_pipeline.py index 2beefcb..730dcff 100644 --- a/src/mlx_dfloat/mflux/_pipeline.py +++ b/src/mlx_dfloat/mflux/_pipeline.py @@ -5,24 +5,44 @@ decode. The family supplies its measured numbers (``PhaseConstants``) and sizes; nothing here imports mflux. """ +import contextlib +import datetime import functools +import gc +import inspect import logging import math +import os +import platform +import stat +import sys +import tempfile +import traceback import warnings from collections.abc import Callable, Iterator, Mapping from contextlib import contextmanager +from importlib import metadata +from pathlib import Path from typing import Any, NoReturn, ParamSpec, TypeVar import mlx.core as mx +from mlx_dfloat import _guard from mlx_dfloat._memory_caps import ( caps_for_recommended_bytes, known_wired_limit, remember_wired_limit, ) -from mlx_dfloat._watchdog import phys_footprint -from mlx_dfloat.errors import DFloatResourceError, DFloatUnsupportedError +from mlx_dfloat._watchdog import ( + Counters, + Watchdog, + default_ceiling, + phys_footprint, + read_counters, +) +from mlx_dfloat.errors import DFloatResourceError, DFloatUnsupportedError, DFloatWatchdogError from mlx_dfloat.integrate.memory import CallPlan +from mlx_dfloat.mflux import _drain from mlx_dfloat.mflux._phases import ( FamilySizes, PhaseConstants, @@ -30,6 +50,7 @@ cache_limit_for, fit_for, ) +from mlx_dfloat.mflux._watchconfig import check_watchdog_arg def refuse(name: str, reason: str) -> NoReturn: @@ -94,6 +115,183 @@ def refuse_precision_args(*, float32: bool, compute_precision: Any) -> None: refuse("float32", "the float32 transformer stream") +# What an armed call's watchdog reads, looked up at call time so tests can put fakes in front of them: the counter +# reader, the host's default ceiling in bytes, and the process exit (None: the watchdog module's own ``_exit``). +_counters: Callable[[], Counters] = read_counters +_default_ceiling: Callable[[], int] = default_ceiling +_exit_process: Callable[[int], object] | None = None + + +def _artifact_root() -> Path: + """The folder an armed call writes its abort record to when its config names none.""" + return Path(tempfile.gettempdir()) / "mlx-dfloat" + + +def _artifact_name() -> str: + """A record name unique per abort: ``abort-Z-.json``.""" + stamp = datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%S%f") + return f"abort-{stamp}Z-{os.getpid()}.json" + + +def clear_call_frames(exc: BaseException, *, outer: BaseException | None) -> None: + """Release the locals of the frames ``exc`` and every exception in its chain (causes and contexts) passed through. + + ``outer`` is the exception the caller was already handling when the call began (``sys.exc_info()`` at entry): the + walk stops there, so the caller's own frames keep their locals. A seen-set ends a chain that loops back. + """ + seen: set[int] = set() if outer is None else {id(outer)} + pending: list[BaseException] = [exc] + while pending: + current = pending.pop() + if id(current) in seen: + continue + seen.add(id(current)) + if current.__traceback__ is not None: + traceback.clear_frames(current.__traceback__) + pending.extend(e for e in (current.__cause__, current.__context__) if e is not None) + + +def _versions() -> dict[str, str | None]: + """The mlx and mflux versions (mflux None when it is not installed).""" + try: + mflux: str | None = metadata.version("mflux") + except metadata.PackageNotFoundError: + mflux = None + return {"mlx": mx.__version__, "mflux": mflux} # type: ignore[attr-defined] + + +_CALL_FIELDS = ("seed", "height", "width", "num_inference_steps", "guidance") + + +def _call_context( + model: Any, method: Callable[..., Any], args: tuple[Any, ...], kwargs: dict[str, Any] +) -> dict[str, Any]: + """What the abort record says about the call: model, class, method, the size and seed arguments, versions.""" + context: dict[str, Any] = { + "model": getattr(model, "_model", None), + "class": type(model).__name__, + "method": method.__name__, + } + try: + bound = inspect.signature(method).bind(*args, **kwargs) + bound.apply_defaults() + except TypeError: # the method itself will refuse these arguments + arguments: dict[str, Any] = {} + else: + arguments = bound.arguments + for name in _CALL_FIELDS: + if name in arguments: + value = arguments[name] + context[name] = ( + value if value is None or isinstance(value, int | float) else repr(value) + ) + context["versions"] = _versions() + context["macos"] = platform.mac_ver()[0] + return context + + +def _private_root_refusal(root: Path) -> str | None: + """Make the default record folder private (0o700); why it cannot be trusted, or None when it can. + + The default folder sits under the shared temp dir, where another user could have placed it first: a symlink, or a + folder that user owns, is refused. + """ + with contextlib.suppress(FileExistsError): + root.mkdir(mode=0o700) + info = os.lstat(root) + if stat.S_ISLNK(info.st_mode): + return f"the record folder {root} is a symlink; nothing was written" + if not stat.S_ISDIR(info.st_mode): + return f"the record folder {root} is not a folder; nothing was written" + if info.st_uid != os.getuid(): + return f"the record folder {root} is owned by uid {info.st_uid}, not this user; nothing was written" + # An own folder made earlier with a looser mode is made private too. + root.chmod(0o700) + return None + + +class _DefaultFolderWatchdog(Watchdog): + """The watchdog of a call whose config names no folder: it writes only into a private folder this user owns.""" + + def _write(self, record: dict[str, Any]) -> Path | None: + try: + refusal = _private_root_refusal(self.out_dir) + # This runs on the sampler thread: a failed check costs the record, never the trip. + except Exception as exc: + refusal = f"{type(exc).__name__}: {exc}" + if refusal is not None: + record["artifact_error"] = refusal + return None + return super()._write(record) + + +def _trip_at_arm(watchdog: Watchdog) -> None: + """One reading before the sampler starts: at or above the stop line, drain, read again, and trip if still there. + + Memory the process already holds counts, so a call that starts over the line stops at ``call_start`` before any + work. Pages an earlier call freed leave the footprint only after the next GPU submission, so a first reading at or + above the line is followed by the drain (``_drain.drain``) and a second reading, and only that second one decides. + A call below the line makes one reading and no drain. A reading that fails leaves the call to the sampler. Uses + the watchdog's own sample and trip, so the record is the one a sampled trip writes. + + Raises: + DFloatWatchdogError: The reading after the drain is at or above the stop line. + """ + + def over_the_line() -> dict[str, float | str | None] | None: + _reason, sample = watchdog._sample() + memory = sample["verdict_memory"] + if not isinstance(memory, int | float) or memory < watchdog.ceiling - watchdog.stop_margin: + return None + return sample + + if over_the_line() is None: + return + _drain.drain(lambda: _counters().footprint) + sample = over_the_line() + if sample is None: + return + watchdog._trip("memory", sample) + with _guard.scope(watchdog): + _guard.checkpoint("call_start") + + +def _after_abort(model: Any, exc: BaseException, *, outer: BaseException | None) -> None: + """Free what the stopped call held: its frames' locals, MLX's buffer pool, then the compressed set if resident. + + The pool is emptied in every case, also when the stop came during the set load (the groups loaded so far are + freed into it), after waiting for the GPU so no free is still pending. It ends with the drain (``_drain.drain``): + one tiny evaluation, then a poll of the footprint while it falls, for 0.25 s at most, and a last clear. Each step + runs on its own: a step that fails is attached to ``exc`` as a note and the next step still runs, so ``exc`` is + never replaced. + """ + + def drop_set() -> None: + lifecycle = getattr(model, "_lifecycle", None) + if lifecycle is not None and lifecycle.set_resident: + try: + lifecycle.drop_set() + except DFloatResourceError as reclaim: + exc.add_note( + "dropping the compressed set after the abort failed: " + f"{type(reclaim).__name__}: {reclaim}" + ) + + steps: list[tuple[str, Callable[[], object]]] = [ + ("clearing the call's frames", lambda: clear_call_frames(exc, outer=outer)), + ("waiting for the GPU", mx.synchronize), + ("collecting garbage", gc.collect), + ("emptying the buffer pool", mx.clear_cache), + ("dropping the compressed set", drop_set), + ("draining the footprint", lambda: _drain.drain(lambda: _counters().footprint)), + ] + for what, step in steps: + try: + step() + except Exception as failure: + exc.add_note(f"{what} after the abort failed: {type(failure).__name__}: {failure}") + + _wired_refusal_warned = False @@ -156,12 +354,110 @@ def call_caps(limits: Any = mx) -> Iterator[tuple[int, int]]: def with_call_caps(method: Callable[_P, _R]) -> Callable[_P, _R]: - """Wrap a model's ``generate_image`` or ``encode`` in ``call_caps``: the whole call runs capped.""" + """Wrap a model's ``generate_image`` or ``encode`` in ``call_caps`` and the model's memory watchdog. + + The outermost decorated call arms a raise-mode watchdog from ``model.watchdog`` (a ``WatchdogConfig``; None runs + unwatched) and makes it the active guard; a nested decorated call (an ``encode`` inside ``generate_image``, or + another model's call) arms none and only lowers the active ceiling for its own duration when its config's is + lower. Before the sampler starts, one reading of memory (what the process already holds counts): at or above the + stop line the call raises at ``call_start`` before the method runs, after the abort cleanup below (which drops a + set an earlier call left resident). After the method returns, one more checkpoint + (``call_end``) catches a trip in a phase with none; the watchdog then stops, and a trip that landed between that + checkpoint and the stop raises too, so no abort record is ever left behind a normal return. On + ``DFloatWatchdogError`` the call's frames are cleared, MLX's buffer pool is emptied and a resident compressed set + is dropped before the error leaves; another error that leaves a tripped call gets the same cleanup and a note + naming the trip and its record. The watchdog stops in every case. + + Raises: + DFloatWatchdogError: Memory crossed the stop line, at the arm-time reading or by a checkpoint. + DFloatUnsupportedError: The config's ceiling is above the host's default ceiling (RAM minus 4 GiB), or its + stop margin is not below the ceiling in force (the host's when the config names none); refused before + anything runs. + """ @functools.wraps(method) def capped(*args: _P.args, **kwargs: _P.kwargs) -> _R: + model = args[0] + # Checked again here: ``model.watchdog`` is reassignable after the constructor's check. + config = check_watchdog_arg(getattr(model, "watchdog", None)) + if config is not None: + host = _default_ceiling() + if config.ceiling is not None and config.ceiling > host: + raise DFloatUnsupportedError( + f"watchdog ceiling {config.ceiling} bytes is above this Mac's ceiling of {host} bytes " + "(its memory minus 4 GiB)" + ) + ceiling = host if config.ceiling is None else config.ceiling + if config.stop_margin >= ceiling: + raise DFloatUnsupportedError( + f"watchdog stop margin {config.stop_margin} bytes is not below the ceiling of {ceiling} " + "bytes" + ) + if _guard.active() is not None: + with call_caps(), _guard.tightened(None if config is None else config.ceiling): + return method(*args, **kwargs) + if config is None: + with call_caps(): + return method(*args, **kwargs) + outer = sys.exc_info()[1] + # A folder the caller names is used as given; the default one, under the shared temp dir, is checked. + watchdog_class = Watchdog if config.artifact_dir else _DefaultFolderWatchdog + watchdog = watchdog_class( + config.artifact_dir or _artifact_root(), + ceiling=_default_ceiling() if config.ceiling is None else config.ceiling, + budget=config.wall_budget, + mode="raise", + stop_margin=config.stop_margin, + grace=config.grace, + counters=_counters, + exit_process=_exit_process, + artifact_name=_artifact_name(), + context=_call_context(model, method, args, kwargs), + live_context={"phase": lambda: getattr(model, "open_phase", None)}, + ) + try: + # Before the sampler, the caps and the method: nothing has run yet. + _trip_at_arm(watchdog) + except DFloatWatchdogError as exc: + # The same cleanup as any abort: a set left resident by an earlier call would keep every later call over + # the line. + _after_abort(model, exc, outer=outer) + raise with call_caps(): - return method(*args, **kwargs) + try: + watchdog.start() # inside the try: an interrupt right after the start still stops it + with _guard.scope(watchdog): + try: + result = method(*args, **kwargs) + _guard.checkpoint("call_end") + watchdog.stop() + # A trip after the checkpoint, before the stop: raise it, never a record behind a return. + if watchdog.tripped.is_set(): + del result + _guard.checkpoint("call_end") + except DFloatWatchdogError as exc: + _after_abort(model, exc, outer=outer) + raise + except Exception as exc: + # Stopped first, as on the return path: no trip lands after the check below. + watchdog.stop() + if watchdog.tripped.is_set(): + trip = watchdog.trip or {} + phase = (trip.get("context") or {}).get("phase") + where = ( + "record not written" + if watchdog.artifact is None + else f"record: {watchdog.artifact}" + ) + exc.add_note( + "the memory watchdog had tripped before this error " + f"({trip.get('reason')}, phase {phase}); {where}" + ) + _after_abort(model, exc, outer=outer) + raise + finally: + watchdog.stop() + return result return capped diff --git a/src/mlx_dfloat/mflux/_watchconfig.py b/src/mlx_dfloat/mflux/_watchconfig.py new file mode 100644 index 0000000..18f5c2b --- /dev/null +++ b/src/mlx_dfloat/mflux/_watchconfig.py @@ -0,0 +1,94 @@ +"""The watchdog settings a model call runs under. + +Standard library only, so ``import mlx_dfloat.mflux`` still loads neither MLX nor mflux. +""" + +import os +from dataclasses import dataclass +from pathlib import Path + +from mlx_dfloat.errors import DFloatUnsupportedError + + +@dataclass(frozen=True, slots=True, kw_only=True) +class WatchdogConfig: + """How the watchdog guards a model call. + + Memory values are in bytes. A checkpoint is a place where the call can stop cleanly, such as between + transformer blocks. + + Attributes: + ceiling: The memory ceiling in bytes. None means the Mac's RAM minus 4 GiB, read at call time. A ceiling + can only be lower than that: a higher one is refused when the call starts. + stop_margin: Bytes below the ceiling at which the call stops at its next checkpoint. It must be above 0 + and below the ceiling. + grace: Seconds the call may take to reach a checkpoint after a wall-time trip, or after a trip when the + latest memory reading failed (counted from the first failed sample when the trip was on memory). A + memory trip with live readings has no grace: the process ends only at the ceiling. + wall_budget: Seconds the whole call may take, or None for no wall limit. + artifact_dir: Folder for the abort record, a str or a path (stored as a ``Path``). None means + ``Path(tempfile.gettempdir()) / "mlx-dfloat"``. A record file is written when a trip happens, unless + the write fails or the default folder is refused (a symlink, not a folder, or owned by another user); + the error then says "record not written". The folder is created only when a trip happens. + """ + + ceiling: int | None = None + stop_margin: int = 1_073_741_824 + grace: float = 10.0 + wall_budget: float | None = None + artifact_dir: Path | None = None + + def __post_init__(self) -> None: + """Refuse a value the watchdog cannot work with. + + Raises: + DFloatUnsupportedError: a ceiling of 0 or less, a stop margin of 0 or less, a stop margin not below an + explicit ceiling, a grace of 0 or less, a wall budget of 0 or less, or an artifact folder that is + neither a str nor a path. + """ + folder: object = self.artifact_dir + if folder is not None and not isinstance(folder, Path): + text = os.fspath(folder) if isinstance(folder, str | os.PathLike) else None + if not isinstance(text, str): + raise DFloatUnsupportedError( + f"WatchdogConfig.artifact_dir must be a str or a path, got {type(folder).__name__}" + ) + object.__setattr__(self, "artifact_dir", Path(text)) + if self.ceiling is not None and self.ceiling <= 0: + raise DFloatUnsupportedError( + f"WatchdogConfig.ceiling must be above 0 bytes, got {self.ceiling}" + ) + if self.stop_margin <= 0: + raise DFloatUnsupportedError( + f"WatchdogConfig.stop_margin must be above 0 bytes, got {self.stop_margin}" + ) + if self.ceiling is not None and self.stop_margin >= self.ceiling: + raise DFloatUnsupportedError( + f"WatchdogConfig.stop_margin ({self.stop_margin}) must be below the ceiling " + f"({self.ceiling})" + ) + if self.grace <= 0: + raise DFloatUnsupportedError( + f"WatchdogConfig.grace must be above 0 seconds, got {self.grace}" + ) + if self.wall_budget is not None and self.wall_budget <= 0: + raise DFloatUnsupportedError( + f"WatchdogConfig.wall_budget must be above 0 seconds, got {self.wall_budget}" + ) + + +DEFAULT_WATCHDOG = WatchdogConfig() + + +def check_watchdog_arg(value: object) -> WatchdogConfig | None: + """Return a model's ``watchdog`` argument unchanged when it is None or a ``WatchdogConfig``. + + Raises: + DFloatUnsupportedError: any other value, such as ``False``, ``True`` or a dict. + """ + if value is None or isinstance(value, WatchdogConfig): + return value + raise DFloatUnsupportedError( + f"watchdog must be a WatchdogConfig, or watchdog=None to turn the watchdog off; " + f"got {type(value).__name__} {value!r}" + ) diff --git a/src/mlx_dfloat/mflux/ernie/model.py b/src/mlx_dfloat/mflux/ernie/model.py index 7c58807..d0c062e 100644 --- a/src/mlx_dfloat/mflux/ernie/model.py +++ b/src/mlx_dfloat/mflux/ernie/model.py @@ -33,6 +33,7 @@ from mlx_dfloat.mflux import families as registry from mlx_dfloat.mflux._compile import uncompiled from mlx_dfloat.mflux._phases import FamilySizes +from mlx_dfloat.mflux._watchconfig import DEFAULT_WATCHDOG, WatchdogConfig, check_watchdog_arg from mlx_dfloat.mflux.ernie import init as einit from mlx_dfloat.mflux.ernie import memory as emem from mlx_dfloat.mflux.ernie.init import ErnieComponents, ResolvedRepo @@ -117,6 +118,7 @@ def __init__( cache_limit: int | None = None, fit_check: bool = True, budget_bytes: int | None = None, + watchdog: WatchdogConfig | None = DEFAULT_WATCHDOG, quantize: int | None = None, lora_paths: list[str] | None = None, lora_scales: list[float] | None = None, @@ -129,9 +131,15 @@ def __init__( package was checked against; a user's own paths are taken as given. ``budget_bytes`` replaces the device's budget in every call's fit estimate and VAE decision. + ``watchdog`` is the memory and wall-time watchdog each ``generate_image`` and ``encode`` + call runs under, kept as ``model.watchdog`` and reassignable between calls; None runs + the calls with no watchdog. The ``mlx-dfloat`` command has its own watchdog, which this + setting does not change. + Raises: DFloatUnsupportedError: ``quantize``, ``lora_paths``, ``lora_scales`` or ``bake_lora=False`` (accepted only - to refuse), an eval policy other than ``"per-block"`` / ``"depth2"``, or an unknown ``model``. + to refuse), an eval policy other than ``"per-block"`` / ``"depth2"``, an unknown ``model``, or a + ``watchdog`` that is neither a ``WatchdogConfig`` nor None. DFloatBackendError: The GPU decoder fails its check on the two packaged self-check groups (raised before anything is resolved or loaded), or Metal is unavailable. DFloatFormatError: The checkpoint is not an ERNIE-Image DF11 checkpoint, its block count differs from the @@ -141,6 +149,7 @@ def __init__( DFloatIntegrationError: mflux's own weight definition or mapping does not shape the way this adapter expects. """ + check_watchdog_arg(watchdog) _pipeline.refuse_construction_args( quantize=quantize, lora_paths=lora_paths, lora_scales=lora_scales, bake_lora=bake_lora ) @@ -178,6 +187,7 @@ def __init__( cache_limit=cache_limit, fit_check=fit_check, budget_bytes=budget_bytes, + watchdog=watchdog, ) @classmethod @@ -203,6 +213,7 @@ def _assemble( cache_limit: int | None = None, fit_check: bool = True, budget_bytes: int | None = None, + watchdog: WatchdogConfig | None = DEFAULT_WATCHDOG, decode: Callable[[MxGroup], DecodeResult] | None = None, ) -> None: from mflux.models.ernie_image.ernie_image_initializer import ErnieImageInitializer @@ -234,6 +245,7 @@ def _assemble( fit_check, ) self._budget_override = budget_bytes + self.watchdog = watchdog self._provider: DF11Provider | None = None self._plan: CallPlan | None = None self._tracker = _pipeline.PhaseTracker() diff --git a/src/mlx_dfloat/mflux/flux1/model.py b/src/mlx_dfloat/mflux/flux1/model.py index 800ba88..b050d18 100644 --- a/src/mlx_dfloat/mflux/flux1/model.py +++ b/src/mlx_dfloat/mflux/flux1/model.py @@ -4,7 +4,7 @@ metadata run unchanged; only construction and the prelude of ``generate_image`` differ. The text encoders and the compressed transformer are never resident together (see ``lifecycle``). Each ``generate_image`` call runs under the memory caps the ``mlx-dfloat`` command installs (unless a wired -limit is already in force) and restores MLX's limits afterwards; only the command adds a watchdog. +limit is already in force) and restores MLX's limits afterwards. """ import logging @@ -31,6 +31,7 @@ from mlx_dfloat.integrate.providers import DF11Provider from mlx_dfloat.mflux import _pipeline, require_mflux from mlx_dfloat.mflux import families as registry +from mlx_dfloat.mflux._watchconfig import DEFAULT_WATCHDOG, WatchdogConfig, check_watchdog_arg from mlx_dfloat.mflux.flux1 import init as base_init from mlx_dfloat.mflux.flux1.init import BaseComponents, ResolvedRepo from mlx_dfloat.mflux.flux1.lifecycle import Lifecycle @@ -122,6 +123,7 @@ def __init__( cache_limit: int | None = None, fit_check: bool = True, budget_bytes: int | None = None, + watchdog: WatchdogConfig | None = DEFAULT_WATCHDOG, quantize: int | None = None, lora_paths: list[str] | None = None, lora_scales: list[float] | None = None, @@ -134,10 +136,15 @@ def __init__( device's budget (its recommended working set minus 2 GiB) in every call's fit estimate and VAE decision, e.g. with a smaller Mac's watchdog ceiling when running under its limits. + ``watchdog`` is the memory and wall-time watchdog each ``generate_image`` and ``encode`` + call runs under, kept as ``model.watchdog`` and reassignable between calls; None runs + the calls with no watchdog. The ``mlx-dfloat`` command has its own watchdog, which this + setting does not change. + Raises: DFloatUnsupportedError: ``quantize``, ``lora_paths``, ``lora_scales`` or ``bake_lora=False`` (accepted only to refuse), an eval policy other than ``"per-block"`` / ``"depth2"``, - or an unknown ``model``. + an unknown ``model``, or a ``watchdog`` that is neither a ``WatchdogConfig`` nor None. DFloatBackendError: The GPU decoder fails its check on the two packaged self-check groups (raised before anything is resolved or loaded), or Metal is unavailable. DFloatFormatError: The checkpoint is not a FLUX.1 DF11 checkpoint, or the base lacks the @@ -147,6 +154,7 @@ def __init__( DFloatIntegrationError: mflux's own weight definition or mapping does not shape the way this adapter expects (a name map ambiguity, an uncovered extra). """ + check_watchdog_arg(watchdog) if quantize is not None: _refuse( "quantize", @@ -193,6 +201,7 @@ def __init__( cache_limit=cache_limit, fit_check=fit_check, budget_bytes=budget_bytes, + watchdog=watchdog, ) @classmethod @@ -219,6 +228,7 @@ def _assemble( cache_limit: int | None = None, fit_check: bool = True, budget_bytes: int | None = None, + watchdog: WatchdogConfig | None = DEFAULT_WATCHDOG, ) -> None: from mflux.models.flux.flux_initializer import FluxInitializer @@ -251,6 +261,7 @@ def _assemble( fit_check, ) self._budget_override = budget_bytes + self.watchdog = watchdog self._provider: DF11Provider | None = None self._plan: CallPlan | None = None self._peaks: dict[str, dict[str, int]] = {} @@ -465,11 +476,15 @@ def generate_image( ) plan = self.plan_call(height=height, width=width) self._phase_begin("encode") - self._lifecycle.ensure_embeddings(prompt) - self._phase_end("encode") + try: + self._lifecycle.ensure_embeddings(prompt) + finally: # a failed encode closes its phase: the watchdog's context must not name it afterwards + self._phase_end("encode") self._phase_begin("set_load") - self._lifecycle.ensure_set() - self._phase_end("set_load") + try: + self._lifecycle.ensure_set() + finally: + self._phase_end("set_load") self._phase_begin("denoise") # before set_cache_limit: a raise here must change nothing previous = mx.set_cache_limit(plan.cache_limit) try: diff --git a/src/mlx_dfloat/mflux/flux2/model.py b/src/mlx_dfloat/mflux/flux2/model.py index c0e2605..8fd1bad 100644 --- a/src/mlx_dfloat/mflux/flux2/model.py +++ b/src/mlx_dfloat/mflux/flux2/model.py @@ -4,7 +4,7 @@ unchanged; only construction and the prelude of ``generate_image`` differ. The text encoder and the compressed transformer are never resident together (see ``mlx_dfloat.mflux.lifecycle``). Each ``generate_image`` call runs under the memory caps the ``mlx-dfloat`` command installs (unless a wired limit is already in force) and restores -MLX's limits afterwards; only the command adds a watchdog. +MLX's limits afterwards. """ import logging @@ -33,6 +33,7 @@ from mlx_dfloat.mflux import families as registry from mlx_dfloat.mflux._compile import predict_mode, uncompiled from mlx_dfloat.mflux._phases import FamilySizes +from mlx_dfloat.mflux._watchconfig import DEFAULT_WATCHDOG, WatchdogConfig, check_watchdog_arg from mlx_dfloat.mflux.flux2 import init as finit from mlx_dfloat.mflux.flux2 import memory as kmem from mlx_dfloat.mflux.flux2.init import Flux2Components, ResolvedRepo @@ -97,6 +98,7 @@ def __init__( cache_limit: int | None = None, fit_check: bool = True, budget_bytes: int | None = None, + watchdog: WatchdogConfig | None = DEFAULT_WATCHDOG, quantize: int | None = None, lora_paths: list[str] | None = None, lora_scales: list[float] | None = None, @@ -109,10 +111,15 @@ def __init__( compressed weights stay lazy until used. ``budget_bytes`` replaces the device's budget in every call's fit estimate and VAE decision. + ``watchdog`` is the memory and wall-time watchdog each ``generate_image`` and ``encode`` + call runs under, kept as ``model.watchdog`` and reassignable between calls; None runs + the calls with no watchdog. The ``mlx-dfloat`` command has its own watchdog, which this + setting does not change. + Raises: DFloatUnsupportedError: ``quantize``, ``lora_paths``, ``lora_scales``, ``bake_lora=False`` or a ``compute_precision`` (accepted only to refuse), an eval policy other than ``"per-block"`` / ``"depth2"``, the KV-cache - model, or an unknown ``model``. + model, an unknown ``model``, or a ``watchdog`` that is neither a ``WatchdogConfig`` nor None. DFloatBackendError: The GPU decoder fails its check on the two packaged self-check groups (raised before anything is resolved or loaded), or Metal is unavailable. DFloatFormatError: The checkpoint is not a FLUX.2 Klein DF11 checkpoint, its block counts differ from @@ -122,6 +129,7 @@ def __init__( DFloatIntegrationError: mflux's own weight definition or mapping does not shape the way this adapter expects (a name map ambiguity, an uncovered extra). """ + check_watchdog_arg(watchdog) _pipeline.refuse_construction_args( quantize=quantize, lora_paths=lora_paths, lora_scales=lora_scales, bake_lora=bake_lora ) @@ -164,6 +172,7 @@ def __init__( cache_limit=cache_limit, fit_check=fit_check, budget_bytes=budget_bytes, + watchdog=watchdog, ) @classmethod @@ -189,6 +198,7 @@ def _assemble( cache_limit: int | None = None, fit_check: bool = True, budget_bytes: int | None = None, + watchdog: WatchdogConfig | None = DEFAULT_WATCHDOG, decode: Callable[[MxGroup], DecodeResult] | None = None, ) -> None: from mflux.models.common.compute_precision import ComputePrecision @@ -224,6 +234,7 @@ def _assemble( fit_check, ) self._budget_override = budget_bytes + self.watchdog = watchdog self._provider: DF11Provider | None = None self._plan: CallPlan | None = None self._tracker = _pipeline.PhaseTracker() diff --git a/src/mlx_dfloat/mflux/generate.py b/src/mlx_dfloat/mflux/generate.py index 3c6f840..7e1722f 100644 --- a/src/mlx_dfloat/mflux/generate.py +++ b/src/mlx_dfloat/mflux/generate.py @@ -580,7 +580,7 @@ def run( try: factory = model_factory if model_factory is not None else _model_class(args.model) resolve = resolve_output if resolve_output is not None else _output_resolver() - model = built["model"] = factory(**model_kwargs) + model = built["model"] = factory(**model_kwargs, watchdog=None) call: dict[str, Any] = { "seed": args.seed, "prompt": args.prompt, diff --git a/src/mlx_dfloat/mflux/krea2/model.py b/src/mlx_dfloat/mflux/krea2/model.py index 6dd7dc4..183ac25 100644 --- a/src/mlx_dfloat/mflux/krea2/model.py +++ b/src/mlx_dfloat/mflux/krea2/model.py @@ -33,6 +33,7 @@ from mlx_dfloat.mflux import families as registry from mlx_dfloat.mflux._compile import uncompiled from mlx_dfloat.mflux._phases import FamilySizes +from mlx_dfloat.mflux._watchconfig import DEFAULT_WATCHDOG, WatchdogConfig, check_watchdog_arg from mlx_dfloat.mflux.krea2 import init as kinit from mlx_dfloat.mflux.krea2 import memory as kmem from mlx_dfloat.mflux.krea2.init import Krea2Components, ResolvedRepo @@ -137,6 +138,7 @@ def __init__( cache_limit: int | None = None, fit_check: bool = True, budget_bytes: int | None = None, + watchdog: WatchdogConfig | None = DEFAULT_WATCHDOG, quantize: int | None = None, lora_paths: list[str] | None = None, lora_scales: list[float] | None = None, @@ -149,9 +151,15 @@ def __init__( package was checked against; a user's own paths are taken as given. ``budget_bytes`` replaces the device's budget in every call's fit estimate and VAE decision. + ``watchdog`` is the memory and wall-time watchdog each ``generate_image`` and ``encode`` + call runs under, kept as ``model.watchdog`` and reassignable between calls; None runs + the calls with no watchdog. The ``mlx-dfloat`` command has its own watchdog, which this + setting does not change. + Raises: DFloatUnsupportedError: ``quantize``, ``lora_paths``, ``lora_scales`` or ``bake_lora=False`` (accepted only - to refuse), an eval policy other than ``"per-block"`` / ``"depth2"``, or an unknown ``model``. + to refuse), an eval policy other than ``"per-block"`` / ``"depth2"``, an unknown ``model``, or a + ``watchdog`` that is neither a ``WatchdogConfig`` nor None. DFloatBackendError: The GPU decoder fails its check on the two packaged self-check groups (raised before anything is resolved or loaded), or Metal is unavailable. DFloatFormatError: The checkpoint is not a Krea 2 DF11 checkpoint (the other Krea 2 model's included), its @@ -161,6 +169,7 @@ def __init__( DFloatIntegrationError: mflux's own weight definition or mapping does not shape the way this adapter expects. """ + check_watchdog_arg(watchdog) _pipeline.refuse_construction_args( quantize=quantize, lora_paths=lora_paths, lora_scales=lora_scales, bake_lora=bake_lora ) @@ -204,6 +213,7 @@ def __init__( cache_limit=cache_limit, fit_check=fit_check, budget_bytes=budget_bytes, + watchdog=watchdog, ) @classmethod @@ -229,6 +239,7 @@ def _assemble( cache_limit: int | None = None, fit_check: bool = True, budget_bytes: int | None = None, + watchdog: WatchdogConfig | None = DEFAULT_WATCHDOG, decode: Callable[[MxGroup], DecodeResult] | None = None, ) -> None: from mflux.models.krea2.krea2_initializer import Krea2Initializer @@ -272,6 +283,7 @@ def _assemble( fit_check, ) self._budget_override = budget_bytes + self.watchdog = watchdog self._provider: DF11Provider | None = None self._plan: CallPlan | None = None self._tracker = _pipeline.PhaseTracker() diff --git a/src/mlx_dfloat/mflux/lifecycle.py b/src/mlx_dfloat/mflux/lifecycle.py index a4a00e0..8a6fb4e 100644 --- a/src/mlx_dfloat/mflux/lifecycle.py +++ b/src/mlx_dfloat/mflux/lifecycle.py @@ -16,10 +16,15 @@ import mlx.core as mx +from mlx_dfloat import _guard +from mlx_dfloat._watchdog import phys_footprint from mlx_dfloat.errors import DFloatResourceError +from mlx_dfloat.mflux import _drain log = logging.getLogger("mlx_dfloat.mflux") _eval = mx.eval # looked up on the module, so a test can record the evaluation +# What an armed drop's drain polls; looked up at call time, so a test can script it. +_read_footprint: Callable[[], int] = phys_footprint @dataclass(slots=True) @@ -93,9 +98,15 @@ def ensure_embeddings(self, *prompts: str) -> None: self.counters.encoder_seconds += time.perf_counter() - start pair: tuple[mx.array, ...] | None = None try: + # Inside the try, so a stop here drops the encoders just loaded. The encoder load is lazy: its weights + # land in the first prompt's evaluation, so the load and the first encode are one stretch with no + # checkpoint between them. + _guard.checkpoint("encoder_loaded") for prompt in missing: pair = self._encode(prompt) _eval(*pair) + # Before the store: a stopped prompt's pair is not cached. + _guard.checkpoint("prompt_encoded") self._cache[prompt] = pair except BaseException as exc: # The traceback keeps the failing frames alive, and with them a lazy pair whose graph @@ -129,6 +140,7 @@ def ensure_set(self) -> None: f"a previous set is still resident: {active / 1024**3:.2f} GiB of MLX memory is active " f"before the load (bound {bound / 1024**3:.2f} GiB)" ) + _guard.checkpoint("set_load_start") start = time.perf_counter() self._load_set() self.set_resident = True @@ -148,6 +160,7 @@ def drop_encoders(self) -> None: self._reclaim("text encoders") def _reclaim(self, what: str) -> None: + mx.synchronize() # a buffer the GPU used is freed when its command completes: wait first gc.collect() mx.clear_cache() active = int(mx.get_active_memory()) @@ -157,3 +170,7 @@ def _reclaim(self, what: str) -> None: f"after dropping the {what}, {active / 1024**3:.2f} GiB of MLX memory is still active " f"(bound {bound / 1024**3:.2f} GiB): something else holds it" ) + if _guard.active() is not None: + # Inside an armed call only: the freed pages leave the footprint the watchdog samples after the next GPU + # submission, so drain them before the call goes on. An unarmed drop stays as it was. + _drain.drain(_read_footprint) diff --git a/src/mlx_dfloat/mflux/qwen21/model.py b/src/mlx_dfloat/mflux/qwen21/model.py index bf868e0..4420b82 100644 --- a/src/mlx_dfloat/mflux/qwen21/model.py +++ b/src/mlx_dfloat/mflux/qwen21/model.py @@ -5,7 +5,7 @@ transformer are never resident together (see ``mlx_dfloat.mflux.lifecycle``): prompts are encoded first into mflux's own prompt cache, which its loop reads without touching the encoder. Each ``generate_image`` call runs under the memory caps the ``mlx-dfloat`` command installs (unless a wired limit is already in force) and restores MLX's -limits afterwards; only the command adds a watchdog. +limits afterwards. """ import logging @@ -33,6 +33,7 @@ from mlx_dfloat.mflux import _pipeline, require_mflux from mlx_dfloat.mflux import families as registry from mlx_dfloat.mflux._phases import FamilySizes +from mlx_dfloat.mflux._watchconfig import DEFAULT_WATCHDOG, WatchdogConfig, check_watchdog_arg from mlx_dfloat.mflux.lifecycle import Lifecycle from mlx_dfloat.mflux.qwen21 import init as qinit from mlx_dfloat.mflux.qwen21 import memory as qmem @@ -106,6 +107,7 @@ def __init__( cache_limit: int | None = None, fit_check: bool = True, budget_bytes: int | None = None, + watchdog: WatchdogConfig | None = DEFAULT_WATCHDOG, quantize: int | None = None, lora_paths: list[str] | None = None, lora_scales: list[float] | None = None, @@ -118,10 +120,15 @@ def __init__( compressed weights stay lazy until used. ``budget_bytes`` replaces the device's budget in every call's fit estimate and VAE decision. + ``watchdog`` is the memory and wall-time watchdog each ``generate_image`` and ``encode`` + call runs under, kept as ``model.watchdog`` and reassignable between calls; None runs + the calls with no watchdog. The ``mlx-dfloat`` command has its own watchdog, which this + setting does not change. + Raises: DFloatUnsupportedError: ``quantize``, ``lora_paths``, ``lora_scales``, ``bake_lora=False`` or a ``compute_precision`` - (accepted only to refuse), an eval policy other than ``"per-block"`` / ``"depth2"``, or an unknown - ``model``. + (accepted only to refuse), an eval policy other than ``"per-block"`` / ``"depth2"``, an unknown + ``model``, or a ``watchdog`` that is neither a ``WatchdogConfig`` nor None. DFloatBackendError: The GPU decoder fails its check on the two packaged self-check groups (raised before anything is resolved or loaded), or Metal is unavailable. DFloatFormatError: The checkpoint is not a Qwen-Image 2.1 DF11 checkpoint (a config-less file of @@ -132,6 +139,7 @@ def __init__( DFloatIntegrationError: mflux's own weight definition or mapping does not shape the way this adapter expects (a name map ambiguity, an uncovered extra). """ + check_watchdog_arg(watchdog) _pipeline.refuse_construction_args( quantize=quantize, lora_paths=lora_paths, lora_scales=lora_scales, bake_lora=bake_lora ) @@ -172,6 +180,7 @@ def __init__( cache_limit=cache_limit, fit_check=fit_check, budget_bytes=budget_bytes, + watchdog=watchdog, ) @classmethod @@ -197,6 +206,7 @@ def _assemble( cache_limit: int | None = None, fit_check: bool = True, budget_bytes: int | None = None, + watchdog: WatchdogConfig | None = DEFAULT_WATCHDOG, decode: Callable[[MxGroup], DecodeResult] | None = None, ) -> None: from mflux.models.common.compute_precision import ComputePrecision @@ -231,6 +241,7 @@ def _assemble( fit_check, ) self._budget_override = budget_bytes + self.watchdog = watchdog self._provider: DF11Provider | None = None self._plan: CallPlan | None = None self._tracker = _pipeline.PhaseTracker() diff --git a/src/mlx_dfloat/mflux/zimage/model.py b/src/mlx_dfloat/mflux/zimage/model.py index 9f0a062..8d2f977 100644 --- a/src/mlx_dfloat/mflux/zimage/model.py +++ b/src/mlx_dfloat/mflux/zimage/model.py @@ -4,7 +4,7 @@ unchanged; only construction and the prelude of ``generate_image`` differ. The text encoder and the compressed transformer are never resident together (see ``mlx_dfloat.mflux.lifecycle``). Each ``generate_image`` call runs under the memory caps the ``mlx-dfloat`` command installs (unless a wired limit is already in force) and restores -MLX's limits afterwards; only the command adds a watchdog. +MLX's limits afterwards. """ import logging @@ -37,6 +37,7 @@ from mlx_dfloat.mflux import _pipeline, require_mflux from mlx_dfloat.mflux import families as registry from mlx_dfloat.mflux._compile import predict_mode, uncompiled +from mlx_dfloat.mflux._watchconfig import DEFAULT_WATCHDOG, WatchdogConfig, check_watchdog_arg from mlx_dfloat.mflux.lifecycle import Lifecycle from mlx_dfloat.mflux.zimage import init as zinit from mlx_dfloat.mflux.zimage.init import ResolvedRepo, ZImageComponents @@ -113,6 +114,7 @@ def __init__( cache_limit: int | None = None, fit_check: bool = True, budget_bytes: int | None = None, + watchdog: WatchdogConfig | None = DEFAULT_WATCHDOG, quantize: int | None = None, lora_paths: list[str] | None = None, lora_scales: list[float] | None = None, @@ -126,10 +128,16 @@ def __init__( compressed weights stay lazy until used. ``budget_bytes`` replaces the device's budget in every call's fit estimate and VAE decision. + ``watchdog`` is the memory and wall-time watchdog each ``generate_image`` and ``encode`` + call runs under, kept as ``model.watchdog`` and reassignable between calls; None runs + the calls with no watchdog. The ``mlx-dfloat`` command has its own watchdog, which this + setting does not change. + Raises: DFloatUnsupportedError: ``quantize``, ``lora_paths``, ``lora_scales``, ``bake_lora=False``, ``float32=True`` or a ``compute_precision`` (accepted only to refuse), an eval policy other than - ``"per-block"`` / ``"depth2"``, a ControlNet model, or an unknown ``model``. + ``"per-block"`` / ``"depth2"``, a ControlNet model, an unknown ``model``, or a ``watchdog`` that + is neither a ``WatchdogConfig`` nor None. DFloatBackendError: The GPU decoder fails its check on the two packaged self-check groups (raised before anything is resolved or loaded), or Metal is unavailable. DFloatFormatError: The checkpoint is not a Z-Image DF11 checkpoint, or the base lacks a component. @@ -138,6 +146,7 @@ def __init__( DFloatIntegrationError: mflux's own weight definition or mapping does not shape the way this adapter expects (a name map ambiguity, an uncovered extra). """ + check_watchdog_arg(watchdog) if quantize is not None: _refuse( "quantize", @@ -190,6 +199,7 @@ def __init__( cache_limit=cache_limit, fit_check=fit_check, budget_bytes=budget_bytes, + watchdog=watchdog, ) @classmethod @@ -215,6 +225,7 @@ def _assemble( cache_limit: int | None = None, fit_check: bool = True, budget_bytes: int | None = None, + watchdog: WatchdogConfig | None = DEFAULT_WATCHDOG, decode: Callable[[MxGroup], DecodeResult] | None = None, ) -> None: from mflux.models.common.compute_precision import ComputePrecision @@ -248,6 +259,7 @@ def _assemble( fit_check, ) self._budget_override = budget_bytes + self.watchdog = watchdog self._provider: DF11Provider | None = None self._plan: CallPlan | None = None self._peaks: dict[str, dict[str, int]] = {} @@ -509,11 +521,15 @@ def generate_image( prompts = self.cfg_prompts(prompt, negative_prompt=negative_prompt, guidance=guidance) self._cfg_calls = len(prompts) self._phase_begin("encode") - self._lifecycle.ensure_embeddings(*prompts) - self._phase_end("encode") + try: + self._lifecycle.ensure_embeddings(*prompts) + finally: # a failed encode closes its phase: the watchdog's context must not name it afterwards + self._phase_end("encode") self._phase_begin("set_load") - self._lifecycle.ensure_set() - self._phase_end("set_load") + try: + self._lifecycle.ensure_set() + finally: + self._phase_end("set_load") self._phase_begin("denoise") # before set_cache_limit: a raise here must change nothing previous = mx.set_cache_limit(plan.cache_limit) try: diff --git a/tests/_fake_counters.py b/tests/_fake_counters.py new file mode 100644 index 0000000..bedd90a --- /dev/null +++ b/tests/_fake_counters.py @@ -0,0 +1,40 @@ +"""An in-memory stand-in for the watchdog's counter reader, so tests decide what it sees.""" + +import threading + +import mlx_dfloat._watchdog as wd + + +class FakeCounters: + """Settable counters; calling the object returns them as one ``Counters`` reading. + + A lock keeps a reading whole: the sampler thread never sees ``footprint`` from one + ``raise_to`` and the MLX numbers from another. + """ + + def __init__(self, footprint=0, rss=0, mlx_active=0, mlx_cache=0): + self._lock = threading.Lock() + self.footprint = footprint + self.rss = rss + self.mlx_active = mlx_active + self.mlx_cache = mlx_cache + + def __call__(self): + with self._lock: + return wd.Counters( + footprint=self.footprint, + rss=self.rss, + mlx_active=self.mlx_active, + mlx_cache=self.mlx_cache, + ) + + def raise_to(self, watched): + """Set the watched number to ``watched``, carried by the footprint counter. + + MLX active + cache together hold half of it, so the footprint is the counter reported. + """ + with self._lock: + self.footprint = watched + half = watched // 2 + self.mlx_active = half // 2 + self.mlx_cache = half - half // 2 diff --git a/tests/conftest.py b/tests/conftest.py index 9365773..4ef2c0b 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -6,14 +6,18 @@ import os import platform import sys -from collections.abc import Callable +from collections.abc import Callable, Iterator +from dataclasses import dataclass from importlib.machinery import ModuleSpec -from typing import Literal +from typing import Any, Literal import pytest from mlx_dfloat._memory_caps import install_memory_caps +# pytester runs the autouse fixture's teardown check end to end in a child pytest (tests/test_markers.py). +pytest_plugins = ["pytester"] + GATED_MARKERS: tuple[tuple[str, str, str], ...] = ( ("slow", "--run-slow", "real-weights decode"), ("network", "--run-network", "real network I/O"), @@ -68,6 +72,77 @@ def _hard_exit_code(recorded: int | None) -> int | None: return recorded +class _ExitRecorder: + """Stands in for the process exit of an armed model call: records each code instead of ending pytest.""" + + def __init__(self) -> None: + self.codes: list[int] = [] + + def __call__(self, code: int) -> None: + self.codes.append(code) + + def take(self) -> list[int]: + """Hand the recorded codes to a test that expected an escalation; the teardown then sees none.""" + taken, self.codes = self.codes, [] + return taken + + +def _host_ceiling_32gib() -> int: + # A 32 GiB Mac's ceiling (32 - 4 GiB) as a literal, so no expected number depends on this runner's RAM. + return 30_064_771_072 + + +def _api_watchdog_patches() -> list[tuple[str, object]]: + """The ``mlx_dfloat.mflux._pipeline`` attributes every test replaces, with fresh fakes. + + The counter reader becomes a ``FakeCounters`` at zero, the host's default ceiling the 32 GiB literal, and the + process exit a recorder, so a decorated model call is armed in every test, never trips on the runner's real + memory, and can never end pytest. + """ + from tests._fake_counters import FakeCounters + + return [ + ("_counters", FakeCounters()), + ("_default_ceiling", _host_ceiling_32gib), + ("_exit_process", _ExitRecorder()), + ] + + +def _untaken_exits(codes: list[int]) -> str | None: + """The teardown's failure message for exit codes left in the recorder, or None when there are none.""" + if not codes: + return None + return ( + f"an armed model call escalated to process exit {codes} and the test did not take the code" + ) + + +@dataclass(frozen=True, slots=True) +class ApiWatchdogFakes: + """What ``_api_watchdog_fakes`` yields: the fake allocator the watchdog reads and the exit recorder.""" + + counters: Any + exits: _ExitRecorder + + +@pytest.fixture(autouse=True) +def _api_watchdog_fakes(monkeypatch: pytest.MonkeyPatch) -> Iterator[ApiWatchdogFakes]: + from mlx_dfloat import _watchdog + from mlx_dfloat.mflux import _pipeline + + patches = dict(_api_watchdog_patches()) + for name, value in patches.items(): + monkeypatch.setattr(_pipeline, name, value) + exits = patches["_exit_process"] + assert isinstance(exits, _ExitRecorder) + # A watchdog built without ``exit_process`` falls back to the module's ``_exit``: record it the same way. + monkeypatch.setattr(_watchdog, "_exit", exits) + yield ApiWatchdogFakes(counters=patches["_counters"], exits=exits) + message = _untaken_exits(exits.codes) + if message is not None: + pytest.fail(message) + + def pytest_addoption(parser: pytest.Parser) -> None: for marker, flag, description in GATED_MARKERS: parser.addoption( diff --git a/tests/test_api_watchdog.py b/tests/test_api_watchdog.py new file mode 100644 index 0000000..7f5b423 --- /dev/null +++ b/tests/test_api_watchdog.py @@ -0,0 +1,779 @@ +"""A model call through ``with_call_caps`` runs under a raise-mode memory watchdog by default. + +mflux-free: a small fake model class carries what the decorator reads (``watchdog``, ``open_phase``, ``_model``, a +real ``Lifecycle`` over in-memory callbacks), and its ``generate_image`` runs two checkpoints around a hook. The +autouse ``_api_watchdog_fakes`` fixture (``tests/conftest.py``) puts the fake allocator in front of the watchdog, +fixes the host ceiling at 30_064_771_072 bytes (a 32 GiB Mac minus 4 GiB) and records any process exit, so every +expected number below is a literal. Hooks raise the fake and wait on the watchdog's ``tripped`` event with a 5 s +timeout; the only fixed waits are the "nothing tripped within 0.3 s" checks. +""" + +import gc +import os +import platform +import re +import stat +import tempfile +import threading +import time +import weakref +from pathlib import Path + +import mlx.core as mx +import pytest + +from mlx_dfloat import _guard, _watchdog +from mlx_dfloat.errors import DFloatUnsupportedError, DFloatWatchdogError +from mlx_dfloat.mflux import _drain, _pipeline, lifecycle +from mlx_dfloat.mflux._watchconfig import DEFAULT_WATCHDOG, WatchdogConfig +from mlx_dfloat.mflux.lifecycle import Lifecycle + +# 32 GiB - 4 GiB, and that minus the default 1 GiB stop margin (27 GiB). +CEILING = 30_064_771_072 +STOP_LINE = 28_991_029_248 +THREAD = "mlx-dfloat-watchdog" + +# Taken before any fixture patches it, for the default-location test. +_REAL_ARTIFACT_ROOT = _pipeline._artifact_root +# The three watchdog seams as shipped, taken before the autouse fixture replaces them. +_SHIPPED_SEAMS = (_pipeline._counters, _pipeline._default_ceiling, _pipeline._exit_process) + + +class _Interrupt(BaseException): + """Stands in for a KeyboardInterrupt landing between two statements of the decorator.""" + + +@pytest.fixture(autouse=True) +def aborts(tmp_path, monkeypatch): + """Every abort record of this file lands under the test's own folder, never in the real temp dir.""" + root = tmp_path / "aborts" + monkeypatch.setattr(_pipeline, "_artifact_root", lambda: root) + return root + + +@pytest.fixture +def fakes(request): + """The autouse ``_api_watchdog_fakes`` value: the fake allocator and the exit recorder of this test.""" + return request.getfixturevalue("_api_watchdog_fakes") + + +class _Held: + """An object only the fake method's frame refers to.""" + + +def _watchdog_threads(): + return {t for t in threading.enumerate() if t.name == THREAD and t.is_alive()} + + +class FakeModel: + """What the decorator reads on a model class, around a body with two checkpoints and three hooks.""" + + def __init__( + self, + *, + watchdog=DEFAULT_WATCHDOG, + hook=None, + inner=None, + tail=None, + leak_set=False, + load_hook=None, + encode_hook=None, + ): + self.watchdog = watchdog + self._model = "fake-model" + self.open_phase = None + self.hook, self.inner, self.tail = hook, inner, tail + self.load_hook = load_hook + self.encode_hook = encode_hook + self.ran = [] + self.held = None + self.bound = 2**62 + self._set = None + self._leaked = [] + self._leak_set = leak_set + self._lifecycle = Lifecycle( + load_encoders=lambda: None, + unload_encoders=lambda: None, + encode=lambda prompt: (), + load_set=self._load_set, + unload_set=self._unload_set, + prompt_cache={}, + retained_bound=lambda: self.bound, + ) + + def _load_set(self): + if self.load_hook is not None: # a trip during the set load: the set is not resident yet + self.load_hook(self) + _guard.checkpoint("set_group") + self._set = mx.zeros((1024,), dtype=mx.float32) + mx.eval(self._set) + + def _unload_set(self): + if self._leak_set: # the drop leaves the set referenced, so the reclaim check fails + self._leaked.append(self._set) + self._set = None + + @_pipeline.with_call_caps + def generate_image( + self, seed, prompt, num_inference_steps=2, height=64, width=64, guidance=None + ): + held = _Held() + self.held = weakref.ref(held) + self.ran.append("body") + self._lifecycle.ensure_set() + self.open_phase = "denoise" + _guard.checkpoint("block_start") + if self.hook is not None: + self.hook(self) + if self.inner is not None: + self.inner.generate_image(seed, prompt) + _guard.checkpoint("block_end") + self.open_phase = "vae" + if self.tail is not None: + self.tail(self) + self.open_phase = None + return "image" + + @_pipeline.with_call_caps + def encode(self, prompt): + self.ran.append("encode") + self.open_phase = "encode" + if self.encode_hook is not None: + self.encode_hook(self) + _guard.checkpoint("prompt_encoded") + self.open_phase = None + return () + + +def overrun(counters, level): + """A hook that raises the fake to ``level`` and waits for the active watchdog to trip (a no-op wait unarmed).""" + + def hook(model): + watchdog = _guard.active() + counters.raise_to(level) + if watchdog is not None: + model.ran.append(("tripped", watchdog.tripped.wait(5.0))) + + return hook + + +def _sampled_at(watchdog, level): + """Poll (5 s) until the watchdog has sampled ``level``; True if it did.""" + deadline = time.monotonic() + 5.0 + while watchdog.peak_watched < level: + if time.monotonic() > deadline: + return False + time.sleep(0.01) + return True + + +def test_a_model_built_with_no_watchdog_argument_is_armed(fakes): + # Bug caught: the default config off (the call runs unwatched and returns), or a stop margin other than 1 GiB. + model = FakeModel(hook=overrun(fakes.counters, STOP_LINE + 1)) + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(1, "p") + err = excinfo.value + assert err.record["ceiling"] == 30_064_771_072 + assert err.record["stop_line"] == 28_991_029_248 + assert (err.reason, err.phase, err.site) == ("memory", "denoise", "block_end") + + +def test_the_stop_line_itself_does_not_trip(fakes): + # Bug caught: `>=` at the stop line in the armed call's watchdog, or a margin one byte off. The hook proves a + # watchdog sampled the level before checking it did not trip. + seen = [] + + def hook(model): + watchdog = _guard.active() + fakes.counters.raise_to(STOP_LINE) + if watchdog is None: + seen.append(None) + return + sampled = _sampled_at(watchdog, STOP_LINE) + seen.append((sampled, watchdog.tripped.wait(0.3))) + + assert FakeModel(hook=hook).generate_image(1, "p") == "image" + assert seen == [(True, False)] + + +def test_watchdog_none_runs_unwatched(fakes): + # Bug caught: watchdog=None still arming (a thread starts; at twice the ceiling it escalates and the fixture's + # teardown fails on the recorded exit). + before = _watchdog_threads() + seen = [] + + def hook(model): + fakes.counters.raise_to(2 * CEILING) + seen.append((_guard.active(), len(_watchdog_threads() - before))) + time.sleep(0.2) # several sample intervals: an armed watchdog would escalate here + + assert FakeModel(watchdog=None, hook=hook).generate_image(1, "p") == "image" + assert seen == [(None, 0)] + + +def test_a_nested_call_does_not_arm_a_second_watchdog(): + # Bug caught: the decorator arming on every call, so a nested encode inside generate_image starts a second thread. + before = _watchdog_threads() + seen = [] + inner = FakeModel(hook=lambda model: seen.append(len(_watchdog_threads() - before))) + assert FakeModel(inner=inner).generate_image(1, "p") == "image" + assert seen == [1] + + +def test_a_nested_lower_ceiling_wins_for_the_inner_call_only(fakes): + # Bug caught: the nested model's lower ceiling ignored (no trip at 20 GB - 1 GiB + 1), or left in force after the + # inner call returns (the same level trips the outer). + level = 20_000_000_000 - 1_073_741_824 + 1 + lower = WatchdogConfig(ceiling=20_000_000_000) + inner = FakeModel(watchdog=lower, hook=overrun(fakes.counters, level)) + with pytest.raises(DFloatWatchdogError) as excinfo: + FakeModel(inner=inner).generate_image(1, "p") + assert excinfo.value.record["ceiling"] == 20_000_000_000 + assert excinfo.value.record["stop_line"] == 18_926_258_176 + + fakes.counters.raise_to(0) + seen = [] + + def after_inner(model): + watchdog = _guard.active() + fakes.counters.raise_to(level) + seen.append((_sampled_at(watchdog, level), watchdog.tripped.wait(0.3))) + + outer = FakeModel(inner=FakeModel(watchdog=lower), tail=after_inner) + assert outer.generate_image(1, "p") == "image" + assert seen == [(True, False)] + + +def test_an_outer_guard_from_another_call_keeps_its_own_ceiling(fakes): + # Bug caught: a nested model built with watchdog=None stepping out of the outer call's guard (scope reset to + # None), so an overrun inside it runs on unwatched. + inner = FakeModel(watchdog=None, hook=overrun(fakes.counters, STOP_LINE + 1)) + with pytest.raises(DFloatWatchdogError) as excinfo: + FakeModel(inner=inner).generate_image(1, "p") + assert excinfo.value.record["ceiling"] == 30_064_771_072 + + +def test_a_ceiling_above_the_host_ceiling_is_refused_before_anything_runs(): + # Bug caught: a ceiling above the host's accepted (the watchdog then guards a line the machine cannot reach), or + # refused only after the body ran. + model = FakeModel(watchdog=WatchdogConfig(ceiling=30_064_771_073)) + with pytest.raises(DFloatUnsupportedError, match="30064771073"): + model.generate_image(1, "p") + assert model.ran == [] + assert model._lifecycle.counters.set_loads == 0 + + +def test_the_abort_drops_a_resident_set_and_clears_frames(fakes): + # Bug caught: the abort leaving the set resident (the next call reuses a half-dropped set), or the traceback + # keeping the method's locals alive for as long as the caller holds the error. + model = FakeModel(hook=overrun(fakes.counters, STOP_LINE + 1)) + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(1, "p") + assert model._lifecycle.set_resident is False + assert excinfo.value.site == "block_end" # the error is still held while the frames are checked + assert model.held() is None + + +def test_a_reclaim_failure_is_attached_to_the_abort(fakes): + # Bug caught: the DFloatResourceError from the drop's reclaim check replacing the abort, so the caller sees a + # "still resident" error and never learns the watchdog stopped the call; or the reclaim failure lost. + def hook(model): + model.bound = 0 + overrun(fakes.counters, STOP_LINE + 1)(model) + + model = FakeModel(hook=hook, leak_set=True) + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(1, "p") + notes = getattr(excinfo.value, "__notes__", []) + assert any("DFloatResourceError" in note for note in notes) + + +def test_no_watchdog_thread_survives_the_call(fakes): + # Bug caught: the watchdog not stopped on the way out (after an abort or a normal return), leaving a sampler that + # can still end the process later. + before = _watchdog_threads() + during = [] + + def hook(model): + during.append(len(_watchdog_threads() - before)) + + assert FakeModel(hook=hook).generate_image(1, "p") == "image" + assert _watchdog_threads() - before == set() + + def tripping(model): + hook(model) + overrun(fakes.counters, STOP_LINE + 1)(model) + + with pytest.raises(DFloatWatchdogError): + FakeModel(hook=tripping).generate_image(1, "p") + assert _watchdog_threads() - before == set() + assert during == [1, 1] + + +def test_a_trip_after_the_last_checkpoint_raises_at_call_end(fakes): + # Bug caught: no checkpoint after the method returns, so a trip during the VAE decode (no checkpoint inside it) + # returns an image from an overrun call; or the phase read when the error is raised instead of at the trip. + model = FakeModel(tail=overrun(fakes.counters, STOP_LINE + 1)) + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(1, "p") + assert (excinfo.value.site, excinfo.value.phase) == ("call_end", "vae") + + +def test_the_artifact_lands_in_the_default_root_with_a_unique_name(fakes, aborts): + # Bug caught: a fixed file name (the second abort overwrites the first), or the record written somewhere other + # than the root when the config names no folder. + errors = [] + for _ in range(2): + fakes.counters.raise_to(0) + with pytest.raises(DFloatWatchdogError) as excinfo: + FakeModel(hook=overrun(fakes.counters, STOP_LINE + 1)).generate_image(1, "p") + errors.append(excinfo.value) + names = sorted(p.name for p in aborts.iterdir()) + assert len(names) == 2 + pattern = re.compile(rf"abort-\d{{8}}T\d{{12}}Z-{os.getpid()}\.json") + assert all(pattern.fullmatch(name) for name in names), names + assert sorted(err.artifact.name for err in errors) == names + + +def test_the_artifact_root_defaults_to_the_temp_dir(): + # Bug caught: the records written to the working directory or a fixed /tmp path instead of the system temp dir. + assert _REAL_ARTIFACT_ROOT() == Path(tempfile.gettempdir()) / "mlx-dfloat" + + +def test_the_default_counter_reader_is_the_real_one(monkeypatch): + # Bug caught: the armed watchdog not reading the counters through the seam (or the seam's default not the real + # reader). The stop line is 1 MiB: a bare Python process with mlx.core imported measured a 17_334_920-byte + # footprint on an M1 Max (2026-11-24), so any real reading is above it, and nowhere near the 28 GiB ceiling. + monkeypatch.setattr(_pipeline, "_counters", _watchdog.read_counters) + config = WatchdogConfig(ceiling=30_064_771_072, stop_margin=30_064_771_072 - 1024**2) + + def hook(model): + model.ran.append(("tripped", _guard.active().tripped.wait(5.0))) + + with pytest.raises(DFloatWatchdogError) as excinfo: + FakeModel(watchdog=config, hook=hook).generate_image(1, "p") + assert excinfo.value.record["verdict_memory"] > 1024**2 + + +def test_default_ceiling_comes_from_the_injected_host_figure(fakes, monkeypatch): + # Bug caught: the default ceiling read from the host directly instead of through the seam at call time. + monkeypatch.setattr(_pipeline, "_default_ceiling", lambda: 17_179_869_184) + model = FakeModel(hook=overrun(fakes.counters, 16_106_127_361)) + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(1, "p") + assert excinfo.value.record["ceiling"] == 17_179_869_184 + + +def test_the_record_names_the_call(fakes): + # Bug caught: an abort record that cannot say which model, method and arguments it stopped, or one that records + # the prompt. + model = FakeModel(hook=overrun(fakes.counters, STOP_LINE + 1)) + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(7, "a secret prompt", num_inference_steps=3, height=48, width=80) + context = excinfo.value.record["context"] + assert {k: context[k] for k in ("model", "class", "method", "seed", "height", "width")} == { + "model": "fake-model", + "class": "FakeModel", + "method": "generate_image", + "seed": 7, + "height": 48, + "width": 80, + } + assert (context["num_inference_steps"], context["guidance"]) == (3, None) + assert context["versions"]["mlx"] == mx.__version__ + assert context["macos"] == platform.mac_ver()[0] + assert "a secret prompt" not in repr(excinfo.value.record) + + +def test_the_seams_ship_as_the_real_reader_ceiling_and_exit(): + # Bug caught: a seam default left pointing at a fake or another function (the autouse fixture replaces all three + # before every test, so nothing else would see it): a shipped call reading no real memory, a ceiling from the + # wrong figure, or an exit other than the watchdog module's own. + counters, ceiling, exit_process = _SHIPPED_SEAMS + assert counters is _watchdog.read_counters + assert ceiling is _watchdog.default_ceiling + assert exit_process is None + + +def _recording_cleanup(monkeypatch, events): + """Record, in ``events``, every synchronize, garbage collection, cache clear and kick the abort path makes.""" + monkeypatch.setattr(mx, "synchronize", lambda *a, **k: events.append("synchronize")) + monkeypatch.setattr(mx, "clear_cache", lambda: events.append("clear_cache")) + monkeypatch.setattr(gc, "collect", lambda *a: events.append("collect") or 0) + monkeypatch.setattr(_drain, "_kick", lambda: events.append("kick")) + monkeypatch.setattr(_drain, "_sleep", lambda seconds: events.append("sleep")) + # A footprint that does not fall: each drain polls its whole 0.25 s budget, 12 sleeps of 0.02 s (D26: a flat + # reading before any fall does not end the poll), whatever the real footprint does. + monkeypatch.setattr(lifecycle, "_read_footprint", lambda: 1, raising=False) + + +def test_an_abort_during_the_set_load_still_empties_the_buffer_pool(fakes, monkeypatch): + # Bug caught: `_after_abort` returning before any cleanup when the set is not resident yet (a stop at a set_group + # checkpoint), so the groups loaded so far stay in MLX's buffer pool after the error; or the pool emptied before + # the GPU finished (no synchronize first), or without the collection that frees the dropped arrays. + events = [] + + def load_hook(model): + overrun(fakes.counters, STOP_LINE + 1)(model) + events.append("tripped") + + model = FakeModel(load_hook=load_hook) + _recording_cleanup(monkeypatch, events) + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(1, "p") + assert excinfo.value.site == "set_group" + assert model._lifecycle.set_resident is False + after = events[events.index("tripped") + 1 :] + # The pool emptied, then the drain (W2 item 3: it replaces the bare kick and clear). + assert after == [ + *["synchronize", "collect", "clear_cache"], + *["synchronize", "clear_cache", "kick", *["sleep"] * 12, "synchronize", "clear_cache"], + ] + + +def test_an_abort_with_the_set_resident_kicks_and_clears_after_the_drop(fakes, monkeypatch): + # Bug caught: the kick and the second clear run before the set's drop (its freed buffers then reach the pool after + # the last clear), or skipped when the set was resident. + events = [] + + def hook(model): + overrun(fakes.counters, STOP_LINE + 1)(model) + events.append("tripped") + + model = FakeModel(hook=hook) + real_unload = model._unload_set + + def unload(): + events.append("unload_set") + real_unload() + + model._lifecycle._unload_set = unload + _recording_cleanup(monkeypatch, events) + with pytest.raises(DFloatWatchdogError): + model.generate_image(1, "p") + after = events[events.index("tripped") + 1 :] + assert after[: after.index("unload_set")] == ["synchronize", "collect", "clear_cache"] + drain = ["synchronize", "clear_cache", "kick", *["sleep"] * 12, "synchronize", "clear_cache"] + # The drop's own reclaim drains inside the armed call, then the abort drains once more (W2 item 3). + assert after[after.index("unload_set") :] == [ + *["unload_set", "synchronize", "collect", "clear_cache"], + *drain, + *drain, + ] + + +def test_an_interrupt_right_after_the_start_still_stops_the_watchdog(monkeypatch): + # Bug caught: `watchdog.start()` outside the `try` whose `finally` stops it, so an interrupt landing between the + # two leaves a live raise-mode sampler that can end the process later. + before = _watchdog_threads() + started = [] + real_start = _watchdog.Watchdog.start + + def start_then_interrupt(self): + started.append(self) + real_start(self) + raise _Interrupt + + monkeypatch.setattr(_watchdog.Watchdog, "start", start_then_interrupt) + try: + with pytest.raises(_Interrupt): + FakeModel().generate_image(1, "p") + alive = _watchdog_threads() - before + finally: + for watchdog in started: + watchdog.stop() + assert alive == set() + + +def test_a_trip_between_the_last_checkpoint_and_the_stop_raises(fakes, aborts, monkeypatch): + # Bug caught: the watchdog stopped only after the `call_end` checkpoint, so a trip in between writes an abort record + # for a call that returns normally (a file on disk with no error to match it), or the late trip ignored. + real_stop = _watchdog.Watchdog.stop + late = [] + + def trip_then_stop(self): + if not late: + late.append(True) + fakes.counters.raise_to(STOP_LINE + 1) + late.append(self.tripped.wait(5.0)) + real_stop(self) + + monkeypatch.setattr(_watchdog.Watchdog, "stop", trip_then_stop) + with pytest.raises(DFloatWatchdogError) as excinfo: + FakeModel().generate_image(1, "p") + assert late == [True, True] + assert excinfo.value.site == "call_end" + assert [p.name for p in aborts.iterdir()] == [excinfo.value.artifact.name] + + +@pytest.mark.parametrize("margin", [30_064_771_072, 30_064_771_073]) +def test_a_margin_not_below_the_default_ceiling_is_refused_before_anything_runs(margin): + # Bug caught: a margin at or above the host ceiling accepted when the config names no ceiling (the stop line is + # then 0 or below and every sample trips), or refused only after the body ran. + model = FakeModel(watchdog=WatchdogConfig(stop_margin=margin)) + with pytest.raises(DFloatUnsupportedError, match=str(margin)): + model.generate_image(1, "p") + assert model.ran == [] + assert model._lifecycle.counters.set_loads == 0 + + +def test_a_margin_one_below_the_default_ceiling_runs(): + # Bug caught: the refusal written as `margin + 1 >= ceiling`, refusing the margin that leaves a 1-byte stop line. + model = FakeModel(watchdog=WatchdogConfig(stop_margin=30_064_771_071)) + assert model.generate_image(1, "p") == "image" + + +def test_a_direct_encode_call_is_armed_and_raises(fakes): + # Bug caught: arming tied to `generate_image` (by name or by a flag only it sets), so a caller who encodes on its + # own runs unwatched and the overrun returns. + model = FakeModel(encode_hook=overrun(fakes.counters, STOP_LINE + 1)) + with pytest.raises(DFloatWatchdogError) as excinfo: + model.encode("p") + assert (excinfo.value.site, excinfo.value.phase) == ("prompt_encoded", "encode") + assert excinfo.value.record["context"]["method"] == "encode" + + +def test_a_failing_cleanup_step_is_noted_and_the_abort_still_leaves(fakes, monkeypatch): + # Bug caught: a cleanup step that raises (here the pool clear) replacing the typed error and skipping the steps + # after it. Three steps clear the pool (the abort's own clear, the set drop's reclaim, the drain), so three notes. + def hook(model): + overrun(fakes.counters, STOP_LINE + 1)(model) + + def broken_clear(): + raise RuntimeError("pool clear failed") + + monkeypatch.setattr(mx, "clear_cache", broken_clear) + + model = FakeModel(hook=hook) + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(1, "p") + notes = getattr(excinfo.value, "__notes__", []) + assert sum("RuntimeError: pool clear failed" in note for note in notes) == 3 + assert model._lifecycle.set_resident is False + assert model.held() is None + + +def _record_starts(monkeypatch): + started = [] + real_start = _watchdog.Watchdog.start + + def start(self): + started.append(self) + return real_start(self) + + monkeypatch.setattr(_watchdog.Watchdog, "start", start) + return started + + +@pytest.mark.parametrize("level", [STOP_LINE, STOP_LINE + 1, 2 * CEILING]) +def test_a_call_that_starts_at_or_above_the_stop_line_raises_before_any_work( + fakes, aborts, monkeypatch, level +): + # Bug caught: no reading at arm time, so a process already over the line starts the sampler and the call (the + # first sample, about 50 ms in, trips it; above the hard line it ends the process); or `>` instead of "at or + # above" at the stop line itself. 2 * CEILING is above the hard line: the call raises and nothing exits. + started = _record_starts(monkeypatch) + fakes.counters.raise_to(level) + model = FakeModel() + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(1, "p") + err = excinfo.value + assert (err.site, err.reason, err.phase) == ("call_start", "memory", None) + assert err.record["verdict_memory"] == level + assert err.artifact.parent == aborts + assert (started, model.ran, model._lifecycle.counters.set_loads) == ([], [], 0) + assert fakes.exits.codes == [] + + +def test_a_call_that_starts_one_byte_below_the_stop_line_runs(fakes, monkeypatch): + # Bug caught: the arm-time comparison one byte too eager (or against the ceiling minus twice the margin). + started = _record_starts(monkeypatch) + fakes.counters.raise_to(STOP_LINE - 1) + assert FakeModel().generate_image(1, "p") == "image" + assert len(started) == 1 + + +def test_another_error_after_a_trip_names_the_trip_and_cleans_up(fakes, aborts): + # Bug caught: an error other than the typed one leaving a tripped call with no word of the trip or its record, + # and with the set resident and the frames alive (no abort cleanup). + def hook(model): + overrun(fakes.counters, STOP_LINE + 1)(model) + raise ValueError("model bug") + + model = FakeModel(hook=hook) + with pytest.raises(ValueError, match="model bug") as excinfo: + model.generate_image(1, "p") + (record,) = aborts.iterdir() + notes = getattr(excinfo.value, "__notes__", []) + assert any("(memory, phase denoise)" in n and f"record: {record}" in n for n in notes), notes + assert model._lifecycle.set_resident is False + assert model.held() is None + + +def test_another_error_with_no_trip_is_left_alone(fakes): + # Bug caught: the trip note and the abort cleanup run for every error, so a plain failure drops the set and reads + # as a watchdog stop. + def hook(model): + raise ValueError("model bug") + + model = FakeModel(hook=hook) + with pytest.raises(ValueError, match="model bug") as excinfo: + model.generate_image(1, "p") + assert getattr(excinfo.value, "__notes__", []) == [] + assert model._lifecycle.set_resident is True + + +def test_the_default_folder_is_created_private(fakes, aborts): + # Bug caught: the default folder made with the umask's mode (0o755), so other users can list the records. + with pytest.raises(DFloatWatchdogError) as excinfo: + FakeModel(hook=overrun(fakes.counters, STOP_LINE + 1)).generate_image(1, "p") + assert stat.S_IMODE(aborts.stat().st_mode) == 0o700 + assert excinfo.value.artifact.parent == aborts + + +def test_a_symlinked_default_folder_gets_no_record(fakes, aborts, tmp_path): + # Bug caught: a default folder that another user pre-placed as a symlink trusted, so the record lands wherever it + # points; or the refusal costing the typed error. + target = tmp_path / "elsewhere" + target.mkdir() + aborts.symlink_to(target) + with pytest.raises(DFloatWatchdogError) as excinfo: + FakeModel(hook=overrun(fakes.counters, STOP_LINE + 1)).generate_image(1, "p") + assert excinfo.value.artifact is None + assert "is a symlink" in excinfo.value.record["artifact_error"] + assert list(target.iterdir()) == [] + + +def test_a_default_folder_owned_by_another_user_gets_no_record(fakes, aborts, monkeypatch): + # Bug caught: the owner not checked, so a folder another user created (and can read) receives the record. + aborts.mkdir(mode=0o700) + real_uid = os.getuid() + monkeypatch.setattr(os, "getuid", lambda: real_uid + 1) + with pytest.raises(DFloatWatchdogError) as excinfo: + FakeModel(hook=overrun(fakes.counters, STOP_LINE + 1)).generate_image(1, "p") + assert excinfo.value.artifact is None + assert "is owned by uid" in excinfo.value.record["artifact_error"] + assert list(aborts.iterdir()) == [] + + +def test_a_symlinked_folder_the_caller_names_is_still_written(fakes, tmp_path): + # Bug caught: the default folder's checks applied to a folder the caller chose, refusing a symlink they made. + target = tmp_path / "chosen" + target.mkdir() + link = tmp_path / "link" + link.symlink_to(target) + model = FakeModel( + watchdog=WatchdogConfig(artifact_dir=link), hook=overrun(fakes.counters, STOP_LINE + 1) + ) + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(1, "p") + assert excinfo.value.artifact is not None + assert [p.name for p in target.iterdir()] == [excinfo.value.artifact.name] + + +def test_a_default_folder_that_is_a_file_gets_no_record(fakes, aborts): + # Bug caught: a non-folder at the default path passed on to the write, which then fails with a less useful error. + aborts.write_text("not a folder") + with pytest.raises(DFloatWatchdogError) as excinfo: + FakeModel(hook=overrun(fakes.counters, STOP_LINE + 1)).generate_image(1, "p") + assert excinfo.value.artifact is None + assert "is not a folder" in excinfo.value.record["artifact_error"] + assert aborts.read_text() == "not a folder" + + +def test_a_default_folder_that_cannot_be_made_still_raises_the_typed_error( + fakes, tmp_path, monkeypatch +): + # Bug caught: the folder check raising on the sampler thread (a missing parent), which kills the sampler before the + # trip is set, so the call runs on unwatched. + root = tmp_path / "missing" / "aborts" + monkeypatch.setattr(_pipeline, "_artifact_root", lambda: root) + with pytest.raises(DFloatWatchdogError) as excinfo: + FakeModel(hook=overrun(fakes.counters, STOP_LINE + 1)).generate_image(1, "p") + assert excinfo.value.artifact is None + assert excinfo.value.record["artifact_error"].startswith("FileNotFoundError") + assert not root.parent.exists() + + +def test_an_entry_trip_drops_a_set_left_resident_so_the_next_call_runs(fakes, monkeypatch): + # Bug caught: the call_start raise skipping the abort cleanup, so a set left resident by an earlier call keeps + # memory over the line and every later call raises at entry for good. + model = FakeModel() + assert model.generate_image(1, "p") == "image" + assert model._lifecycle.set_resident is True + started = _record_starts(monkeypatch) + fakes.counters.raise_to(STOP_LINE + 1) + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(1, "p") + assert excinfo.value.site == "call_start" + assert (started, model.ran) == ([], ["body"]) + assert model._lifecycle.set_resident is False + fakes.counters.raise_to(0) + assert model.generate_image(1, "p") == "image" + assert model._lifecycle.counters.set_loads == 2 + + +def test_memory_that_falls_after_the_arm_time_drain_does_not_raise(fakes, aborts, monkeypatch): + # Bug caught: the arm-time reading trips on pages an earlier unarmed call freed but the driver has not yet + # released (they leave the footprint only after the next GPU submission), so a call raises at call_start for + # memory that a drain gives back. + started = _record_starts(monkeypatch) + monkeypatch.setattr(_drain, "_kick", lambda: fakes.counters.raise_to(STOP_LINE - 1)) + monkeypatch.setattr(_drain, "_sleep", lambda seconds: None) + fakes.counters.raise_to(STOP_LINE + 1) + model = FakeModel() + assert model.generate_image(1, "p") == "image" + assert len(started) == 1 + assert not aborts.exists() + + +def test_a_call_below_the_stop_line_reads_once_at_arm_time_and_never_drains(fakes, monkeypatch): + # Bug caught: the drain (0.25 s at most, plus a GPU wait) run on every call, or a second arm-time reading taken + # when the first is already below the line. + events = [] + real_sample = _watchdog.Watchdog._sample + real_drain = _drain.drain + real_start = _watchdog.Watchdog.start + + def sample(self): + if threading.current_thread() is threading.main_thread(): + events.append("read") + return real_sample(self) + + def drain(*args, **kwargs): + events.append("drain") + return real_drain(*args, **kwargs) + + def start(self): + events.append("start") + return real_start(self) + + monkeypatch.setattr(_watchdog.Watchdog, "_sample", sample) + monkeypatch.setattr(_drain, "drain", drain) + monkeypatch.setattr(_watchdog.Watchdog, "start", start) + fakes.counters.raise_to(STOP_LINE - 1) + assert FakeModel().generate_image(1, "p") == "image" + assert events[: events.index("start") + 1] == ["read", "start"] + + +def test_a_watchdog_reassigned_to_false_after_construction_is_refused_with_the_typed_error(fakes): + # Bug caught: the constructor's check not repeated at call time, so `model.watchdog = False` fails with an + # AttributeError from deep inside the decorator instead of the package's refusal. + model = FakeModel() + model.watchdog = False + with pytest.raises(DFloatUnsupportedError, match="watchdog must be a WatchdogConfig"): + model.generate_image(1, "p") + assert model.ran == [] + + +def test_an_own_default_folder_open_to_everyone_is_made_private_and_written(fakes, aborts): + # Bug caught: an existing default folder this user owns accepted at any mode, so an own 0o777 folder (made by an + # earlier tool, or a loose umask) lets every user list and replace the records. + aborts.mkdir() + aborts.chmod(0o777) + with pytest.raises(DFloatWatchdogError) as excinfo: + FakeModel(hook=overrun(fakes.counters, STOP_LINE + 1)).generate_image(1, "p") + assert stat.S_IMODE(aborts.stat().st_mode) == 0o700 + assert excinfo.value.artifact is not None + assert excinfo.value.artifact.parent == aborts + assert [p.name for p in aborts.iterdir()] == [excinfo.value.artifact.name] diff --git a/tests/test_api_watchdog_gaps.py b/tests/test_api_watchdog_gaps.py new file mode 100644 index 0000000..8413a41 --- /dev/null +++ b/tests/test_api_watchdog_gaps.py @@ -0,0 +1,170 @@ +"""Three things about the armed model call that the other watchdog tests leave open (mflux-free). + +1. The autouse ``_api_watchdog_fakes`` fixture's exit recorder is in force: an escalation inside a test lands in the + recorder and pytest goes on. +2. ``clear_call_frames(outer=...)``: a call made inside the caller's own ``except`` block clears its own frames but + leaves the frames of the exception the caller is handling. +3. An explicit ``WatchdogConfig(artifact_dir=..., grace=..., wall_budget=...)`` reaches the armed watchdog. + +A small decorated fake carries what ``with_call_caps`` reads (``watchdog``, ``open_phase``, ``_model``) and runs one +checkpoint after a hook. The fixture fixes the host ceiling at 30_064_771_072 bytes (a 32 GiB Mac minus 4 GiB), so +every number below is a literal. Waits poll with a 5 s timeout. +""" + +import time +import weakref + +import pytest + +from mlx_dfloat import _guard +from mlx_dfloat.errors import DFloatWatchdogError +from mlx_dfloat.mflux import _pipeline +from mlx_dfloat.mflux._watchconfig import WatchdogConfig + +# 32 GiB - 4 GiB, and that minus the default 1 GiB stop margin (27 GiB). +CEILING = 30_064_771_072 +STOP_LINE = 28_991_029_248 + + +@pytest.fixture(autouse=True) +def default_root(tmp_path, monkeypatch): + """The folder a config with no ``artifact_dir`` writes to, under the test's own folder.""" + root = tmp_path / "default-root" + monkeypatch.setattr(_pipeline, "_artifact_root", lambda: root) + return root + + +@pytest.fixture +def fakes(request): + """The autouse ``_api_watchdog_fakes`` value: the fake allocator and the exit recorder of this test.""" + return request.getfixturevalue("_api_watchdog_fakes") + + +class GapModel: + """A model class as the decorator sees it: the hook runs in the denoise phase, then one checkpoint.""" + + def __init__(self, watchdog, hook): + self.watchdog = watchdog + self._model = "gap-model" + self.open_phase = None + self.hook = hook + + @_pipeline.with_call_caps + def generate_image(self, seed=1): + self.open_phase = "denoise" + self.hook(self) + _guard.checkpoint("block_end") + self.open_phase = None + return "image" + + +def _poll(condition): + deadline = time.monotonic() + 5.0 + while not condition(): + if time.monotonic() > deadline: + return False + time.sleep(0.01) + return True + + +def _trip_and_wait(counters, level, seen): + def hook(model): + counters.raise_to(level) + seen["tripped"] = _guard.active().tripped.wait(5.0) + + return hook + + +def test_an_escalation_during_a_test_lands_in_the_exit_recorder(fakes): + # Bug caught: the fixture not putting its recorder in front of the armed watchdog's exit, so a call that reaches + # the ceiling ends pytest with code 70 and no summary instead of recording the code. + seen = {} + + def hook(model): + fakes.counters.raise_to(CEILING) + seen["exited"] = _poll(lambda: fakes.exits.codes != []) + + with pytest.raises(DFloatWatchdogError): + GapModel(WatchdogConfig(), hook).generate_image() + + assert seen["exited"] is True + assert fakes.exits.take() == [70] + + +def test_a_call_inside_the_callers_except_block_leaves_the_handled_exceptions_frames(fakes): + # Bug caught: the decorator not taking the exception being handled at entry as the walk's stop (outer None), so + # clearing the abort's chain also clears the caller's handled exception's frames (the abort's __context__). + class Evidence: + pass + + def failing_helper(): + evidence = Evidence() + refs.append(weakref.ref(evidence)) + raise ValueError("the caller's own failure") + + refs = [] + seen = {} + model = GapModel(WatchdogConfig(), _trip_and_wait(fakes.counters, STOP_LINE + 1, seen)) + try: + failing_helper() + except ValueError as exc: + handled = exc + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image() + + assert excinfo.value.__context__ is handled + assert seen["tripped"] is True + assert refs[0]() is not None # failing_helper's frame still holds its local + + +def test_an_explicit_artifact_dir_receives_the_record(tmp_path, fakes, default_root): + # Bug caught: the decorator ignoring config.artifact_dir (always the default root). + seen = {} + mine = tmp_path / "mine" + model = GapModel( + WatchdogConfig(artifact_dir=mine), _trip_and_wait(fakes.counters, STOP_LINE + 1, seen) + ) + + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image() + + assert seen["tripped"] is True + assert excinfo.value.artifact is not None + assert excinfo.value.artifact.parent == mine + assert excinfo.value.artifact.is_file() + assert not default_root.exists() + + +def test_an_explicit_wall_budget_trips_with_reason_wall(fakes): + # Bug caught: the decorator not passing config.wall_budget to the watchdog (no wall limit at all), so the call + # runs past its budget and returns. + seen = {} + + def hook(model): + seen["tripped"] = _guard.active().tripped.wait(5.0) + + with pytest.raises(DFloatWatchdogError) as excinfo: + GapModel(WatchdogConfig(wall_budget=0.2), hook).generate_image() + + assert seen["tripped"] is True + assert excinfo.value.reason == "wall" + assert excinfo.value.record["budget"] == 0.2 + + +def test_an_explicit_grace_ends_the_process_when_no_checkpoint_comes_in_time(fakes): + # Bug caught: the decorator not passing config.grace (the 10 s default instead), so a trip that no checkpoint + # takes for 0.3 s is not escalated within the 5 s this test waits. + seen = {} + + def hook(model): + # A wall trip with memory at zero: grace still ends a wall trip, and the ceiling is far away. + seen["tripped"] = _guard.active().tripped.wait(5.0) + seen["exited"] = _poll(lambda: fakes.exits.codes != []) + + with pytest.raises(DFloatWatchdogError) as excinfo: + GapModel(WatchdogConfig(wall_budget=0.2, grace=0.3), hook).generate_image() + + assert seen["tripped"] is True + assert seen["exited"] is True + assert excinfo.value.reason == "wall" + assert fakes.exits.take() == [71] diff --git a/tests/test_api_watchdog_proof.py b/tests/test_api_watchdog_proof.py new file mode 100644 index 0000000..fc62b48 --- /dev/null +++ b/tests/test_api_watchdog_proof.py @@ -0,0 +1,598 @@ +"""The pure parts of the API watchdog's hardware proof: the per-phase ceilings, the unit verdicts, resume. + +The synthetic peaks are in MiB so every expected stop line and ceiling can be worked by hand in the comments, +never taken from the code. The offline test feeds every committed FLUX.2 Klein 4B record through the derivation. +No test here imports mflux, builds a model or runs a unit. +""" + +import json +from pathlib import Path +from typing import Any + +import pytest + +GIB = 1_073_741_824 +MIB = 1_048_576 +REPO = Path(__file__).resolve().parent.parent + +# The headroom rule from the proof's spec: at least 0.4 GiB (the records differ by about 0.3 GiB between runs). +MIN_HEADROOM = 0.4 * GIB + +PEAKS: dict[str, Any] = { + "label": "sampled at phase boundaries", + "encode": {"footprint_start": 400 * MIB, "mlx_peak": 6000 * MIB, "footprint_end": 6400 * MIB}, + # Set load opens on the encoder's residue (6300 MiB), above its own top (5600 MiB). + "set_load": { + "footprint_start": 6300 * MIB, + "mlx_peak": 5000 * MIB, + "footprint_end": 5600 * MIB, + }, + "denoise": { + "footprint_start": 5600 * MIB, + "mlx_peak": 6600 * MIB, + "footprint_end": 7600 * MIB, + "watched_peak": 7800 * MIB, + }, + "vae": { + "footprint_start": 7600 * MIB, + "mlx_peak": 11000 * MIB, + "footprint_end": 6000 * MIB, + "watched_peak": 11500 * MIB, + }, +} + + +def _peaks(**changes: dict[str, int]) -> dict[str, Any]: + peaks = {k: dict(v) if isinstance(v, dict) else v for k, v in PEAKS.items()} + for phase, fields in changes.items(): + peaks[phase].update(fields) + return peaks + + +def test_raise_units_stop_half_a_margin_under_the_phase_peak_and_set_load_mid_climb(): + # Bug: the stop line placed at the phase midpoint for encode, denoise or the VAE (ceiling under the VAE's sampled + # peak), or the set load's high taken from its start footprint (the encoder's residue), or a sampled peak + # ignored; or set load placed half a margin under its top, where the line is crossed only in the last group or + # the non-block decode after it, with no set-load checkpoint left. + from scripts._api_watchdog_proof import ceilings_for + + ceilings = ceilings_for(PEAKS, stop_margin=1024 * MIB) + + assert ceilings == { + # hi = end 6400; stop 6400 - 512 = 5888; ceiling 5888 + 1024 = 6912 + "encode": (6912 * MIB, 1024 * MIB), + # lo = encode start 400, hi = end 5600 (the start 6300 is the encoder's residue); + # stop mid-climb (400 + 5600) / 2 = 3000; ceiling 3000 + 1024 = 4024 + "set_load": (4024 * MIB, 1024 * MIB), + # hi = sampled 7800; stop 7288; ceiling 8312 + "denoise": (8312 * MIB, 1024 * MIB), + # hi = sampled 11500; stop 10988; ceiling 12012 + "vae": (12012 * MIB, 1024 * MIB), + } + + +def test_a_margin_of_twice_the_headroom_or_less_places_the_line_for_an_exit(): + # Bug: U5's 64 MiB margin placed like a raise (32 MiB under the peak: never isolable, so every run stops at U0), + # or the exit window not centred between the earlier peak and the VAE's peak. + from scripts._api_watchdog_proof import ceilings_for + + # VAE: lo = max(set load 6300, denoise 7800) = 7800, hi = 11500; stop (7800 + 11500 - 64) // 2 = 9618 + assert ceilings_for(PEAKS, stop_margin=64 * MIB)["vae"] == (9682 * MIB, 64 * MIB) + + +def test_the_mode_switch_sits_at_twice_the_headroom(): + # Bug: `>` turned into `>=` in the mode choice, so a margin of exactly twice the headroom places a raise whose + # peak sits only one headroom under the ceiling. + from scripts._api_watchdog_proof import ceilings_for + + headroom = 100 * MIB + # raise: VAE stop 11500 - 100 = 11400 (margin 200 + 2 bytes: half is 100 MiB + 1) + raise_line = ceilings_for(PEAKS, stop_margin=200 * MIB + 2, headroom=headroom)["vae"] + assert raise_line == (11500 * MIB - (100 * MIB + 1) + 200 * MIB + 2, 200 * MIB + 2) + # exit: stop (7800 + 11500 - 200) // 2 = 9550, ceiling 9750 + assert ceilings_for(PEAKS, stop_margin=200 * MIB, headroom=headroom)["vae"] == ( + 9750 * MIB, + 200 * MIB, + ) + + +@pytest.mark.parametrize("field", ["footprint_start", "watched_after"]) +@pytest.mark.parametrize( + ("residue", "derived"), + [ + # denoise stop 7288; the earlier peak is set load's; 7288 - 410 = 6878 is the boundary + (6878 * MIB - 1, True), + (6878 * MIB, False), + ], +) +def test_a_stop_line_within_headroom_of_an_earlier_peak_is_not_isolable(field, residue, derived): + # Bug: `>` turned into `>=`, the headroom dropped, or set load's start footprint (or the stretch sampled after + # it) left out of the earlier peak: a unit armed through set load would trip there, not in denoise. + from scripts._api_watchdog_proof import ceilings_for + + ceilings = ceilings_for(_peaks(set_load={field: residue}), stop_margin=1024 * MIB) + + assert (ceilings["denoise"] is not None) is derived + + +def test_the_headroom_default_is_at_least_0_4_gib(): + # Bug: the headroom constant shrunk under the run-to-run spread of the records. + from scripts._api_watchdog_proof import HEADROOM + + assert HEADROOM >= MIN_HEADROOM + + +@pytest.mark.parametrize( + ("settled", "derived"), + [ + # stop = (settled + 5600) // 2 must pass settled + 410, so 5600 - settled must pass 820 after the floor: + # settled 4780 - 2 bytes gives stop 5190 MiB - 1, 410 MiB + 1 over it; 4780 - 1 byte gives exactly 410 MiB + (4780 * MIB - 2, True), + (4780 * MIB - 1, False), + ], +) +def test_set_load_takes_its_low_bound_from_the_settled_reading(settled, derived): + # Bug: the settled reading ignored (the encode start, 400 MiB, used instead), or compared with `>=`. + from scripts._api_watchdog_proof import ceilings_for + + ceiling = ceilings_for(PEAKS, stop_margin=1024 * MIB, settled=settled)["set_load"] + + assert (ceiling is not None) is derived + if derived: + # stop 5190 MiB - 1, ceiling 5190 + 1024 = 6214 MiB - 1 + assert ceiling == (6214 * MIB - 1, 1024 * MIB) + + +@pytest.mark.parametrize( + ("peaks", "expected_stop"), + [ + # the overall peak is the VAE's sampled 11500; stop 11500 + 1024 = 12524 + (PEAKS, 12524 * MIB), + # the overall peak sits in the stretch after the denoise (12000), not in the VAE + (_peaks(denoise={"watched_after": 12000 * MIB}), 13024 * MIB), + # the overall peak is the encode's start footprint (13000) + (_peaks(encode={"footprint_start": 13000 * MIB}), 14024 * MIB), + ], +) +def test_the_retry_line_sits_1_gib_over_the_baselines_overall_peak(peaks, expected_stop): + # Bug: the retry line taken from one phase only (the VAE), a sampled field left out, the headroom dropped, or the + # ceiling not one margin over the stop: then a retry whose drain freed nothing still completes, unseen. + from scripts._api_watchdog_proof import retry_line + + assert retry_line(peaks, stop_margin=1024 * MIB) == (expected_stop + 1024 * MIB, 1024 * MIB) + + +def test_no_retry_line_without_a_phase_record(): + # Bug: a KeyError or a line at 0 + headroom (every retry trips) when the baseline kept no peaks. + from scripts._api_watchdog_proof import retry_line + + assert retry_line({"label": "x"}, stop_margin=1024 * MIB) is None + + +@pytest.mark.parametrize( + ("hi", "derived"), + [ + # lo 7800, margin 64: centred, so stop - lo = hi - ceiling = (hi - 7800 - 64) / 2 must pass 410: hi > 8684 + (8684 * MIB, False), + (8684 * MIB + 2, True), + ], +) +def test_an_exit_line_needs_headroom_on_both_sides(hi, derived): + # Bug: the exit placement accepted with the peak too close to the ceiling (U5 might end by a raise instead). + from scripts._api_watchdog_proof import ceilings_for + + peaks = _peaks( + vae={"watched_peak": hi, "mlx_peak": 0, "footprint_start": 0, "footprint_end": 0} + ) + + assert (ceilings_for(peaks, stop_margin=64 * MIB)["vae"] is not None) is derived + + +@pytest.mark.parametrize( + ("dropped", "expected"), + [ + # Set load's planning low bound is the encode's start footprint. + ("encode", {"encode": None, "set_load": None, "denoise": "derived", "vae": "derived"}), + ("set_load", {"encode": "derived", "set_load": None, "denoise": None, "vae": None}), + ("denoise", {"encode": "derived", "set_load": "derived", "denoise": None, "vae": None}), + ], +) +def test_a_missing_earlier_phase_record_gives_no_ceiling(dropped, expected): + # Bug: a KeyError on a missing record, or a low bound taken from only the phases that are there. + from scripts._api_watchdog_proof import ceilings_for + + peaks = {name: record for name, record in PEAKS.items() if name != dropped} + + ceilings = ceilings_for(peaks, stop_margin=GIB) + + assert {p: None if c is None else "derived" for p, c in ceilings.items()} == expected + + +def test_phase_peaks_keep_each_phase_and_the_stretch_after_it(): + # Bug: a sample taken between phases counted in the next phase, or dropped (the earlier peak a later unit must + # clear would miss the encoder's residue), or a lower sample overwriting a higher one. + from scripts._api_watchdog_proof import PhasePeaks + + sampled = PhasePeaks() + for phase, watched in [ + (None, 50), # before the first phase: no phase to charge + ("encode", 10), + ("encode", 30), + ("encode", 20), + (None, 25), + (None, 40), + ("set_load", 5), + ]: + sampled.add(phase, watched) + + merged = sampled.into({"label": "x", "encode": {"mlx_peak": 1}, "set_load": {"mlx_peak": 2}}) + + assert merged == { + "label": "x", + "encode": {"mlx_peak": 1, "watched_peak": 30, "watched_after": 40}, + "set_load": {"mlx_peak": 2, "watched_peak": 5}, + } + + +def test_the_sampler_samples_on_its_thread_and_once_more_at_stop(): + # Bug: the thread never samples (the U0 peaks are boundary-only again), or stop() skips its last sample, so + # the stretch after the decode is lost. + import threading + + from scripts._api_watchdog_proof import PhaseSampler + + reads: list[int] = [] + two = threading.Event() + phase = ["vae"] + + def read() -> int: + reads.append(len(reads) + 1) + if len(reads) >= 2: + two.set() + return reads[-1] + + sampler = PhaseSampler(read, lambda: phase[0], interval=0.001).start() + assert two.wait(timeout=5) + phase[0] = None # the call has closed its last phase + sampler.stop() + + assert sampler.sampled.peaks["vae"]["watched_peak"] >= 2 + assert sampler.sampled.peaks["vae"]["watched_after"] == reads[-1] + + +# ---- unit verdicts ---- + + +def _exited(code, *, phase, escalation, reason="memory"): + artifact = {"reason": reason, "escalation": escalation, "context": {"phase": phase}} + return {"exit_code": code, "result": None, "artifact": artifact} + + +def _baseline(code, *, completed, image_saved): + return { + "exit_code": code, + "result": {"completed": completed, "image_saved": image_saved}, + "artifact": None, + } + + +def _raised(*, phase, site, reason="memory", retry=None, after_abort=None): + raised = {"type": "DFloatWatchdogError", "reason": reason, "phase": phase, "site": site} + # The armed line: ceiling 4096 MiB, margin 1024 MiB, so the stop line is 3072 MiB. + result: dict[str, Any] = {"ceiling": [4096 * MIB, 1024 * MIB], "raised": raised} + if after_abort is not None: + result["watched_after_abort"] = after_abort + if retry is not None: + result["retry"] = retry + return {"exit_code": 0, "result": result, "artifact": None} + + +DONE = {"completed": True, "raised": None} +# The watched memory after the stopped call's cleanup, 1024 MiB under the stop line. +RELEASED = 2048 * MIB +RETRY_RAISED = { + "type": "DFloatWatchdogError", + "reason": "memory", + "phase": "vae", + "site": "call_end", +} + + +@pytest.mark.parametrize( + ("unit", "outcome", "expected"), + [ + ("U1", _raised(phase="encode", site="prompt_encoded"), "pass"), + ("U1", _raised(phase="encode", site="encoder_loaded"), "pass"), + ("U1", _raised(phase="encode", site="call_start"), "fail"), # stopped before any work + ("U1", _raised(phase="set_load", site="set_group"), "fail"), + ("U1", _exited(70, phase="encode", escalation="ceiling"), "fail"), + ("U2", _raised(phase="set_load", site="set_load_start"), "pass"), + ("U2", _raised(phase="set_load", site="set_group"), "pass"), + ("U2", _raised(phase="set_load", site="call_start"), "fail"), + ("U2", _raised(phase="encode", site="encoder_loaded"), "fail"), + ("U2", _raised(phase="set_load", site="block_start"), "fail"), + ("U2", _raised(phase="set_load", site="set_group", reason="wall"), "fail"), + ("U3", _raised(phase="denoise", site="block_start"), "pass"), + ("U3", _raised(phase="denoise", site="block_end"), "pass"), + ("U3", _raised(phase="denoise", site="call_start"), "fail"), + ("U3", _raised(phase="vae", site="call_end"), "fail"), + ("U3", _raised(phase="set_load", site="block_start"), "fail"), + ("U4", _raised(phase="vae", site="call_end"), "pass"), + # The finished image must be discarded by a raise: an exit proves the same thing U5 does. + ("U4", _exited(70, phase="vae", escalation="ceiling"), "fail"), + ("U4", _raised(phase="vae", site="call_start"), "fail"), + ("U4", _raised(phase="vae", site="block_end"), "fail"), + ("U4", _raised(phase="denoise", site="call_end"), "fail"), + ("U5", _exited(70, phase="vae", escalation="ceiling"), "pass"), + # A memory trip ends by grace only when the sampler died, so a grace exit is not the watchdog working. + ("U5", _exited(70, phase="vae", escalation="grace"), "fail"), + ("U5", _exited(70, phase="vae", escalation=None), "fail"), + ("U5", _exited(70, phase="denoise", escalation="ceiling"), "fail"), + ("U5", _exited(71, phase="vae", escalation="grace", reason="wall"), "fail"), + ("U5", _raised(phase="vae", site="call_end"), "fail"), + ( + "U6", + _raised(phase="set_load", site="set_group", retry=DONE, after_abort=RELEASED), + "pass", + ), + # the stopped call's memory came back to 1 byte under the 3072 MiB stop line: released + ( + "U6", + _raised(phase="set_load", site="set_group", retry=DONE, after_abort=3072 * MIB - 1), + "pass", + ), + # on or over the stop line after the cleanup: the set's pages were kept, even if the retry completes + ( + "U6", + _raised(phase="set_load", site="set_group", retry=DONE, after_abort=3072 * MIB), + "fail", + ), + ( + "U6", + _raised(phase="set_load", site="set_group", retry=DONE, after_abort=5000 * MIB), + "fail", + ), + ( + "U6", + _raised(phase="set_load", site="set_group", retry=DONE), + "fail", + ), # no reading after the abort + ( + "U6", + _raised( + phase="set_load", + site="set_group", + retry={"completed": False, "raised": RETRY_RAISED}, + after_abort=RELEASED, + ), + "fail", + ), + ( + "U6", + _raised(phase="set_load", site="set_load_start", retry=DONE, after_abort=RELEASED), + "pass", + ), + ( + "U6", + _raised(phase="set_load", site="set_group", after_abort=RELEASED), + "fail", + ), # no retry ran + ( + "U6", + _raised( + phase="set_load", site="set_group", retry={"completed": False}, after_abort=RELEASED + ), + "fail", + ), + ( + "U6", + _raised(phase="denoise", site="block_start", retry=DONE, after_abort=RELEASED), + "fail", + ), + ( + "U6", + {"exit_code": 0, "result": {"ceiling": [1, 1], "raised": None, "retry": DONE}}, + "fail", + ), + ("U6", _exited(70, phase="set_load", escalation="ceiling"), "fail"), + ("U3", {"exit_code": 0, "result": {"ceiling": None}, "artifact": None}, "not isolable"), + ("U0", _baseline(0, completed=True, image_saved=True), "pass"), + ("U0", _baseline(70, completed=True, image_saved=True), "fail"), + ("U0", _baseline(0, completed=False, image_saved=True), "fail"), + ("U0", _baseline(0, completed=True, image_saved=False), "fail"), + ], +) +def test_unit_verdicts(unit, outcome, expected): + # Bug: the verdict ignores the phase, the site or the trip's reason; U4 passes on an exit; U6 passes without its + # completed retry, without the abort before it, or with the watched memory after the abort at or over its stop line + # (the stopped call kept its pages), or without that reading; a raise at call_start (before any work) passes; "not + # isolable" reads as a pass; or the baseline passes on a non-zero exit, an unfinished run or an unsaved image. + from scripts._api_watchdog_proof import unit_verdict + + assert unit_verdict(unit, outcome) == expected + + +@pytest.mark.parametrize("unit", ["U7", "u1", ""]) +def test_an_unknown_unit_is_refused(unit): + # Bug: the unit check missing, so an unknown unit falls through to PHASE_OF and raises KeyError (or a lowercase + # name is accepted), not the documented ValueError. + from scripts._api_watchdog_proof import unit_verdict + + with pytest.raises(ValueError, match="unknown unit"): + unit_verdict(unit, _baseline(0, completed=True, image_saved=True)) + + +def test_a_resumed_run_skips_finished_units(tmp_path: Path): + # Bug: a finished unit runs again (its JSON ignored), or a half-written one counts as finished. + from scripts._api_watchdog_proof import pending_units + + (tmp_path / "U1.json").write_text(json.dumps({"unit": "U1", "verdict": "pass"})) + (tmp_path / "U2.json.tmp").write_text("{") + (tmp_path / "U3.outcome.json").write_text("{}") + + assert pending_units(tmp_path) == ["U0", "U2", "U3", "U4", "U5", "U6"] + + +# ---- the committed FLUX.2 Klein 4B records ---- + +RECORDS = [ + "bench/results/tiers/flux2-klein-4b-1024.json", + "bench/results/tiers/flux2-klein-base-4b-1024.json", + "bench/results/tiers/flux2-klein-base-4b-1024-tier16.json", + "bench/results/tiers/flux2-klein-base-4b-1024-tier24.json", + "bench/results/identity/flux2-klein-4b-1024/df11-result.json", + "bench/results/identity/flux2-klein-base-4b-1024/df11-result.json", +] +# The 16 GB tier frees the transformer set before the decode: its VAE peak (6.93 GiB) is under the denoise +# peak (7.61 GiB), so no line can stop the decode without stopping denoise first. The proof runs the default tier. +VAE_BELOW_DENOISE = {"bench/results/tiers/flux2-klein-base-4b-1024-tier16.json"} + + +def _find_peaks(data: Any) -> dict[str, Any] | None: + if isinstance(data, dict): + if isinstance(data.get("peaks"), dict) and "encode" in data["peaks"]: + return data["peaks"] + for value in data.values(): + if (found := _find_peaks(value)) is not None: + return found + return None + + +def _load(rel: str) -> tuple[dict[str, Any], int]: + """A committed record's boundary peaks, with its call-wide sampled peak charged to its highest phase. + + These records predate the per-phase sampled peak. The call-wide ``footprint_peak_bytes`` (the watchdog's + 0.05 s samples) is above every boundary reading, so it is charged to the phase whose boundary readings are + highest; without it, the VAE's high would be 0.9-1.0 GiB under what the watchdog sees. + """ + data = json.loads((REPO / rel).read_text()) + peaks = {k: dict(v) if isinstance(v, dict) else v for k, v in _find_peaks(data).items()} # type: ignore[union-attr] + call_peak = int(data["footprint_peak_bytes"]) + phases = ("encode", "set_load", "denoise", "vae") + top = max( + phases, + key=lambda p: max(peaks[p][k] for k in ("footprint_start", "mlx_peak", "footprint_end")), + ) + peaks[top]["watched_peak"] = call_peak + return peaks, call_peak + + +def _all(record: dict[str, int]) -> int: + return max(v for k, v in record.items() if k != "active_at_start") + + +def _own(phase: str, record: dict[str, int]) -> int: + if phase == "set_load": # its start footprint is the encoder's residue in a baseline run + return max(record["mlx_peak"], record["footprint_end"]) + return _all(record) + + +def _earlier(phase: str, peaks: dict[str, Any]) -> int: + if phase in ("encode", "set_load"): + return peaks["encode"]["footprint_start"] + if phase == "denoise": + return _all(peaks["set_load"]) + return max(_all(peaks["set_load"]), _all(peaks["denoise"])) + + +@pytest.mark.parametrize("rel", RECORDS) +def test_every_committed_klein_4b_record_places_a_line_for_each_unit(rel): + # Bug: the derivation cannot stop a unit on the records this model really produces (the old midpoint rule left + # set load not isolable six times out of six and put the VAE ceiling under the sampled decode peak). + import scripts.prove_api_watchdog as prove + from scripts._api_watchdog_proof import PHASE_OF, ceilings_for + + peaks, _ = _load(rel) + for unit, phase in PHASE_OF.items(): + margin = prove.ESCALATION_MARGIN if unit == "U5" else GIB + line = ceilings_for(peaks, stop_margin=margin)[phase] + if phase == "vae" and rel in VAE_BELOW_DENOISE: + assert line is None, unit + continue + assert line is not None, unit + ceiling, stop_margin = line + stop = ceiling - stop_margin + lo, hi = _earlier(phase, peaks), _own(phase, peaks[phase]) + # the earlier phases and the arm-time reading stay under the line + assert stop > lo + MIN_HEADROOM, unit + if unit == "U5": + assert hi > ceiling + MIN_HEADROOM, unit # the decode passes the hard line: exit 70 + elif phase == "set_load": + # crossed before the tail with no set-load checkpoint: the last group plus the non-block decode + assert hi - stop > _set_load_tail(rel), unit + else: + # crosses the stop, not the ceiling + assert stop + MIN_HEADROOM < hi < ceiling - MIN_HEADROOM, unit + expected_blocked = ["U4", "U5"] if rel in VAE_BELOW_DENOISE else [] + assert prove._not_isolable(peaks) == expected_blocked + + +# Compressed group sizes in bytes, in the order the set loads them (sorted names), read from the safetensors +# headers of mingyi456/FLUX.2-klein-4B-DF11@d29a2c2 (distilled) and mingyi456/FLUX.2-klein-base-4B-DF11@b887c73. +# Five non-block groups, single blocks 0, 1, 10-19, 2-9, then double blocks 0-4. +GROUPS_DISTILLED = ( + *(31102869, 77274555, 76422697, 27252494, 40906061), + *(166173729, 166061116, 166101474, 166241621, 166283109, 166291721, 166407701, 166590094), + *(166618477, 166820360, 166856951, 167054860, 166293159, 166684440, 167202190, 167388461), + *(166153645, 166069826, 165987779, 166100410), + *(331860073, 331018225, 331084614, 331171115, 331565605), +) +GROUPS_BASE = ( + *(31097515, 77270676, 76426672, 27248241, 40908632), + *(166172845, 166060147, 166101998, 166244554, 166284512, 166293371, 166411738, 166595908), + *(166623546, 166828945, 166861230, 167052344, 166292112, 166685588, 167201234, 167389902), + *(166149637, 166069235, 165988347, 166100828), + *(331857016, 331013479, 331079435, 331164200, 331559145), +) + + +def _groups(rel: str) -> tuple[int, ...]: + return GROUPS_BASE if "base" in rel else GROUPS_DISTILLED + + +def _sizes(rel: str) -> dict[str, int]: + data = json.loads((REPO / rel).read_text()) + + def find(node: Any) -> dict[str, int] | None: + if isinstance(node, dict): + if isinstance(node.get("sizes"), dict) and "nonblock" in node["sizes"]: + return node["sizes"] + for value in node.values(): + if (found := find(value)) is not None: + return found + return None + + sizes = find(data) + assert sizes is not None, rel + return sizes + + +def _set_load_tail(rel: str) -> int: + return _sizes(rel)["nonblock"] + _groups(rel)[-1] + + +@pytest.mark.parametrize("rel", RECORDS) +@pytest.mark.parametrize("planned", [True, False], ids=["planned", "settled"]) +def test_the_set_load_line_is_crossed_with_set_load_checkpoints_left(rel, planned): + # Bug: the set-load line placed half a margin under the phase top: the climb passes it only while the last group + # is read or the non-block groups decode, the next checkpoint is block_start, and the unit fails; or so late in + # the climb that the raise one group after the crossing lands within the headroom of the ceiling. + from scripts._api_watchdog_proof import ceilings_for + + peaks, _ = _load(rel) + groups = _groups(rel) + sizes = _sizes(rel) + # Each read is one copy into MLX and the freed compressed non-block groups stay counted, so the watched memory + # at the checkpoint before group i is the start plus the groups read so far; the start is the phase end less + # every group and the decoded non-block weights (the unit's settled reading after its pre-encode). + start = peaks["set_load"]["footprint_end"] - sizes["compressed"] - sizes["nonblock"] + line = ceilings_for(peaks, stop_margin=GIB, settled=None if planned else start)["set_load"] + assert line is not None + ceiling, margin = line + stop = ceiling - margin + readings = [start + sum(groups[:i]) for i in range(len(groups))] + over = [i for i, reading in enumerate(readings) if reading >= stop] + # A second set-group checkpoint over the line: the sampler may latch only after the first one has run. + assert len(over) >= 2, (stop / GIB, readings[-1] / GIB) + late = readings[over[1]] + assert ceiling - late >= MIN_HEADROOM, (stop / GIB, late / GIB, ceiling / GIB) diff --git a/tests/test_cli.py b/tests/test_cli.py index 004d5ed..cb695cd 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -265,6 +265,27 @@ def test_generate_builds_the_model_from_the_flags_writes_the_image_and_the_repor ) +def test_the_command_builds_its_model_with_the_watchdog_off(tmp_path): + # Bug caught: the command building its model with the model's own default watchdog on, so a call is watched twice + # (the command's exit-mode watchdog and the model's raise-mode one) and an abort exits 2 instead of 70; or the + # keyword leaking into the report's model_kwargs, which record the user's flags only. + built = [] + + def factory(**kw): + built.append(kw) + return _Model([], **kw) + + report_path = tmp_path / "r.json" + argv = ["--prompt", "p", "--output", str(tmp_path / "o.png"), "--report", str(report_path)] + code, _ = _run(argv, [], tmp_path, factory=factory) + assert code == 0 + assert len(built) == 1 + assert "watchdog" in built[0] + assert built[0]["watchdog"] is None + report = json.loads(report_path.read_text()) + assert "watchdog" not in report["model_kwargs"] + + def test_the_watchdog_context_carries_the_models_default_steps(tmp_path): # Bug caught: the context recording the --steps flag (None) instead of the steps that ran. _, watchdogs = _run(["--prompt", "p", "--output", str(tmp_path / "o.png")], [], tmp_path) diff --git a/tests/test_drain.py b/tests/test_drain.py new file mode 100644 index 0000000..d6aeb98 --- /dev/null +++ b/tests/test_drain.py @@ -0,0 +1,129 @@ +"""The drain run after an armed call frees memory: wait, clear, kick, poll the footprint, wait, clear. + +MLX-free in effect: every step the drain takes is recorded through monkeypatched ``mx`` calls and the module's kick and +sleep, and the footprint comes from a scripted reader, so no test pays wall time and every count is a literal. +""" + +import mlx.core as mx +import pytest + +from mlx_dfloat.mflux import _drain + +MiB = 1 << 20 +GiB = 1 << 30 + + +@pytest.fixture +def events(monkeypatch): + """Record every synchronize, cache clear, kick and sleep the drain makes, in order.""" + log = [] + monkeypatch.setattr(mx, "synchronize", lambda *a, **k: log.append("synchronize")) + monkeypatch.setattr(mx, "clear_cache", lambda: log.append("clear_cache")) + monkeypatch.setattr(_drain, "_kick", lambda: log.append("kick")) + monkeypatch.setattr(_drain, "_sleep", lambda seconds: log.append(("sleep", seconds))) + return log + + +def _reader(values, log): + """A footprint reader that returns ``values`` in turn (the last one forever) and logs each read.""" + remaining = list(values) + + def read(): + value = remaining.pop(0) if len(remaining) > 1 else remaining[0] + log.append(("read", value)) + return value + + return read + + +def _reads(log): + return [e[1] for e in log if isinstance(e, tuple) and e[0] == "read"] + + +def _sleeps(log): + return [e for e in log if isinstance(e, tuple) and e[0] == "sleep"] + + +def test_the_drain_kicks_before_it_polls_and_clears_again_after(events): + # Bug caught: the poll started before the kick (the freed pages leave the footprint only after the next GPU + # submission, so the poll sees no fall and ends at once), or no last synchronize and clear (the kick's own + # buffers stay in the pool). + _drain.drain(_reader([500 * MiB, 400 * MiB, 400 * MiB], events), budget_s=0.25) + assert events == [ + "synchronize", + "clear_cache", + "kick", + ("read", 500 * MiB), + ("sleep", 0.02), + ("read", 400 * MiB), + ("sleep", 0.02), + ("read", 400 * MiB), + "synchronize", + "clear_cache", + ] + + +def test_the_poll_goes_on_while_the_footprint_falls_and_stops_when_it_does_not(events): + # Bug caught: a poll that stops after the first fall (the drop is still under way), or one that ignores a reading + # equal to the last and runs to the budget. + _drain.drain( + _reader([900 * MiB, 700 * MiB, 600 * MiB, 600 * MiB, 100 * MiB], events), budget_s=0.25 + ) + assert _reads(events) == [900 * MiB, 700 * MiB, 600 * MiB, 600 * MiB] + + +def test_a_fall_that_starts_late_is_still_waited_for(events): + # Bug caught: a poll that ends at the first flat reading before any fall. On an idle GPU the freed pages leave the + # footprint 80-700 ms after the kick, so that poll ends after one 20 ms sleep and drains nothing. + values = [900 * MiB, 900 * MiB, 900 * MiB, 700 * MiB, 600 * MiB, 600 * MiB, 100 * MiB] + _drain.drain(_reader(values, events), budget_s=0.25) + assert _reads(events) == values[:-1] + + +def test_a_footprint_that_never_falls_is_polled_for_the_whole_budget(events): + # Bug caught: a flat footprint ending the poll before the budget, so a fall that comes after 20 ms is never seen. + _drain.drain(_reader([500 * MiB], events), budget_s=0.25) + assert _sleeps(events) == [("sleep", 0.02)] * 12 + assert events[-2:] == ["synchronize", "clear_cache"] + + +def test_the_poll_stops_at_the_budget_while_the_footprint_still_falls(events): + # Bug caught: a poll with no end while memory keeps falling, or one step past the budget. 0.25 s of 0.02 s steps + # is 12 sleeps (a 13th would end at 0.26 s). + _drain.drain(_reader([n * MiB for n in range(1000, 0, -1)], events), budget_s=0.25) + assert _sleeps(events) == [("sleep", 0.02)] * 12 + assert events[-2:] == ["synchronize", "clear_cache"] + + +def test_a_dip_of_a_few_pages_does_not_end_the_poll(events): + # Bug caught: the poll counting any lower reading as the fall, so footprint noise (a 352 KiB dip was seen on an + # idle Mac) followed by a flat reading ends the poll at 40 ms, before the real release arrives. + _drain.drain(_reader([9 * GiB, 9 * GiB - 360_448], events), budget_s=0.25) + assert _sleeps(events) == [("sleep", 0.02)] * 12 + assert events[-2:] == ["synchronize", "clear_cache"] + + +def test_a_two_mib_fall_then_a_flat_reading_ends_the_poll(events): + # Bug caught: a fall threshold above 2 MiB, or a latch that also counts the flat reading after the fall, so a real + # release runs the poll to the budget. + _drain.drain(_reader([9 * GiB, 9 * GiB - 2_097_152], events), budget_s=0.25) + assert _reads(events) == [9 * GiB, 9 * GiB - 2_097_152, 9 * GiB - 2_097_152] + assert _sleeps(events) == [("sleep", 0.02)] * 2 + + +def test_a_one_mib_fall_in_smaller_steps_counts_as_the_fall(events): + # Bug caught: the fall measured from the reading before instead of the first one, so a release that leaves the + # footprint in steps under 1 MiB is never counted and the poll runs to the budget; or a fall of exactly 1 MiB not + # counted. + values = [9 * GiB, 9 * GiB - 524_288, 9 * GiB - 1_048_576] + _drain.drain(_reader(values, events), budget_s=0.25) + assert _reads(events) == [*values, 9 * GiB - 1_048_576] + assert _sleeps(events) == [("sleep", 0.02)] * 3 + + +def test_a_sleep_passed_in_replaces_the_module_one(events): + # Bug caught: the injected sleep ignored, so a caller that needs no wall time still sleeps. + slept = [] + _drain.drain(_reader([5 * MiB, 4 * MiB, 4 * MiB], events), budget_s=0.25, sleep=slept.append) + assert slept == [0.02, 0.02] + assert not any(isinstance(e, tuple) and e[0] == "sleep" for e in events) diff --git a/tests/test_guard.py b/tests/test_guard.py new file mode 100644 index 0000000..8da3842 --- /dev/null +++ b/tests/test_guard.py @@ -0,0 +1,250 @@ +"""The guard: one watchdog per call scope, checkpoints that turn a trip into a typed error. + +Every watchdog here is a real raise-mode ``Watchdog`` that samples a ``FakeCounters`` and ends the +"process" through a recorder, so no test reads the real allocator or can end pytest. No test here +imports mflux. +""" + +import ast +import contextlib +from pathlib import Path + +import pytest +from tests._fake_counters import FakeCounters + +from mlx_dfloat import _guard +from mlx_dfloat._watchdog import Watchdog +from mlx_dfloat.errors import DFloatWatchdogError + +GUARD_SOURCE = Path(_guard.__file__) + + +class _ExitRecorder: + """Stands in for the process exit: records each code.""" + + def __init__(self): + self.codes: list[int] = [] + + def __call__(self, code): + self.codes.append(code) + + +@pytest.fixture +def armed(tmp_path): + """Start raise-mode watchdogs (ceiling 10_000, stop margin 1_000: a stop line of 9_000). + + Each is stopped at teardown, so none can escalate into a later test. + """ + started = [] + + def _arm(*, ceiling=10_000, live_context=None, out_dir=None): + fake, exits = FakeCounters(), _ExitRecorder() + watchdog = Watchdog( + tmp_path if out_dir is None else out_dir, + ceiling=ceiling, + budget=None, + interval=0.01, + counters=fake, + exit_process=exits, + mode="raise", + stop_margin=1_000, + live_context=live_context, + ) + started.append(watchdog) + return watchdog.start(), fake, exits + + yield _arm + for watchdog in started: + watchdog.stop() + + +def _trip(watchdog, fake, watched=9_500): + fake.raise_to(watched) + assert watchdog.tripped.wait(timeout=5) + + +def test_checkpoint_without_a_scope_is_a_no_op(armed): + # Bug caught: checkpoint reaching a watchdog that no scope armed (a global set at start(), or + # a scope left set by an earlier call), so an unwatched call raises. + watchdog, fake, exits = armed() + _trip(watchdog, fake) + assert _guard.active() is None + _guard.checkpoint("block_end") + assert watchdog.trip["checkpoint_latency_s"] is None + assert exits.codes == [] + + +def test_checkpoint_raises_once_tripped_and_consumes(armed): + # Bug caught: no consume() before the raise, so the grace clock keeps running through the + # cleanup and can end the process; or the error carrying the wrong reason or site. + watchdog, fake, exits = armed() + with _guard.scope(watchdog): + _guard.checkpoint("block_start") # not tripped yet: no raise + _trip(watchdog, fake) + with pytest.raises(DFloatWatchdogError) as caught: + _guard.checkpoint("block_end") + assert (caught.value.reason, caught.value.site) == ("memory", "block_end") + assert watchdog.trip["checkpoint_latency_s"] >= 0 + assert caught.value.record["checkpoint_latency_s"] >= 0 + assert exits.codes == [] + + +def test_scope_resets_on_exit_even_after_a_raise(armed): + # Bug caught: the ContextVar not reset in a finally, so a raised call leaks its watchdog into + # every later call (and test) in this thread. + watchdog, _, _ = armed() + with contextlib.suppress(RuntimeError), _guard.scope(watchdog): + assert _guard.active() is watchdog + raise RuntimeError("boom") + assert _guard.active() is None + + +def test_scope_nested_restores_the_outer_watchdog(armed): + # Bug caught: the reset done with set(None) instead of the token, so an inner scope's exit + # leaves the outer call unwatched. + outer, _, _ = armed() + inner, _, _ = armed() + with _guard.scope(outer): + with _guard.scope(inner): + assert _guard.active() is inner + assert _guard.active() is outer + assert _guard.active() is None + + +def test_tightened_lowers_and_restores(armed): + # Bug caught: the min rule inverted (a higher inner ceiling raising the outer one), `>=` written + # as `>` (an equal ceiling still swapped in, caught by the spy below), or the old ceiling not + # restored after the inner call (also after a raise). + watchdog, _, _ = armed(ceiling=10_000) + calls = [] + real_set_ceiling = watchdog.set_ceiling + + def spy(ceiling): + calls.append(ceiling) + return real_set_ceiling(ceiling) + + watchdog.set_ceiling = spy + with _guard.scope(watchdog), _guard.tightened(10_000): + assert watchdog.ceiling == 10_000 + assert calls == [] + with _guard.scope(watchdog): + with _guard.tightened(5_000): + assert watchdog.ceiling == 5_000 + assert watchdog.ceiling == 10_000 + with contextlib.suppress(RuntimeError), _guard.tightened(9_999): + assert watchdog.ceiling == 9_999 + raise RuntimeError("inner call failed") + assert watchdog.ceiling == 10_000 + for no_change in (20_000, 10_000, None): + with _guard.tightened(no_change): + assert watchdog.ceiling == 10_000 + with _guard.tightened(5_000): # no active watchdog: nothing to lower + assert _guard.active() is None + + +def test_error_message_names_phase_artifact_and_site(armed, tmp_path): + # Bug caught: a message that drops the phase, the record's path or the site, so the user + # cannot tell where the call stopped or find the record. + watchdog, fake, _ = armed(live_context={"phase": lambda: "denoise"}) + _trip(watchdog, fake) + err = _guard.error_for(watchdog, "set_group") + message = str(err) + assert "(memory, phase denoise)" in message + assert "set_group" in message + assert str(tmp_path / "abort.json") in message + assert (err.reason, err.phase, err.site, err.artifact) == ( + "memory", + "denoise", + "set_group", + tmp_path / "abort.json", + ) + + +def test_error_message_gives_the_watched_number_and_the_stop_line_in_gib(tmp_path): + # Bug caught: bytes printed raw, or the watched number and the stop line swapped. + fake = FakeCounters() + gib = 1024**3 + watchdog = Watchdog( + tmp_path, + ceiling=28 * gib, + budget=None, + interval=0.01, + counters=fake, + exit_process=_ExitRecorder(), + mode="raise", + stop_margin=gib, + ) + watchdog.start() + try: + _trip(watchdog, fake, watched=27 * gib + gib // 2) + message = str(_guard.error_for(watchdog, "block_end")) + finally: + watchdog.stop() + assert "27.50 GiB" in message + assert "27.00 GiB" in message + assert message.index("27.50 GiB") < message.index("27.00 GiB") + + +def test_guard_imports_neither_the_watchdog_nor_mlx(): + # Bug caught: `from mlx_dfloat._watchdog import Watchdog` in _guard (an import cycle once the + # watchdog or the seam imports the guard). + tree = ast.parse(GUARD_SOURCE.read_text()) + imported = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imported |= {alias.name for alias in node.names} + elif isinstance(node, ast.ImportFrom): + imported.add(node.module) + assert imported <= {"contextvars", "contextlib", "typing", "mlx_dfloat.errors"} + + +def test_a_string_folder_still_raises_the_typed_error(armed, tmp_path): + # Bug caught: the record path joined outside the write's try, so a str folder raises TypeError in the sampler at + # the first trip: no trip is set, the sampler is dead, and the call runs on with no error. + watchdog, fake, exits = armed(out_dir=str(tmp_path)) + with _guard.scope(watchdog): + _trip(watchdog, fake) + with pytest.raises(DFloatWatchdogError) as caught: + _guard.checkpoint("block_end") + assert caught.value.reason == "memory" + assert caught.value.artifact is None + assert "artifact_error" in caught.value.record + assert exits.codes == [] + + +class _WallTripped: + """A tripped watchdog as the guard reads it: a wall trip 12.34 s into a 10 s budget.""" + + def __init__(self): + self.tripped = _Set() + self.trip = { + "reason": "wall", + "elapsed": 12.34, + "budget": 10.0, + "verdict_memory": 5 * 1024**3, + "stop_line": 27 * 1024**3, + "context": {"phase": "denoise"}, + } + self.artifact = None + self.ceiling = 28 * 1024**3 + + def consume(self): + pass + + def set_ceiling(self, ceiling): + previous, self.ceiling = self.ceiling, ceiling + return previous + + +class _Set: + def is_set(self): + return True + + +def test_a_wall_trip_message_gives_the_elapsed_time_against_the_budget(): + # Bug caught: a wall trip worded as a memory comparison ("watched 5.00 GiB against the stop line 27.00 GiB"), + # so the user reads a memory stop where the clock stopped the call. + message = str(_guard.error_for(_WallTripped(), "block_end")) + assert "(wall, phase denoise)" in message + assert "12.3 s against the wall budget of 10.0 s" in message + assert "GiB" not in message diff --git a/tests/test_integrate_coverage.py b/tests/test_integrate_coverage.py index f28284f..4d9d664 100644 --- a/tests/test_integrate_coverage.py +++ b/tests/test_integrate_coverage.py @@ -1,12 +1,14 @@ """Coverage bookkeeping: the resident set, the extras plan, coverage checks, full-block decode.""" import dataclasses +from types import SimpleNamespace import mlx.core as mx import mlx.nn as nn import numpy as np import pytest from tests._df11_fixtures import random_bf16, write_checkpoint +from tests._fake_counters import FakeCounters from tests._flux_fakes import ( FF, FLUX_TABLE, @@ -19,10 +21,12 @@ write_flux_checkpoint, ) +from mlx_dfloat import _guard +from mlx_dfloat._watchdog import Watchdog from mlx_dfloat.decode import STATUS_INVALID_CODE, decode_group -from mlx_dfloat.errors import DFloatFormatError, DFloatIntegrationError +from mlx_dfloat.errors import DFloatFormatError, DFloatIntegrationError, DFloatWatchdogError from mlx_dfloat.format import MxGroup, open_checkpoint -from mlx_dfloat.integrate import seam +from mlx_dfloat.integrate import coverage, seam from mlx_dfloat.integrate.coverage import ( _block_of, check_extras_cover, @@ -286,3 +290,69 @@ def test_load_extras_without_the_transform_refuses_the_stored_shape(tmp_path): _src, module, plan, name_map = _load_extras_fixture(tmp_path, None) with pytest.raises(DFloatFormatError, match="shape"): load_extras(module, plan, name_map) + + +@pytest.fixture +def raise_mode(tmp_path): + """A started raise-mode watchdog (stop line 9_000) over FakeCounters, and a call that trips it. + + Stopped at teardown; no test may see it end the "process". + """ + fake, exits = FakeCounters(), [] + watchdog = Watchdog( + tmp_path, + ceiling=10_000, + budget=None, + interval=0.01, + counters=fake, + exit_process=exits.append, + mode="raise", + stop_margin=1_000, + ).start() + + def trip(): + fake.raise_to(9_500) + assert watchdog.tripped.wait(timeout=5) + + yield watchdog, trip + watchdog.stop() + assert exits == [] + + +def _counting_group_reader(monkeypatch, *, trip_on=None, trip=None): + """Replace the group read with a fake that logs each group and can trip on the n-th read.""" + read = [] + + def load_group_mx(group): + read.append(group) + if trip_on is not None and len(read) == trip_on: + trip() + return f"loaded {group}" + + monkeypatch.setattr(coverage, "load_group_mx", load_group_mx) + return read + + +_FOUR_GROUPS = SimpleNamespace(groups={f"transformer_blocks.{i}": f"g{i}" for i in range(4)}) + + +def test_a_trip_mid_set_load_raises_before_the_next_group(raise_mode, monkeypatch): + # Bug caught: no checkpoint in the loop, so a set load that crosses the stop line reads every + # remaining group (about 0.5 s and one group of memory each) before anything stops it. + watchdog, trip = raise_mode + read = _counting_group_reader(monkeypatch, trip_on=2, trip=trip) + with _guard.scope(watchdog), pytest.raises(DFloatWatchdogError) as caught: + load_resident_set(_FOUR_GROUPS) + assert caught.value.site == "set_group" + assert read == ["g0", "g1"] + + +def test_a_tripped_call_reads_no_group(raise_mode, monkeypatch): + # Bug caught: the checkpoint after each group's read instead of before it, so a load that + # starts tripped still reads one group. + watchdog, trip = raise_mode + read = _counting_group_reader(monkeypatch) + trip() + with _guard.scope(watchdog), pytest.raises(DFloatWatchdogError): + load_resident_set(_FOUR_GROUPS) + assert read == [] diff --git a/tests/test_integrate_seam.py b/tests/test_integrate_seam.py index 61d9269..06dd52f 100644 --- a/tests/test_integrate_seam.py +++ b/tests/test_integrate_seam.py @@ -12,6 +12,7 @@ import mlx.core as mx import numpy as np import pytest +from tests._fake_counters import FakeCounters from tests._flux_fakes import ( FLUX_TABLE, D, @@ -26,8 +27,10 @@ resident_dicts, ) +from mlx_dfloat import _guard +from mlx_dfloat._watchdog import Watchdog from mlx_dfloat.decode import STATUS_INVALID_CODE, decode_group -from mlx_dfloat.errors import DFloatFormatError, DFloatIntegrationError +from mlx_dfloat.errors import DFloatFormatError, DFloatIntegrationError, DFloatWatchdogError from mlx_dfloat.integrate import seam from mlx_dfloat.integrate.placeholders import install_placeholders from mlx_dfloat.integrate.providers import ( @@ -504,3 +507,78 @@ def before_block(self, block_name, args, kwargs): mx.eval(tf(*inputs())) mx.eval(tf(*inputs())) assert [(args, kwargs) for _name, args, kwargs in seen] == [((), {})] * 6 + + +@pytest.fixture +def raise_mode(tmp_path): + """A started raise-mode watchdog (stop line 9_000) over FakeCounters, and a call that trips it. + + Stopped at teardown; no test may see it end the "process". + """ + fake, exits = FakeCounters(), [] + watchdog = Watchdog( + tmp_path, + ceiling=10_000, + budget=None, + interval=0.01, + counters=fake, + exit_process=exits.append, + mode="raise", + stop_margin=1_000, + ).start() + + def trip(): + fake.raise_to(9_500) + assert watchdog.tripped.wait(timeout=5) + + yield watchdog, trip + watchdog.stop() + assert exits == [] + + +def test_a_trip_raises_at_the_next_block_and_restores_placeholders(raise_mode, monkeypatch): + # Bug caught: no checkpoint after the block's evaluation, or one placed before it (the + # evaluation is the long call that crosses the line, so the step runs on past the trip), or + # one placed in the finally, so the raising block keeps its decoded weights. + watchdog, trip = raise_mode + real_eval, evals = seam._eval, [] + + def eval_crossing_on_block_1(out): + evals.append(out) + real_eval(out) + if len(evals) == 2: + trip() + + monkeypatch.setattr(seam, "_eval", eval_crossing_on_block_1) + rec = Recorder() + tf = FakeSeamTransformer(rec, n_double=2, n_single=0) + shapes = install_placeholders(block_lists(tf), FLUX_TABLE) + tf.attach(ResidentProvider(resident_dicts(shapes)), shapes, eval_policy="per-block") + with _guard.scope(watchdog), pytest.raises(DFloatWatchdogError) as caught: + tf(*inputs()) + assert caught.value.site == "block_end" + assert len(rec.seen) == 2 + assert rec.seen[1].size > 0 # the block ran on its decoded weight + assert all(w.size == 0 for w in all_block_weights(tf)) + + +def test_a_tripped_step_raises_before_the_first_block_decodes(raise_mode): + # Bug caught: no checkpoint at the block's start, so a step that begins tripped still runs + # the provider's hook and decodes a block before stopping. + watchdog, trip = raise_mode + hooked = [] + + class Hooked(ResidentProvider): + def before_block(self, block_name, args, kwargs): + hooked.append(block_name) + + rec = Recorder() + tf = FakeSeamTransformer(rec, n_double=2, n_single=0) + shapes = install_placeholders(block_lists(tf), FLUX_TABLE) + tf.attach(Hooked(resident_dicts(shapes)), shapes, eval_policy="per-block") + trip() + with _guard.scope(watchdog), pytest.raises(DFloatWatchdogError) as caught: + tf(*inputs()) + assert caught.value.site == "block_start" + assert (hooked, rec.seen) == ([], []) + assert all(w.size == 0 for w in all_block_weights(tf)) diff --git a/tests/test_markers.py b/tests/test_markers.py index 8d1d471..24ab01d 100644 --- a/tests/test_markers.py +++ b/tests/test_markers.py @@ -198,3 +198,87 @@ def test_mflux_marker_tests_skip_with_the_install_hint_where_mflux_is_missing(): assert "skipped" in summary assert "passed" not in summary assert "failed" not in summary + + +def test_api_watchdog_patches_name_the_three_seams(): + # Bug caught: a seam left out of the list (the real allocator or this runner's RAM reaching a test, or an + # escalation ending pytest with code 70 and no summary), or a host ceiling other than a 32 GiB Mac's minus 4 GiB. + patches = dict(conftest._api_watchdog_patches()) + assert set(patches) == {"_counters", "_default_ceiling", "_exit_process"} + assert patches["_default_ceiling"]() == 30_064_771_072 + assert tuple(patches["_counters"]()) == (0, 0, 0, 0) + patches["_exit_process"](70) + assert patches["_exit_process"].codes == [70] + + +def test_an_exit_code_the_test_did_not_take_fails_the_teardown(): + # Bug caught: the teardown ignoring a recorded escalation, so a call that would have ended the process reads green; + # or a test that took its expected code out still failing. + recorder = dict(conftest._api_watchdog_patches())["_exit_process"] + assert conftest._untaken_exits(recorder.codes) is None + recorder(71) + assert "71" in conftest._untaken_exits(recorder.codes) + assert recorder.take() == [71] + assert conftest._untaken_exits(recorder.codes) is None + + +def test_the_autouse_fixture_puts_the_fakes_in_front_of_the_pipeline(request): + # Bug caught: the fixture yielding objects other than the ones it patched in, so a test raising the fake raises + # nothing the watchdog reads. + from mlx_dfloat.mflux import _pipeline + + _api_watchdog_fakes = request.getfixturevalue("_api_watchdog_fakes") + assert _pipeline._counters is _api_watchdog_fakes.counters + assert _pipeline._exit_process is _api_watchdog_fakes.exits + assert _pipeline._default_ceiling() == 30_064_771_072 + + +_UNTAKEN_EXITS_MODULE = """ +from mlx_dfloat import _watchdog +from mlx_dfloat.mflux import _pipeline + + +def test_leaves_a_pipeline_exit_code(): + _pipeline._exit_process(70) + + +def test_leaves_a_watchdog_exit_code(): + _watchdog._exit(71) + + +def test_takes_its_exit_code(_api_watchdog_fakes): + _watchdog._exit(70) + assert _api_watchdog_fakes.exits.take() == [70] + + +def test_makes_no_exit(): + pass +""" + + +def test_the_fixture_fails_a_test_that_leaves_an_exit_code_untaken(pytester, monkeypatch): + # Bug caught: the autouse fixture's teardown check not wired to the recorder it patched in (a recorded escalation + # reads green), a test that took its code still failing, or `_watchdog._exit` left as the real `os._exit` (a + # raise-mode watchdog built without `exit_process` would end the run: the child exits 71 with no summary). + pytester.makeconftest((REPO / "tests" / "conftest.py").read_text()) + pytester.makepyfile(test_untaken=_UNTAKEN_EXITS_MODULE) + monkeypatch.setenv("PYTHONPATH", str(REPO)) + result = pytester.runpytest_subprocess( + "-ra", + f"--rootdir={pytester.path}", + f"--confcutdir={pytester.path}", + "-p", + "no:cacheprovider", + ) + assert result.ret == pytest.ExitCode.TESTS_FAILED, result.stdout.str()[-2000:] + result.assert_outcomes(passed=4, errors=2) + result.stdout.fnmatch_lines( + [ + "*ERROR at teardown of test_leaves_a_pipeline_exit_code*", + "E * process exit [[]70[]] and the test did not take the code", + "*ERROR at teardown of test_leaves_a_watchdog_exit_code*", + "E * process exit [[]71[]] and the test did not take the code", + "ERROR test_untaken.py::test_leaves_a_pipeline_exit_code*", + "ERROR test_untaken.py::test_leaves_a_watchdog_exit_code*", + ] + ) diff --git a/tests/test_mflux_api_watchdog.py b/tests/test_mflux_api_watchdog.py new file mode 100644 index 0000000..93d494e --- /dev/null +++ b/tests/test_mflux_api_watchdog.py @@ -0,0 +1,320 @@ +"""A model built with no ``watchdog`` argument stops a denoise overrun, and the next call generates. + +One real tiny generation per family through mflux's own loop. The autouse ``_api_watchdog_fakes`` fixture +(``tests/conftest.py``) puts the fake allocator in front of the watchdog and fixes the host ceiling at +30_064_771_072 bytes (a 32 GiB Mac minus 4 GiB), so the expected numbers below do not depend on the runner. A wrapper +around the provider's per-block ``weights_for`` raises the fake above the stop line on the first block fetched in +the denoise phase, waits for the watchdog to trip, and counts the blocks fetched after that. Every test is +`@pytest.mark.mflux`. +""" + +import pytest + +from mlx_dfloat import _guard +from mlx_dfloat.errors import DFloatWatchdogError + +pytestmark = pytest.mark.mflux + +# 27 GiB: the 30_064_771_072-byte ceiling minus the default 1 GiB stop margin. +STOP_LINE = 28_991_029_248 + + +# --- one tiny model per family, the arguments of one short generation, and the provider class it fetches blocks from + + +def _flux1(tmp_path, monkeypatch): + # The fake-width transformer cannot run mflux's loop, so this is the seamed mflux transformer at 1 + 1 blocks + # over a resident set of zeros (tests/test_flux1_model.py, the upstream-loop test). Two steps: 4 block runs. + import mlx.core as mx + from mflux.models.common.config.model_config import ModelConfig + from tests.test_flux1_model import StubTokenizer, _fake_model, _ShapedEncoder, _StubVAE + + from mlx_dfloat.integrate.placeholders import install_placeholders + from mlx_dfloat.integrate.providers import ResidentProvider + from mlx_dfloat.mflux.flux1.init import BaseComponents + from mlx_dfloat.mflux.flux1.names import flux_name_map + from mlx_dfloat.mflux.flux1.transformer import seam_transformer_class + + tf = seam_transformer_class()( + ModelConfig.schnell(), num_transformer_blocks=1, num_single_transformer_blocks=1 + ) + shapes = install_placeholders( + [ + ("transformer_blocks", tf.transformer_blocks), + ("single_transformer_blocks", tf.single_transformer_blocks), + ], + flux_name_map(), + ) + components = BaseComponents( + vae=_StubVAE(), + t5=_ShapedEncoder((1, 256, 4096)), + clip=_ShapedEncoder((1, 768)), + tokenizers={"t5": StubTokenizer(256), "clip": StubTokenizer(77)}, + ) + model = _fake_model( + tmp_path, monkeypatch, model="schnell", transformer=tf, components=components + ) + model._shapes = shapes + + def load_resident_zeros(): + zeros = { + block: {attr: mx.zeros(shape, dtype=mx.bfloat16) for attr, shape in per.items()} + for block, per in shapes.items() + } + model.transformer.attach( + ResidentProvider(zeros), shapes, eval_policy=model._policy, verify_in_call=True + ) + + monkeypatch.setattr(model._lifecycle, "_load_set", load_resident_zeros) + run = { + "seed": 1, + "prompt": "p", + "num_inference_steps": 2, + "height": 64, + "width": 64, + "guidance": 0.0, + } + return model, "schnell", run, ResidentProvider + + +def _zimage(tmp_path, monkeypatch): + # 2 layers (4 blocks), 2 steps, one transformer call per step: 8 block runs. The VAE decode is a zero image. + import mlx.core as mx + from mflux.models.z_image.variants.z_image import ZImage + from tests._zimage_tiny import fake_model + + from mlx_dfloat.integrate.providers import DF11Provider + + monkeypatch.setattr(ZImage, "_decode_latents", lambda self, **kw: mx.zeros((1, 3, 32, 32))) + model = fake_model(tmp_path, monkeypatch, model="z-image-turbo") + run = { + "seed": 3, + "prompt": "p", + "num_inference_steps": 2, + "height": 32, + "width": 32, + "guidance": 4.0, + } + return model, "z-image-turbo", run, DF11Provider + + +def _flux2(tmp_path, monkeypatch): + # 1 double + 2 single blocks, 2 steps, no CFG at guidance 1.0: 6 block runs. + from tests._flux2_tiny import fake_model + + from mlx_dfloat.integrate.providers import DF11Provider + + model = fake_model(tmp_path, monkeypatch, model="flux2-klein-base-4b") + run = { + "seed": 1, + "prompt": "a", + "num_inference_steps": 2, + "height": 64, + "width": 64, + "guidance": 1.0, + } + return model, "flux2-klein-base-4b", run, DF11Provider + + +def _qwen21(tmp_path, monkeypatch): + # 2 blocks, 2 steps, no CFG at guidance 1.0. + from tests._qwen21_tiny import fake_model + + from mlx_dfloat.integrate.providers import DF11Provider + + model = fake_model(tmp_path, monkeypatch, model="qwen-image-2.1") + run = { + "seed": 1, + "prompt": "a", + "num_inference_steps": 2, + "height": 64, + "width": 64, + "guidance": 1.0, + } + run["negative_prompt"] = "" + return model, "qwen-image-2.1", run, DF11Provider + + +def _ernie(tmp_path, monkeypatch): + # 2 blocks, 2 steps: 4 block runs. + from tests._ernie_tiny import fake_model + + from mlx_dfloat.integrate.providers import DF11Provider + + model = fake_model(tmp_path, monkeypatch, model="ernie-image-turbo") + run = { + "seed": 1, + "prompt": "a", + "num_inference_steps": 2, + "height": 64, + "width": 64, + "guidance": 1.0, + } + return model, "ernie-image-turbo", run, DF11Provider + + +def _krea2(tmp_path, monkeypatch): + # 2 blocks, 2 steps, no CFG at guidance 1.0: 4 block runs. Counting blocks at weights_for, not decodes at the + # decode hook, keeps the per-call non-block decodes of this build out of the count. + from tests._krea2_tiny import fake_model + + from mlx_dfloat.integrate.providers import DF11Provider + + model = fake_model(tmp_path, monkeypatch, model="krea-2") + run = { + "seed": 1, + "prompt": "a", + "num_inference_steps": 2, + "height": 64, + "width": 64, + "guidance": 1.0, + } + return model, "krea-2", run, DF11Provider + + +FAMILIES = [ + pytest.param(_flux1, id="flux1"), + pytest.param(_zimage, id="zimage"), + pytest.param(_flux2, id="flux2"), + pytest.param(_qwen21, id="qwen21"), + pytest.param(_ernie, id="ernie"), + pytest.param(_krea2, id="krea2"), +] + + +class DenoiseOverrun: + """Raises the fake allocator over the stop line on the first block fetched in the denoise phase. + + One-shot, and a pass-through when no watchdog is active, so a call that is not armed simply returns (the red + run's "DID NOT RAISE") and a retry is never tripped again. It records and never asserts: the test asserts after + the call. ``blocks_after_trip`` counts the block whose fetch tripped (it still runs) and every block fetched later. + """ + + def __init__(self, model, counters): + self.model = model + self.counters = counters + self.armed = True + self.tripped_in_time = None + self.blocks_after_trip = 0 + + def install(self, monkeypatch, provider_cls): + real = provider_cls.weights_for + + def weights_for(provider, block_name, shapes): + if self.tripped_in_time is not None: + self.blocks_after_trip += 1 + elif self.armed and self.model.open_phase == "denoise": + watchdog = _guard.active() + if watchdog is not None: + self.armed = False + self.counters.raise_to(STOP_LINE + 1) + self.tripped_in_time = watchdog.tripped.wait(5.0) + self.blocks_after_trip = 1 + return real(provider, block_name, shapes) + + monkeypatch.setattr(provider_cls, "weights_for", weights_for) + + +def _overrun(build, tmp_path, monkeypatch, request): + from mlx_dfloat.mflux import _pipeline + + fakes = request.getfixturevalue("_api_watchdog_fakes") + aborts = tmp_path / "aborts" + monkeypatch.setattr(_pipeline, "_artifact_root", lambda: aborts) + model, model_name, run, provider_cls = build(tmp_path, monkeypatch) + overrun = DenoiseOverrun(model, fakes.counters) + overrun.install(monkeypatch, provider_cls) + return fakes, aborts, model, model_name, run, overrun + + +@pytest.mark.parametrize("build", FAMILIES) +def test_default_watchdog_stops_a_denoise_overrun(build, tmp_path, monkeypatch, request): + # Bug caught: a model built with no watchdog argument running unwatched (the default flipped to None, or the + # class's generate_image not armed), or the block seam's checkpoints missing, so a tripped call runs every + # remaining block and stops only at call_end (site "call_end", blocks after the trip > 1). + _fakes, aborts, model, model_name, run, overrun = _overrun( + build, tmp_path, monkeypatch, request + ) + + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(**run) + + err = excinfo.value + assert overrun.tripped_in_time is True + assert err.phase == "denoise" + assert err.reason == "memory" + assert err.site in {"block_start", "block_end"} + assert overrun.blocks_after_trip <= 1 + assert err.record["verdict_counter"] == "footprint" + # The injected 32 GiB host, not this runner's RAM. + assert err.record["ceiling"] == 30_064_771_072 + assert err.record["context"]["model"] == model_name + assert err.artifact is not None + assert err.artifact.is_file() + assert err.artifact.parent == aborts + + +@pytest.mark.parametrize("build", FAMILIES) +def test_retry_after_abort_generates(build, tmp_path, monkeypatch, request): + # Bug caught: an abort that leaves the model unusable (the set marked resident while its provider is gone, block + # placeholders not restored, the guard's scope or a stopped watchdog leaking into the next call), so the second + # call fails or reuses a half-dropped set instead of loading it again (set_loads stays 1). + fakes, _aborts, model, _model_name, run, _overrun_hook = _overrun( + build, tmp_path, monkeypatch, request + ) + with pytest.raises(DFloatWatchdogError): + model.generate_image(**run) + + fakes.counters.raise_to(0) + image = model.generate_image(**run) + + assert image is not None + assert model._lifecycle.counters.set_loads == 2 + + +# --- the watchdog argument at construction + +MODEL_CLASSES = [ + pytest.param("mlx_dfloat.mflux.flux1.model", "DFloatFlux1", id="flux1"), + pytest.param("mlx_dfloat.mflux.zimage.model", "DFloatZImage", id="zimage"), + pytest.param("mlx_dfloat.mflux.flux2.model", "DFloatFlux2Klein", id="flux2"), + pytest.param("mlx_dfloat.mflux.qwen21.model", "DFloatQwenImage21", id="qwen21"), + pytest.param("mlx_dfloat.mflux.ernie.model", "DFloatErnieImage", id="ernie"), + pytest.param("mlx_dfloat.mflux.krea2.model", "DFloatKrea2", id="krea2"), +] + + +class _BuildStartedError(Exception): + """Raised by the patched GPU decoder self-check: the constructor got past its argument checks.""" + + +def _construct(module, name, monkeypatch, **kwargs): + # The decoder self-check is the constructor's first step after its argument checks; stopping there keeps this + # test from resolving a checkpoint or loading a base, whatever the local Hub cache holds. + import importlib + + from mlx_dfloat import _metal_decode + + def ensure_canary(**_kwargs): + raise _BuildStartedError + + monkeypatch.setattr(_metal_decode, "ensure_canary", ensure_canary) + getattr(importlib.import_module(module), name)(**kwargs) + + +@pytest.mark.parametrize(("module", "name"), MODEL_CLASSES) +def test_watchdog_false_is_refused_at_construction(module, name, monkeypatch): + # Bug caught: a constructor that does not check its watchdog argument, so watchdog=False builds the model and + # fails later, at the first call, with an AttributeError on a bool. + from mlx_dfloat.errors import DFloatUnsupportedError + + with pytest.raises(DFloatUnsupportedError, match="watchdog=None"): + _construct(module, name, monkeypatch, watchdog=False) + + +@pytest.mark.parametrize(("module", "name"), MODEL_CLASSES) +def test_watchdog_none_is_accepted_at_construction(module, name, monkeypatch): + # Bug caught: a check that tests truthiness (`if not watchdog`) and so refuses None, the documented way to run + # the calls unwatched. + with pytest.raises(_BuildStartedError): + _construct(module, name, monkeypatch, watchdog=None) diff --git a/tests/test_mflux_api_watchdog_phases.py b/tests/test_mflux_api_watchdog_phases.py new file mode 100644 index 0000000..fb44928 --- /dev/null +++ b/tests/test_mflux_api_watchdog_phases.py @@ -0,0 +1,543 @@ +"""Where an armed model call stops, per phase, and what it leaves behind: FLUX.2 Klein and FLUX.1 tiny models. + +The autouse ``_api_watchdog_fakes`` fixture (``tests/conftest.py``) puts the fake allocator in front of the watchdog, +fixes the host ceiling at 30_064_771_072 bytes (a 32 GiB Mac minus 4 GiB) and records any process exit. Each test +wraps one phase's component: the wrapper raises the fake above the stop line and waits on the watchdog's ``tripped`` +event (5 s timeout), which is a trip during an evaluation with no checkpoint. The tests then assert where the call +stopped (``site``) and how much work ran after the trip, not only ``phase``: ``phase`` is read at trip time, so a +later checkpoint would still report it. + +Where FLUX.1's VAE evaluates (mflux 0.24.0): ``Flux1.generate_image`` calls ``VAEUtil.decode`` (lazy) and then +``ImageUtil.to_image``, which evaluates the decode once at ``np.array`` in ``ImageUtil._to_numpy`` +(``mflux/utils/image_util.py:134``), the same shape as Klein. No checkpoint runs inside it; a VAE trip on FLUX.1 is +taken at ``call_end`` (``test_flux1_abort_in_vae_raises_at_call_end``). Every test is `@pytest.mark.mflux`. +""" + +import threading +import weakref + +import pytest + +from mlx_dfloat import _guard +from mlx_dfloat.errors import DFloatWatchdogError + +pytestmark = pytest.mark.mflux + +# 27 GiB: the 30_064_771_072-byte ceiling minus the default 1 GiB stop margin. +STOP_LINE = 28_991_029_248 +THREAD = "mlx-dfloat-watchdog" + +# One short Klein generation: 1 double + 2 single blocks, 2 steps, no CFG at guidance 1.0 (6 block runs). +KLEIN_RUN = { + "seed": 1, + "prompt": "a", + "num_inference_steps": 2, + "height": 64, + "width": 64, + "guidance": 1.0, +} + + +@pytest.fixture +def fakes(request): + """The autouse ``_api_watchdog_fakes`` value: the fake allocator and the exit recorder of this test.""" + return request.getfixturevalue("_api_watchdog_fakes") + + +@pytest.fixture(autouse=True) +def aborts(tmp_path, monkeypatch): + """Every abort record of this file lands under the test's own folder, never in the real temp dir. + + On the way out the model's reference cycle (model and lifecycle) is collected and MLX's cache emptied, so the + tiny model's arrays (about 1 GiB for the 1 + 1 block FLUX.1 set of zeros) are not still active in a later test + that reads ``mx.get_active_memory()`` as its baseline. + """ + import gc + + import mlx.core as mx + + from mlx_dfloat.mflux import _pipeline + + root = tmp_path / "aborts" + monkeypatch.setattr(_pipeline, "_artifact_root", lambda: root) + yield root + monkeypatch.undo() # the patched wrappers' closures reach the model; release them before the collect + gc.collect() + mx.clear_cache() + + +class Overrun: + """One-shot: raises the fake over the stop line the first time ``fire`` runs in ``phase`` under an armed call. + + A pass-through otherwise, so an unarmed call simply returns and a retry is never tripped again. It records and + never asserts. ``calls`` counts every ``fire``; ``after_trip`` counts the firing call and every later one. + """ + + def __init__(self, model, counters, phase): + self.model, self.counters, self.phase = model, counters, phase + self.armed = True + self.tripped_in_time = None + self.calls = 0 + self.after_trip = 0 + + def fire(self): + self.calls += 1 + if self.tripped_in_time is not None: + self.after_trip += 1 + return + if not self.armed or self.model.open_phase != self.phase: + return + watchdog = _guard.active() + if watchdog is None: + return + self.armed = False + self.counters.raise_to(STOP_LINE + 1) + self.tripped_in_time = watchdog.tripped.wait(5.0) + self.after_trip = 1 + + +def _klein(tmp_path, monkeypatch, **overrides): + from tests._flux2_tiny import fake_model + + return fake_model(tmp_path, monkeypatch, model="flux2-klein-base-4b", **overrides) + + +def _wrap_text_encoder(monkeypatch, before_call): + from tests._flux2_tiny import StubTextEncoder + + real = StubTextEncoder.get_prompt_embeds + + def get_prompt_embeds(self, *args, **kwargs): + before_call() + return real(self, *args, **kwargs) + + monkeypatch.setattr(StubTextEncoder, "get_prompt_embeds", get_prompt_embeds) + + +def _wrap_group_reads(monkeypatch, before_read): + from mlx_dfloat.integrate import coverage + + real = coverage.load_group_mx + + def load_group_mx(group): + out = real(group) + before_read() + return out + + monkeypatch.setattr(coverage, "load_group_mx", load_group_mx) + + +def test_klein_abort_in_encode_stops_in_encode(tmp_path, monkeypatch, fakes): + # Bug caught: the prompt_encoded checkpoint missing from Lifecycle.ensure_embeddings (alone, or with + # encoder_loaded), so a trip during the prompt's encoder pass caches the pair, runs on into the set load and stops + # there (site "set_load_start"). + model = _klein(tmp_path, monkeypatch) + overrun = Overrun(model, fakes.counters, "encode") + _wrap_text_encoder(monkeypatch, overrun.fire) + + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(**KLEIN_RUN) + + err = excinfo.value + assert overrun.tripped_in_time is True + assert err.phase == "encode" + assert err.site == "prompt_encoded" + assert model._lifecycle.counters.set_loads == 0 + assert model._lifecycle.encoders_loaded is False + + +def test_klein_abort_in_set_load_stops_before_the_next_group(tmp_path, monkeypatch, fakes): + # Bug caught: the set_group checkpoint missing from load_resident_set, so a tripped load reads every remaining + # group (wrapper calls 8, not 1) and stops only at the first block (site "block_start"). And: the abort returning + # without emptying MLX's cache when the set is not yet resident, so the groups already read stay in the buffer + # pool (with the set load's raised cache limit) after the error leaves. + import mlx.core as mx + + model = _klein(tmp_path, monkeypatch) + overrun = Overrun(model, fakes.counters, "set_load") + _wrap_group_reads(monkeypatch, overrun.fire) + + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(**KLEIN_RUN) + + err = excinfo.value + assert overrun.tripped_in_time is True + assert err.phase == "set_load" + assert err.site == "set_group" + assert overrun.calls == 1 + assert model._lifecycle.set_resident is False + assert mx.get_cache_memory() == 0 + + +def test_klein_abort_in_denoise_stops_at_the_next_block(tmp_path, monkeypatch, fakes): + # Bug caught: the block_end checkpoint missing from seam.run_block, so a trip in a block's decode runs that block + # and stops at the next block's block_start (or, with block_start gone too, runs every remaining block and the VAE + # and stops at call_end); or an abort that leaves a decoded weight installed in a block or MLX's limits changed. + from functools import partial + + from mlx_dfloat.bench.capped import current_limits + from mlx_dfloat.decode import decode_group + from mlx_dfloat.integrate.placeholders import PLACEHOLDER, get_attr_path + + real_decode = partial(decode_group, backend="reference") + holder = {} + + def decode(group): + holder["overrun"].fire() + return real_decode(group) + + model = _klein(tmp_path, monkeypatch, decode=decode) + overrun = holder["overrun"] = Overrun(model, fakes.counters, "denoise") + limits_before = current_limits() + + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(**KLEIN_RUN) + + err = excinfo.value + assert overrun.tripped_in_time is True + assert err.phase == "denoise" + assert err.site == "block_end" + assert overrun.after_trip <= 1 + not_placeholder = [ + f"{block}.{attr}" + for block, per in model._shapes.items() + for attr in per + if get_attr_path(model.transformer, f"{block}.{attr}").weight is not PLACEHOLDER + ] + assert not_placeholder == [] + assert current_limits() == limits_before + + +def test_klein_abort_in_vae_raises_at_call_end(tmp_path, monkeypatch, fakes): + # Bug caught: the decorator's call_end checkpoint missing, so a trip during the VAE decode (which has no + # checkpoint) returns the image as if nothing happened, and the set stays resident past the abort. + from tests._flux2_tiny import StubVAE + + model = _klein(tmp_path, monkeypatch) + overrun = Overrun(model, fakes.counters, "vae") + real = StubVAE.decode_packed_latents + + def decode_packed_latents(self, packed, tiling_config=None): + overrun.fire() + return real(self, packed, tiling_config=tiling_config) + + monkeypatch.setattr(StubVAE, "decode_packed_latents", decode_packed_latents) + + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(**KLEIN_RUN) + + err = excinfo.value + assert overrun.tripped_in_time is True + assert err.phase == "vae" + assert err.site == "call_end" + assert model._lifecycle.set_resident is False + + +def test_klein_abort_in_an_encoder_reload_stops_at_encoder_loaded(tmp_path, monkeypatch, fakes): + # Bug caught: the encoder_loaded checkpoint alone missing from Lifecycle.ensure_embeddings, so a trip while a + # new prompt reloads the text encoders runs the encoder pass anyway and stops at prompt_encoded. + from mlx_dfloat.mflux.flux2 import init as finit + + model = _klein(tmp_path, monkeypatch) + # Encodes "a", then drops the encoders: the next prompt reloads them. + model.generate_image(**KLEIN_RUN) + overrun = Overrun(model, fakes.counters, "encode") + real_load = finit.load_text_encoder + + def load_text_encoder(root, model_config): + encoder = real_load(root, model_config) + overrun.fire() + return encoder + + monkeypatch.setattr(finit, "load_text_encoder", load_text_encoder) + passes = [] + _wrap_text_encoder(monkeypatch, lambda: passes.append(model.open_phase)) + + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(**{**KLEIN_RUN, "prompt": "b"}) + + err = excinfo.value + assert overrun.tripped_in_time is True + assert err.phase == "encode" + assert err.site == "encoder_loaded" + assert passes == [] + + +def test_klein_abort_before_the_set_load_stops_at_set_load_start(tmp_path, monkeypatch, fakes): + # Bug caught: the set_load_start checkpoint alone missing from Lifecycle.ensure_set, so a trip during the + # pre-load memory check starts the load, reads no group but stops at the first set_group instead. + model = _klein(tmp_path, monkeypatch) + overrun = Overrun(model, fakes.counters, "set_load") + real_bound = model._lifecycle.retained_bound + + def retained_bound(): + overrun.fire() # a no-op outside the set-load phase (the encoders' reclaim also calls it) + return real_bound() + + monkeypatch.setattr(model._lifecycle, "retained_bound", retained_bound) + reads = [] + _wrap_group_reads(monkeypatch, lambda: reads.append(1)) + + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(**KLEIN_RUN) + + err = excinfo.value + assert overrun.tripped_in_time is True + assert err.phase == "set_load" + assert err.site == "set_load_start" + assert reads == [] + + +def test_klein_abort_at_a_step_start_stops_at_block_start(tmp_path, monkeypatch, fakes): + # Bug caught: the block_start checkpoint alone missing from seam.run_block, so a trip at the start of a denoise + # step (before any block) decodes and runs the first block and stops at its block_end. + from mlx_dfloat.integrate import seam + + model = _klein(tmp_path, monkeypatch) + overrun = Overrun(model, fakes.counters, "denoise") + real_begin = seam.begin_step + + def begin_step(state): + overrun.fire() + return real_begin(state) + + monkeypatch.setattr(seam, "begin_step", begin_step) + + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(**KLEIN_RUN) + + err = excinfo.value + assert overrun.tripped_in_time is True + assert err.phase == "denoise" + assert err.site == "block_start" + + +def test_klein_nested_encode_arms_once(tmp_path, monkeypatch): + # Bug caught: the decorator's active-guard check missing, so generate_image's nested self.encode() arms a second + # watchdog (two sampler threads, two stop lines) instead of running under the outer one. + model = _klein(tmp_path, monkeypatch) + counts = [] + + def count_threads(): + if model.open_phase == "encode": + counts.append( + sum(1 for t in threading.enumerate() if t.name == THREAD and t.is_alive()) + ) + + _wrap_text_encoder(monkeypatch, count_threads) + + image = model.generate_image(**KLEIN_RUN) + + assert image is not None + assert counts == [1] + + +def _flux1_fake(tmp_path, monkeypatch): + """FLUX.1 over the fake-width seamed transformer and a real 2 + 2 block DF11 set, its real ``_load_set``.""" + from tests.test_flux1_model import _fake_model + + return _fake_model(tmp_path, monkeypatch) + + +def test_flux1_abort_in_set_load_leaves_no_set(tmp_path, monkeypatch, fakes): + # Bug caught: a FLUX.1 set-load abort (its _load_set has no unload guard) that marks the set resident or leaves a + # half-attached set, so the retry skips the load or is refused; or the load running on past the trip (the set + # resident and the stop at call_end, not set_group). + from tests.test_flux1_model import _patch_upstream_generate + + model = _flux1_fake(tmp_path, monkeypatch) + _patch_upstream_generate(monkeypatch, model) + overrun = Overrun(model, fakes.counters, "set_load") + _wrap_group_reads(monkeypatch, overrun.fire) + run = {"seed": 1, "prompt": "p", "height": 256, "width": 256} + + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(**run) + + err = excinfo.value + assert overrun.tripped_in_time is True + assert err.phase == "set_load" + assert err.site == "set_group" + assert model._lifecycle.set_resident is False + + fakes.counters.raise_to(0) + assert model.generate_image(**run) == "image" + assert model._lifecycle.counters.set_loads == 1 + + +def test_flux1_abort_traceback_does_not_pin_the_provider(tmp_path, monkeypatch, fakes): + # Bug caught: the decorator not clearing the abort's frames (clear_call_frames). FLUX.1 clears frames only for + # DFloatFormatError, so the seam frames in the traceback would keep the compressed set's provider alive for as + # long as the caller holds the error. + from mflux.models.flux.variants.txt2img.flux import Flux1 + from tests._flux_fakes import inputs + + from mlx_dfloat.integrate.providers import DF11Provider + + model = _flux1_fake(tmp_path, monkeypatch) + overrun = Overrun(model, fakes.counters, "denoise") + refs = [] + real_weights_for = DF11Provider.weights_for + + def weights_for(provider, block_name, shapes): + if not refs: + refs.append(weakref.ref(provider)) + overrun.fire() + return real_weights_for(provider, block_name, shapes) + + monkeypatch.setattr(DF11Provider, "weights_for", weights_for) + + def upstream(self, **kwargs): + # One step of the seamed fake-width transformer, as mflux's loop would run it. + self.transformer(*inputs()) + return "image" + + monkeypatch.setattr(Flux1, "generate_image", upstream) + + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(seed=1, prompt="p", height=256, width=256) + + assert overrun.tripped_in_time is True + assert excinfo.value.phase == "denoise" + assert model._provider is None + assert len(refs) == 1 + assert refs[0]() is None # dead while excinfo.value is still held + + +def test_flux1_abort_in_vae_raises_at_call_end(tmp_path, monkeypatch, fakes): + # Bug caught: the decorator's call_end checkpoint missing, so a trip during FLUX.1's VAE decode (evaluated at + # np.array inside ImageUtil.to_image, with no checkpoint) returns the image. Runs mflux's real Flux1 loop on the + # seamed 1 + 1 block transformer over a resident set of zeros (tests/test_mflux_api_watchdog.py). + from tests.test_flux1_model import _StubVAE + from tests.test_mflux_api_watchdog import _flux1 + + model, _name, run, _provider_cls = _flux1(tmp_path, monkeypatch) + overrun = Overrun(model, fakes.counters, "vae") + real = _StubVAE.decode + + def decode(self, latents): + overrun.fire() + return real(self, latents) + + monkeypatch.setattr(_StubVAE, "decode", decode) + + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(**run) + + err = excinfo.value + assert overrun.tripped_in_time is True + assert err.phase == "vae" + assert err.site == "call_end" + assert model._lifecycle.set_resident is False + + +# --- a direct encode() after an abort, and the phase it reports + + +class DirectEncodeOverrun: + """One-shot: raises the fake over the stop line at the first encoder pass under an armed call, in any phase. + + Wraps the lifecycle's encode callback, so it fires in a direct ``model.encode()`` (which opens no phase) as well + as in a call. ``phase_seen`` is ``model.open_phase`` at the firing pass. It records and never asserts. + """ + + def __init__(self, model, counters): + self.model, self.counters = model, counters + self.armed = True + self.tripped_in_time = None + self.phase_seen = "not fired" + + def install(self, monkeypatch): + real = self.model._lifecycle._encode + + def encode(prompt): + watchdog = _guard.active() + if self.armed and watchdog is not None: + self.armed = False + self.phase_seen = self.model.open_phase + self.counters.raise_to(STOP_LINE + 1) + self.tripped_in_time = watchdog.tripped.wait(5.0) + return real(prompt) + + monkeypatch.setattr(self.model._lifecycle, "_encode", encode) + + +def test_klein_direct_encode_overrun_stops_at_prompt_encoded(tmp_path, monkeypatch, fakes): + # Bug caught: encode() not armed on its own (the decorator missing from the public encode), so a direct + # model.encode() runs the encoder pass unwatched, caches the pair and returns. + model = _klein(tmp_path, monkeypatch) + overrun = DirectEncodeOverrun(model, fakes.counters) + overrun.install(monkeypatch) + + with pytest.raises(DFloatWatchdogError) as excinfo: + model.encode("p") + + err = excinfo.value + assert overrun.tripped_in_time is True + assert err.site == "prompt_encoded" + assert err.phase is None + assert "p" not in model.prompt_cache + + +def _zimage_fake(tmp_path, monkeypatch): + from tests._zimage_tiny import fake_model + + return fake_model(tmp_path, monkeypatch, model="z-image-turbo") + + +def _trip_in_encode(model, counters, monkeypatch): + overrun = Overrun(model, counters, "encode") + real = model._lifecycle._encode + + def encode(prompt): + overrun.fire() + return real(prompt) + + monkeypatch.setattr(model._lifecycle, "_encode", encode) + return overrun + + +def _trip_in_set_load(model, counters, monkeypatch): + overrun = Overrun(model, counters, "set_load") + _wrap_group_reads(monkeypatch, overrun.fire) + return overrun + + +@pytest.mark.parametrize("build", [_flux1_fake, _zimage_fake], ids=["flux1", "zimage"]) +@pytest.mark.parametrize( + ("trip", "phase", "site"), + [ + pytest.param(_trip_in_encode, "encode", "prompt_encoded", id="encode"), + pytest.param(_trip_in_set_load, "set_load", "set_group", id="set_load"), + ], +) +def test_an_abort_closes_its_phase_for_a_later_direct_encode( + build, trip, phase, site, tmp_path, monkeypatch, fakes +): + # Bug caught: FLUX.1 or Z-Image closing the encode or set-load phase only on a normal return (no `finally`), so + # after an abort there the phase stays open and a later direct encode() that trips names that stale phase in + # its error and its record. A direct encode() opens no phase, as on FLUX.2 Klein + # (test_klein_direct_encode_overrun_stops_at_prompt_encoded). + model = build(tmp_path, monkeypatch) + first = trip(model, fakes.counters, monkeypatch) + + with pytest.raises(DFloatWatchdogError) as excinfo: + model.generate_image(seed=1, prompt="p", height=256, width=256) + + assert first.tripped_in_time is True + assert (excinfo.value.phase, excinfo.value.site) == (phase, site) + assert model.open_phase is None + + fakes.counters.raise_to(0) + later = DirectEncodeOverrun(model, fakes.counters) + later.install(monkeypatch) + + with pytest.raises(DFloatWatchdogError) as excinfo: + model.encode("q") + + err = excinfo.value + assert later.tripped_in_time is True + assert later.phase_seen is None + assert err.site == "prompt_encoded" + assert err.phase is None + assert err.record["context"]["phase"] is None diff --git a/tests/test_mflux_lifecycle.py b/tests/test_mflux_lifecycle.py index b230455..d6cb5fc 100644 --- a/tests/test_mflux_lifecycle.py +++ b/tests/test_mflux_lifecycle.py @@ -1,10 +1,15 @@ """The lifecycle moved from flux1/ to mflux/ so every family shares it; FLUX.1's old path stays importable.""" +import gc import logging import mlx.core as mx import pytest +from tests._fake_counters import FakeCounters +from mlx_dfloat import _guard +from mlx_dfloat._watchdog import Watchdog +from mlx_dfloat.errors import DFloatWatchdogError from mlx_dfloat.mflux import lifecycle as shared from mlx_dfloat.mflux.flux1 import lifecycle as old @@ -29,6 +34,8 @@ def load_encoders(): ) # kept alive: the reclaim check must complain mx.eval(leaked[0]) + gc.collect() # garbage an earlier test left would otherwise be freed inside the check and pass it + mx.clear_cache() bound = int(mx.get_active_memory()) life = shared.Lifecycle( load_encoders=load_encoders, @@ -45,3 +52,206 @@ def load_encoders(): ): life.ensure_embeddings("p") assert [r.name for r in caplog.records] == ["mlx_dfloat.mflux"] + + +@pytest.fixture +def raise_mode(tmp_path): + """A started raise-mode watchdog (stop line 9_000) over FakeCounters, and a call that trips it. + + Stopped at teardown; no test may see it end the "process". + """ + fake, exits = FakeCounters(), [] + watchdog = Watchdog( + tmp_path, + ceiling=10_000, + budget=None, + interval=0.01, + counters=fake, + exit_process=exits.append, + mode="raise", + stop_margin=1_000, + ).start() + + def trip(): + fake.raise_to(9_500) + assert watchdog.tripped.wait(timeout=5) + + yield watchdog, trip + watchdog.stop() + assert exits == [] + + +def _lifecycle(calls, *, load_encoders=None, encode=None, cache=None): + """A Lifecycle whose callbacks log to ``calls``; a bound no drop can miss.""" + + def default_encode(prompt): + calls.append(("encode", prompt)) + return (mx.ones((2,)), mx.zeros((2,))) + + return shared.Lifecycle( + load_encoders=load_encoders or (lambda: calls.append(("load_encoders",))), + unload_encoders=lambda: calls.append(("unload_encoders",)), + encode=encode or default_encode, + load_set=lambda: calls.append(("load_set",)), + unload_set=lambda: calls.append(("unload_set",)), + prompt_cache={} if cache is None else cache, + retained_bound=lambda: 1 << 62, + ) + + +def test_a_trip_during_encode_raises_and_drops_the_encoders(raise_mode, monkeypatch): + # Bug caught: the checkpoint before the pair's evaluation (the long call that crosses the + # line, so the next prompt is encoded past the trip) or after the cache store (the stopped + # prompt's pair kept), or outside the try that drops the encoders. + watchdog, trip = raise_mode + calls, cache = [], {} + real_eval = shared._eval + + def eval_crossing_the_line(*pair): + real_eval(*pair) + trip() + + monkeypatch.setattr(shared, "_eval", eval_crossing_the_line) + life = _lifecycle(calls, cache=cache) + with _guard.scope(watchdog), pytest.raises(DFloatWatchdogError) as caught: + life.ensure_embeddings("a", "b") + assert caught.value.site == "prompt_encoded" + assert life.encoders_loaded is False + assert "a" not in cache + assert calls == [("load_encoders",), ("encode", "a"), ("unload_encoders",)] + + +def test_a_trip_during_the_encoder_load_raises_before_any_encode(raise_mode): + # Bug caught: no checkpoint after the load (the prompt is encoded past the trip), or one + # placed before the try, so the loaded encoders are never dropped. + watchdog, trip = raise_mode + calls = [] + + def load_encoders(): + calls.append(("load_encoders",)) + trip() + + life = _lifecycle(calls, load_encoders=load_encoders) + with _guard.scope(watchdog), pytest.raises(DFloatWatchdogError) as caught: + life.ensure_embeddings("a") + assert caught.value.site == "encoder_loaded" + assert life.encoders_loaded is False + assert calls == [("load_encoders",), ("unload_encoders",)] + + +def test_a_tripped_call_raises_before_the_set_load(raise_mode): + # Bug caught: no checkpoint before the set load, so a call that is already over the stop line + # reads the whole compressed set before stopping. + watchdog, trip = raise_mode + calls = [] + life = _lifecycle(calls) + trip() + with _guard.scope(watchdog), pytest.raises(DFloatWatchdogError) as caught: + life.ensure_set() + assert caught.value.site == "set_load_start" + assert (calls, life.set_resident) == ([], False) + + +def test_a_drop_waits_for_the_gpu_before_it_collects_and_checks(monkeypatch): + # Bug caught: `_reclaim` collecting and reading active memory with GPU work still in flight (no synchronize + # first): a buffer whose free is pending in a command's completion handler is still counted active, so the check + # reports a false "still active" and the bytes land in the cache after the clear. + events = [] + monkeypatch.setattr(mx, "synchronize", lambda *a, **k: events.append("synchronize")) + monkeypatch.setattr(mx, "clear_cache", lambda: events.append("clear_cache")) + monkeypatch.setattr(gc, "collect", lambda *a: events.append("collect") or 0) + life = shared.Lifecycle( + load_encoders=lambda: None, + unload_encoders=lambda: None, + encode=lambda prompt: (), + load_set=lambda: None, + unload_set=lambda: events.append("unload_set"), + prompt_cache={}, + retained_bound=lambda: events.append("bound") or 1 << 62, + ) + life.drop_set() + assert events == ["unload_set", "synchronize", "collect", "clear_cache", "bound"] + + +def _record_drop(monkeypatch, events, *, footprints=(800, 800)): + """Record every step a set drop takes: waits, collections, clears, the bound read, kicks, footprint reads, sleeps.""" + from mlx_dfloat.mflux import _drain + + remaining = list(footprints) + monkeypatch.setattr(mx, "synchronize", lambda *a, **k: events.append("synchronize")) + monkeypatch.setattr(mx, "clear_cache", lambda: events.append("clear_cache")) + monkeypatch.setattr(gc, "collect", lambda *a: events.append("collect") or 0) + monkeypatch.setattr(_drain, "_kick", lambda: events.append("kick")) + monkeypatch.setattr(_drain, "_sleep", lambda seconds: events.append("sleep")) + + def read(): + events.append("read") + return remaining.pop(0) if len(remaining) > 1 else remaining[0] + + monkeypatch.setattr(shared, "_read_footprint", read, raising=False) + return shared.Lifecycle( + load_encoders=lambda: None, + unload_encoders=lambda: events.append("unload_encoders"), + encode=lambda prompt: (), + load_set=lambda: None, + unload_set=lambda: events.append("unload_set"), + prompt_cache={}, + retained_bound=lambda: events.append("bound") or 1 << 62, + ) + + +class _ScopeOnly: + """An active guard that never tripped: what an armed call's scope looks like to the lifecycle.""" + + class tripped: # noqa: N801 + @staticmethod + def is_set(): + return False + + +def test_an_unarmed_drop_makes_exactly_the_calls_it_made_before(monkeypatch): + # Bug caught: the drain run on an unarmed path (the command, watchdog=None, verify_image), which then pays a GPU + # kick and up to 0.25 s of polling on every drop that no watchdog asked for. The list is the 0.2.2 sequence. + events = [] + life = _record_drop(monkeypatch, events) + life.drop_set() + life.drop_encoders() + assert events == [ + "unload_set", + "synchronize", + "collect", + "clear_cache", + "bound", + "unload_encoders", + "synchronize", + "collect", + "clear_cache", + "bound", + ] + + +def test_an_armed_drop_drains_after_the_check(monkeypatch): + # Bug caught: no drain inside an armed call, so the released pages stay in the footprint and the next sample (the + # set load right after the encoders' drop) trips on memory the call already gave back; or the drain run before the + # active-memory check (a failed check would then have kicked for nothing). + events = [] + life = _record_drop(monkeypatch, events, footprints=(900 << 20, 700 << 20, 700 << 20)) + with _guard.scope(_ScopeOnly()): + life.drop_encoders() + assert events == [ + "unload_encoders", + "synchronize", + "collect", + "clear_cache", + "bound", + "synchronize", + "clear_cache", + "kick", + "read", + "sleep", + "read", + "sleep", + "read", + "synchronize", + "clear_cache", + ] diff --git a/tests/test_mflux_watchdog_wiring.py b/tests/test_mflux_watchdog_wiring.py new file mode 100644 index 0000000..97a5e3c --- /dev/null +++ b/tests/test_mflux_watchdog_wiring.py @@ -0,0 +1,197 @@ +"""The ``watchdog`` keyword on the six model classes: stored as ``model.watchdog`` by ``_assemble``. + +Every test is `@pytest.mark.mflux`; the builders import mflux only when called, so the module collects without it. +""" + +import pytest + +from mlx_dfloat.mflux import WatchdogConfig + +pytestmark = pytest.mark.mflux + + +def _flux1(tmp_path, monkeypatch, **overrides): + from tests.test_flux1_model import _fake_model + + return _fake_model(tmp_path, monkeypatch, **overrides) + + +def _zimage(tmp_path, monkeypatch, **overrides): + from tests._zimage_tiny import fake_model + + return fake_model(tmp_path, monkeypatch, **overrides) + + +def _flux2(tmp_path, monkeypatch, **overrides): + from tests._flux2_tiny import fake_model + + return fake_model(tmp_path, monkeypatch, **overrides) + + +def _qwen21(tmp_path, monkeypatch, **overrides): + from tests._qwen21_tiny import fake_model + + return fake_model(tmp_path, monkeypatch, **overrides) + + +def _ernie(tmp_path, monkeypatch, **overrides): + from tests._ernie_tiny import fake_model + + return fake_model(tmp_path, monkeypatch, **overrides) + + +def _krea2(tmp_path, monkeypatch, **overrides): + from tests._krea2_tiny import fake_model + + return fake_model(tmp_path, monkeypatch, **overrides) + + +BUILDERS = [ + pytest.param(_flux1, id="flux1"), + pytest.param(_zimage, id="zimage"), + pytest.param(_flux2, id="flux2"), + pytest.param(_qwen21, id="qwen21"), + pytest.param(_ernie, id="ernie"), + pytest.param(_krea2, id="krea2"), +] + + +@pytest.mark.parametrize("build", BUILDERS) +def test_the_watchdog_keyword_defaults_to_the_default_config(build, tmp_path, monkeypatch): + # Bug caught: an _assemble that never sets model.watchdog, or a default of None that leaves a Python caller + # unwatched (the spec's default is WatchdogConfig()). + model = build(tmp_path, monkeypatch) + assert model.watchdog == WatchdogConfig() + + +@pytest.mark.parametrize("build", BUILDERS) +def test_the_watchdog_keyword_none_is_stored_as_none(build, tmp_path, monkeypatch): + # Bug caught: an _assemble that drops the keyword (TypeError) or replaces None with the default config, so the + # command's model would arm a second watchdog under the command's own. + model = build(tmp_path, monkeypatch, watchdog=None) + assert model.watchdog is None + + +@pytest.mark.parametrize("build", BUILDERS) +def test_the_watchdog_keyword_keeps_the_callers_config(build, tmp_path, monkeypatch): + # Bug caught: an _assemble that copies or rebuilds the config (losing a tier's explicit ceiling) instead of keeping + # the caller's object. stop_margin=1: the default 1 GiB margin is refused below a 123-byte ceiling. + config = WatchdogConfig(ceiling=123, stop_margin=1) + model = build(tmp_path, monkeypatch, watchdog=config) + assert model.watchdog is config + + +# --- the constructor forwards the keyword to _assemble ------------------------------------------------------------- +# +# The builders above enter through ``_from_parts``, so they cannot see a ``__init__`` that takes ``watchdog`` and then +# drops it: ``_assemble`` would quietly fall back to its own default. Each case below calls the real ``__init__`` with +# every step between the decoder self-check and ``_assemble`` replaced (``monkeypatch.setattr`` refuses a name that +# does not exist, so a renamed step fails here instead of resolving or loading anything), and records what reaches +# ``_assemble``. + +# What every replaced step returns; nothing reads it, because _assemble is replaced too. +_STUB = object() + + +def _stub(*args, **kwargs): + return _STUB + + +# family: (model module, class name, model name, init-module alias, memory-module alias or None, model-module steps) +INIT_STEPS = { + "flux1": ( + "mlx_dfloat.mflux.flux1.model", + "DFloatFlux1", + "schnell", + "base_init", + None, + { + "open_checkpoint": _stub, + "check_flux_groups": _stub, + "build_transformer": lambda *a, **k: (_STUB, _STUB), # (transformer, shapes) + "sizes_for": _stub, + }, + ), + "zimage": ( + "mlx_dfloat.mflux.zimage.model", + "DFloatZImage", + "z-image-turbo", + "zinit", + None, + { + "open_checkpoint": _stub, + "check_zimage_groups": _stub, + "build_transformer": _stub, + "sizes_for": _stub, + }, + ), + "flux2": ( + "mlx_dfloat.mflux.flux2.model", + "DFloatFlux2Klein", + "flux2-klein-4b", + "finit", + "kmem", + {"open_checkpoint": _stub, "build_transformer": _stub}, + ), + "qwen21": ( + "mlx_dfloat.mflux.qwen21.model", + "DFloatQwenImage21", + "qwen-image-2.1", + "qinit", + "qmem", + {"open_checkpoint": _stub, "build_transformer": _stub}, + ), + "ernie": ( + "mlx_dfloat.mflux.ernie.model", + "DFloatErnieImage", + "ernie-image-turbo", + "einit", + "emem", + {"open_checkpoint": _stub, "build_transformer": _stub}, + ), + "krea2": ( + "mlx_dfloat.mflux.krea2.model", + "DFloatKrea2", + "krea-2", + "kinit", + "kmem", + {"open_checkpoint": _stub, "check_variant": _stub, "build_transformer": _stub}, + ), +} + + +@pytest.mark.parametrize("family", list(INIT_STEPS)) +def test_init_forwards_the_watchdog_keyword(family, tmp_path, monkeypatch): + # Bug caught: a class whose __init__ accepts `watchdog=` but leaves `watchdog=watchdog` out of its `_assemble` + # call, so a caller's config (a tier's lower ceiling, or None under the command's own watchdog) is silently + # replaced by the default config. + import importlib + + from mlx_dfloat import _metal_decode + from mlx_dfloat.mflux._hub import ResolvedRepo + + module_name, class_name, model_name, init_alias, memory_alias, steps = INIT_STEPS[family] + module = importlib.import_module(module_name) + cls = getattr(module, class_name) + init = getattr(module, init_alias) + monkeypatch.setattr(_metal_decode, "ensure_canary", lambda **kwargs: None) + monkeypatch.setattr( + init, + "resolve", + lambda spec, *, patterns, revision=None: ResolvedRepo( + root=tmp_path, repo_id=spec, revision=revision + ), + ) + monkeypatch.setattr(init, "load_base", _stub) + if memory_alias is not None: + monkeypatch.setattr(getattr(module, memory_alias), "sizes_for", _stub) + for name, replacement in steps.items(): + monkeypatch.setattr(module, name, replacement) + received = [] + monkeypatch.setattr(cls, "_assemble", lambda self, **parts: received.append(parts)) + + config = WatchdogConfig(ceiling=123, stop_margin=1) + cls(model_name, watchdog=config) + + assert len(received) == 1 + assert received[0].get("watchdog", "") is config diff --git a/tests/test_prove_api_watchdog.py b/tests/test_prove_api_watchdog.py new file mode 100644 index 0000000..a5e132c --- /dev/null +++ b/tests/test_prove_api_watchdog.py @@ -0,0 +1,378 @@ +"""The proof orchestrator, driven through a fake unit runner: no test here builds a model or runs a unit. + +The fake stands in for the unit subprocess: it writes the unit's ``.outcome.json`` and abort records +where a real unit would, and returns a chosen exit code. The peaks are synthetic, with multi-GiB gaps, so +every phase is isolable unless a test removes a phase record. +""" + +import json +import os +import subprocess +import sys +from pathlib import Path +from typing import Any + +import scripts.prove_api_watchdog as prove + +GIB = 1_073_741_824 + + +def _phase(start: float, peak: float, end: float) -> dict[str, int]: + return { + "footprint_start": int(start * GIB), + "mlx_peak": int(peak * GIB), + "footprint_end": int(end * GIB), + } + + +PEAKS: dict[str, Any] = { + "label": "sampled at phase boundaries", + "encode": _phase(1, 6, 7), + "set_load": _phase(4, 5, 8), + "denoise": _phase(8, 12, 12), + "vae": _phase(12, 16, 13), +} + +U0_DONE = {"unit": "U0", "completed": True, "image_saved": True, "peaks": PEAKS} +SITE = {"U1": "prompt_encoded", "U2": "set_group", "U3": "block_start", "U4": "call_end"} +PHASE = {"U1": "encode", "U2": "set_load", "U3": "denoise", "U4": "vae"} +U5_ABORT = {"reason": "memory", "context": {"phase": "vae"}, "escalation": "ceiling"} + + +def _raised(unit: str, *, site: str | None = None, artifact: str | None = None) -> dict[str, Any]: + return { + "unit": unit, + "ceiling": [9 * GIB, GIB], + "raised": { + "type": "DFloatWatchdogError", + "reason": "memory", + "phase": PHASE[unit], + "site": site or SITE[unit], + "artifact": artifact, + }, + } + + +def _passing_plan() -> dict[str, tuple[int, Any, list[tuple[str, Any]]]]: + plan: dict[str, tuple[int, Any, list[tuple[str, Any]]]] = {"U0": (0, U0_DONE, [])} + for unit in ("U1", "U2", "U3", "U4"): + plan[unit] = (0, _raised(unit), []) + plan["U5"] = ( + 70, + {"unit": "U5", "ceiling": [9 * GIB, 64 << 20]}, + [("abort-1Z-9.json", U5_ABORT)], + ) + # U6: U2's abort, the watched memory back at 1 GiB after it (under the 8 GiB stop line), then the baseline + # call again in the same process, completed. + plan["U6"] = ( + 0, + {**_raised("U2"), "unit": "U6", "watched_after_abort": GIB, "retry": {"completed": True}}, + [], + ) + return plan + + +class FakeUnits: + """Plays each unit process: writes its outcome and abort records, returns the planned exit code. + + A plan entry is one attempt, used for every run of the unit, or a list of attempts, one per run in order. + """ + + def __init__(self, plan: dict[str, Any]) -> None: + self.plan = plan + self.calls: list[str] = [] + + def __call__(self, cmd: list[str], **_: Any) -> subprocess.CompletedProcess[Any]: + unit = cmd[cmd.index("--unit") + 1] + out = Path(cmd[cmd.index("--out") + 1]) + attempt = self.calls.count(unit) + self.calls.append(unit) + entry = self.plan[unit] + code, outcome, aborts = entry[attempt] if isinstance(entry, list) else entry + if outcome is not None: + (out / f"{unit}.outcome.json").write_text(json.dumps(outcome)) + for name, record in aborts: + (out / f"{unit}-artifacts").mkdir(exist_ok=True) + (out / f"{unit}-artifacts" / name).write_text(json.dumps(record)) + return subprocess.CompletedProcess(cmd, code) + + +def _record(out: Path, unit: str) -> Any: + return json.loads((out / f"{unit}.json").read_text()) + + +def test_every_unit_passing_returns_0_with_one_record_per_unit(tmp_path): + # Bug caught: the return code inverted, or a passing unit's record not written. + fake = FakeUnits(_passing_plan()) + assert prove.orchestrate(tmp_path, model=prove.MODEL, wall=60.0, run=fake) == 0 + assert fake.calls == ["U0", "U1", "U2", "U3", "U4", "U5", "U6"] + for unit in fake.calls: + assert _record(tmp_path, unit)["verdict"] == "pass", unit + assert _record(tmp_path, "U5")["exit_code"] == 70 + + +def test_one_failed_unit_returns_1_and_the_later_units_still_run(tmp_path): + # Bug caught: a failed stopping unit ends the run early, or the run returns 0 on a failed unit. + plan = _passing_plan() + # stopped, but at the wrong checkpoint, on both attempts + plan["U3"] = (0, _raised("U3", site="call_end"), []) + fake = FakeUnits(plan) + assert prove.orchestrate(tmp_path, model=prove.MODEL, wall=60.0, run=fake) == 1 + assert fake.calls == ["U0", "U1", "U2", "U3", "U3", "U4", "U5", "U6"] + assert _record(tmp_path, "U3")["verdict"] == "fail" + + +def _first_attempt(out: Path, unit: str) -> Any: + pointer = _record(out, unit)["first_attempt"] + return pointer, json.loads((out / pointer["record"]).read_text()) + + +def test_a_unit_that_fails_then_passes_returns_0_and_both_attempts_are_kept(tmp_path): + # Bug caught: no second attempt (exit 1 on a spread fail), the first attempt overwritten or deleted, its + # outcome or abort records left where the second attempt reads them, or the second record not naming it. + plan = _passing_plan() + first = (70, {"unit": "U4", "ceiling": [9 * GIB, GIB]}, [("abort-1Z-9.json", U5_ABORT)]) + plan["U4"] = [first, (0, _raised("U4"), [])] + fake = FakeUnits(plan) + assert prove.orchestrate(tmp_path, model=prove.MODEL, wall=60.0, run=fake) == 0 + assert fake.calls == ["U0", "U1", "U2", "U3", "U4", "U4", "U5", "U6"] + second = _record(tmp_path, "U4") + assert second["verdict"] == "pass" + assert second["artifact"] is None # the first attempt's abort record was moved, not read again + pointer, kept = _first_attempt(tmp_path, "U4") + assert pointer["verdict"] == "fail" + assert pointer["record"].startswith("earlier/") + assert (kept["exit_code"], kept["verdict"]) == (70, "fail") + folder = (tmp_path / pointer["record"]).parent + assert json.loads((folder / "U4.outcome.json").read_text())["ceiling"] == [9 * GIB, GIB] + assert (folder / "U4-artifacts" / "abort-1Z-9.json").is_file() + + +def test_a_unit_that_fails_twice_returns_1_and_the_second_attempt_decides(tmp_path): + # Bug caught: the first attempt's verdict reported, a third attempt run, or the retry's fail turned into a pass. + plan = _passing_plan() + plan["U2"] = [ + (0, _raised("U2", site="block_start"), []), + (0, _raised("U2", site="call_end"), []), + ] + fake = FakeUnits(plan) + assert prove.orchestrate(tmp_path, model=prove.MODEL, wall=60.0, run=fake) == 1 + assert fake.calls.count("U2") == 2 + assert _record(tmp_path, "U2")["result"]["raised"]["site"] == "call_end" + _, kept = _first_attempt(tmp_path, "U2") + assert kept["result"]["raised"]["site"] == "block_start" + + +def test_a_failed_baseline_is_never_run_twice(tmp_path): + # Bug caught: the second attempt also given to U0, which then passes and runs the stopping units on peaks + # from a run that failed once. + plan = _passing_plan() + plan["U0"] = [(1, None, []), (0, U0_DONE, [])] + fake = FakeUnits(plan) + assert prove.orchestrate(tmp_path, model=prove.MODEL, wall=60.0, run=fake) == 2 + assert fake.calls == ["U0"] + + +def test_a_unit_not_isolable_is_not_rerun_and_the_run_returns_2(tmp_path): + # Bug caught: "not isolable" (U2's settled reading too close to its line) re-run as a fail, or counted as a + # plain fail (1) and not as a run that could not test the unit (2). + plan = _passing_plan() + plan["U2"] = (0, {"unit": "U2", "ceiling": None, "settled": 5 * GIB}, []) + fake = FakeUnits(plan) + assert prove.orchestrate(tmp_path, model=prove.MODEL, wall=60.0, run=fake) == 2 + assert fake.calls == ["U0", "U1", "U2", "U3", "U4", "U5", "U6"] + assert _record(tmp_path, "U2")["verdict"] == "not isolable" + + +def test_not_isolable_outranks_a_failed_unit(tmp_path): + # Bug caught: the exit code checks for a fail first, so a run with both reads 1. + plan = _passing_plan() + plan["U2"] = (0, {"unit": "U2", "ceiling": None}, []) + plan["U3"] = (0, _raised("U3", site="call_end"), []) + fake = FakeUnits(plan) + assert prove.orchestrate(tmp_path, model=prove.MODEL, wall=60.0, run=fake) == 2 + + +def test_a_not_isolable_record_found_on_resume_returns_2(tmp_path): + # Bug caught: only the units run now are checked for "not isolable", so a resumed run reads 1 or 0. + (tmp_path / "U0.json").write_text(json.dumps({"verdict": "pass", "result": U0_DONE})) + (tmp_path / "U2.json").write_text(json.dumps({"unit": "U2", "verdict": "not isolable"})) + fake = FakeUnits(_passing_plan()) + assert prove.orchestrate(tmp_path, model=prove.MODEL, wall=60.0, run=fake) == 2 + assert "U2" not in fake.calls + + +def test_stale_leftovers_and_a_failed_first_attempt_go_to_separate_folders(tmp_path): + # Bug caught: both set-asides in the same second share one folder, so the first attempt's outcome replaces the + # killed attempt's (or its artifacts folder cannot be moved onto the one already there). + (tmp_path / "U0.json").write_text(json.dumps({"verdict": "pass", "result": U0_DONE})) + (tmp_path / "U1.outcome.json").write_text(json.dumps({"stale": True})) + (tmp_path / "U1-artifacts").mkdir() + (tmp_path / "U1-artifacts" / "abort-old.json").write_text(json.dumps({"stale": True})) + plan = _passing_plan() + first = (70, {"unit": "U1", "attempt": 1}, [("abort-new.json", U5_ABORT)]) + plan["U1"] = [first, (0, _raised("U1"), [])] + fake = FakeUnits(plan) + assert prove.orchestrate(tmp_path, model=prove.MODEL, wall=60.0, run=fake) == 0 + outcomes = [json.loads(p.read_text()) for p in (tmp_path / "earlier").glob("*/U1.outcome.json")] + assert sorted(outcomes, key=str) == sorted( + [{"stale": True}, {"unit": "U1", "attempt": 1}], key=str + ) + assert len(list((tmp_path / "earlier").glob("*/U1-artifacts/abort-old.json"))) == 1 + assert len(list((tmp_path / "earlier").glob("*/U1-artifacts/abort-new.json"))) == 1 + + +def test_a_failed_baseline_returns_2_keeps_a_u0_failed_file_and_runs_nothing_else(tmp_path): + # Bug caught: a failed U0 written as U0.json (a re-run would skip it) or the stopping units run anyway. + plan = _passing_plan() + plan["U0"] = (1, None, []) + fake = FakeUnits(plan) + assert prove.orchestrate(tmp_path, model=prove.MODEL, wall=60.0, run=fake) == 2 + assert fake.calls == ["U0"] + assert not (tmp_path / "U0.json").exists() + failed = list(tmp_path.glob("U0-failed-*.json")) + assert len(failed) == 1 + assert json.loads(failed[0].read_text())["exit_code"] == 1 + again = FakeUnits(_passing_plan()) + assert prove.orchestrate(tmp_path, model=prove.MODEL, wall=60.0, run=again) == 0 + assert again.calls[0] == "U0" + + +def test_a_unit_that_is_not_isolable_stops_the_run_with_2_right_after_u0(tmp_path): + # Bug caught: the orchestrator runs U1-U6 for hours before reporting that U4 and U5 could never stop. + plan = _passing_plan() + no_vae = {key: value for key, value in PEAKS.items() if key != "vae"} + plan["U0"] = (0, {**U0_DONE, "peaks": no_vae}, []) + fake = FakeUnits(plan) + assert prove.orchestrate(tmp_path, model=prove.MODEL, wall=60.0, run=fake) == 2 + assert fake.calls == ["U0"] + assert not (tmp_path / "U0.json").exists() # the next run repeats the baseline + stopped = list(tmp_path.glob("U0-not-isolable-*.json")) + assert len(stopped) == 1 + record = json.loads(stopped[0].read_text()) + assert record["not_isolable"] == ["U4", "U5"] + assert "U4" in record["reason"] + assert "U5" in record["reason"] + + +def test_units_with_a_record_are_skipped_and_their_record_is_untouched(tmp_path): + # Bug caught: resume ignored, so a finished unit is run again and its record overwritten. + (tmp_path / "U0.json").write_text(json.dumps({"verdict": "pass", "result": U0_DONE})) + kept = json.dumps({"unit": "U1", "verdict": "pass", "kept": True}) + (tmp_path / "U1.json").write_text(kept) + fake = FakeUnits(_passing_plan()) + assert prove.orchestrate(tmp_path, model=prove.MODEL, wall=60.0, run=fake) == 0 + assert fake.calls == ["U2", "U3", "U4", "U5", "U6"] + assert (tmp_path / "U1.json").read_text() == kept + + +def test_an_earlier_attempt_is_set_aside_and_not_read_as_this_run(tmp_path): + # Bug caught: a stale outcome or abort record from a killed attempt counted as this run's result. + (tmp_path / "U0.json").write_text(json.dumps({"verdict": "pass", "result": U0_DONE})) + (tmp_path / "U1.outcome.json").write_text(json.dumps(_raised("U1"))) + (tmp_path / "U1-artifacts").mkdir() + (tmp_path / "U1-artifacts" / "abort-old.json").write_text(json.dumps({"stale": True})) + plan = _passing_plan() + plan["U1"] = (70, None, []) # this attempt wrote nothing + fake = FakeUnits(plan) + assert prove.orchestrate(tmp_path, model=prove.MODEL, wall=60.0, run=fake) == 1 + record = _record(tmp_path, "U1") + assert record["result"] is None + assert record["artifact"] is None + assert record["verdict"] == "fail" + aside = list((tmp_path / "earlier").glob("*/U1.outcome.json")) + assert len(aside) == 1 + assert json.loads(aside[0].read_text())["raised"]["site"] == "prompt_encoded" + assert list((tmp_path / "earlier").glob("*/U1-artifacts/abort-old.json")) + + +def test_the_newest_abort_record_is_the_one_kept(tmp_path): + # Bug caught: the first-written, the last-written or the first-listed abort record read instead of the newest + # by its stamp. + plan = _passing_plan() + middle = ("abort-20261125T100002.000000Z-7.json", {**U5_ABORT, "escalation": "grace"}) + newest = ("abort-20261125T100003.000000Z-7.json", U5_ABORT) + oldest = ("abort-20261125T100001.000000Z-7.json", {**U5_ABORT, "escalation": None}) + # written out of name order: the newest is neither the first nor the last written + plan["U5"] = (70, plan["U5"][1], [middle, newest, oldest]) + fake = FakeUnits(plan) + assert prove.orchestrate(tmp_path, model=prove.MODEL, wall=60.0, run=fake) == 0 + assert _record(tmp_path, "U5")["artifact"] == U5_ABORT + + +def test_records_under_a_fake_home_name_no_home_directory(tmp_path, monkeypatch): + # Bug caught: the records (committed with the proof) carry the user's home path, as the abort artifact + # path and the resolved --out do. + home = tmp_path.resolve() / "home" + home.mkdir() + monkeypatch.setenv("HOME", str(home)) + monkeypatch.chdir(home) + out = home / "proof" + plan = _passing_plan() + artifact = str(out / "U1-artifacts" / "abort-1Z-9.json") + plan["U1"] = (0, _raised("U1", artifact=artifact), []) + fake = FakeUnits(plan) + assert prove.main(["--orchestrate", "--out", "proof"], run=fake) == 0 + assert str(home) in (out / "U1.outcome.json").read_text() # the input does carry the home + written = [out / f"{unit}.json" for unit in fake.calls] + for path in written: + assert str(home) not in path.read_text(), path.name + assert ( + _record(out, "U1")["result"]["raised"]["artifact"] == "~/proof/U1-artifacts/abort-1Z-9.json" + ) + + +def test_a_path_value_under_the_home_is_written_with_a_tilde(tmp_path, monkeypatch): + # Bug caught: the scrub runs before JSON turns a Path into text, so a Path under the home escapes it. + home = tmp_path.resolve() / "home" + monkeypatch.setenv("HOME", str(home)) + target = tmp_path / "r.json" + prove._write_json(target, {"folder": home / "proof", "n": 3}) + text = target.read_text() + assert str(home) not in text + assert json.loads(text)["n"] == 3 + assert "~/proof" in text + + +def test_u5_is_placed_with_its_own_64_mib_margin(): + # Bug caught: `_not_isolable` places U5 with the default 1 GiB margin, so a VAE that only an exit line can + # isolate stops the whole run at U0. The VAE top is 900 MiB above the denoise top (12 GiB): + # - U4, 1 GiB margin: stop 12 GiB + 900 - 512 = 12 GiB + 388 MiB, not above 12 GiB + 410 MiB headroom: blocked; + # - U5, 64 MiB margin: stop (12 GiB + 12 GiB + 900 - 64) / 2 = 12 GiB + 418 MiB, above it: placed. + mib = 1024**2 + peaks = { + **PEAKS, + "vae": {"footprint_start": 12 * GIB, "mlx_peak": 12 * GIB + 900 * mib, "footprint_end": 0}, + } + assert prove._not_isolable(peaks) == ["U4"] + + +def test_a_baseline_without_peaks_stops_with_every_stopping_unit_not_isolable(tmp_path): + # Bug caught: a passing U0 whose outcome lacks peaks crashes the orchestrator (no reason written) instead of + # stopping with exit 2 and naming the six units it cannot place. + plan = _passing_plan() + plan["U0"] = (0, {key: value for key, value in U0_DONE.items() if key != "peaks"}, []) + fake = FakeUnits(plan) + assert prove.orchestrate(tmp_path, model=prove.MODEL, wall=60.0, run=fake) == 2 + assert fake.calls == ["U0"] + (stopped,) = tmp_path.glob("U0-not-isolable-*.json") + assert json.loads(stopped.read_text())["not_isolable"] == ["U1", "U2", "U3", "U4", "U5", "U6"] + + +def test_help_works_when_mlx_cannot_be_imported(tmp_path): + # Bug caught: the orchestrator's imports load MLX (the guard would turn that into exit 2), so the + # parent process of a proof run holds Metal state and --help fails on a host without MLX. + shadow = tmp_path / "mlx" + shadow.mkdir() + (shadow / "__init__.py").write_text('raise ImportError("no mlx here")\n') + result = subprocess.run( + [sys.executable, "-m", "scripts.prove_api_watchdog", "--help"], + cwd=Path(prove.__file__).resolve().parents[1], + capture_output=True, + text=True, + timeout=60, + check=False, + env={**os.environ, "PYTHONPATH": str(tmp_path)}, + ) + assert result.returncode == 0, result.stderr[-800:] + assert "usage:" in result.stdout diff --git a/tests/test_public_api.py b/tests/test_public_api.py index 7abdcaa..f4e0e0c 100644 --- a/tests/test_public_api.py +++ b/tests/test_public_api.py @@ -77,7 +77,72 @@ def test_the_model_classes_stay_out_of_the_star_import(): # Bug caught: a model class added to __all__ (`from mlx_dfloat.mflux import *` would then need mflux). import mlx_dfloat.mflux as adapters - assert sorted(adapters.__all__) == ["DFloatModel", "require_mflux"] + assert sorted(adapters.__all__) == ["DFloatModel", "WatchdogConfig", "require_mflux"] + + +def test_the_mflux_package_exports_watchdog_config(): + # Bug caught: WatchdogConfig left out of __all__, or listed there but not bound on the package (a star-import + # would then fall into __getattr__ and raise AttributeError). + import mlx_dfloat.mflux as adapters + from mlx_dfloat.mflux._watchconfig import WatchdogConfig + + assert adapters.__all__ == ["DFloatModel", "WatchdogConfig", "require_mflux"] + assert adapters.WatchdogConfig is WatchdogConfig + + +def test_watchdog_error_is_exported_and_a_memory_error(): + # Bug caught: the watchdog error deriving from DFloatError alone, so a caller's `except MemoryError` or + # `except DFloatResourceError` misses a memory trip; or the name missing from either __all__. + import mlx_dfloat.errors + from mlx_dfloat import DFloatResourceError, DFloatWatchdogError + + assert "DFloatWatchdogError" in mlx_dfloat.__all__ + assert "DFloatWatchdogError" in mlx_dfloat.errors.__all__ + assert issubclass(DFloatWatchdogError, DFloatResourceError) + assert issubclass(DFloatWatchdogError, MemoryError) + assert issubclass(DFloatWatchdogError, DFloatError) + + +def test_watchdog_error_pickles_with_its_fields(): + # Bug caught: default Exception pickling, which re-calls __init__ with the message alone and drops the + # keyword-only fields (TypeError on load), or a __reduce__ that loses one field. + import pickle + from pathlib import Path + + from mlx_dfloat import DFloatWatchdogError + + e = DFloatWatchdogError( + "stopped at the memory ceiling", + reason="memory", + phase="denoise", + site="block_end", + artifact=Path("/tmp/watchdog/run.json"), + record={"peak": 123, "samples": [1, 2]}, + ) + back = pickle.loads(pickle.dumps(e)) + assert type(back) is DFloatWatchdogError + assert str(back) == "stopped at the memory ceiling" + assert back.reason == "memory" + assert back.phase == "denoise" + assert back.site == "block_end" + assert back.artifact == Path("/tmp/watchdog/run.json") + assert back.record == {"peak": 123, "samples": [1, 2]} + + +def test_watchdog_error_pickles_with_no_phase_and_no_artifact(): + # Bug caught: a __reduce__ that coerces None (str(None) == "None", Path(None) raises) for the optional fields. + import pickle + + from mlx_dfloat import DFloatWatchdogError + + e = DFloatWatchdogError( + "wall", reason="wall", phase=None, site="call_end", artifact=None, record={} + ) + back = pickle.loads(pickle.dumps(e)) + assert back.phase is None + assert back.artifact is None + assert back.site == "call_end" + assert back.record == {} @pytest.mark.mflux diff --git a/tests/test_script_entry.py b/tests/test_script_entry.py index c499b2a..20e70b5 100644 --- a/tests/test_script_entry.py +++ b/tests/test_script_entry.py @@ -14,6 +14,7 @@ "scripts/bench_control_validation.py", "scripts/encode_prompt.py", "scripts/verify_image.py", # its --help must work without mflux (mflux loads inside the sides) + "scripts/prove_api_watchdog.py", # its --help must work without MLX or mflux (they load in run_unit) ] diff --git a/tests/test_verify_image.py b/tests/test_verify_image.py index 22ffcae..2cc8df2 100644 --- a/tests/test_verify_image.py +++ b/tests/test_verify_image.py @@ -1214,3 +1214,43 @@ def test_the_krea2_bf16_side_gives_stock_mfluxs_latents_on_a_tiny_checkpoint( assert np.array_equal(np.array(ours.view(mx.uint32)), np.array(theirs.view(mx.uint32))) (decoded,) = ours_vae.seen # the VAE decodes the side's own final latents assert np.array_equal(np.array(decoded.view(mx.uint32)), np.array(ours.view(mx.uint32))) + + +DF11_SIDES = [ + pytest.param("run_df11", "mlx_dfloat.mflux.flux1.model", "DFloatFlux1", id="flux1"), + pytest.param("run_df11_zimage", "mlx_dfloat.mflux.zimage.model", "DFloatZImage", id="zimage"), + pytest.param("run_df11_flux2", "mlx_dfloat.mflux.flux2.model", "DFloatFlux2Klein", id="flux2"), + pytest.param( + "run_df11_qwen21", "mlx_dfloat.mflux.qwen21.model", "DFloatQwenImage21", id="qwen21" + ), + pytest.param("run_df11_ernie", "mlx_dfloat.mflux.ernie.model", "DFloatErnieImage", id="ernie"), + pytest.param("run_df11_krea2", "mlx_dfloat.mflux.krea2.model", "DFloatKrea2", id="krea2"), +] + + +class _BuiltError(Exception): + """Raised by the fake model factory once it has recorded the constructor's arguments.""" + + +@pytest.mark.mflux # the runners import mflux's latent creators +@pytest.mark.parametrize(("runner", "module", "name"), DF11_SIDES) +def test_every_df11_side_builds_its_model_unwatched(runner, module, name, tmp_path, monkeypatch): + # Bug caught: a df11 runner that drops watchdog=None, so the model's own default watchdog (a stop line at RAM + # minus 5 GiB) runs inside the side's footprint watchdog and raises where the side should run to its own limit. + import argparse + import importlib + + seen = {} + + def factory(*args, **kwargs): + seen.update(kwargs) + raise _BuiltError + + monkeypatch.setattr(importlib.import_module(module), name, factory) + args = argparse.Namespace(out=tmp_path, model="m", df11="d", base="b", eval_policy="per-block") + + with pytest.raises(_BuiltError): + getattr(vi, runner)(args, object()) + + assert "watchdog" in seen + assert seen["watchdog"] is None diff --git a/tests/test_watchconfig.py b/tests/test_watchconfig.py new file mode 100644 index 0000000..af02bef --- /dev/null +++ b/tests/test_watchconfig.py @@ -0,0 +1,119 @@ +import dataclasses +from pathlib import Path + +import pytest + +from mlx_dfloat.errors import DFloatUnsupportedError +from mlx_dfloat.mflux._watchconfig import DEFAULT_WATCHDOG, WatchdogConfig, check_watchdog_arg + + +def test_defaults(): + # Bug caught: a default changed from the documented one (a 1 GiB stop margin, a 10 s grace, no ceiling, no + # wall budget, no artifact folder), e.g. stop_margin written as 1_000_000_000 or grace as 1.0. + config = WatchdogConfig() + assert config.ceiling is None + assert config.stop_margin == 1_073_741_824 + assert config.grace == 10.0 + assert config.wall_budget is None + assert config.artifact_dir is None + + +def test_the_default_watchdog_is_the_default_config(): + # Bug caught: DEFAULT_WATCHDOG built with non-default arguments, so the constructor default differs from + # WatchdogConfig(). + assert WatchdogConfig() == DEFAULT_WATCHDOG + + +def test_the_config_has_exactly_the_documented_fields(): + # Bug caught: a field added, dropped or renamed. + names = [f.name for f in dataclasses.fields(WatchdogConfig)] + assert names == ["ceiling", "stop_margin", "grace", "wall_budget", "artifact_dir"] + + +def test_the_config_is_frozen(): + # Bug caught: a mutable config, so one model reassigning a field changes the shared DEFAULT_WATCHDOG for + # every other model. + with pytest.raises(dataclasses.FrozenInstanceError): + DEFAULT_WATCHDOG.grace = 1.0 # type: ignore[misc] + + +def test_the_config_is_keyword_only(): + # Bug caught: kw_only dropped, so WatchdogConfig(5) silently sets the ceiling to 5 bytes. + with pytest.raises(TypeError): + WatchdogConfig(5) # type: ignore[misc] + + +@pytest.mark.parametrize( + ("kwargs", "field"), + [ + ({"ceiling": 0}, "ceiling"), + ({"stop_margin": -1}, "stop_margin"), + ({"stop_margin": 0}, "stop_margin"), + ({"ceiling": 10, "stop_margin": 10}, "stop_margin"), + ({"grace": 0}, "grace"), + ({"wall_budget": 0}, "wall_budget"), + ], +) +def test_each_invalid_value_is_refused_by_name(kwargs, field): + # Bug caught: a missing check (the value is accepted), a check off by one (`<` for `<=`), or an error that + # names a different field than the one at fault. + with pytest.raises(DFloatUnsupportedError, match=rf"^WatchdogConfig\.{field} "): + WatchdogConfig(**kwargs) + + +def test_a_margin_one_below_the_ceiling_passes(): + # Bug caught: `stop_margin > ceiling` flipped to `>=` one step further (`stop_margin + 1 >= ceiling`), refusing + # the boundary that leaves one byte of room. + config = WatchdogConfig(ceiling=10, stop_margin=9) + assert config.ceiling == 10 + assert config.stop_margin == 9 + + +def test_the_smallest_valid_values_pass(): + # Bug caught: `stop_margin <= 0` written as `<= 1`, or `ceiling <= 0` as `<= 2`, refusing the lowest valid value. + config = WatchdogConfig(ceiling=2, stop_margin=1, grace=0.001, wall_budget=0.001) + assert config.ceiling == 2 + assert config.stop_margin == 1 + + +def test_check_watchdog_arg_passes_none_and_a_config_through_unchanged(): + # Bug caught: the check replaces None with the default config, or copies the caller's config, so a model + # built with watchdog=None is armed anyway or the identity of the given config is lost. + config = WatchdogConfig(grace=2.0) + assert check_watchdog_arg(None) is None + assert check_watchdog_arg(config) is config + + +@pytest.mark.parametrize("value", [False, True, {"grace": 1.0}, 0, "off"]) +def test_check_watchdog_arg_refuses_anything_else_naming_none(value): + # Bug caught: a falsy check (`if not value: return None`) lets watchdog=False through as "no watchdog", or a + # truthy one lets True or a dict through; the message must point at watchdog=None as the way to turn it off. + with pytest.raises(DFloatUnsupportedError, match=r"watchdog=None"): + check_watchdog_arg(value) + + +class _Folder: + """A path-like that is not a ``Path``.""" + + def __init__(self, path): + self._path = path + + def __fspath__(self): + return self._path + + +@pytest.mark.parametrize("folder", ["/x/records", _Folder("/x/records")]) +def test_a_str_or_path_like_folder_becomes_a_path(folder): + # Bug caught: a str folder stored as given, so the watchdog's `out_dir / name` join raises TypeError at the first + # trip and the call runs on unwatched. + config = WatchdogConfig(artifact_dir=folder) + assert type(config.artifact_dir) is not str + assert config.artifact_dir == Path("/x/records") + + +@pytest.mark.parametrize("folder", [5, b"/x/records", _Folder(b"/x/records")]) +def test_a_folder_that_is_not_a_str_or_path_is_refused(folder): + # Bug caught: any value accepted as the folder (an int, bytes), failing later inside the sampler instead of at + # construction; or bytes from __fspath__ turned into a Path of the repr. + with pytest.raises(DFloatUnsupportedError, match=r"^WatchdogConfig\.artifact_dir "): + WatchdogConfig(artifact_dir=folder) diff --git a/tests/test_watchdog.py b/tests/test_watchdog.py index 9835eb3..48648e4 100644 --- a/tests/test_watchdog.py +++ b/tests/test_watchdog.py @@ -1,10 +1,12 @@ import builtins import json +import stat import sys import threading import psutil import pytest +from tests._fake_counters import FakeCounters import mlx_dfloat._watchdog as wd from mlx_dfloat._watchdog import Watchdog, verdict, watched_memory @@ -440,6 +442,121 @@ def test_reset_peak_takes_the_lock(tmp_path): assert watchdog.peak_footprint == 0 +class _ExitRecorder: + """Stands in for the process exit: records each code and lets a test wait for the first.""" + + def __init__(self): + self.codes: list[int] = [] + self.fired = threading.Event() + + def __call__(self, code): + self.codes.append(code) + self.fired.set() + + +def test_injected_counters_decide_the_abort(tmp_path): + # Bug caught: _sample still reading the real counters (the verdict would carry this + # process's real footprint, not 5), or the injected exit not being the one called. + record = _ExitRecorder() + fake = FakeCounters(footprint=5, mlx_active=1, mlx_cache=1) + watchdog = Watchdog( + tmp_path, ceiling=4, budget=1e9, interval=0.01, counters=fake, exit_process=record + ).start() + try: + assert record.fired.wait(timeout=5) + finally: + watchdog.stop() + assert record.codes == [70] + artifact = json.loads((tmp_path / "abort.json").read_text()) + assert artifact["verdict_counter"] == "footprint" + assert artifact["verdict_memory"] == 5 + + +def test_exit_mode_artifact_keys_are_unchanged(tmp_path): + # Bug caught: a raise-mode key ("mode", "stop_line", "escalation", ...) leaking into the + # command's abort.json, or a key of today's artifact dropped. + record = _ExitRecorder() + watchdog = Watchdog( + tmp_path, + ceiling=4, + budget=1e9, + interval=0.01, + counters=FakeCounters(footprint=5), + exit_process=record, + ).start() + try: + assert record.fired.wait(timeout=5) + finally: + watchdog.stop() + assert set(json.loads((tmp_path / "abort.json").read_text())) == { + "reason", + "footprint", + "peak_footprint", + "ceiling", + "elapsed", + "budget", + "rss", + "mlx_active", + "mlx_cache", + "verdict_memory", + "verdict_counter", + "peak_watched", + "peak_mlx", + } + + +def test_the_exit_alias_is_looked_up_at_fire_time(tmp_path, monkeypatch): + # Bug caught: the default exit bound when the watchdog is built (`exit_process or _exit` in + # __init__), so tests that patch `wd._exit` afterwards stop reaching it. The alias in place + # at construction is itself a recorder, so that bug lands there instead of in os._exit. + at_construction = _ExitRecorder() + at_fire = _ExitRecorder() + monkeypatch.setattr(wd, "_exit", at_construction) + watchdog = Watchdog( + tmp_path, ceiling=4, budget=1e9, interval=0.01, counters=FakeCounters(footprint=5) + ) + monkeypatch.setattr(wd, "_exit", at_fire) + watchdog.start() + try: + assert at_fire.fired.wait(timeout=5) + finally: + watchdog.stop() + assert (at_fire.codes, at_construction.codes) == ([70], []) + + +def test_artifact_name_is_honoured(tmp_path): + # Bug caught: the file name still hard-coded as abort.json. + record = _ExitRecorder() + watchdog = Watchdog( + tmp_path, + ceiling=4, + budget=1e9, + interval=0.01, + counters=FakeCounters(footprint=5), + exit_process=record, + artifact_name="x.json", + ).start() + try: + assert record.fired.wait(timeout=5) + finally: + watchdog.stop() + assert sorted(p.name for p in tmp_path.iterdir()) == ["x.json"] + assert json.loads((tmp_path / "x.json").read_text())["reason"] == "memory" + + +def test_the_sampler_thread_is_named(tmp_path): + # Bug caught: an anonymous "Thread-N", which the API's "no watchdog thread left" check + # cannot find by name. + watchdog = Watchdog( + tmp_path, ceiling=10**15, budget=1e9, interval=3600, counters=FakeCounters() + ).start() + try: + names = {t.name for t in threading.enumerate()} + finally: + watchdog.stop() + assert "mlx-dfloat-watchdog" in names + + def test_the_sampler_updates_the_peaks_under_the_lock(tmp_path, monkeypatch): # Bug caught: _sample updating the peaks without the lock (the race reset_peak's lock guards). monkeypatch.setattr(wd, "phys_footprint", lambda: 7) @@ -447,3 +564,30 @@ def test_the_sampler_updates_the_peaks_under_the_lock(tmp_path, monkeypatch): watchdog = Watchdog(tmp_path, ceiling=10**15, budget=1e9) assert _blocked_while_locked(watchdog, watchdog._sample) == (False, True) assert (watchdog.peak_footprint, watchdog.peak_mlx, watchdog.peak_watched) == (7, 5, 7) + + +def test_exit_mode_replaces_a_symlink_at_the_record_name_and_writes_it_private(tmp_path): + # Bug caught: the record written through `path.write_text`, which follows a symlink planted at the record name + # and truncates its target, and leaves the record readable by every local user (0644). + target = tmp_path / "target.txt" + target.write_text("keep") + (tmp_path / "abort.json").symlink_to(target) + record = _ExitRecorder() + watchdog = Watchdog( + tmp_path, + ceiling=4, + budget=1e9, + interval=0.01, + counters=FakeCounters(footprint=5), + exit_process=record, + ).start() + try: + assert record.fired.wait(timeout=5) + finally: + watchdog.stop() + written = tmp_path / "abort.json" + assert not written.is_symlink() + assert json.loads(written.read_text())["reason"] == "memory" + assert target.read_text() == "keep" + assert stat.S_IMODE(written.stat().st_mode) == 0o600 + assert sorted(p.name for p in tmp_path.iterdir()) == ["abort.json", "target.txt"] diff --git a/tests/test_watchdog_raise.py b/tests/test_watchdog_raise.py new file mode 100644 index 0000000..d99c2a4 --- /dev/null +++ b/tests/test_watchdog_raise.py @@ -0,0 +1,472 @@ +"""The watchdog's raise mode: a cooperative trip at the stop line, a hard exit at the ceiling or past grace. + +Every watchdog here samples an injected ``FakeCounters`` and ends the "process" through a recorder, +so no test reads the real allocator or can end pytest. Waits poll an event with a 5 s timeout; the +only fixed waits are the "nothing happened within N s" checks. +""" + +import json +import stat +import threading +import time + +import pytest +from tests._fake_counters import FakeCounters + +from mlx_dfloat._watchdog import Counters, Watchdog + +PREFIX = "mlx-dfloat: the memory watchdog ended the process" + + +class _ExitRecorder: + """Stands in for the process exit: records each code and lets a test wait for the first.""" + + def __init__(self): + self.codes: list[int] = [] + self.fired = threading.Event() + + def __call__(self, code): + self.codes.append(code) + self.fired.set() + + +@pytest.fixture +def arm(tmp_path): + """Start a raise-mode watchdog (ceiling 10_000, stop margin 1_000, so a stop line of 9_000). + + Every watchdog started here is stopped at teardown, so none can escalate into a later test. + """ + started = [] + + def _arm( + fake, *, out_dir=None, ceiling=10_000, stop_margin=1_000, grace=10.0, budget=1e9, **kw + ): + record = _ExitRecorder() + watchdog = Watchdog( + tmp_path if out_dir is None else out_dir, + ceiling=ceiling, + budget=budget, + interval=0.01, + counters=fake, + exit_process=record, + mode="raise", + stop_margin=stop_margin, + grace=grace, + **kw, + ) + started.append(watchdog) + return watchdog.start(), record + + yield _arm + for watchdog in started: + watchdog.stop() + + +def _at(watched): + fake = FakeCounters() + fake.raise_to(watched) + return fake + + +def _refuse(constant): + raise ValueError(f"not strict JSON: {constant}") + + +def test_raise_mode_trip_writes_the_record_and_does_not_exit(arm, tmp_path): + # Bug caught: _fire still exiting in raise mode, or the trip not writing the record. + watchdog, record = arm(_at(9_001)) + assert watchdog.tripped.wait(timeout=5) + assert not record.fired.wait(timeout=0.3) + assert watchdog.trip["mode"] == "raise" + assert watchdog.trip["stop_line"] == 9_000 + assert watchdog.trip["reason"] == "memory" + assert watchdog.trip["escalation"] is None + assert watchdog.artifact == tmp_path / "abort.json" + assert json.loads(watchdog.artifact.read_text())["stop_line"] == 9_000 + + +def test_a_trip_below_the_stop_line_does_not_fire(arm): + # Bug caught: `>=` in place of `>` at the stop line (9_000 would trip). + fake = _at(9_000) + watchdog, _ = arm(fake) + assert not watchdog.tripped.wait(timeout=0.3) + fake.raise_to(9_001) + assert watchdog.tripped.wait(timeout=5) + + +def test_reaching_the_ceiling_after_a_trip_exits_70(arm, tmp_path): + # Bug caught: no ceiling check after the trip, `>` in place of `>=` at the ceiling, or a + # sampler that keeps escalating (`[70, 70, ...]`) instead of ending. + fake = _at(9_001) + watchdog, record = arm(fake) + assert watchdog.tripped.wait(timeout=5) + fake.raise_to(10_000) + assert record.fired.wait(timeout=5) + watchdog._thread.join(timeout=5) + assert record.codes == [70] + assert json.loads((tmp_path / "abort.json").read_text())["escalation"] == "ceiling" + + +class _Breakable(FakeCounters): + """``FakeCounters`` whose reads start raising once ``broken`` is set: a sampler that dies mid-run.""" + + def __init__(self): + super().__init__() + self.broken = False + + def __call__(self): + if self.broken: + raise OSError("rusage") + return super().__call__() + + +def _broken(): + raise OSError("rusage") + + +def test_a_memory_trip_below_the_ceiling_never_exits_by_grace(arm): + # Bug caught: the grace clock applied to a memory trip, so a stretch with no checkpoint longer + # than grace (a prompt encode, a VAE decode) ends the process below the ceiling. + watchdog, record = arm(_at(9_500), grace=0.2) + assert watchdog.tripped.wait(timeout=5) + assert not record.fired.wait(timeout=1.0) + watchdog.consume() + assert record.codes == [] + assert watchdog.trip["escalation"] is None + + +def test_an_unconsumed_wall_trip_exits_after_grace(arm, tmp_path): + # Bug caught: the grace clock dropped for wall trips too, so a wall trip no checkpoint takes + # runs on unbounded below the ceiling. + watchdog, record = arm(_at(0), budget=0.05, grace=0.2) + assert record.fired.wait(timeout=5) + watchdog._thread.join(timeout=5) + assert record.codes == [71] + assert json.loads((tmp_path / "abort.json").read_text())["escalation"] == "grace" + + +def test_a_sample_error_trip_exits_after_grace(arm, tmp_path): + # Bug caught: no grace for a trip whose samples carry no number, so a dead sampler leaves the + # job unwatched for good. + watchdog, record = arm(_broken, grace=0.2) + assert record.fired.wait(timeout=5) + watchdog._thread.join(timeout=5) + assert record.codes == [70] + assert json.loads((tmp_path / "abort.json").read_text())["escalation"] == "grace" + + +def test_a_failed_sample_after_a_memory_trip_starts_the_grace_clock(arm, tmp_path): + # Bug caught: grace decided by the trip's reason alone, so a sampler that dies after a memory + # trip leaves the job unwatched (no number for the ceiling, no grace). + fake = _Breakable() + fake.raise_to(9_500) + watchdog, record = arm(fake, grace=0.2) + assert watchdog.tripped.wait(timeout=5) + assert not record.fired.wait(timeout=0.5) + fake.broken = True + assert record.fired.wait(timeout=5) + watchdog._thread.join(timeout=5) + assert record.codes == [70] + on_disk = json.loads((tmp_path / "abort.json").read_text()) + assert (on_disk["reason"], on_disk["escalation"]) == ("memory", "grace") + + +def test_after_a_memory_trip_the_grace_clock_starts_at_the_first_failed_sample(arm, tmp_path): + # Bug caught: the clock counted from the memory trip, so a sampler that dies long after a trip + # with live samples ends the process on its first failed sample, with no grace at all. + fake = _Breakable() + fake.raise_to(9_500) + watchdog, record = arm(fake, grace=0.3) + assert watchdog.tripped.wait(timeout=5) + assert not record.fired.wait(timeout=0.5) # the trip is now older than grace + broke_at = time.monotonic() + fake.broken = True + assert not record.fired.wait(timeout=0.15) + assert record.fired.wait(timeout=5) + assert time.monotonic() - broke_at >= 0.3 + watchdog._thread.join(timeout=5) + assert record.codes == [70] + on_disk = json.loads((tmp_path / "abort.json").read_text()) + assert (on_disk["reason"], on_disk["escalation"]) == ("memory", "grace") + + +def test_a_recovered_sampler_resets_the_grace_clock_after_a_memory_trip(arm): + # Bug caught: the failed-sample clock kept running across a recovery, so a second short outage + # ends the process at once, counted from the first outage. + fake = _Breakable() + fake.raise_to(9_500) + watchdog, record = arm(fake, grace=0.5) + assert watchdog.tripped.wait(timeout=5) + fake.broken = True + assert not record.fired.wait(timeout=0.2) + fake.broken = False + assert not record.fired.wait(timeout=0.4) + fake.broken = True + assert not record.fired.wait(timeout=0.25) + assert record.fired.wait(timeout=5) + watchdog._thread.join(timeout=5) + assert record.codes == [70] + + +def test_a_sample_error_trip_whose_sampler_recovers_has_no_grace(arm): + # Bug caught: grace decided by the trip's reason alone, so a sample-error trip whose sampler + # comes back below the ceiling still ends the process by grace. + fake = _Breakable() + fake.broken = True + watchdog, record = arm(fake, grace=1.0) + assert watchdog.tripped.wait(timeout=5) + fake.raise_to(9_500) + fake.broken = False + assert not record.fired.wait(timeout=1.5) + assert watchdog.trip["reason"] == "sample_error" + assert record.codes == [] + + +def test_consume_stops_the_grace_clock(arm): + # Bug caught: consume() not stopping the clock, so cleanup after the error is cut off by a + # hard exit; or the latency never recorded. A wall trip, the kind grace still ends. + watchdog, record = arm(_at(0), budget=0.05, grace=1.0) + assert watchdog.tripped.wait(timeout=5) + watchdog.consume() + assert not record.fired.wait(timeout=1.5) + assert watchdog.trip["checkpoint_latency_s"] >= 0 + + +def test_consume_does_not_stop_the_ceiling_check(arm): + # Bug caught: consume() also turning off the hard line, so cleanup could run past the ceiling. + fake = _at(9_500) + watchdog, record = arm(fake) + assert watchdog.tripped.wait(timeout=5) + watchdog.consume() + fake.raise_to(10_000) + assert record.fired.wait(timeout=5) + assert record.codes == [70] + + +def test_stop_after_a_trip_never_exits(arm): + # Bug caught: the sampler outliving stop(), so a caller that already raised and cleaned up is + # ended later by the backstop. + fake = _at(9_001) + watchdog, record = arm(fake) + assert watchdog.tripped.wait(timeout=5) + watchdog.stop() + fake.raise_to(10_000) + assert not record.fired.wait(timeout=0.3) + + +def test_wall_trip_in_raise_mode_escalates_with_71(arm): + # Bug caught: the wall escalation exiting 70, which reads as a memory abort. + watchdog, record = arm(_at(0), budget=0.05, grace=0.2) + assert record.fired.wait(timeout=5) + assert record.codes == [71] + assert watchdog.trip["reason"] == "wall" + + +def test_a_wall_trip_that_reaches_the_ceiling_exits_70(arm, tmp_path): + # Bug caught: the exit code taken from the trip's reason instead of what ended the process, + # so a wall trip that later reaches the ceiling exits 71 and tells the user it was the clock + # when memory ended it. + fake = _at(0) + watchdog, record = arm(fake, budget=0.05) + assert watchdog.tripped.wait(timeout=5) + fake.raise_to(10_000) + assert record.fired.wait(timeout=5) + assert record.codes == [70] + assert json.loads((tmp_path / "abort.json").read_text())["escalation"] == "ceiling" + + +def _blocked_while_locked(watchdog, action): + """Run ``action`` on another thread while the test holds the watchdog's lock. + + Returns whether it finished while the lock was held, and whether it finished after release. + """ + done = threading.Event() + with watchdog._lock: + worker = threading.Thread(target=lambda: (action(), done.set())) + worker.start() + finished_while_locked = done.wait(timeout=0.2) + finished_after = done.wait(timeout=5) + worker.join(timeout=5) + return finished_while_locked, finished_after + + +def test_set_ceiling_tightens_and_returns_the_previous(arm): + # Bug caught: set_ceiling not reaching the sampler (a stop line fixed at construction), not + # returning the old value, or writing the ceiling outside the lock. + fake = _at(0) + watchdog, _ = arm(fake) + assert watchdog.set_ceiling(5_000) == 10_000 + assert _blocked_while_locked(watchdog, lambda: watchdog.set_ceiling(6_000)) == (False, True) + assert watchdog.set_ceiling(5_000) == 6_000 + fake.raise_to(4_001) + assert watchdog.tripped.wait(timeout=5) + assert (watchdog.trip["ceiling"], watchdog.trip["stop_line"]) == (5_000, 4_000) + + +def test_unwritable_artifact_dir_still_raises_with_artifact_none(arm, tmp_path): + # Bug caught: the write failure killing the sampler thread (no trip, nothing watched). + blocked = tmp_path / "blocked" + blocked.write_text("a regular file") + watchdog, record = arm(_at(9_001), out_dir=blocked / "out") + assert watchdog.tripped.wait(timeout=5) + assert watchdog.artifact is None + assert "artifact_error" in watchdog.trip + assert not record.fired.wait(timeout=0.3) + + +def test_no_wall_budget_records_null_and_parses_as_strict_json(arm): + # Bug caught: None turned into float("inf"), which json.dumps writes as `Infinity`. + watchdog, _ = arm(_at(9_001), budget=None) + assert watchdog.tripped.wait(timeout=5) + record = json.loads(watchdog.artifact.read_text(), parse_constant=_refuse) + assert record["budget"] is None + + +def test_the_escalation_line_names_the_record_on_stderr(arm, tmp_path, capfd): + # Bug caught: a hard exit with nothing on stderr, so the user cannot find the record. + fake = _at(9_001) + watchdog, record = arm(fake, live_context={"phase": lambda: "vae"}) + assert watchdog.tripped.wait(timeout=5) + fake.raise_to(10_000) + assert record.fired.wait(timeout=5) + err = capfd.readouterr().err + assert f"{PREFIX} (memory, phase vae); record: {tmp_path / 'abort.json'}" in err.splitlines() + + +def test_the_escalation_line_carries_the_record_when_the_write_failed(arm, tmp_path, capfd): + # Bug caught: a line pointing at a file that does not exist, leaving no record anywhere. + blocked = tmp_path / "blocked" + blocked.write_text("a regular file") + fake = _at(9_001) + watchdog, record = arm(fake, out_dir=blocked / "out") + assert watchdog.tripped.wait(timeout=5) + fake.raise_to(10_000) + assert record.fired.wait(timeout=5) + (line,) = [x for x in capfd.readouterr().err.splitlines() if x.startswith(PREFIX)] + assert "record not written" in line + carried = json.loads(line[line.index("{") :]) + assert (carried["escalation"], carried["stop_line"]) == ("ceiling", 9_000) + + +def test_a_sample_error_trip_escalates_only_by_grace(arm): + # Bug caught: the ceiling compare run on a sample with no number (None >= ceiling raises in + # the sampler thread), or a sample error escalating at once instead of after grace. + watchdog, record = arm(_broken) + assert watchdog.tripped.wait(timeout=5) + assert watchdog.trip["reason"] == "sample_error" + assert not record.fired.wait(timeout=0.3) + + +def test_a_wall_trip_ended_at_the_ceiling_names_memory_on_stderr(arm, tmp_path, capfd): + # Bug caught: the line naming only the trip's reason ("wall") while the process exits 70 because memory reached + # the ceiling, so the user reads a clock stop where memory ended the run. + fake = _at(0) + watchdog, record = arm(fake, budget=0.05, live_context={"phase": lambda: "denoise"}) + assert watchdog.tripped.wait(timeout=5) + fake.raise_to(10_000) + assert record.fired.wait(timeout=5) + assert record.codes == [70] + err = capfd.readouterr().err + line = f"{PREFIX} (memory ceiling after a wall trip, phase denoise); record: {tmp_path / 'abort.json'}" + assert line in err.splitlines() + + +def _boom(*_args): + raise RuntimeError("the trip failed") + + +def test_a_trip_that_raises_on_failing_samples_ends_70_after_grace(arm, tmp_path): + # Bug caught: an exception inside the raise-mode loop kills the sampler thread, so a call whose samples fail runs + # unwatched: no trip for a checkpoint to raise, and no exit however long it runs. + fake = _Breakable() + watchdog, record = arm(fake, grace=1.0) + watchdog._trip = _boom + fake.broken = True + assert watchdog.tripped.wait(timeout=5) + latched_at = time.monotonic() + assert not record.fired.wait(timeout=0.5) + assert record.fired.wait(timeout=5) + assert time.monotonic() - latched_at >= 0.9 + watchdog._thread.join(timeout=5) + assert record.codes == [70] + on_disk = json.loads((tmp_path / "abort.json").read_text()) + assert (on_disk["reason"], on_disk["escalation"]) == ("sample_error", "grace") + + +def test_a_trip_that_raises_on_a_live_sample_still_trips_and_ends_at_the_ceiling(arm): + # Bug caught: the same dead sampler with live readings: the call passes the stop line and then the ceiling with + # no checkpoint error and no exit (the probe returned normally at 29 GiB against a 28 GiB ceiling). + fake = _at(0) + watchdog, record = arm(fake) + watchdog._trip = _boom + fake.raise_to(9_500) + assert watchdog.tripped.wait(timeout=5) + assert not record.fired.wait(timeout=0.3) + fake.raise_to(10_000) + assert record.fired.wait(timeout=5) + watchdog._thread.join(timeout=5) + assert record.codes == [70] + + +def test_a_sample_in_flight_when_stop_returns_writes_no_record(arm, tmp_path): + # Bug caught: _trip not checking the stop flag under the lock, so a reading taken before stop() lands a trip and + # a record after the caller stopped the watchdog and already owns the outcome. + entered, release = threading.Event(), threading.Event() + + def reader(): + entered.set() + release.wait(timeout=10) + return Counters(footprint=9_500, rss=0, mlx_active=0, mlx_cache=0) + + watchdog, record = arm(reader) + assert entered.wait(timeout=5) + watchdog.stop() # the sampler is blocked in the read: stop() returns after its join times out + release.set() + watchdog._thread.join(timeout=5) + assert not watchdog._thread.is_alive() + assert not watchdog.tripped.is_set() + assert watchdog.trip is None + assert list(tmp_path.iterdir()) == [] + assert record.codes == [] + + +def _plant_symlink(at, target): + """Put a symlink to ``target`` at ``at``, replacing whatever file is there.""" + planted = at.with_name(at.name + ".planted") + planted.symlink_to(target) + planted.replace(at) + + +def test_the_trip_record_replaces_a_planted_symlink_and_is_private(arm, tmp_path): + # Bug caught: the first write follows a symlink at the record name and truncates its target, or leaves the + # record 0644, or leaves the temp file behind next to it. + target = tmp_path / "target.txt" + target.write_text("keep") + (tmp_path / "abort.json").symlink_to(target) + watchdog, _ = arm(_at(9_001)) + assert watchdog.tripped.wait(timeout=5) + written = tmp_path / "abort.json" + assert not written.is_symlink() + assert json.loads(written.read_text())["stop_line"] == 9_000 + assert target.read_text() == "keep" + assert stat.S_IMODE(written.stat().st_mode) == 0o600 + assert sorted(p.name for p in tmp_path.iterdir()) == ["abort.json", "target.txt"] + + +def test_the_escalation_rewrite_replaces_a_symlink_planted_after_the_trip(arm, tmp_path): + # Bug caught: the rewrite at the ceiling follows a symlink swapped in after the first write (a local user who owns + # the folder) and truncates its target. + fake = _at(9_001) + watchdog, record = arm(fake) + assert watchdog.tripped.wait(timeout=5) + target = tmp_path / "target.txt" + target.write_text("keep") + _plant_symlink(tmp_path / "abort.json", target) + fake.raise_to(10_000) + assert record.fired.wait(timeout=5) + watchdog._thread.join(timeout=5) + written = tmp_path / "abort.json" + assert not written.is_symlink() + assert json.loads(written.read_text())["escalation"] == "ceiling" + assert target.read_text() == "keep" + assert stat.S_IMODE(written.stat().st_mode) == 0o600