File size: 3,766 Bytes
5805ce8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/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 <id>/<id>.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()