interplane.Get Omega
Read in your language

openaccel-lab

aien-dev/openaccel-lab

Brought by drakestapleton

branch main Branches Tags History

openaccel-lab / oal / case.py

144 lines · 5566 bytes Raw Blame History
1# SPDX-License-Identifier: Apache-2.0
2"""Deterministic inputs and the case container (docs/CONTAINER.md).
3
4Every input value is made from splitmix64 integers with IEEE basic operations only (+ - * /),
5never with a libm function, so two machines produce byte-identical inputs. The case sha256 is
6recorded with every result so the board can show that two runners ran the same bytes.
7
8INTERIM host glue (Python + numpy). Successor: oal-gen in seeded Omega (splitmix64 and the
9container writer need only integer words and write).
10"""
11import hashlib
12import struct
13
14import numpy as np
15
16from . import manifest
17
18MAGIC = b"OALCASE1"
19M64 = np.uint64(0xFFFFFFFFFFFFFFFF)
20
21
22def fnv1a64(text):
23 h = 0xCBF29CE484222325
24 for b in text.encode():
25 h = ((h ^ b) * 0x100000001B3) & 0xFFFFFFFFFFFFFFFF
26 return h
27
28
29def splitmix64(seed, count):
30 """count outputs of splitmix64 (Steele, Lea, Flood 2014) starting from state seed."""
31 with np.errstate(over="ignore"):
32 idx = np.arange(1, count + 1, dtype=np.uint64)
33 z = np.uint64(seed) + idx * np.uint64(0x9E3779B97F4A7C15)
34 z = (z ^ (z >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9)
35 z = (z ^ (z >> np.uint64(27))) * np.uint64(0x94D049BB133111EB)
36 return z ^ (z >> np.uint64(31))
37
38
39def unit24(bits):
40 """Top 24 bits as a float64 in [0, 1), exact."""
41 return (bits >> np.uint64(40)).astype(np.float64) * (2.0 ** -24)
42
43
44def generate(spec, count, stream_seed):
45 g = spec["gen"]
46 kind = g["kind"]
47 if kind == "uniform":
48 v = g["lo"] + (g["hi"] - g["lo"]) * unit24(splitmix64(stream_seed, count))
49 elif kind == "normal4":
50 # Irwin-Hall: sum of four U(0,1) minus 2, scaled to unit variance (var = 4/12).
51 b = splitmix64(stream_seed, 4 * count).reshape(count, 4)
52 s = unit24(b).sum(axis=1) - 2.0
53 v = g.get("mean", 0.0) + g.get("std", 1.0) * s * np.sqrt(3.0)
54 elif kind == "grid":
55 # integers k in [klo, khi] times 2^-shift: exactly representable in narrow formats.
56 span = np.uint64(g["khi"] - g["klo"] + 1)
57 k = (splitmix64(stream_seed, count) % span).astype(np.int64) + g["klo"]
58 v = k.astype(np.float64) * (2.0 ** -g["shift"])
59 elif kind == "int":
60 span = np.uint64(g["hi"] - g["lo"] + 1)
61 v = (splitmix64(stream_seed, count) % span).astype(np.int64) + g["lo"]
62 elif kind == "const":
63 v = np.full(count, g["value"], dtype=np.float64)
64 elif kind == "iota":
65 v = (np.arange(count, dtype=np.int64) % g.get("mod", count)).astype(np.float64)
66 else:
67 raise ValueError("unknown generator %r" % kind)
68 return v
69
70
71def inputs(m, params, seed):
72 """Dict name -> numpy array (manifest dtype and shape), in manifest order."""
73 out = {}
74 for spec in m["inputs"]:
75 dims = manifest.shape(spec, params)
76 count = int(np.prod(dims))
77 stream = (seed ^ fnv1a64(m["name"] + "/" + spec["name"])) & 0xFFFFFFFFFFFFFFFF
78 v = generate(spec, count, stream)
79 np_dtype = manifest.DTYPES[spec["dtype"]][0]
80 if spec["dtype"] in ("i32", "i8", "u8"):
81 arr = np.asarray(v).astype(np.int64)
82 info = np.iinfo(np_dtype)
83 if arr.min() < info.min or arr.max() > info.max:
84 raise ValueError("%s: generator leaves %s range" % (spec["name"], spec["dtype"]))
85 arr = arr.astype(np_dtype)
86 else:
87 arr = np.asarray(v, dtype=np.float64).astype(np_dtype)
88 out[spec["name"]] = arr.reshape(dims)
89 return out
90
91
92def pad8(n):
93 return (n + 7) // 8 * 8
94
95
96def pack(m, params, tensors, warmup, repeats):
97 """The container bytes: header, int64 params, tensor byte sizes, then padded input data."""
98 names = list(params)
99 head = MAGIC + struct.pack("<5Q", len(names), len(m["inputs"]), len(m["outputs"]), warmup, repeats)
100 head += struct.pack("<%dq" % len(names), *[int(params[k]) for k in names])
101 sizes = [manifest.nbytes(s, params) for s in m["inputs"] + m["outputs"]]
102 head += struct.pack("<%dQ" % len(sizes), *sizes)
103 body = b""
104 for spec in m["inputs"]:
105 raw = np.ascontiguousarray(tensors[spec["name"]]).tobytes()
106 body += raw + b"\0" * (pad8(len(raw)) - len(raw))
107 return head + body
108
109
110def unpack(blob):
111 """Inverse of pack for Python entrants: (params list, sizes list, inputs bytes list, warmup, repeats)."""
112 if blob[:8] != MAGIC:
113 raise ValueError("not an OALCASE1 container")
114 np_, nin, nout, warm, reps = struct.unpack_from("<5Q", blob, 8)
115 o = 48
116 params = list(struct.unpack_from("<%dq" % np_, blob, o))
117 o += 8 * np_
118 sizes = list(struct.unpack_from("<%dQ" % (nin + nout), blob, o))
119 o += 8 * (nin + nout)
120 ins = []
121 for k in range(nin):
122 ins.append(blob[o:o + sizes[k]])
123 o += pad8(sizes[k])
124 return params, sizes, ins, warm, reps
125
126
127def split_outputs(m, params, raw):
128 """Cut an entrant's stdout into named output arrays; raises on a short or long stream."""
129 out = {}
130 o = 0
131 for spec in m["outputs"]:
132 n = manifest.nbytes(spec, params)
133 if o + n > len(raw):
134 raise ValueError("output stream ends inside %s (%d of %d bytes)" % (spec["name"], len(raw) - o, n))
135 out[spec["name"]] = np.frombuffer(raw[o:o + n], dtype=manifest.DTYPES[spec["dtype"]][0]).reshape(
136 manifest.shape(spec, params))
137 o += pad8(n)
138 if o != len(raw):
139 raise ValueError("output stream has %d bytes, expected %d" % (len(raw), o))
140 return out
141
142
143def sha256(blob):
144 return hashlib.sha256(blob).hexdigest()