Instructions to use Taykhoom/Helix-mRNA with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Taykhoom/Helix-mRNA with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Taykhoom/Helix-mRNA", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("Taykhoom/Helix-mRNA", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Taykhoom/Helix-mRNA with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Taykhoom/Helix-mRNA" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Taykhoom/Helix-mRNA", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/Taykhoom/Helix-mRNA
- SGLang
How to use Taykhoom/Helix-mRNA with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "Taykhoom/Helix-mRNA" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Taykhoom/Helix-mRNA", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "Taykhoom/Helix-mRNA" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Taykhoom/Helix-mRNA", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use Taykhoom/Helix-mRNA with Docker Model Runner:
docker model run hf.co/Taykhoom/Helix-mRNA
Commit ·
d7a7842
0
Parent(s):
Initial Helix-mRNA HF port
Browse files- .gitattributes +35 -0
- README.md +178 -0
- config.json +40 -0
- configuration_helix_mrna.py +97 -0
- modeling_helix_mrna.py +522 -0
- special_tokens_map.json +9 -0
- tokenization_helix_mrna.py +113 -0
- tokenizer_config.json +62 -0
- vocab.json +16 -0
.gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: transformers
|
| 3 |
+
tags:
|
| 4 |
+
- biology
|
| 5 |
+
- RNA
|
| 6 |
+
- mRNA
|
| 7 |
+
- language-model
|
| 8 |
+
- mamba
|
| 9 |
+
license: cc-by-nc-sa-4.0
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# Helix-mRNA
|
| 13 |
+
|
| 14 |
+
Minimal HuggingFace port of [Helix-mRNA](https://huggingface.co/helical-ai/Helix-mRNA)
|
| 15 |
+
-- a hybrid Mamba2 / attention language model for full-length mRNA, trained with
|
| 16 |
+
next-token prediction on single-nucleotide tokens with a codon-start marker.
|
| 17 |
+
|
| 18 |
+
**This repository contains code and configuration only.** The pretrained weights
|
| 19 |
+
are gated and licensed for non-commercial use, so they are not redistributed here:
|
| 20 |
+
`from_pretrained` downloads them from
|
| 21 |
+
[`helical-ai/Helix-mRNA`](https://huggingface.co/helical-ai/Helix-mRNA). Request
|
| 22 |
+
access on that page and log in (`hf auth login` or `HF_TOKEN`) before loading.
|
| 23 |
+
|
| 24 |
+
## Architecture
|
| 25 |
+
|
| 26 |
+
| Parameter | Value |
|
| 27 |
+
|---|---|
|
| 28 |
+
| Layers | 8 (`M+M*M+M+`: 4 Mamba2, 3 MLP, 1 attention + MLP) |
|
| 29 |
+
| Attention heads | 32 query / 8 key-value (head dim 8), causal, 1 layer |
|
| 30 |
+
| Embedding dimension | 256 |
|
| 31 |
+
| FFN hidden dimension | 1024 (SwiGLU) |
|
| 32 |
+
| Mamba2 | 16 heads x 32, state size 128, expand 2, conv kernel 4, chunk size 256 |
|
| 33 |
+
| Vocabulary size | 14 |
|
| 34 |
+
| Positional encoding | None (order comes from the causal Mamba2 blocks) |
|
| 35 |
+
| Normalization | RMSNorm (pre-norm), gated RMSNorm inside Mamba2 |
|
| 36 |
+
| Architecture | Hybrid Mamba2 / Transformer decoder |
|
| 37 |
+
| Max sequence length | 12288 |
|
| 38 |
+
| Parameters | 5.2M |
|
| 39 |
+
|
| 40 |
+
**Vocabulary:** `A C G U N`, `E` (start of a codon), `T` (read as `U`), and the
|
| 41 |
+
special tokens `[BOS]`, `[SEP]`/`[PAD]` (shared id 1), `[CLS]`, `[MASK]`, `[UNK]`.
|
| 42 |
+
The tokenizer appends `[SEP]` to each sequence and pads on the left.
|
| 43 |
+
|
| 44 |
+
## Pretraining
|
| 45 |
+
|
| 46 |
+
- **Objective:** Causal language modeling (next-token prediction)
|
| 47 |
+
- **Data:** mRNA sequences, with `E` inserted before each codon of the coding region
|
| 48 |
+
- **Source checkpoint:** [`helical-ai/Helix-mRNA`](https://huggingface.co/helical-ai/Helix-mRNA) (weights stored in bfloat16)
|
| 49 |
+
|
| 50 |
+
## Parity Verification
|
| 51 |
+
|
| 52 |
+
All 9 representation levels (embedding + 8 blocks), the final norm and the LM
|
| 53 |
+
logits were verified to be bit-exact (max abs diff = 0.00) against the upstream
|
| 54 |
+
Helical blocks run in sequence (see Implementation Notes), with eager and sdpa
|
| 55 |
+
attention, on padded and unpadded batches. Verified on an NVIDIA H100 with
|
| 56 |
+
PyTorch 2.7 / CUDA 12. On 24 human mRNAs the next-token loss is 1.26 nats per
|
| 57 |
+
token (uniform over the four bases: 1.39).
|
| 58 |
+
|
| 59 |
+
## Related Models
|
| 60 |
+
|
| 61 |
+
See the full [Helix-mRNA collection](https://huggingface.co/collections/Taykhoom/helix-mrna-6ac574d998d9cddff2ce3f9a).
|
| 62 |
+
|
| 63 |
+
| Model | Parameters | Notes |
|
| 64 |
+
|---|---:|---|
|
| 65 |
+
| **[Helix-mRNA](https://huggingface.co/Taykhoom/Helix-mRNA)** | 5.2M | This model |
|
| 66 |
+
|
| 67 |
+
## Usage
|
| 68 |
+
|
| 69 |
+
### Embedding generation
|
| 70 |
+
|
| 71 |
+
```python
|
| 72 |
+
import torch
|
| 73 |
+
from transformers import AutoTokenizer, AutoModel
|
| 74 |
+
|
| 75 |
+
tokenizer = AutoTokenizer.from_pretrained("Taykhoom/Helix-mRNA", trust_remote_code=True)
|
| 76 |
+
model = AutoModel.from_pretrained("Taykhoom/Helix-mRNA", trust_remote_code=True)
|
| 77 |
+
model = model.to("cuda").eval() # Mamba2 blocks need a CUDA GPU
|
| 78 |
+
|
| 79 |
+
# Mark the start of each codon in the coding region with "E" (recommended
|
| 80 |
+
# upstream); UTRs and non-coding RNA are given as plain nucleotides.
|
| 81 |
+
cds = "AUGGCCAAGUAA"
|
| 82 |
+
sequences = ["GGAUC" + "".join("E" + cds[i:i + 3] for i in range(0, len(cds), 3)), "ACGUACGU"]
|
| 83 |
+
enc = tokenizer(sequences, return_tensors="pt", padding=True).to("cuda")
|
| 84 |
+
|
| 85 |
+
with torch.no_grad():
|
| 86 |
+
out = model(**enc)
|
| 87 |
+
|
| 88 |
+
token_emb = out.last_hidden_state # (batch, seq_len, 256)
|
| 89 |
+
mask = enc.attention_mask.unsqueeze(-1).to(token_emb.dtype)
|
| 90 |
+
mean_emb = (token_emb * mask).sum(1) / mask.sum(1) # masked mean pooling
|
| 91 |
+
|
| 92 |
+
# Intermediate layers: hidden_states[0] is the embedding, [i] the output of block i
|
| 93 |
+
out_all = model(**enc, output_hidden_states=True)
|
| 94 |
+
block4_emb = out_all.hidden_states[4]
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
### Next-token logits
|
| 98 |
+
|
| 99 |
+
```python
|
| 100 |
+
import torch
|
| 101 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 102 |
+
|
| 103 |
+
tokenizer = AutoTokenizer.from_pretrained("Taykhoom/Helix-mRNA", trust_remote_code=True)
|
| 104 |
+
model = AutoModelForCausalLM.from_pretrained("Taykhoom/Helix-mRNA", trust_remote_code=True)
|
| 105 |
+
model = model.to("cuda").eval()
|
| 106 |
+
|
| 107 |
+
enc = tokenizer(["ACGUACGUEAUGEGCC"], return_tensors="pt").to("cuda")
|
| 108 |
+
with torch.no_grad():
|
| 109 |
+
out = model(**enc, labels=enc.input_ids)
|
| 110 |
+
logits = out.logits # (1, seq_len, 14); out.loss is the mean next-token loss
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
### Faster attention backends
|
| 114 |
+
|
| 115 |
+
```python
|
| 116 |
+
# SDPA (PyTorch 2.0+) -- recommended for production
|
| 117 |
+
model = AutoModel.from_pretrained("Taykhoom/Helix-mRNA", trust_remote_code=True,
|
| 118 |
+
attn_implementation="sdpa")
|
| 119 |
+
|
| 120 |
+
# Flash Attention 2 (requires flash-attn) -- fastest on long sequences
|
| 121 |
+
model = AutoModel.from_pretrained("Taykhoom/Helix-mRNA", trust_remote_code=True,
|
| 122 |
+
attn_implementation="flash_attention_2",
|
| 123 |
+
dtype=torch.bfloat16)
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
The Mamba2 blocks require a CUDA GPU and the `mamba-ssm` kernels
|
| 127 |
+
(`pip install mamba-ssm causal-conv1d --no-build-isolation`), as upstream;
|
| 128 |
+
`causal-conv1d` is optional.
|
| 129 |
+
|
| 130 |
+
### Fine-tuning
|
| 131 |
+
|
| 132 |
+
Standard HF conventions. For sequence-level tasks, pool over non-padding
|
| 133 |
+
positions (masked mean) before a prediction head. Gradients flow through all
|
| 134 |
+
blocks and `gradient_checkpointing_enable()` is supported. A fine-tuned model saved with `save_pretrained` includes its own
|
| 135 |
+
weights and loads from that directory without contacting the gated repo.
|
| 136 |
+
|
| 137 |
+
## Implementation Notes
|
| 138 |
+
|
| 139 |
+
**Blocks are chained.** The upstream Helical inference code (`helical` 3.1.3,
|
| 140 |
+
`HelixmRNAPretrainedModel.forward`) never sets `hidden_states = layer_outputs[0]`
|
| 141 |
+
inside its layer loop, so every block receives the token embeddings and only the
|
| 142 |
+
last block's output reaches the final norm. This port runs the blocks in
|
| 143 |
+
sequence, as the weights were trained: next-token loss is 1.26 nats per token
|
| 144 |
+
chained versus 4.09 for the upstream forward, worse than uniform guessing (1.39).
|
| 145 |
+
Embeddings from this port therefore differ from the upstream `helical` package.
|
| 146 |
+
|
| 147 |
+
The Mamba2 mixer always uses the upstream inference path (separate causal
|
| 148 |
+
convolution and chunked scan, with padded positions zeroed), also in training
|
| 149 |
+
mode, where upstream switches to a fused kernel that skips the post-convolution
|
| 150 |
+
padding mask. The attention
|
| 151 |
+
block's `eager`, `sdpa` and `flash_attention_2` backends are selectable via
|
| 152 |
+
`attn_implementation`; `output_attentions=True` falls back to eager and returns
|
| 153 |
+
post-softmax probabilities. Generation caching is not implemented.
|
| 154 |
+
|
| 155 |
+
## Citation
|
| 156 |
+
|
| 157 |
+
```bibtex
|
| 158 |
+
@article{wood2025_helixmrna,
|
| 159 |
+
title = {Helix-{mRNA}: A Hybrid Foundation Model For Full Sequence {mRNA} Therapeutics},
|
| 160 |
+
author = {Wood, Matthew and Klop, Mathieu and Allard, Maxime},
|
| 161 |
+
journal = {arXiv preprint arXiv:2502.13785},
|
| 162 |
+
year = {2025},
|
| 163 |
+
doi = {10.48550/arXiv.2502.13785}
|
| 164 |
+
}
|
| 165 |
+
```
|
| 166 |
+
|
| 167 |
+
## Credits
|
| 168 |
+
|
| 169 |
+
Original model and code by Wood et al. (Helical). Source:
|
| 170 |
+
[GitHub](https://github.com/helicalAI/helical),
|
| 171 |
+
[`helical-ai/Helix-mRNA` on the Hub](https://huggingface.co/helical-ai/Helix-mRNA).
|
| 172 |
+
Hugging Face port maintained by Taykhoom Dalal.
|
| 173 |
+
|
| 174 |
+
## License
|
| 175 |
+
|
| 176 |
+
The weights are licensed CC BY-NC-SA 4.0 (non-commercial use only) and gated by
|
| 177 |
+
Helical, following the original repository; contact hello@helical-ai.com for
|
| 178 |
+
commercial use. This repository distributes only code and configuration.
|
config.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"HelixmRNAForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_helix_mrna.HelixmRNAConfig",
|
| 7 |
+
"AutoModel": "modeling_helix_mrna.HelixmRNAModel",
|
| 8 |
+
"AutoModelForCausalLM": "modeling_helix_mrna.HelixmRNAForCausalLM"
|
| 9 |
+
},
|
| 10 |
+
"attention_dropout": 0.0,
|
| 11 |
+
"bos_token_id": 0,
|
| 12 |
+
"chunk_size": 256,
|
| 13 |
+
"conv_kernel": 4,
|
| 14 |
+
"eos_token_id": 2,
|
| 15 |
+
"expand": 2,
|
| 16 |
+
"head_dim": 32,
|
| 17 |
+
"hidden_act": "silu",
|
| 18 |
+
"hidden_size": 256,
|
| 19 |
+
"initializer_range": 0.1,
|
| 20 |
+
"layer_norm_epsilon": 1e-05,
|
| 21 |
+
"layers_block_type_string": "M+M*M+M+",
|
| 22 |
+
"model_max_length": 12288,
|
| 23 |
+
"model_type": "helix_mrna",
|
| 24 |
+
"n_groups": 1,
|
| 25 |
+
"num_attention_heads": 32,
|
| 26 |
+
"num_heads": 16,
|
| 27 |
+
"num_hidden_layers": 8,
|
| 28 |
+
"num_key_value_heads": 8,
|
| 29 |
+
"pad_token_id": 1,
|
| 30 |
+
"residual_in_fp32": true,
|
| 31 |
+
"state_size": 128,
|
| 32 |
+
"tie_word_embeddings": false,
|
| 33 |
+
"time_step_limit": null,
|
| 34 |
+
"time_step_min": 0.001,
|
| 35 |
+
"transformers_version": "4.57.6",
|
| 36 |
+
"use_bias": false,
|
| 37 |
+
"use_conv_bias": true,
|
| 38 |
+
"vocab_size": 14,
|
| 39 |
+
"weights_repo": "helical-ai/Helix-mRNA"
|
| 40 |
+
}
|
configuration_helix_mrna.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Helix-mRNA configuration."""
|
| 2 |
+
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
from transformers import PretrainedConfig
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class HelixmRNAConfig(PretrainedConfig):
|
| 9 |
+
"""Configuration for the Helix-mRNA hybrid Mamba2 / attention model.
|
| 10 |
+
|
| 11 |
+
``layers_block_type_string`` gives one character per layer: ``M`` is a
|
| 12 |
+
Mamba2 block, ``*`` an attention block (attention + MLP) and ``+`` an MLP
|
| 13 |
+
block. The pretrained weights are not stored with this config; they are
|
| 14 |
+
loaded from the gated ``weights_repo`` (see ``HelixmRNAPreTrainedModel``).
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
model_type = "helix_mrna"
|
| 18 |
+
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
vocab_size: int = 14,
|
| 22 |
+
hidden_size: int = 256,
|
| 23 |
+
num_hidden_layers: int = 8,
|
| 24 |
+
layers_block_type_string: str = "M+M*M+M+",
|
| 25 |
+
num_heads: int = 16,
|
| 26 |
+
head_dim: int = 32,
|
| 27 |
+
state_size: int = 128,
|
| 28 |
+
expand: int = 2,
|
| 29 |
+
n_groups: int = 1,
|
| 30 |
+
conv_kernel: int = 4,
|
| 31 |
+
chunk_size: int = 256,
|
| 32 |
+
use_bias: bool = False,
|
| 33 |
+
use_conv_bias: bool = True,
|
| 34 |
+
time_step_min: float = 0.001,
|
| 35 |
+
time_step_limit: Optional[tuple] = None,
|
| 36 |
+
num_attention_heads: int = 32,
|
| 37 |
+
num_key_value_heads: int = 8,
|
| 38 |
+
attention_dropout: float = 0.0,
|
| 39 |
+
hidden_act: str = "silu",
|
| 40 |
+
layer_norm_epsilon: float = 1e-5,
|
| 41 |
+
residual_in_fp32: bool = True,
|
| 42 |
+
initializer_range: float = 0.1,
|
| 43 |
+
model_max_length: int = 12288,
|
| 44 |
+
weights_repo: str = "helical-ai/Helix-mRNA",
|
| 45 |
+
pad_token_id: int = 1,
|
| 46 |
+
bos_token_id: int = 0,
|
| 47 |
+
eos_token_id: int = 2,
|
| 48 |
+
tie_word_embeddings: bool = False,
|
| 49 |
+
**kwargs,
|
| 50 |
+
):
|
| 51 |
+
if len(layers_block_type_string) != num_hidden_layers:
|
| 52 |
+
raise ValueError(
|
| 53 |
+
"layers_block_type_string must have one character per layer, "
|
| 54 |
+
f"got {len(layers_block_type_string)} for {num_hidden_layers} layers."
|
| 55 |
+
)
|
| 56 |
+
self.vocab_size = vocab_size
|
| 57 |
+
self.hidden_size = hidden_size
|
| 58 |
+
self.num_hidden_layers = num_hidden_layers
|
| 59 |
+
self.layers_block_type_string = layers_block_type_string
|
| 60 |
+
self.num_heads = num_heads
|
| 61 |
+
self.head_dim = head_dim
|
| 62 |
+
self.state_size = state_size
|
| 63 |
+
self.expand = expand
|
| 64 |
+
self.n_groups = n_groups
|
| 65 |
+
self.conv_kernel = conv_kernel
|
| 66 |
+
self.chunk_size = chunk_size
|
| 67 |
+
self.use_bias = use_bias
|
| 68 |
+
self.use_conv_bias = use_conv_bias
|
| 69 |
+
self.time_step_min = time_step_min
|
| 70 |
+
# None means no limit; stored as null since JSON has no Infinity.
|
| 71 |
+
self.time_step_limit = tuple(time_step_limit) if time_step_limit is not None else None
|
| 72 |
+
self.num_attention_heads = num_attention_heads
|
| 73 |
+
self.num_key_value_heads = num_key_value_heads
|
| 74 |
+
self.attention_dropout = attention_dropout
|
| 75 |
+
self.hidden_act = hidden_act
|
| 76 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
| 77 |
+
self.residual_in_fp32 = residual_in_fp32
|
| 78 |
+
self.initializer_range = initializer_range
|
| 79 |
+
self.model_max_length = model_max_length
|
| 80 |
+
self.weights_repo = weights_repo
|
| 81 |
+
self.auto_map = {
|
| 82 |
+
"AutoConfig": "configuration_helix_mrna.HelixmRNAConfig",
|
| 83 |
+
"AutoModel": "modeling_helix_mrna.HelixmRNAModel",
|
| 84 |
+
"AutoModelForCausalLM": "modeling_helix_mrna.HelixmRNAForCausalLM",
|
| 85 |
+
}
|
| 86 |
+
super().__init__(
|
| 87 |
+
pad_token_id=pad_token_id,
|
| 88 |
+
bos_token_id=bos_token_id,
|
| 89 |
+
eos_token_id=eos_token_id,
|
| 90 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 91 |
+
**kwargs,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
@property
|
| 95 |
+
def layers_block_type(self) -> list[str]:
|
| 96 |
+
kinds = {"M": "mamba", "*": "attention", "+": "mlp"}
|
| 97 |
+
return [kinds[c] for c in self.layers_block_type_string]
|
modeling_helix_mrna.py
ADDED
|
@@ -0,0 +1,522 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PyTorch Helix-mRNA: a hybrid Mamba2 / attention mRNA language model.
|
| 2 |
+
|
| 3 |
+
Minimal port of the Helix-mRNA backbone released by Helical. The upstream
|
| 4 |
+
inference code passes every block the token embeddings instead of the
|
| 5 |
+
previous block's output; here blocks are chained, which is what the
|
| 6 |
+
pretrained weights expect.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import math
|
| 10 |
+
import os
|
| 11 |
+
from typing import Optional
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
from torch import nn
|
| 16 |
+
from transformers import PretrainedConfig, PreTrainedModel
|
| 17 |
+
from transformers.activations import ACT2FN
|
| 18 |
+
from transformers.modeling_outputs import BaseModelOutput, CausalLMOutput
|
| 19 |
+
|
| 20 |
+
from .configuration_helix_mrna import HelixmRNAConfig
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined
|
| 24 |
+
except ImportError:
|
| 25 |
+
mamba_chunk_scan_combined = None
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
from causal_conv1d import causal_conv1d_fn
|
| 29 |
+
except ImportError:
|
| 30 |
+
causal_conv1d_fn = None
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class HelixmRNARMSNorm(nn.Module):
|
| 34 |
+
def __init__(self, hidden_size: int, eps: float = 1e-6):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 37 |
+
self.variance_epsilon = eps
|
| 38 |
+
|
| 39 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 40 |
+
input_dtype = hidden_states.dtype
|
| 41 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 42 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 43 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 44 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class HelixmRNAGatedRMSNorm(HelixmRNARMSNorm):
|
| 48 |
+
"""RMSNorm of ``hidden_states * silu(gate)``."""
|
| 49 |
+
|
| 50 |
+
def forward(self, hidden_states: torch.Tensor, gate: torch.Tensor) -> torch.Tensor:
|
| 51 |
+
input_dtype = hidden_states.dtype
|
| 52 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 53 |
+
hidden_states = hidden_states * F.silu(gate.to(torch.float32))
|
| 54 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 55 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 56 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class HelixmRNAMamba2Mixer(nn.Module):
|
| 60 |
+
"""Mamba2 mixer. Requires the mamba_ssm CUDA kernels."""
|
| 61 |
+
|
| 62 |
+
def __init__(self, config: HelixmRNAConfig, layer_idx: int):
|
| 63 |
+
super().__init__()
|
| 64 |
+
self.layer_idx = layer_idx
|
| 65 |
+
self.num_heads = config.num_heads
|
| 66 |
+
self.head_dim = config.head_dim
|
| 67 |
+
self.ssm_state_size = config.state_size
|
| 68 |
+
self.n_groups = config.n_groups
|
| 69 |
+
self.chunk_size = config.chunk_size
|
| 70 |
+
self.intermediate_size = config.expand * config.hidden_size
|
| 71 |
+
self.time_step_limit = config.time_step_limit
|
| 72 |
+
self.activation = config.hidden_act
|
| 73 |
+
self.act = ACT2FN[config.hidden_act]
|
| 74 |
+
|
| 75 |
+
self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
|
| 76 |
+
self.conv1d = nn.Conv1d(
|
| 77 |
+
self.conv_dim,
|
| 78 |
+
self.conv_dim,
|
| 79 |
+
kernel_size=config.conv_kernel,
|
| 80 |
+
groups=self.conv_dim,
|
| 81 |
+
padding=config.conv_kernel - 1,
|
| 82 |
+
bias=config.use_conv_bias,
|
| 83 |
+
)
|
| 84 |
+
self.in_proj = nn.Linear(
|
| 85 |
+
config.hidden_size,
|
| 86 |
+
self.intermediate_size + self.conv_dim + self.num_heads,
|
| 87 |
+
bias=config.use_bias,
|
| 88 |
+
)
|
| 89 |
+
self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
|
| 90 |
+
self.A_log = nn.Parameter(torch.log(torch.arange(1, self.num_heads + 1, dtype=torch.float32)))
|
| 91 |
+
self.D = nn.Parameter(torch.ones(self.num_heads))
|
| 92 |
+
self.norm = HelixmRNAGatedRMSNorm(self.intermediate_size, eps=config.layer_norm_epsilon)
|
| 93 |
+
self.out_proj = nn.Linear(self.intermediate_size, config.hidden_size, bias=config.use_bias)
|
| 94 |
+
|
| 95 |
+
def forward(
|
| 96 |
+
self, hidden_states: torch.Tensor, padding_mask: Optional[torch.Tensor] = None
|
| 97 |
+
) -> torch.Tensor:
|
| 98 |
+
"""padding_mask: (B, T), 1 = real token, 0 = padding; None if no padding."""
|
| 99 |
+
batch_size, seq_len, _ = hidden_states.shape
|
| 100 |
+
if mamba_chunk_scan_combined is None:
|
| 101 |
+
raise ImportError(
|
| 102 |
+
"Helix-mRNA requires mamba-ssm for its Mamba2 blocks: "
|
| 103 |
+
"pip install mamba-ssm causal-conv1d --no-build-isolation"
|
| 104 |
+
)
|
| 105 |
+
if not hidden_states.is_cuda:
|
| 106 |
+
raise RuntimeError("Helix-mRNA's Mamba2 blocks run on CUDA only.")
|
| 107 |
+
groups_state = self.n_groups * self.ssm_state_size
|
| 108 |
+
|
| 109 |
+
# Zero padded positions so they add nothing to the state.
|
| 110 |
+
if padding_mask is not None:
|
| 111 |
+
hidden_states = hidden_states * padding_mask[:, :, None].to(hidden_states.dtype)
|
| 112 |
+
|
| 113 |
+
projected = self.in_proj(hidden_states)
|
| 114 |
+
gate, xBC, dt = torch.split(
|
| 115 |
+
projected, [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
if causal_conv1d_fn is not None and self.activation in ("silu", "swish"):
|
| 119 |
+
xBC = causal_conv1d_fn(
|
| 120 |
+
x=xBC.transpose(1, 2),
|
| 121 |
+
weight=self.conv1d.weight.squeeze(1),
|
| 122 |
+
bias=self.conv1d.bias,
|
| 123 |
+
activation=self.activation,
|
| 124 |
+
).transpose(1, 2)
|
| 125 |
+
else:
|
| 126 |
+
xBC = self.act(self.conv1d(xBC.transpose(1, 2))[..., :seq_len].transpose(1, 2))
|
| 127 |
+
|
| 128 |
+
x, B, C = torch.split(xBC, [self.intermediate_size, groups_state, groups_state], dim=-1)
|
| 129 |
+
if padding_mask is not None:
|
| 130 |
+
x = x * padding_mask[:, :, None].to(x.dtype)
|
| 131 |
+
|
| 132 |
+
A = -torch.exp(self.A_log.float())
|
| 133 |
+
x = x.reshape(batch_size, seq_len, self.num_heads, self.head_dim)
|
| 134 |
+
B = B.reshape(batch_size, seq_len, self.n_groups, self.ssm_state_size)
|
| 135 |
+
C = C.reshape(batch_size, seq_len, self.n_groups, self.ssm_state_size)
|
| 136 |
+
|
| 137 |
+
dt_limit = {} if self.time_step_limit is None else {"dt_limit": self.time_step_limit}
|
| 138 |
+
y = mamba_chunk_scan_combined(
|
| 139 |
+
x, dt, A, B, C,
|
| 140 |
+
chunk_size=self.chunk_size,
|
| 141 |
+
D=self.D,
|
| 142 |
+
z=None,
|
| 143 |
+
seq_idx=None,
|
| 144 |
+
dt_bias=self.dt_bias,
|
| 145 |
+
dt_softplus=True,
|
| 146 |
+
**dt_limit,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
y = self.norm(y.reshape(batch_size, seq_len, -1), gate)
|
| 150 |
+
return self.out_proj(y.to(self.out_proj.weight.dtype))
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 154 |
+
if n_rep == 1:
|
| 155 |
+
return hidden_states
|
| 156 |
+
batch, num_kv_heads, seq_len, head_dim = hidden_states.shape
|
| 157 |
+
hidden_states = hidden_states[:, :, None].expand(batch, num_kv_heads, n_rep, seq_len, head_dim)
|
| 158 |
+
return hidden_states.reshape(batch, num_kv_heads * n_rep, seq_len, head_dim)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class HelixmRNAAttention(nn.Module):
|
| 162 |
+
"""Causal grouped-query attention, eager implementation (no positional encoding)."""
|
| 163 |
+
|
| 164 |
+
def __init__(self, config: HelixmRNAConfig, layer_idx: int):
|
| 165 |
+
super().__init__()
|
| 166 |
+
self.layer_idx = layer_idx
|
| 167 |
+
self.hidden_size = config.hidden_size
|
| 168 |
+
self.num_heads = config.num_attention_heads
|
| 169 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 170 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 171 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 172 |
+
self.attention_dropout = config.attention_dropout
|
| 173 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
| 174 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
| 175 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
| 176 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
| 177 |
+
|
| 178 |
+
def _project(self, hidden_states):
|
| 179 |
+
bsz, q_len, _ = hidden_states.shape
|
| 180 |
+
q = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 181 |
+
k = self.k_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 182 |
+
v = self.v_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 183 |
+
return q, k, v
|
| 184 |
+
|
| 185 |
+
def forward(self, hidden_states, attn_mask, padding_mask=None, output_attentions=False):
|
| 186 |
+
"""attn_mask: bool (B, 1, T, T), True = may attend."""
|
| 187 |
+
bsz, q_len, _ = hidden_states.shape
|
| 188 |
+
q, k, v = self._project(hidden_states)
|
| 189 |
+
k = _repeat_kv(k, self.num_key_value_groups)
|
| 190 |
+
v = _repeat_kv(v, self.num_key_value_groups)
|
| 191 |
+
|
| 192 |
+
scores = torch.matmul(q, k.transpose(2, 3)) / math.sqrt(self.head_dim)
|
| 193 |
+
scores = scores.masked_fill(~attn_mask, torch.finfo(scores.dtype).min)
|
| 194 |
+
weights = F.softmax(scores, dim=-1, dtype=torch.float32).to(q.dtype)
|
| 195 |
+
probs = weights
|
| 196 |
+
weights = F.dropout(weights, p=self.attention_dropout, training=self.training)
|
| 197 |
+
out = torch.matmul(weights, v)
|
| 198 |
+
|
| 199 |
+
out = out.transpose(1, 2).reshape(bsz, q_len, self.hidden_size)
|
| 200 |
+
return self.o_proj(out), (probs if output_attentions else None)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class HelixmRNASdpaAttention(HelixmRNAAttention):
|
| 204 |
+
def forward(self, hidden_states, attn_mask, padding_mask=None, output_attentions=False):
|
| 205 |
+
if output_attentions:
|
| 206 |
+
return super().forward(hidden_states, attn_mask, padding_mask, output_attentions=True)
|
| 207 |
+
bsz, q_len, _ = hidden_states.shape
|
| 208 |
+
q, k, v = self._project(hidden_states)
|
| 209 |
+
k = _repeat_kv(k, self.num_key_value_groups)
|
| 210 |
+
v = _repeat_kv(v, self.num_key_value_groups)
|
| 211 |
+
out = F.scaled_dot_product_attention(
|
| 212 |
+
q.contiguous(), k.contiguous(), v.contiguous(),
|
| 213 |
+
attn_mask=attn_mask,
|
| 214 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
| 215 |
+
)
|
| 216 |
+
out = out.transpose(1, 2).reshape(bsz, q_len, self.hidden_size)
|
| 217 |
+
return self.o_proj(out), None
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class HelixmRNAFlashAttention2(HelixmRNAAttention):
|
| 221 |
+
def forward(self, hidden_states, attn_mask, padding_mask=None, output_attentions=False):
|
| 222 |
+
if output_attentions:
|
| 223 |
+
return super().forward(hidden_states, attn_mask, padding_mask, output_attentions=True)
|
| 224 |
+
try:
|
| 225 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
| 226 |
+
from flash_attn.bert_padding import pad_input, unpad_input
|
| 227 |
+
except ImportError as e:
|
| 228 |
+
raise ImportError(
|
| 229 |
+
"flash_attn is required for attn_implementation='flash_attention_2'. "
|
| 230 |
+
"Install with: pip install flash-attn --no-build-isolation"
|
| 231 |
+
) from e
|
| 232 |
+
|
| 233 |
+
bsz, q_len, _ = hidden_states.shape
|
| 234 |
+
q, k, v = (t.transpose(1, 2) for t in self._project(hidden_states)) # (B, T, H, D)
|
| 235 |
+
orig_dtype = q.dtype
|
| 236 |
+
if orig_dtype not in (torch.float16, torch.bfloat16):
|
| 237 |
+
q, k, v = q.to(torch.bfloat16), k.to(torch.bfloat16), v.to(torch.bfloat16)
|
| 238 |
+
dropout = self.attention_dropout if self.training else 0.0
|
| 239 |
+
|
| 240 |
+
if padding_mask is not None:
|
| 241 |
+
keep = padding_mask.bool()
|
| 242 |
+
q_unpad, indices, cu_seqlens, max_seqlen, _ = unpad_input(q, keep)
|
| 243 |
+
k_unpad, *_ = unpad_input(k, keep)
|
| 244 |
+
v_unpad, *_ = unpad_input(v, keep)
|
| 245 |
+
out = flash_attn_varlen_func(
|
| 246 |
+
q_unpad, k_unpad, v_unpad,
|
| 247 |
+
cu_seqlens_q=cu_seqlens, cu_seqlens_k=cu_seqlens,
|
| 248 |
+
max_seqlen_q=max_seqlen, max_seqlen_k=max_seqlen,
|
| 249 |
+
dropout_p=dropout, causal=True,
|
| 250 |
+
)
|
| 251 |
+
out = pad_input(out, indices, bsz, q_len)
|
| 252 |
+
else:
|
| 253 |
+
out = flash_attn_func(q, k, v, dropout_p=dropout, causal=True)
|
| 254 |
+
|
| 255 |
+
out = out.to(orig_dtype).reshape(bsz, q_len, self.hidden_size)
|
| 256 |
+
return self.o_proj(out), None
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
HELIX_MRNA_ATTENTION_CLASSES = {
|
| 260 |
+
"eager": HelixmRNAAttention,
|
| 261 |
+
"sdpa": HelixmRNASdpaAttention,
|
| 262 |
+
"flash_attention_2": HelixmRNAFlashAttention2,
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
class HelixmRNAMLP(nn.Module):
|
| 267 |
+
def __init__(self, config: HelixmRNAConfig):
|
| 268 |
+
super().__init__()
|
| 269 |
+
# Upstream uses 4 * hidden_size, not config.intermediate_size.
|
| 270 |
+
intermediate_size = 4 * config.hidden_size
|
| 271 |
+
self.gate_proj = nn.Linear(config.hidden_size, intermediate_size, bias=False)
|
| 272 |
+
self.up_proj = nn.Linear(config.hidden_size, intermediate_size, bias=False)
|
| 273 |
+
self.down_proj = nn.Linear(intermediate_size, config.hidden_size, bias=False)
|
| 274 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 275 |
+
|
| 276 |
+
def forward(self, hidden_states):
|
| 277 |
+
return self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
class HelixmRNAMambaLayer(nn.Module):
|
| 281 |
+
def __init__(self, config: HelixmRNAConfig, layer_idx: int):
|
| 282 |
+
super().__init__()
|
| 283 |
+
self.residual_in_fp32 = config.residual_in_fp32
|
| 284 |
+
self.norm = HelixmRNARMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
| 285 |
+
self.mixer = HelixmRNAMamba2Mixer(config, layer_idx)
|
| 286 |
+
|
| 287 |
+
def forward(self, hidden_states, attn_mask=None, padding_mask=None, output_attentions=False):
|
| 288 |
+
residual = hidden_states.float() if self.residual_in_fp32 else hidden_states
|
| 289 |
+
hidden_states = self.norm(hidden_states.to(self.norm.weight.dtype))
|
| 290 |
+
return residual + self.mixer(hidden_states, padding_mask), None
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
class HelixmRNAMLPLayer(nn.Module):
|
| 294 |
+
def __init__(self, config: HelixmRNAConfig, layer_idx: int):
|
| 295 |
+
super().__init__()
|
| 296 |
+
self.input_layernorm = HelixmRNARMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
| 297 |
+
self.feed_forward = HelixmRNAMLP(config)
|
| 298 |
+
|
| 299 |
+
def forward(self, hidden_states, attn_mask=None, padding_mask=None, output_attentions=False):
|
| 300 |
+
normed = self.input_layernorm(hidden_states.to(self.input_layernorm.weight.dtype))
|
| 301 |
+
return hidden_states + self.feed_forward(normed), None
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class HelixmRNAAttentionLayer(nn.Module):
|
| 305 |
+
def __init__(self, config: HelixmRNAConfig, layer_idx: int):
|
| 306 |
+
super().__init__()
|
| 307 |
+
attn_cls = HELIX_MRNA_ATTENTION_CLASSES[getattr(config, "_attn_implementation", None) or "eager"]
|
| 308 |
+
self.self_attn = attn_cls(config, layer_idx)
|
| 309 |
+
self.input_layernorm = HelixmRNARMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
| 310 |
+
self.pre_ff_layernorm = HelixmRNARMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
| 311 |
+
self.feed_forward = HelixmRNAMLP(config)
|
| 312 |
+
|
| 313 |
+
def forward(self, hidden_states, attn_mask=None, padding_mask=None, output_attentions=False):
|
| 314 |
+
dtype = self.input_layernorm.weight.dtype
|
| 315 |
+
attn_out, attn_weights = self.self_attn(
|
| 316 |
+
self.input_layernorm(hidden_states.to(dtype)), attn_mask, padding_mask, output_attentions
|
| 317 |
+
)
|
| 318 |
+
hidden_states = hidden_states + attn_out
|
| 319 |
+
hidden_states = hidden_states + self.feed_forward(self.pre_ff_layernorm(hidden_states.to(dtype)))
|
| 320 |
+
return hidden_states, attn_weights
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
HELIX_MRNA_LAYER_CLASSES = {
|
| 324 |
+
"mamba": HelixmRNAMambaLayer,
|
| 325 |
+
"attention": HelixmRNAAttentionLayer,
|
| 326 |
+
"mlp": HelixmRNAMLPLayer,
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class HelixmRNAPreTrainedModel(PreTrainedModel):
|
| 331 |
+
"""Base class. ``from_pretrained`` fetches the gated upstream weights.
|
| 332 |
+
|
| 333 |
+
The Helix-mRNA weights (``config.weights_repo``) are gated and licensed
|
| 334 |
+
CC BY-NC-SA 4.0, so they are not redistributed with this port. Loading
|
| 335 |
+
from a repo or directory without a weights file downloads them from the
|
| 336 |
+
upstream repo, which requires accepting its terms on the Hub and a token
|
| 337 |
+
with access. A directory that does contain weights (e.g. a fine-tuned
|
| 338 |
+
model saved with ``save_pretrained``) is loaded as usual.
|
| 339 |
+
"""
|
| 340 |
+
|
| 341 |
+
config_class = HelixmRNAConfig
|
| 342 |
+
base_model_prefix = "backbone"
|
| 343 |
+
supports_gradient_checkpointing = True
|
| 344 |
+
_no_split_modules = ["HelixmRNAMambaLayer", "HelixmRNAAttentionLayer", "HelixmRNAMLPLayer"]
|
| 345 |
+
_supports_sdpa = True
|
| 346 |
+
_supports_flash_attn_2 = True
|
| 347 |
+
_supports_flash_attn = True
|
| 348 |
+
|
| 349 |
+
def _init_weights(self, module):
|
| 350 |
+
if isinstance(module, nn.Linear):
|
| 351 |
+
nn.init.normal_(module.weight, std=self.config.initializer_range)
|
| 352 |
+
if module.bias is not None:
|
| 353 |
+
nn.init.zeros_(module.bias)
|
| 354 |
+
elif isinstance(module, nn.Embedding):
|
| 355 |
+
nn.init.normal_(module.weight, std=self.config.initializer_range)
|
| 356 |
+
|
| 357 |
+
@classmethod
|
| 358 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 359 |
+
path = pretrained_model_name_or_path
|
| 360 |
+
has_local_weights = path is not None and os.path.isdir(path) and any(
|
| 361 |
+
f.endswith((".safetensors", ".bin")) for f in os.listdir(path)
|
| 362 |
+
)
|
| 363 |
+
if kwargs.get("state_dict") is not None or has_local_weights:
|
| 364 |
+
return super().from_pretrained(path, *model_args, **kwargs)
|
| 365 |
+
|
| 366 |
+
from huggingface_hub import hf_hub_download
|
| 367 |
+
from safetensors.torch import load_file
|
| 368 |
+
|
| 369 |
+
hub_kwargs = {
|
| 370 |
+
k: kwargs[k]
|
| 371 |
+
for k in ("token", "cache_dir", "force_download", "local_files_only", "proxies")
|
| 372 |
+
if k in kwargs
|
| 373 |
+
}
|
| 374 |
+
config = kwargs.pop("config", None)
|
| 375 |
+
if not isinstance(config, PretrainedConfig):
|
| 376 |
+
config = cls.config_class.from_pretrained(
|
| 377 |
+
path, revision=kwargs.get("revision"), **hub_kwargs
|
| 378 |
+
)
|
| 379 |
+
weights = hf_hub_download(config.weights_repo, "model.safetensors", **hub_kwargs)
|
| 380 |
+
kwargs.pop("revision", None)
|
| 381 |
+
return super().from_pretrained(
|
| 382 |
+
None, *model_args, config=config, state_dict=load_file(weights), **kwargs
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
class HelixmRNAModel(HelixmRNAPreTrainedModel):
|
| 387 |
+
"""Helix-mRNA backbone: token embeddings -> hybrid blocks -> final RMSNorm."""
|
| 388 |
+
|
| 389 |
+
def __init__(self, config: HelixmRNAConfig):
|
| 390 |
+
super().__init__(config)
|
| 391 |
+
self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 392 |
+
self.layers = nn.ModuleList(
|
| 393 |
+
HELIX_MRNA_LAYER_CLASSES[kind](config, layer_idx=i)
|
| 394 |
+
for i, kind in enumerate(config.layers_block_type)
|
| 395 |
+
)
|
| 396 |
+
self.norm_f = HelixmRNARMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
| 397 |
+
self.gradient_checkpointing = False
|
| 398 |
+
self.post_init()
|
| 399 |
+
|
| 400 |
+
def get_input_embeddings(self):
|
| 401 |
+
return self.embeddings
|
| 402 |
+
|
| 403 |
+
def set_input_embeddings(self, value):
|
| 404 |
+
self.embeddings = value
|
| 405 |
+
|
| 406 |
+
def forward(
|
| 407 |
+
self,
|
| 408 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 409 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 410 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 411 |
+
output_hidden_states: Optional[bool] = None,
|
| 412 |
+
output_attentions: Optional[bool] = None,
|
| 413 |
+
return_dict: Optional[bool] = None,
|
| 414 |
+
**kwargs,
|
| 415 |
+
):
|
| 416 |
+
output_hidden_states = (
|
| 417 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 418 |
+
)
|
| 419 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 420 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 421 |
+
|
| 422 |
+
if (input_ids is None) == (inputs_embeds is None):
|
| 423 |
+
raise ValueError("Specify exactly one of input_ids or inputs_embeds.")
|
| 424 |
+
if inputs_embeds is None:
|
| 425 |
+
inputs_embeds = self.embeddings(input_ids)
|
| 426 |
+
batch_size, seq_len, _ = inputs_embeds.shape
|
| 427 |
+
|
| 428 |
+
# HF convention: 1 = attend, 0 = pad. None when nothing is padded.
|
| 429 |
+
padding_mask = None
|
| 430 |
+
if attention_mask is not None and not bool(attention_mask.all()):
|
| 431 |
+
padding_mask = attention_mask.to(torch.long)
|
| 432 |
+
|
| 433 |
+
# Causal mask; queries at padded positions attend everywhere so their
|
| 434 |
+
# softmax stays finite (their outputs are discarded).
|
| 435 |
+
attn_mask = torch.ones(seq_len, seq_len, dtype=torch.bool, device=inputs_embeds.device).tril()
|
| 436 |
+
attn_mask = attn_mask[None, None].expand(batch_size, 1, seq_len, seq_len)
|
| 437 |
+
if padding_mask is not None:
|
| 438 |
+
keep = padding_mask.bool()
|
| 439 |
+
attn_mask = attn_mask & keep[:, None, None, :]
|
| 440 |
+
attn_mask = attn_mask | ~keep[:, None, :, None]
|
| 441 |
+
|
| 442 |
+
hidden_states = inputs_embeds
|
| 443 |
+
all_hidden_states = [hidden_states] if output_hidden_states else None
|
| 444 |
+
all_attentions = [] if output_attentions else None
|
| 445 |
+
|
| 446 |
+
for layer in self.layers:
|
| 447 |
+
if self.gradient_checkpointing and self.training:
|
| 448 |
+
hidden_states, attn = self._gradient_checkpointing_func(
|
| 449 |
+
layer.__call__, hidden_states, attn_mask, padding_mask, output_attentions
|
| 450 |
+
)
|
| 451 |
+
else:
|
| 452 |
+
hidden_states, attn = layer(hidden_states, attn_mask, padding_mask, output_attentions)
|
| 453 |
+
if output_hidden_states:
|
| 454 |
+
all_hidden_states.append(hidden_states)
|
| 455 |
+
if output_attentions and attn is not None:
|
| 456 |
+
all_attentions.append(attn)
|
| 457 |
+
|
| 458 |
+
hidden_states = self.norm_f(hidden_states.to(self.norm_f.weight.dtype))
|
| 459 |
+
|
| 460 |
+
if not return_dict:
|
| 461 |
+
return tuple(
|
| 462 |
+
v for v in (hidden_states, all_hidden_states, all_attentions) if v is not None
|
| 463 |
+
)
|
| 464 |
+
return BaseModelOutput(
|
| 465 |
+
last_hidden_state=hidden_states,
|
| 466 |
+
hidden_states=tuple(all_hidden_states) if output_hidden_states else None,
|
| 467 |
+
attentions=tuple(all_attentions) if output_attentions else None,
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
class HelixmRNAForCausalLM(HelixmRNAPreTrainedModel):
|
| 472 |
+
"""Helix-mRNA with its next-token prediction head."""
|
| 473 |
+
|
| 474 |
+
def __init__(self, config: HelixmRNAConfig):
|
| 475 |
+
super().__init__(config)
|
| 476 |
+
self.backbone = HelixmRNAModel(config)
|
| 477 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 478 |
+
self.post_init()
|
| 479 |
+
|
| 480 |
+
def get_input_embeddings(self):
|
| 481 |
+
return self.backbone.embeddings
|
| 482 |
+
|
| 483 |
+
def get_output_embeddings(self):
|
| 484 |
+
return self.lm_head
|
| 485 |
+
|
| 486 |
+
def forward(
|
| 487 |
+
self,
|
| 488 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 489 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 490 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 491 |
+
labels: Optional[torch.LongTensor] = None,
|
| 492 |
+
output_hidden_states: Optional[bool] = None,
|
| 493 |
+
output_attentions: Optional[bool] = None,
|
| 494 |
+
return_dict: Optional[bool] = None,
|
| 495 |
+
**kwargs,
|
| 496 |
+
):
|
| 497 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 498 |
+
out = self.backbone(
|
| 499 |
+
input_ids=input_ids,
|
| 500 |
+
attention_mask=attention_mask,
|
| 501 |
+
inputs_embeds=inputs_embeds,
|
| 502 |
+
output_hidden_states=output_hidden_states,
|
| 503 |
+
output_attentions=output_attentions,
|
| 504 |
+
return_dict=True,
|
| 505 |
+
)
|
| 506 |
+
logits = self.lm_head(out.last_hidden_state.to(self.lm_head.weight.dtype)).float()
|
| 507 |
+
|
| 508 |
+
loss = None
|
| 509 |
+
if labels is not None:
|
| 510 |
+
loss = F.cross_entropy(
|
| 511 |
+
logits[:, :-1].reshape(-1, self.config.vocab_size),
|
| 512 |
+
labels[:, 1:].reshape(-1),
|
| 513 |
+
ignore_index=-100,
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
if not return_dict:
|
| 517 |
+
output = (logits, out.hidden_states, out.attentions)
|
| 518 |
+
output = tuple(v for v in output if v is not None)
|
| 519 |
+
return ((loss,) + output) if loss is not None else output
|
| 520 |
+
return CausalLMOutput(
|
| 521 |
+
loss=loss, logits=logits, hidden_states=out.hidden_states, attentions=out.attentions
|
| 522 |
+
)
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token": "[BOS]",
|
| 3 |
+
"cls_token": "[CLS]",
|
| 4 |
+
"eos_token": "[SEP]",
|
| 5 |
+
"mask_token": "[MASK]",
|
| 6 |
+
"pad_token": "[PAD]",
|
| 7 |
+
"sep_token": "[SEP]",
|
| 8 |
+
"unk_token": "[UNK]"
|
| 9 |
+
}
|
tokenization_helix_mrna.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Helix-mRNA character tokenizer."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
from transformers import PreTrainedTokenizer
|
| 8 |
+
|
| 9 |
+
# Ids match the upstream Helix-mRNA tokenizer. [SEP] and [PAD] share id 1,
|
| 10 |
+
# and T is read as U.
|
| 11 |
+
_SPECIAL = {
|
| 12 |
+
"[BOS]": 0,
|
| 13 |
+
"[SEP]": 1,
|
| 14 |
+
"[PAD]": 1,
|
| 15 |
+
"[CLS]": 2,
|
| 16 |
+
"[MASK]": 3,
|
| 17 |
+
"[RESERVED]": 5,
|
| 18 |
+
"[UNK]": 6,
|
| 19 |
+
}
|
| 20 |
+
_CHARACTERS = ("A", "C", "G", "U", "N", "E", "T")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class HelixmRNATokenizer(PreTrainedTokenizer):
|
| 24 |
+
"""Single-nucleotide tokenizer for Helix-mRNA.
|
| 25 |
+
|
| 26 |
+
Each sequence is upper-cased, split into characters and followed by
|
| 27 |
+
[SEP]. ``E`` marks the start of a codon in the coding region; inserting
|
| 28 |
+
it is up to the caller. Padding is on the left, as upstream.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
vocab_files_names = {}
|
| 32 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 33 |
+
|
| 34 |
+
def __init__(
|
| 35 |
+
self,
|
| 36 |
+
bos_token="[BOS]",
|
| 37 |
+
eos_token="[SEP]",
|
| 38 |
+
sep_token="[SEP]",
|
| 39 |
+
cls_token="[CLS]",
|
| 40 |
+
pad_token="[PAD]",
|
| 41 |
+
mask_token="[MASK]",
|
| 42 |
+
unk_token="[UNK]",
|
| 43 |
+
model_max_length=12288,
|
| 44 |
+
padding_side="left",
|
| 45 |
+
**kwargs,
|
| 46 |
+
):
|
| 47 |
+
self._vocab = {
|
| 48 |
+
**_SPECIAL,
|
| 49 |
+
**{c: i + 7 for i, c in enumerate(_CHARACTERS)},
|
| 50 |
+
}
|
| 51 |
+
self._vocab["T"] = self._vocab["U"]
|
| 52 |
+
self._ids_to_tokens = {}
|
| 53 |
+
for token, index in self._vocab.items():
|
| 54 |
+
self._ids_to_tokens.setdefault(index, token)
|
| 55 |
+
super().__init__(
|
| 56 |
+
bos_token=bos_token,
|
| 57 |
+
eos_token=eos_token,
|
| 58 |
+
sep_token=sep_token,
|
| 59 |
+
cls_token=cls_token,
|
| 60 |
+
pad_token=pad_token,
|
| 61 |
+
mask_token=mask_token,
|
| 62 |
+
unk_token=unk_token,
|
| 63 |
+
model_max_length=model_max_length,
|
| 64 |
+
padding_side=padding_side,
|
| 65 |
+
**kwargs,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
@property
|
| 69 |
+
def vocab_size(self) -> int:
|
| 70 |
+
return 14
|
| 71 |
+
|
| 72 |
+
def get_vocab(self) -> dict:
|
| 73 |
+
return dict(self._vocab)
|
| 74 |
+
|
| 75 |
+
def _tokenize(self, text: str) -> list:
|
| 76 |
+
return list(text.upper())
|
| 77 |
+
|
| 78 |
+
def _convert_token_to_id(self, token: str) -> int:
|
| 79 |
+
return self._vocab.get(token, self._vocab["[UNK]"])
|
| 80 |
+
|
| 81 |
+
def _convert_id_to_token(self, index: int) -> str:
|
| 82 |
+
return self._ids_to_tokens.get(index, "[UNK]")
|
| 83 |
+
|
| 84 |
+
def convert_tokens_to_string(self, tokens: list) -> str:
|
| 85 |
+
return "".join(tokens)
|
| 86 |
+
|
| 87 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
| 88 |
+
result = token_ids_0 + [self.sep_token_id]
|
| 89 |
+
if token_ids_1 is not None:
|
| 90 |
+
result += token_ids_1 + [self.sep_token_id]
|
| 91 |
+
return result
|
| 92 |
+
|
| 93 |
+
def get_special_tokens_mask(
|
| 94 |
+
self, token_ids_0, token_ids_1=None, already_has_special_tokens=False
|
| 95 |
+
):
|
| 96 |
+
if already_has_special_tokens:
|
| 97 |
+
return super().get_special_tokens_mask(
|
| 98 |
+
token_ids_0, token_ids_1, already_has_special_tokens=True
|
| 99 |
+
)
|
| 100 |
+
mask = [0] * len(token_ids_0) + [1]
|
| 101 |
+
if token_ids_1 is not None:
|
| 102 |
+
mask += [0] * len(token_ids_1) + [1]
|
| 103 |
+
return mask
|
| 104 |
+
|
| 105 |
+
def save_vocabulary(
|
| 106 |
+
self, save_directory: str, filename_prefix: Optional[str] = None
|
| 107 |
+
) -> tuple:
|
| 108 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 109 |
+
name = (filename_prefix + "-" if filename_prefix else "") + "vocab.json"
|
| 110 |
+
path = os.path.join(save_directory, name)
|
| 111 |
+
with open(path, "w") as f:
|
| 112 |
+
json.dump(self._vocab, f, indent=2)
|
| 113 |
+
return (path,)
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"added_tokens_decoder": {
|
| 3 |
+
"0": {
|
| 4 |
+
"content": "[BOS]",
|
| 5 |
+
"lstrip": false,
|
| 6 |
+
"normalized": false,
|
| 7 |
+
"rstrip": false,
|
| 8 |
+
"single_word": false,
|
| 9 |
+
"special": true
|
| 10 |
+
},
|
| 11 |
+
"1": {
|
| 12 |
+
"content": "[PAD]",
|
| 13 |
+
"lstrip": false,
|
| 14 |
+
"normalized": false,
|
| 15 |
+
"rstrip": false,
|
| 16 |
+
"single_word": false,
|
| 17 |
+
"special": true
|
| 18 |
+
},
|
| 19 |
+
"2": {
|
| 20 |
+
"content": "[CLS]",
|
| 21 |
+
"lstrip": false,
|
| 22 |
+
"normalized": false,
|
| 23 |
+
"rstrip": false,
|
| 24 |
+
"single_word": false,
|
| 25 |
+
"special": true
|
| 26 |
+
},
|
| 27 |
+
"3": {
|
| 28 |
+
"content": "[MASK]",
|
| 29 |
+
"lstrip": false,
|
| 30 |
+
"normalized": false,
|
| 31 |
+
"rstrip": false,
|
| 32 |
+
"single_word": false,
|
| 33 |
+
"special": true
|
| 34 |
+
},
|
| 35 |
+
"6": {
|
| 36 |
+
"content": "[UNK]",
|
| 37 |
+
"lstrip": false,
|
| 38 |
+
"normalized": false,
|
| 39 |
+
"rstrip": false,
|
| 40 |
+
"single_word": false,
|
| 41 |
+
"special": true
|
| 42 |
+
}
|
| 43 |
+
},
|
| 44 |
+
"bos_token": "[BOS]",
|
| 45 |
+
"clean_up_tokenization_spaces": false,
|
| 46 |
+
"cls_token": "[CLS]",
|
| 47 |
+
"eos_token": "[SEP]",
|
| 48 |
+
"extra_special_tokens": {},
|
| 49 |
+
"mask_token": "[MASK]",
|
| 50 |
+
"model_max_length": 12288,
|
| 51 |
+
"pad_token": "[PAD]",
|
| 52 |
+
"padding_side": "left",
|
| 53 |
+
"sep_token": "[SEP]",
|
| 54 |
+
"tokenizer_class": "HelixmRNATokenizer",
|
| 55 |
+
"unk_token": "[UNK]",
|
| 56 |
+
"auto_map": {
|
| 57 |
+
"AutoTokenizer": [
|
| 58 |
+
"tokenization_helix_mrna.HelixmRNATokenizer",
|
| 59 |
+
null
|
| 60 |
+
]
|
| 61 |
+
}
|
| 62 |
+
}
|
vocab.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"[BOS]": 0,
|
| 3 |
+
"[SEP]": 1,
|
| 4 |
+
"[PAD]": 1,
|
| 5 |
+
"[CLS]": 2,
|
| 6 |
+
"[MASK]": 3,
|
| 7 |
+
"[RESERVED]": 5,
|
| 8 |
+
"[UNK]": 6,
|
| 9 |
+
"A": 7,
|
| 10 |
+
"C": 8,
|
| 11 |
+
"G": 9,
|
| 12 |
+
"U": 10,
|
| 13 |
+
"N": 11,
|
| 14 |
+
"E": 12,
|
| 15 |
+
"T": 10
|
| 16 |
+
}
|