#!/usr/bin/env python3 """Execute predicted CadQuery programs into meshes, one throwaway process each. Split out of infer_cadrille_geomcad.py because running these in the generation loop kept killing the job. OCCT does not hand memory back between programs, and a predicted sweep is routinely a few hundred spline segments whose tessellation allocates gigabytes, so a long split climbs until the OOM killer takes it with the GPU work half finished. maxtasksperchild=1 gives every program a fresh interpreter, which makes accumulation impossible rather than merely slower, and an address-space cap turns a pathological solid into one failed sample instead of a dead machine. Spawn cost is milliseconds against a 30 second timeout. Idempotent: a directory that already holds a mesh is skipped, so this can be run against a split that is still being generated, and again when it finishes. python exec_preds.py --pred preds_geomcad20k/sweep --workers 8 """ from __future__ import annotations import argparse import multiprocessing as mp import os import resource import signal from pathlib import Path EXEC_TIMEOUT = 30 # Per-child address space. Comfortably above any legitimate tessellation here # and far below what it takes to disturb the machine. MEM_LIMIT_GB = 8 class _Timeout(Exception): pass def _alarm(signum, frame): raise _Timeout() def _init(): lim = MEM_LIMIT_GB * 1024 ** 3 try: resource.setrlimit(resource.RLIMIT_AS, (lim, lim)) except (ValueError, OSError): pass for v in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"): os.environ.setdefault(v, "1") def run_one(args) -> bool: py, stl = args signal.signal(signal.SIGALRM, _alarm) signal.alarm(EXEC_TIMEOUT) try: import cadquery as cq import trimesh ns = {} exec(Path(py).read_text(errors="ignore"), {"cq": cq}, ns) vertices, faces = ns["r"].val().tessellate(0.001, 0.1) trimesh.Trimesh([(v.x, v.y, v.z) for v in vertices], faces).export(str(stl)) return True except BaseException: # MemoryError from the rlimit and _Timeout from the alarm both land here, # and both mean the same thing downstream: this prediction has no mesh. return False finally: try: signal.alarm(0) except BaseException: pass def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--pred", required=True, help="directory of /.txt") ap.add_argument("--workers", type=int, default=4) ap.add_argument("--redo", action="store_true", help="rebuild meshes that exist") args = ap.parse_args() root = Path(args.pred) jobs, skipped = [], 0 for d in sorted(root.iterdir(), key=lambda p: (len(p.name), p.name)): if not d.is_dir(): continue sid = d.name py = d / f"{sid}.txt" stl = d / f"{sid}.stl" if not py.is_file(): continue if stl.is_file() and not args.redo: skipped += 1 continue jobs.append((str(py), str(stl))) print(f"{root.name}: {len(jobs)} to execute, {skipped} already have a mesh", flush=True) if not jobs: return ok = 0 ctx = mp.get_context("spawn") with ctx.Pool(args.workers, initializer=_init, maxtasksperchild=1) as pool: for n, good in enumerate(pool.imap_unordered(run_one, jobs, chunksize=1), 1): ok += good if n % 100 == 0 or n == len(jobs): print(f" {n}/{len(jobs)} executed {ok}", flush=True) total = ok + skipped print(f"{root.name}: {ok}/{len(jobs)} newly executed, {total} meshes present") if __name__ == "__main__": main()