-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathtest_evo2_dataset.py
More file actions
1137 lines (984 loc) · 38.2 KB
/
Copy pathtest_evo2_dataset.py
File metadata and controls
1137 lines (984 loc) · 38.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
# Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# Copyright (c) 2024 Arc Institute. All rights reserved.
# Copyright (c) 2024 Michael Poli. All rights reserved.
# Copyright (c) 2024 Stanford University. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import random
import timeit
import pytest
import torch
from megatron.core.datasets.utils import Split
from nemo.collections.llm.gpt.data.megatron.hyena.evo2_dataset import Evo2Dataset, Evo2DatasetPadEodLossMask
"""
The tag token is constructed as follows: So note that one way to know you have a tag is if you look at the first
token after the pipe and it is a 'd' character. Make sure tests are consistent with this simplification.
@staticmethod
def _construct_taxonomy_token(
lineage: Evo2TaxonomyLineage, dropout: float = 0.0, seed: Optional[int] = None
) -> Optional[str]:
'''Construct a special Taxonomy token for natural language prompting of DNA generation models.
Args:
lineage (Evo2TaxonomyLineage): The taxonomy lineage information.
dropout (float): The probability of dropping out segments of the lineage. Defaults to 0.0.
seed (Optional[int]): The seed for the random number generator. Defaults to None.
Returns:
Optional[str]: The constructed taxonomy token or None if lineage is None.
'''
# If dropout > 0, randomly drop out segments of the lineage for training on incomplete lineages.
with Evo2Preprocessor.preprocessing_context_manager(seed if seed is not None else None):
return (
"|d__{};p__{};c__{};o__{};f__{};g__{};s__{}|".format(
lineage.domain if random.random() >= dropout else None,
lineage.phylum if random.random() >= dropout else None,
lineage.clazz if random.random() >= dropout else None,
lineage.order if random.random() >= dropout else None,
lineage.family if random.random() >= dropout else None,
lineage.genus if random.random() >= dropout else None,
lineage.species if random.random() >= dropout else None,
)
if lineage is not None
else None
)
"""
@pytest.fixture
def tag_tokens():
"""Standard tokens for phylogenetic tag tests, defined in Evo2_DataseT:
CONTROL_TAGS: ClassVar[list[int]] = [64, 35] # '@' tag for splice splits/windows, '#' for contig splits
TAG_BOUNDS = 124 # start and end delim: '|'
TAG_CHARS: ClassVar[set[int]] = {95, 59, 32} # chars only found in control tags: _, ;, space
DEFAULT_EOD = 0
"""
return {
"terminal": 124, # |
"other_chars": {95, 59, 32}, # _, ;, space
"eod": 0, # end of document token
}
def test_mask_phylogenetic_tags_with_eod(tag_tokens):
"""
Tests a sequence where an EOD splits two partial tags.
Example sequence (ASCII):
65 124 100 0 124 65
'A' '|' 'd' EOD '|' 'A'
- Segment 1: "A|d" => keep 'A' (DNA), mask '|' and 'd'
- EOD => masked
- Segment 2: "|A" => mask '|', keep 'A' (DNA)
Expected masking: [1, 0, 0, 1, 0, 1]
"""
sequence = torch.tensor([65, 124, 100, 0, 124, 65]) # "A|d" + EOD + "|A"
mask = Evo2Dataset.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"], # '|'
other_tag_chars=tag_tokens["other_chars"], # { '_',';',' ' }
eod_token_id=tag_tokens["eod"], # 0
)
expected_mask = torch.tensor([1, 0, 0, 1, 0, 1])
assert torch.equal(mask, expected_mask)
def test_mask_phylogenetic_tags_middle(tag_tokens):
"""Tests masking a phylogenetic tag that appears in the middle of a DNA sequence.
The sequence contains:
1. Normal DNA (ATG)
2. A phylo tag (|d_|)
3. More DNA (TCGA)
Expected behavior: The DNA should be unmasked (1s) while everything between
and including the pipe characters should be masked (0s), as it's a valid phylo tag.
"""
sequence = torch.tensor(
[
65,
84,
71, # ATG
124,
100,
110,
102,
111,
95,
116,
97,
103,
124, # |d__tag|
84,
67,
71,
65, # TCGA
]
)
mask = Evo2Dataset.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"], # |
other_tag_chars=tag_tokens["other_chars"], # _, ;, space
eod_token_id=tag_tokens["eod"],
)
expected_mask = torch.tensor(
[
1,
1,
1, # DNA unmasked
0,
0,
0,
0,
0,
0,
0,
0,
0,
0, # phylo tag masked
1,
1,
1,
1, # DNA unmasked
]
)
assert torch.equal(mask, expected_mask)
def test_mask_partial_tag_start(tag_tokens):
"""Tests handling a sequence that starts with a partial phylogenetic tag.
The sequence starts with characters that would be inside a phylo tag,
followed by a closing pipe and DNA. Since we want to prevent the model from
learning non-DNA outputs, we mask all potential tag characters even without
complete tag delimiters.
Sequence: "tag;_|ATG" (starting mid-tag)
Expected: All tag characters and delimiters masked, only DNA unmasked
"""
sequence = torch.tensor(
[
116,
97,
103,
59,
95, # tag;_
124, # |
65,
84,
71, # ATG
]
)
mask = Evo2Dataset.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
expected_mask = torch.tensor(
[
0,
0,
0,
0,
0, # partial tag start masked
0, # closing pipe masked
1,
1,
1, # DNA unmasked
]
)
assert torch.equal(mask, expected_mask)
def test_mask_partial_tag_end(tag_tokens):
"""Tests handling a sequence that ends with a partial phylogenetic tag.
The sequence contains DNA followed by an opening pipe and tag characters,
but no closing pipe. Per requirements, we aggressively mask any potential
tag characters to ensure the model only learns DNA bases {A,C,G,T}.
Sequence: "ATG|info_" (ending mid-tag)
Expected: DNA unmasked, all tag-related characters masked
"""
sequence = torch.tensor(
[
65,
84,
71, # ATG
124, # |
100,
110,
102,
111,
95, # info_
]
)
mask = Evo2Dataset.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
expected_mask = torch.tensor(
[
1,
1,
1, # DNA unmasked
0, # opening pipe masked
0,
0,
0,
0,
0, # partial tag end masked
]
)
assert torch.equal(mask, expected_mask)
def test_standalone_tag(tag_tokens):
"""Tests masking of a single complete tag with no surrounding sequence.
Tests that a standalone tag (|tag_|) is fully masked since it contains
non-DNA characters. This ensures the model only learns to output
{A,C,G,T} tokens.
Sequence: |tag_|
Expected: All tokens masked (all zeros)
"""
sequence = torch.tensor([124, 100, 97, 103, 95, 124]) # |dtag_|
mask = Evo2Dataset.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
expected = torch.tensor([0, 0, 0, 0, 0, 0]) # All masked
assert torch.equal(mask, expected)
def test_sequence_starting_with_tag(tag_tokens):
"""Tests sequence that begins with a complete tag followed by DNA.
Verifies that when a sequence starts with a complete tag followed by
DNA bases, the tag portion is masked while the DNA portion remains
unmasked.
Sequence: |tag_|ATG
Expected: Tag masked (zeros), DNA unmasked (ones)
"""
sequence = torch.tensor(
[
124,
100, # d token for domain
97,
103,
95,
124, # |tag_|
65,
84,
71, # ATG
]
)
mask = Evo2Dataset.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
expected = torch.tensor([0, 0, 0, 0, 0, 0, 1, 1, 1]) # Tag masked, DNA unmasked
assert torch.equal(mask, expected)
def test_sequence_ending_with_tag(tag_tokens):
"""Tests sequence that ends with a complete tag.
Verifies that when a sequence ends with a complete tag, the DNA portion
remains unmasked while the entire tag portion is masked.
Sequence: ATG|tag_|
Expected: DNA unmasked (ones), tag masked (zeros)
"""
sequence = torch.tensor(
[
65,
84,
71, # ATG
124,
100,
97,
103,
95,
124, # |tag_|
]
)
mask = Evo2Dataset.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
expected = torch.tensor([1, 1, 1, 0, 0, 0, 0, 0, 0]) # DNA unmasked, tag masked
assert torch.equal(mask, expected)
def test_mask_multiple_tags(tag_tokens):
"""Tests handling multiple phylogenetic tags in sequence, demonstrating state transitions.
This tests how the masking switches states between phylo and non-phylo regions:
1. Starts in non-phylo state with DNA
2. Switches to phylo state at first pipe (with tag chars)
3. Switches back to non-phylo at closing pipe
4. Pattern repeats for second tag
Sequence: "ATG|tag_1|CG|tag_2|AT"
Expected: Only DNA sequences should remain unmasked
"""
sequence = torch.tensor(
[
65,
84,
71, # ATG
124,
100,
97,
103,
95,
49,
124, # |tag_1|
67,
71, # CG
124,
100,
97,
103,
95,
50,
124, # |tag_2|
65,
84, # AT
]
)
mask = Evo2Dataset.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
expected_mask = torch.tensor(
[
1,
1,
1, # DNA unmasked
0,
0,
0,
0,
0,
0,
0, # first tag masked
1,
1, # DNA unmasked
0,
0,
0,
0,
0,
0,
0, # second tag masked
1,
1, # DNA unmasked
]
)
assert torch.equal(mask, expected_mask)
def test_mask_dna_after_pipe(tag_tokens):
"""Tests the scenario where we have a pipe followed by DNA sequence.
This tests the edge case of a pipe character appearing at the start of a sequence.
Even if DNA follows, we mask the pipe character to prevent the model from
learning to output non-DNA tokens.
Sequence: "|ATG" (pipe followed by DNA)
Expected: Pipe masked, DNA unmasked
"""
sequence = torch.tensor(
[
124, # |
65,
84,
71, # ATG
]
)
mask = Evo2Dataset.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
expected_mask = torch.tensor([0, 1, 1, 1]) # Pipe masked, DNA unmasked
assert torch.equal(mask, expected_mask)
def test_ambiguous_dna_char_followed_by_tag_start(tag_tokens):
"""Tests handling of an ambiguous DNA character followed by a tag start.
When we see a character that could be either DNA or the end of a truncated tag
followed by a pipe, we should mask both for safety since we can't disambiguate
whether the character was part of a tag.
Sequence: "t|AAAT" (t could be DNA or end of tag)
Expected: First t and pipe masked (0), AAAT unmasked (1)
"""
sequence = torch.tensor(
[
116, # t (ambiguous - could be DNA or end of tag)
124, # |
65, # A
65, # A
65, # A
84, # T
]
)
mask = Evo2Dataset.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
expected_mask = torch.tensor([0, 0, 1, 1, 1, 1]) # Ambiguous t and pipe masked, DNA unmasked
assert torch.equal(mask, expected_mask)
def test_dna_followed_by_unambiguous_tag_start(tag_tokens):
"""Tests handling of DNA sequence followed by clear tag start.
When we see DNA followed by |d, it's unambiguous - the d clearly indicates
the start of a phylogenetic tag (d__), so we can safely unmask the DNA and
mask the tag portion.
Sequence: "AAAT|d" (AAAT is DNA, |d starts tag)
Expected: AAAT unmasked (1), |d masked (0)
"""
sequence = torch.tensor(
[
65, # A
65, # A
65, # A
84, # T
124, # |
100, # d (clearly starts d__ tag)
]
)
mask = Evo2Dataset.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
expected_mask = torch.tensor([1, 1, 1, 1, 0, 0]) # DNA unmasked, tag start masked
assert torch.equal(mask, expected_mask)
def test_double_partial_tags_with_dna_middle(tag_tokens):
"""Tests a sequence that has partial tags at both ends with DNA in the middle.
Tests the specific case where a sequence slice cuts through phylogenetic tags
on both ends, with valid DNA sequence in the middle. The behavior we want is:
1. The partial tag at the start should be masked
2. The DNA in the middle should be unmasked
3. The partial tag at the end should be masked
Sequence: "cacata|acagataaaataTACAGGGAATA|d__"
Expected: First partial tag masked (0s), middle DNA unmasked (1s), end tag masked (0s)
"""
sequence = torch.tensor(
[
99,
97,
99,
97,
116,
97, # cacata
124, # |
97,
99,
97,
103,
97,
116,
97,
97,
97,
97,
116,
97, # acagataaaata
84,
65,
67,
65,
71,
71,
71,
65,
65,
84,
65, # TACAGGGAATA
124, # |
100,
95,
95, # d__
]
)
mask = Evo2Dataset.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
expected_mask = torch.tensor(
[
0,
0,
0,
0,
0,
0, # partial start tag masked
0, # pipe masked
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1, # middle DNA unmasked
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1, # middle DNA unmasked
0, # pipe masked
0,
0,
0, # partial end tag masked
]
)
assert torch.equal(mask, expected_mask)
def test_packed_partial_tag_subsequence_predna(tag_tokens):
"""
Sequence: "GAATA[EOD]cacata|acagataaaataTACAGGGAATA|d__"
Expected: First partial tag masked (0s), middle DNA unmasked (1s), end tag masked (0s)
"""
sequence_alpha = "GAATA0cacata|acagataaaataTACAGGGAATA|d__"
sequence = torch.tensor([ord(t) if t != "0" else 0 for t in sequence_alpha], dtype=torch.int32)
expected_mask = torch.tensor(
len("GAATA0") * [1] + [0] * len("cacata|") + len("acagataaaataTACAGGGAATA") * [1] + [0] * len("|d__"),
dtype=torch.int32,
)
mask = Evo2Dataset.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
torch.testing.assert_close(mask, expected_mask)
def test_packed_partial_tag_subsequence_pretag(tag_tokens):
"""
Sequence: "cacata|[EOD]acagataaaataTACAGGGAATA|d__"
Expected: First partial tag masked (0s), middle DNA unmasked (1s), end tag masked (0s)
"""
sequence_alpha = "cacata|0acagataaaataTACAGGGAATA|d__"
sequence = torch.tensor([ord(t) if t != "0" else 0 for t in sequence_alpha], dtype=torch.int32)
expected_mask = torch.tensor(
len("cacata") * [1] + [0] + [1] * len("0acagataaaataTACAGGGAATA") + len("|d__") * [0], dtype=torch.int32
)
mask = Evo2Dataset.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
torch.testing.assert_close(mask, expected_mask)
def test_packed_partial_tag_subsequence_predna_middletag(tag_tokens):
"""
Sequence: "GAATA[EOD]cacata|acagataaaata|d__tag;|TACAGGGAATA|d__"
Expected: First partial tag masked (0s), middle DNA unmasked (1s), end tag masked (0s)
"""
sequence_alpha = "GAATA0cacata|acagataaaata|d__tag;|TACAGGGAATA|d__"
sequence = torch.tensor([ord(t) if t != "0" else 0 for t in sequence_alpha], dtype=torch.int32)
expected_mask = torch.tensor(
len("GAATA0") * [1]
+ len("cacata|") * [0]
+ [1] * len("acagataaaata")
+ len("|d__tag;|") * [0]
+ len("TACAGGGAATA") * [1]
+ len("|d__") * [0],
dtype=torch.int32,
)
mask = Evo2Dataset.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
torch.testing.assert_close(mask, expected_mask)
def test_packed_partial_tag_subsequence_pretag_middletag(tag_tokens):
"""
Sequence: "cacata|[EOD]acagataaaata|d__tag;|TACAGGGAATA|d__"
Expected: First partial tag masked (0s), middle DNA unmasked (1s), end tag masked (0s)
"""
sequence_alpha = "cacata|0acagataaaata|d__tag;|TACAGGGAATA|d__"
sequence = torch.tensor([ord(t) if t != "0" else 0 for t in sequence_alpha], dtype=torch.int32)
expected_mask = torch.tensor(
len("cacata") * [1]
+ [0] # masked pipe.
+ [1] * len("0acagataaaata")
+ len("|d__tag;|") * [0]
+ len("TACAGGGAATA") * [1]
+ len("|d__") * [0],
dtype=torch.int32,
)
mask = Evo2DatasetPadEodLossMask.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
torch.testing.assert_close(mask, expected_mask)
def test_packed_partial_tag_subsequence_pretag_middletag_bs2(tag_tokens):
"""
Sequence: "cacata|[EOD]acagataaaata|d__tag;|TACAGGGAATA|d__"
Expected: First partial tag masked (0s), middle DNA unmasked (1s), end tag masked (0s)
"""
sequence_alpha = "cacata|0acagataaaata|d__tag;|TACAGGGAATA|d__"
sequence = torch.tensor([ord(t) if t != "0" else 0 for t in sequence_alpha], dtype=torch.int32)
expected_mask = torch.tensor(
len("cacata") * [1]
+ [0]
+ [1] * len("0acagataaaata")
+ len("|d__tag;|") * [0]
+ len("TACAGGGAATA") * [1]
+ len("|d__") * [0],
dtype=torch.int32,
)
expected_mask = torch.stack([expected_mask, expected_mask])
mask = Evo2DatasetPadEodLossMask.mask_phylogenetic_tags(
tokenized_sequence=torch.stack([sequence, sequence]),
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
torch.testing.assert_close(mask, expected_mask)
def test_packed_partial_tag_subsequence_pretag_middletag_bs3(tag_tokens):
"""
Sequence: "cacata|[EOD]acagataaaata|d__tag;|TACAGGGAATA|d__"
Expected: First partial tag masked (0s), middle DNA unmasked (1s), end tag masked (0s)
"""
sequence_alpha = "cacata|0acagataaaata|d__tag;|TACAGGGAATA|d__somet"
sequence = torch.tensor([ord(t) if t != "0" else 0 for t in sequence_alpha], dtype=torch.int32)
expected_mask = torch.tensor(
len("cacata") * [1]
+ [0]
+ [1] * len("0acagataaaata")
+ len("|d__tag;|") * [0]
+ len("TACAGGGAATA") * [1]
+ len("|d__somet") * [0],
dtype=torch.int32,
)
sequence_alpha2 = "GAATA0cacata|acagataaaata|d__tag;|TACAGGGAATA|d__"
sequence2 = torch.tensor([ord(t) if t != "0" else 0 for t in sequence_alpha2], dtype=torch.int32)
expected_mask2 = torch.tensor(
len("GAATA0") * [1]
+ len("cacata|") * [0]
+ [1] * len("acagataaaata")
+ len("|d__tag;|") * [0]
+ len("TACAGGGAATA") * [1]
+ len("|d__") * [0],
dtype=torch.int32,
)
expected_mask = torch.stack([expected_mask, expected_mask, expected_mask2])
mask = Evo2DatasetPadEodLossMask.mask_phylogenetic_tags(
tokenized_sequence=torch.stack([sequence, sequence, sequence2]),
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
torch.testing.assert_close(mask, expected_mask)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available")
def test_packed_partial_tag_subsequence_pretag_middletag_bs3_cuda(tag_tokens):
sequence_alpha = "cacata|0acagataaaata|d__tag;|TACAGGGAATA|d__somet"
sequence = torch.tensor([ord(t) if t != "0" else 0 for t in sequence_alpha], dtype=torch.int32)
expected_mask = torch.tensor(
len("cacata") * [1]
+ [0]
+ [1] * len("0acagataaaata")
+ len("|d__tag;|") * [0]
+ len("TACAGGGAATA") * [1]
+ len("|d__somet") * [0],
dtype=torch.int32,
)
sequence_alpha2 = "GAATA0cacata|acagataaaata|d__tag;|TACAGGGAATA|d__"
sequence2 = torch.tensor([ord(t) if t != "0" else 0 for t in sequence_alpha2], dtype=torch.int32)
expected_mask2 = torch.tensor(
len("GAATA0") * [1]
+ len("cacata|") * [0]
+ [1] * len("acagataaaata")
+ len("|d__tag;|") * [0]
+ len("TACAGGGAATA") * [1]
+ len("|d__") * [0],
dtype=torch.int32,
)
expected_mask = torch.stack([expected_mask, expected_mask, expected_mask2])
mask = Evo2DatasetPadEodLossMask.mask_phylogenetic_tags(
tokenized_sequence=torch.stack([sequence, sequence, sequence2]).cuda(),
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
torch.testing.assert_close(mask.cpu(), expected_mask)
def test_multiple_packed_tags(tag_tokens):
"""
Tests a sequence with multiple packed tags.
"""
sequence_alpha = "|d__tag;|0|d__tag;|0|d__somet"
sequence = torch.tensor([ord(t) if t != "0" else 0 for t in sequence_alpha], dtype=torch.int32)
expected_mask = torch.tensor(
len("|d__tag;|") * [0] + len("0") * [1] + len("|d__tag;|") * [0] + len("0") * [1] + len("|d__somet") * [0],
dtype=torch.int32,
)
mask = Evo2DatasetPadEodLossMask.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
torch.testing.assert_close(mask, expected_mask)
def test_multiple_eods(tag_tokens):
"""
Tests a sequence with multiple EODs.
"""
sequence_alpha = "ACGT0tacg0"
sequence = torch.tensor([ord(t) if t != "0" else 0 for t in sequence_alpha], dtype=torch.int32)
expected_mask = torch.tensor(len(sequence_alpha) * [1], dtype=torch.int32)
mask = Evo2DatasetPadEodLossMask.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
torch.testing.assert_close(mask, expected_mask)
def test_multiple_eods_prefix_no_suffix(tag_tokens):
"""
Tests a sequence with multiple EODs.
"""
sequence_alpha = "0ACGT0tacg0aa"
sequence = torch.tensor([ord(t) if t != "0" else 0 for t in sequence_alpha], dtype=torch.int32)
expected_mask = torch.tensor(len(sequence_alpha) * [1], dtype=torch.int32)
mask = Evo2DatasetPadEodLossMask.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
torch.testing.assert_close(mask, expected_mask)
def test_no_eods_with_batch(tag_tokens):
"""
Tests a sequence with multiple EODs.
"""
sequence_alpha = "ACATAGATTT"
sequence = torch.tensor([ord(t) if t != "0" else 0 for t in sequence_alpha], dtype=torch.int32)
expected_mask = torch.tensor(len(sequence_alpha) * [1], dtype=torch.int32)
mask = Evo2DatasetPadEodLossMask.mask_phylogenetic_tags(
tokenized_sequence=torch.stack([sequence, sequence]),
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
torch.testing.assert_close(mask, torch.stack([expected_mask, expected_mask]))
def test_no_eods_one_tag_with_batch_bs2(tag_tokens):
"""
Tests a sequence with multiple EODs.
"""
sequence_alpha = "ACAT|d__tag;|AGATTT"
sequence = torch.tensor([ord(t) if t != "0" else 0 for t in sequence_alpha], dtype=torch.int32)
expected_mask = torch.tensor(len("ACAT") * [1] + len("|d__tag;|") * [0] + len("AGATTT") * [1], dtype=torch.int32)
mask = Evo2DatasetPadEodLossMask.mask_phylogenetic_tags(
tokenized_sequence=torch.stack([sequence, sequence]),
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
torch.testing.assert_close(mask, torch.stack([expected_mask, expected_mask]))
def test_packed_partial_tag_subsequence_predna_with_control_and_degenerate_base(tag_tokens):
"""
Sequence: "GAATA[EOD]cacata|acagataaa@ataTACAGGGAATA|d__"
Expected: First partial tag masked (0s), middle DNA unmasked (1s), end tag masked (0s)
"""
sequence_alpha = "GAWTA0cacata|acagaraaaa@taTACAGGGAATA|d__"
sequence = torch.tensor([ord(t) if t != "0" else 0 for t in sequence_alpha], dtype=torch.int32)
expected_mask = torch.tensor(
len("GAWTA0") * [1] + [0] * len("cacata|") + len("acagataaaa@taTACAGGGAATA") * [1] + [0] * len("|d__"),
dtype=torch.int32,
)
mask = Evo2Dataset.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
torch.testing.assert_close(mask, expected_mask)
def test_packed_partial_tag_subsequence_predna_with_control2(tag_tokens):
"""
Sequence: "GAATA[EOD]cacata|acagataaa@ataTACAGGGAATA|d__"
Expected: First partial tag masked (0s), middle DNA unmasked (1s), end tag masked (0s)
"""
sequence_alpha = "GA#ATA0cacata|acagataaaa@taTACAGGGAATA|d__"
sequence = torch.tensor([ord(t) if t != "0" else 0 for t in sequence_alpha], dtype=torch.int32)
expected_mask = torch.tensor(
len("GA#ATA0") * [1] + [0] * len("cacata|") + len("acagataaaa@taTACAGGGAATA") * [1] + [0] * len("|d__"),
dtype=torch.int32,
)
mask = Evo2Dataset.mask_phylogenetic_tags(
tokenized_sequence=sequence,
terminal_tag_char=tag_tokens["terminal"],
other_tag_chars=tag_tokens["other_chars"],
eod_token_id=tag_tokens["eod"],
)
torch.testing.assert_close(mask, expected_mask)
def _construct_taxonomy_token(dropout: float = 0.0) -> str:
"""Construct a special Taxonomy token for natural language prompting of DNA generation models.
Args:
dropout (float): The probability of dropping out segments of the lineage. Defaults to 0.0.
Returns:
Optional[str]: The constructed taxonomy token or None if lineage is None.
"""
# If dropout > 0, randomly drop out segments of the lineage for training on incomplete lineages.
return "|d__{};p__{};c__{};o__{};f__{};g__{};s__{}|".format(
"somedomain" if random.random() >= dropout else None,
"somephylum" if random.random() >= dropout else None,
"someclass" if random.random() >= dropout else None,
"someorder" if random.random() >= dropout else None,
"somefamily" if random.random() >= dropout else None,
"lineage.genus" if random.random() >= dropout else None,
"lineage.speciescactaca" if random.random() >= dropout else None,
)
def mask_phylogenetic_tags_old(tokenized_sequence, terminal_tag_char, other_tag_chars, eod_token_id):
"""
Optimized version to create a phylonetic tag mask for batched tokenized sequences with correct handling of partial tags.
Args:
- tokenized_sequence (torch.Tensor): A batched tensor of shape (batch_size, seq_length).
- terminal_tag_char (int): The token ID representing the start and end of a phylogenetic tag ('|').
- other_tag_chars (set of int): A set of token IDs that are uniquely part of the tag ('_', ';', etc.).
- eod_token_id (int): The token ID representing the end-of-document (EOD).
Returns:
- mask_vector (torch.Tensor): A batched mask of the same shape as tokenized_sequence where
1 represents non-tag tokens and 0 represents tokens within the masked region.
"""
device = tokenized_sequence.device
batch_size, seq_len = tokenized_sequence.shape
mask_vector = torch.ones_like(tokenized_sequence, dtype=torch.int, device=device)
# To address when unbalanced tags are present
terms = torch.tensor([0, seq_len - 1], device=device)
other_tags = torch.tensor(list(other_tag_chars), device=device)
for batch_idx in range(batch_size):
tag_term_locs = torch.where(tokenized_sequence[batch_idx] == terminal_tag_char)[0]
tag_end_locs = torch.where(tokenized_sequence[batch_idx] == eod_token_id)[0]
merged_tags = torch.cat((terms, tag_term_locs, tag_end_locs)).sort()[0]
merged_tags = merged_tags.unique()
start = 0 # First and last locations are always added
for end in merged_tags[1:]:
if torch.isin(tokenized_sequence[batch_idx][start:end], other_tags).sum() > 0:
# end token is not part of the tag
if eod_token_id == tokenized_sequence[batch_idx][end]:
end = end - 1
if eod_token_id == tokenized_sequence[batch_idx][start]:
start = start + 1
mask_vector[batch_idx][start : (end + 1)] = 0
start = end
return mask_vector