5 import torch, torchvision
8 from torch.nn import functional as F
10 ######################################################################
13 def rpl_exec(program, stack):
17 a, b = stack.pop(), stack.pop()
21 a, b = stack.pop(), stack.pop()
22 stack.append(min(a, b))
25 a, b = stack.pop(), stack.pop()
26 stack.append(max(a, b))
29 a, b = stack.pop(), stack.pop()
34 a, b = stack.pop(), stack.pop()
45 raise ValueError(f"Unknown instruction {op}")
48 rpl_ops = ["add", "min", "max", "swp", "rep", "dup", "del"]
50 ######################################################################
53 def generate(nb_values=3, max_input=9, prog_len=6, nb_runs=5):
54 prog_len = 1 + torch.randint(prog_len - 1, (1,)).item()
55 prog = [rpl_ops[k] for k in torch.randint(len(rpl_ops), (prog_len,))]
58 for _ in range(nb_runs):
59 stack = [x.item() for x in torch.randint(max_input + 1, (nb_values,))]
60 result = result + ["<input>"] + stack
62 result = result + ["<output>"] + stack
64 result = result + ["<prog>"] + prog
65 result = result + ["<end>"]
69 def next_marker(seq, tokens, start=0):
73 i = seq.index(t, start)
74 if pos is None or i < pos:
84 while seq[k] == "<input>":
85 o = next_marker(seq, ["<output>"], start=k + 1)
86 e = next_marker(seq, ["<input>", "<prog>"], start=o)
87 if o is None or e is None:
88 raise ValueError("Invalid input/output")
89 io.append((seq[k + 1 : o], seq[o + 1 : e]))
92 if seq[k] == "<prog>":
93 e = next_marker(seq, ["<end>"], start=k)
99 nb_total, nb_errors = 0, 0
101 if len(set(prog) - set(rpl_ops)) > 0:
102 for stack, target_stack in io:
103 nb_total += len(target_stack)
104 nb_errors += len(target_stack)
107 for stack, target_stack in io:
108 # print(f"INIT {stack} PROG {prog}")
109 rpl_exec(prog, stack)
110 # print(f"CHECK {stack} REF {target_stack} NB_ERROR {abs(len(stack) - len(target_stack))+sum([0 if x == y else 1 for x, y in zip(stack, target_stack)])}")
111 nb_total += len(target_stack)
112 nb_errors += abs(len(stack) - len(target_stack))
113 nb_errors += sum([0 if x == y else 1 for x, y in zip(stack, target_stack)])
115 return nb_total, nb_errors
118 ######################################################################
120 if __name__ == "__main__":