[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M75KK7AH2AK9000B2FVFCYRN":3,"skill-same:01M75KK7AH2AK9000B2FVFCYRN":46},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M75KK7AH2AK9000B2FVFCYRN","deep-learning-genomics",null,"Use CNNs (DeepBind, Basset), RNNs, and transformers (DNABERT, HyenaDNA, Evo, Nucleotide Transformer) for genomic sequence analysis. Use when predicting TF binding, chromatin profiles, splicing, or noncoding variant effects from raw sequence.","pradyumnasagar\u002Fopen-research-skills","pradyumnasagar","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F10559871?v=4","01M75K78MYCCVKRTYGT8KKC380","Pradyumna Jayaram","01M75K78NTNE41F2PE1XBVFHAS",8,"MIT","https:\u002F\u002Fgithub.com\u002Fpradyumnasagar\u002Fopen-research-skills\u002Fblob\u002Fmain\u002Fskills\u002Fmachine-learning-bio\u002Fdeep-learning-genomics\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\n\nname: deep-learning-genomics\ndescription: \"Use CNNs (DeepBind, Basset), RNNs, and transformers (DNABERT, HyenaDNA, Evo, Nucleotide Transformer) for genomic sequence analysis. Use when predicting TF binding, chromatin profiles, splicing, or noncoding variant effects from raw sequence.\"\nlicense: MIT\n---\n\u003C!-- metadata:\n  category: machine-learning-bio\n  oversight: low\n  version: 1.0.0\n  author: Pradyumna Jayaram\n  tags: [machine-learning-bio, research]\n  difficulty: intermediate\n-->\n\n# Deep Learning for Genomics\n\n## Hard rules\n\n1. **No fabricated citations.** Every cited work must resolve to a verifiable\n2. **No claim without provenance.** Every quantitative or factual claim\n3. **No silent failure.** Every script invocation, API call, or tool use must declare its exit status and what to do on non-zero. A skill that silently swallows errors is a violation.\n\n## When to use\n\n- You want to predict transcription-factor binding from DNA sequence alone (no ChIP-seq label is available or you need an *in silico* filter).\n- You need to score variant effect in noncoding regions where there is no experimental data — transformer models give you a learned prior.\n- You need to generate per-base functional annotations along the genome and your only input is the reference + alt alleles.\n- You want to pull embeddings from a pre-trained foundation model to use as features in a downstream classifier.\n- You are building a chromatin assay-to-sequence model (the inverse of TF binding: given histone marks, where is the gene?).\n\n## When NOT to use\n\n- The task is purely variant calling from reads (not sequence). Use traditional variant callers (GATK, FreeBayes) combined with deep-learning post-filtering, not a genomic sequence model.\n- You have enough high-quality ChIP-seq \u002F ATAC-seq data to train a supervised model — DeepBind \u002F Basset models are good but your data will always beat a generic model on your system.\n- The functional question is about splicing (exon definition, NMD, splice-site conservation). Use splice-score models (MaxEntScan, MMSplice) specifically.\n- The signal is very short or very local (\u003C10 bp). CNNs are overkill for simple motif counts or k-mer filters, but you can use a shallow CNN to learn a kernel.\n- You need interpretability or PWM \u002F MEME-level motif discovery. CNN filter visualization works but is not the same as a rigorous de novo motif find; use meme-suite for discovery and the CNN for scoring.\n\n## Prerequisites\n\n```bash\n# Core deep-learning frameworks\npip install torch keras tensorflow\n\n# Sequence handling utilities\npip install biotite pyfaidx scikit-bio\n\n# Big genome tools\npip install pybedtools  # requires bedtools2 installed separately\n\n# For DNABERT: a full model run is ~10-20 GB GPU memory for the full model\npip install dna-nlp  # or follow github.com\u002F3011git\u002FDeepBug\n\n# For HyenaDNA and other foundation models\npip install hyena-dna  # check the repo for installation\npip install transformers\n\n# GPU CUDA verification\npython -c \"import torch; print(torch.cuda.is_available(), torch.cuda.get_device_name(0) if torch.cuda.is_available() else None)\"\n```\n\nHardware baselines (rough; verify against each repo):\n\n- DeepBind-sized CNNs (single-task): 4–8 GB VRAM.\n- DNABERT \u002F HyenaDNA fine-tuning: 16–40 GB VRAM.\n- Full foundation model inference: ≥24 GB (the full model weights + forward + gradient storage).\n- Embedding extraction only (no backward pass): half the memory of forward.\n\nConceptual prerequisites: know the difference between a **k-mer convolution kernel** learned from data vs. a known PWM (position-weight matrix), and understand that \"zero-shot\" for genomics means predicting function for a TF or variant type that the model has never seen in training — this is inherently harder than a model with full annotation.\n\n## Core workflow\n\n### 1. Pick the model architecture\n\n| Task | Default model | Why |\n|------|---------------|-----|\n| Binding site prediction | DeepBind \u002F Basset | Proven on ChIP-seq; CNN kernels directly learn PWMs |\n| Variant effect in regulatory DNA | Nucleotide Transformer \u002F DNABERT | Transformer gives contextual embeddings; pre-trained on 100M+ motifs \u002F genomes |\n| Full-genome functional annotation | DNABERT-2 \u002F Evo | Token-level classification across entire chromosomes |\n| Embedding extraction for downstream | Any foundation model (DNABERT, NT, HyenaDNA) | Use the [CLS] token or mean-pool |\n| Long-sequence modeling (>2 kb) | HyenaDNA \u002F Evo | Recurrence \u002F state-space; linear in sequence length |\n| Multi-modal (DNA + RNA + protein) | scGPT \u002F Geneformer cross-modal | Outside scope; see single-cell skill |\n\n### 2. Basic CNN binding prediction (DeepBind-style)\n\nThe 2015 DeepBind paper showed that a small 1D CNN on one-hot DNA can match PWM-based tools. This is the baseline reference architecture.\n\n```python\nimport torch, torch.nn as nn\n\nclass DeepBindCNN(nn.Module):\n    def __init__(self, seq_len=200, n_classes=1, conv_dims=[128, 64], kernel_sizes=[15, 11]):\n        super().__init__()\n        self.convs = nn.ModuleList([\n            nn.Conv1d(4, d, k) for d, k in zip(conv_dims, kernel_sizes)\n        ])\n        self.pool = nn.AdaptiveMaxPool1d(1)\n        self.fc = nn.Linear(sum(conv_dims), n_classes)\n\n    def forward(self, x):  # x: (B, 4, L)\n        h = torch.cat([torch.relu(conv(x)) for conv in self.convs], dim=1)\n        h = self.pool(h).squeeze(-1)\n        return self.fc(h)\n```\n\nTraining typical: BCEWithLogitsLoss (for binding yes\u002Fno) or CrossEntropy (for multi-class). Use BAsset \u002F `train_bigwig.py` from the DeepBind repo for data preprocessing.\n\n### 3. Encode a genome for transformer ingestion\n\nDNABERT and HyenaDNA diverge in tokenization. In general, use a k-mer tokenizer (di-nucleotide or tri-nucleotide, not per-base).\n\n```python\ndef kmer_tokenize(seq, k=3):\n    \"\"\"Convert DNA to k-mer token indices. Standard: k=3 (codons) or k=2 (dinucleotides).\"\"\"\n    seq = seq.upper().replace(\"N\", \"A\")  # mask ambiguous bases\n    kmers = [seq[i:i+k] for i in range(len(seq) - k + 1)]\n    # Map each k-mer to an integer via hash or lookup table\n    return kmers\n\n# For DNABERT, use the built-in tokenizer\nfrom transformers import AutoTokenizer\ntok = AutoTokenizer.from_pretrained(\"dna bert-base\")\nenc = tok(\"ACGTACGT...\", return_tensors=\"pt\")\n```\n\nThe k-mer tokenizer is important: per-base tokenization produces a vocabulary size of 4 (plus special tokens). k-mer vocabulary is 4^k — 3-mer → 64 tokens, which is enough for a model to learn di-nucleotide \u002F tri-nucleotide interactions.\n\n### 4. Per-base variant effect scoring\n\nThe standard pattern: forward pass for ref vs. alt, take the difference at the changed position.\n\n```python\ndef score_variant(ref_seq, alt_seq, position, model, tokenizer):\n    \"\"\"\n    Return a score difference (alt - ref) at position (0-indexed).\n    The model is a token-level classifier or MLM.\n    \"\"\"\n    # Tokenize both sequences\n    ref_enc = tokenizer(ref_seq, return_tensors=\"pt\")\n    alt_enc = tokenizer(alt_seq, return_tensors=\"pt\")\n\n    with torch.no_grad():\n        ref_out = model(**ref_enc).logits[0, position]\n        alt_out = model(**alt_enc).logits[0, position]\n\n    # For binary classification: sigmoid (ref) -> prob, same for alt\n    ref_prob = torch.sigmoid(ref_out)\n    alt_prob = torch.sigmoid(alt_out)\n    return (alt_prob - ref_prob).item()  # positive = alt increases predicted function\n```\n\nVariant-effect models are evaluated by: AUC against functional assays (ChIP-seq, eCLIP, GWAS hits), not by absolute scores. Use a held-out benchmark set (ProteinGym for proteins, a held-out TF for DNA) to calibrate.\n\n### 5. Embedding extraction from a foundation model\n\nUse this as input to any downstream classifier that takes sequence features.\n\n```python\nimport torch\nfrom transformers import AutoModel, AutoTokenizer\n\nmodel_name = \"InstaDeepAI\u002Fnucleotide-transformer-v2-100m-6t-30k\"  # or dna-bert, hyena-dna\ntok = AutoTokenizer.from_pretrained(model_name)\nmodel = AutoModel.from_pretrained(model_name).eval()\n\ndef get_embedding(seq, layer=-1):\n    \"\"\"Return a per-token embedding, `layer` from the last hidden state.\"\"\"\n    enc = tok(seq, return_tensors=\"pt\")\n    with torch.no_grad():\n        out = model(**enc, output_hidden_states=True)\n    hidden = out.hidden_states[layer]\n    # Average over sequence (or use CLS token)\n    mask = enc[\"attention_mask\"].unsqueeze(-1).float()\n    avg = (hidden * mask).sum(1) \u002F mask.sum(1).clamp(min=1)\n    return avg.squeeze(0).numpy()\n```\n\nThe embedding dimension varies: 256–768 typically for small models, 1280 for large. Check the model card.\n\n### 6. Whole-genome annotation pipeline (sketch)\n\nFor annotation of an entire chromosome, chunk, batch, and write to BED\u002FbigWig.\n\n```python\n# Pseudo-code: chunk + batch + save as BED\nimport numpy as np\nfrom pybedtools import BedTool\n\ndef annotate_genome(genome_fasta, model, tokenizer, chunk_size=512, step=256):\n    \"\"\"Yield per-base scores across the whole chromosome.\"\"\"\n    seq = load_genome(genome_fasta)  # pyfaidx or Biotite\n    scores = []\n    for i in range(0, len(seq) - chunk_size, step):\n        chunk = seq[i:i+chunk_size]\n        scores.append(predict_one(chunk))\n    # Flatten and save as bigWig or BEDGraph\n    return np.concatenate(scores)\n```\n\nThis is expensive. For whole-genome runs, use DNABERT's `--BedGraph` flag if the tool has one, or subsample. You will not annotate the human genome at single-base resolution in a single run — plan for chunking.\n\n## Code patterns\n\n### Visualizing learned CNN filters as PWMs (DeepBind interpretability)\n\n```python\ndef filter_to_pwm(conv_weight):\n    \"\"\"conv_weight: (4, kernel_size). Convert to PWM-like view.\"\"\"\n    return conv_weight.T.abs() \u002F conv_weight.T.abs().sum(dim=1, keepdim=True)\n\n# Plot with logomaker or Biopython SeqLogo\nimport logomaker\nlogo = logomaker.Logo(filter_to_pwm(model.convs[0].weight.detach().numpy()), shade_below=0.5)\n```\n\n### Convert BED to training regions\n\n```python\nimport pybedtools\n\ndef bed_to_training_chunks(bed_file, genome_fasta, window=200):\n    \"\"\"Yield (sequence, label) pairs from BED intervals.\"\"\"\n    bt = pybedtools.BedTool(bed_file)\n    genome = pyfaidx.Fasta(genome_fasta)\n    for interval in bt:\n        start, end = interval.start, interval.end\n        # pad to window\n        pad_before = (window - (end - start)) \u002F\u002F 2\n        pad_after = window - (end - start) - pad_before\n        seq = genome[interval.chrom][start - pad_before:end + pad_after].seq\n        label = float(interval.score) if interval.score else 1.0  # assume positive class\n        yield seq.upper(), label\n```\n\n### GPU memory saving for long sequences\n\n```python\n# Gradient checkpointing for long sequences (no model changes needed)\nfrom torch.utils.checkpoint import checkpoint_sequential\n\nmodel = AutoModel.from_pretrained(\"hyena-dna\")\nmodel gradients = [p.requires_grad for p in model.parameters()]\n\ndef forward_with_checkpoint(seq):\n    # Split the model into two halves for checkpointing\n    modules = [model.embed + model.encoder.layer[:6], model.encoder.layer[6:]]\n    return checkpoint_sequential(modules, 2, seq)\n```\n\n## Common pitfalls\n\n- **One-hot encoding is memory-expensive for long sequences.** Use k-mer tokenization; one-hot of 100kb → 400k floats; k-mer → 64 × 100k.\n- **Ignoring strand.** DNA has no intrinsic orientation — double the model capacity (forward \u002F reverse complement) or pre-reverse complement your sequences. Basset does this internally; not all tools do.\n- **Mixing up model types.** A masked language model (MLM) such as DNABERT trained with [MASK] tokens is different from a sequence-to-label classifier which predicts a scalar at [CLS]. The MLM gives you per-position logits; theClassifier aggregates to a single prediction. Both are \"transformers\" but the outputs differ.\n- **Assuming the model sees the right strand.** Some tools expect the sequence as-written, others reverse-complement automatically. Check the repo.\n- **Training on the same genome the model was pre-trained on.** If you train on hg38 and the model was trained on hg38 for \"genome modeling\", you are learning the residual, not the function. Split by chromosome or hold out entire chromosomes.\n- **Overfitting small TF ChIP-seq.** If you have \u003C5,000 peaks, a CNN may memorize; use transfer learning, augment by reverse complement, or use a pre-trained model as a frozen feature extractor.\n- **Not using a proper negative set.** Random negatives (shuffled sequences) are too easy. Use conservation-matched negatives or flanks of the positive peaks.\n\n## Validation\n\n- **Held-out ChIP-seq.** Split peaks by chromosome, train on chr1-22, validate on chrM or chrY.\n- **Variant-effect benchmarks.** Use held-out GWAS variant sets (the variant was not in the training set of the model). Compute AUC \u002F Precision-Recall.\n- **Motif recovery.** Run a CNN filter visualization; if it matches a known PWM in JASPAR, you have an interpretability signal.\n- **Per-base functional annotation.** Run on a region with known functional data not used in training (e.g. an ENCODE tier 1 enhancer), compare predicted accessibility against the assay.\n- **Downstream classifier.** Use the extracted embeddings as input to a simple logistic regression on a held-out functional task. If embeddings are randomly distributed, the model learned nothing useful. If logistic regression on frozen embeddings beats random, the model is useful.\n\n## Open alternatives\n\n- **DeepBind:** The original (Alipanahi et al. 2015). Closed academic license but widely reproduced. Basset is the open successor with a fully convolutional architecture.\n- **DNABERT:** Open weights (GitHub: `3011git\u002FDeepBug`). Fine-tuning requires GPU but the model is reproducible.\n- **HyenaDNA:** Open (Nature Methods 2024). Linear-time for long sequences; competes with token-level transformers.\n- **Nucleotide Transformer:** Open weights (InstaDeepAI). Pre-trained on 100M+ genomes; use for embedding extraction.\n- **Evo:** From Character.AI \u002F a]6]S. High-quality genome model but check the license.\n- **Non-deep options:** FIMO \u002F meme-suite for PWM scanning; linear SVM or XGBoost on k-mer features for baseline classification (faster than CNN, interpretable).\n\n## References\n\n- Alipanahi et al., 2015, *Nature Biotechnology* — DeepBind (the landmark CNN for TF binding).\n- Kelley et al., 2016, *Genome Research* — Basset (open CNN for chromatin accessibility).\n- Zhou et al., 2023 — DNABERT (transformer for DNA).\n- Nguyen et al., 2024, *Nature Methods* — HyenaDNA (state-space model for long sequences).\n- Zhou et al., 2023 — Nucleotide Transformer (InstaDeepAI; 100M+ pre-training).\n- Varadi et al. — JASPAR for PWM ground truth.\n- Quinlan & Pennock — bedtools2 for BED manipulation.\n- Scherp et al. — pyfaidx for FASTA access.\n- The ENCODE Consortium — ChIP-seq \u002F ATAC-seq benchmarks.\n\n## Related Skills\n\n- `machine-learning-bio\u002Falphafold-structure-prediction` — protein structural counterpart (embedding extraction from protein language model)\n- `machine-learning-bio\u002Fscrnaseq-deep-learning` — single-cell RNA-seq foundation models (Geneformer, scGPT)\n- `bioinformatics-sequence\u002Ffasta-fastq-io` — sequence I\u002FO (input preparation)\n- `bioinformatics-omics\u002Fchip-seq-analysis` — ChIP-seq (the experimental data for binding prediction)\n- `bioinformatics-omics\u002Fatac-seq-analysis` — ATAC-seq (the accessibility assay)\n\n## Changelog\n\n- 1.0.0 (2026-06-10): Initial adaptation by Pradyumna Jayaram from DeepBind paper, DNABERT repo, and HyenaDNA paper; added practical k-mer tokenization and variant-scoring pipeline, GPU baselines, and model-selection rubric.\n\n## Cross-references\n\nOther skills in this category:\n\n- alphafold-structure-prediction\n- protein-language-models\n- scrnaseq-deep-learning\n","\u003C!-- metadata:\n  category: machine-learning-bio\n  oversight: low\n  version: 1.0.0\n  author: Pradyumna Jayaram\n  tags: [machine-learning-bio, research]\n  difficulty: intermediate\n-->\n\n# Deep Learning for Genomics\n\n## Hard rules\n\n1. **No fabricated citations.** Every cited work must resolve to a verifiable\n2. **No claim without provenance.** Every quantitative or factual claim\n3. **No silent failure.** Every script invocation, API call, or tool use must declare its exit status and what to do on non-zero. A skill that silently swallows errors is a violation.\n\n## When to use\n\n- You want to predict transcription-factor binding from DNA sequence alone (no ChIP-seq label is available or you need an *in silico* filter).\n- You need to score variant effect in noncoding regions where there is no experimental data — transformer models give you a learned prior.\n- You need to generate per-base functional annotations along the genome and your only input is the reference + alt alleles.\n- You want to pull embeddings from a pre-trained foundation model to use as features in a downstream classifier.\n- You are building a chromatin assay-to-sequence model (the inverse of TF binding: given histone marks, where is the gene?).\n\n## When NOT to use\n\n- The task is purely variant calling from reads (not sequence). Use traditional variant callers (GATK, FreeBayes) combined with deep-learning post-filtering, not a genomic sequence model.\n- You have enough high-quality ChIP-seq \u002F ATAC-seq data to train a supervised model — DeepBind \u002F Basset models are good but your data will always beat a generic model on your system.\n- The functional question is about splicing (exon definition, NMD, splice-site conservation). Use splice-score models (MaxEntScan, MMSplice) specifically.\n- The signal is very short or very local (\u003C10 bp). CNNs are overkill for simple motif counts or k-mer filters, but you can use a shallow CNN to learn a kernel.\n- You need interpretability or PWM \u002F MEME-level motif discovery. CNN filter visualization works but is not the same as a rigorous de novo motif find; use meme-suite for discovery and the CNN for scoring.\n\n## Prerequisites\n\n```bash\n# Core deep-learning frameworks\npip install torch keras tensorflow\n\n# Sequence handling utilities\npip install biotite pyfaidx scikit-bio\n\n# Big genome tools\npip install pybedtools  # requires bedtools2 installed separately\n\n# For DNABERT: a full model run is ~10-20 GB GPU memory for the full model\npip install dna-nlp  # or follow github.com\u002F3011git\u002FDeepBug\n\n# For HyenaDNA and other foundation models\npip install hyena-dna  # check the repo for installation\npip install transformers\n\n# GPU CUDA verification\npython -c \"import torch; print(torch.cuda.is_available(), torch.cuda.get_device_name(0) if torch.cuda.is_available() else None)\"\n```\n\nHardware baselines (rough; verify against each repo):\n\n- DeepBind-sized CNNs (single-task): 4–8 GB VRAM.\n- DNABERT \u002F HyenaDNA fine-tuning: 16–40 GB VRAM.\n- Full foundation model inference: ≥24 GB (the full model weights + forward + gradient storage).\n- Embedding extraction only (no backward pass): half the memory of forward.\n\nConceptual prerequisites: know the difference between a **k-mer convolution kernel** learned from data vs. a known PWM (position-weight matrix), and understand that \"zero-shot\" for genomics means predicting function for a TF or variant type that the model has never seen in training — this is inherently harder than a model with full annotation.\n\n## Core workflow\n\n### 1. Pick the model architecture\n\n| Task | Default model | Why |\n|------|---------------|-----|\n| Binding site prediction | DeepBind \u002F Basset | Proven on ChIP-seq; CNN kernels directly learn PWMs |\n| Variant effect in regulatory DNA | Nucleotide Transformer \u002F DNABERT | Transformer gives contextual embeddings; pre-trained on 100M+ motifs \u002F genomes |\n| Full-genome functional annotation | DNABERT-2 \u002F Evo | Token-level classification across entire chromosomes |\n| Embedding extraction for downstream | Any foundation model (DNABERT, NT, HyenaDNA) | Use the [CLS] token or mean-pool |\n| Long-sequence modeling (>2 kb) | HyenaDNA \u002F Evo | Recurrence \u002F state-space; linear in sequence length |\n| Multi-modal (DNA + RNA + protein) | scGPT \u002F Geneformer cross-modal | Outside scope; see single-cell skill |\n\n### 2. Basic CNN binding prediction (DeepBind-style)\n\nThe 2015 DeepBind paper showed that a small 1D CNN on one-hot DNA can match PWM-based tools. This is the baseline reference architecture.\n\n```python\nimport torch, torch.nn as nn\n\nclass DeepBindCNN(nn.Module):\n    def __init__(self, seq_len=200, n_classes=1, conv_dims=[128, 64], kernel_sizes=[15, 11]):\n        super().__init__()\n        self.convs = nn.ModuleList([\n            nn.Conv1d(4, d, k) for d, k in zip(conv_dims, kernel_sizes)\n        ])\n        self.pool = nn.AdaptiveMaxPool1d(1)\n        self.fc = nn.Linear(sum(conv_dims), n_classes)\n\n    def forward(self, x):  # x: (B, 4, L)\n        h = torch.cat([torch.relu(conv(x)) for conv in self.convs], dim=1)\n        h = self.pool(h).squeeze(-1)\n        return self.fc(h)\n```\n\nTraining typical: BCEWithLogitsLoss (for binding yes\u002Fno) or CrossEntropy (for multi-class). Use BAsset \u002F `train_bigwig.py` from the DeepBind repo for data preprocessing.\n\n### 3. Encode a genome for transformer ingestion\n\nDNABERT and HyenaDNA diverge in tokenization. In general, use a k-mer tokenizer (di-nucleotide or tri-nucleotide, not per-base).\n\n```python\ndef kmer_tokenize(seq, k=3):\n    \"\"\"Convert DNA to k-mer token indices. Standard: k=3 (codons) or k=2 (dinucleotides).\"\"\"\n    seq = seq.upper().replace(\"N\", \"A\")  # mask ambiguous bases\n    kmers = [seq[i:i+k] for i in range(len(seq) - k + 1)]\n    # Map each k-mer to an integer via hash or lookup table\n    return kmers\n\n# For DNABERT, use the built-in tokenizer\nfrom transformers import AutoTokenizer\ntok = AutoTokenizer.from_pretrained(\"dna bert-base\")\nenc = tok(\"ACGTACGT...\", return_tensors=\"pt\")\n```\n\nThe k-mer tokenizer is important: per-base tokenization produces a vocabulary size of 4 (plus special tokens). k-mer vocabulary is 4^k — 3-mer → 64 tokens, which is enough for a model to learn di-nucleotide \u002F tri-nucleotide interactions.\n\n### 4. Per-base variant effect scoring\n\nThe standard pattern: forward pass for ref vs. alt, take the difference at the changed position.\n\n```python\ndef score_variant(ref_seq, alt_seq, position, model, tokenizer):\n    \"\"\"\n    Return a score difference (alt - ref) at position (0-indexed).\n    The model is a token-level classifier or MLM.\n    \"\"\"\n    # Tokenize both sequences\n    ref_enc = tokenizer(ref_seq, return_tensors=\"pt\")\n    alt_enc = tokenizer(alt_seq, return_tensors=\"pt\")\n\n    with torch.no_grad():\n        ref_out = model(**ref_enc).logits[0, position]\n        alt_out = model(**alt_enc).logits[0, position]\n\n    # For binary classification: sigmoid (ref) -> prob, same for alt\n    ref_prob = torch.sigmoid(ref_out)\n    alt_prob = torch.sigmoid(alt_out)\n    return (alt_prob - ref_prob).item()  # positive = alt increases predicted function\n```\n\nVariant-effect models are evaluated by: AUC against functional assays (ChIP-seq, eCLIP, GWAS hits), not by absolute scores. Use a held-out benchmark set (ProteinGym for proteins, a held-out TF for DNA) to calibrate.\n\n### 5. Embedding extraction from a foundation model\n\nUse this as input to any downstream classifier that takes sequence features.\n\n```python\nimport torch\nfrom transformers import AutoModel, AutoTokenizer\n\nmodel_name = \"InstaDeepAI\u002Fnucleotide-transformer-v2-100m-6t-30k\"  # or dna-bert, hyena-dna\ntok = AutoTokenizer.from_pretrained(model_name)\nmodel = AutoModel.from_pretrained(model_name).eval()\n\ndef get_embedding(seq, layer=-1):\n    \"\"\"Return a per-token embedding, `layer` from the last hidden state.\"\"\"\n    enc = tok(seq, return_tensors=\"pt\")\n    with torch.no_grad():\n        out = model(**enc, output_hidden_states=True)\n    hidden = out.hidden_states[layer]\n    # Average over sequence (or use CLS token)\n    mask = enc[\"attention_mask\"].unsqueeze(-1).float()\n    avg = (hidden * mask).sum(1) \u002F mask.sum(1).clamp(min=1)\n    return avg.squeeze(0).numpy()\n```\n\nThe embedding dimension varies: 256–768 typically for small models, 1280 for large. Check the model card.\n\n### 6. Whole-genome annotation pipeline (sketch)\n\nFor annotation of an entire chromosome, chunk, batch, and write to BED\u002FbigWig.\n\n```python\n# Pseudo-code: chunk + batch + save as BED\nimport numpy as np\nfrom pybedtools import BedTool\n\ndef annotate_genome(genome_fasta, model, tokenizer, chunk_size=512, step=256):\n    \"\"\"Yield per-base scores across the whole chromosome.\"\"\"\n    seq = load_genome(genome_fasta)  # pyfaidx or Biotite\n    scores = []\n    for i in range(0, len(seq) - chunk_size, step):\n        chunk = seq[i:i+chunk_size]\n        scores.append(predict_one(chunk))\n    # Flatten and save as bigWig or BEDGraph\n    return np.concatenate(scores)\n```\n\nThis is expensive. For whole-genome runs, use DNABERT's `--BedGraph` flag if the tool has one, or subsample. You will not annotate the human genome at single-base resolution in a single run — plan for chunking.\n\n## Code patterns\n\n### Visualizing learned CNN filters as PWMs (DeepBind interpretability)\n\n```python\ndef filter_to_pwm(conv_weight):\n    \"\"\"conv_weight: (4, kernel_size). Convert to PWM-like view.\"\"\"\n    return conv_weight.T.abs() \u002F conv_weight.T.abs().sum(dim=1, keepdim=True)\n\n# Plot with logomaker or Biopython SeqLogo\nimport logomaker\nlogo = logomaker.Logo(filter_to_pwm(model.convs[0].weight.detach().numpy()), shade_below=0.5)\n```\n\n### Convert BED to training regions\n\n```python\nimport pybedtools\n\ndef bed_to_training_chunks(bed_file, genome_fasta, window=200):\n    \"\"\"Yield (sequence, label) pairs from BED intervals.\"\"\"\n    bt = pybedtools.BedTool(bed_file)\n    genome = pyfaidx.Fasta(genome_fasta)\n    for interval in bt:\n        start, end = interval.start, interval.end\n        # pad to window\n        pad_before = (window - (end - start)) \u002F\u002F 2\n        pad_after = window - (end - start) - pad_before\n        seq = genome[interval.chrom][start - pad_before:end + pad_after].seq\n        label = float(interval.score) if interval.score else 1.0  # assume positive class\n        yield seq.upper(), label\n```\n\n### GPU memory saving for long sequences\n\n```python\n# Gradient checkpointing for long sequences (no model changes needed)\nfrom torch.utils.checkpoint import checkpoint_sequential\n\nmodel = AutoModel.from_pretrained(\"hyena-dna\")\nmodel gradients = [p.requires_grad for p in model.parameters()]\n\ndef forward_with_checkpoint(seq):\n    # Split the model into two halves for checkpointing\n    modules = [model.embed + model.encoder.layer[:6], model.encoder.layer[6:]]\n    return checkpoint_sequential(modules, 2, seq)\n```\n\n## Common pitfalls\n\n- **One-hot encoding is memory-expensive for long sequences.** Use k-mer tokenization; one-hot of 100kb → 400k floats; k-mer → 64 × 100k.\n- **Ignoring strand.** DNA has no intrinsic orientation — double the model capacity (forward \u002F reverse complement) or pre-reverse complement your sequences. Basset does this internally; not all tools do.\n- **Mixing up model types.** A masked language model (MLM) such as DNABERT trained with [MASK] tokens is different from a sequence-to-label classifier which predicts a scalar at [CLS]. The MLM gives you per-position logits; theClassifier aggregates to a single prediction. Both are \"transformers\" but the outputs differ.\n- **Assuming the model sees the right strand.** Some tools expect the sequence as-written, others reverse-complement automatically. Check the repo.\n- **Training on the same genome the model was pre-trained on.** If you train on hg38 and the model was trained on hg38 for \"genome modeling\", you are learning the residual, not the function. Split by chromosome or hold out entire chromosomes.\n- **Overfitting small TF ChIP-seq.** If you have \u003C5,000 peaks, a CNN may memorize; use transfer learning, augment by reverse complement, or use a pre-trained model as a frozen feature extractor.\n- **Not using a proper negative set.** Random negatives (shuffled sequences) are too easy. Use conservation-matched negatives or flanks of the positive peaks.\n\n## Validation\n\n- **Held-out ChIP-seq.** Split peaks by chromosome, train on chr1-22, validate on chrM or chrY.\n- **Variant-effect benchmarks.** Use held-out GWAS variant sets (the variant was not in the training set of the model). Compute AUC \u002F Precision-Recall.\n- **Motif recovery.** Run a CNN filter visualization; if it matches a known PWM in JASPAR, you have an interpretability signal.\n- **Per-base functional annotation.** Run on a region with known functional data not used in training (e.g. an ENCODE tier 1 enhancer), compare predicted accessibility against the assay.\n- **Downstream classifier.** Use the extracted embeddings as input to a simple logistic regression on a held-out functional task. If embeddings are randomly distributed, the model learned nothing useful. If logistic regression on frozen embeddings beats random, the model is useful.\n\n## Open alternatives\n\n- **DeepBind:** The original (Alipanahi et al. 2015). Closed academic license but widely reproduced. Basset is the open successor with a fully convolutional architecture.\n- **DNABERT:** Open weights (GitHub: `3011git\u002FDeepBug`). Fine-tuning requires GPU but the model is reproducible.\n- **HyenaDNA:** Open (Nature Methods 2024). Linear-time for long sequences; competes with token-level transformers.\n- **Nucleotide Transformer:** Open weights (InstaDeepAI). Pre-trained on 100M+ genomes; use for embedding extraction.\n- **Evo:** From Character.AI \u002F a]6]S. High-quality genome model but check the license.\n- **Non-deep options:** FIMO \u002F meme-suite for PWM scanning; linear SVM or XGBoost on k-mer features for baseline classification (faster than CNN, interpretable).\n\n## References\n\n- Alipanahi et al., 2015, *Nature Biotechnology* — DeepBind (the landmark CNN for TF binding).\n- Kelley et al., 2016, *Genome Research* — Basset (open CNN for chromatin accessibility).\n- Zhou et al., 2023 — DNABERT (transformer for DNA).\n- Nguyen et al., 2024, *Nature Methods* — HyenaDNA (state-space model for long sequences).\n- Zhou et al., 2023 — Nucleotide Transformer (InstaDeepAI; 100M+ pre-training).\n- Varadi et al. — JASPAR for PWM ground truth.\n- Quinlan & Pennock — bedtools2 for BED manipulation.\n- Scherp et al. — pyfaidx for FASTA access.\n- The ENCODE Consortium — ChIP-seq \u002F ATAC-seq benchmarks.\n\n## Related Skills\n\n- `machine-learning-bio\u002Falphafold-structure-prediction` — protein structural counterpart (embedding extraction from protein language model)\n- `machine-learning-bio\u002Fscrnaseq-deep-learning` — single-cell RNA-seq foundation models (Geneformer, scGPT)\n- `bioinformatics-sequence\u002Ffasta-fastq-io` — sequence I\u002FO (input preparation)\n- `bioinformatics-omics\u002Fchip-seq-analysis` — ChIP-seq (the experimental data for binding prediction)\n- `bioinformatics-omics\u002Fatac-seq-analysis` — ATAC-seq (the accessibility assay)\n\n## Changelog\n\n- 1.0.0 (2026-06-10): Initial adaptation by Pradyumna Jayaram from DeepBind paper, DNABERT repo, and HyenaDNA paper; added practical k-mer tokenization and variant-scoring pipeline, GPU baselines, and model-selection rubric.\n\n## Cross-references\n\nOther skills in this category:\n\n- alphafold-structure-prediction\n- protein-language-models\n- scrnaseq-deep-learning\n",{"name":5,"license":15,"description":7},"main","9c0b41e2036cc5588c699f06e658ea6dc3b9685d","skills\u002Fmachine-learning-bio\u002Fdeep-learning-genomics",2,"https:\u002F\u002Fgithub.com\u002Fpradyumnasagar\u002Fopen-research-skills","https:\u002F\u002Fgithub.com\u002Fpradyumnasagar","PhD Scholar,\r\nManipal School Of Life Sciences, Manipal\r\n #OpenSourceDeveloper #LifeSciences #ComputationalBiology","2026-10-30 01:30:52",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add pradyumnasagar\u002Fopen-research-skills --skill deep-learning-genomics",{"tool":38,"command":39},"bunx","bunx skills add pradyumnasagar\u002Fopen-research-skills --skill deep-learning-genomics",{"tool":41,"command":42},"pnpm","pnpm dlx skills add pradyumnasagar\u002Fopen-research-skills --skill deep-learning-genomics","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fpradyumnasagar\u002Fopen-research-skills\u002Fblob\u002Fmain\u002Fskills\u002Fmachine-learning-bio\u002Fdeep-learning-genomics\u002FSKILL.md",true,[],[47,54,60,67,74,81],{"skillNo":48,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":19},"01M75KTS5K9QNX8FQBTJW2GQSH","good-skill","A well-formed test fixture for the validation script.","https:\u002F\u002Fgithub.com\u002Fpradyumnasagar\u002Fopen-research-skills\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fgood-skill\u002FSKILL.md",[],[],{"skillNo":55,"name":56,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M75KTR7FAT0MMMED2EGC9WZZ","BadSkill","https:\u002F\u002Fgithub.com\u002Fpradyumnasagar\u002Fopen-research-skills\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fbad-skill\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M75KTN949EDF77GJDS8H6VR8","my-new-skill","One sentence (max 200 chars) — what the skill does and when to use it.","https:\u002F\u002Fgithub.com\u002Fpradyumnasagar\u002Fopen-research-skills\u002Fblob\u002Fmain\u002Ftemplate\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M75KTHTFS121SSF1Q5X2FXDA","thesis-structure","Use when planning or checking the architecture of a PhD \u002F MPhil thesis in the life sciences or bioinformatics — monograph vs article-based, chapter sequence, IMRaD-based chapters, abstract-to-conclusion flow, and the examiner expectations that the structure must meet.","https:\u002F\u002Fgithub.com\u002Fpradyumnasagar\u002Fopen-research-skills\u002Fblob\u002Fmain\u002Fskills\u002Fthesis-writing\u002Fthesis-structure\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M75KTE3WKW46FXFHQ579H8YP","thesis-methods-reproducibility","Use when writing or checking the Methods, figures, data, and code of a bioinformatics \u002F microbiology \u002F life-science PhD thesis — the FAIR data, versioned code, report-generation, figure-and-table discipline, and the reproducibility expectations that examiners probe at viva.","https:\u002F\u002Fgithub.com\u002Fpradyumnasagar\u002Fopen-research-skills\u002Fblob\u002Fmain\u002Fskills\u002Fthesis-writing\u002Fthesis-methods-reproducibility\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M75KTA033ZQCJY3DC8P5VQET","thesis-defense-viva","Use when preparing for the viva voce \u002F oral thesis defense — building the examiner's question set, rehearsing the presentation, and the pre-defense polish (slides, summary, the 'what if I'm stuck' responses) for a life-science or bioinformatics PhD.","https:\u002F\u002Fgithub.com\u002Fpradyumnasagar\u002Fopen-research-skills\u002Fblob\u002Fmain\u002Fskills\u002Fthesis-writing\u002Fthesis-defense-viva\u002FSKILL.md",[],[]]