|
@ -1,3 +1,9 @@ |
|
|
|
|
|
from math import exp, log |
|
|
|
|
|
from random import random |
|
|
|
|
|
from typing import List |
|
|
|
|
|
|
|
|
|
|
|
from gbso.program.test_case import Output, TestCase, eq_on_testcase |
|
|
|
|
|
from gbso.program.mutate import mutate_program |
|
|
from gbso.program.program import Program |
|
|
from gbso.program.program import Program |
|
|
|
|
|
|
|
|
EPSILON = 0.00001 |
|
|
EPSILON = 0.00001 |
|
@ -12,8 +18,23 @@ DEFAULT_PROB_INSN = 0.25 |
|
|
DEFAULT_PROB_INSN_UNUSED = 0.1 |
|
|
DEFAULT_PROB_INSN_UNUSED = 0.1 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def cost(orig_prgm, test_cases, outputs, prgm) -> int: |
|
|
|
|
|
c = prgm.perf() - orig_prgm.perf() |
|
|
|
|
|
# print(f"init cost: {c}") |
|
|
|
|
|
|
|
|
|
|
|
for test_case in test_cases: |
|
|
|
|
|
c += eq_on_testcase(orig_prgm, prgm, test_case, outputs) |
|
|
|
|
|
# print(f"cost after testcase: {c}") |
|
|
|
|
|
|
|
|
|
|
|
return c |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def optimize( |
|
|
def optimize( |
|
|
prgm: Program, |
|
|
prgm: Program, |
|
|
|
|
|
max_size: int, |
|
|
|
|
|
test_cases: List[TestCase], |
|
|
|
|
|
outputs: List[Output], |
|
|
|
|
|
beta: int = 0.75, # How far away in cost you are allowed to search |
|
|
num_iters: int = DEFAULT_NUM_ITERS, |
|
|
num_iters: int = DEFAULT_NUM_ITERS, |
|
|
prob_opcode: float = DEFAULT_PROB_OPCODE, |
|
|
prob_opcode: float = DEFAULT_PROB_OPCODE, |
|
|
prob_operand: float = DEFAULT_PROB_OPERAND, |
|
|
prob_operand: float = DEFAULT_PROB_OPERAND, |
|
@ -21,7 +42,19 @@ def optimize( |
|
|
prob_insn: float = DEFAULT_PROB_INSN, |
|
|
prob_insn: float = DEFAULT_PROB_INSN, |
|
|
prob_insn_unused: float = DEFAULT_PROB_INSN_UNUSED, |
|
|
prob_insn_unused: float = DEFAULT_PROB_INSN_UNUSED, |
|
|
) -> Program: |
|
|
) -> Program: |
|
|
prob_sum = sum([prob_opcode, prob_operand, prob_swap, prob_insn]) |
|
|
|
|
|
assert abs(1 - prob_sum) < EPSILON |
|
|
|
|
|
|
|
|
padded_prgm = prgm.pad(max_size) |
|
|
|
|
|
|
|
|
|
|
|
last_prgm = padded_prgm |
|
|
|
|
|
last_cost = cost(padded_prgm, test_cases, outputs, last_prgm) |
|
|
|
|
|
|
|
|
|
|
|
for _ in range(num_iters): |
|
|
|
|
|
candidate_prgm = mutate_program( |
|
|
|
|
|
last_prgm, prob_opcode, prob_operand, prob_swap, prob_insn, prob_insn_unused |
|
|
|
|
|
) |
|
|
|
|
|
candidate_cost = cost(padded_prgm, test_cases, outputs, candidate_prgm) |
|
|
|
|
|
|
|
|
|
|
|
if candidate_cost < last_cost - log(random()) / beta: |
|
|
|
|
|
last_prgm = candidate_prgm |
|
|
|
|
|
last_cost = candidate_cost |
|
|
|
|
|
|
|
|
return prgm |
|
|
|
|
|
|
|
|
return last_prgm |