Algorithmresearch
Stochastic superoptimization
Also called STOKE.
Searches the space of instruction sequences by Markov chain Monte Carlo with a cost of correctness on tests plus speed.
- Time
- O(s L (n + I) + (L + I) L I) worst
- Space
- O(L + n + I) extra
- Where
- I = the number of possible inputs of the program; L = the number of instruction slots of a program; n = the number of initial tests; s = the number of steps of the chain
- Model
- Word RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Stochastic superoptimization, as in the STOKE tool of Schkufza, Sharma and Aiken, looks for a faster loop-free program that is equivalent to a given one by a random walk over programs. The walk is a Metropolis-Hastings chain. Its cost function adds two terms: how many output bits are wrong on a set of test inputs, and how slow the program is. Each step changes one random part of the current program and keeps the change with a probability that depends on how much the cost goes up. The chain can pass through wrong programs on its way to a right one, which lets it reach rewrites far from the start. A candidate that is right on all tests is not yet known to be right, so it must pass an equivalence check before it is accepted. When the check fails, the input it finds becomes a new test.
In plain words
We want a shorter piece of code that does exactly what a given piece does. There are far too many pieces of code to try them all, so we take a random walk. At each step we make one small random edit: change an operation, change a register, swap two lines, or replace or delete a line. We score each piece of code by how wrong it is on some sample inputs and by how long it is. A better score is always kept. A worse score is kept only sometimes, and less often the worse it is. This lets the walk climb out of dead ends. When we find code that is right on every sample and shorter than our best, we check it on every possible input. If it fails, the failing input joins the samples. Only checked code is ever returned.
The problem
Machine. A toy machine has registers r0 to r3 of bits. All arithmetic is modulo . The inputs start in r0 and r1, the other registers start at 0, and the output is r0 at the end. An instruction in toy IR form is rd = ra op rb with op one of + - & | ^ << >>, or a copy rd = ra. An operand is a register or the constant 1. A shift by or more gives 0. With there are 716 instructions and inputs.
Programs. A program has slots. Each slot holds an instruction or is unused. The length of a program is its number of used slots; here every instruction costs one cycle.
Task. Given a target program , find a program that gives the same output as on every input, with as small as possible. The target is loop-free, as in STOKE.
Cost. For a list of tests , each an input with the output of on it,
counts the wrong output bits, the Hamming distance to the right outputs. It is 0 exactly when is right on all tests. Counting bits, and not just right or wrong tests, gives the walk a slope to follow towards right programs.
Target distribution. For an inverse temperature , the chain is built to sample from
over all programs with slots. Cheap programs are likely, and a program with one more wrong bit or one more instruction is times less likely.
Moves. Each step picks one of four moves with probability each and a slot uniformly:
- opcode: if slot holds an operator instruction, replace the operator by another one, chosen uniformly;
- operand: pick an operand place of slot (the destination or a source) and replace it by another value, chosen uniformly;
- swap: pick a second slot uniformly and swap slots and ;
- instruction: make slot unused with probability , or else fill it with an instruction chosen uniformly from all instructions.
A move that does not apply leaves the program as it is. The first three moves are symmetric: the chance to propose from equals the chance to propose from . The instruction move is not, unless . With for an unused slot and for an instruction, its Hastings factor is
where and are the old and new contents of slot . For the three symmetric moves .
Acceptance. A proposal is accepted with probability
With symmetric proposals this is the Metropolis rule , which the STOKE paper uses. Hastings added the factor for proposals that are not symmetric. Without it, the chain does not sample from .
The algorithm
STOKE(T, tests, L, beta, steps)- 1
R <- T with unused slots added up to L slots; c <- cost(R) - 2
best <- T - 3
repeat steps times - 4
pick a move and propose R* from R; h <- its Hastings factor - 5
c* <- cost(R*) - 6
with probability min(1, h * exp(-beta (c* - c))) set R <- R* and c <- c* - 7
if eq(R; tests) = 0 and perf(R) < perf(best) then - 8
if R and T agree on every input then best <- R without its unused slots - 9
else add an input where R and T differ to tests; c <- cost(R) - 10
return best
L1 starts from the target, as in the optimization phase of STOKE. The synthesis phase starts from a random or empty program instead, and drops the performance term until it finds a right program. L8 is the equivalence check. Here it runs the two programs on all inputs. STOKE proves equivalence with an SMT solver over bit vectors, which also gives a counterexample when it fails. L9 is the same loop as counterexample-guided inductive synthesis: every wrong candidate that passed the tests makes the tests stronger.
Example
Target. x + y written with the identity , in four instructions:
r2 = r0 ^ r1
r3 = r0 & r1
r3 = r3 << 1
r0 = r2 + r3
The tests are the inputs , , and , with , , , , and random seed 1. In 50000 steps the run does this:
| step | event | program |
|---|---|---|
| 1120 | right on the 4 tests, refuted at input : it gives 2, the target gives 1 | r3 = 1 ^ r0; r2 = r0 ^ r1; r0 = r2 << r3 |
| 1535 | checked, accepted, 3 instructions | r0 = r1 + r0; r2 = r0 - 1; r2 = 1 - 1 |
| 2563 | checked, accepted, 2 instructions | r0 = r1 + r0; r3 = r2 - r3 |
| 30250 | checked, accepted, 1 instruction | r0 = r1 + r0 |
The refuted program is a good case of why the check is needed. It computes . On the four tests this happens to equal modulo 16: for the shift is by 6, which gives 0, and is also 0. It is wrong on 233 of the 256 inputs. After the check, is a fifth test, and the chain moves on. The two accepted programs of length 3 and 2 hold dead instructions, which the chain removes later. Massalin's search over all programs of length 0 and 1 confirms that one instruction is the least possible. With seeds 0 to 5, all six runs reach the one-instruction program within 50000 steps.
A second target. 2x + 2y as r2 = r0 + r0; r3 = r1 + r1; r0 = r2 + r3. Exhaustive search finds that the shortest equivalent program has 2 instructions, for example r0 = r0 + r1; r0 = r0 + r0. With , all six seeds 0 to 5 reach length 2 within 50000 steps, in forms like r0 = r0 + r1; r0 = r0 << 1. Three of the six runs first meet a candidate that is right on the tests but wrong at .
Tests are not proof. With only the tests and , the program r0 = r0 | r1 has , since and . The check finds , where it gives 1 and the target gives 2. It is wrong on 175 of the 256 inputs.
The temperature. There are 716 instructions and one unused value per slot. A move that deletes an instruction has Hastings factor , and it lowers the cost by 1. At it is accepted with probability ; at only with . In 50000 steps with , only one of six seeds reaches one instruction, against all six with .
The chain samples . On a machine with 1-bit registers, two registers, the operators ^ and &, and , there are programs, and can be computed exactly. With , and 200000 steps, the visit frequencies are at total variation distance 0.027 from . With the Hastings factor left out, the distance is 0.68: the chain spends most of its time on the empty program, because the unused slot is proposed half of the time.
Correctness
The full proofs are in proofs/correctness.md.
- Soundness. The returned program agrees with on every input.
beststarts as and changes only in L8, after the check on all inputs. Being right on all tests does not suffice, as the examples show. - The chain samples . With the tests fixed, each move with its acceptance rule satisfies detailed balance with respect to : for , . A mix of such moves, chosen independently of the state, keeps too. The chain is irreducible, since instruction moves turn any program into any other, and aperiodic, since a move can leave the program as it is. So it converges to from any start.
- Complete in the limit. L9 adds a new input each time, so the tests change at most times. After the last change the chain is a fixed irreducible chain on a finite set, so with probability 1 it visits a shortest equivalent program, which then passes L7 and L8. So with probability 1,
bestreaches the least length among programs of slots, but there is no bound on the time.
Proof: STOKE returns only equivalent programs, its chain samples exp(-beta cost), and it is complete in the limitfull
Setting. The machine, the programs of slots, the cost , the four moves and the acceptance rule are as on the page. is the finite set of programs with slots, and the finite set of inputs, with . STOKE is lines L1 to L10 of the page. We write when and give the same output on every input in .
Theorem 1: soundness
Claim. The program returned in L10 is equivalent to , whatever the tests, the seed and the number of steps.
Proof. Invariant: . L2 sets . The only other assignment is in L8, and it runs only when and agree on every input of ; dropping unused slots does not change the output, since an unused slot does nothing. L10 returns .
The test condition alone is not enough. L7 asks for , which only says that is right on the inputs of . If , there are programs right on and wrong elsewhere: the page gives r0 = r0 | r1, which is right on and for the target and wrong on , and a three-instruction program found by the chain that is right on four tests and wrong on 233 of the 256 inputs. So a version of STOKE that accepts in L7 without L8 is not sound.
Theorem 2: with fixed tests, the chain has stationary distribution and converges to it
Fix the tests. Lines L4 to L6 then define a Markov chain on with kernel , one kernel per move. Each proposes from with probability and accepts it with probability
Step 1: the Hastings factor of each move. We show that for with , the ratio is the factor that the implementation uses: 1 for the first three moves, and for the instruction move.
- Opcode. differs from in the operator of one slot . Both directions pick slot with probability and then the other operator with probability . No other slot gives the same change. So the two probabilities are equal.
- Operand. differs in one operand place of one slot , and the instruction kind is the same in and , so both directions have the same number of places and the same pool. Each direction has probability .
- Swap. is with slots swapped. Both directions choose the ordered pairs or , with total probability each.
- Instruction. differs from only in slot . From , the move picks slot with probability and then the new content with probability , where and . The reverse picks the old content with probability . So the ratio is .
Step 2: detailed balance for each move. Let , and write and . If both proposals are 0, both sides below are 0. Otherwise both are positive, by Step 1 (each move can be undone by the same kind of move). Since , we have and . Then
Step 3: the mixture. The move is chosen with probability each, independently of the state. So for . Summing detailed balance over gives : is stationary.
Step 4: convergence. The chain is irreducible: given and , the instruction moves that set slot to the content of each have positive proposal probability, and every acceptance probability is positive, because and . It is aperiodic: the instruction move that picks a slot and proposes its current content leaves the program unchanged, with positive probability. A finite irreducible aperiodic chain has a unique stationary distribution, and the distribution of its state converges to it from any start. So the chain converges to .
Without the Hastings factor. If the instruction move uses while , Step 2 fails for a pair that differs in one slot, one unused and one not, and is in general not stationary. The page measures this on a machine with 361 programs: with , the visit frequencies are at total variation distance 0.027 from with the factor and 0.68 without it.
Theorem 3: completeness in the limit
Let . The set is not empty if fits in slots, as L1 assumes.
Claim. If the chain runs forever, then with probability 1 there is a step after which .
Proof. Each time L9 runs, the program is right on all tests () and wrong on the input that L9 adds, so was not a test yet. So L9 runs at most times, and the tests change at most times. Let be the step of the last change, or 0 if none.
After step , the tests are fixed, so the chain moves by the fixed kernel of Theorem 2, which is irreducible on the finite set . An irreducible chain on a finite set visits every state infinitely often with probability 1, from any start. Formally: for each of the at most possible values of the test set, the chain after the time that set is reached is the chain of Theorem 2, and it hits every state with probability 1. A union over finitely many events of probability 0 has probability 0.
Pick with and . When the chain visits it after , because it is right on every input. If at that time, L7 holds, the check in L8 passes, and gets length . By Theorem 1, always, so its length is never below , and L7 only lets it go down.
What the theorem does not say. It gives no bound on the number of steps. The time to visit a given program can be exponential in , and in practice it depends on , and the cost landscape, as the experiments on the page show. A finite run is a heuristic search with a sound filter.
Complexity
The model is the word RAM with words of at least bits. A step costs for the move and for the cost, and since each new test is a new input. A check in L8 costs . A failed check adds a test, which happens at most times, and a passed check makes best shorter, which happens at most times. So steps take time and space. In practice stays close to : the example adds one test in 50000 steps. The number of steps needed to find a short program has no useful bound. On real x86-64 code, STOKE evaluates many millions of proposals.
Properties
- Sound. Only checked programs are returned. The soundness rests on the check, not on the search.
- Randomized and incomplete. A run of fixed length may miss the shortest program. Different seeds find different programs.
- Works on long programs. Exhaustive search by length tries programs of length , which is already at length 3 here. The chain only ever looks at one program and its neighbours, so it scales to targets of tens of instructions.
- Loop-free targets. The cost and the check are for straight-line code, as in STOKE.
Variants and improvements
- Better correctness terms. STOKE also counts a right value in the wrong register at a small extra cost, so that the chain can find it and move it. It adds penalties for faults and undefined behaviour.
- Real performance models. STOKE sums the latencies of the instructions as a fast estimate of the run time, in place of the instruction count used here, and measures the final candidates by running them.
- Floating point with tunable precision. Schkufza, Sharma and Aiken (PLDI 2014) allow a bounded error in floating-point results, which makes faster rewrites legal.
- Conditional correctness. Sharma, Schkufza, Churchill and Aiken (OOPSLA 2015) optimize code under conditions that hold where it is used.
- Mixed search. Phothilimthana and others split the program into windows and combine stochastic, enumerative and symbolic search, which finds better code than any one of them.
- Simulated annealing. Lowering over time, as in simulated annealing, trades sampling of for a faster descent.
When to use it
Use it to optimize a hot, loop-free kernel of tens of instructions where a few cycles matter, such as a cryptographic or numeric inner block, and where an equivalence checker for the instruction set exists. For very short sequences, an exhaustive superoptimizer is complete and fast enough. For whole programs, equality saturation or a peephole optimizer with known rules scales better.
Pitfalls
- Returning a program that only passed the tests. A rewrite found by testing needs a proof. The example finds a program that is right on the four tests and wrong on 233 of the 256 inputs. Always check, and keep the counterexample as a test.
- Leaving out the Hastings factor. With a fixed for unused slots, the plain Metropolis rule samples a different distribution. Either include or choose the proposals so that they are symmetric.
- A temperature that is too high. For small , the many long programs with dead code outweigh the few short ones, and the chain seldom shortens the program.
- A temperature that is too low. For large , the chain rarely accepts a worse program, and it gets stuck near the start like a local search.
- Checks for a model that is too small. A check over a toy machine, or over some inputs, says nothing about the real instruction set. STOKE checks with a bit-vector model of each x86-64 instruction, and the check is only as good as that model.
- Equivalence on outputs only. Here only
r0is compared. A real rewrite must also keep memory, flags and every other live register, or the check must state which of them are dead.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
"""Stochastic superoptimization (STOKE) on toy straight-line programs.
A machine has nregs registers of w bits. The inputs are in r0, r1, ...,
the other registers start at 0, and the output is r0 at the end. A program
is a list of L slots; a slot is None (unused) or an instruction in toy IR
form:
("op", d, op, a, b) rd = ra op rb, op one of + - & | ^ << >>
("copy", d, a) rd = ra
Registers are numbered 0 .. nregs-1, and an operand is a register number
or ("k", c) for a constant c. All arithmetic is modulo 2**w; a shift by w
or more gives 0.
search is the Metropolis-Hastings search of Schkufza, Sharma and Aiken:
the cost of a program is the number of wrong output bits on the tests
plus its number of instructions, moves change one random part of the
program, and a move is accepted with the Metropolis-Hastings rule. A
program that is right on all tests and shorter than the best so far is
checked on every input; if the check fails, an input where it differs
becomes a new test.
"""
import math
import random
from itertools import product
OPS = ("+", "-", "&", "|", "^", "<<", ">>")
class Machine:
"""The machine model: word size w, nregs registers, ninputs inputs,
the binary operators ops and the constants that may be operands."""
def __init__(self, w=4, nregs=4, ninputs=2, ops=OPS, consts=(1,)):
self.w = w
self.mask = (1 << w) - 1
self.nregs = nregs
self.ninputs = ninputs
self.ops = tuple(ops)
self.operands = list(range(nregs)) + [("k", c) for c in consts]
# Every instruction, for the instruction move.
self.instrs = [("op", d, op, a, b) for op in self.ops for d in range(nregs)
for a in self.operands for b in self.operands]
self.instrs += [("copy", d, a) for d in range(nregs) for a in self.operands if a != d]
def all_inputs(self):
return list(product(range(1 << self.w), repeat=self.ninputs))
def _val(regs, a):
return a[1] if isinstance(a, tuple) else regs[a]
def _apply(m, op, x, y):
if op == "+":
return (x + y) & m.mask
if op == "-":
return (x - y) & m.mask
if op == "&":
return x & y
if op == "|":
return x | y
if op == "^":
return x ^ y
if op == "<<":
return (x << y) & m.mask if y < m.w else 0
if op == ">>":
return x >> y if y < m.w else 0
raise ValueError("unknown operator %r" % (op,))
def run(m, prog, inputs):
"""The value of r0 after prog runs on the given inputs."""
regs = [0] * m.nregs
for i, x in enumerate(inputs):
regs[i] = x & m.mask
for ins in prog:
if ins is None:
continue
if ins[0] == "op":
regs[ins[1]] = _apply(m, ins[2], _val(regs, ins[3]), _val(regs, ins[4]))
else:
regs[ins[1]] = _val(regs, ins[2])
return regs[0]
def perf(prog):
"""The number of instructions that are used: every one costs one cycle."""
return sum(1 for ins in prog if ins is not None)
def eq(m, prog, tests):
"""The number of wrong bits of the output, over the tests. tests is a
list of (inputs, expected output)."""
return sum(bin(run(m, prog, x) ^ want).count("1") for x, want in tests)
def cost(m, prog, tests):
return eq(m, prog, tests) + perf(prog)
def counterexample(m, prog, target):
"""An input where prog and target differ, or None when they agree on
every input (an exhaustive check over all 2**(w*ninputs) inputs)."""
for x in m.all_inputs():
if run(m, prog, x) != run(m, target, x):
return x
return None
def acceptance(beta, c, c_new, hastings=1.0):
"""The Metropolis-Hastings acceptance probability of a move from a
program of cost c to one of cost c_new, where hastings is the ratio
q(new -> old) / q(old -> new) of the proposal probabilities."""
d = c_new - c
if d <= 0 and hastings >= 1:
return 1.0
return min(1.0, hastings * math.exp(-beta * d))
def propose(m, prog, rng, p_unused):
"""One random move. Returns (the new program, the move name, the
Hastings ratio q(new -> old) / q(old -> new) of this move)."""
L = len(prog)
new = list(prog)
kind = rng.choice(("opcode", "operand", "swap", "instruction"))
i = rng.randrange(L)
ins = prog[i]
if kind == "opcode":
# Another operator for a binary instruction: symmetric.
if ins is not None and ins[0] == "op":
op = rng.choice([o for o in m.ops if o != ins[2]])
new[i] = ("op", ins[1], op, ins[3], ins[4])
return new, kind, 1.0
if kind == "operand":
# Another value for one of the operand places: symmetric.
if ins is not None:
places = [1, 3, 4] if ins[0] == "op" else [1, 2]
k = rng.choice(places)
pool = list(range(m.nregs)) if k == 1 else m.operands
choice = rng.choice([v for v in pool if v != ins[k]])
cand = list(ins)
cand[k] = choice
cand = tuple(cand)
if cand[0] == "copy" and cand[1] == cand[2]:
return list(prog), kind, 1.0 # not an instruction of the set
new[i] = cand
return new, kind, 1.0
if kind == "swap":
j = rng.randrange(L)
new[i], new[j] = new[j], new[i]
return new, kind, 1.0
# Instruction move: unused with probability p_unused, otherwise a
# uniformly random instruction. The proposal is not symmetric, so the
# Hastings ratio is P(old slot) / P(new slot).
new[i] = None if rng.random() < p_unused else rng.choice(m.instrs)
def p(s):
return p_unused if s is None else (1 - p_unused) / len(m.instrs)
return new, kind, p(prog[i]) / p(new[i])
def mh_step(m, R, c, tests, beta, rng, p_unused, hastings=True):
"""One step of the chain from program R of cost c. With hastings=False
the proposal is treated as symmetric (plain Metropolis rule)."""
R2, _, h = propose(m, R, rng, p_unused) # @line L4
c2 = cost(m, R2, tests) # @line L5
if rng.random() < acceptance(beta, c, c2, h if hastings else 1.0): # @line L6
return R2, c2
return R, c
class Result:
def __init__(self, best, tests, accepted, verified, counterexamples, steps):
self.best = best # the shortest verified program found
self.tests = tests # the final test set
self.accepted = accepted # (step, program) for each verified improvement
self.verified = verified # number of exhaustive checks
self.counterexamples = counterexamples # (step, input added as a test, the program it refuted)
self.steps = steps
def search(m, target, tests, L, steps, beta=4.0, seed=0, p_unused=0.2, start=None):
"""STOKE: Metropolis-Hastings over programs of L slots.
target is the program to optimize and tests its initial test inputs.
The chain starts from start (default: target padded to L slots).
Returns a Result whose best program is equivalent to target on every
input.
"""
rng = random.Random(seed)
tests = [(tuple(x), run(m, target, x)) for x in tests]
pad = list(target) + [None] * (L - len(target))
R = list(start) if start is not None else pad
c = cost(m, R, tests) # @line L1
best, accepted, verified, cex = [ins for ins in target if ins is not None], [], 0, [] # @line L2
for step in range(1, steps + 1): # @line L3
R, c = mh_step(m, R, c, tests, beta, rng, p_unused)
if c == perf(R) and perf(R) < perf(best): # @line L7
verified += 1
x = counterexample(m, R, target)
if x is None:
best = [ins for ins in R if ins is not None] # @line L8
accepted.append((step, best))
else:
tests.append((x, run(m, target, x))) # @line L9
cex.append((step, x, [ins for ins in R if ins is not None]))
c = cost(m, R, tests)
return Result(best, tests, accepted, verified, cex, steps) # @line L10
def shortest_by_enumeration(m, target, max_len):
"""The shortest program equivalent to target, by trying all programs of
length 0, 1, 2, ... (Massalin's exhaustive search), or None."""
inputs = m.all_inputs()
want = [run(m, target, x) for x in inputs]
for n in range(max_len + 1):
for prog in product(m.instrs, repeat=n):
if all(run(m, prog, x) == y for x, y in zip(inputs, want)):
return list(prog)
return None
def _operand_text(a):
return str(a[1]) if isinstance(a, tuple) else "r%d" % a
def show(prog):
"""The program in toy IR text, one instruction per line."""
lines = []
for ins in prog:
if ins is None:
continue
if ins[0] == "op":
lines.append("r%d = %s %s %s" % (ins[1], _operand_text(ins[3]), ins[2], _operand_text(ins[4])))
else:
lines.append("r%d = %s" % (ins[1], _operand_text(ins[2])))
return "\n".join(lines)
test_stochastic_superoptimization.py 166 lines
# SPDX-License-Identifier: MIT
import math
import random
import unittest
from collections import Counter
from itertools import product
import stochastic_superoptimization as st
K = ("k", 1)
# x + y written with xor, and, a shift and an add: four instructions.
ADD4 = [("op", 2, "^", 0, 1), ("op", 3, "&", 0, 1), ("op", 3, "<<", 3, K), ("op", 0, "+", 2, 3)]
# 2x + 2y in three instructions; the shortest has two.
DOUBLE3 = [("op", 2, "+", 0, 0), ("op", 3, "+", 1, 1), ("op", 0, "+", 2, 3)]
# (x | y) - (x & y), which is x ^ y.
XOR3 = [("op", 2, "|", 0, 1), ("op", 3, "&", 0, 1), ("op", 0, "-", 2, 3)]
TESTS = [(0, 0), (1, 2), (3, 5), (7, 9)]
def reference_run(prog, x, y, w=4):
"""An independent 4-bit evaluator, written from the definition."""
mask = (1 << w) - 1
r = [x, y, 0, 0]
def val(a):
return a[1] if isinstance(a, tuple) else r[a]
for ins in prog:
if ins is None:
continue
if ins[0] == "copy":
r[ins[1]] = val(ins[2])
continue
a, b = val(ins[3]), val(ins[4])
r[ins[1]] = {
"+": (a + b) % (mask + 1),
"-": (a - b) % (mask + 1),
"&": a & b, "|": a | b, "^": a ^ b,
"<<": (a * 2 ** b) % (mask + 1) if b < w else 0,
">>": a // 2 ** b if b < w else 0,
}[ins[2]]
return r[0]
def equivalent(p, q):
return all(reference_run(p, x, y) == reference_run(q, x, y) for x in range(16) for y in range(16))
class SearchTest(unittest.TestCase):
def test_finds_the_known_shorter_program(self):
m = st.Machine()
r = st.search(m, ADD4, TESTS, L=4, steps=50000, seed=1)
self.assertEqual([st.perf(p) for _, p in r.accepted], [3, 2, 1])
self.assertEqual([s for s, _ in r.accepted], [1535, 2563, 30250])
self.assertEqual(st.show(r.best), "r0 = r1 + r0")
# Massalin's enumeration agrees that one instruction is the least.
self.assertEqual(st.shortest_by_enumeration(m, ADD4, 2), [("op", 0, "+", 0, 1)])
def test_every_accepted_rewrite_is_equivalent(self):
m = st.Machine()
count = 0
for target, L in ((ADD4, 4), (DOUBLE3, 3), (XOR3, 3)):
for seed in range(4):
r = st.search(m, target, TESTS, L=L, steps=15000, seed=seed)
self.assertTrue(equivalent(r.best, target))
for _, p in r.accepted:
self.assertTrue(equivalent(p, target), st.show(p))
count += 1
lengths = [st.perf(p) for _, p in r.accepted]
self.assertEqual(lengths, sorted(lengths, reverse=True))
self.assertEqual(len(set(lengths)), len(lengths))
self.assertGreater(count, 15)
def test_shortest_for_the_other_targets(self):
m = st.Machine()
self.assertEqual(len(st.shortest_by_enumeration(m, DOUBLE3, 2)), 2)
self.assertEqual(len(st.shortest_by_enumeration(m, XOR3, 2)), 1)
r = st.search(m, XOR3, TESTS, L=3, steps=20000, seed=0)
self.assertEqual(st.perf(r.best), 1)
class CheckTest(unittest.TestCase):
def test_tests_alone_are_not_enough(self):
m = st.Machine()
bad = [("op", 0, "|", 0, 1)]
few = [((0, 0), 0), ((1, 2), 3)]
self.assertEqual(st.eq(m, bad, few), 0)
self.assertEqual(st.counterexample(m, bad, ADD4), (1, 1))
self.assertFalse(equivalent(bad, ADD4))
def test_refuted_candidates_become_tests(self):
m = st.Machine()
r = st.search(m, ADD4, TESTS, L=4, steps=50000, seed=1)
self.assertEqual(r.verified, 4)
self.assertEqual(len(r.counterexamples), 1)
step, x, p = r.counterexamples[0]
self.assertEqual((step, x), (1120, (0, 1)))
self.assertEqual(st.show(p), "r3 = 1 ^ r0\nr2 = r0 ^ r1\nr0 = r2 << r3")
# It was right on the four tests, and wrong on the input it gave.
for t in TESTS:
self.assertEqual(reference_run(p, *t), reference_run(ADD4, *t))
self.assertEqual((reference_run(p, 0, 1), reference_run(ADD4, 0, 1)), (2, 1))
self.assertIn(((0, 1), 1), r.tests)
def test_counterexample_none_iff_equivalent(self):
m = st.Machine()
rng = random.Random(3)
agree = 0
for _ in range(300):
p = [rng.choice(m.instrs) for _ in range(rng.randint(1, 3))]
q = [rng.choice(m.instrs) for _ in range(rng.randint(1, 3))]
same = equivalent(p, q)
self.assertEqual(st.counterexample(m, p, q) is None, same)
agree += same
self.assertGreater(agree, 0)
class ChainTest(unittest.TestCase):
def test_acceptance_rule(self):
self.assertEqual(st.acceptance(4, 10, 9), 1.0)
self.assertEqual(st.acceptance(4, 10, 10), 1.0)
self.assertAlmostEqual(st.acceptance(4, 10, 11), math.exp(-4))
self.assertAlmostEqual(st.acceptance(4, 10, 12, 2.0), 2 * math.exp(-8))
self.assertAlmostEqual(st.acceptance(4, 10, 10, 0.5), 0.5)
self.assertEqual(st.acceptance(4, 10, 5, 0.5), 1.0)
def stationary_tv(self, hastings):
m = st.Machine(w=1, nregs=2, ninputs=1, ops=("^", "&"), consts=())
target = [("op", 0, "^", 0, 0)]
tests = [((x,), st.run(m, target, (x,))) for x in (0, 1)]
beta, L, n = 1.0, 2, 200000
states = list(product([None] + m.instrs, repeat=L))
weight = {s: math.exp(-beta * st.cost(m, list(s), tests)) for s in states}
z = sum(weight.values())
rng = random.Random(7)
R = [None] * L
c = st.cost(m, R, tests)
seen = Counter()
for _ in range(n):
R, c = st.mh_step(m, R, c, tests, beta, rng, 0.5, hastings=hastings)
seen[tuple(R)] += 1
return 0.5 * sum(abs(seen[s] / n - weight[s] / z) for s in states)
def test_chain_samples_exp_minus_beta_cost(self):
# 19 * 19 = 361 programs: the visit frequencies are close to
# exp(-beta cost) / Z with the Hastings factor, and far from it
# without, because the unused slot is proposed half of the time.
self.assertLess(self.stationary_tv(True), 0.05)
self.assertGreater(self.stationary_tv(False), 0.5)
def test_moves_keep_programs_valid(self):
m = st.Machine()
rng = random.Random(5)
R = list(ADD4)
allowed = set(m.instrs)
for _ in range(3000):
R, _, h = st.propose(m, R, rng, 0.2)
self.assertEqual(len(R), 4)
self.assertGreater(h, 0)
for ins in R:
self.assertTrue(ins is None or ins in allowed, ins)
if __name__ == "__main__":
unittest.main()
History
Massalin's 1987 superoptimizer searched all programs by length and only scaled to a handful of instructions. Bansal and Aiken (2006) built a superoptimizer from a database of short rewrites. Schkufza, Sharma and Aiken presented STOKE at ASPLOS 2013. They replaced enumeration by a Metropolis chain over loop-free x86-64 programs, and their rewrites matched or beat the code of gcc and icc at -O3, and in some cases expert hand-written assembly. Later work extended STOKE to floating point with bounded error (2014) and to conditional correctness (2015), and Phothilimthana and others combined it with other searches (2016).
References
- Eric Schkufza, Rahul Sharma and Alex Aiken, Stochastic superoptimization, Proceedings of the 18th International Conference on Architectural Support for Programming Languages and Operating Systems (ASPLOS 2013), 305-316, the cost function with the Hamming-distance correctness term and the performance term, the four moves (opcode, operand, swap, instruction), the Metropolis acceptance rule, the synthesis and optimization phases, and the validation with counterexamples
- Nicholas Metropolis, Arianna W. Rosenbluth, Marshall N. Rosenbluth, Augusta H. Teller and Edward Teller, Equation of state calculations by fast computing machines, The Journal of Chemical Physics 21(6), 1953, 1087-1092, the acceptance rule min(1, exp(-ΔE/kT)) for symmetric moves
- W. K. Hastings, Monte Carlo sampling methods using Markov chains and their applications, Biometrika 57(1), 1970, 97-109, the acceptance rule for proposals that are not symmetric, and the proof that it keeps the target distribution
- Henry Massalin, Superoptimizer, a look at the smallest program, Proceedings of the Second International Conference on Architectural Support for Programming Languages and Operating Systems (ASPLOS II), 1987, 122-126, the exhaustive search by length that stochastic search replaces for long programs
- Phitchaya Mangpo Phothilimthana, Aditya Thakur, Rastislav Bodik and Dinakar Dhurjati, Scaling up superoptimization, Proceedings of the 21st International Conference on Architectural Support for Programming Languages and Operating Systems (ASPLOS 2016), 297-310, the comparison and combination of stochastic, enumerative and symbolic search
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag JYEF5C Edit this page History Report an error Markdown