-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtorch_AC.py
More file actions
1706 lines (1433 loc) · 80.2 KB
/
Copy pathtorch_AC.py
File metadata and controls
1706 lines (1433 loc) · 80.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import torch
from AC_env import *
import random
def OLD_apply_all_moves_to_all_states_torch(states):
"""
Applies all possible moves to each state in the batch of states using PyTorch.
Args:
states: Tensor of shape (batch_size, state_size) containing multiple cube states
Returns:
Tensor of shape (batch_size, num_moves, state_size) containing all resulting states
"""
batch_size = states.shape[0]
num_moves = 12
# Create output tensor with shape (batch_size, num_moves, state_size)
all_states = torch.zeros(batch_size, num_moves, states.shape[1], dtype=states.dtype, device=states.device)
# For each move
for move_idx in range(num_moves):
# Copy original states
#all_states[:,move_idx] = states.clone()
# Apply move to this slice
all_states[:,move_idx] = finger_ix_fast_vec_torch(states, move_idx)
return all_states
def apply_all_moves_to_all_states_torch(states):
"""
Applies all possible moves to each state in the batch of states using PyTorch.
Uses same batched approach as finger_ix_fast_vec_torch_list_of_moves.
Args:
states: Tensor of shape (batch_size, state_size) containing multiple cube states
Returns:
Tensor of shape (batch_size, num_moves, state_size) containing all resulting states
"""
batch_size = states.shape[0]
num_moves = 12
device = states.device
max_rel_length = states.shape[-1]//2
# Create output tensor
all_states = torch.zeros(batch_size, num_moves, states.shape[1], dtype=states.dtype, device=device)
# Split into r0 and r1 components
r0 = states[:, :max_rel_length]
r1 = states[:, max_rel_length:]
# Create minus reversed versions once for basic moves
minusreverse_r0 = minus_reverse_torch(r0)
minusreverse_r1 = minus_reverse_torch(r1)
# Handle moves 0-3 efficiently by batching
# Prepare inputs for single combine_relator_and_relator2_torch_vmap call
first_relators = torch.zeros(batch_size * 4, max_rel_length, device=device, dtype=states.dtype)
second_relators = torch.zeros_like(first_relators)
# Set up which relators get combined based on move type
first_relators[0::4] = r1 # move 0: r1 for r_1 --> r_1 r_0
first_relators[1::4] = r0 # move 1: r0 for r_0 --> r_0 r_1^{-1}
first_relators[2::4] = r1 # move 2: r1 for r_1 --> r_1 r_0^{-1}
first_relators[3::4] = r0 # move 3: r0 for r_0 --> r_0 r_1
second_relators[0::4] = r0 # move 0: r0
second_relators[1::4] = minusreverse_r1 # move 1: -r1^rev
second_relators[2::4] = minusreverse_r0 # move 2: -r0^rev
second_relators[3::4] = r1 # move 3: r1
# Single call to combine relators
combined = combine_relator_and_relator2_torch_vmap(first_relators, second_relators)
# Update outputs based on move type
all_states[:, 0] = torch.cat([r0, combined[0::4]], dim=-1) # move 0
all_states[:, 1] = torch.cat([combined[1::4], r1], dim=-1) # move 1
all_states[:, 2] = torch.cat([r0, combined[2::4]], dim=-1) # move 2
all_states[:, 3] = torch.cat([combined[3::4], r1], dim=-1) # move 3
# Handle conjugation moves 4-11
conjugations = {
4: (1, torch.tensor([1,-1], device=device)), # r1, x0^-1 r1 x0
5: (0, torch.tensor([2,-2], device=device)), # r0, x1^-1 r0 x1
6: (1, torch.tensor([2,-2], device=device)), # r1, x1^-1 r1 x1
7: (0, torch.tensor([-1,1], device=device)), # r0, x0 r0 x0^-1
8: (1, torch.tensor([-1,1], device=device)), # r1, x0 r1 x0^-1
9: (0, torch.tensor([-2,2], device=device)), # r0, x1 r0 x1^-1
10: (1, torch.tensor([-2,2], device=device)), # r1, x1 r1 x1^-1
11: (0, torch.tensor([1,-1], device=device)) # r0, x0^-1 r0 x0
}
for move in range(4, 12):
rel_idx, conj_pattern = conjugations[move]
if rel_idx == 0:
r0_out = contract_endpoints_of_relator_flexible_torch_vmap(r0, conj_pattern)
all_states[:,move] = torch.cat([r0_out, r1], dim=-1)
else:
r1_out = contract_endpoints_of_relator_flexible_torch_vmap(r1, conj_pattern)
all_states[:,move] = torch.cat([r0, r1_out], dim=-1)
return all_states
def OLD_finger_ix_fast_vec_torch(states: torch.Tensor, ix: int, simplify: bool = True) -> torch.Tensor:
"""
PyTorch version of finger_ix_fast_vec that operates on multiple states at once.
Args:
states: Tensor of shape (batch_size, state_size) containing multiple cube states
ix: Move index to apply to all states
Returns:
Updated states after applying the move
"""
max_relator_length = states.shape[1] // 2
# Split states into r0 and r1 components
r0 = states[:, :max_relator_length]
r1 = states[:, max_relator_length:]
r0_nonzero_mask = r0 != 0
r1_nonzero_mask = r1 != 0
r0_counts = r0_nonzero_mask.sum(dim=1)
r1_counts = r1_nonzero_mask.sum(dim=1)
r0_indices = torch.arange(max_relator_length, device=states.device)[None, :]
r1_indices = torch.arange(max_relator_length, device=states.device)[None, :]
# Create output states tensor
new_states = states.clone()
if ix == 0: # r_1 --> r_1 r_0
mask = (r0_counts + r1_counts) <= max_relator_length
new_r1 = torch.zeros_like(states)
new_r1[:,:max_relator_length] = r1
r0_start_positions = r1_counts[:, None]
r0_newindices = r0_indices + r0_start_positions
new_r1.scatter_(1, r0_newindices, r0 * r0_nonzero_mask)
new_states[mask, max_relator_length:] = new_r1[mask,:max_relator_length]
elif ix == 1: # r_0 --> r_0 r_1^{-1}
mask = (r0_counts + r1_counts) <= max_relator_length
new_r0 = torch.zeros_like(states)
new_r0[:,:max_relator_length] = r0
#reversed_r1 = -1 * torch.flip(r1 * r1_nonzero_mask, [1])
reversed_r1 = -1* reverse_padded_vectors_torch(r1)
r1_start_positions = r0_counts[:, None]
r1_newindices = r0_indices + r1_start_positions
new_r0.scatter_(1, r1_newindices, reversed_r1)
new_states[mask, :max_relator_length] = new_r0[mask,:max_relator_length]
elif ix == 2: # r_1 --> r_1 r_0^{-1}
mask = (r0_counts + r1_counts) <= max_relator_length
new_r1 = torch.zeros_like(states)
new_r1[:,:max_relator_length] = r1
#reversed_r0 = -1 * torch.flip(r0 * r0_nonzero_mask, [1])
reversed_r0 = -1* reverse_padded_vectors_torch(r0)
r0_start_positions = r1_counts[:, None]
r0_newindices = r1_indices + r0_start_positions
new_r1.scatter_(1, r0_newindices, reversed_r0)
new_states[mask, max_relator_length:] = new_r1[mask,:max_relator_length]
elif ix == 3: # r_0 --> r_0 r_1
mask = (r0_counts + r1_counts) <= max_relator_length
new_r0 = torch.zeros_like(states)
new_r0[:,:max_relator_length] = r0
r1_start_positions = r0_counts[:, None]
r1_newindices = r0_indices + r1_start_positions
new_r0.scatter_(1, r1_newindices, r1 * r1_nonzero_mask)
new_states[mask, :max_relator_length] = new_r0[mask,:max_relator_length]
elif ix == 4: # r_1 --> x_0^{-1} r_1 x_0
mask = (r1_counts + 2) <= max_relator_length
new_r1 = torch.zeros((r1.shape[0], max_relator_length+2), device=states.device,dtype=states.dtype)
new_r1[:,1:max_relator_length] = r1[:,:-1]
new_r1[:, 0] = -1
new_r1[torch.arange(len(r1_counts), device=states.device,dtype=torch.int64), r1_counts + 1] = 1
new_states[mask, max_relator_length:] = new_r1[mask, :max_relator_length]
unmasked = ~mask
if torch.any(unmasked):
contracted_r1 = contract_endpoints_torch(r1[unmasked], torch.tensor([1,-1], device=states.device))
new_states[unmasked, max_relator_length:] = contracted_r1
elif ix == 5: # r_0 --> x_1^{-1} r_0 x_1
mask = (r0_counts + 2) <= max_relator_length
new_r0 = torch.zeros((r0.shape[0], max_relator_length+2), device=states.device, dtype=states.dtype)
new_r0[:,1:max_relator_length] = r0[:,:-1]
new_r0[:, 0] = -2
new_r0[torch.arange(len(r0_counts), device=states.device), r0_counts + 1] = 2
new_states[mask, :max_relator_length] = new_r0[mask, :max_relator_length]
unmasked = ~mask
if torch.any(unmasked):
contracted_r0 = contract_endpoints_torch(r0[unmasked], torch.tensor([2,-2], device=states.device))
new_states[unmasked, :max_relator_length] = contracted_r0
elif ix == 6: # r_1 --> x_1^{-1} r_1 x_1
mask = (r1_counts + 2) <= max_relator_length
new_r1 = torch.zeros((r1.shape[0], max_relator_length+2), device=states.device,dtype=states.dtype)
new_r1[:,1:max_relator_length] = r1[:,:-1]
new_r1[:, 0] = -2
new_r1[torch.arange(len(r1_counts), device=states.device), r1_counts + 1] = 2
new_states[mask, max_relator_length:] = new_r1[mask, :max_relator_length]
unmasked = ~mask
if torch.any(unmasked):
contracted_r1 = contract_endpoints_torch(r1[unmasked], torch.tensor([2,-2], device=states.device))
new_states[unmasked, max_relator_length:] = contracted_r1
elif ix == 7: # r_0 --> x_0 r_0 x_0^{-1}
mask = (r0_counts + 2) <= max_relator_length
new_r0 = torch.zeros((r0.shape[0], max_relator_length+2), device=states.device,dtype=states.dtype)
new_r0[:,1:max_relator_length] = r0[:,:-1]
new_r0[:, 0] = 1
new_r0[torch.arange(len(r0_counts), device=states.device), r0_counts + 1] = -1
new_states[mask, :max_relator_length] = new_r0[mask, :max_relator_length]
unmasked = ~mask
if torch.any(unmasked):
contracted_r0 = contract_endpoints_torch(r0[unmasked], torch.tensor([-1,1], device=states.device))
new_states[unmasked, :max_relator_length] = contracted_r0
elif ix == 8: # r_1 --> x_0 r_1 x_0^{-1}
mask = (r1_counts + 2) <= max_relator_length
new_r1 = torch.zeros((r1.shape[0], max_relator_length+2), device=states.device,dtype=states.dtype)
new_r1[:,1:max_relator_length] = r1[:,:-1]
new_r1[:, 0] = 1
new_r1[torch.arange(len(r1_counts), device=states.device), r1_counts + 1] = -1
new_states[mask, max_relator_length:] = new_r1[mask, :max_relator_length]
unmasked = ~mask
if torch.any(unmasked):
contracted_r1 = contract_endpoints_torch(r1[unmasked], torch.tensor([-1,1], device=states.device))
new_states[unmasked, max_relator_length:] = contracted_r1
elif ix == 9: # r_0 --> x_1 r_0 x_1^{-1}
mask = (r0_counts + 2) <= max_relator_length
new_r0 = torch.zeros((r0.shape[0], max_relator_length+2), device=states.device,dtype=states.dtype)
new_r0[:,1:max_relator_length] = r0[:,:-1]
new_r0[:, 0] = 2
new_r0[torch.arange(len(r0_counts), device=states.device), r0_counts + 1] = -2
new_states[mask, :max_relator_length] = new_r0[mask, :max_relator_length]
unmasked = ~mask
if torch.any(unmasked):
contracted_r0 = contract_endpoints_torch(r0[unmasked], torch.tensor([-2,2], device=states.device))
new_states[unmasked, :max_relator_length] = contracted_r0
elif ix == 10: # r_1 --> x_1 r_1 x_1^{-1}
mask = (r1_counts + 2) <= max_relator_length
new_r1 = torch.zeros((r1.shape[0], max_relator_length+2), device=states.device,dtype=states.dtype)
new_r1[:,1:max_relator_length] = r1[:,:-1]
new_r1[:, 0] = 2
new_r1[torch.arange(len(r1_counts), device=states.device), r1_counts + 1] = -2
new_states[mask, max_relator_length:] = new_r1[mask, :max_relator_length]
unmasked = ~mask
if torch.any(unmasked):
contracted_r1 = contract_endpoints_torch(r1[unmasked], torch.tensor([-2,2], device=states.device) )
new_states[unmasked, max_relator_length:] = contracted_r1
elif ix == 11: # r_0 --> x_0^{-1} r_0 x_0
mask = (r0_counts + 2) <= max_relator_length
new_r0 = torch.zeros((r0.shape[0], max_relator_length+2), device=states.device,dtype=states.dtype)
new_r0[:,1:max_relator_length] = r0[:,:-1]
new_r0[:, 0] = -1
new_r0[torch.arange(len(r0_counts), device=states.device), r0_counts + 1] = 1
new_states[mask, :max_relator_length] = new_r0[mask, :max_relator_length]
unmasked = ~mask
if torch.any(unmasked):
contracted_r0 = contract_endpoints_torch(r0[unmasked], torch.tensor([1,-1], device=states.device) )
new_states[unmasked, :max_relator_length] = contracted_r0
if simplify:
new_states = simplify_state_vec_torch(new_states)
return new_states
def simplify_state_vec_torch(states):
"""PyTorch version of simplify_state_vec that operates on a batch of states."""
# Split states into r0 and r1
max_relator_length = states.shape[-1] // 2
r0 = states[:, :max_relator_length]
r1 = states[:, max_relator_length:]
# Simplify both halves of the states
r0_simplified = _iterative_simplify_vectorized_torch(r0)
r1_simplified = _iterative_simplify_vectorized_torch(r1)
# Recombine
simplified_states = torch.hstack([r0_simplified, r1_simplified])
return simplified_states
def _iterative_simplify_vectorized_torch(relators):
"""
Vectorized simplification of relator batches using preallocated tensors and fused operations.
Only processes rows that still have valid cancellation pairs.
"""
batch_size, max_len = relators.shape
device = relators.device
# Preallocate tensors we'll reuse
current = relators.clone()
buffer = torch.zeros(batch_size, max_len*2, dtype=relators.dtype, device=device)
positions = torch.arange(max_len*2, device=device).expand(batch_size, -1)
# Track which rows still need processing
active_rows = torch.ones(batch_size, dtype=torch.bool, device=device)
while active_rows.any():
# Copy current into first half of buffer (only for active rows)
buffer[active_rows, :max_len] = current[active_rows]
buffer[active_rows, max_len:] = 0
# Find cancellations using fused operations (only for active rows)
nonzero = buffer[active_rows] != 0
sums = buffer[active_rows, :-1] + buffer[active_rows, 1:]
valid_pairs = (sums == 0) & nonzero[:, :-1] & nonzero[:, 1:]
# Update active rows - if a row has no valid pairs, we're done with it
has_valid = valid_pairs.any(dim=1)
active_indices = torch.nonzero(active_rows).squeeze(1)
active_rows[active_indices[~has_valid]] = False
if not has_valid.any():
break
# Get indices for remaining active rows
still_active = active_indices[has_valid]
# Find first cancellation per remaining active row
cancel_idx = torch.argmax(valid_pairs[has_valid].to(torch.int8), dim=1)
# Mask out cancelled pairs
to_remove = (positions[still_active] == cancel_idx.unsqueeze(1)) | (positions[still_active] == (cancel_idx + 1).unsqueeze(1))
keep_mask = ~to_remove
# Compact remaining elements
kept = torch.where(keep_mask, buffer[still_active], torch.zeros_like(buffer[still_active]))
nonzero = kept != 0
sort_keys = (~nonzero) * (max_len*2) + positions[still_active]
sorted_indices = sort_keys.argsort(dim=1)
current[still_active] = torch.gather(kept, 1, sorted_indices)[:, :max_len]
return current
# test_vecs = torch.tensor([[-1, 1, 1, 1, -2, 1, 1, -2, -2, -1, 2, 1, 2, -1, 2, -1, 2, -1,
# -2, -1, 2, -1, -1, -1, 1],
# [-1, 1, 1, 1, -2, 1, 1, -2, -2, -1, 2, 1, 2, -1, 2, -1, 2, -1,
# -2, -1, 2, -1, -1, -1, 1],
# [-1, 1, 1, 1, -2, 1, 1, -2, -2, -1, 2, 1, 2, -1, 2, -1, 2, -1,
# -2, -1, 2, -1, -1, -1, 1]])[0:3]
# test_result = _iterative_simplify_vectorized_torch(test_vecs)
# print("Original test vectors:")
# print(test_vecs)
# print("\nSimplified result:")
# print(test_result)
def reverse_padded_vectors_torch(padded_vectors):
# Create a mask for non-zero elements
mask = padded_vectors != 0
# Get the counts of non-zero elements per row
lengths = mask.sum(dim=1)
# Create indices array for each row
row_indices = torch.arange(padded_vectors.shape[0], device=padded_vectors.device)[:, None]
col_indices = torch.arange(padded_vectors.shape[1], device=padded_vectors.device)[None, :]
# Create reversed indices for non-zero elements
reversed_indices = lengths[:, None] - 1 - col_indices
# Create mask for valid reversed indices
valid_mask = (reversed_indices >= 0) & mask
# Create output tensor of zeros
result = torch.zeros_like(padded_vectors)
# Fill in reversed values
result = torch.where(valid_mask,
padded_vectors.gather(1, torch.clamp(reversed_indices, min=0)),
torch.zeros_like(padded_vectors))
return result
def contract_endpoints_torch(states, pattern):
"""
Removes the first and last nonzero elements of each state if they match the given pattern.
Args:
states: Tensor of shape (batch_size, state_size) containing states to check
pattern: List/array of [first,last] values to match against endpoints
Returns:
New states with endpoints removed where pattern matched
"""
# Get nonzero masks and counts
nonzero_mask = states != 0
nonzero_counts = torch.sum(nonzero_mask, dim=1)
# Get first nonzero element for each state
first_nonzero_indices = torch.argmax(nonzero_mask.long(), dim=1)
first_elements = states[torch.arange(len(states)), first_nonzero_indices]
# Get last nonzero element for each state
# Flip the mask and find first True to get last nonzero position
last_nonzero_indices = states.shape[1] - 1 - torch.argmax(torch.fliplr(nonzero_mask).long(), dim=1)
last_elements = states[torch.arange(len(states)), last_nonzero_indices]
# Find which states can be contracted
can_contract = (first_elements == pattern[0]) & (last_elements == pattern[1])
# Create output tensor
new_states = states.clone()
if torch.any(can_contract):
# Get indices of states that can be contracted
contract_indices = torch.where(can_contract)[0]
# For each state that can be contracted
for idx in contract_indices:
# Remove first and last elements by shifting everything left
nonzero_count = nonzero_counts[idx]
new_state = torch.zeros_like(states[idx])
new_state[:nonzero_count-2] = states[idx][1:nonzero_count-1]
new_states[idx] = new_state
return new_states
def minus_reverse_torch(r1):
# r1 has shape (batch_size, seq_len)
minusreverser1 = -torch.flip(r1, dims=[-1])
nonzero_mask = minusreverser1 != 0
nonzero_counts = torch.sum(nonzero_mask, dim=1)
minusreverser1_full = torch.zeros_like(r1)
# Create indices for placing nonzeros
batch_size = r1.shape[0]
batch_indices = torch.arange(batch_size,device=r1.device).unsqueeze(1)
seq_indices = torch.arange(r1.shape[1],device=r1.device).unsqueeze(0)
# Place nonzeros at start using mask
valid_indices = seq_indices < nonzero_counts.unsqueeze(1)
minusreverser1_full[valid_indices] = minusreverser1[nonzero_mask][:(valid_indices.sum())]
return minusreverser1_full
def left_justify_states(rs):
"""
Pushes all nonzero elements to the left and zeros to the right.
Args:
rs: Tensor of shape (batch_size, state_size) containing states to justify
Returns:
States with nonzeros on left and zeros on right, same shape as input
"""
# Get nonzero values and their original positions
nonzero_mask = rs != 0
nonzero_values = rs[nonzero_mask]
nonzero_counts = torch.sum(nonzero_mask, dim=1)
justified = torch.zeros_like(rs)
batch_size = rs.shape[0]
seq_indices = torch.arange(rs.shape[1],device=rs.device).unsqueeze(0)
# Place all nonzeros at start, pushing zeros to right
valid_indices = seq_indices < nonzero_counts.unsqueeze(1)
justified[valid_indices] = nonzero_values[:(valid_indices.sum())]
return justified
def right_justify_states(rs):
"""
Pushes all nonzero elements to the right and zeros to the left
Args:
rs: Tensor of shape (batch_size, state_size) containing states to justify
Returns:
States with zeros on left and nonzeros on right, same shape as input
"""
# Get nonzero values and their original positions
nonzero_mask = rs != 0
nonzero_values = rs[nonzero_mask]
nonzero_counts = torch.sum(nonzero_mask, dim=1)
justified = torch.zeros_like(rs)
batch_size = rs.shape[0]
seq_indices = torch.arange(rs.shape[1],device=rs.device).unsqueeze(0)
# Place nonzeros at end by offsetting indices by sequence length minus nonzero count
offsets = rs.shape[1] - nonzero_counts
valid_indices = seq_indices >= offsets.unsqueeze(1)
justified[valid_indices] = nonzero_values[:(valid_indices.sum())]
return justified
def finger_ix_fast_vec_torch_list_of_moves(states: torch.Tensor, moves: torch.Tensor) -> torch.Tensor:
"""
Do relator type moves using PyTorch for a batch of moves 0-3.
Args:
states: Tensor of shape (batch_size, state_size) containing cube states
moves: Tensor of shape (batch_size,) containing move indices 0-11
Returns:
Tensor of same shape as states with moves applied
Notes:
- Optimized version that batches moves 0-3 together
- Not a true vmap (vectorized map) implementation
- Simplification is NOT applied to output states
- Moves 0-3: Combine relators (r0,r1) in different orders
- Moves 4-11: Contract endpoints of relators with conjugation
"""
max_rel_length = states.shape[-1]//2
r0, r1 = torch.split(states, max_rel_length, dim=-1)
batch_size = states.shape[0]
device = states.device
# Handle moves 0-3 efficiently by batching
basic_moves_mask = moves < 4
if basic_moves_mask.any():
# Get indices where basic moves occur
basic_move_indices = basic_moves_mask.nonzero().squeeze(-1)
basic_moves = moves[basic_move_indices]
# Prepare relators for combination
r0_basic = r0[basic_move_indices]
r1_basic = r1[basic_move_indices]
# Create minus reversed versions once
minusreverse_r0 = minus_reverse_torch(r0_basic)
minusreverse_r1 = minus_reverse_torch(r1_basic)
# Create output tensors
r0_out = r0.clone()
r1_out = r1.clone()
# Handle each basic move type
move_0_mask = basic_moves == 0 # r_1 --> r_1 r_0
move_1_mask = basic_moves == 1 # r_0 --> r_0 r_1^{-1}
move_2_mask = basic_moves == 2 # r_1 --> r_1 r_0^{-1}
move_3_mask = basic_moves == 3 # r_0 --> r_0 r_1
# Combine all relators in one batch operation
# Prepare inputs for single combine_relator_and_relator2_torch_vmap call
first_relators = torch.zeros_like(r0_basic)
second_relators = torch.zeros_like(r0_basic)
# Set up which relators get combined based on move type
first_relators[move_0_mask] = r1_basic[move_0_mask] # r1 for move 0
first_relators[move_1_mask] = r0_basic[move_1_mask] # r0 for move 1
first_relators[move_2_mask] = r1_basic[move_2_mask] # r1 for move 2
first_relators[move_3_mask] = r0_basic[move_3_mask] # r0 for move 3
second_relators[move_0_mask] = r0_basic[move_0_mask] # r0 for move 0
second_relators[move_1_mask] = minusreverse_r1[move_1_mask] # -r1^rev for move 1
second_relators[move_2_mask] = minusreverse_r0[move_2_mask] # -r0^rev for move 2
second_relators[move_3_mask] = r1_basic[move_3_mask] # r1 for move 3
# Single call to combine relators
combined = combine_relator_and_relator2_torch_vmap(first_relators, second_relators)
# Update outputs based on move type
r1_out[basic_move_indices[move_0_mask]] = combined[move_0_mask]
r0_out[basic_move_indices[move_1_mask]] = combined[move_1_mask]
r1_out[basic_move_indices[move_2_mask]] = combined[move_2_mask]
r0_out[basic_move_indices[move_3_mask]] = combined[move_3_mask]
# Handle conjugation moves 4-11
conj_moves_mask = ~basic_moves_mask
if conj_moves_mask.any():
conj_move_indices = conj_moves_mask.nonzero().squeeze(-1)
conj_moves = moves[conj_move_indices]
# Create output tensors if not already created
if not basic_moves_mask.any():
r0_out = r0.clone()
r1_out = r1.clone()
# Define conjugation patterns
conjugations = {
4: (1, torch.tensor([1,-1], device=device)), # r1, x0^-1 r1 x0
5: (0, torch.tensor([2,-2], device=device)), # r0, x1^-1 r0 x1
6: (1, torch.tensor([2,-2], device=device)), # r1, x1^-1 r1 x1
7: (0, torch.tensor([-1,1], device=device)), # r0, x0 r0 x0^-1
8: (1, torch.tensor([-1,1], device=device)), # r1, x0 r1 x0^-1
9: (0, torch.tensor([-2,2], device=device)), # r0, x1 r0 x1^-1
10: (1, torch.tensor([-2,2], device=device)), # r1, x1 r1 x1^-1
11: (0, torch.tensor([1,-1], device=device)) # r0, x0^-1 r0 x0
}
for move in range(4, 12):
move_mask = conj_moves == move
if move_mask.any():
rel_idx, conj_pattern = conjugations[move]
if rel_idx == 0:
r0_out[conj_move_indices[move_mask]] = contract_endpoints_of_relator_flexible_torch_vmap(
r0[conj_move_indices[move_mask]], conj_pattern)
else:
r1_out[conj_move_indices[move_mask]] = contract_endpoints_of_relator_flexible_torch_vmap(
r1[conj_move_indices[move_mask]], conj_pattern)
return torch.cat([r0_out, r1_out], dim=-1)
def finger_ix_fast_vec_torch(states: torch.Tensor, ix: int) -> torch.Tensor:
"""
Do relator type moves using PyTorch.
Args:
states: Tensor of shape (batch_size, state_size) containing cube states
ix: Integer index specifying which move to apply (0-11)
Returns:
Tensor of same shape as state with move applied
Notes:
- Not a true vmap (vectorized map) implementation
- Simplification is NOT applied to output states
- Moves 0-3: Combine relators (r0,r1) in different orders
- Moves 4-11: Contract endpoints of relators with conjugation
"""
max_rel_length = states.shape[-1]//2
r0,r1 = torch.split(states,max_rel_length,dim=-1)
# No need to extract nonzero elements since we want full width
# For minus reverse: flip, negate, and left-justify by removing zeros
if ix ==0:# r_1 --> r_1 r_0
r1=combine_relator_and_relator2_torch_vmap(r1,r0)
elif ix ==1:# r_0 --> r_0 r_1^{-1}
minusreverser1 = minus_reverse_torch(r1)
r0=combine_relator_and_relator2_torch_vmap(r0,minusreverser1)
elif ix ==2:# r_1 --> r_1 r_0^{-1}
minusreverser0 = minus_reverse_torch(r0)
r1=combine_relator_and_relator2_torch_vmap(r1,minusreverser0)
elif ix ==3:# r_0 --> r_0 r_1
r0=combine_relator_and_relator2_torch_vmap(r0,r1)
elif ix == 4:# r_1 --> x_0^{-1} r_1 x_0
r1=contract_endpoints_of_relator_flexible_torch_vmap(r1,torch.tensor([1,-1],device=r0.device))
elif ix == 5:# r_0 ---> x_1^{-1} r_0 x_1
r0=contract_endpoints_of_relator_flexible_torch_vmap(r0,torch.tensor([2,-2],device=r0.device))
elif ix == 6:# r_1 --> x_1^{-1} r_1 x_1
r1=contract_endpoints_of_relator_flexible_torch_vmap(r1,torch.tensor([2,-2],device=r0.device))
elif ix == 7:# r_0 ---> x_0 r_0 x_0^{-1}
r0=contract_endpoints_of_relator_flexible_torch_vmap(r0,torch.tensor([-1,1],device=r0.device))
elif ix == 8:# r_1 --> x_0 r_1 x_0^{-1}
r1=contract_endpoints_of_relator_flexible_torch_vmap(r1,torch.tensor([-1,1],device=r0.device))
elif ix == 9:# r_0 --> x_1 r_0 x_1^{-1}
r0=contract_endpoints_of_relator_flexible_torch_vmap(r0,torch.tensor([-2,2],device=r0.device))
elif ix == 10:# r_1 --> x_1 r_1 x_1^{-1}
r1=contract_endpoints_of_relator_flexible_torch_vmap(r1,torch.tensor([-2,2],device=r0.device))
elif ix == 11:# r_0 --> x_0^{-1} r_0 x_0
r0=contract_endpoints_of_relator_flexible_torch_vmap(r0,torch.tensor([1,-1],device=r0.device))
out_state = torch.cat([r0,r1],dim=-1)
#if ix>=4:
# out_state = simplify_state_vec_torch(out_state)
return out_state
#OLD VERSION OF LISTOF MOVES
def OLD_finger_ix_fast_vec_torch_list_of_moves(states,ixs_all):
#unique,reverse_ixs = torch.unique(ixs_all,return_inverse=True)#reverse_ixs is the size of ixs_all, and indexes to unique
out_states = torch.zeros_like(states,device=states.device)
moves = torch.arange(12,device=states.device)
for ix in moves:
mask = (ixs_all==ix)
if mask.any():
out_states[mask] = finger_ix_fast_vec_torch(states[mask],ix)
return out_states
def finger_ix_fast_vec_torch_list_of_moves_all_pick(states,ixs_all):
#out_states = torch.zeros_like(states,device=states.device)
out_states = apply_all_moves_to_all_states_torch(states)[torch.arange(states.shape[0]),ixs_all]
return out_states
# def combine_relator_and_nonzero_relator_torch_single_vec(relator,nonzero_relator):
# """
# Combine relator and nonzero_relator by dragging nonzero_relator R along relator r.
# PyTorch version that operates on a single vector.
# """
# # Get lengths
# R_len_nonzero = len(nonzero_relator)
# r_len = len(relator)
# r_len_nonzero = len(relator[torch.nonzero(relator).squeeze()])
# # Try each valid offset
# for offset in range(max(0, r_len_nonzero-R_len_nonzero), min(r_len-R_len_nonzero+1, r_len_nonzero+1)):
# # Create padded version of nonzero_relator
# padded_R = torch.zeros_like(relator)
# padded_R[offset:offset+R_len_nonzero] = nonzero_relator
# # Check for valid cancellation
# overlap_mask = (padded_R != 0) & (relator != 0)
# sum = relator[overlap_mask] + torch.flip(padded_R[overlap_mask], [0])
# if not torch.any(sum):
# # Valid cancellation found - construct output
# out = torch.zeros_like(relator)
# out[:offset] = relator[:offset]
# out[offset:offset+len(padded_R[r_len_nonzero:])] = padded_R[r_len_nonzero:]
# return out
# return relator # No valid cancellation found - return unchanged
# def combine_relator_and_relator2_torch_vmap(relators, relators2):
# """
# Combine relator and nonzero_relator by dragging nonzero_relator R along relator r.
# PyTorch version that operates on batches of vectors without loops.
# Args:
# relators: Tensor of shape (batch_size, state_size) containing relators
# nonzero_relators: Tensor of shape (batch_size, state_size) containing nonzero relators
# Returns:
# New relators with combinations applied where valid
# """
# batch_size, r_len = relators.shape
# # Get lengths for each relator
# nonzero_mask = relators != 0
# r_len_nonzero = torch.sum(nonzero_mask, dim=1)
# R_len_nonzero = torch.sum(relators2 != 0, dim=1)
# # Calculate valid offset ranges for each relator
# min_offsets = torch.maximum(torch.zeros_like(r_len_nonzero),
# r_len_nonzero - R_len_nonzero)
# max_offsets = torch.minimum(r_len - R_len_nonzero + 1,
# r_len_nonzero + 1)
# # Create offset matrix (batch_size x max_possible_offsets)
# max_offset_range = torch.max(max_offsets - min_offsets).item()
# offset_matrix = (torch.arange(max_offset_range, device=relators.device)
# .unsqueeze(0).expand(batch_size, -1))
# valid_offsets = (offset_matrix >= min_offsets.unsqueeze(1)) & \
# (offset_matrix < max_offsets.unsqueeze(1))
# # Create double-width relators and padded_R
# wide_relators = torch.zeros((batch_size, r_len*2), device=relators.device)
# wide_relators[:, :r_len] = relators
# #padded_R = torch.zeros((batch_size, r_len), device=relators.device)
# padded_R = relators2
# # For each offset, shift padded_R and check for cancellations
# best_offset = torch.full((batch_size,), -1, device=relators.device)
# best_result = wide_relators.clone()
# for offset in range(max_offset_range):
# # Only process batches where this offset is valid
# valid_batch = valid_offsets[:, offset]
# if not torch.any(valid_batch):
# continue
# # Shift padded_R by offset
# shifted_R = torch.roll(padded_R[valid_batch], offset, dims=1)
# # Check for cancellations
# overlap_mask = (shifted_R != 0) & (wide_relators[valid_batch] != 0)
# sums = wide_relators[valid_batch][overlap_mask] + torch.flip(shifted_R[overlap_mask], [0])
# # Where sum is zero, we found a valid cancellation
# valid_cancel = ~torch.any(sums, dim=-1)
# # Update best results for batches with valid cancellations
# update_mask = valid_batch.clone()
# update_mask[valid_batch] &= valid_cancel
# if torch.any(update_mask):
# # Only update if this is the first valid cancellation found
# first_time = best_offset[update_mask] == -1
# if torch.any(first_time):
# update_mask[update_mask.clone()] &= first_time
# best_offset[update_mask] = offset
# best_result[update_mask] = shifted_R[first_time]
# # Return original relator where no valid cancellation was found
# no_valid = best_offset == -1
# best_result[no_valid] = relators[no_valid]
# # Truncate back to original width
# return best_result[:, :r_len]
#def combine_relator_and_relator2_torch_vmap2(relators, relators2):
def combine_relator_and_relator2_torch_vmap(relators, relators2):
"""
More efficient version that right-justifies relator1, left-justifies relator2,
and searches for cancellations by pulling them apart.
ie. do r1 -> r1 r2
Args:
relators: Tensor of shape (batch_size, state_size) containing relators
relators2: Tensor of shape (batch_size, state_size) containing second relators
Returns:
New relators with combinations applied where valid
"""
batch_size, r_len = relators.shape
device = relators.device
#print("relators:",relators)
#print("relators2:",relators2)
# Get nonzero lengths and masks
rL_nonzero = relators != 0
rR_nonzero = relators2 != 0
rL_len_nonzero = torch.sum(rL_nonzero, dim=1)
rR_len_nonzero = torch.sum(rR_nonzero, dim=1)
# Right justify relator1 by rolling each row
#roll_amounts = r_len - r1_len_nonzero
justified_rL = right_justify_states(relators)
# Left justify relator2 (already left justified if using zeros padding)
justified_rR = relators2
# Calculate valid offset range
# Offset measures how much overlap between right-justified relator1 and left-justified relator2
# For example with relator1=xxx00 and relator2=yyy00:
# offset=3 means maximum overlap: xxx00
# yyy00
# offset=2 means overlap of 2: xxx00
# yyy00
# offset=1 means overlap of 1: xxx00
# yyy00
# offset=0 means no overlap: xxx00
# yyy00
max_offsets = torch.minimum(rL_len_nonzero, rR_len_nonzero) # Maximum overlap is min of nonzero lengths
min_offsets = torch.maximum(torch.zeros_like(rL_len_nonzero), rL_len_nonzero+rR_len_nonzero-r_len)
max_offset_range = torch.max(max_offsets).item()
# Track best results
best_offset = torch.full((batch_size,), -1, device=device)
best_result = justified_rL.clone()
# Start with maximum overlap and reduce
#print("max_offset_range",max_offset_range)
for offset in torch.arange(max_offset_range, -1, -1, device=device):
#print("offset",offset)
# Determine which batches to process at this offset
valid_batch = (offset <= max_offsets) & (offset >= min_offsets)
#print("valid_batch",valid_batch)
if not torch.any(valid_batch):
continue
# Get overlap region: last offset elements of r1 and first offset elements of r2
overlap_size = offset
rL_free = justified_rL[valid_batch, :r_len-overlap_size]
#print("r1_free",r1_free.shape)
rL_overlap = justified_rL[valid_batch, -overlap_size:]
#print("r1_overlap",r1_overlap.shape)
rR_overlap = justified_rR[valid_batch, :overlap_size]
#print("r2_overlap",r2_overlap.shape)
remaining_rR = justified_rR[valid_batch, overlap_size:]
#print("remaining_r2",remaining_r2.shape)
if overlap_size == 0:
# Empty overlap case - no need to calculate sums
sums = torch.zeros(valid_batch.sum().item(),0, device=device)
valid_cancel = torch.ones(valid_batch.sum().item(), device=device,dtype=torch.bool)
else:
sums = rL_overlap + torch.flip(rR_overlap, [-1])
valid_cancel = ~torch.any(sums, dim=-1)
#print("valid_cancel",valid_cancel)
#print("sums",sums.shape)
# Check for cancellations
#overlap_mask = (shifted_r2 != 0) & (justified_r1[valid_batch, -overlap_size:] != 0)
#sums = justified_r1[valid_batch][overlap_mask] + torch.flip(shifted_r2[overlap_mask], [0])
#print("sums",sums.shape)
#print("sums",sums)
# Where sum is zero, we found a valid cancellation
# Update best results for first valid cancellation found
# print("\n overlap_size",overlap_size)
# print("sums.shape",sums.shape)
# print("r1_overlap",r1_overlap.shape)
# print("best_offset",best_offset.shape)
# print("valid_batch",valid_batch.shape)
# print("valid_cancel",valid_cancel.shape)
# Create mask for valid batches that haven't found a valid cancellation yet
update_mask = torch.zeros_like(valid_batch, dtype=torch.bool, device=valid_batch.device)
update_mask[valid_batch] = valid_cancel & (best_offset[valid_batch] == -1)
if torch.any(update_mask):
best_offset[update_mask] = offset
temp_result = torch.zeros(update_mask.sum(),r_len,device=device,dtype=relators.dtype)
temp_result[:,:min(r_len - overlap_size + r_len-overlap_size,r_len)] = left_justify_states(torch.cat([rL_free[update_mask[valid_batch]],remaining_rR[update_mask[valid_batch]]],dim=-1))[:,:r_len]
best_result[update_mask] = temp_result
# Return original relator where no valid cancellation was found
no_valid = best_offset == -1
best_result[no_valid] = relators[no_valid]
# Left justify the final result to ensure consistent format
#print("best_result",best_result)
best_result = left_justify_states(best_result)
return best_result
def contract_endpoints_of_relator_flexible_torch_vmap(relators, pattern):
"""
Removes the first and last nonzero elements of each relator if they match the given pattern.
PyTorch version that operates on a batch of vectors.
Args:
relators: Tensor of shape (batch_size, state_size) containing relators to check
pattern: Tensor of [first,last] values to match against endpoints
Returns:
New relators with endpoints removed where pattern matched
"""
# Get nonzero counts and elements for all relators
nonzero_mask = relators != 0
nonzero_counts = torch.sum(nonzero_mask, dim=1)
max_rel_length = relators.shape[1]
# Get first and last nonzero elements
first_nonzero_indices = torch.argmax(nonzero_mask.long(), dim=1)
first_elements = relators[torch.arange(len(relators),device=relators.device), first_nonzero_indices]
last_nonzero_indices = relators.shape[1] - 1 - torch.argmax(torch.fliplr(nonzero_mask).long(), dim=1)
last_elements = relators[torch.arange(len(relators),device=relators.device), last_nonzero_indices]
#print("first_elements",first_elements.shape,first_elements)
#print("last_elements",last_elements.shape,last_elements)
# Create output tensor
new_relators = relators.clone()
# Path 1: nonzero_length <= max_rel_length-2
#print("nonzero_counts",nonzero_counts, "max_rel_length",max_rel_length)
short_mask = nonzero_counts <= (max_rel_length - 2)
if torch.any(short_mask):
# Shift everything right by 1
shifted = relators[short_mask]
#print("shifted",shifted)
shifted = torch.roll(shifted, shifts=(0,1), dims=(0,1))
#print("shifted2",shifted)
shifted[:, 0] = -pattern[0]
#print("shifted3",shifted)
nonzero_mask = shifted != 0
nonzero_counts_shifted = torch.sum(nonzero_mask, dim=1)
batch_indices = torch.arange(len(nonzero_counts_shifted))
shifted[batch_indices, nonzero_counts_shifted] = -pattern[1]
#print("shifted4",shifted)
#print("shifted",shifted)
shifted = _iterative_simplify_vectorized_torch(shifted)
new_relators[short_mask] = shifted
#print("new_relators",new_relators)
# # Path 2: nonzero_length == max_rel_length-1
# mid_mask = nonzero_counts == (max_rel_length - 1)
# if torch.any(mid_mask):
# start_match = first_elements[mid_mask] == pattern[0]
# end_match = last_elements[mid_mask] == pattern[1]
# # Handle start matches
# start_only = mid_mask.clone()
# start_only[mid_mask] &= start_match
# if torch.any(start_only):
# indices = torch.arange(1, max_rel_length, device=relators.device)
# new_relators[start_only,0:-1] = torch.index_select(relators[start_only], 1, indices)
# nonzero_mask = new_relators[start_only] != 0
# nonzero_counts = torch.sum(nonzero_mask, dim=1)
# batch_indices = torch.arange(start_only.sum())
# new_relators[start_only][batch_indices, nonzero_counts] = -pattern[1]
# # Handle end matches
# end_only = mid_mask.clone()
# end_only[mid_mask] &= end_match & ~start_match
# if torch.any(end_only):
# indices = torch.arange(0, max_rel_length-1, device=relators.device)
# shifted = torch.index_select(relators[end_only], 1, indices)
# shifted = torch.cat([
# -pattern[0].expand(shifted.shape[0], 1),
# shifted
# ], dim=1)
# new_relators[end_only] = shifted
#print("nonzero_counts",nonzero_counts, "max_rel_length",max_rel_length)
mid_mask = nonzero_counts == (max_rel_length - 1)
if torch.any(mid_mask):
start_match = first_elements[mid_mask] == pattern[0]
end_match = last_elements[mid_mask] == pattern[1]
# Handle both matches
both_match = mid_mask.clone()
both_match[mid_mask] &= start_match & end_match
if torch.any(both_match):
indices = torch.arange(1, max_rel_length-2, device=relators.device)
new_relators[both_match,0:-3] = torch.index_select(relators[both_match], 1, indices)
new_relators[both_match,-3:]=0
# Handle start match only
start_only = mid_mask.clone()
start_only[mid_mask] &= start_match & ~end_match
if torch.any(start_only):
indices = torch.arange(1, max_rel_length-1, device=relators.device)