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(nb, nb_steps, nb_stacks, nb_values, device=torch.device("cpu")):
17 stack = torch.empty(nb, nb_stacks, nb_steps, dtype=torch.int64)
18 stack_counts = torch.zeros(nb, nb_stacks, dtype=torch.int64)
20 result = torch.empty(nb, 2 * nb_steps, dtype=torch.int64)
21 recorded_stack_counts = torch.zeros(nb, 2 * nb_steps, dtype=torch.int64)
23 for t in range(nb_steps):
24 op = torch.randint(2, (nb,))
25 st = torch.randint(nb_stacks, (nb,))
26 op = op * (stack_counts[k, st] > 0)
27 val_push = torch.randint(nb_values, (nb,))
31 (stack_counts[k, st] - 1).clamp(min=0),
33 stack[k, st, stack_counts[k, st]] = val_push
34 recorded_stack_counts[:, 2 * t + 1] = stack_counts[k, st]
35 stack_counts[k[op == 0], st[op == 0]] += 1
36 stack_counts[k[op == 1], st[op == 1]] -= 1
37 result[:, 2 * t] = st * 2 + op
38 result[:, 2 * t + 1] = (op * val_pop + (1 - op) * val_push) + 2 * nb_stacks
40 return result.to(device), recorded_stack_counts.to(device)
43 def remove_poped_values(seq, nb_stacks):
44 m = torch.logical_and(seq % 2 == 1, seq < 2 * nb_stacks).long()
45 seq[:, 1:] = -m[:, :-1] + (1 - m[:, :-1]) * seq[:, 1:]
48 def seq_to_str(seq, recorded_stack_counts=None):
49 assert seq.size(0) % 2 == 0
51 for t in range(seq.size(0) // 2):
53 op = f"POP_{op//2}" if op % 2 == 1 else f"PSH_{op//2}"
54 if seq[2 * t + 1] == -1:
57 val = seq[2 * t + 1] - 2 * nb_stacks
60 if recorded_stack_counts is not None:
61 s += f"[{recorded_stack_counts[2*t+1]}] "
66 ######################################################################
68 if __name__ == "__main__":
69 nb, nb_steps, nb_stacks, nb_values = 150000, 10, 1, 5
70 seq, recorded_stack_counts = generate_sequences(
71 nb=nb, nb_steps=nb_steps, nb_stacks=nb_stacks, nb_values=nb_values
74 for n in range(min(10, seq.size(0))):
75 # print(seq_to_str(seq[n], recorded_stack_counts[n]))
76 print(seq_to_str(seq[n]))
78 print("--------------------------------------")
80 remove_poped_values(seq, nb_stacks)
82 for n in range(min(10, seq.size(0))):
83 print(seq_to_str(seq[n]))