Repository navigation
Expand file tree
/
Copy pathDNA_modeling.py
More file actions
2174 lines (1876 loc) · 92.6 KB
/
Copy pathDNA_modeling.py
File metadata and controls
2174 lines (1876 loc) · 92.6 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
'''
This script provides DNA foundation model adaptation strategies.
With independent masking channel
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.attention import sdpa_kernel, SDPBackend
from torch.utils.checkpoint import checkpoint_sequential
from functools import partial
# Core dependency: Borzoi/Flashzoi backbone
try:
from borzoi_pytorch import Borzoi
except Exception as e:
raise ImportError(
"Missing dependency `borzoi-pytorch`. Install it from PyPI (see "
"`https://github.com/johahi/borzoi-pytorch`) and ensure it is importable."
) from e
# Optional dependencies: used for speed (flash-attn) and PEFT fine-tuning.
try:
from peft import LoraConfig, get_peft_model, TaskType
except Exception:
LoraConfig = None
get_peft_model = None
TaskType = None
try:
from flash_attn import flash_attn_func
from flash_attn.layers.rotary import RotaryEmbedding
except Exception:
flash_attn_func = None
RotaryEmbedding = None
import time
import math
import numpy as np
import random
import os
import sys
import hashlib
from collections import OrderedDict
class CellSpecificCCREBias(nn.Module):
"""
Learn cell- and distance-specific additive logit bias for cCRE tokens.
- Uses: token embedding X, cell embedding z_cell, coarse distance bin (short/mid/long).
- Outputs: bias_ij in [-max_bias, max_bias] for each position j in batch i.
- Applied *only* to cCRE tokens; non-cCRE and padded tokens get 0 bias.
- Optionally mean-centers bias over cCREs per sample to focus on relative priorities.
"""
def __init__(self, dim=1536, cell_dim=128, num_distance_bins=3,
max_bias: float = 3.0, normalize_per_sample: bool = True):
super().__init__()
self.max_bias = float(max_bias)
self.normalize_per_sample = bool(normalize_per_sample)
self.cell_encoder = nn.Sequential(
nn.Linear(cell_dim, 128),
nn.LayerNorm(128),
nn.GELU(),
nn.Linear(128, 128)
)
# Distance bin embeddings (e.g. short/mid/long)
self.distance_embed = nn.Embedding(num_distance_bins, num_distance_bins)
# Predictor: [X || cell_ctx || dist_embed] -> scalar bias
in_dim = dim + 128 + num_distance_bins
self.importance_predictor = nn.Sequential(
nn.Linear(in_dim, 256),
nn.LayerNorm(256),
nn.GELU(),
nn.Linear(256, 64),
nn.GELU(),
nn.Linear(64, 1)
)
def forward(self, X, z_cell, distances_bp, ccre_mask):
"""
Args:
X: (B, L, dim) token embeddings
z_cell: (B, cell_dim) cell embedding
distances_bp: (B, L) bp distances from perturbation anchor (>= 0)
ccre_mask: (B, L) bool True = cCRE token (not perturb, not padding)
Returns:
ccre_bias: (B, L) float additive logit bias for cCRE tokens
"""
B, L, dim = X.shape
device = X.device
dtype = X.dtype
# encode cell: (B, 128) -> broadcast to (B, L, 128)
z_cell_enc = self.cell_encoder(z_cell) # (B, 128)
z_cell_exp = z_cell_enc.unsqueeze(1).expand(-1, L, -1) # (B, L, 128)
# distance bins: 0 (short), 1 (mid), 2 (long)
d_kb = (distances_bp.to(dtype) / 1000.0) # (B, L)
dist_bins = torch.zeros(B, L, device=device, dtype=torch.long) # default short
mid_mask = (d_kb >= 10.0) & (d_kb < 100.0)
long_mask = (d_kb >= 100.0)
dist_bins[mid_mask] = 1
dist_bins[long_mask] = 2 # (B, L)
dist_embed = self.distance_embed(dist_bins) # (B, L, num_distance_bins)
# predictor input: (B, L, dim + 128 + num_distance_bins)
predictor_input = torch.cat([X, z_cell_exp, dist_embed.to(dtype)], dim=-1)
raw = self.importance_predictor(predictor_input).squeeze(-1) # (B, L)
# map to [-max_bias, max_bias]
bias = self.max_bias * torch.tanh(raw) # (B, L)
# apply only to cCRE tokens
ccre_mask_f = ccre_mask.float()
bias = bias * ccre_mask_f # (B, L)
# optional per-sample centering over cCREs
if self.normalize_per_sample:
denom = ccre_mask_f.sum(dim=-1, keepdim=True).clamp_min(1.0)
mean_bias = (bias * ccre_mask_f).sum(dim=-1, keepdim=True) / denom
bias = (bias - mean_bias) * ccre_mask_f # (B, L)
return bias
class StructuredCCREDropout(nn.Module):
"""
Biologically motivated dropout that keeps the closest cCREs to the perturbation
while randomly dropping redundant distal ones during training.
"""
def __init__(self, keep_closest_n: int = 2, base_drop_prob: float = 0.2):
super().__init__()
self.keep_closest_n = max(0, int(keep_closest_n))
self.base_drop_prob = float(base_drop_prob)
def forward(
self,
ccre_mask: torch.Tensor,
perturbation_mask: torch.Tensor,
distances_bp: torch.Tensor,
) -> torch.Tensor:
"""
Args:
ccre_mask: (B, L) bool tensor indicating current cCRE tokens (excludes perturbation).
perturbation_mask: (B, L) bool tensor marking perturbation bins.
distances_bp: (B, L) float tensor with distances to perturbation anchor in bp.
Returns:
(B, L) bool tensor with a subset of distal cCREs dropped.
"""
if (
(not self.training)
or self.keep_closest_n <= 0
or self.base_drop_prob <= 0.0
):
return ccre_mask
B, _ = ccre_mask.shape
device = ccre_mask.device
augmented = ccre_mask.clone()
for b in range(B):
valid = ccre_mask[b] & (~perturbation_mask[b])
ccre_indices = torch.where(valid)[0]
num_ccres = ccre_indices.numel()
if num_ccres <= self.keep_closest_n:
continue # nothing to drop
dists = distances_bp[b, ccre_indices]
sorted_indices = torch.argsort(dists)
keep_core = ccre_indices[sorted_indices[: self.keep_closest_n]]
distal = ccre_indices[sorted_indices[self.keep_closest_n :]]
if distal.numel() == 0:
continue
drop_prob = min(self.base_drop_prob, 2.0 / float(num_ccres))
# sample Bernoulli per distal cCRE
drop_mask = torch.rand(
distal.shape[0], device=device, dtype=distances_bp.dtype
) < drop_prob
if drop_mask.any():
augmented[b, distal[drop_mask]] = False
# ensure closest cCREs are always kept
augmented[b, keep_core] = True
return augmented
def build_attn_bias(pos_q: torch.Tensor, pos_k: torch.Tensor, tau: float = 16.0, quadratic: bool = False):
"""
pos_q: (B, Lq) continuous coords centered at perturbation
pos_k: (B, Lk) continuous coords centered at perturbation
Returns: (B,1,Lq,Lk) additive bias to feed into SDPA. Larger |d| => more negative.
"""
d = pos_q[:, None, :, None] - pos_k[:, None, None, :] # (B,1,Lq,Lk)
if quadratic:
return -(d * d) / (2.0 * (tau ** 2))
else:
return -d.abs() / tau
def build_rope_cache(L: int, Dh: int, base: float = 10000.0, device=None, dtype=torch.float32):
"""
Returns cos, sin with shapes (1, 1, L, Dh) for half-dim rotations.
Assumes Dh is even. Compute in fp32 and cast later for stability.
"""
assert Dh % 2 == 0, "RoPE head dim must be even."
device = device or torch.device('cpu')
# frequencies for each pair (even/odd)
half = Dh // 2
# inv_freq: (half,) — standard RoPE geometric progression
inv_freq = 1.0 / (base ** (torch.arange(0, half, device=device, dtype=dtype) / half)) # (half,)
# positions: (L,)
t = torch.arange(L, device=device, dtype=dtype)
# angles: (L, half)
angles = torch.einsum('l,d->ld', t, inv_freq)
# expand to (1,1,L,half) for broadcasting over (B,H)
cos = torch.cos(angles)[None, None, :, :] # (1,1,L,half)
sin = torch.sin(angles)[None, None, :, :] # (1,1,L,half)
# we'll use these to rotate [x_even, x_odd]
return cos, sin
def apply_rope(x: torch.Tensor, pos: torch.Tensor, base: float = 10000.0):
"""
x: (B, H, L, Dh) — queries or keys
pos: (B, L) or (1, L) integer positions for this stream
Returns rotated x with same shape. Computes cos/sin in fp32 then casts to x.dtype.
NOTE: If L varies per batch, you can pre-compute a max-length cache and slice.
"""
B, H, L, Dh = x.shape
assert Dh % 2 == 0
# Build cos/sin cache at fp32 for numeric stability
cos, sin = build_rope_cache(L=L, Dh=Dh, base=base, device=x.device, dtype=torch.float32)
# Allow per-batch offsets by indexing cos/sin with pos if needed.
# If pos is not the trivial [0..L-1], we "gather" positions; else, fast path.
# pos: (B,L) — clamp just in case
if pos.dim() == 2 and (not torch.equal(pos, torch.arange(L, device=pos.device).expand(B, -1))):
pos = pos.clamp_(0, L-1)
# gather cos/sin per batch position: (B,1,L,half)
cos = cos.expand(B, 1, L, Dh//2).gather(2, pos[:, None, :, None].expand(B,1,L,Dh//2))
sin = sin.expand(B, 1, L, Dh//2).gather(2, pos[:, None, :, None].expand(B,1,L,Dh//2))
else:
# broadcast to (B,1,L,half)
cos = cos.expand(B, 1, L, Dh//2)
sin = sin.expand(B, 1, L, Dh//2)
# cast to x.dtype (bf16-safe after computing in fp32)
cos = cos.to(dtype=x.dtype)
sin = sin.to(dtype=x.dtype)
# split even/odd
x_even = x[..., 0::2] # (B,H,L,half)
x_odd = x[..., 1::2] # (B,H,L,half)
# rotation: [x_even, x_odd] -> [x_even*cos - x_odd*sin, x_even*sin + x_odd*cos]
x_rot_even = x_even * cos - x_odd * sin
x_rot_odd = x_even * sin + x_odd * cos
# interleave back to (B,H,L,Dh)
# stack & reshape to original layout
x_out = torch.empty_like(x)
x_out[..., 0::2] = x_rot_even
x_out[..., 1::2] = x_rot_odd
return x_out
def build_ccre_mask(L, ccre_intervals_rel, bp_per_token=128.0, device=None):
"""
Build cCRE mask on GPU (shared across batch).
Args:
L: number of tokens along sequence
ccre_intervals_rel: list[(start_bp, end_bp)] in bp, relative to window
bp_per_token: bp covered by a single token at current resolution
device: torch.device
Returns:
(L,) bool tensor on GPU, all ops GPU-native.
"""
if ccre_intervals_rel is None or len(ccre_intervals_rel) == 0:
return torch.zeros(L, device=device, dtype=torch.bool)
iv = torch.tensor(ccre_intervals_rel, device=device, dtype=torch.float32) # (N, 2)
starts = (iv[:, 0] / bp_per_token).round().to(torch.long)
ends = (iv[:, 1] / bp_per_token).round().to(torch.long)
s = torch.clamp(torch.minimum(starts, ends), 0, L - 1)
e = torch.clamp(torch.maximum(starts, ends), 0, L - 1)
diff = torch.zeros(L + 1, device=device, dtype=torch.int32)
if s.numel() > 0:
diff.scatter_add_(0, s, torch.ones_like(s, dtype=torch.int32))
e1 = torch.clamp(e + 1, max=L)
diff.scatter_add_(0, e1, -torch.ones_like(e1, dtype=torch.int32))
return diff.cumsum(0)[:L] > 0 # (L,) bool
def compress_after_transformer_fast(
feat,
mask_128,
ccre_intervals_rel=None,
distal_stride_tokens=1,
bp_per_token=None,
):
"""
Fast compression with adaptive resolution support:
- full-resolution perturbation region
- pooled flanks at stride k
- cCRE + perturbation bins marked via keep_regions_mask
- adaptive resolution: bp_per_token can be float or tensor (B, L) or (L,)
feat: (B, L, C) # after transformer at *current* resolution
mask_128: (B, 1, L) # mask at same resolution as feat
ccre_intervals_rel: list of (start_bp, end_bp) tuples
distal_stride_tokens: pooling stride for distal (non-perturbation) regions
bp_per_token: bp covered by a single token of `feat`
- float: uniform resolution (default: 128.0)
- tensor (B, L) or (L,): per-token adaptive resolution
Returns: (feat_comp, mask_comp, width_comp_bp, keep_regions_mask)
feat_comp: (B, L_out, C) compressed features
mask_comp: (B, 1, L_out) pooled perturbation mask
width_comp_bp: (B, 1, L_out) width per token in bp
keep_regions_mask: (B, 1, L_out) True = cCRE/pert bin, used by SPE
"""
B, L, C = feat.shape
device = feat.device
k = distal_stride_tokens
# Handle adaptive resolution: normalize bp_per_token to (B, L) tensor
if bp_per_token is None:
bp_per_token = 128.0
if isinstance(bp_per_token, (int, float)):
# Uniform resolution: broadcast to (B, L)
bp_per_token_tensor = torch.full((B, L), float(bp_per_token), device=device, dtype=torch.float32)
bp_per_token_scalar = float(bp_per_token)
elif isinstance(bp_per_token, torch.Tensor):
if bp_per_token.dim() == 1 and bp_per_token.shape[0] == L:
# (L,) -> broadcast to (B, L)
bp_per_token_tensor = bp_per_token.unsqueeze(0).expand(B, -1).to(device=device, dtype=torch.float32)
bp_per_token_scalar = bp_per_token.mean().item() # For backward compat with build_ccre_mask
elif bp_per_token.dim() == 2 and bp_per_token.shape == (B, L):
# (B, L) -> use as is
bp_per_token_tensor = bp_per_token.to(device=device, dtype=torch.float32)
bp_per_token_scalar = bp_per_token.mean().item() # For backward compat with build_ccre_mask
else:
raise ValueError(f"bp_per_token tensor must be (L,) or (B, L), got {bp_per_token.shape}")
else:
raise TypeError(f"bp_per_token must be float or tensor, got {type(bp_per_token)}")
# ---------- 1. Build keep_mask = perturbation OR cCRE ----------
pert_mask = (mask_128.squeeze(1) != 0) # (B, L)
keep_mask = pert_mask.clone() # (B, L)
# Detect per-sample vs shared cCRE intervals
is_per_sample = (
ccre_intervals_rel is not None
and isinstance(ccre_intervals_rel, (list, tuple))
and len(ccre_intervals_rel) == B
and any(
(samp is not None)
and isinstance(samp, (list, tuple))
and (len(samp) == 0 or (isinstance(samp[0], (list, tuple)) and len(samp[0]) == 2))
for samp in ccre_intervals_rel
)
)
if ccre_intervals_rel is not None and len(ccre_intervals_rel) > 0 and not is_per_sample:
# Single shared cCRE definition
valid_intervals = [
iv for iv in ccre_intervals_rel
if iv is not None and isinstance(iv, (list, tuple)) and len(iv) == 2
]
if valid_intervals:
# Use mean resolution for cCRE mask building (backward compat)
ccre_mask = build_ccre_mask(
L,
valid_intervals,
bp_per_token=bp_per_token_scalar,
device=device,
) # (L,)
keep_mask = keep_mask | ccre_mask.unsqueeze(0) # (B, L)
if not is_per_sample:
has_any_keep = keep_mask.any(dim=1) # (B,)
if not has_any_keep.all():
center = L // 2
span = min(L, 512)
fallback = torch.zeros(L, device=device, dtype=torch.bool)
fallback[max(0, center - span // 2):min(L, center + span // 2)] = True
keep_mask[~has_any_keep] = fallback
# ---------- 2. Helper to pool a segment (left/right flanks) with adaptive resolution ----------
def pool_segment(feat_seg, mask_seg, keep_seg, k, bp_per_token_seg):
"""
feat_seg: (L_seg, C)
mask_seg: (1, L_seg)
keep_seg: (L_seg,) bool
bp_per_token_seg: (L_seg,) tensor of bp per token for this segment
Returns:
feat_p: (L_seg_out, C)
mask_p: (1, L_seg_out)
keep_p: (L_seg_out,) bool
width_p: (1, L_seg_out) in bp
"""
L_seg = feat_seg.shape[0]
if L_seg == 0:
return (
feat_seg.new_empty(0, C),
mask_seg.new_empty(1, 0),
keep_seg.new_empty(0, dtype=torch.bool),
mask_seg.new_empty(1, 0),
)
n_full = (L_seg // k) * k
parts_f, parts_m, parts_k, parts_w = [], [], [], []
if n_full > 0:
feat_main = feat_seg[:n_full].view(n_full // k, k, C).mean(dim=1) # (L_main, C)
mask_main = mask_seg[:, :n_full].view(1, n_full // k, k).amax(dim=-1) # (1, L_main)
keep_main = keep_seg[:n_full].view(n_full // k, k).any(dim=-1) # (L_main,)
# Adaptive resolution: sum bp_per_token for each pooled block
bp_main = bp_per_token_seg[:n_full].view(n_full // k, k).sum(dim=1) # (L_main,)
width_main = bp_main.unsqueeze(0) # (1, L_main)
parts_f.append(feat_main)
parts_m.append(mask_main)
parts_k.append(keep_main)
parts_w.append(width_main)
if n_full < L_seg:
feat_tail = feat_seg[n_full:].mean(dim=0, keepdim=True) # (1, C)
mask_tail = mask_seg[:, n_full:].amax(dim=-1, keepdim=True) # (1, 1)
keep_tail = keep_seg[n_full:].any().unsqueeze(0) # (1,)
# Adaptive resolution: sum bp_per_token for tail
width_tail = bp_per_token_seg[n_full:].sum().unsqueeze(0).unsqueeze(0) # (1, 1)
parts_f.append(feat_tail)
parts_m.append(mask_tail)
parts_k.append(keep_tail)
parts_w.append(width_tail)
feat_p = torch.cat(parts_f, dim=0) # (L_seg_out, C)
mask_p = torch.cat(parts_m, dim=1) # (1, L_seg_out)
keep_p = torch.cat(parts_k, dim=0) # (L_seg_out,)
width_p = torch.cat(parts_w, dim=1) # (1, L_seg_out)
return feat_p, mask_p, keep_p, width_p
# ---------- 3. Per-sample processing ----------
feat_chunks, mask_chunks, width_chunks, keep_chunks = [], [], [], []
for b in range(B):
feat_b = feat[b] # (L, C)
mask_b = mask_128[b] # (1, L)
pert_b = (mask_b[0] != 0) # (L,)
bp_per_token_b = bp_per_token_tensor[b] # (L,) per-token resolution for this sample
if is_per_sample:
ccre_b = ccre_intervals_rel[b] if b < len(ccre_intervals_rel) else []
else:
ccre_b = ccre_intervals_rel if ccre_intervals_rel else []
keep_b = pert_b.clone() # (L,)
if is_per_sample and ccre_b:
_valid_ccre = [
iv for iv in ccre_b
if iv is not None and isinstance(iv, (list, tuple)) and len(iv) == 2
]
if _valid_ccre:
# Use mean resolution for this sample's cCRE mask
ccre_mask_b = build_ccre_mask(
L,
_valid_ccre,
bp_per_token=bp_per_token_b.mean().item(),
device=device,
)
keep_b = keep_b | ccre_mask_b
elif not is_per_sample:
keep_b = keep_mask[b]
if not keep_b.any():
center = L // 2
span = min(L, 512)
keep_b[max(0, center - span // 2):min(L, center + span // 2)] = True
if not pert_b.any():
feat_p, mask_p, keep_p, width_p = pool_segment(feat_b, mask_b, keep_b, k, bp_per_token_b)
feat_chunks.append(feat_p)
mask_chunks.append(mask_p)
width_chunks.append(width_p)
keep_chunks.append(keep_p)
continue
pert_idx = pert_b.nonzero(as_tuple=True)[0]
if pert_idx.numel() > 0:
p_start = int(pert_idx.min().item())
p_end = int(pert_idx.max().item())
else:
p_start, p_end = 0, -1
# Left flank
if p_start > 0:
feat_left, mask_left, keep_left, width_left = pool_segment(
feat_b[:p_start],
mask_b[:, :p_start],
keep_b[:p_start],
k,
bp_per_token_b[:p_start],
)
else:
feat_left = feat_b.new_empty(0, C)
mask_left = mask_b.new_empty(1, 0)
keep_left = keep_b.new_empty(0, dtype=torch.bool)
width_left = mask_b.new_empty(1, 0)
# Middle (pert span full-res at current resolution)
feat_mid = feat_b[p_start:p_end+1]
mask_mid = mask_b[:, p_start:p_end+1]
keep_mid = keep_b[p_start:p_end+1]
# Adaptive resolution: use per-token bp values
width_mid = bp_per_token_b[p_start:p_end+1].unsqueeze(0) # (1, L_mid)
# Right flank
if p_end + 1 < L:
feat_right, mask_right, keep_right, width_right = pool_segment(
feat_b[p_end+1:],
mask_b[:, p_end+1:],
keep_b[p_end+1:],
k,
bp_per_token_b[p_end+1:],
)
else:
feat_right = feat_b.new_empty(0, C)
mask_right = mask_b.new_empty(1, 0)
keep_right = keep_b.new_empty(0, dtype=torch.bool)
width_right = mask_b.new_empty(1, 0)
feat_b_comp = torch.cat([feat_left, feat_mid, feat_right], dim=0)
mask_b_comp = torch.cat([mask_left, mask_mid, mask_right], dim=1)
keep_b_comp = torch.cat([keep_left, keep_mid, keep_right], dim=0)
width_b_comp = torch.cat([width_left, width_mid, width_right], dim=1)
feat_chunks.append(feat_b_comp)
mask_chunks.append(mask_b_comp)
width_chunks.append(width_b_comp)
keep_chunks.append(keep_b_comp)
# ---------- 4. Pad batch ----------
L_out = max(f.shape[0] for f in feat_chunks)
feat_comp = torch.stack(
[F.pad(f, (0, 0, 0, L_out - f.shape[0])) for f in feat_chunks], dim=0
) # (B, L_out, C)
mask_comp = torch.stack(
[F.pad(m, (0, L_out - m.shape[1])) for m in mask_chunks], dim=0
) # (B, 1, L_out)
width_comp_bp = torch.stack(
[F.pad(w, (0, L_out - w.shape[1])) for w in width_chunks], dim=0
) # (B, 1, L_out)
keep_regions_mask = torch.stack(
[F.pad(k.float(), (0, L_out - k.shape[0])) for k in keep_chunks], dim=0
).bool() # (B, L_out)
keep_regions_mask = keep_regions_mask.unsqueeze(1) # (B, 1, L_out)
return feat_comp, mask_comp, width_comp_bp, keep_regions_mask
# def compress_after_transformer(feat, mask_128, ccre_intervals_rel=None, distal_stride_tokens=32):
# """
# Compress features after Borzoi transformer, respecting cCRE and perturbation regions.
# GPU-native implementation: all operations stay on GPU, no CPU-GPU sync.
#
# feat: (B, L, C) # after transformer at 128bp resolution
# mask_128: (B, 1, L) # mask at 128bp resolution
# ccre_intervals_rel: list of (start_bp, end_bp) tuples relative to window (base-pair coordinates)
# distal_stride_tokens: pooling stride in tokens at 128bp resolution
# Returns: (feat_comp, mask_comp, width_comp_bp, keep_regions_mask) where:
# - feat_comp: (B, Lmax, C) compressed features (padded to common length)
# - mask_comp: (B, 1, Lmax) compressed mask
# - width_comp_bp: (B, 1, Lmax) bp width per compressed token
# - keep_regions_mask: (B, 1, Lmax) bool - True = keep (cCRE/pert), False = compress
# """
# B, L, C = feat.shape
# device = feat.device
# bp_per_token = 128.0
#
# # Shared cCRE mask across batch (GPU-native)
# ccre_mask_1d = build_ccre_mask(L, ccre_intervals_rel, bp_per_token=bp_per_token, device=device) # (L,)
#
# def pool_feat_gap(x):
# """Pool features along sequence dimension: (C, len_gap) -> (C, len_gap//k)"""
# if x.numel() == 0:
# return x
# k = distal_stride_tokens
# n = (x.shape[-1] // k) * k
# main = x[:, :n].reshape(C, -1, k).mean(-1) if n > 0 else x.new_empty(C, 0)
# tail = x[:, n:].mean(-1, keepdim=True) if n < x.shape[-1] else x.new_empty(C, 0)
# return torch.cat([main, tail], dim=-1)
#
# def pool_mask_gap(x):
# """Pool mask along sequence dimension: (1, len_gap) -> (1, len_gap//k)"""
# if x.numel() == 0:
# return x
# k = distal_stride_tokens
# n = (x.shape[-1] // k) * k
# main = x[:, :n].reshape(1, -1, k).amax(-1) if n > 0 else x.new_empty(1, 0)
# tail = x[:, n:].amax(-1, keepdim=True) if n < x.shape[-1] else x.new_empty(1, 0)
# return torch.cat([main, tail], dim=-1)
#
# def build_widths(n_tokens, k):
# """Build width tensor in tokens (will be converted to bp later)"""
# if n_tokens == 0:
# return torch.empty(1, 0, device=device, dtype=torch.int32)
# n_full = (n_tokens // k) * k
# if k > 1:
# w_main = torch.full((1, n_full // k), k, device=device, dtype=torch.int32)
# else:
# w_main = torch.full((1, n_full), 1, device=device, dtype=torch.int32)
# w_tail = torch.full((1, 1), n_tokens - n_full, device=device, dtype=torch.int32) if n_full < n_tokens else torch.empty(1, 0, device=device, dtype=torch.int32)
# return torch.cat([w_main, w_tail], dim=-1)
#
# feat_chunks, mask_chunks, width_chunks, keep_mask_chunks = [], [], [], []
#
# for b in range(B):
# feat_b = feat[b].transpose(0, 1) # (C, L)
# mask_b = mask_128[b] # (1, L)
# pert_mask_b = (mask_b[0] != 0) # (L,) bool
#
# # keep tokens = perturbation OR cCRE
# keep_b = pert_mask_b | ccre_mask_1d # (L,) bool
#
# # If no keep tokens, fallback to full central region
# if not bool(keep_b.any()):
# keep_b = torch.zeros(L, device=device, dtype=torch.bool)
# center = L // 2
# span = L # or some fixed central span if you want
# l = max(0, center - span // 2)
# r = min(L, center + span // 2)
# keep_b[l:r] = True
#
# # Convert keep_b into contiguous intervals (all on GPU)
# keep_int = keep_b.to(torch.int8) # (L,)
# keep_pad = F.pad(keep_int, (1, 1)) # (L+2,)
# edges = keep_pad[1:] - keep_pad[:-1] # (L+1,)
# starts = torch.nonzero(edges == 1, as_tuple=False).flatten() # (n_int,)
# ends = torch.nonzero(edges == -1, as_tuple=False).flatten() # (n_int,)
# # Each interval is [starts[i], ends[i]) in token indices
#
# parts_f, parts_m, parts_w, parts_keep = [], [], [], []
# prev_end = 0
#
# # iterate over intervals; we *do* use Python loop but everything sliced as tensors
# for i in range(starts.numel()):
# ks = int(starts[i])
# ke = int(ends[i])
#
# # gap before this keep interval
# if ks > prev_end:
# gap_f = feat_b[:, prev_end:ks] # (C, gap_len)
# gap_m = mask_b[:, prev_end:ks] # (1, gap_len)
# gap_f_p = pool_feat_gap(gap_f)
# gap_m_p = pool_mask_gap(gap_m)
# gap_w = build_widths(gap_f.shape[-1], distal_stride_tokens)
# gap_keep = torch.zeros(1, gap_f_p.shape[-1], device=device, dtype=torch.bool)
#
# parts_f.append(gap_f_p)
# parts_m.append(gap_m_p)
# parts_w.append(gap_w)
# parts_keep.append(gap_keep)
#
# # keep region full-res
# keep_f = feat_b[:, ks:ke] # (C, keep_len)
# keep_m = mask_b[:, ks:ke]
# keep_w = torch.full((1, keep_f.shape[-1]), 1, device=device, dtype=torch.int32) # 1 token per position
# keep_mask = torch.ones(1, keep_f.shape[-1], device=device, dtype=torch.bool)
#
# parts_f.append(keep_f)
# parts_m.append(keep_m)
# parts_w.append(keep_w)
# parts_keep.append(keep_mask)
#
# prev_end = ke
#
# # gap after last keep interval
# if prev_end < L:
# gap_f = feat_b[:, prev_end:]
# gap_m = mask_b[:, prev_end:]
# gap_f_p = pool_feat_gap(gap_f)
# gap_m_p = pool_mask_gap(gap_m)
# gap_w = build_widths(gap_f.shape[-1], distal_stride_tokens)
# gap_keep = torch.zeros(1, gap_f_p.shape[-1], device=device, dtype=torch.bool)
#
# parts_f.append(gap_f_p)
# parts_m.append(gap_m_p)
# parts_w.append(gap_w)
# parts_keep.append(gap_keep)
#
# # stitch per-sample
# if parts_f:
# feat_b_comp = torch.cat(parts_f, dim=-1) # (C, L_comp_b)
# mask_b_comp = torch.cat(parts_m, dim=-1) # (1, L_comp_b)
# width_b_comp = torch.cat(parts_w, dim=-1) # (1, L_comp_b) int32, converted to float later
# keep_b_comp = torch.cat(parts_keep, dim=-1) # (1, L_comp_b)
# else:
# feat_b_comp = feat_b # fallback
# mask_b_comp = mask_b
# width_b_comp = torch.ones(1, L, device=device, dtype=torch.int32) # 1 token per position
# keep_b_comp = torch.zeros(1, L, device=device, dtype=torch.bool)
#
# feat_chunks.append(feat_b_comp)
# mask_chunks.append(mask_b_comp)
# width_chunks.append(width_b_comp)
# keep_mask_chunks.append(keep_b_comp)
#
# # Pad to common length across batch
# Lmax = max(f.shape[-1] for f in feat_chunks)
# feat_comp = torch.stack([F.pad(f, (0, Lmax - f.shape[-1])) for f in feat_chunks], dim=0).transpose(1, 2) # (B,Lmax,C)
# mask_comp = torch.stack([F.pad(m, (0, Lmax - m.shape[-1])) for m in mask_chunks], dim=0) # (B,1,Lmax)
# # Convert width from tokens to bp: all widths are in tokens, multiply by bp_per_token
# width_comp_bp = torch.stack([F.pad(w, (0, Lmax - w.shape[-1])) for w in width_chunks], dim=0).float() * bp_per_token # (B,1,Lmax)
# keep_regions_mask = torch.stack([F.pad(k.float(), (0, Lmax - k.shape[-1])) for k in keep_mask_chunks], dim=0).bool() # (B,1,Lmax)
#
# return feat_comp.contiguous(), mask_comp.contiguous(), width_comp_bp.contiguous(), keep_regions_mask.contiguous()
def compress_after_stem(feat, mask_raw, keep_span_bp=512, distal_stride_tokens=8, ccre_intervals_rel=None):
"""
feat: (B, C, L1) # after conv_dna + first pool
mask_raw: (B, 1, Lraw)
keep_span_bp: biological span to keep near center (e.g., 512 bp)
distal_stride_tokens: pooling stride in tokens at this stem resolution (power of 2 recommended)
ccre_intervals_rel: list of (start_bp, end_bp) tuples relative to window (base-pair coordinates)
If None or empty, falls back to default behavior
Returns: (feat_comp, mask_comp, width_comp, keep_regions_mask) where keep_regions_mask indicates full-res tokens
"""
B, C, L1 = feat.shape
device = feat.device
# Downsample mask to stem length with 'max' semantics (don't lose thin edits)
# Estimate bp_per_token at stem by relative lengths (works for arbitrary inputs)
Lraw = mask_raw.shape[-1]
# avoid division by 0
bp_per_token_stem = max(1.0, float(Lraw) / float(L1))
def build_widths(n_tokens, k):
if n_tokens == 0:
return torch.empty(1,0, device=device, dtype=torch.int32)
n_full = (n_tokens // k) * k
w_main = torch.full((1, n_full // k), k, device=device, dtype=torch.int32) if k > 1 else torch.full((1, n_full), 1, device=device, dtype=torch.int32)
w_tail = torch.full((1, 1), n_tokens - n_full, device=device, dtype=torch.int32) if n_full < n_tokens else torch.empty(1,0, device=device, dtype=torch.int32)
return torch.cat([w_main, w_tail], dim=-1) # (1,*)
def downsample_mask_max(mask, L_target):
if L_target == mask.shape[-1]: return mask
k = mask.shape[-1] // L_target
if k >= 2 and mask.shape[-1] % L_target == 0:
return mask.unfold(-1, k, k).amax(-1)
return (F.interpolate(mask.float(), size=L_target, mode='nearest') > 0.5).to(mask.dtype)
mask_stem = downsample_mask_max(mask_raw, L1) # (B,1,L1)
# Center at stem resolution
with torch.no_grad():
m = (mask_stem != 0).float()
idx = torch.arange(L1, device=device).view(1,1,L1)
centers = ((m*idx).sum(-1) / m.sum(-1).clamp_min(1e-6)).round().squeeze(1).long()
centers.clamp_(0, L1-1)
# Convert keep span from bp to tokens at stem
keep_tokens = max(1, int(round(keep_span_bp / bp_per_token_stem)))
half = keep_tokens // 2
# pool distal features (avg) and mask (max) by the same stride
def pool_feat(x):
if x.numel()==0: return x
k = distal_stride_tokens
n = (x.shape[-1] // k) * k
main = x[:, :n].contiguous().reshape(C, -1, k).mean(-1) # (C, n/k)
tail = x[:, n:].mean(-1, keepdim=True) if n < x.shape[-1] else x.new_empty(C,0)
return torch.cat([main, tail], dim=-1) # (C, *)
def pool_mask(x):
if x.numel()==0: return x
k = distal_stride_tokens
n = (x.shape[-1] // k) * k
main = x[:, :n].reshape(1, -1, k).amax(-1) # (1, n/k)
tail = x[:, n:].amax(-1, keepdim=True) if n < x.shape[-1] else x.new_empty(1,0, device=x.device)
return torch.cat([main, tail], dim=-1) # (1, *)
feat_chunks, mask_chunks, width_chunks, keep_mask_chunks = [], [], [], []
for b in range(B):
c_tensor = centers[b]
c = int(c_tensor.item())
l = max(0, c - half)
r = min(L1, c + half)
# Identify perturbation region tokens (from mask) - keep on GPU
pert_mask = (mask_stem[b, 0, :] != 0) # (L1,) bool tensor on GPU
pert_tokens = torch.where(pert_mask)[0].cpu().numpy().tolist() # Convert only when needed
# Identify cCRE region tokens (convert bp to tokens)
ccre_tokens_set = set()
if ccre_intervals_rel is not None and len(ccre_intervals_rel) > 0:
for ccre_start_bp, ccre_end_bp in ccre_intervals_rel:
# Convert bp to stem token coordinates
ccre_start_token = max(0, int(round(ccre_start_bp / bp_per_token_stem)))
ccre_end_token = min(L1 - 1, int(round(ccre_end_bp / bp_per_token_stem)))
if ccre_end_token >= ccre_start_token:
ccre_tokens_set.update(range(ccre_start_token, ccre_end_token + 1))
# Merge perturbation + cCRE regions
keep_tokens_set = set(pert_tokens) | ccre_tokens_set
# If no cCREs and no perturbation, fall back to default (central region)
if len(keep_tokens_set) == 0:
keep_tokens_set = set(range(l, r))
# Convert to sorted list of intervals
if keep_tokens_set:
keep_tokens_sorted = sorted(keep_tokens_set)
# Merge adjacent tokens into intervals
keep_intervals = []
start = keep_tokens_sorted[0]
for i in range(1, len(keep_tokens_sorted)):
if keep_tokens_sorted[i] != keep_tokens_sorted[i-1] + 1:
keep_intervals.append((start, keep_tokens_sorted[i-1] + 1))
start = keep_tokens_sorted[i]
keep_intervals.append((start, keep_tokens_sorted[-1] + 1))
else:
# Fallback: use central region
keep_intervals = [(l, r)]
# Split sequence into chunks: keep regions (full res) vs. gaps (compressed)
feat_parts, mask_parts, width_parts, keep_mask_parts = [], [], [], []
prev_end = 0
for keep_start, keep_end in keep_intervals:
# Gap before this keep region (compress)
if keep_start > prev_end:
gap_f = feat[b, :, prev_end:keep_start]
gap_m = mask_stem[b, :, prev_end:keep_start]
gap_f_p = pool_feat(gap_f) if gap_f.numel() > 0 else gap_f
gap_m_p = pool_mask(gap_m) if gap_m.numel() > 0 else gap_m
gap_w = build_widths(gap_f.shape[-1], distal_stride_tokens)
gap_keep = torch.zeros(1, gap_f_p.shape[-1], device=device, dtype=torch.bool)
feat_parts.append(gap_f_p)
mask_parts.append(gap_m_p)
width_parts.append(gap_w)
keep_mask_parts.append(gap_keep)
# Keep region (full resolution)
keep_f = feat[b, :, keep_start:keep_end]
keep_m = mask_stem[b, :, keep_start:keep_end]
keep_w = torch.ones(1, keep_f.shape[-1], device=device, dtype=torch.int32)
keep_mask = torch.ones(1, keep_f.shape[-1], device=device, dtype=torch.bool)
feat_parts.append(keep_f)
mask_parts.append(keep_m)
width_parts.append(keep_w)
keep_mask_parts.append(keep_mask)
prev_end = keep_end
# Gap after last keep region (compress)
if prev_end < L1:
gap_f = feat[b, :, prev_end:]
gap_m = mask_stem[b, :, prev_end:]
gap_f_p = pool_feat(gap_f) if gap_f.numel() > 0 else gap_f
gap_m_p = pool_mask(gap_m) if gap_m.numel() > 0 else gap_m
gap_w = build_widths(gap_f.shape[-1], distal_stride_tokens)
gap_keep = torch.zeros(1, gap_f_p.shape[-1], device=device, dtype=torch.bool)
feat_parts.append(gap_f_p)
mask_parts.append(gap_m_p)
width_parts.append(gap_w)
keep_mask_parts.append(gap_keep)
# Stitch all parts
feat_b = torch.cat(feat_parts, dim=-1) if feat_parts else feat[b]
mask_b = torch.cat(mask_parts, dim=-1) if mask_parts else mask_stem[b]
width_b = torch.cat(width_parts, dim=-1) if width_parts else torch.ones(1, L1, device=device, dtype=torch.int32)
keep_mask_b = torch.cat(keep_mask_parts, dim=-1) if keep_mask_parts else torch.zeros(1, L1, device=device, dtype=torch.bool)
feat_chunks.append(feat_b)
mask_chunks.append(mask_b)
width_chunks.append(width_b)
keep_mask_chunks.append(keep_mask_b)
# pad to a common length
Lmax = max(t.shape[-1] for t in feat_chunks)
feat_comp = torch.stack([F.pad(t, (0, Lmax - t.shape[-1])) for t in feat_chunks], 0) # (B,C,Lmax)
mask_comp = torch.stack([F.pad(t, (0, Lmax - t.shape[-1])) for t in mask_chunks], 0) # (B,1,Lmax)
width_comp = torch.stack([F.pad(w.float(), (0, Lmax - w.shape[-1])) for w in width_chunks], 0) # (B,1,Lmax)
keep_regions_mask = torch.stack([F.pad(k.float(), (0, Lmax - k.shape[-1])) for k in keep_mask_chunks], 0) # (B,1,Lmax)
return feat_comp.contiguous(), mask_comp.contiguous(), width_comp.contiguous(), keep_regions_mask.contiguous()
def _fwd_bwd_dt(m): # m: (B,L) bool
B, L = m.shape
inf = L + 1
# forward pass
d = torch.full((B, L), inf, device=m.device, dtype=torch.int32)
d[:, 0] = torch.where(m[:, 0], 0, inf)
for i in range(1, L):
d[:, i] = torch.where(m[:, i], 0, torch.minimum(d[:, i-1] + 1, torch.tensor(inf, device=m.device, dtype=d.dtype)))
# backward pass
for i in range(L-2, -1, -1):
d[:, i] = torch.minimum(d[:, i], d[:, i+1] + 1)
return d
def signed_nearest_distance(mask_128):
"""
Vectorized signed distance to the nearest nonzero mask position per token.
Tie-breaking matches original behavior (tie-left => negative).
Returns:
d_signed: (B, L) float32
has_pert: (B,) bool
"""
B, _, L = mask_128.shape
m = (mask_128 != 0).squeeze(1) # (B,L)
has_pert = m.any(dim=1) # (B,)
# Early exit: entire batch empty
if not has_pert.any():
d_signed = torch.full((B, L), float(L), device=mask_128.device, dtype=torch.float32)
return d_signed, has_pert
idx = torch.arange(L, device=mask_128.device, dtype=torch.int32).expand(B, -1) # (B,L)
# Left distance (last True at or before i) via prefix max of indices
neg_sentinel = torch.full((B, L), -2**30, device=mask_128.device, dtype=torch.int32)
left_idx_src = torch.where(m, idx, neg_sentinel)
last_true_idx, _ = left_idx_src.cummax(dim=1)
left_dist = idx - last_true_idx
left_dist = torch.where(last_true_idx < 0, torch.full_like(left_dist, L + 1), left_dist)
# Right distance (next True at or after i) via suffix min of indices
pos_sentinel = torch.full((B, L), 2**30, device=mask_128.device, dtype=torch.int32)
right_idx_src = torch.where(m, idx, pos_sentinel)
rev_min, _ = torch.flip(right_idx_src, dims=[1]).cummin(dim=1)
next_true_idx = torch.flip(rev_min, dims=[1])
right_dist = next_true_idx - idx
right_dist = torch.where(next_true_idx >= L, torch.full_like(right_dist, L + 1), right_dist)
# Tie-left signed rule
d_signed_int = torch.where(left_dist <= right_dist, -left_dist, right_dist)
d_signed = d_signed_int.to(torch.float32)
# Rows with no perturbation -> large positive constant
d_signed = torch.where(has_pert.view(-1, 1), d_signed, torch.full_like(d_signed, float(L)))
return d_signed, has_pert
class DistanceKernel(nn.Module):
"""Learnable distance-dependent decay kernel for regulatory effects."""
def __init__(self):
super().__init__()
# Sigmoid -> [0,1] for mixing ratio
self.alpha_raw = nn.Parameter(torch.tensor(0.0))
# Softplus -> >0, in units of 128bp tokens
self.ell_raw = nn.Parameter(torch.tensor(32.0)) # ~4kb default
# Softplus -> >0, power law decay
self.beta_raw = nn.Parameter(torch.tensor(0.8))
@staticmethod
def _pos(x, eps=1e-6):
return F.softplus(x) + eps
def forward(self, d_tokens):
"""
Args:
d_tokens: (B,1,L) signed or absolute distances in tokens (128bp each)