Fill-Mask
Transformers
Safetensors
nucengram
feature-extraction
biology
genomics
dna
masked-lm
custom_code
Instructions to use FreakingPotato/NucEngram with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use FreakingPotato/NucEngram with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("fill-mask", model="FreakingPotato/NucEngram", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("FreakingPotato/NucEngram", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Add NucEngram genomic language model (base, S123) + usage
Browse files- README.md +103 -0
- config.json +50 -0
- configuration_nucengram.py +13 -0
- engram.py +400 -0
- model.safetensors +3 -0
- model_modernbert.py +218 -0
- model_modernbert_engram.py +151 -0
- modeling_nucengram.py +99 -0
- tokenizer.py +85 -0
README.md
CHANGED
|
@@ -1,3 +1,106 @@
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
| 3 |
+
tags:
|
| 4 |
+
- biology
|
| 5 |
+
- genomics
|
| 6 |
+
- dna
|
| 7 |
+
- masked-lm
|
| 8 |
+
library_name: transformers
|
| 9 |
+
pipeline_tag: fill-mask
|
| 10 |
---
|
| 11 |
+
|
| 12 |
+
# NucEngram
|
| 13 |
+
|
| 14 |
+
A **genomic language model (GLM)** for DNA sequences. It is a character-level
|
| 15 |
+
(single-nucleotide) model over the alphabet `A / C / G / T / N`, pretrained with
|
| 16 |
+
masked language modeling on genomic sequence, built on a ModernBERT encoder with
|
| 17 |
+
an 8192-nucleotide context window (~188M parameters).
|
| 18 |
+
|
| 19 |
+
It produces a **per-nucleotide contextual embedding** that you can pool and use
|
| 20 |
+
as features for downstream genomics tasks — promoter / splice-site / enhancer /
|
| 21 |
+
regulatory-element classification, sequence property prediction, etc. — either as
|
| 22 |
+
a frozen feature extractor or by fine-tuning.
|
| 23 |
+
|
| 24 |
+
The custom architecture ships with the repo, so load it with
|
| 25 |
+
`trust_remote_code=True`.
|
| 26 |
+
|
| 27 |
+
## Install
|
| 28 |
+
|
| 29 |
+
```bash
|
| 30 |
+
pip install "transformers>=4.44" torch safetensors
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
## Quick start — embeddings
|
| 34 |
+
|
| 35 |
+
```python
|
| 36 |
+
from transformers import AutoModel
|
| 37 |
+
|
| 38 |
+
model = AutoModel.from_pretrained("FreakingPotato/NucEngram",
|
| 39 |
+
trust_remote_code=True).eval()
|
| 40 |
+
|
| 41 |
+
# convenience helper: sequence(s) -> pooled embedding [B, 512]
|
| 42 |
+
emb = model.embed(["ACGTACGTACGTGGTAAGT", "TTGCCGCGCGATCGATCG"])
|
| 43 |
+
print(emb.shape) # torch.Size([2, 512])
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
Per-nucleotide hidden states (for token-level tasks):
|
| 47 |
+
|
| 48 |
+
```python
|
| 49 |
+
ids, attention_mask = model.encode("ACGT...") # char-level tokenizer, pad id 0
|
| 50 |
+
out = model(ids, attention_mask)
|
| 51 |
+
h = out.last_hidden_state # [B, T, 512]
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
## Downstream task — fine-tuning
|
| 55 |
+
|
| 56 |
+
Add a pooling + linear head and fine-tune (or freeze `base` for linear probing):
|
| 57 |
+
|
| 58 |
+
```python
|
| 59 |
+
import torch, torch.nn as nn
|
| 60 |
+
from transformers import AutoModel
|
| 61 |
+
|
| 62 |
+
class SequenceClassifier(nn.Module):
|
| 63 |
+
def __init__(self, n_classes, freeze_base=False):
|
| 64 |
+
super().__init__()
|
| 65 |
+
self.base = AutoModel.from_pretrained("FreakingPotato/NucEngram",
|
| 66 |
+
trust_remote_code=True)
|
| 67 |
+
if freeze_base:
|
| 68 |
+
for p in self.base.parameters():
|
| 69 |
+
p.requires_grad_(False)
|
| 70 |
+
self.head = nn.Linear(512, n_classes)
|
| 71 |
+
|
| 72 |
+
def forward(self, input_ids, attention_mask):
|
| 73 |
+
h = self.base(input_ids, attention_mask).last_hidden_state # [B, T, 512]
|
| 74 |
+
m = attention_mask.unsqueeze(-1).float()
|
| 75 |
+
pooled = (h * m).sum(1) / m.sum(1).clamp(min=1.0) # mean-pool
|
| 76 |
+
return self.head(pooled)
|
| 77 |
+
|
| 78 |
+
clf = SequenceClassifier(n_classes=2).train()
|
| 79 |
+
ids, am = clf.base.encode(["ACGT...", "GGGT..."]) # your batch of sequences
|
| 80 |
+
logits = clf(ids, am)
|
| 81 |
+
# ... standard cross-entropy training loop on your labelled dataset ...
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
For masked-LM scoring / filling:
|
| 85 |
+
|
| 86 |
+
```python
|
| 87 |
+
from transformers import AutoModelForMaskedLM
|
| 88 |
+
mlm = AutoModelForMaskedLM.from_pretrained("FreakingPotato/NucEngram",
|
| 89 |
+
trust_remote_code=True).eval()
|
| 90 |
+
ids, am = mlm.encode("ACGTACGT")
|
| 91 |
+
logits = mlm(ids, am).logits # [B, T, 9] over A/C/G/T/N + special tokens
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
## Details
|
| 95 |
+
|
| 96 |
+
| | |
|
| 97 |
+
|---|---|
|
| 98 |
+
| Backbone | ModernBERT encoder, 22 layers, hidden 512, 16 heads |
|
| 99 |
+
| Context | up to 8192 nucleotides |
|
| 100 |
+
| Vocabulary | 9 tokens (A, C, G, T, N + pad/bos/eos/mask), char-level |
|
| 101 |
+
| Params | ~188M |
|
| 102 |
+
| Attention | `sdpa` by default (no flash-attn required) |
|
| 103 |
+
| Precision | fp32 weights (cast with `.half()` / `.bfloat16()` as you like) |
|
| 104 |
+
|
| 105 |
+
Input sequences are uppercase DNA strings; the built-in `encode()` maps
|
| 106 |
+
characters to ids and pads with id 0. Use `attention_mask` to ignore padding.
|
config.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_type": "nucengram",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"NucEngramModel"
|
| 5 |
+
],
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "configuration_nucengram.NucEngramConfig",
|
| 8 |
+
"AutoModel": "modeling_nucengram.NucEngramModel",
|
| 9 |
+
"AutoModelForMaskedLM": "modeling_nucengram.NucEngramForMaskedLM"
|
| 10 |
+
},
|
| 11 |
+
"backbone": {
|
| 12 |
+
"vocab_size": 9,
|
| 13 |
+
"hidden_size": 512,
|
| 14 |
+
"intermediate_size": 2048,
|
| 15 |
+
"num_hidden_layers": 22,
|
| 16 |
+
"num_attention_heads": 16,
|
| 17 |
+
"max_position_embeddings": 8192,
|
| 18 |
+
"local_attention": 128,
|
| 19 |
+
"rope_theta_global": 160000.0,
|
| 20 |
+
"rope_theta_local": 10000.0,
|
| 21 |
+
"attn_implementation": "sdpa",
|
| 22 |
+
"tie_word_embeddings": true
|
| 23 |
+
},
|
| 24 |
+
"engram": {
|
| 25 |
+
"ngram_orders": [
|
| 26 |
+
3,
|
| 27 |
+
4,
|
| 28 |
+
5,
|
| 29 |
+
6,
|
| 30 |
+
8
|
| 31 |
+
],
|
| 32 |
+
"n_heads_per_order": 4,
|
| 33 |
+
"d_mem": 48,
|
| 34 |
+
"layer_inject_ids": [
|
| 35 |
+
1,
|
| 36 |
+
4
|
| 37 |
+
],
|
| 38 |
+
"use_conv": true,
|
| 39 |
+
"gate_temp": 1.0,
|
| 40 |
+
"seed": 0,
|
| 41 |
+
"hidden_size": 512,
|
| 42 |
+
"vocab_size": 9,
|
| 43 |
+
"pad_id": 0
|
| 44 |
+
},
|
| 45 |
+
"max_length": 8192,
|
| 46 |
+
"pad_token_id": 0,
|
| 47 |
+
"hidden_size": 512,
|
| 48 |
+
"torch_dtype": "float32",
|
| 49 |
+
"transformers_version": "5.7.0"
|
| 50 |
+
}
|
configuration_nucengram.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HuggingFace config for the NucEngram genomic language model."""
|
| 2 |
+
from transformers import PretrainedConfig
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class NucEngramConfig(PretrainedConfig):
|
| 6 |
+
model_type = "nucengram"
|
| 7 |
+
|
| 8 |
+
def __init__(self, backbone=None, engram=None, max_length=8192, pad_token_id=0, **kwargs):
|
| 9 |
+
# `backbone` = ModernBertGenomicConfig kwargs; `engram` = EngramConfig kwargs.
|
| 10 |
+
self.backbone = backbone or {}
|
| 11 |
+
self.engram = engram or {}
|
| 12 |
+
self.max_length = max_length
|
| 13 |
+
super().__init__(pad_token_id=pad_token_id, **kwargs)
|
engram.py
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Engram module — conditional N-gram memory via scalable lookup.
|
| 2 |
+
|
| 3 |
+
Adapted from DeepSeek's Engram (Conditional Memory via Scalable Lookup, Jan 2026,
|
| 4 |
+
https://github.com/deepseek-ai/Engram) for genomic LMs operating over a small
|
| 5 |
+
single-nucleotide vocabulary.
|
| 6 |
+
|
| 7 |
+
Key adaptations vs. the NLP reference:
|
| 8 |
+
* No tokenizer compression — single-nucleotide ids are already collision-free.
|
| 9 |
+
* Hashing is vectorised on the GPU (no NumPy CPU roundtrip).
|
| 10 |
+
* N-gram orders default to {3, 4, 5, 6, 8} (codons, splice, TFBS, Kozak…).
|
| 11 |
+
* Per-head table sizes auto-sized to next prime ≥ target.
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import math
|
| 16 |
+
from dataclasses import dataclass, field
|
| 17 |
+
from typing import List, Sequence
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn as nn
|
| 21 |
+
import torch.nn.functional as F
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# ---------------------------------------------------------------------------
|
| 25 |
+
# prime utilities
|
| 26 |
+
# ---------------------------------------------------------------------------
|
| 27 |
+
def _is_prime(n: int) -> bool:
|
| 28 |
+
if n < 2:
|
| 29 |
+
return False
|
| 30 |
+
if n < 4:
|
| 31 |
+
return True
|
| 32 |
+
if n % 2 == 0:
|
| 33 |
+
return False
|
| 34 |
+
i = 3
|
| 35 |
+
while i * i <= n:
|
| 36 |
+
if n % i == 0:
|
| 37 |
+
return False
|
| 38 |
+
i += 2
|
| 39 |
+
return True
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def next_prime(n: int, *, exclude: set[int] | None = None) -> int:
|
| 43 |
+
exclude = exclude or set()
|
| 44 |
+
candidate = max(2, n)
|
| 45 |
+
if candidate % 2 == 0 and candidate != 2:
|
| 46 |
+
candidate += 1
|
| 47 |
+
while True:
|
| 48 |
+
if _is_prime(candidate) and candidate not in exclude:
|
| 49 |
+
return candidate
|
| 50 |
+
candidate += 1 if candidate == 2 else 2
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# ---------------------------------------------------------------------------
|
| 54 |
+
# config
|
| 55 |
+
# ---------------------------------------------------------------------------
|
| 56 |
+
@dataclass
|
| 57 |
+
class EngramConfig:
|
| 58 |
+
vocab_size: int = 9 # token vocabulary (incl. specials)
|
| 59 |
+
pad_id: int = 0
|
| 60 |
+
ngram_orders: Sequence[int] = (3, 4, 5, 6, 8)
|
| 61 |
+
n_heads_per_order: int = 4
|
| 62 |
+
table_size_targets: dict | None = None # if None → defaults below
|
| 63 |
+
d_mem: int = 64 # per-head embedding dim
|
| 64 |
+
hidden_size: int = 512
|
| 65 |
+
kernel_size: int = 4
|
| 66 |
+
layer_inject_ids: Sequence[int] = (1, 6) # which backbone layers receive Engram
|
| 67 |
+
seed: int = 0
|
| 68 |
+
use_conv: bool = True
|
| 69 |
+
gate_temp: float = 1.0
|
| 70 |
+
# Fusion module across cross-position taps (depthwise conv by default,
|
| 71 |
+
# alternative: cross-position MLP for richer fusion). "conv" matches the
|
| 72 |
+
# paper; "mlp" replaces the depthwise conv with a 2-layer MLP that takes
|
| 73 |
+
# the same `kernel_size` dilated taps and outputs the residual. Default
|
| 74 |
+
# "conv" preserves existing behavior and old ckpt loading.
|
| 75 |
+
fusion_type: str = "conv" # "conv" | "mlp"
|
| 76 |
+
# Conv temporal direction: True = causal (left-pad only, paper default,
|
| 77 |
+
# each position sees only past dilated taps); False = bidirectional
|
| 78 |
+
# (symmetric pad, sees past+future). MLM encoder can use either; paper
|
| 79 |
+
# (decoder LM) is causal. Default True preserves existing behavior.
|
| 80 |
+
conv_causal: bool = True
|
| 81 |
+
# Gapped (wildcard) n-gram patterns, ADDED on top of the exact `ngram_orders`
|
| 82 |
+
# tables. Each entry is a string over {o, X} (or '_' for X): 'o' = informative
|
| 83 |
+
# position (its base contributes to the hash), 'X' = wildcard (base ignored ->
|
| 84 |
+
# every base there maps to the same bucket, so 4^(#X) k-mers collapse into one
|
| 85 |
+
# degenerate family). E.g. ["oXo", "Xoo", "ooX"] adds the three single-gap
|
| 86 |
+
# order-3 tables. A gapped pattern owns its own K hash tables, sized by its
|
| 87 |
+
# informative width (span - #wildcards), so wildcard tables are naturally
|
| 88 |
+
# small. None (default) -> exact-only, byte-identical to prior behavior.
|
| 89 |
+
gapped_patterns: Sequence[str] | None = None
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _default_table_targets(orders: Sequence[int]) -> dict:
|
| 93 |
+
"""Default table-size targets per n-gram order.
|
| 94 |
+
|
| 95 |
+
Heuristic: for order n with vocab_size 9, the universe is 9**n.
|
| 96 |
+
We exhaustively cover small orders and over-provision higher orders.
|
| 97 |
+
"""
|
| 98 |
+
defaults = {2: 251, 3: 1009, 4: 4099, 5: 16411, 6: 65537, 7: 131101, 8: 262147,
|
| 99 |
+
9: 524309, 10: 1048583, 12: 2097169}
|
| 100 |
+
return {n: defaults.get(n, 65537) for n in orders}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# ---------------------------------------------------------------------------
|
| 104 |
+
# vectorised n-gram hashing on GPU
|
| 105 |
+
# ---------------------------------------------------------------------------
|
| 106 |
+
class NgramHasher:
|
| 107 |
+
"""Compute multi-head multiplicative-XOR n-gram hashes for every position.
|
| 108 |
+
|
| 109 |
+
Causal: positions before the start are filled with `pad_id`.
|
| 110 |
+
Per layer-id × per order × per head, an independent random odd multiplier
|
| 111 |
+
vector and prime modulus is used. Identical recipe to the DeepSeek demo
|
| 112 |
+
but evaluated entirely with torch ops on the input device.
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
def __init__(self, cfg: EngramConfig, layer_id: int):
|
| 116 |
+
self.cfg = cfg
|
| 117 |
+
self.layer_id = layer_id
|
| 118 |
+
self.orders: list[int] = list(cfg.ngram_orders)
|
| 119 |
+
self.n_heads: int = cfg.n_heads_per_order
|
| 120 |
+
|
| 121 |
+
# Build the full pattern list. Each pattern is (span, wild) where `wild`
|
| 122 |
+
# is a per-position tuple of bools (True = wildcard, base ignored). The
|
| 123 |
+
# exact `ngram_orders` come FIRST as no-wildcard patterns, so when no
|
| 124 |
+
# gapped patterns are configured the prime/RNG draw order — and thus old
|
| 125 |
+
# checkpoints — is byte-identical to the previous order-based code. Any
|
| 126 |
+
# explicit gapped patterns are appended after.
|
| 127 |
+
patterns: list[tuple[int, tuple[bool, ...]]] = [
|
| 128 |
+
(n, (False,) * n) for n in self.orders
|
| 129 |
+
]
|
| 130 |
+
for spec in (cfg.gapped_patterns or []):
|
| 131 |
+
span = len(spec)
|
| 132 |
+
# convention: spec is written left->right = oldest (t-span+1) -> current (t).
|
| 133 |
+
# internally column j of `tokens` holds position t-j (column 0 = current),
|
| 134 |
+
# so reverse the spec to index columns: wild[j] = spec[span-1-j] is wildcard.
|
| 135 |
+
wild = tuple(c in "Xx_" for c in reversed(spec))
|
| 136 |
+
patterns.append((span, wild))
|
| 137 |
+
self.patterns = patterns
|
| 138 |
+
self.n_patterns = len(patterns)
|
| 139 |
+
|
| 140 |
+
# Each pattern's table size is governed by its informative width
|
| 141 |
+
# (span - #wildcards): a gapped pattern collapses 4^(#wild) k-mers into a
|
| 142 |
+
# single bucket, so it needs a far smaller table than its span implies.
|
| 143 |
+
defaults = {2: 251, 3: 1009, 4: 4099, 5: 16411, 6: 65537,
|
| 144 |
+
7: 131101, 8: 262147, 9: 524309, 10: 1048583, 12: 2097169}
|
| 145 |
+
override = cfg.table_size_targets
|
| 146 |
+
|
| 147 |
+
def _target_for(inf: int) -> int:
|
| 148 |
+
if override is not None and inf in override:
|
| 149 |
+
return override[inf]
|
| 150 |
+
return defaults.get(inf, 65537)
|
| 151 |
+
|
| 152 |
+
# per-pattern, per-head prime modulus (avoid duplicates across heads)
|
| 153 |
+
seen: set[int] = set()
|
| 154 |
+
self.pattern_mods: list[list[int]] = []
|
| 155 |
+
for (span, wild) in patterns:
|
| 156 |
+
inf = span - sum(wild)
|
| 157 |
+
tgt = _target_for(inf)
|
| 158 |
+
mods = []
|
| 159 |
+
cur = tgt - 1
|
| 160 |
+
for _ in range(self.n_heads):
|
| 161 |
+
p = next_prime(cur, exclude=seen)
|
| 162 |
+
seen.add(p)
|
| 163 |
+
mods.append(p)
|
| 164 |
+
cur = p
|
| 165 |
+
self.pattern_mods.append(mods)
|
| 166 |
+
|
| 167 |
+
# per-pattern, per-head, per-position multipliers (deterministic from
|
| 168 |
+
# seed+layer). Wildcard columns are zeroed so that position contributes
|
| 169 |
+
# 0 to the multiply-XOR mix -> every base there maps to the same bucket.
|
| 170 |
+
# HF packaging note: NgramHasher is NOT an nn.Module, and
|
| 171 |
+
# `from_pretrained` builds the model under a meta-device context — so we
|
| 172 |
+
# must NOT create these tensors in __init__ (they would be meta and
|
| 173 |
+
# unrecoverable). Store only the seed; build the multipliers lazily,
|
| 174 |
+
# per real device, in _to(). Values are byte-identical to before.
|
| 175 |
+
self._mult_seed = cfg.seed + 10007 * (layer_id + 1)
|
| 176 |
+
self._mult_upper = 1 << 50 # keeps multipliers*vocab_size < 2**63 mid-XOR
|
| 177 |
+
|
| 178 |
+
# backward-compat alias: head_mods keyed by exact order (first len(orders)
|
| 179 |
+
# patterns are the exact orders, in order).
|
| 180 |
+
self.head_mods: dict[int, list[int]] = {
|
| 181 |
+
n: self.pattern_mods[i] for i, n in enumerate(self.orders)
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
self._device_multipliers: dict[str, list[torch.Tensor]] = {}
|
| 185 |
+
self._device_mods: dict[str, list[torch.Tensor]] = {}
|
| 186 |
+
|
| 187 |
+
def _build_multipliers(self, device):
|
| 188 |
+
gen = torch.Generator(device="cpu")
|
| 189 |
+
gen.manual_seed(self._mult_seed)
|
| 190 |
+
mults = []
|
| 191 |
+
for (span, wild) in self.patterns:
|
| 192 |
+
# shape [n_heads, span] of odd ints
|
| 193 |
+
r = torch.randint(0, self._mult_upper // 2, (self.n_heads, span),
|
| 194 |
+
generator=gen, dtype=torch.int64)
|
| 195 |
+
r = r * 2 + 1 # odd
|
| 196 |
+
if any(wild):
|
| 197 |
+
keep = torch.tensor([0 if w else 1 for w in wild], dtype=torch.int64)
|
| 198 |
+
r = r * keep.view(1, span) # zero wildcard columns
|
| 199 |
+
mults.append(r.to(device))
|
| 200 |
+
return mults
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------
|
| 203 |
+
def _to(self, device: torch.device):
|
| 204 |
+
key = str(device)
|
| 205 |
+
if key not in self._device_multipliers:
|
| 206 |
+
self._device_multipliers[key] = self._build_multipliers(device)
|
| 207 |
+
self._device_mods[key] = [
|
| 208 |
+
torch.tensor(m, device=device, dtype=torch.int64)
|
| 209 |
+
for m in self.pattern_mods
|
| 210 |
+
]
|
| 211 |
+
return self._device_multipliers[key], self._device_mods[key]
|
| 212 |
+
|
| 213 |
+
# ------------------------------------------------------------------
|
| 214 |
+
@torch.no_grad()
|
| 215 |
+
def hash(self, input_ids: torch.Tensor) -> torch.Tensor:
|
| 216 |
+
"""Return hash ids of shape [B, T, n_patterns*K] dtype int64.
|
| 217 |
+
|
| 218 |
+
Layout along the last dim: pattern-major then head-minor —
|
| 219 |
+
[(pattern[0], h=0..K-1), (pattern[1], h=0..K-1), ...]
|
| 220 |
+
Exact orders come first, gapped patterns after.
|
| 221 |
+
"""
|
| 222 |
+
assert input_ids.dim() == 2, "expected [B, T] input ids"
|
| 223 |
+
B, T = input_ids.shape
|
| 224 |
+
device = input_ids.device
|
| 225 |
+
x64 = input_ids.to(torch.int64)
|
| 226 |
+
mults, mods = self._to(device)
|
| 227 |
+
pad = self.cfg.pad_id
|
| 228 |
+
|
| 229 |
+
# Pre-compute left-shifted views of the input. shifts[k] = x shifted right by k,
|
| 230 |
+
# so position t holds the token that was at position t-k (pad if out of range).
|
| 231 |
+
max_n = max(span for span, _ in self.patterns)
|
| 232 |
+
shifts: list[torch.Tensor] = [x64]
|
| 233 |
+
for k in range(1, max_n):
|
| 234 |
+
shifted = torch.full_like(x64, pad)
|
| 235 |
+
shifted[:, k:] = x64[:, :-k]
|
| 236 |
+
shifts.append(shifted)
|
| 237 |
+
|
| 238 |
+
out_chunks: list[torch.Tensor] = []
|
| 239 |
+
for i, (span, wild) in enumerate(self.patterns):
|
| 240 |
+
mult = mults[i] # [K, span] int64 (wildcard cols = 0)
|
| 241 |
+
head_mods = mods[i] # [K] int64
|
| 242 |
+
tokens = torch.stack(shifts[:span], dim=-1) # [B, T, span]
|
| 243 |
+
|
| 244 |
+
# mix[b,t,k] = (tokens[b,t,0] * mult[k,0]) XOR (tokens[b,t,1] * mult[k,1]) XOR ...
|
| 245 |
+
# broadcast: tokens [B,T,1,span] * mult [1,1,K,span] -> [B,T,K,span], reduce-XOR.
|
| 246 |
+
# Wildcard columns have mult=0 -> contribute 0 -> XOR-identity (base ignored).
|
| 247 |
+
scaled = tokens.unsqueeze(2) * mult.view(1, 1, self.n_heads, span)
|
| 248 |
+
mix = scaled[..., 0]
|
| 249 |
+
for j in range(1, span):
|
| 250 |
+
mix = torch.bitwise_xor(mix, scaled[..., j])
|
| 251 |
+
|
| 252 |
+
# mod per head
|
| 253 |
+
head_hash = mix % head_mods.view(1, 1, self.n_heads) # [B, T, K]
|
| 254 |
+
out_chunks.append(head_hash)
|
| 255 |
+
|
| 256 |
+
return torch.cat(out_chunks, dim=-1) # [B, T, n_patterns*K]
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
# ---------------------------------------------------------------------------
|
| 260 |
+
# multi-head embedding: one nn.Embedding sharing the underlying buffer
|
| 261 |
+
# ---------------------------------------------------------------------------
|
| 262 |
+
class MultiHeadEmbedding(nn.Module):
|
| 263 |
+
"""Wrap multiple variable-size embedding tables in a single nn.Embedding.
|
| 264 |
+
|
| 265 |
+
For head k with size N_k and dim d, addresses live in [Σ_{<k} N_j, Σ_{≤k} N_j).
|
| 266 |
+
Forward expects per-position per-head ids in their *local* (per-head) range.
|
| 267 |
+
"""
|
| 268 |
+
|
| 269 |
+
def __init__(self, table_sizes: Sequence[int], dim: int):
|
| 270 |
+
super().__init__()
|
| 271 |
+
self.table_sizes = list(table_sizes)
|
| 272 |
+
self.dim = dim
|
| 273 |
+
offsets = [0]
|
| 274 |
+
for n in self.table_sizes[:-1]:
|
| 275 |
+
offsets.append(offsets[-1] + n)
|
| 276 |
+
self.register_buffer("offsets", torch.tensor(offsets, dtype=torch.long))
|
| 277 |
+
self.total = sum(self.table_sizes)
|
| 278 |
+
self.emb = nn.Embedding(self.total, dim)
|
| 279 |
+
# Modest init — defaults to N(0, 1) which is too large for residual injection.
|
| 280 |
+
nn.init.normal_(self.emb.weight, mean=0.0, std=0.02)
|
| 281 |
+
|
| 282 |
+
def forward(self, head_ids: torch.Tensor) -> torch.Tensor:
|
| 283 |
+
"""head_ids: [..., H] in local per-head range. Returns [..., H, dim]."""
|
| 284 |
+
shifted = head_ids + self.offsets
|
| 285 |
+
return self.emb(shifted)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
# ---------------------------------------------------------------------------
|
| 289 |
+
# the Engram block
|
| 290 |
+
# ---------------------------------------------------------------------------
|
| 291 |
+
class Engram(nn.Module):
|
| 292 |
+
"""A single Engram injection layer.
|
| 293 |
+
|
| 294 |
+
Forward:
|
| 295 |
+
hidden_states: [B, T, hidden]
|
| 296 |
+
input_ids: [B, T] (token ids; required because hashing uses raw tokens)
|
| 297 |
+
Returns:
|
| 298 |
+
delta: [B, T, hidden] (to be added to the residual stream)
|
| 299 |
+
"""
|
| 300 |
+
|
| 301 |
+
def __init__(self, cfg: EngramConfig, layer_id: int):
|
| 302 |
+
super().__init__()
|
| 303 |
+
self.cfg = cfg
|
| 304 |
+
self.layer_id = layer_id
|
| 305 |
+
self.hasher = NgramHasher(cfg, layer_id=layer_id)
|
| 306 |
+
|
| 307 |
+
flat_table_sizes: list[int] = []
|
| 308 |
+
for mods in self.hasher.pattern_mods:
|
| 309 |
+
flat_table_sizes.extend(mods)
|
| 310 |
+
|
| 311 |
+
self.embedding = MultiHeadEmbedding(flat_table_sizes, cfg.d_mem)
|
| 312 |
+
|
| 313 |
+
n_heads_total = self.hasher.n_patterns * cfg.n_heads_per_order
|
| 314 |
+
engram_hidden = n_heads_total * cfg.d_mem
|
| 315 |
+
self.value_proj = nn.Linear(engram_hidden, cfg.hidden_size, bias=False)
|
| 316 |
+
self.key_proj = nn.Linear(engram_hidden, cfg.hidden_size, bias=False)
|
| 317 |
+
self.norm_q = nn.RMSNorm(cfg.hidden_size)
|
| 318 |
+
self.norm_k = nn.RMSNorm(cfg.hidden_size)
|
| 319 |
+
|
| 320 |
+
self.conv = None
|
| 321 |
+
self.fusion_mlp = None
|
| 322 |
+
self.conv_pad = 0
|
| 323 |
+
if cfg.use_conv:
|
| 324 |
+
dilation = max(span for span, _ in self.hasher.patterns)
|
| 325 |
+
self.dilation = dilation
|
| 326 |
+
self.conv_pad = (cfg.kernel_size - 1) * dilation
|
| 327 |
+
if cfg.fusion_type == "conv":
|
| 328 |
+
# depthwise 1-D causal conv over the sequence axis (paper default)
|
| 329 |
+
self.conv = nn.Conv1d(
|
| 330 |
+
in_channels=cfg.hidden_size,
|
| 331 |
+
out_channels=cfg.hidden_size,
|
| 332 |
+
kernel_size=cfg.kernel_size,
|
| 333 |
+
groups=cfg.hidden_size,
|
| 334 |
+
bias=False,
|
| 335 |
+
dilation=dilation,
|
| 336 |
+
)
|
| 337 |
+
# zero-init: identity at initialisation (conv contributes 0 to residual)
|
| 338 |
+
nn.init.zeros_(self.conv.weight)
|
| 339 |
+
elif cfg.fusion_type == "mlp":
|
| 340 |
+
# 2-layer MLP that fuses `kernel_size` dilated taps cross-channel.
|
| 341 |
+
# Input: concat(v_t, v_{t-d}, v_{t-2d}, ..., v_{t-(k-1)d}) along channel dim.
|
| 342 |
+
fusion_in = cfg.kernel_size * cfg.hidden_size
|
| 343 |
+
self.fusion_mlp = nn.Sequential(
|
| 344 |
+
nn.Linear(fusion_in, 2 * cfg.hidden_size, bias=False),
|
| 345 |
+
nn.GELU(),
|
| 346 |
+
nn.Linear(2 * cfg.hidden_size, cfg.hidden_size, bias=False),
|
| 347 |
+
)
|
| 348 |
+
# zero-init the last layer so the fusion contributes 0 at init
|
| 349 |
+
nn.init.zeros_(self.fusion_mlp[-1].weight)
|
| 350 |
+
else:
|
| 351 |
+
raise ValueError(
|
| 352 |
+
f"unknown fusion_type={cfg.fusion_type!r}; "
|
| 353 |
+
f"expected 'conv' or 'mlp'"
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
# ------------------------------------------------------------------
|
| 357 |
+
def forward(self, hidden_states: torch.Tensor, input_ids: torch.Tensor) -> torch.Tensor:
|
| 358 |
+
B, T, _ = hidden_states.shape
|
| 359 |
+
# [B, T, H_total] where H_total = O * K
|
| 360 |
+
hash_ids = self.hasher.hash(input_ids)
|
| 361 |
+
# [B, T, H_total, d_mem] → [B, T, H_total*d_mem]
|
| 362 |
+
emb = self.embedding(hash_ids).flatten(start_dim=-2)
|
| 363 |
+
|
| 364 |
+
# context-aware gate: query from hidden_states, key from emb
|
| 365 |
+
q = self.norm_q(hidden_states)
|
| 366 |
+
k = self.norm_k(self.key_proj(emb))
|
| 367 |
+
gate_score = (q * k).sum(dim=-1) / math.sqrt(self.cfg.hidden_size)
|
| 368 |
+
# DeepSeek's nonlinear soft gate: sign·sqrt(|.|)·sigmoid
|
| 369 |
+
gate = (gate_score.abs().clamp_min(1e-6).sqrt() * gate_score.sign())
|
| 370 |
+
gate = torch.sigmoid(gate / self.cfg.gate_temp).unsqueeze(-1) # [B, T, 1]
|
| 371 |
+
|
| 372 |
+
v = self.value_proj(emb) # [B, T, hidden]
|
| 373 |
+
v_gated = gate * v # [B, T, hidden]
|
| 374 |
+
|
| 375 |
+
if self.conv is not None:
|
| 376 |
+
# conv expects [B, C, T]. Pad keeps output length = T.
|
| 377 |
+
# causal: all pad on the left (only past taps).
|
| 378 |
+
# bidirectional: split pad left/right (past + future taps).
|
| 379 |
+
x = v_gated.transpose(1, 2)
|
| 380 |
+
if self.cfg.conv_causal:
|
| 381 |
+
x = F.pad(x, (self.conv_pad, 0))
|
| 382 |
+
else:
|
| 383 |
+
left = self.conv_pad // 2
|
| 384 |
+
x = F.pad(x, (left, self.conv_pad - left))
|
| 385 |
+
y = self.conv(x).transpose(1, 2) # [B, T, hidden]
|
| 386 |
+
return v_gated + y
|
| 387 |
+
|
| 388 |
+
if self.fusion_mlp is not None:
|
| 389 |
+
# left-pad causally, then extract `kernel_size` dilated taps along T
|
| 390 |
+
# and concat along channel dim before MLP fusion.
|
| 391 |
+
B, T, H = v_gated.shape
|
| 392 |
+
padded = F.pad(v_gated.transpose(1, 2), (self.conv_pad, 0)).transpose(1, 2)
|
| 393 |
+
# padded: [B, T + conv_pad, H]
|
| 394 |
+
taps = [padded[:, i * self.dilation : i * self.dilation + T, :]
|
| 395 |
+
for i in range(self.cfg.kernel_size)]
|
| 396 |
+
concat = torch.cat(taps, dim=-1) # [B, T, kernel*hidden]
|
| 397 |
+
y = self.fusion_mlp(concat) # [B, T, hidden]
|
| 398 |
+
return v_gated + y
|
| 399 |
+
|
| 400 |
+
return v_gated
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d6091bba04d62c45b0b59a9e0e2f21fba2f16eb0c4712295aa81d60aa6cf3bcf
|
| 3 |
+
size 914637444
|
model_modernbert.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ModernBERT-based encoder for genomic MLM, built on HuggingFace.
|
| 2 |
+
|
| 3 |
+
We construct ``ModernBertForMaskedLM`` from scratch with our 9-token DNA
|
| 4 |
+
vocabulary and configurable max_position. Supports both ``sdpa`` and
|
| 5 |
+
``flash_attention_2`` attention implementations.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from typing import Literal
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# ─── Patch HF ModernBertConfig for global_attn_every_n_layers=1 ───────────
|
| 18 |
+
# transformers 5.7.0 has a bug: when all layers are "full_attention", the
|
| 19 |
+
# original convert_rope_params_to_dict unconditionally injects a
|
| 20 |
+
# "sliding_attention" entry into rope_parameters, then standardize_rope_params
|
| 21 |
+
# takes its Case-1 (single-rope) path and mutates rope_parameters with
|
| 22 |
+
# top-level "rope_type"/"rope_theta" keys — the strict-dataclass validator
|
| 23 |
+
# then rejects the result because those keys aren't in the Literal subset.
|
| 24 |
+
# Fix: only add "sliding_attention" rope params when layer_types actually has
|
| 25 |
+
# at least one sliding_attention layer. Drop it otherwise so standardize takes
|
| 26 |
+
# the Case-2 (per-layer-type) path with only "full_attention".
|
| 27 |
+
def _patch_modernbert_rope_params():
|
| 28 |
+
from transformers import ModernBertConfig
|
| 29 |
+
if getattr(ModernBertConfig, "_nucengram_patched", False):
|
| 30 |
+
return
|
| 31 |
+
def patched(self, **kwargs):
|
| 32 |
+
rope_scaling = kwargs.pop("rope_scaling", None)
|
| 33 |
+
default_rope_params = {
|
| 34 |
+
"sliding_attention": {"rope_type": "default"},
|
| 35 |
+
"full_attention": {"rope_type": "default"},
|
| 36 |
+
}
|
| 37 |
+
self.rope_parameters = (self.rope_parameters
|
| 38 |
+
if self.rope_parameters is not None
|
| 39 |
+
else default_rope_params)
|
| 40 |
+
if rope_scaling is not None:
|
| 41 |
+
if "full_attention" in self.rope_parameters:
|
| 42 |
+
self.rope_parameters["full_attention"].update(rope_scaling)
|
| 43 |
+
if "sliding_attention" in self.rope_parameters:
|
| 44 |
+
self.rope_parameters["sliding_attention"].update(rope_scaling)
|
| 45 |
+
|
| 46 |
+
needs_sliding = (self.layer_types is not None
|
| 47 |
+
and "sliding_attention" in set(self.layer_types))
|
| 48 |
+
|
| 49 |
+
if self.rope_parameters.get("full_attention") is None:
|
| 50 |
+
self.rope_parameters["full_attention"] = {"rope_type": "default"}
|
| 51 |
+
self.rope_parameters["full_attention"].setdefault(
|
| 52 |
+
"rope_theta", kwargs.pop("global_rope_theta", self.default_theta["global"]))
|
| 53 |
+
|
| 54 |
+
if needs_sliding:
|
| 55 |
+
if self.rope_parameters.get("sliding_attention") is None:
|
| 56 |
+
self.rope_parameters["sliding_attention"] = {"rope_type": "default"}
|
| 57 |
+
self.rope_parameters["sliding_attention"].setdefault(
|
| 58 |
+
"rope_theta", kwargs.pop("local_rope_theta", self.default_theta["local"]))
|
| 59 |
+
else:
|
| 60 |
+
# No sliding-attention layers → drop the entry so standardize_rope_params
|
| 61 |
+
# takes Case-2 (per-layer-type) with only "full_attention" key.
|
| 62 |
+
self.rope_parameters.pop("sliding_attention", None)
|
| 63 |
+
kwargs.pop("local_rope_theta", None)
|
| 64 |
+
|
| 65 |
+
self.standardize_rope_params()
|
| 66 |
+
return kwargs
|
| 67 |
+
ModernBertConfig.convert_rope_params_to_dict = patched
|
| 68 |
+
ModernBertConfig._nucengram_patched = True
|
| 69 |
+
|
| 70 |
+
_patch_modernbert_rope_params()
|
| 71 |
+
|
| 72 |
+
from .tokenizer import VOCAB_SIZE, PAD_ID, BOS_ID, EOS_ID, MASK_ID
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
AttentionImpl = Literal["sdpa", "flash_attention_2", "eager"]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@dataclass
|
| 79 |
+
class ModernBertGenomicConfig:
|
| 80 |
+
vocab_size: int = VOCAB_SIZE
|
| 81 |
+
hidden_size: int = 384
|
| 82 |
+
intermediate_size: int = 1024
|
| 83 |
+
num_hidden_layers: int = 8
|
| 84 |
+
num_attention_heads: int = 6
|
| 85 |
+
max_position_embeddings: int = 8192
|
| 86 |
+
local_attention: int = 128 # span for local attention layers
|
| 87 |
+
global_attn_every_n_layers: int = 3 # =3 alternating GLOBAL+2×LOCAL; =1 every layer GLOBAL
|
| 88 |
+
rope_theta_global: float = 160000.0 # bigger theta for long context
|
| 89 |
+
rope_theta_local: float = 10000.0
|
| 90 |
+
attn_implementation: AttentionImpl = "sdpa"
|
| 91 |
+
pad_token_id: int = PAD_ID
|
| 92 |
+
bos_token_id: int = BOS_ID
|
| 93 |
+
eos_token_id: int = EOS_ID
|
| 94 |
+
cls_token_id: int = BOS_ID
|
| 95 |
+
sep_token_id: int = EOS_ID
|
| 96 |
+
mask_token_id: int = MASK_ID
|
| 97 |
+
norm_eps: float = 1e-5
|
| 98 |
+
embedding_dropout: float = 0.0
|
| 99 |
+
attention_dropout: float = 0.0
|
| 100 |
+
mlp_dropout: float = 0.0
|
| 101 |
+
initializer_range: float = 0.02
|
| 102 |
+
tie_word_embeddings: bool = True
|
| 103 |
+
sparse_prediction: bool = False
|
| 104 |
+
deterministic_flash_attn: bool = False
|
| 105 |
+
bf16: bool = True
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def build_modernbert(cfg: ModernBertGenomicConfig):
|
| 109 |
+
"""Construct a ModernBertForMaskedLM with the given config."""
|
| 110 |
+
from transformers import ModernBertConfig, ModernBertForMaskedLM
|
| 111 |
+
|
| 112 |
+
# When global_attn_every_n_layers=1 every layer is full_attention — no
|
| 113 |
+
# sliding rope params needed. The HF patch above keeps strict validation happy.
|
| 114 |
+
if cfg.global_attn_every_n_layers == 1:
|
| 115 |
+
rope_parameters = {"full_attention": {"rope_theta": cfg.rope_theta_global}}
|
| 116 |
+
else:
|
| 117 |
+
rope_parameters = {
|
| 118 |
+
"full_attention": {"rope_theta": cfg.rope_theta_global},
|
| 119 |
+
"sliding_attention": {"rope_theta": cfg.rope_theta_local},
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
hf_cfg = ModernBertConfig(
|
| 123 |
+
vocab_size=cfg.vocab_size,
|
| 124 |
+
hidden_size=cfg.hidden_size,
|
| 125 |
+
intermediate_size=cfg.intermediate_size,
|
| 126 |
+
num_hidden_layers=cfg.num_hidden_layers,
|
| 127 |
+
num_attention_heads=cfg.num_attention_heads,
|
| 128 |
+
hidden_activation="gelu",
|
| 129 |
+
max_position_embeddings=cfg.max_position_embeddings,
|
| 130 |
+
norm_eps=cfg.norm_eps,
|
| 131 |
+
norm_bias=False,
|
| 132 |
+
pad_token_id=cfg.pad_token_id,
|
| 133 |
+
bos_token_id=cfg.bos_token_id,
|
| 134 |
+
eos_token_id=cfg.eos_token_id,
|
| 135 |
+
cls_token_id=cfg.cls_token_id,
|
| 136 |
+
sep_token_id=cfg.sep_token_id,
|
| 137 |
+
attention_bias=False,
|
| 138 |
+
attention_dropout=cfg.attention_dropout,
|
| 139 |
+
local_attention=cfg.local_attention,
|
| 140 |
+
global_attn_every_n_layers=cfg.global_attn_every_n_layers,
|
| 141 |
+
rope_parameters=rope_parameters,
|
| 142 |
+
embedding_dropout=cfg.embedding_dropout,
|
| 143 |
+
mlp_bias=False,
|
| 144 |
+
mlp_dropout=cfg.mlp_dropout,
|
| 145 |
+
decoder_bias=True,
|
| 146 |
+
classifier_pooling="mean",
|
| 147 |
+
deterministic_flash_attn=cfg.deterministic_flash_attn,
|
| 148 |
+
sparse_prediction=cfg.sparse_prediction,
|
| 149 |
+
tie_word_embeddings=cfg.tie_word_embeddings,
|
| 150 |
+
initializer_range=cfg.initializer_range,
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
# Use FA2 only if we asked for it AND the install supports it.
|
| 154 |
+
impl = cfg.attn_implementation
|
| 155 |
+
if impl == "flash_attention_2":
|
| 156 |
+
try:
|
| 157 |
+
import flash_attn # noqa: F401
|
| 158 |
+
except ImportError as e: # pragma: no cover
|
| 159 |
+
raise RuntimeError(
|
| 160 |
+
"attn_implementation='flash_attention_2' requested but "
|
| 161 |
+
"flash-attn is not importable. Install flash-attn or use 'sdpa'."
|
| 162 |
+
) from e
|
| 163 |
+
|
| 164 |
+
model = ModernBertForMaskedLM(hf_cfg)
|
| 165 |
+
# HuggingFace stores the chosen attention impl on the config as well as on
|
| 166 |
+
# individual modules; we set it explicitly on the loaded model so it takes
|
| 167 |
+
# effect for our from-scratch instantiation.
|
| 168 |
+
model.config._attn_implementation = impl
|
| 169 |
+
if hasattr(model, "set_attn_implementation"):
|
| 170 |
+
model.set_attn_implementation(impl)
|
| 171 |
+
|
| 172 |
+
return model, hf_cfg
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# ---------------------------------------------------------------------------
|
| 176 |
+
# common adapter so the training loop can swap models
|
| 177 |
+
# ---------------------------------------------------------------------------
|
| 178 |
+
class ModernBertWrapper(nn.Module):
|
| 179 |
+
"""Thin adapter that gives a ModernBertForMaskedLM the same forward
|
| 180 |
+
signature as our in-house ``NucEngramModel.forward`` (returns dict with
|
| 181 |
+
``loss``, ``logits``, ``hidden``).
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
def __init__(self, cfg: ModernBertGenomicConfig):
|
| 185 |
+
super().__init__()
|
| 186 |
+
self.cfg = cfg
|
| 187 |
+
self.model, self.hf_cfg = build_modernbert(cfg)
|
| 188 |
+
|
| 189 |
+
@property
|
| 190 |
+
def attn_implementation(self) -> str:
|
| 191 |
+
impl = getattr(self.model.config, "_attn_implementation", None)
|
| 192 |
+
if impl:
|
| 193 |
+
return impl
|
| 194 |
+
return getattr(self.model.config, "attn_implementation", "unknown")
|
| 195 |
+
|
| 196 |
+
def num_params(self, only_trainable: bool = True) -> dict:
|
| 197 |
+
backbone = sum(p.numel() for p in self.parameters()
|
| 198 |
+
if p.requires_grad or not only_trainable)
|
| 199 |
+
return {"backbone": backbone, "memory": 0, "total": backbone}
|
| 200 |
+
|
| 201 |
+
def forward(self,
|
| 202 |
+
input_ids: torch.Tensor,
|
| 203 |
+
labels: torch.Tensor | None = None,
|
| 204 |
+
attention_mask: torch.Tensor | None = None) -> dict:
|
| 205 |
+
# ModernBert wants attention_mask in {0, 1} (1 = keep).
|
| 206 |
+
if attention_mask is not None:
|
| 207 |
+
attention_mask = attention_mask.to(torch.long)
|
| 208 |
+
out = self.model(
|
| 209 |
+
input_ids=input_ids,
|
| 210 |
+
attention_mask=attention_mask,
|
| 211 |
+
labels=labels,
|
| 212 |
+
output_hidden_states=False,
|
| 213 |
+
)
|
| 214 |
+
return {
|
| 215 |
+
"loss": out.loss,
|
| 216 |
+
"logits": out.logits,
|
| 217 |
+
"hidden": None,
|
| 218 |
+
}
|
model_modernbert_engram.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ModernBERT-based encoder for genomic MLM, augmented with Engram injection.
|
| 2 |
+
|
| 3 |
+
This wrapper adds Engram (conditional N-gram memory) deltas to specific
|
| 4 |
+
ModernBERT encoder layers via forward pre-hooks. It does NOT modify HF's
|
| 5 |
+
ModernBERT code, the ``engram`` module, or the ``model_modernbert`` module —
|
| 6 |
+
all three are reused unchanged.
|
| 7 |
+
|
| 8 |
+
Backbone parameter names match ``ModernBertWrapper`` exactly so a checkpoint
|
| 9 |
+
trained as ``model_type='modernbert'`` can be warm-started into this class
|
| 10 |
+
with ``strict=False``: only ``engram_blocks.*`` keys are missing.
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
from dataclasses import replace
|
| 15 |
+
from typing import Sequence
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn as nn
|
| 19 |
+
|
| 20 |
+
from .engram import Engram, EngramConfig
|
| 21 |
+
from .model_modernbert import (
|
| 22 |
+
ModernBertGenomicConfig,
|
| 23 |
+
build_modernbert,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _validate_layer_inject_ids(ids: Sequence[int], num_layers: int) -> list[int]:
|
| 28 |
+
out: list[int] = []
|
| 29 |
+
for idx, i in enumerate(ids):
|
| 30 |
+
if isinstance(i, bool) or not isinstance(i, int):
|
| 31 |
+
raise ValueError(
|
| 32 |
+
f"layer_inject_ids[{idx}] = {i!r} is not an int (bools are rejected too)"
|
| 33 |
+
)
|
| 34 |
+
if i < 0 or i >= num_layers:
|
| 35 |
+
raise ValueError(
|
| 36 |
+
f"layer_inject_ids[{idx}] = {i} out of range [0, {num_layers})"
|
| 37 |
+
)
|
| 38 |
+
out.append(i)
|
| 39 |
+
if len(set(out)) != len(out):
|
| 40 |
+
raise ValueError(f"layer_inject_ids contains duplicates: {list(ids)}")
|
| 41 |
+
return out
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _engram_key(i: int) -> str:
|
| 45 |
+
return f"layer_{i:04d}"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class ModernBertEngramWrapper(nn.Module):
|
| 49 |
+
"""ModernBERT encoder for MLM with Engram modules injected at chosen layers.
|
| 50 |
+
|
| 51 |
+
The wrapper:
|
| 52 |
+
* Constructs a stock ``ModernBertForMaskedLM`` via :func:`build_modernbert`
|
| 53 |
+
and stores it at ``self.model`` (identical attribute layout to
|
| 54 |
+
:class:`ModernBertWrapper`, so state_dict keys are exactly the same
|
| 55 |
+
for every backbone tensor).
|
| 56 |
+
* Adds ``self.engram_blocks: nn.ModuleDict`` keyed by ``layer_{i:04d}``,
|
| 57 |
+
one :class:`Engram` per index in ``engram_cfg.layer_inject_ids``.
|
| 58 |
+
* Registers a ``forward_pre_hook(with_kwargs=True)`` on each target
|
| 59 |
+
encoder layer that adds ``engram_blocks[layer_{i:04d}](hidden, input_ids)``
|
| 60 |
+
to the layer's input ``hidden_states``.
|
| 61 |
+
|
| 62 |
+
``input_ids`` is stashed on ``self._current_input_ids`` at the start of
|
| 63 |
+
each ``forward`` and never cleared inside the same call, so layers
|
| 64 |
+
recomputed during backward (e.g. under ``torch.utils.checkpoint``) still
|
| 65 |
+
see the right ids.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
def __init__(self, cfg: ModernBertGenomicConfig, engram_cfg: EngramConfig):
|
| 69 |
+
super().__init__()
|
| 70 |
+
ids = _validate_layer_inject_ids(engram_cfg.layer_inject_ids, cfg.num_hidden_layers)
|
| 71 |
+
engram_cfg = replace(
|
| 72 |
+
engram_cfg,
|
| 73 |
+
hidden_size=cfg.hidden_size,
|
| 74 |
+
vocab_size=cfg.vocab_size,
|
| 75 |
+
pad_id=cfg.pad_token_id,
|
| 76 |
+
)
|
| 77 |
+
self.cfg = cfg
|
| 78 |
+
self.engram_cfg = engram_cfg
|
| 79 |
+
# IDENTICAL outer attribute layout to ModernBertWrapper:
|
| 80 |
+
self.model, self.hf_cfg = build_modernbert(cfg)
|
| 81 |
+
# Sibling engram modules — NOT inside self.model, so backbone keys are unchanged.
|
| 82 |
+
self.engram_blocks = nn.ModuleDict(
|
| 83 |
+
{_engram_key(i): Engram(engram_cfg, layer_id=i) for i in ids}
|
| 84 |
+
)
|
| 85 |
+
for i in ids:
|
| 86 |
+
self.model.model.layers[i].register_forward_pre_hook(
|
| 87 |
+
self._make_hook(i), with_kwargs=True
|
| 88 |
+
)
|
| 89 |
+
self._current_input_ids: torch.Tensor | None = None
|
| 90 |
+
|
| 91 |
+
@property
|
| 92 |
+
def attn_implementation(self) -> str:
|
| 93 |
+
impl = getattr(self.model.config, "_attn_implementation", None)
|
| 94 |
+
if impl:
|
| 95 |
+
return impl
|
| 96 |
+
return getattr(self.model.config, "attn_implementation", "unknown")
|
| 97 |
+
|
| 98 |
+
def num_params(self, only_trainable: bool = True) -> dict:
|
| 99 |
+
backbone = 0
|
| 100 |
+
memory = 0
|
| 101 |
+
for name, p in self.named_parameters():
|
| 102 |
+
if only_trainable and not p.requires_grad:
|
| 103 |
+
continue
|
| 104 |
+
n = p.numel()
|
| 105 |
+
if "engram" in name and "embedding.emb" in name:
|
| 106 |
+
memory += n
|
| 107 |
+
else:
|
| 108 |
+
backbone += n
|
| 109 |
+
return {"backbone": backbone, "memory": memory, "total": backbone + memory}
|
| 110 |
+
|
| 111 |
+
def _make_hook(self, layer_id: int):
|
| 112 |
+
key = _engram_key(layer_id)
|
| 113 |
+
# Cache to avoid one dict lookup per call.
|
| 114 |
+
block_ref = self.engram_blocks[key]
|
| 115 |
+
wrapper_self = self
|
| 116 |
+
|
| 117 |
+
def hook(module, args, kwargs):
|
| 118 |
+
ids = wrapper_self._current_input_ids
|
| 119 |
+
if ids is None:
|
| 120 |
+
return None # cold-call safety (e.g. tracing); do nothing
|
| 121 |
+
if args:
|
| 122 |
+
hidden = args[0]
|
| 123 |
+
delta = block_ref(hidden, input_ids=ids)
|
| 124 |
+
new_args = (hidden + delta, *args[1:])
|
| 125 |
+
return new_args, kwargs
|
| 126 |
+
hidden = kwargs["hidden_states"]
|
| 127 |
+
delta = block_ref(hidden, input_ids=ids)
|
| 128 |
+
kwargs = {**kwargs, "hidden_states": hidden + delta}
|
| 129 |
+
return args, kwargs
|
| 130 |
+
|
| 131 |
+
return hook
|
| 132 |
+
|
| 133 |
+
def forward(
|
| 134 |
+
self,
|
| 135 |
+
input_ids: torch.Tensor,
|
| 136 |
+
labels: torch.Tensor | None = None,
|
| 137 |
+
attention_mask: torch.Tensor | None = None,
|
| 138 |
+
) -> dict:
|
| 139 |
+
# Overwrite-only on every forward; do NOT clear before/after model() so
|
| 140 |
+
# that any backward-time recomputed forward (e.g. gradient checkpointing)
|
| 141 |
+
# still reads the same ids that the original forward used.
|
| 142 |
+
self._current_input_ids = input_ids
|
| 143 |
+
if attention_mask is not None:
|
| 144 |
+
attention_mask = attention_mask.to(torch.long)
|
| 145 |
+
out = self.model(
|
| 146 |
+
input_ids=input_ids,
|
| 147 |
+
attention_mask=attention_mask,
|
| 148 |
+
labels=labels,
|
| 149 |
+
output_hidden_states=False,
|
| 150 |
+
)
|
| 151 |
+
return {"loss": out.loss, "logits": out.logits, "hidden": None}
|
modeling_nucengram.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HuggingFace wrapper for the NucEngram genomic language model.
|
| 2 |
+
|
| 3 |
+
A char-level DNA masked language model (A/C/G/T/N, 9-token vocab) built on a
|
| 4 |
+
ModernBERT encoder with an n-gram memory module injected into two early layers.
|
| 5 |
+
`AutoModel.from_pretrained(..., trust_remote_code=True)` returns the encoder;
|
| 6 |
+
`last_hidden_state` is a per-nucleotide embedding you can pool + probe/fine-tune.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
from transformers import PreTrainedModel
|
| 13 |
+
from transformers.modeling_outputs import BaseModelOutput, MaskedLMOutput
|
| 14 |
+
|
| 15 |
+
from .configuration_nucengram import NucEngramConfig
|
| 16 |
+
from .engram import EngramConfig
|
| 17 |
+
from .model_modernbert import ModernBertGenomicConfig
|
| 18 |
+
from .model_modernbert_engram import ModernBertEngramWrapper
|
| 19 |
+
from .tokenizer import encode as _encode, PAD_ID
|
| 20 |
+
|
| 21 |
+
_VOCAB = {i: c for i, c in zip(range(9), "_XXXACGTN")} # display only
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class NucEngramPreTrainedModel(PreTrainedModel):
|
| 25 |
+
config_class = NucEngramConfig
|
| 26 |
+
base_model_prefix = "net"
|
| 27 |
+
_no_split_modules = ["ModernBertEncoderLayer", "Engram"]
|
| 28 |
+
|
| 29 |
+
def _init_weights(self, module):
|
| 30 |
+
pass # weights come from the pretrained checkpoint
|
| 31 |
+
|
| 32 |
+
# --- tokenisation helper (the tokenizer is a fixed char->id map) ---
|
| 33 |
+
@staticmethod
|
| 34 |
+
def encode(sequences, max_length=8192, device="cpu"):
|
| 35 |
+
"""str | list[str] -> (input_ids, attention_mask) LongTensors."""
|
| 36 |
+
if isinstance(sequences, str):
|
| 37 |
+
sequences = [sequences]
|
| 38 |
+
B = len(sequences)
|
| 39 |
+
L = min(max(len(s) for s in sequences), max_length)
|
| 40 |
+
ids = np.full((B, L), PAD_ID, dtype=np.int64)
|
| 41 |
+
for i, s in enumerate(sequences):
|
| 42 |
+
e = _encode(s).astype(np.int64)[:L]
|
| 43 |
+
ids[i, :len(e)] = e
|
| 44 |
+
ids = torch.from_numpy(ids)
|
| 45 |
+
return ids.to(device), (ids != PAD_ID).long().to(device)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class NucEngramModel(NucEngramPreTrainedModel):
|
| 49 |
+
"""Encoder — returns per-token `last_hidden_state` (use for embeddings / FT)."""
|
| 50 |
+
|
| 51 |
+
def __init__(self, config: NucEngramConfig):
|
| 52 |
+
super().__init__(config)
|
| 53 |
+
mb = ModernBertGenomicConfig(**config.backbone)
|
| 54 |
+
eng = EngramConfig(**config.engram)
|
| 55 |
+
self.net = ModernBertEngramWrapper(mb, eng)
|
| 56 |
+
self.post_init()
|
| 57 |
+
|
| 58 |
+
def forward(self, input_ids, attention_mask=None, **kwargs):
|
| 59 |
+
if attention_mask is None:
|
| 60 |
+
attention_mask = (input_ids != PAD_ID).long()
|
| 61 |
+
# the engram hooks read the raw ids off the wrapper
|
| 62 |
+
self.net._current_input_ids = input_ids
|
| 63 |
+
out = self.net.model.model(input_ids=input_ids, attention_mask=attention_mask)
|
| 64 |
+
return BaseModelOutput(last_hidden_state=out.last_hidden_state)
|
| 65 |
+
|
| 66 |
+
@torch.no_grad()
|
| 67 |
+
def embed(self, sequences, pooling="mean", max_length=8192):
|
| 68 |
+
"""Convenience: sequence(s) -> pooled embedding [B, hidden]."""
|
| 69 |
+
self.eval()
|
| 70 |
+
dev = next(self.parameters()).device
|
| 71 |
+
ids, am = self.encode(sequences, max_length=max_length, device=dev)
|
| 72 |
+
h = self.forward(ids, am).last_hidden_state.float()
|
| 73 |
+
if pooling == "cls":
|
| 74 |
+
return h[:, 0]
|
| 75 |
+
m = am.float().unsqueeze(-1)
|
| 76 |
+
return (h * m).sum(1) / m.sum(1).clamp_min(1.0)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class NucEngramForMaskedLM(NucEngramPreTrainedModel):
|
| 80 |
+
"""Same weights, exposing the MLM head (returns `logits` over the 9-token vocab)."""
|
| 81 |
+
|
| 82 |
+
def __init__(self, config: NucEngramConfig):
|
| 83 |
+
super().__init__(config)
|
| 84 |
+
mb = ModernBertGenomicConfig(**config.backbone)
|
| 85 |
+
eng = EngramConfig(**config.engram)
|
| 86 |
+
self.net = ModernBertEngramWrapper(mb, eng)
|
| 87 |
+
self.post_init()
|
| 88 |
+
|
| 89 |
+
def forward(self, input_ids, attention_mask=None, labels=None, **kwargs):
|
| 90 |
+
if attention_mask is None:
|
| 91 |
+
attention_mask = (input_ids != PAD_ID).long()
|
| 92 |
+
self.net._current_input_ids = input_ids
|
| 93 |
+
out = self.net.model(input_ids=input_ids, attention_mask=attention_mask)
|
| 94 |
+
logits = out.logits if hasattr(out, "logits") else out
|
| 95 |
+
loss = None
|
| 96 |
+
if labels is not None:
|
| 97 |
+
loss = nn.functional.cross_entropy(
|
| 98 |
+
logits.view(-1, logits.size(-1)), labels.view(-1), ignore_index=-100)
|
| 99 |
+
return MaskedLMOutput(loss=loss, logits=logits)
|
tokenizer.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Single-nucleotide tokenizer for genomic sequences.
|
| 2 |
+
|
| 3 |
+
Vocabulary (small, fixed):
|
| 4 |
+
0: <pad>
|
| 5 |
+
1: <bos>
|
| 6 |
+
2: <eos>
|
| 7 |
+
3: <mask>
|
| 8 |
+
4: A
|
| 9 |
+
5: C
|
| 10 |
+
6: G
|
| 11 |
+
7: T
|
| 12 |
+
8: N (unknown / soft-masked nucleotide)
|
| 13 |
+
|
| 14 |
+
Lower- and upper-case nucleotides collapse. Anything not in {A,C,G,T} maps to N.
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
PAD_ID = 0
|
| 22 |
+
BOS_ID = 1
|
| 23 |
+
EOS_ID = 2
|
| 24 |
+
MASK_ID = 3
|
| 25 |
+
A_ID = 4
|
| 26 |
+
C_ID = 5
|
| 27 |
+
G_ID = 6
|
| 28 |
+
T_ID = 7
|
| 29 |
+
N_ID = 8
|
| 30 |
+
|
| 31 |
+
VOCAB_SIZE = 9
|
| 32 |
+
SPECIAL_IDS = (PAD_ID, BOS_ID, EOS_ID, MASK_ID)
|
| 33 |
+
NUCLEOTIDE_IDS = (A_ID, C_ID, G_ID, T_ID, N_ID)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _build_lookup() -> np.ndarray:
|
| 37 |
+
"""Byte → token-id table. Length 256."""
|
| 38 |
+
table = np.full(256, N_ID, dtype=np.int64)
|
| 39 |
+
table[ord("A")] = A_ID
|
| 40 |
+
table[ord("a")] = A_ID
|
| 41 |
+
table[ord("C")] = C_ID
|
| 42 |
+
table[ord("c")] = C_ID
|
| 43 |
+
table[ord("G")] = G_ID
|
| 44 |
+
table[ord("g")] = G_ID
|
| 45 |
+
table[ord("T")] = T_ID
|
| 46 |
+
table[ord("t")] = T_ID
|
| 47 |
+
table[ord("U")] = T_ID
|
| 48 |
+
table[ord("u")] = T_ID
|
| 49 |
+
table[ord("N")] = N_ID
|
| 50 |
+
table[ord("n")] = N_ID
|
| 51 |
+
return table
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
_LOOKUP = _build_lookup()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def encode(seq: str | bytes) -> np.ndarray:
|
| 58 |
+
"""Encode a DNA string to a numpy int64 array of token-ids (no BOS/EOS)."""
|
| 59 |
+
if isinstance(seq, str):
|
| 60 |
+
seq = seq.encode("ascii", errors="replace")
|
| 61 |
+
arr = np.frombuffer(seq, dtype=np.uint8)
|
| 62 |
+
return _LOOKUP[arr]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def encode_torch(seq: str | bytes, device: str | torch.device = "cpu") -> torch.Tensor:
|
| 66 |
+
return torch.from_numpy(encode(seq).copy()).to(device)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
_DECODE_TABLE = {
|
| 70 |
+
PAD_ID: "_",
|
| 71 |
+
BOS_ID: "[",
|
| 72 |
+
EOS_ID: "]",
|
| 73 |
+
MASK_ID: "?",
|
| 74 |
+
A_ID: "A",
|
| 75 |
+
C_ID: "C",
|
| 76 |
+
G_ID: "G",
|
| 77 |
+
T_ID: "T",
|
| 78 |
+
N_ID: "N",
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def decode(ids) -> str:
|
| 83 |
+
if torch.is_tensor(ids):
|
| 84 |
+
ids = ids.detach().cpu().tolist()
|
| 85 |
+
return "".join(_DECODE_TABLE.get(int(i), "?") for i in ids)
|