"""Guarded, reversible, opt-in interception layer. Levels of integration (all off by default unless LPU_ENABLED=1 set by lpu-run): LEVEL 1 - bootstrap (lpu-run only): PYTHONPATH gains a bootstrap dir containing sitecustomize.py which (a) CHAINS to any pre-existing sitecustomize first (never shadows user tooling), (b) when LPU_ENABLED=1, applies the safe environment (cudnn flags etc.) and starts a session channel. This level never changes program behavior beyond documented torch global flags. LEVEL 2 - interception (LPU_INTERCEPT=1, or config integration.interception): Temporarily wraps torch.Tensor.backward / Optimizer.step / Optimizer.zero_grad / DataLoader.__init__ to provide AMP scaling, OOM recovery, and dataloader advisory application for STANDARD training loops (model(x); loss.backward(); optimizer.step()). Non-standard loops are detected (multiple backwards per step, GradScaler already in use) and interception auto-disables itself, logging why. unsafe_injection=true is REFUSED outright: no config value can force the dangerous path. Every patch is stored with its original; teardown restores bit-identical callables; atexit guarantees restoration even on normal exit. Interception FAILS OPEN: any exception during install or a patched call re-routes to the original untouched function. """ from __future__ import annotations import atexit import os import sys import threading from pathlib import Path from typing import Any, Dict, Optional from ..compat import optional_import from ..monitoring.logger import get_logger from ..ipc import SessionChannel from . import pytorch_adapter from .project_detector import classify_cmdline BOOTSTRAP_MARKER = "LPU_BOOTSTRAPED" def bootstrap_dir() -> Path: """Directory holding our sitecustomize; layout: /_bootstrap/.""" return Path(__file__).resolve().parent.parent / "_bootstrap" def install_bootstrap_marker() -> None: os.environ[BOOTSTRAP_MARKER] = "1" def bootstrap_already_done() -> bool: return os.environ.get(BOOTSTRAP_MARKER) == "1" def run_bootstrap() -> Optional[Any]: """Called from _bootstrap/sitecustomize.py inside the target process. Returns the created session handle (for in-process reporting) or None. """ if bootstrap_already_done(): return None install_bootstrap_marker() if os.environ.get("LPU_ENABLED") != "1": return None from ..config import load_config config = load_config(os.environ.get("LPU_CONFIG_PATH")) log = get_logger("bootstrap", log_dir=None, console=False) # explicit refusal of the unsafe path (cannot be enabled at all) if config.get("integration.unsafe_injection", False): log.warning( "integration.unsafe_injection=true is REFUSED by LPU. " "No code injection beyond the documented guarded hooks will occur." ) applied = pytorch_adapter.apply_environment(config, log) channel = SessionChannel() info = classify_cmdline(sys.argv) channel.write_descriptor({ "kind": "launched_project", "pid": os.getpid(), "python": sys.executable, "argv": sys.argv, "classified": info.summary(), "settings_applied": [k for k in applied.get("restorable", {})], }) channel.write_status({"state": "running", "bootstrap": "level1"}) state = {"applied": applied, "channel": channel, "config": config, "log": log} if os.environ.get("LPU_INTERCEPT") == "1" and config.get( "integration.interception", False ): interceptor = TorchInterceptor(state) if interceptor.install(): state["interceptor"] = interceptor def _teardown(): try: pytorch_adapter.restore_environment(applied, log) channel.write_status({"state": "finished"}) channel.archive() except Exception: # noqa: BLE001 pass atexit.register(_teardown) return state class TorchInterceptor: """Reversible wrapper around the torch training-loop primitives. PATCH SEMANTICS (critical): the callables assigned onto torch classes must be PLAIN FUNCTIONS, never bound methods of this object. Bound methods are not descriptors, so `loss.backward()` would fail to pass `loss` as the first argument. Plain functions ARE descriptors and receive the calling instance correctly. """ def __init__(self, state: dict): self.state = state self.log = state["log"] self.channel: SessionChannel = state["channel"] self.config = state["config"] self._orig: Dict[str, Any] = {} self._patched: Dict[str, Any] = {} # exact objects assigned self._installed = False self._backward_depth = 0 self._warned_nonstandard = False self._scaler = None self._amp_active = False # -- install / restore ----------------------------------------------------- def install(self) -> bool: torch = optional_import("torch") if torch is None: self.log.info("interceptor: no torch; nothing to do") return False try: self._orig = { "backward": torch.Tensor.backward, "step": torch.optim.Optimizer.step, "zero_grad": torch.optim.Optimizer.zero_grad, "dataloader_init": torch.utils.data.DataLoader.__init__, } except AttributeError as exc: self.log.warning("interceptor: torch API mismatch (%s); not installed", exc) return False try: self._patched = { "backward": _make_backward(self), "step": _make_step(self), "zero_grad": self._orig["zero_grad"], # unchanged (semantics note) "dataloader_init": _make_dataloader_init(self), } torch.Tensor.backward = self._patched["backward"] torch.optim.Optimizer.step = self._patched["step"] torch.utils.data.DataLoader.__init__ = self._patched["dataloader_init"] except Exception as exc: # noqa: BLE001 self.log.warning("interceptor install failed (%s); restoring", exc) self.uninstall() return False self._installed = True self.log.info( "interceptor installed (backward/step/DataLoader; zero_grad untouched " "to preserve torch<2 default semantics)" ) atexit.register(self.uninstall) return True def uninstall(self) -> bool: torch = optional_import("torch") if torch is None or not self._orig: return False restored = [] try: if torch.Tensor.backward is self._patched.get("backward"): torch.Tensor.backward = self._orig["backward"] restored.append("backward") if torch.optim.Optimizer.step is self._patched.get("step"): torch.optim.Optimizer.step = self._orig["step"] restored.append("step") if torch.utils.data.DataLoader.__init__ is self._patched.get("dataloader_init"): torch.utils.data.DataLoader.__init__ = self._orig["dataloader_init"] restored.append("DataLoader.__init__") except Exception as exc: # noqa: BLE001 self.log.error("interceptor restore error: %s", exc) self._installed = False try: # atexit may run after streams close - never crash teardown self.log.info("interceptor restored: %s", restored) except Exception: # noqa: BLE001 pass return len(restored) == 3 # -- helpers used by the closures ------------------------------------------- def detect_nonstandard(self) -> bool: if self._backward_depth > 1: if not self._warned_nonstandard: self._warned_nonstandard = True self.log.warning( "interceptor: multiple backward calls per step detected - " "non-standard loop; disabling AMP interception (fail-open)" ) self._amp_active = False return True return False def _make_backward(ic: "TorchInterceptor"): def backward(tensor, *args, **kwargs): original = ic._orig["backward"] try: ic._backward_depth += 1 use_amp = ( ic._amp_active and ic._scaler is not None and getattr(tensor, "requires_grad", False) and getattr(tensor, "is_cuda", False) and not ic.detect_nonstandard() ) if use_amp: scaled = ic._scaler.scale(tensor) return original(scaled, *args, **kwargs) return original(tensor, *args, **kwargs) except Exception: # noqa: BLE001 - fail open to the original path return original(tensor, *args, **kwargs) finally: ic._backward_depth -= 1 return backward def _make_step(ic: "TorchInterceptor"): def step(optimizer, *args, **kwargs): original = ic._orig["step"] try: if ic._amp_active and ic._scaler is not None: try: ic._scaler.step(optimizer) ic._scaler.update() return None except Exception: # noqa: BLE001 ic._amp_active = False ic.log.warning( "interceptor: scaler.step failed; falling back to plain step" ) return original(optimizer, *args, **kwargs) except Exception: # noqa: BLE001 return original(optimizer, *args, **kwargs) return step def _make_dataloader_init(ic: "TorchInterceptor"): def dataloader_init(loader_self, dataset, *args, **kwargs): original = ic._orig["dataloader_init"] torch = optional_import("torch") try: from ..training import dataloader_optimizer as dlo stats = dlo.DataLoaderStats( num_workers=kwargs.get("num_workers", 0) or 0, pin_memory=bool(kwargs.get("pin_memory", False)), persistent_workers=bool(kwargs.get("persistent_workers", False)), prefetch_factor=kwargs.get("prefetch_factor", None), batch_size=kwargs.get("batch_size", None), dataset_len=len(dataset) if hasattr(dataset, "__len__") else None, ) has_cuda = torch is not None and torch.cuda.is_available() recs = dlo.recommend( stats, has_cuda, ic.config.get("training.dataloader_max_workers", 8), ) apply_on = ic.config.get( "training.dataloader_apply_recommendations", False ) new_kwargs, changelog = dlo.apply_to_kwargs(kwargs, stats, recs, apply_on) if changelog: ic.log.info("DataLoader advisory applied: %s", changelog) ic.channel.append_metrics( {"kind": "dataloader_change", "changes": changelog} ) return original(loader_self, dataset, *args, **new_kwargs) except Exception as exc: # noqa: BLE001 - fail open ic.log.warning("dataloader wrapper failed (%s); original path", exc) return original(loader_self, dataset, *args, **kwargs) return dataloader_init