-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathevent_transform.py
More file actions
1393 lines (1094 loc) · 53.1 KB
/
event_transform.py
File metadata and controls
1393 lines (1094 loc) · 53.1 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
from modulefinder import Module
import torch
import torch.nn as nn
from math import pi
import torch.nn.functional as F
# also refer to https://pytorch.org/vision/main/auto_examples/transforms/plot_transforms_illustrations.html#sphx-glr-auto-examples-transforms-plot-transforms-illustrations-py
'''
Note that each transform will regard inputs as floats and output floats
So, an additional tranform (ToEventDomain) will be used as the last output to bound coordinates and round them to long
'''
class ToFloat(nn.Module):
def __init__(self):
super().__init__()
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
return p.float(), y.float(), x.float(), t.float(), valid_mask, target
class ToEventDomain(nn.Module):
def __init__(self, H: int, W: int):
super().__init__()
self.H = H
self.W = W
def extra_repr(self) -> str:
return f'H={self.H}, W={self.W}'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
# y = y.round_()
# x = x.round_()
# p = p.round_()
mask = (y >= 0) & (y < self.H)
mask = mask & (x >= 0) & (x < self.W)
valid_mask = valid_mask & mask
return p, y, x, t, valid_mask, target
class DiscardTail(nn.Module):
def __init__(self, scale_y: float, scale_x: float):
super().__init__()
self.scale_y = scale_y
self.scale_x = scale_x
def extra_repr(self) -> str:
return f'scale_y={self.scale_y:.6f}, scale_x={self.scale_x:.6f}'
@staticmethod
def get_range(v: torch.Tensor, scale: float):
v_m = v.mean()
v_std = v.std()
s = scale * v_std
return v_m - s, v_m + s
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
# valid_mask.shape = [B, L]
mask_y = self.get_range(y, self.scale_y)
mask_x = self.get_range(x, self.scale_x)
valid_mask = valid_mask & (y >= mask_y[0]) & (y <= mask_y[1])
valid_mask = valid_mask & (x >= mask_x[0]) & (x <= mask_x[1])
return p, y, x, t, valid_mask, target
class PositionalNorm(nn.Module):
def __init__(self, H: int, W: int):
# it is better to use after DiscardTail to avoid the noise
super().__init__()
self.H = H
self.W = W
def extra_repr(self) -> str:
return f'H={self.H}, W={self.W}'
@staticmethod
def norm_to_01(v: torch.Tensor):
v_min = v.min()
v_max = v.max()
return (v - v_min) / (v_max - v_min)
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
y = self.norm_to_01(y) * (self.H - 1)
x = self.norm_to_01(x) * (self.W - 1)
return p, y, x, t, valid_mask, target
class RadiusFilter(nn.Module):
def __init__(self, r: float, n_neighbors):
# only keep events with >= n_neighbors events in neighbor area distance <= r
super().__init__()
self.r = r
assert n_neighbors >= 1
self.n_neighbors = n_neighbors
def extra_repr(self) -> str:
return f'r={self.r:.6f}, n_neighbors={self.n_neighbors}'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
# shape = [B, L]
B, L = x.shape
dx = x.view(B, L, 1) - x.view(B, 1, L)
dy = y.view(B, L, 1) - y.view(B, 1, L)
d = torch.square_(dx) + torch.square_(dy) # [B, L, L]
mask = d <= (self.r ** 2)
mask = mask.long().sum(-1) # shape = [B, L]
mask = mask > self.n_neighbors
return p, y, x, t, valid_mask & mask, target
class RandomErasing(nn.Module):
def __init__(self, H: int, W: int, prob: float, h: int, w: int):
super().__init__()
self.H = H
self.W = W
self.prob = prob
self.h = h
self.w = w
def extra_repr(self) -> str:
return (f'H={self.H}, W={self.W}, prob={self.prob:.6f}, h={self.h}, w={self.w}')
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
B = p.shape[0]
cy = torch.rand([B, 1], device=y.device) * (self.H - 1)
cx = torch.rand([B, 1], device=x.device) * (self.W - 1)
h = torch.rand([B, 1], device=y.device) * (self.h / 2)
w = torch.rand([B, 1], device=y.device) * (self.w / 2)
mask = y >= (cy - h)
mask = mask & (y <= (cy + h))
mask = mask & (x >= (cx - w))
mask = mask & (x <= (cx + w))
mask_prob = torch.rand([B, 1], device=x.device) < self.prob
mask = mask & mask_prob
valid_mask = valid_mask & (~mask)
return p, y, x, t, valid_mask, target
class Resize(nn.Module):
def __init__(self, H: int, W: int, h: int, w: int):
super().__init__()
self.H = H
self.W = W
self.h = h
self.w = w
def extra_repr(self) -> str:
return f'scale_y={self.h / self.H:.6f}, scale_x={self.w / self.W:.6f}'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
y = (y + 0.5) / self.H * self.h - 0.5
x = (x + 0.5) / self.W * self.w - 0.5
return p, y, x, t, valid_mask, target
class Downsample(nn.Module):
def __init__(self, H: int, W: int, h: int, w: int):
super().__init__()
self.H = H
self.W = W
self.h = h
self.w = w
def extra_repr(self) -> str:
return f'scale_y={self.h / self.H:.6f}, scale_x={self.w / self.W:.6f}'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
y = (y + 0.5) / self.H * self.h - 0.5
x = (x + 0.5) / self.W * self.w - 0.5
y = y.round().float()
x = x.round().float()
y = (y + 0.5) / self.h * self.H - 0.5
x = (x + 0.5) / self.w * self.W - 0.5
return p, y, x, t, valid_mask, target
class RandomResize(nn.Module):
def __init__(self, scale_y: tuple, scale_x: tuple):
super().__init__()
self.scale_y = scale_y
self.scale_x = scale_x
def extra_repr(self) -> str:
return f'scale_y=({self.scale_y[0]:.6f}, {self.scale_y[1]:.6f}), scale_x=({self.scale_x[0]:.6f}, {self.scale_x[1]:.6f})'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
B = p.shape[0]
scale_y = torch.empty([B, 1], device=y.device, dtype=torch.float).uniform_(self.scale_y[0], self.scale_y[1])
scale_x = torch.empty([B, 1], device=x.device, dtype=torch.float).uniform_(self.scale_x[0], self.scale_x[1])
y = y * scale_y
x = x * scale_x
return p, y, x, t, valid_mask, target
class RandomRotation(nn.Module):
def __init__(self, H: int, W: int, degrees: float or tuple[float]):
super().__init__()
self.H, self.W = H, W
if isinstance(degrees, tuple):
assert len(degrees) == 2
self.degrees = (degrees[0] * pi / 180, degrees[1] * pi / 180)
elif isinstance(degrees, float):
self.degrees = (-degrees * pi / 180, degrees * pi / 180)
else:
raise ValueError(f'degrees must be either a float or a tuple of floats')
self.center_y = (H - 1) / 2
self.center_x = (W - 1) / 2
def extra_repr(self) -> str:
return f'center=({self.center_y:.3f}, {self.center_x:.3f}), degrees=({self.degrees[0] * 180 / pi:.3f}, {self.degrees[1] * 180 / pi:.3f})'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
B = x.shape[0]
theta = torch.empty([B, 1], device=x.device, dtype=torch.float)
theta.uniform_(self.degrees[0], self.degrees[1])
cos_theta = torch.cos(theta)
sin_theta = torch.sin_(theta)
x -= self.center_x
y -= self.center_y
# x = x - self.center_x
# y = y - self.center_y
x_ = x * cos_theta - y * sin_theta
y_ = x * sin_theta + y * cos_theta
x_ += self.center_x
y_ += self.center_y
# x_ = x_ + self.center_x
# y_ = y_ + self.center_y
return p, y_, x_, t, valid_mask, target
class RandomHorizontalFlip(nn.Module):
def __init__(self, W: int, prob: float):
super().__init__()
self.W = W
self.prob = prob
def extra_repr(self) -> str:
return f'W={self.W}, prob={self.prob:.3f}'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
B = x.shape[0]
mask = torch.rand([B, 1], device=x.device) < self.prob
return p, y, torch.where(mask, self.W - 1 - x, x), t, valid_mask, target
class RandomVerticalFlip(nn.Module):
def __init__(self, H: int, prob: float):
super().__init__()
self.H = H
self.prob = prob
def extra_repr(self) -> str:
return f'H={self.H}, prob={self.prob:.3f}'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
B = x.shape[0]
mask = torch.rand([B, 1], device=y.device) < self.prob
return p, torch.where(mask, self.H - 1 - y, y), x, t, valid_mask, target
def crop(y_range: tuple, x_range: tuple, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor,
valid_mask: torch.BoolTensor):
mask = (y >= y_range[0]) & (y <= y_range[1])
mask = mask & (x >= x_range[0]) & (x <= x_range[1])
# we can return p[mask], y[mask], x[mask], valid_mask[mask]
# but the number of events (sequence length) will change
# so, we just set the events to be removed as "padded"
valid_mask = valid_mask & mask
return p, y, x, t, valid_mask
class Crop(nn.Module):
def __init__(self, y_range: tuple, x_range: tuple):
super().__init__()
self.y_range, self.x_range = y_range, x_range
def extra_repr(self) -> str:
return f'y_range=({self.y_range[0]:.3f}, {self.y_range[1]:.3f}), x_range=({self.x_range[0]:.3f}, {self.x_range[1]:.3f})'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
p, y, x, t, valid_mask = crop(self.y_range, self.x_range, p, y, x, t, valid_mask)
return p, y, x, t, valid_mask, target
class CenterCrop(Crop):
def __init__(self, H: int, W: int, size: int or tuple[int]):
if isinstance(size, int):
size = (size, size)
elif isinstance(size, tuple):
assert len(size) == 2
size = (size[0], size[1])
else:
raise ValueError(f'size must be either a int or a tuple of ints')
center_x = W / 2
center_y = H / 2
y_range = (center_y - size[0] / 2, center_y + size[0] / 2)
x_range = (center_x - size[1] / 2, center_x + size[1] / 2)
super().__init__(y_range, x_range)
class RandomCrop(nn.Module):
def __init__(self, H: int, W: int, size: int or tuple[int]):
super().__init__()
self.H = H
self.W = W
if isinstance(size, int):
self.size = (size, size)
elif isinstance(size, tuple):
assert len(size) == 2
self.size = (size[0], size[1])
else:
raise ValueError(f'size must be either a int or a tuple of ints')
def extra_repr(self) -> str:
return f'H={self.H}, W={self.W}, size=({self.size[0]}, {self.size[1]})'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
B = x.shape[0]
y_start = torch.empty([B, 1], device=x.device, dtype=torch.float).uniform_(0, self.H - self.size[0] - 1)
y_end = y_start + self.size[0]
x_start = torch.empty([B, 1], device=x.device, dtype=torch.float).uniform_(0, self.W - self.size[1] - 1)
x_end = x_start + self.size[1]
y_range = (y_start, y_end)
x_range = (x_start, x_end)
p, y, x, t, valid_mask = crop(y_range, x_range, p, y, x, t, valid_mask)
return p, y, x, t, valid_mask, target
class RandomCropResize(nn.Module):
def __init__(self, H: int, W: int, size: int or tuple[int]):
# resize to the original size after crop
super().__init__()
self.H = H
self.W = W
if isinstance(size, int):
self.size = (size, size)
elif isinstance(size, tuple):
assert len(size) == 2
self.size = (size[0], size[1])
else:
raise ValueError(f'size must be either a int or a tuple of ints')
def extra_repr(self) -> str:
return f'H={self.H}, W={self.W}, size=({self.size[0]}, {self.size[1]})'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
B = x.shape[0]
y_start = torch.empty([B, 1], device=x.device, dtype=torch.float).uniform_(0, self.H - self.size[0] - 1)
y_end = y_start + self.size[0]
x_start = torch.empty([B, 1], device=x.device, dtype=torch.float).uniform_(0, self.W - self.size[1] - 1)
x_end = x_start + self.size[1]
y_range = (y_start, y_end)
x_range = (x_start, x_end)
p, y, x, t, valid_mask = crop(y_range, x_range, p, y, x, t, valid_mask)
y = (y - y_start) / self.size[0] * (self.H - 1)
x = (x - x_start) / self.size[1] * (self.W - 1)
return p, y, x, t, valid_mask, target
class RandomChunkDrop(nn.Module):
def __init__(self, n_chunk: int, max_mask_len: int):
super().__init__()
self.n_chunk = n_chunk
self.max_mask_len = max_mask_len
def extra_repr(self) -> str:
return f'n_chunk={self.n_chunk}, max_mask_len={self.max_mask_len}'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
B, L = valid_mask.shape
device = valid_mask.device
# 1. 生成每个 chunk 的随机长度
# shape: [B, n_chunk]
mask_lengths = torch.randint(1, self.max_mask_len + 1, (B, self.n_chunk), device=device)
mask_lengths = mask_lengths * valid_mask.long().sum(1, keepdim=True) / L
# 按实际长度比例进行缩放,避免事件数量太少的样本被全部mask
# 2. 生成每个 chunk 的随机起始位置
# 为防止区间超出边界,我们从 [0, L - 1] 中采样
# shape: [B, n_chunk]
mask_starts = torch.randint(0, L, (B, self.n_chunk), device=device)
# 3. 构建掩码 (高效的向量化方法)
# 创建一个序列索引 [0, 1, ..., L-1]
indices = torch.arange(L, device=device).unsqueeze(0).unsqueeze(1) # shape: [1, 1, L]
# 将 starts 和 lengths 扩展维度以进行广播
starts = mask_starts.unsqueeze(2) # shape: [B, n_chunk, 1]
lengths = mask_lengths.unsqueeze(2) # shape: [B, n_chunk, 1]
ends = starts + lengths # shape: [B, n_chunk, 1]
# 利用广播机制判断每个位置是否在任何一个 chunk 内
# (indices >= starts) & (indices < ends) 会生成一个 [B, n_chunk, L] 的布尔张量
# .any(dim=1) 在 n_chunk 维度上做 OR 操作,得到最终的掩码
mask = (indices >= starts) & (indices < ends)
mask = mask.any(dim=1) # shape: [B, L]
# 4. 应用掩码
valid_mask[mask] = False
return p, y, x, t, valid_mask, target
class RandomShear(nn.Module):
def __init__(self, sy: float, sx: float):
super().__init__()
self.sy = sy
self.sx = sx
def extra_repr(self) -> str:
return f'sy={self.sy:.3f}, sx={self.sx:.3f}'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
B = x.shape[0]
sy = torch.empty([B, 1], device=y.device, dtype=torch.float).uniform_(-self.sy, self.sy)
sx = torch.empty([B, 1], device=x.device, dtype=torch.float).uniform_(-self.sx, self.sx)
y_ = y + sy * x
x_ = x + sx * y
return p, y_, x_, t, valid_mask, target
class RandomTranslate(nn.Module):
def __init__(self, dy: int, dx: int):
super().__init__()
self.dy = dy
self.dx = dx
def extra_repr(self) -> str:
return f'dy={self.dy}, dx={self.dx}'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
B = x.shape[0]
dy = torch.empty([B, 1], device=y.device, dtype=torch.float).uniform_(-self.dy, self.dy)
dx = torch.empty([B, 1], device=x.device, dtype=torch.float).uniform_(-self.dx, self.dx)
y = y + dy
x = x + dx
return p, y, x, t, valid_mask, target
class RandomTemporalWrap(nn.Module):
def __init__(self, scale_low: float, scale_high: float):
super().__init__()
self.scale_low = scale_low
self.scale_high = scale_high
assert scale_high > scale_low
def extra_repr(self) -> str:
return f'scale={self.scale_low:.3f}, {self.scale_high:.3f}'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
if t.dtype != torch.float:
print(t.dtype)
exit(-1)
'''
考虑到valid_mask,t可能是类似
0 1 2 3 4 x x x ...
diff得到
1 1 1 1 x x x x ..
cumsum得到
1 2 3 4
'''
invalid_mask = ~valid_mask
diff_t = torch.diff(t, dim=1)
diff_t[invalid_mask[:, 1:]] = 0.
scale = torch.rand_like(diff_t) * (self.scale_high - self.scale_low) + self.scale_low
# diff_t *= scale
diff_t = diff_t * scale
t = torch.cat((t[:, 0:1], t[:, 0:1] + torch.cumsum(diff_t, dim=1)), dim=1)
t[invalid_mask] = -1.
return p, y, x, t, valid_mask, target
class RandomChunkWrap(nn.Module):
"""
正确实现的时间扭曲 (Time Warping) 版本。
此版本通过缩放时间差 (delta t, 或 dt),然后重建绝对时间戳 t,
来模拟事件流在随机区块内的速度变化。
这保证了时间戳的单调递增性,无需进行代价高昂且物理意义
不明确的排序操作。
"""
def __init__(self, n_chunk: int, max_mask_ratio: float, scale_low: float, scale_high: float):
super().__init__()
self.n_chunk = n_chunk
assert 0.0 < max_mask_ratio <= 1.0, "max_mask_ratio 必须在 (0, 1] 范围内"
self.max_mask_ratio = max_mask_ratio
self.scale_low = scale_low
self.scale_high = scale_high
def extra_repr(self) -> str:
return f'n_chunk={self.n_chunk}, max_mask_ratio={self.max_mask_ratio}'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
if t.dtype != torch.float:
print(t.dtype)
exit(-1)
B, L = valid_mask.shape
device = valid_mask.device
# --- 1. 计算要修改的 mask ---
# (这部分逻辑与之前完全相同)
event_lengths = valid_mask.sum(dim=1)
max_len_per_item = (event_lengths * self.max_mask_ratio).unsqueeze(1)
mask_lengths = (torch.rand(B, self.n_chunk, device=device) * max_len_per_item).int().clamp(min=1)
mask_starts = torch.randint(0, L, (B, self.n_chunk), device=device)
indices = torch.arange(L, device=device).unsqueeze(0).unsqueeze(1) # shape: [1, 1, L]
starts = mask_starts.unsqueeze(2) # shape: [B, n_chunk, 1]
lengths = mask_lengths.unsqueeze(2) # shape: [B, n_chunk, 1]
ends = starts + lengths # shape: [B, n_chunk, 1]
mask = (indices >= starts) & (indices < ends)
mask = mask.any(dim=1) # shape: [B, L]
# 关键:只在 'valid_mask' 为 True 的地方应用我们生成的 'mask'
mask = valid_mask & mask
# --- 2. 【核心修改】对 delta t (dt) 进行操作 ---
# 2a. 计算 delta t (dt)
# 我们使用 t[i] - t[i-1],并假设 t[0] 的差值是 t[0] - 0
# t.new_zeros((B, 1)) 确保在正确设备上创建 (B, 1) 的 0 张量
dt = torch.diff(t, dim=1, prepend=t.new_zeros((B, 1)))
# 2b. 生成缩放因子 (scale)
# 我们需要为 t 张量中的每个元素生成一个 scale
# (更高效的方法是只为 mask=True 的地方生成, 但
# 为整个张量生成再用 mask 替换更简洁)
#
# scale shape: [B, L]
scale = torch.rand(B, L, device=device) * (self.scale_high - self.scale_low) + self.scale_low
# 2c. 只在 mask 为 True 的地方应用缩放
# dt[mask] = dt[mask] * scale[mask]
# (注意:上面的操作在 torch < 1.9 中可能效率不高,用 where 更安全)
# 使用 torch.where:
# dt_scaled = dt * scale
# dt = torch.where(mask, dt_scaled, dt)
# 最直接的索引赋值 (在现代 PyTorch 中是高效的)
# 我们只缩放被选中的 dt
dt[mask] = dt[mask] * scale[mask]
# 2d. 从被缩放的 dt 重建 t
# (t_new[i] = dt[0] + dt[1] + ... + dt[i])
t_new = torch.cumsum(dt, dim=1)
# 3. 返回结果
# p, y, x, valid_mask, target 根本不需要改变!
# 我们只返回新的、时间上单调递增的 t_new。
return p, y, x, t_new, valid_mask, target
class RandomReplaceByNoise(nn.Module):
def __init__(self, H: int, W: int, p_replace: float):
super().__init__()
self.H = H
self.W = W
self.p_replace = p_replace
def extra_repr(self) -> str:
return f'H={self.H}, W={self.W}, p_replace={self.p_replace:.3f}'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
replace_mask = torch.rand_like(p, dtype=torch.float) < self.p_replace
replace_mask = replace_mask.logical_and(valid_mask)
noise_x = torch.rand_like(x, dtype=torch.float) * (self.W - 1)
noise_y = torch.rand_like(y, dtype=torch.float) * (self.H - 1)
noise_p = torch.randint(low=0, high=2, size=p.shape, device=p.device).float()
x[replace_mask] = noise_x[replace_mask]
y[replace_mask] = noise_y[replace_mask]
p[replace_mask] = noise_p[replace_mask]
return p, y, x, t, valid_mask, target
class RandomDrop(nn.Module):
def __init__(self, p_drop: float):
super().__init__()
self.p_drop = p_drop
def extra_repr(self) -> str:
return f'p_drop={self.p_drop}'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
keep_mask = torch.rand_like(p, dtype=torch.float) > self.p_drop
valid_mask = torch.logical_and(valid_mask, keep_mask)
return p, y, x, t, valid_mask, target
class RandomPolarityFlip(nn.Module):
def __init__(self, p_flip: float):
super().__init__()
self.p_flip = p_flip
def extra_repr(self) -> str:
return f'p_flip={self.p_flip}'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
mask = torch.rand_like(p) < self.p_flip
mask = mask & valid_mask
p[mask] = 1 - p[mask]
return p, y, x, t, valid_mask, target
class Sequential(nn.Sequential):
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
for module in self:
p, y, x, t, valid_mask, target = module(p, y, x, t, valid_mask, target)
return p, y, x, t, valid_mask, target
class RandomApply(nn.ModuleList):
def __init__(self, prob: float, *args):
super().__init__()
self.prob = prob
for m in args:
self.append(m)
def extra_repr(self) -> str:
return super().extra_repr() + f', prob={self.prob:.3f}'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
mask = torch.rand(len(self)) < self.prob
for i in range(len(self)):
if mask[i]:
p, y, x, t, valid_mask, target = self[i](p, y, x, t, valid_mask, target)
return p, y, x, t, valid_mask, target
class RandomShuffleApply(nn.ModuleList):
def __init__(self, prob: float, *args):
super().__init__()
self.prob = prob
for m in args:
self.append(m)
def extra_repr(self) -> str:
return super().extra_repr() + f', prob={self.prob:.3f}'
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
mask = torch.rand(len(self)) < self.prob
indices = torch.randperm(len(self))
for i in range(len(self)):
if mask[i]:
p, y, x, t, valid_mask, target = self[indices[i].item()](p, y, x, t, valid_mask, target)
return p, y, x, t, valid_mask, target
class RandomChoice(nn.ModuleList):
def __init__(self, *args):
super().__init__()
for arg in args:
self.append(arg)
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
i = torch.randint(low=0, high=len(self), size=[1]).item()
return self[i](p, y, x, t, valid_mask, target)
class Identity(nn.Module):
def __init__(self):
super().__init__()
def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, t: torch.Tensor, valid_mask: torch.BoolTensor, target: torch.Tensor):
return p, y, x, t, valid_mask, target
class TransformWrapper(nn.Module):
def __init__(self, train_transforms: nn.Module, test_transforms: nn.Module):
super().__init__()
self.train_transforms = train_transforms
self.test_transforms = test_transforms
def forward(self, p, y, x, t, valid_mask, target):
if self.training:
return self.train_transforms(p, y, x, t, valid_mask, target)
else:
return self.test_transforms(p, y, x, t, valid_mask, target)
def parse_transforms(transform_args: str):
transform_args = transform_args.split('/')
transforms = []
for item in transform_args:
if item.startswith('DiscardTail-'):
# DiscardTail-{scale}
item = item.split('-')[1].split(',')
scale_y = float(item[0])
scale_x = float(item[1])
transforms.append(DiscardTail(scale_y, scale_x))
elif item.startswith('PositionalNorm-'):
# PositionalNorm-{H,W}
item = item.split('-')[1].split(',')
H = int(item[0])
W = int(item[1])
transforms.append(PositionalNorm(H, W))
elif item.startswith('RadiusFilter-'):
# RadiusFilter-{r,n_neighbors}
item = item.split('-')[1].split(',')
r = float(item[0])
n_neighbors = int(item[1])
transforms.append(RadiusFilter(r, n_neighbors))
elif item.startswith('RandomErasing-'):
# RandomErasing-{H,W}-{prob}-{h,w}
item = item.split('-')
HW = item[1].split(',')
H = int(HW[0])
W = int(HW[1])
prob = float(item[2])
hw = item[3].split(',')
h = int(hw[0])
w = int(hw[1])
transforms.append(RandomErasing(H=H, W=W, prob=prob, h=h, w=w))
elif item.startswith('Resize-'):
# Resize-{H,W}-{h,w}
item = item.split('-')
temp = item[1].split(',')
H = int(temp[0])
W = int(temp[1])
temp = item[2].split(',')
h = int(temp[0])
w = int(temp[1])
transforms.append(Resize(H=H, W=W, h=h, w=w))
elif item.startswith('Downsample-'):
# Downsample-{H,W}-{h,w}
item = item.split('-')
temp = item[1].split(',')
H = int(temp[0])
W = int(temp[1])
temp = item[2].split(',')
h = int(temp[0])
w = int(temp[1])
transforms.append(Downsample(H=H, W=W, h=h, w=w))
elif item.startswith('RandomResize-'):
# RandomResize-{scale_y[0],scale_y[1]}-{scale_x[0],scale_x[1]}
item = item.split('-')
scale_y = item[1].split(',')
scale_x = item[2].split(',')
scale_y = (float(scale_y[0]), float(scale_y[1]))
scale_x = (float(scale_x[0]), float(scale_x[1]))
transforms.append(RandomResize(scale_y, scale_x))
elif item.startswith('RandomRotation-'):
# RandomRotation-{H,W}-{degrees}
# RandomRotation-{H,W}-{degrees[0],degrees[1]}
item = item.split('-')
HW = item[1].split(',')
H = int(HW[0])
W = int(HW[1])
if ',' in item[2]:
degrees = item[2].split(',')
degrees = (float(degrees[0]), float(degrees[1]))
else:
degrees = float(item[2])
transforms.append(RandomRotation(H, W, degrees))
elif item.startswith('RandomHorizontalFlip-'):
# RandomHorizontalFlip-{W}-{prob}
item = item.split('-')
W = int(item[1])
prob = float(item[2])
transforms.append(RandomHorizontalFlip(W, prob))
elif item.startswith('RandomVerticalFlip-'):
# RandomVerticalFlip-{H}-{prob}
item = item.split('-')
H = int(item[1])
prob = float(item[2])
transforms.append(RandomVerticalFlip(H, prob))
elif item.startswith('Crop-'):
# Crop-{y_range[0],y_range[1]}-{x_range[0],x_range[1]}
item = item.split('-')
y_range = item[1].split(',')
y_range = (int(y_range[0]), int(y_range[1]))
x_range = item[2].split(',')
x_range = (int(x_range[0]), int(x_range[1]))
transforms.append(Crop(y_range, x_range))
elif item.startswith('CenterCrop-'):
# CenterCrop-{H,W}-{size}
# CenterCrop-{H,W}-{size[0],size[1]}
item = item.split('-')
HW = item[1].split(',')
H = int(HW[0])
W = int(HW[1])
if ',' in item[2]:
size = item[2].split(',')
size = (int(size[0]), int(size[1]))
else:
size = int(item[2])
transforms.append(CenterCrop(H, W, size))
elif item.startswith('RandomCrop-'):
# RandomCrop-{H,W}-{size}
# RandomCrop-{H,W}-{size[0],size[1]}
item = item.split('-')
HW = item[1].split(',')
H = int(HW[0])
W = int(HW[1])
if ',' in item[2]:
size = item[2].split(',')
size = (int(size[0]), int(size[1]))
else:
size = int(item[2])
transforms.append(RandomCrop(H, W, size))
elif item.startswith('RandomCropResize-'):
# RandomCropResize-{H,W}-{size}
# RandomCropResize-{H,W}-{size[0],size[1]}
item = item.split('-')
HW = item[1].split(',')
H = int(HW[0])
W = int(HW[1])
if ',' in item[2]:
size = item[2].split(',')
size = (int(size[0]), int(size[1]))
else:
size = int(item[2])
transforms.append(RandomCropResize(H, W, size))
elif item.startswith('RandomShear-'):
# RandomShear-{sy,sx}
item = item.split('-')[1].split(',')
sy = float(item[0])
sx = float(item[1])
transforms.append(RandomShear(sy, sx))
elif item.startswith('RandomTranslate-'):
# RandomTranslate-{dy,dx}
item = item.split('-')[1].split(',')
dy = int(item[0])
dx = int(item[1])
transforms.append(RandomTranslate(dy, dx))
elif item.startswith('RandomChunkDrop-'):
# RandomChunkDrop-{n_chunk,max_mask_len}
item = item.split('-')[1].split(',')
n_chunk = int(item[0])
max_mask_len = int(item[1])
transforms.append(RandomChunkDrop(n_chunk, max_mask_len))
elif item.startswith('RandomChunkWrap-'):
# RandomChunkWrap-{n_chunk,max_mask_ratio}-{scale_low,scale_high}
item = item.split('-')
temp = item[1].split(',')
n_chunk = int(temp[0])
max_mask_ratio = float(temp[1])
temp = item[2].split(',')
scale_low = float(temp[0])
scale_high = float(temp[1])
transforms.append(RandomChunkWrap(n_chunk, max_mask_ratio, scale_low, scale_high))
elif item.startswith('RandomPolarityFlip-'):
# RandomPolarityFlip-{p_flip}
p_flip = float(item.split('-')[1])
transforms.append(RandomPolarityFlip(p_flip))
elif item.startswith('RandomTemporalWrap-'):
# RandomTemporalWrap-{scale_low,scale_high}
item = item.split('-')[1].split(',')
scale_low = float(item[0])
scale_high = float(item[1])
transforms.append(RandomTemporalWrap(scale_low, scale_high))
elif item.startswith('RandomDrop-'):
# RandomDrop-{p_drop}
p_drop = float(item.split('-')[1])
transforms.append(RandomDrop(p_drop))
elif item.startswith('RandomReplaceByNoise-'):
# RandomReplaceByNoise-{H,W}-{p_replace}
item = item.split('-')
temp = item[1].split(',')
H = int(temp[0])
W = int(temp[1])
p_replace = float(item[2])
transforms.append(RandomReplaceByNoise(H=H, W=W, p_replace=p_replace))
else:
raise NotImplementedError(item)
return transforms
# class EventTransforms(Sequential):
# def forward(self, p: torch.Tensor, y: torch.Tensor, x: torch.Tensor, valid_mask: torch.BoolTensor):
# # 使用分组采样时,数据就需要展平了
# shape = p.shape
# p = p.flatten(1)
# y = y.flatten(1)
# x = x.flatten(1)
# valid_mask = valid_mask.flatten(1)
# p, y, x, valid_mask = super().forward(p, y, x, valid_mask)
# p = p.reshape(shape)
# y = y.reshape(shape)
# x = x.reshape(shape)
# valid_mask = valid_mask.reshape(shape)
# return p, y, x, valid_mask
def get_transform_module(train_transform_args: str, train_transform_policy: str, test_transform_args: str, H: int,
W: int, h: int, w: int):
if train_transform_args is not None and train_transform_args != 'none' and train_transform_args != '':
train_transforms = parse_transforms(train_transform_args)
if train_transform_policy == 'Sequential':
train_transforms = Sequential(*train_transforms)
elif train_transform_policy.startswith('RandomApply-'):
# RandomApply-{prob}
prob = float(train_transform_policy.split('-')[1])
train_transforms = RandomApply(prob, *train_transforms)
elif train_transform_policy.startswith('RandomShuffleApply-'):
# RandomShuffleApply-{prob}
prob = float(train_transform_policy.split('-')[1])
train_transforms = RandomShuffleApply(prob, *train_transforms)
elif train_transform_policy == 'RandomChoice':
train_transforms.append(Identity())
train_transforms = RandomChoice(*train_transforms)
else:
raise ValueError(train_transform_policy)
else:
train_transforms = Identity()
if test_transform_args is None or test_transform_args == '' or test_transform_args == 'none':
test_transforms = Identity()
else:
test_transforms = Sequential(*parse_transforms(test_transform_args))
tfs = [
ToFloat(),
TransformWrapper(train_transforms=train_transforms, test_transforms=test_transforms),
]
if h == H and w == W:
tfs.append(ToEventDomain(H, W))
pass
else:
tfs.append(Resize(H=H, W=W, h=h, w=w))
tfs.append(ToEventDomain(h, w))