File size: 3,048 Bytes
7f50cd1 | 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 | """Build an offline NBIPOP-aCMA-ES oracle policy for the declared box."""
import base64
import json
import math
import os
from pathlib import Path
import subprocess
import sys
import tempfile
def main():
here = Path(__file__).resolve().parent
data = json.loads((Path(sys.argv[1]) / "instance.json").read_text())
n = data["dimension"]
q = data["queries"]
lower, upper = float(data["lower"]), float(data["upper"])
if type(n) is not int or not 1 <= n <= 100:
raise ValueError("dimension must be between 1 and 100")
if type(q) is not int or q < 1:
raise ValueError("query limit must be positive")
if not (math.isfinite(lower) and math.isfinite(upper) and lower < upper
and math.isfinite(upper - lower)):
raise ValueError("finite ordered bounds are required")
initial_pop = 4 + int(3 * math.log(n))
# Nine increasing-population restarts, as in xacmes.m. Samples are
# regenerated from seeds, rather than storing O(lambda * dimension) arrays.
cap = max(initial_pop, min(q, initial_pop * 512))
hist = min(20000, q // initial_pop + 2)
# The exact source histories and population fit on all visible inputs.
# On much larger inputs, stop cleanly when a storage limit is reached.
# This is a resource limit, not a changed population or history parameter.
available = 1048576 - 65536 - 48 * n * n - 448 * n - 32768
hist = min(hist, max(2, available // 40 // 3))
cap = min(cap, max(initial_pop, (available - 24 * hist) // 60))
cache = max(1, min(cap, (available - 24 * hist - 60 * cap) // (16*n)))
out = Path(sys.argv[2])
out.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=out) as temporary:
tmp = Path(temporary)
config = tmp / "instance_config.h"
config.write_text(
f"#define DIM {n}\n#define POP_CAP {cap}\n#define HIST_CAP {hist}\n"
f"#define CACHE_CAP {cache}\n"
f"#define BOUND_LO ({lower.hex()})\n#define BOUND_HI ({upper.hex()})\n"
)
wasm = tmp / "program.wasm"
core = Path(os.environ["CORE_DIR"])
subprocess.run([
"clang", "--target=wasm32", "-O3", "-msimd128", "-nostdlib", "-fno-builtin",
"-fno-strict-aliasing", "-fwrapv", "-ffp-contract=off",
"-D__LITTLE_ENDIAN", "-include", str(config),
"-I", str(core / "interface"), str(here / "search.c"),
str(here / "vendor/fdlibm/e_log.c"),
str(here / "vendor/fdlibm/e_exp.c"),
"-o", str(wasm), "-Wl,--no-entry", "-Wl,--export=run",
"-Wl,--initial-memory=1048576", "-Wl,--max-memory=1048576",
"-Wl,-z,stack-size=65536",
], check=True)
blob = wasm.read_bytes()
if len(blob) > 262144:
raise ValueError("WASM module exceeds the task limit")
(out / "policy.json").write_text(json.dumps({
"wasm_base64": base64.b64encode(blob).decode("ascii")
}) + "\n")
if __name__ == "__main__":
main()
|