3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
6 # Written by Francois Fleuret <francois@fleuret.org>
8 import torch, torchvision
10 ######################################################################
12 # CODE_OP=[0 for push, 1 for pop] + 2 * n_stack
13 # CODE_VAL=val + 2 * nb_stacks
16 def generate_sequences(
17 nb, nb_steps, nb_stacks, nb_digits, values=None, device=torch.device("cpu")
19 stack = torch.empty(nb, nb_stacks, nb_steps, dtype=torch.int64)
20 stack_counts = torch.zeros(nb, nb_stacks, dtype=torch.int64)
22 result = torch.empty(nb, (1 + nb_digits) * nb_steps, dtype=torch.int64)
23 recorded_stack_counts = torch.zeros(
24 nb, (1 + nb_digits) * nb_steps, dtype=torch.int64
27 for t in range(nb_steps):
28 op = torch.randint(2, (nb,))
29 st = torch.randint(nb_stacks, (nb,))
30 op = op * (stack_counts[k, st] > 0)
32 val_push = torch.randint(10**nb_digits, (nb,))
34 val_push = values[torch.randint(values.size(0), (nb,))]
38 (stack_counts[k, st] - 1).clamp(min=0),
40 stack[k, st, stack_counts[k, st]] = val_push
41 recorded_stack_counts[:, (1 + nb_digits) * t] = stack_counts[k, st]
42 stack_counts[k[op == 0], st[op == 0]] += 1
43 stack_counts[k[op == 1], st[op == 1]] -= 1
44 result[:, (1 + nb_digits) * t] = st * 2 + op
45 for d in range(nb_digits):
46 result[:, (1 + nb_digits) * t + 1 + d] = (
47 (op * val_pop + (1 - op) * val_push) // (10**d)
48 ) % 10 + 2 * nb_stacks
50 return result.to(device), recorded_stack_counts.to(device)
53 def remove_popped_values(seq, nb_stacks, nb_digits):
54 m = torch.logical_and(seq % 2 == 1, seq < 2 * nb_stacks).long()
55 for d in range(nb_digits):
57 seq[:, k:] = -m[:, :-k] + (1 - m[:, :-k]) * seq[:, k:]
60 def seq_to_str(seq, nb_stacks, nb_digits, recorded_stack_counts=None):
61 assert seq.size(0) % (1 + nb_digits) == 0
63 for t in range(seq.size(0) // (1 + nb_digits)):
64 n_op = seq[(1 + nb_digits) * t]
67 if recorded_stack_counts is not None:
68 s += f"[{recorded_stack_counts[(1 + nb_digits)*t]}] "
69 s += f"POP" if n_op % 2 == 1 else f"PSH"
72 for d in range(nb_digits):
73 if seq[(1 + nb_digits) * t + 1 + d] == -1:
76 s += f" {seq[(1 + nb_digits) * t + 1 + d] - 2 * nb_stacks:1d}"
80 ######################################################################
82 if __name__ == "__main__":
83 nb, nb_steps, nb_stacks, nb_digits = 150000, 20, 2, 1
84 seq, recorded_stack_counts = generate_sequences(
91 for n in range(min(10, seq.size(0))):
97 recorded_stack_counts=recorded_stack_counts[n],
100 # print(seq_to_str(seq[n], nb_stacks=nb_stacks, nb_digits=nb_digits))
102 print("-- PREPARED FOR TEST -----------------")
104 remove_popped_values(seq, nb_stacks, nb_digits)
106 for n in range(min(10, seq.size(0))):
107 print(seq_to_str(seq[n], nb_stacks=nb_stacks, nb_digits=nb_digits))