Source code for pytc.solver.bug_helper

"""Small device, memory and timing tools shared by the BUG solvers.

Nothing here is numerical: device residency of the DF factors (cached upload,
aux-chunk streaming), counted host<->device transfers, memory probes and a
device-synchronised clock.
"""
from __future__ import annotations

import os
import tempfile
import time
from contextlib import contextmanager

import jax
import jax.numpy as jnp
import numpy as np

# DF factors larger than this stay on the host and are streamed by aux
# chunks of about AUX_CHUNK_BYTES.
RESIDENT_LIMIT_BYTES = 24e9
AUX_CHUNK_BYTES = 6e9


[docs] def clock() -> float: """Wall clock after the device queue drains. JAX dispatch is asynchronous, so without this a kernel's device time is charged to whichever later timer first waits on a result. """ (jnp.zeros(()) + 1).block_until_ready() return time.perf_counter()
[docs] @contextmanager def timed(timings, name): start = clock() yield if timings is not None: timings[name] = timings.get(name, 0.0) + clock() - start
# -------------------------------------------------------------------------- # DF factors and their device residency # -------------------------------------------------------------------------- _ON_DEVICE: dict = {}
[docs] def on_device(x): """Device copy of a static host array, uploaded once per solve. Keyed by ``id``; the entry keeps the host array alive so the id stays unique. Arrays above ``RESIDENT_LIMIT_BYTES`` stay on the host. """ if isinstance(x, jax.Array) or x.nbytes > RESIDENT_LIMIT_BYTES: return x hit = _ON_DEVICE.get(id(x)) if hit is None or hit[0] is not x: hit = (x, jnp.asarray(x)) _ON_DEVICE[id(x)] = hit return hit[1]
_HOST_CHUNKS: dict = {}
[docs] def _aux_major(a): """Aux-major (naux, ...) copy of a static host array, made once per solve. Slicing the last axis of a C-ordered (p, q, naux) array is a strided copy, several times slower than the upload it feeds; B_vv is re-streamed many times per iteration once it exceeds RESIDENT_LIMIT_BYTES. In aux-major order every chunk width is a contiguous view, so all consumers share one copy instead of holding one copy per width. """ hit = _HOST_CHUNKS.get(id(a)) if hit is None or hit[0] is not a: hit = (a, np.ascontiguousarray(np.moveaxis(a, -1, 0))) _HOST_CHUNKS[id(a)] = hit return hit[1]
[docs] def release_device_copies(): _ON_DEVICE.clear() _HOST_CHUNKS.clear()
[docs] def aux_streamed(call, *aux_arrays, static=None): """``call(*aux_arrays)`` for a call that is a single sum over the aux index. Arrays that fit stay device-resident; if any does not, the aux axis (last) is walked in chunks and the outputs are summed. ``static`` flags the arrays that live for the whole solve (the DF factors) and may be cached by ``on_device``; per-state arrays are uploaded without caching. """ static = (True,) * len(aux_arrays) if static is None else static resident = [on_device(a) if keep else (jnp.asarray(a) if a.nbytes <= RESIDENT_LIMIT_BYTES else a) for a, keep in zip(aux_arrays, static)] if all(isinstance(a, jax.Array) for a in resident): return call(*resident) naux = aux_arrays[0].shape[-1] per_aux = sum(a.nbytes for a in aux_arrays) / naux step = max(1, int(AUX_CHUNK_BYTES // per_aux)) major = [_aux_major(a) if keep and not isinstance(a, jax.Array) else None for a, keep in zip(resident, static)] total = None for q0 in range(0, naux, step): chunk = [a[..., q0:q0 + step] if isinstance(a, jax.Array) else jnp.moveaxis(jnp.asarray(m[q0:q0 + step]), 0, -1) if m is not None else jnp.asarray(np.ascontiguousarray(a[..., q0:q0 + step])) for a, m in zip(resident, major)] out = call(*chunk) total = out if total is None else jax.tree_util.tree_map( lambda x, y: x + y, total, out) return total
[docs] def device_memory_stats() -> dict | None: """Allocator statistics of the first device, or ``None`` where none exist.""" try: stats = jax.local_devices()[0].memory_stats() except (AttributeError, IndexError, KeyError, RuntimeError, TypeError): return None return dict(stats) if stats else None
[docs] def _live_bytes() -> int | None: """Device ``bytes_in_use``, or ``None`` where no statistics exist.""" v = (device_memory_stats() or {}).get('bytes_in_use') return None if v is None else int(v)
[docs] def arena_bytes() -> int: """Device allocator limit, or 0 when the backend reports none.""" return int((device_memory_stats() or {}).get("bytes_limit") or 0)
#: Synchronous host<->device transfer accounting. These transfers are NOT #: overlapped with compute -- there is no double buffering and the copies are #: pageable -- so the totals below are a true serial cost and must never be #: presented as evidence of hiding transfer behind compute. _XFER = {"put_s": 0.0, "put_bytes": 0, "get_s": 0.0, "get_bytes": 0, "put_calls": 0, "get_calls": 0}
[docs] def reset_transfer_counters() -> None: for k in _XFER: _XFER[k] = 0.0 if k.endswith("_s") else 0
[docs] def transfer_counters() -> dict: """Measured synchronous transfer cost since the last reset.""" return dict(_XFER)
[docs] def put_counted(a): """device_put, timed and counted.""" arr = np.asarray(a) t0 = time.perf_counter() d = jax.device_put(arr) d.block_until_ready() _XFER["put_s"] += time.perf_counter() - t0 _XFER["put_bytes"] += int(arr.nbytes) _XFER["put_calls"] += 1 return d
[docs] def get_counted(a): """device_get, timed and counted -- AFTER the producer has finished. Several callers pass a fresh asynchronous GEMM output. Timing `device_get` on such a value measures the kernel wait plus the copy, so `get_s` absorbs real compute and `compute_s = iteration_s - transfer_s` subtracts it twice. Synchronise first: the wait stays inside the enclosing phase wall, where it belongs, and only the D->H copy is charged to transfer. """ if hasattr(a, "block_until_ready"): a.block_until_ready() t0 = time.perf_counter() h = np.asarray(jax.device_get(a)) _XFER["get_s"] += time.perf_counter() - t0 _XFER["get_bytes"] += int(h.nbytes) _XFER["get_calls"] += 1 return h
[docs] def host_memory_limits() -> tuple[int, dict[str, int | None]]: """Every observable host-memory ceiling, and the binding one. Returns ``(binding, sources)``. ``binding`` is the **minimum finite** limit across all sources, not the first one that parses: cgroup, Slurm and physical RAM can disagree, and when they do the smallest is the only one that will actually be enforced. Taking the first parsable source makes stale or misaligned environment metadata dangerous; taking the minimum makes it merely conservative. ``MemTotal`` is the machine's, not ours -- a job is killed at its own limit, not at the node's -- so it participates like any other candidate rather than being trusted as the answer. ``sources`` records every observation for the receipt, so a later reader can see which limit was binding and which were merely present. """ src: dict[str, int | None] = {} def _cgroup(path: str) -> int | None: try: raw = open(path).read().strip() except OSError: return None if not raw or raw == "max": return None try: v = int(raw) except ValueError: return None # cgroup v1 reports an absurd sentinel when unlimited return v if 0 < v < (1 << 62) else None src["cgroup_v2"] = _cgroup("/sys/fs/cgroup/memory.max") src["cgroup_v1"] = _cgroup("/sys/fs/cgroup/memory/memory.limit_in_bytes") def _int_env(name: str) -> int | None: raw = os.environ.get(name) if not raw: return None try: return int(raw) except ValueError: return None mem_node = _int_env("SLURM_MEM_PER_NODE") src["slurm_mem_per_node"] = mem_node * 1024 * 1024 if mem_node else None per_cpu, ncpu = _int_env("SLURM_MEM_PER_CPU"), _int_env("SLURM_CPUS_PER_TASK") src["slurm_mem_per_cpu_total"] = (per_cpu * ncpu * 1024 * 1024 if per_cpu and ncpu else None) try: src["physical"] = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") except (AttributeError, ValueError, OSError): src["physical"] = None finite = [v for v in src.values() if isinstance(v, int) and v > 0] return (min(finite) if finite else 0), src
[docs] def auto_block_rows(nov: int, rank_hint: int, itemsize: int = 8) -> int: """Largest row panel whose scratch stays a small fraction of the arena. Resolved once per solve: the panel is static to the compiled loop, so a width that tracked the running rank would recompile it every iteration. """ limit = arena_bytes() if limit <= 0: return int(min(nov, 8192)) budget = max(limit // 200, 1 << 24) rows = budget // max(rank_hint * itemsize, 1) return int(min(nov, max(256, 1 << (max(rows, 1).bit_length() - 1))))
[docs] def host_scratch_dir() -> str | None: """Directory for disk-backed pair-height buffers, from ``PYTC_HOST_SCRATCH``.""" return os.environ.get("PYTC_HOST_SCRATCH") or None
[docs] def host_empty(shape, dtype=np.float64): """A host buffer for a pair-height array (rows of length r or naux). With ``PYTC_HOST_SCRATCH`` unset this is ``np.empty``. Set, it is an ``np.memmap`` on a file in that directory (node-local NVMe), unlinked at once so the space goes when the array does. Every host-backed kernel reads and writes these arrays one row panel at a time, so the page cache holds only the panels in flight and RAM no longer scales with nov * r. """ shape = tuple(int(n) for n in shape) d = host_scratch_dir() if not d or int(np.prod(shape)) == 0: return np.empty(shape, dtype=dtype) fd, path = tempfile.mkstemp(dir=d, prefix="pytc_", suffix=".mm") try: # The map holds its own handle, so the file object can close at once. with os.fdopen(fd, "w+b") as f: return np.memmap(f, dtype=dtype, mode="w+", shape=shape) finally: os.unlink(path)
[docs] def put_rows(A, s, e): """Rows ``s:e`` of a host array on the device, zero-padded past its end.""" if e <= A.shape[0]: return put_counted(A[s:e]) out = np.zeros((e - s,) + A.shape[1:]) out[:max(0, A.shape[0] - s)] = A[s:] return put_counted(out)