openaccel-lab
aien-dev/openaccel-lab
Brought by drakestapleton
openaccel-lab / oal / manifest.py
| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | """Workload manifests: load workloads/<name>/workload.json and evaluate its shape and tolerance |
| 3 | expressions against the case parameters. Expressions are integer/float arithmetic over parameter |
| 4 | names plus gamma(n) and u (unit roundoff 2^-24); nothing else is evaluated. |
| 5 | |
| 6 | INTERIM host glue (Python). Successor: an Omega manifest reader once seeded Omega has the JSON |
| 7 | reader of seed/json/ wired into a program-mode library. |
| 8 | """ |
| 9 | import ast |
| 10 | import json |
| 11 | import math |
| 12 | import os |
| 13 | |
| 14 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 15 | DTYPES = {"f32": ("float32", 4), "f64": ("float64", 8), "i32": ("int32", 4), "i8": ("int8", 1), |
| 16 | "u8": ("uint8", 1)} |
| 17 | U32 = 2.0 ** -24 # unit roundoff of binary32, round to nearest |
| 18 | |
| 19 | |
| 20 | def gamma(n): |
| 21 | """gamma_n = n u / (1 - n u), the classic bound on n roundings (Higham, ASNA 2nd ed. 3.1).""" |
| 22 | n = float(n) |
| 23 | if n * U32 >= 1.0: |
| 24 | raise ValueError("gamma(%g) undefined: n u >= 1" % n) |
| 25 | return n * U32 / (1.0 - n * U32) |
| 26 | |
| 27 | |
| 28 | _FUNCS = {"gamma": gamma, "max": max, "min": min, "log2": math.log2, "ceil": math.ceil} |
| 29 | _OPS = (ast.Expression, ast.BinOp, ast.UnaryOp, ast.Add, ast.Sub, ast.Mult, ast.Div, ast.FloorDiv, |
| 30 | ast.Mod, ast.Pow, ast.USub, ast.UAdd, ast.Constant, ast.Name, ast.Load, ast.Call) |
| 31 | |
| 32 | |
| 33 | def evaluate(expr, params): |
| 34 | """Evaluate a shape or tolerance expression. Numbers pass through unchanged.""" |
| 35 | if isinstance(expr, (int, float)): |
| 36 | return expr |
| 37 | tree = ast.parse(str(expr), mode="eval") |
| 38 | for node in ast.walk(tree): |
| 39 | if not isinstance(node, _OPS): |
| 40 | raise ValueError("manifest expression %r: %s not allowed" % (expr, type(node).__name__)) |
| 41 | if isinstance(node, ast.Call) and not (isinstance(node.func, ast.Name) and node.func.id in _FUNCS): |
| 42 | raise ValueError("manifest expression %r: unknown function" % expr) |
| 43 | env = dict(_FUNCS) |
| 44 | env["u"] = U32 |
| 45 | env.update(params) |
| 46 | return eval(compile(tree, "<manifest>", "eval"), {"__builtins__": {}}, env) |
| 47 | |
| 48 | |
| 49 | def shape(spec, params): |
| 50 | dims = [int(evaluate(d, params)) for d in spec["shape"]] |
| 51 | if any(d < 1 for d in dims): |
| 52 | raise ValueError("%s: non-positive dimension %s" % (spec["name"], dims)) |
| 53 | return dims |
| 54 | |
| 55 | |
| 56 | def nbytes(spec, params): |
| 57 | n = 1 |
| 58 | for d in shape(spec, params): |
| 59 | n *= d |
| 60 | return n * DTYPES[spec["dtype"]][1] |
| 61 | |
| 62 | |
| 63 | def workload_dir(name): |
| 64 | for top in ("workloads", "controls"): |
| 65 | d = os.path.join(ROOT, top, name) |
| 66 | if os.path.isfile(os.path.join(d, "workload.json")): |
| 67 | return d |
| 68 | raise FileNotFoundError("no workload %r under workloads/ or controls/" % name) |
| 69 | |
| 70 | |
| 71 | def load(name): |
| 72 | d = workload_dir(name) |
| 73 | with open(os.path.join(d, "workload.json")) as f: |
| 74 | m = json.load(f) |
| 75 | if m.get("name") != name: |
| 76 | raise ValueError("%s/workload.json names %r" % (d, m.get("name"))) |
| 77 | m["_dir"] = d |
| 78 | m["_control"] = os.path.basename(os.path.dirname(d)) == "controls" |
| 79 | for key in ("params", "inputs", "outputs", "tolerance", "timing", "backends"): |
| 80 | if key not in m: |
| 81 | raise ValueError("%s: missing %r" % (name, key)) |
| 82 | for t in m["inputs"] + m["outputs"]: |
| 83 | if t["dtype"] not in DTYPES: |
| 84 | raise ValueError("%s: tensor %s has dtype %s" % (name, t["name"], t["dtype"])) |
| 85 | for o in m["outputs"]: |
| 86 | if o["name"] not in m["tolerance"]: |
| 87 | raise ValueError("%s: output %s has no tolerance contract" % (name, o["name"])) |
| 88 | return m |
| 89 | |
| 90 | |
| 91 | def all_names(include_controls=False): |
| 92 | tops = ["workloads"] + (["controls"] if include_controls else []) |
| 93 | names = [] |
| 94 | for top in tops: |
| 95 | base = os.path.join(ROOT, top) |
| 96 | if not os.path.isdir(base): |
| 97 | continue |
| 98 | for n in sorted(os.listdir(base)): |
| 99 | if os.path.isfile(os.path.join(base, n, "workload.json")): |
| 100 | names.append(n) |
| 101 | return names |
| 102 | |
| 103 | |
| 104 | def params_of(m, overrides=None): |
| 105 | p = dict(m["params"]) |
| 106 | for k, v in (overrides or {}).items(): |
| 107 | if k not in p: |
| 108 | raise ValueError("%s has no parameter %r" % (m["name"], k)) |
| 109 | p[k] = int(v) |
| 110 | for k, expr in m.get("derived", {}).items(): |
| 111 | p[k] = int(evaluate(expr, p)) |
| 112 | return p |