5 import torch, torchvision
8 from torch.nn import functional as F
11 def random_var(nb_variables=None, variables=None):
13 return chr(ord("A") + torch.randint(nb_variables, (1,)).item())
16 return l[torch.randint(len(l), (1,)).item()]
19 def random_expr(variables, operand_max, budget):
21 op = torch.randint(2, (1,)).item()
22 if op == 0 and len(variables) > 0:
23 return random_var(variables=variables)
25 return str(torch.randint(operand_max + 1, (1,)).item())
27 op = torch.randint(3, (1,)).item()
29 e = random_expr(variables, operand_max, budget - 2)
30 if ("+" in e or "-" in e or "*" in e) and (e[0] != "(" or e[-1] != ")"):
35 b = 2 + torch.randint(budget - 5, (1,)).item()
36 e1 = random_expr(variables, operand_max, b)
37 e2 = random_expr(variables, operand_max, budget - b - 1)
44 def generate_program(nb_variables, operand_max, length):
48 while len(s) < length:
49 v = random_var(nb_variables=nb_variables)
50 s += v + "=" + random_expr(variables, operand_max, budget=20) + ";"
56 def generate_sequences(nb, nb_variables=5, length=20, operand_max=9, result_max=99):
57 assert nb_variables <= 26
61 # We take length itself half of the time, and uniform between
62 # 1 and length otherwise. The actual length can be slightly
65 l = min(length, 1 + torch.randint(length * 2, (1,)).item())
67 while result == None or max(result.values()) > result_max:
68 p, v = generate_program(nb_variables, operand_max, l)
69 v = ", ".join(['"' + v + '": ' + v for v in v])
71 exec(p + "result={" + v + "}", globals(), ldict)
72 result = ldict["result"]
74 k = list(result.keys())
76 sequences.append(p + " " + "".join([v + ":" + str(result[v]) + ";" for v in k]))
81 def extract_results(seq):
82 f = lambda a: (a[0], -1 if a[1] == "" else int(a[1]))
84 dict([f(tuple(x.split(":"))) for x in re.findall("[A-Z]:[0-9]*", s)])
90 if __name__ == "__main__":
93 start_time = time.perf_counter()
94 sequences = generate_sequences(1000, length=40)
95 end_time = time.perf_counter()
96 for s in sequences[:10]:
98 print(f"{len(sequences) / (end_time - start_time):.02f} samples per second")
100 print(extract_results(sequences[:10]))