Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/atomistic-materials/atomistic-materials-astra-xhigh-1h100-48h-20261020b/submissions/S023/additional-neb57-cuda-diagnostic/barriers.pdf +0 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/README.md +64 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/infer.sh +12 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/package_manifest.json +26 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/perturb.py +101 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/perturb.sh +12 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/predict.py +130 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/prediction_contract.py +23 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/__init__.py +1 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/alphagenome_50m/__init__.py +5 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/alphagenome_50m/alphagenome_50m.yaml +23 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/alphagenome_50m/dataset.py +229 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/alphagenome_50m/layers.py +124 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/alphagenome_50m/model.py +368 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/alphagenome_50m/reference_large.yaml +23 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/alphagenome_50m/run_ddp.sh +16 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/alphagenome_50m/tiny_overfit.yaml +24 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/alphagenome_50m/train_eval.py +534 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/validation_tracks.json +0 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/validation_variants.json +125 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/README.md +70 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/infer.sh +12 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/package_manifest.json +26 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/perturb.py +101 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/perturb.sh +12 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/predict.py +130 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/prediction_contract.py +23 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/__init__.py +1 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/alphagenome_50m/__init__.py +5 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/alphagenome_50m/alphagenome_50m.yaml +23 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/alphagenome_50m/dataset.py +229 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/alphagenome_50m/layers.py +124 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/alphagenome_50m/model.py +426 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/alphagenome_50m/reference_large.yaml +23 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/alphagenome_50m/run_ddp.sh +16 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/alphagenome_50m/tiny_overfit.yaml +24 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/alphagenome_50m/train_eval.py +534 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/validation_tracks.json +0 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/validation_variants.json +125 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/README.md +77 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/attach_local.py +52 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/infer.sh +12 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/package_manifest.json +30 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/perturb.py +101 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/perturb.sh +12 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/predict.py +130 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/prediction_contract.py +23 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/reference/__init__.py +1 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/reference/alphagenome_50m/__init__.py +5 -0
- tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/reference/alphagenome_50m/alphagenome_50m.yaml +23 -0
tasks/atomistic-materials/atomistic-materials-astra-xhigh-1h100-48h-20261020b/submissions/S023/additional-neb57-cuda-diagnostic/barriers.pdf
ADDED
|
Binary file (19.6 kB). View file
|
|
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/README.md
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SeqFunc smoke00
|
| 2 |
+
|
| 3 |
+
This is an initial pipeline checkpoint, not a fully trained scientific result.
|
| 4 |
+
|
| 5 |
+
The single model has 13,218,756 trainable parameters. A convolutional encoder maps the complete
|
| 6 |
+
1,048,576-base DNA input to 1,024 tokens, followed by six 384-wide transformer blocks and shared
|
| 7 |
+
heads for all eleven output families. Dense heads predict 128-bp bins; splice sites use per-offset
|
| 8 |
+
logits, usage uses predicted positions, junctions use low-rank donor/acceptor factors, and contacts
|
| 9 |
+
use symmetric token products. The implementation is derived from the supplied reference code.
|
| 10 |
+
|
| 11 |
+
All parameters were initialized locally with seed 17. This checkpoint ran 16 optimizer steps on
|
| 12 |
+
the first 16 eligible training intervals, using quantized targets decoded by the supplied reader,
|
| 13 |
+
on one H100 80 GB on 2026-10-22. The measured training loop took 4.0 seconds, excluding setup.
|
| 14 |
+
This short run checks the pipeline; it does not yet meet the intended full-training coverage.
|
| 15 |
+
Subsequent experiments use every one of the 41,020 eligible intervals per epoch. No pretrained
|
| 16 |
+
parameters, validation training labels, test labels, or test-derived caches were used.
|
| 17 |
+
|
| 18 |
+
Both executable entry points take INPUT_ROOT and OUTPUT_ROOT. They use only public manifests and
|
| 19 |
+
the pinned reference FASTA. The package includes its CPython 3.11 environment, PyTorch 2.7.1 CUDA
|
| 20 |
+
12.6 runtime, and all Python dependencies in runtime.tar.gz. Entry points extract this environment
|
| 21 |
+
into a temporary directory, run offline, and remove it on completion. The host supplies Linux,
|
| 22 |
+
bash/tar/gzip and the NVIDIA driver. Model parameters are last.pt; source code and a SHA-256
|
| 23 |
+
manifest are included. Track values are float16; perturbation values are float32.
|
| 24 |
+
|
| 25 |
+
Validation reports accompanying publication cover all 200 validation intervals (validation_tracks.json)
|
| 26 |
+
and all 2,697 development perturbations across 13 evaluations (validation_variants.json). These are
|
| 27 |
+
scored by the unmodified verifier tools. The checkpoint is deliberately undertrained, its splicing
|
| 28 |
+
head lacks a local base-resolution encoder, and variant effects should not be used clinically.
|
| 29 |
+
The supplied 215M baseline has validation family-mean Pearson 0.302; this checkpoint is a pipeline
|
| 30 |
+
milestone, not a claim to improve that baseline.
|
| 31 |
+
|
| 32 |
+
## Measured validation results
|
| 33 |
+
|
| 34 |
+
Family-mean Pearson: **0.004141** on 200 validation intervals.
|
| 35 |
+
|
| 36 |
+
| Family | Pearson |
|
| 37 |
+
|---|---:|
|
| 38 |
+
| atac | 0.004916 |
|
| 39 |
+
| dnase | -0.000656 |
|
| 40 |
+
| procap | 0.047810 |
|
| 41 |
+
| cage | -0.000640 |
|
| 42 |
+
| rna_seq | -0.002504 |
|
| 43 |
+
| chip_tf | 0.002254 |
|
| 44 |
+
| chip_histone | 0.000647 |
|
| 45 |
+
| splice_sites | 0.000067 |
|
| 46 |
+
| splice_usage | -0.000982 |
|
| 47 |
+
| junctions | 0.000000 |
|
| 48 |
+
| contact_maps | -0.005367 |
|
| 49 |
+
|
| 50 |
+
| Development evaluation | Metric | Model | Published anchors on the same rows |
|
| 51 |
+
|---|---|---:|---|
|
| 52 |
+
| eqtl_sign | auroc | 0.4941 | AlphaGenome: 0.8264 |
|
| 53 |
+
| eqtl_causality | auroc | 0.6542 | AlphaGenome: 0.8325 |
|
| 54 |
+
| eqtl_coefficient | spearman | -0.0486 | AlphaGenome: 0.4134 |
|
| 55 |
+
| sqtl_causality | auprc | 0.8434 | AlphaGenome: 0.8447 |
|
| 56 |
+
| clinvar_noncoding | auprc | 0.1946 | AlphaGenome: 0.9410 |
|
| 57 |
+
| clinvar_splice_region | auprc | 0.1778 | AlphaGenome: 0.7225 |
|
| 58 |
+
| clinvar_missense | auprc | 0.2330 | AlphaGenome: 0.3738 |
|
| 59 |
+
| mfass | auprc | 0.2177 | AlphaGenome: 0.7343 |
|
| 60 |
+
| caqtl | auprc | 0.1637 | AlphaGenome: 0.8076 |
|
| 61 |
+
| bqtl_spi1 | auprc | 0.2077 | AlphaGenome: 0.8167 |
|
| 62 |
+
| enhancer_gene | auprc | 0.4133 | AlphaGenome: 0.9594 |
|
| 63 |
+
| traitgym_mendelian | auprc | 0.2092 | Borzoi_L2_L2.plus.all: 0.5026; Enformer_L2_L2.plus.all: 0.5453; CADD.plus.RawScore: 0.7189; GPN-MSA_absLLR.plus.score: 0.6729 |
|
| 64 |
+
| traitgym_complex | auprc | 0.2001 | Borzoi_L2_L2.plus.all: 0.2945; Enformer_L2_L2.plus.all: 0.2692; CADD.plus.RawScore: 0.4134; GPN-MSA_absLLR.plus.score: 0.4214 |
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/infer.sh
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
[[ $# == 2 ]] || { echo "usage: infer.sh INPUT_ROOT OUTPUT_ROOT" >&2; exit 2; }
|
| 4 |
+
package_dir=$(cd "$(dirname "$0")" && pwd)
|
| 5 |
+
runtime_dir=$(mktemp -d "${TMPDIR:-/tmp}/seqfunc-runtime.XXXXXXXX")
|
| 6 |
+
trap 'rm -rf "$runtime_dir"' EXIT
|
| 7 |
+
tar -xzf "$package_dir/runtime.tar.gz" -C "$runtime_dir"
|
| 8 |
+
unset PYTHONPATH
|
| 9 |
+
export PYTHONHOME="$runtime_dir" PYTHONNOUSERSITE=1 PYTHONDONTWRITEBYTECODE=1
|
| 10 |
+
export LD_LIBRARY_PATH="$runtime_dir/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
|
| 11 |
+
export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 NUMEXPR_NUM_THREADS=4
|
| 12 |
+
"$runtime_dir/bin/python" -s "$package_dir/predict.py" "$1" "$2" --checkpoint "$package_dir/last.pt"
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/package_manifest.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"parameters": 13218756,
|
| 3 |
+
"source_checkpoint_sha256": "a8d6d7e5a4852d7e869b05d30ed4086a1ed8f2c5711b8a8baaf909f8cccc63f8",
|
| 4 |
+
"files": {
|
| 5 |
+
"README.md": "325e8e0af474a1a5ed730515b06f61cc57aff5ed6148c951f5287783372e7de6",
|
| 6 |
+
"infer.sh": "ef810532b1e72b85fbe283e4f52c177bb70025977dbb2345d75837c9bbd51e37",
|
| 7 |
+
"last.pt": "fd99cef3f7bff9a57881cb645a717ae2812f4d5a2229bfd96f288a5cbbd024bc",
|
| 8 |
+
"perturb.py": "ba37a6f9f8b8eccb052903618bcb4c91d3f4cbed62dfe678ee362644dc80801e",
|
| 9 |
+
"perturb.sh": "113ec2383276a6e83fe1e4e8b0fa914f8d535d5dd0f5b2c34240140312dd5fb4",
|
| 10 |
+
"predict.py": "2725592456c55c188b22c376f0cb249e9f46b4ae1370d2226df7143da358a8b2",
|
| 11 |
+
"prediction_contract.py": "b11af8f7cff82b35afc6282be387358a48464b78bd1dfa44452dace26a5e0a83",
|
| 12 |
+
"reference/__init__.py": "45f3cf93f48859104e70bb58d717130dfd6521a45d2aba06b1a726afc0dc51dd",
|
| 13 |
+
"reference/alphagenome_50m/__init__.py": "a5a7e45d5940c3b201017c6322128e9f47efd37e1d29f717da2c1f787688eff9",
|
| 14 |
+
"reference/alphagenome_50m/alphagenome_50m.yaml": "3cac32e9f55e352dff78bb85ac892fdae1f9e412d9bba3e945750210c5252eee",
|
| 15 |
+
"reference/alphagenome_50m/dataset.py": "ad6670f742f4de9898064becc525d0aea98b402abe7b210bb1b26a9eee6402b9",
|
| 16 |
+
"reference/alphagenome_50m/layers.py": "26a116a72aa3f0e307a3606163547edbdecb7965f7fdcd96bc5f805cd21b3352",
|
| 17 |
+
"reference/alphagenome_50m/model.py": "713940fd2b335bf1ce16d1d76241a174f42c3ec15ebdf5c97c1e03f9cd691293",
|
| 18 |
+
"reference/alphagenome_50m/reference_large.yaml": "68084d299b39418034c6bbf71db174c3ffa68bbeea8779c1694e44ec71f3529c",
|
| 19 |
+
"reference/alphagenome_50m/run_ddp.sh": "96d35a24a4e6789311501fb98203807ac0c4429375c44d5c6671908270c93bb0",
|
| 20 |
+
"reference/alphagenome_50m/tiny_overfit.yaml": "f7a104c3929de0530a9a8f73f66d794cca595aefad8ef262e09ecbeb9cfce6de",
|
| 21 |
+
"reference/alphagenome_50m/train_eval.py": "2547c9adbdb51ad1acf796a548724cc7770eba90a755f4cb3b37d6f591adf6ec",
|
| 22 |
+
"runtime.tar.gz": "718da4c374e0c552b6e429b226c90b2fded5c900d95577d190d4df520aaf3901",
|
| 23 |
+
"validation_tracks.json": "73a44a7400dce3e367ed4aa3fb4fd4b4d14524acad6aaea26843fc89813d9519",
|
| 24 |
+
"validation_variants.json": "74ea2d8e1f2714cd73a6a71bdc5f302139075871e85b7a3100b349c9d9472c84"
|
| 25 |
+
}
|
| 26 |
+
}
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/perturb.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Predict both sequences of every perturbation (contract: perturbations/v1).
|
| 2 |
+
|
| 3 |
+
python perturb.py INPUT_ROOT OUTPUT_ROOT --checkpoint last.pt
|
| 4 |
+
|
| 5 |
+
INPUT_ROOT holds `public/perturbations.parquet` and `reference/GRCh38.p13.genome.fa` (in the
|
| 6 |
+
workspace, `/workspace/data` works too: the queries are then read from `variant_evals/public/`). Each row is a
|
| 7 |
+
1,048,576-bp window starting at `input_start` and an edit spanning [edit_start, edit_end) in genomic
|
| 8 |
+
0-based coordinates:
|
| 9 |
+
|
| 10 |
+
- `snv`: sequence A carries `allele_a` at edit_start, sequence B carries `allele_b` (both are written
|
| 11 |
+
explicitly; either may differ from the reference genome);
|
| 12 |
+
- `mask`: sequence A is the reference, sequence B has the interval replaced by N.
|
| 13 |
+
|
| 14 |
+
For each perturbation the output group `perturbations/p{index:06d}` holds `a/<family>` and
|
| 15 |
+
`b/<family>` for every family in `families`: dense families sliced to bins
|
| 16 |
+
[dense_bin_start, dense_bin_end) of the central target window, and `splice_sites` sliced to bp
|
| 17 |
+
[splice_start, splice_end). Values are the same quantities as predictions.zarr (asinh space for
|
| 18 |
+
dense tracks, splice-site scores for splice_sites).
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import argparse
|
| 24 |
+
import json
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
from numcodecs import Blosc
|
| 28 |
+
import numpy as np
|
| 29 |
+
import pandas as pd
|
| 30 |
+
import pysam
|
| 31 |
+
import torch
|
| 32 |
+
import zarr
|
| 33 |
+
|
| 34 |
+
from reference.alphagenome_50m.dataset import AlphaGenomeDataset
|
| 35 |
+
from reference.alphagenome_50m.model import CompactModel, ModelConfig
|
| 36 |
+
|
| 37 |
+
PERTURBATION_SCHEMA = "genome-sequence-to-function-perturbations/v1"
|
| 38 |
+
COMPRESSOR = Blosc(cname="zstd", clevel=3, shuffle=Blosc.BITSHUFFLE)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def sequences(fasta, row) -> tuple[str, str]:
|
| 42 |
+
length = fasta.get_reference_length(row.chrom)
|
| 43 |
+
start, end = int(row.input_start), int(row.input_start) + 1_048_576
|
| 44 |
+
sequence = fasta.fetch(row.chrom, max(0, start), min(length, end)).upper()
|
| 45 |
+
sequence = "N" * max(0, -start) + sequence + "N" * max(0, end - length)
|
| 46 |
+
lo, hi = int(row.edit_start) - start, int(row.edit_end) - start
|
| 47 |
+
if row.edit == "snv":
|
| 48 |
+
return sequence[:lo] + row.allele_a + sequence[hi:], sequence[:lo] + row.allele_b + sequence[hi:]
|
| 49 |
+
if row.edit == "mask":
|
| 50 |
+
return sequence, sequence[:lo] + "N" * (hi - lo) + sequence[hi:]
|
| 51 |
+
raise ValueError(f"unknown edit {row.edit!r}")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def main(input_root: Path, output_root: Path, checkpoint: Path, queries: Path | None = None) -> None:
|
| 55 |
+
payload = torch.load(checkpoint, map_location="cpu", weights_only=True)
|
| 56 |
+
config = ModelConfig(**payload["config"])
|
| 57 |
+
model = CompactModel(config)
|
| 58 |
+
model.load_state_dict(payload["model"], strict=True)
|
| 59 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 60 |
+
model.to(device).eval()
|
| 61 |
+
if queries is None:
|
| 62 |
+
queries = input_root / "public/perturbations.parquet"
|
| 63 |
+
if not queries.exists():
|
| 64 |
+
queries = input_root / "variant_evals/public/perturbations.parquet"
|
| 65 |
+
rows = pd.read_parquet(queries)
|
| 66 |
+
fasta = pysam.FastaFile(str(input_root / "reference/GRCh38.p13.genome.fa"))
|
| 67 |
+
output_root.mkdir(parents=True, exist_ok=True)
|
| 68 |
+
root = zarr.open_group(str(output_root / "perturbations.zarr"), mode="w")
|
| 69 |
+
target_start = (config.input_length - config.target_length) // 2
|
| 70 |
+
with torch.inference_mode():
|
| 71 |
+
for index, row in enumerate(rows.itertuples(index=False)):
|
| 72 |
+
pair = sequences(fasta, row)
|
| 73 |
+
dna = torch.from_numpy(np.stack([AlphaGenomeDataset._one_hot(s) for s in pair])).to(device)
|
| 74 |
+
trunk = model._trunk(dna)
|
| 75 |
+
group = root.create_group(f"perturbations/p{index:06d}")
|
| 76 |
+
features = None
|
| 77 |
+
for family in row.families:
|
| 78 |
+
if family == "splice_sites":
|
| 79 |
+
logits = model._splice_site_logits(trunk)[:, target_start:target_start + config.target_length]
|
| 80 |
+
values = logits[:, row.splice_start:row.splice_end]
|
| 81 |
+
else:
|
| 82 |
+
features = model._dense_features(trunk) if features is None else features
|
| 83 |
+
values = model.dense_heads[family](features)[:, row.dense_bin_start:row.dense_bin_end]
|
| 84 |
+
# float32: one variant's effect is often below float16 resolution (about 0.004 at
|
| 85 |
+
# asinh values of 4-8), so A and B would round to the same numbers.
|
| 86 |
+
values = values.float().cpu().numpy()
|
| 87 |
+
for side, array in zip("ab", values):
|
| 88 |
+
group.create_dataset(f"{side}/{family}", data=array, compressor=COMPRESSOR)
|
| 89 |
+
print(json.dumps({"event": "perturb", "done": index + 1, "total": len(rows)}), flush=True)
|
| 90 |
+
root.attrs.update({"schema": PERTURBATION_SCHEMA,
|
| 91 |
+
"perturbation_ids": rows.perturbation_id.astype(str).tolist()})
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
if __name__ == "__main__":
|
| 95 |
+
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 96 |
+
parser.add_argument("input_root", type=Path)
|
| 97 |
+
parser.add_argument("output_root", type=Path)
|
| 98 |
+
parser.add_argument("--checkpoint", type=Path, default=Path(__file__).resolve().parent / "last.pt")
|
| 99 |
+
parser.add_argument("--queries", type=Path, help="another query table, e.g. the development split")
|
| 100 |
+
args = parser.parse_args()
|
| 101 |
+
main(args.input_root, args.output_root, args.checkpoint, args.queries)
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/perturb.sh
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
[[ $# == 2 ]] || { echo "usage: perturb.sh INPUT_ROOT OUTPUT_ROOT" >&2; exit 2; }
|
| 4 |
+
package_dir=$(cd "$(dirname "$0")" && pwd)
|
| 5 |
+
runtime_dir=$(mktemp -d "${TMPDIR:-/tmp}/seqfunc-runtime.XXXXXXXX")
|
| 6 |
+
trap 'rm -rf "$runtime_dir"' EXIT
|
| 7 |
+
tar -xzf "$package_dir/runtime.tar.gz" -C "$runtime_dir"
|
| 8 |
+
unset PYTHONPATH
|
| 9 |
+
export PYTHONHOME="$runtime_dir" PYTHONNOUSERSITE=1 PYTHONDONTWRITEBYTECODE=1
|
| 10 |
+
export LD_LIBRARY_PATH="$runtime_dir/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
|
| 11 |
+
export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 NUMEXPR_NUM_THREADS=4
|
| 12 |
+
"$runtime_dir/bin/python" -s "$package_dir/perturb.py" "$1" "$2" --checkpoint "$package_dir/last.pt"
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/predict.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Stream the single benchmark model into the sharded prediction contract."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
from numcodecs import Blosc
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
import zarr
|
| 14 |
+
|
| 15 |
+
from prediction_contract import DENSE_TRACKS, MAX_JUNCTION_PAIRS, MAX_USAGE_SITES, PREDICTION_SCHEMA
|
| 16 |
+
from reference.alphagenome_50m.dataset import AlphaGenomeDataset
|
| 17 |
+
from reference.alphagenome_50m.model import CompactModel, ModelConfig
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
COMPRESSOR = Blosc(cname="zstd", clevel=7, shuffle=Blosc.BITSHUFFLE)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def main(input_root: Path, output_root: Path, checkpoint: Path, split: str = "test") -> None:
|
| 24 |
+
payload = torch.load(checkpoint, map_location="cpu", weights_only=True)
|
| 25 |
+
config = ModelConfig(**payload["config"])
|
| 26 |
+
model = CompactModel(config)
|
| 27 |
+
model.load_state_dict(payload["model"], strict=True)
|
| 28 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 29 |
+
model.to(device).eval()
|
| 30 |
+
dataset = AlphaGenomeDataset(input_root, split, include_targets=False)
|
| 31 |
+
model.set_junction_track_halves(dataset.junction_track_halves)
|
| 32 |
+
output_root.mkdir(parents=True, exist_ok=True)
|
| 33 |
+
root = zarr.open_group(str(output_root / "predictions.zarr"), mode="w")
|
| 34 |
+
ids = []
|
| 35 |
+
with torch.inference_mode():
|
| 36 |
+
for sample in dataset:
|
| 37 |
+
example_id = sample["example_id"]
|
| 38 |
+
dna = sample["dna"][None].to(device)
|
| 39 |
+
trunk = model._trunk(dna)
|
| 40 |
+
dense_features = model._dense_features(trunk)
|
| 41 |
+
group = root.create_group(f"examples/{example_id}")
|
| 42 |
+
for family in DENSE_TRACKS:
|
| 43 |
+
values = model.dense_heads[family](dense_features)[0]
|
| 44 |
+
group.create_dataset(family, data=values.cpu().numpy().astype(np.float16), compressor=COMPRESSOR)
|
| 45 |
+
|
| 46 |
+
all_site_logits = model._splice_site_logits(trunk)
|
| 47 |
+
target_start = (config.input_length - config.target_length) // 2
|
| 48 |
+
group.create_dataset(
|
| 49 |
+
"splice_sites",
|
| 50 |
+
data=all_site_logits[0, target_start:target_start + config.target_length].cpu().numpy().astype(np.float16),
|
| 51 |
+
chunks=(4096, 4), compressor=COMPRESSOR,
|
| 52 |
+
)
|
| 53 |
+
predicted_positions = model.select_junction_positions(all_site_logits)[0]
|
| 54 |
+
|
| 55 |
+
# Usage at the model's own predicted sites (v4 is sparse; unlisted hidden sites score 0).
|
| 56 |
+
usage_bins = model.splice_usage_head(dense_features)[0].float()
|
| 57 |
+
sites = predicted_positions.cpu().numpy().astype(np.int64).reshape(-1)
|
| 58 |
+
sites = np.unique(sites[(sites >= target_start) & (sites < target_start + config.target_length)]
|
| 59 |
+
- target_start)[:MAX_USAGE_SITES]
|
| 60 |
+
group.create_dataset("splice_usage_positions", data=sites.astype(np.int32), compressor=COMPRESSOR)
|
| 61 |
+
usage = usage_bins[torch.as_tensor(sites // 128, device=usage_bins.device)] if len(sites) \
|
| 62 |
+
else usage_bins[:0]
|
| 63 |
+
group.create_dataset("splice_usage", data=usage.cpu().numpy().astype(np.float16),
|
| 64 |
+
chunks=(1024, 734), compressor=COMPRESSOR)
|
| 65 |
+
|
| 66 |
+
# Junctions: score every donor x acceptor pair of each strand, keep the strongest pairs.
|
| 67 |
+
positions_batch = predicted_positions[None]
|
| 68 |
+
site_factors = model.junction_site_factors(trunk, positions_batch)
|
| 69 |
+
halves = model.junction_track_half
|
| 70 |
+
candidates = []
|
| 71 |
+
for row_start in range(0, 512, 128):
|
| 72 |
+
for column_start in range(0, 512, 128):
|
| 73 |
+
block = torch.cat([
|
| 74 |
+
model.junction_block(
|
| 75 |
+
trunk, positions_batch, row_start, row_start + 128,
|
| 76 |
+
column_start, column_start + 128, track_start,
|
| 77 |
+
min(track_start + 64, config.junction_tracks), site_factors,
|
| 78 |
+
)[0]
|
| 79 |
+
for track_start in range(0, config.junction_tracks, 64)
|
| 80 |
+
], dim=-1).float() # [128, 128, 734]
|
| 81 |
+
for half in (0, 1):
|
| 82 |
+
donors = predicted_positions[2 * half, row_start:row_start + 128]
|
| 83 |
+
acceptors = predicted_positions[2 * half + 1, column_start:column_start + 128]
|
| 84 |
+
valid = (donors[:, None] >= 0) & (acceptors[None, :] >= 0)
|
| 85 |
+
strength = block[..., halves == half].amax(dim=-1).masked_fill(~valid, -torch.inf)
|
| 86 |
+
keep = min(MAX_JUNCTION_PAIRS // 2, int(valid.sum()))
|
| 87 |
+
if not keep:
|
| 88 |
+
continue
|
| 89 |
+
best = strength.flatten().topk(keep)
|
| 90 |
+
rows, columns = best.indices // 128, best.indices % 128
|
| 91 |
+
candidates.append((best.values, torch.full_like(rows, half), donors[rows],
|
| 92 |
+
acceptors[columns], block[rows, columns]))
|
| 93 |
+
if candidates:
|
| 94 |
+
score, half, donor, acceptor, values = (torch.cat(x) for x in zip(*candidates))
|
| 95 |
+
order = score.topk(min(MAX_JUNCTION_PAIRS, len(score))).indices
|
| 96 |
+
half, donor, acceptor, values = half[order], donor[order], acceptor[order], values[order]
|
| 97 |
+
else:
|
| 98 |
+
half = donor = acceptor = torch.zeros(0, dtype=torch.long)
|
| 99 |
+
values = torch.zeros(0, config.junction_tracks)
|
| 100 |
+
group.create_dataset("junction_half", data=half.cpu().numpy().astype(np.int8), compressor=COMPRESSOR)
|
| 101 |
+
group.create_dataset("junction_donor", data=donor.cpu().numpy().astype(np.int32), compressor=COMPRESSOR)
|
| 102 |
+
group.create_dataset("junction_acceptor", data=acceptor.cpu().numpy().astype(np.int32), compressor=COMPRESSOR)
|
| 103 |
+
group.create_dataset("junctions", data=values.cpu().numpy().astype(np.float16),
|
| 104 |
+
chunks=(4096, 734), compressor=COMPRESSOR)
|
| 105 |
+
|
| 106 |
+
contact = trunk.reshape(
|
| 107 |
+
1, config.contact_bins, -1, config.hidden_dim
|
| 108 |
+
).mean(dim=2)
|
| 109 |
+
q, k = model.contact_q(contact), model.contact_k(contact)
|
| 110 |
+
row, column = model.contact_row, model.contact_column
|
| 111 |
+
contact_values = 0.5 * (q[:, row] * k[:, column] + q[:, column] * k[:, row])
|
| 112 |
+
group.create_dataset(
|
| 113 |
+
"contact_maps", data=contact_values[0].cpu().numpy().astype(np.float16),
|
| 114 |
+
chunks=(8192, 28), compressor=COMPRESSOR,
|
| 115 |
+
)
|
| 116 |
+
ids.append(example_id)
|
| 117 |
+
print(json.dumps({"event": "predict", "example": len(ids), "total": len(dataset)}), flush=True)
|
| 118 |
+
root.attrs.update({"schema": PREDICTION_SCHEMA, "example_ids": ids})
|
| 119 |
+
(output_root / "example_ids.json").write_text(json.dumps(ids) + "\n")
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
if __name__ == "__main__":
|
| 123 |
+
parser = argparse.ArgumentParser()
|
| 124 |
+
parser.add_argument("input_root", type=Path)
|
| 125 |
+
parser.add_argument("output_root", type=Path)
|
| 126 |
+
parser.add_argument("--checkpoint", type=Path, default=Path(__file__).resolve().parent / "last.pt")
|
| 127 |
+
parser.add_argument("--split", default="test", choices=("valid", "test"),
|
| 128 |
+
help="manifest to predict; the verifier uses test, local validation uses valid")
|
| 129 |
+
args = parser.parse_args()
|
| 130 |
+
main(args.input_root, args.output_root, args.checkpoint, args.split)
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/prediction_contract.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Public prediction shapes; no trusted splice coordinates are exposed."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
DENSE_TRACKS = {
|
| 6 |
+
"atac": 167,
|
| 7 |
+
"dnase": 305,
|
| 8 |
+
"procap": 12,
|
| 9 |
+
"cage": 546,
|
| 10 |
+
"rna_seq": 667,
|
| 11 |
+
"chip_tf": 1_617,
|
| 12 |
+
"chip_histone": 1_116,
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
PREDICTION_SCHEMA = "genome-sequence-to-function-predictions/v4"
|
| 16 |
+
MAX_USAGE_SITES = 4_096
|
| 17 |
+
MAX_JUNCTION_PAIRS = 16_384
|
| 18 |
+
# Fixed-shape arrays per example; splice usage and junctions are sparse (see contract.md).
|
| 19 |
+
FIXED_SHAPES = {
|
| 20 |
+
**{name: (1_536, tracks) for name, tracks in DENSE_TRACKS.items()},
|
| 21 |
+
"splice_sites": (196_608, 4),
|
| 22 |
+
"contact_maps": (131_328, 28),
|
| 23 |
+
}
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""The reference model of the alphagenome-reference baseline."""
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/alphagenome_50m/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compact 1-Mb, eleven-family AlphaGenome reference model."""
|
| 2 |
+
|
| 3 |
+
from .model import CompactModel, ModelConfig, count_parameters
|
| 4 |
+
|
| 5 |
+
__all__ = ["CompactModel", "ModelConfig", "count_parameters"]
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/alphagenome_50m/alphagenome_50m.yaml
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
input_length: 1048576
|
| 2 |
+
target_length: 196608
|
| 3 |
+
dense_bin_size: 128
|
| 4 |
+
trunk_bin_size: 1024
|
| 5 |
+
contact_bin_size: 2048
|
| 6 |
+
stem_stride: 8
|
| 7 |
+
encoder_width: 32
|
| 8 |
+
channel_growth: 32
|
| 9 |
+
num_downsampling_blocks: 7
|
| 10 |
+
conv_kernel_size: 5
|
| 11 |
+
dna_kernel_size: 15
|
| 12 |
+
hidden_dim: 384
|
| 13 |
+
num_sequence_blocks: 6
|
| 14 |
+
num_attention_heads: 6
|
| 15 |
+
attention_head_dim: 64
|
| 16 |
+
mlp_expansion: 4.0
|
| 17 |
+
dropout: 0.0
|
| 18 |
+
head_hidden_size: 256
|
| 19 |
+
junction_rank: 32
|
| 20 |
+
splice_usage_tracks: 734
|
| 21 |
+
junction_tracks: 734
|
| 22 |
+
contact_tracks: 28
|
| 23 |
+
gradient_checkpointing: true
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/alphagenome_50m/dataset.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Streaming reader for the compact 1 Mb / eleven-family release."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections import OrderedDict
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import pysam
|
| 11 |
+
import torch
|
| 12 |
+
from torch.utils.data import Dataset
|
| 13 |
+
import zarr
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _open_part(path: Path):
|
| 17 |
+
if str(path).endswith(".zarr.zip"):
|
| 18 |
+
store = zarr.ZipStore(str(path), mode="r")
|
| 19 |
+
try:
|
| 20 |
+
return zarr.open_group(store=store, mode="r"), store
|
| 21 |
+
except BaseException:
|
| 22 |
+
store.close()
|
| 23 |
+
raise
|
| 24 |
+
return zarr.open_group(str(path), mode="r"), None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
DENSE_FAMILIES = (
|
| 28 |
+
"atac",
|
| 29 |
+
"dnase",
|
| 30 |
+
"procap",
|
| 31 |
+
"cage",
|
| 32 |
+
"rna_seq",
|
| 33 |
+
"chip_tf",
|
| 34 |
+
"chip_histone",
|
| 35 |
+
)
|
| 36 |
+
def normalize_splice_positions(value) -> np.ndarray:
|
| 37 |
+
"""Normalize Arrow's nested-list representation to the public [4, 512] array."""
|
| 38 |
+
|
| 39 |
+
outer = np.asarray(value, dtype=object).reshape(-1).tolist()
|
| 40 |
+
positions = np.stack([np.asarray(item, dtype=np.int64) for item in outer])
|
| 41 |
+
if positions.shape != (4, 512):
|
| 42 |
+
raise ValueError(f"splice_site_positions must have shape (4, 512), got {positions.shape}")
|
| 43 |
+
return positions
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class AlphaGenomeDataset(Dataset):
|
| 47 |
+
"""Resolve frozen coordinates to reference DNA and one Zarr example group."""
|
| 48 |
+
|
| 49 |
+
def __init__(
|
| 50 |
+
self,
|
| 51 |
+
data_root: str | Path,
|
| 52 |
+
split: str,
|
| 53 |
+
*,
|
| 54 |
+
max_open_parts: int = 8,
|
| 55 |
+
include_targets: bool = True,
|
| 56 |
+
) -> None:
|
| 57 |
+
self.root = Path(data_root)
|
| 58 |
+
self.split = split
|
| 59 |
+
manifest = self.root / "public" / f"{split}.parquet"
|
| 60 |
+
if not manifest.is_file():
|
| 61 |
+
raise FileNotFoundError(f"Missing materialized manifest: {manifest}")
|
| 62 |
+
self.rows = pd.read_parquet(manifest).reset_index(drop=True)
|
| 63 |
+
junction_tracks = pd.read_parquet(self.root / "public/junction_tracks.parquet")
|
| 64 |
+
junction_tracks = junction_tracks.sort_values("tensor_index")
|
| 65 |
+
self.junction_track_halves = torch.from_numpy(
|
| 66 |
+
junction_tracks.junction_channel_half.to_numpy(np.int64)
|
| 67 |
+
)
|
| 68 |
+
if include_targets:
|
| 69 |
+
labels_path = self.root / "labels" / f"{split}.parquet"
|
| 70 |
+
if not labels_path.is_file():
|
| 71 |
+
raise FileNotFoundError(f"Missing trusted labels manifest: {labels_path}")
|
| 72 |
+
labels = pd.read_parquet(labels_path).reset_index(drop=True)
|
| 73 |
+
if self.rows.example_id.astype(str).tolist() != labels.example_id.astype(str).tolist():
|
| 74 |
+
raise ValueError("public and labels manifests have different IDs/order")
|
| 75 |
+
self.rows = self.rows.merge(labels, on="example_id", validate="one_to_one", sort=False)
|
| 76 |
+
self.fasta_path = self.root / "reference" / "GRCh38.p13.genome.fa"
|
| 77 |
+
self.max_open_parts = max_open_parts
|
| 78 |
+
self.include_targets = include_targets
|
| 79 |
+
self._fasta = None
|
| 80 |
+
self._parts: OrderedDict[str, tuple[zarr.Group, object | None]] = OrderedDict()
|
| 81 |
+
|
| 82 |
+
def __len__(self) -> int:
|
| 83 |
+
return len(self.rows)
|
| 84 |
+
|
| 85 |
+
def _reference(self):
|
| 86 |
+
if self._fasta is None:
|
| 87 |
+
self._fasta = pysam.FastaFile(str(self.fasta_path))
|
| 88 |
+
return self._fasta
|
| 89 |
+
|
| 90 |
+
def _part(self, relative: str):
|
| 91 |
+
if relative in self._parts:
|
| 92 |
+
opened = self._parts.pop(relative)
|
| 93 |
+
self._parts[relative] = opened
|
| 94 |
+
return opened[0]
|
| 95 |
+
group, store = _open_part(self.root / relative)
|
| 96 |
+
if len(self._parts) >= self.max_open_parts:
|
| 97 |
+
_, (_, old_store) = self._parts.popitem(last=False)
|
| 98 |
+
if old_store is not None:
|
| 99 |
+
old_store.close()
|
| 100 |
+
self._parts[relative] = (group, store)
|
| 101 |
+
return group
|
| 102 |
+
|
| 103 |
+
@staticmethod
|
| 104 |
+
def _one_hot(sequence: str) -> np.ndarray:
|
| 105 |
+
encoded = np.frombuffer(sequence.upper().encode("ascii"), dtype=np.uint8)
|
| 106 |
+
output = np.zeros((len(encoded), 4), dtype=np.float32)
|
| 107 |
+
for index, letter in enumerate(b"ACGT"):
|
| 108 |
+
output[:, index] = encoded == letter
|
| 109 |
+
return output
|
| 110 |
+
|
| 111 |
+
def _sequence(self, row) -> tuple[np.ndarray, np.ndarray]:
|
| 112 |
+
reference = self._reference()
|
| 113 |
+
chromosome_length = reference.get_reference_length(str(row.chromosome))
|
| 114 |
+
start, end = int(row.input_start), int(row.input_end)
|
| 115 |
+
clipped_start, clipped_end = max(0, start), min(chromosome_length, end)
|
| 116 |
+
sequence = reference.fetch(str(row.chromosome), clipped_start, clipped_end)
|
| 117 |
+
left, right = clipped_start - start, end - clipped_end
|
| 118 |
+
if left or right:
|
| 119 |
+
sequence = "N" * left + sequence + "N" * right
|
| 120 |
+
valid = np.ones(end - start, dtype=bool)
|
| 121 |
+
if left:
|
| 122 |
+
valid[:left] = False
|
| 123 |
+
if right:
|
| 124 |
+
valid[-right:] = False
|
| 125 |
+
return self._one_hot(sequence), valid
|
| 126 |
+
|
| 127 |
+
@staticmethod
|
| 128 |
+
def _decode(example, name: str, *, asinh: bool) -> np.ndarray:
|
| 129 |
+
"""Train targets may be stored as 8-bit codes with per-track ranges; they are decoded
|
| 130 |
+
here, one example at a time, so the release stays compressed on disk."""
|
| 131 |
+
array = example[name]
|
| 132 |
+
if array.dtype != np.uint8:
|
| 133 |
+
return np.asarray(array, dtype=np.float32)
|
| 134 |
+
lo = np.asarray(example[f"{name}_lo"], dtype=np.float32)
|
| 135 |
+
hi = np.asarray(example[f"{name}_hi"], dtype=np.float32)
|
| 136 |
+
x = lo + np.asarray(array, dtype=np.float32) * ((hi - lo) / 255.0)
|
| 137 |
+
return np.sinh(x) if asinh else x
|
| 138 |
+
|
| 139 |
+
@staticmethod
|
| 140 |
+
def _dense_target(example, family: str) -> dict[str, torch.Tensor]:
|
| 141 |
+
values = AlphaGenomeDataset._decode(example, f"{family}/values", asinh=True)
|
| 142 |
+
mask = np.asarray(example[f"{family}/mask"], dtype=bool)
|
| 143 |
+
if mask.ndim == 1:
|
| 144 |
+
mask = np.broadcast_to(mask[None, :], values.shape).copy()
|
| 145 |
+
return {
|
| 146 |
+
"values": torch.from_numpy(values),
|
| 147 |
+
"mask": torch.from_numpy(mask),
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
def __getitem__(self, item: int):
|
| 151 |
+
row = self.rows.iloc[item]
|
| 152 |
+
dna, input_mask = self._sequence(row)
|
| 153 |
+
result = {
|
| 154 |
+
"example_id": str(row.example_id),
|
| 155 |
+
"dna": torch.from_numpy(dna),
|
| 156 |
+
"input_mask": torch.from_numpy(input_mask),
|
| 157 |
+
"junction_track_halves": self.junction_track_halves,
|
| 158 |
+
}
|
| 159 |
+
if not self.include_targets:
|
| 160 |
+
return result
|
| 161 |
+
|
| 162 |
+
part = self._part(str(row.target_shard))
|
| 163 |
+
example = part[str(row.target_group)]
|
| 164 |
+
result["dense"] = {
|
| 165 |
+
family: self._dense_target(example, family) for family in DENSE_FAMILIES
|
| 166 |
+
}
|
| 167 |
+
result["splice_sites"] = torch.from_numpy(
|
| 168 |
+
np.asarray(example["splice_sites/values"], dtype=np.float32)
|
| 169 |
+
)
|
| 170 |
+
result["splice_usage"] = {
|
| 171 |
+
"positions": torch.from_numpy(
|
| 172 |
+
np.asarray(example["splice_site_usage/positions"], dtype=np.int64)
|
| 173 |
+
),
|
| 174 |
+
"values": torch.from_numpy(
|
| 175 |
+
np.asarray(example["splice_site_usage/values"], dtype=np.float32)
|
| 176 |
+
),
|
| 177 |
+
"mask": torch.from_numpy(
|
| 178 |
+
np.asarray(example["splice_site_usage/mask"], dtype=bool)
|
| 179 |
+
),
|
| 180 |
+
}
|
| 181 |
+
result["usage_positions"] = result["splice_usage"]["positions"]
|
| 182 |
+
result["junctions"] = {
|
| 183 |
+
name: torch.from_numpy(
|
| 184 |
+
np.asarray(
|
| 185 |
+
example[f"splice_junctions/{name}"],
|
| 186 |
+
dtype=np.float32 if name == "value" else np.int64,
|
| 187 |
+
)
|
| 188 |
+
)
|
| 189 |
+
for name in ("row", "column", "track", "value")
|
| 190 |
+
}
|
| 191 |
+
result["junctions"]["site_positions"] = torch.from_numpy(
|
| 192 |
+
np.asarray(example["splice_junctions/site_positions"], dtype=np.int64)
|
| 193 |
+
)
|
| 194 |
+
site_positions = normalize_splice_positions(row.splice_site_positions)
|
| 195 |
+
result["site_positions"] = torch.from_numpy(site_positions)
|
| 196 |
+
if not torch.equal(result["junctions"]["site_positions"], result["site_positions"]):
|
| 197 |
+
raise ValueError(f"public/private splice positions differ for {row.example_id}")
|
| 198 |
+
scoring_path = self.root / "scoring" / self.split / f"part-{item:06d}.parquet"
|
| 199 |
+
scoring = pd.read_parquet(scoring_path)
|
| 200 |
+
if not (scoring.example_id.astype(str) == str(row.example_id)).all():
|
| 201 |
+
raise ValueError(f"scoring part ID differs for {row.example_id}")
|
| 202 |
+
result["junction_scoring"] = {
|
| 203 |
+
"donor_position": torch.from_numpy(
|
| 204 |
+
scoring.donor_position.to_numpy(np.int64)
|
| 205 |
+
),
|
| 206 |
+
"acceptor_position": torch.from_numpy(
|
| 207 |
+
scoring.acceptor_position.to_numpy(np.int64)
|
| 208 |
+
),
|
| 209 |
+
"track": torch.from_numpy(scoring.track.to_numpy(np.int64)),
|
| 210 |
+
"target_value": torch.from_numpy(
|
| 211 |
+
scoring.target_value.to_numpy(np.float32)
|
| 212 |
+
),
|
| 213 |
+
"valid": torch.from_numpy(scoring.valid.to_numpy(bool)),
|
| 214 |
+
}
|
| 215 |
+
result["contact_maps"] = torch.from_numpy(
|
| 216 |
+
self._decode(example, "contact_maps/upper_triangle", asinh=False)
|
| 217 |
+
)
|
| 218 |
+
result["contact_map_mask"] = torch.from_numpy(
|
| 219 |
+
np.asarray(example["contact_maps/mask"], dtype=bool)
|
| 220 |
+
)
|
| 221 |
+
return result
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def single_example_collate(items):
|
| 225 |
+
"""Keep variable-size event tensors intact; the reference currently trains at batch one."""
|
| 226 |
+
|
| 227 |
+
if len(items) != 1:
|
| 228 |
+
raise ValueError("The compact event loader currently requires batch_size=1")
|
| 229 |
+
return items[0]
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/alphagenome_50m/layers.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared neural-network layers for the single compact AlphaGenome model."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch import Tensor, nn
|
| 9 |
+
from torch.nn import functional as F
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ChannelRMSNorm(nn.Module):
|
| 13 |
+
def __init__(self, channels: int, eps: float = 1e-6):
|
| 14 |
+
super().__init__()
|
| 15 |
+
self.weight = nn.Parameter(torch.ones(channels))
|
| 16 |
+
self.eps = eps
|
| 17 |
+
|
| 18 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 19 |
+
variance = x.float().square().mean(dim=1, keepdim=True)
|
| 20 |
+
normalized = x * torch.rsqrt(variance + self.eps).to(x.dtype)
|
| 21 |
+
return normalized * self.weight[None, :, None].to(x.dtype)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class StandardizedConv1d(nn.Conv1d):
|
| 25 |
+
def __init__(self, in_channels: int, out_channels: int, kernel_size: int):
|
| 26 |
+
super().__init__(in_channels, out_channels, kernel_size, padding="same", bias=True)
|
| 27 |
+
self.scale = nn.Parameter(torch.ones(out_channels))
|
| 28 |
+
nn.init.trunc_normal_(self.weight, std=1.0 / math.sqrt(in_channels * kernel_size))
|
| 29 |
+
nn.init.trunc_normal_(self.bias, std=1e-4)
|
| 30 |
+
|
| 31 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 32 |
+
centered = self.weight - self.weight.mean(dim=(1, 2), keepdim=True)
|
| 33 |
+
variance = centered.float().square().mean(dim=(1, 2), keepdim=True)
|
| 34 |
+
fan_in = self.weight.shape[1] * self.weight.shape[2]
|
| 35 |
+
multiplier = self.scale[:, None, None] * torch.rsqrt(
|
| 36 |
+
(fan_in * variance).clamp_min(1e-4)
|
| 37 |
+
).to(self.weight.dtype)
|
| 38 |
+
return F.conv1d(x, centered * multiplier, self.bias, padding="same")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class ConvBlock(nn.Module):
|
| 42 |
+
def __init__(self, in_channels: int, out_channels: int, kernel_size: int):
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.norm = ChannelRMSNorm(in_channels)
|
| 45 |
+
self.conv = StandardizedConv1d(in_channels, out_channels, kernel_size)
|
| 46 |
+
|
| 47 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 48 |
+
return self.conv(F.gelu(self.norm(x), approximate="tanh"))
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _apply_rope(x: Tensor) -> Tensor:
|
| 52 |
+
rotary_dim = x.shape[-1] - x.shape[-1] % 2
|
| 53 |
+
if rotary_dim == 0:
|
| 54 |
+
return x
|
| 55 |
+
positions = torch.arange(x.shape[-2], device=x.device, dtype=torch.float32)
|
| 56 |
+
inverse_frequency = 1.0 / (
|
| 57 |
+
10_000 ** (
|
| 58 |
+
torch.arange(0, rotary_dim, 2, device=x.device, dtype=torch.float32)
|
| 59 |
+
/ rotary_dim
|
| 60 |
+
)
|
| 61 |
+
)
|
| 62 |
+
angles = torch.outer(positions, inverse_frequency)
|
| 63 |
+
cos = angles.cos()[None, None, :, :].to(x.dtype)
|
| 64 |
+
sin = angles.sin()[None, None, :, :].to(x.dtype)
|
| 65 |
+
even, odd = x[..., :rotary_dim:2], x[..., 1:rotary_dim:2]
|
| 66 |
+
rotated = torch.stack((even * cos - odd * sin, even * sin + odd * cos), dim=-1)
|
| 67 |
+
return torch.cat((rotated.flatten(-2), x[..., rotary_dim:]), dim=-1)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class MultiHeadAttention(nn.Module):
|
| 71 |
+
def __init__(self, config):
|
| 72 |
+
super().__init__()
|
| 73 |
+
self.num_heads = config.num_attention_heads
|
| 74 |
+
self.head_dim = config.attention_head_dim
|
| 75 |
+
inner_dim = self.num_heads * self.head_dim
|
| 76 |
+
self.norm = nn.RMSNorm(config.hidden_dim)
|
| 77 |
+
self.qkv = nn.Linear(config.hidden_dim, 3 * inner_dim, bias=False)
|
| 78 |
+
self.output = nn.Linear(inner_dim, config.hidden_dim)
|
| 79 |
+
self.dropout = config.dropout
|
| 80 |
+
nn.init.trunc_normal_(self.output.weight, std=1e-3)
|
| 81 |
+
nn.init.zeros_(self.output.bias)
|
| 82 |
+
|
| 83 |
+
def forward(self, x: Tensor, attention_bias: Tensor | None = None) -> Tensor:
|
| 84 |
+
batch, length, _ = x.shape
|
| 85 |
+
qkv = self.qkv(self.norm(x)).view(
|
| 86 |
+
batch, length, 3, self.num_heads, self.head_dim
|
| 87 |
+
)
|
| 88 |
+
q, k, value = qkv.unbind(dim=2)
|
| 89 |
+
attended = F.scaled_dot_product_attention(
|
| 90 |
+
_apply_rope(q.transpose(1, 2)),
|
| 91 |
+
_apply_rope(k.transpose(1, 2)),
|
| 92 |
+
value.transpose(1, 2),
|
| 93 |
+
attn_mask=attention_bias,
|
| 94 |
+
dropout_p=self.dropout if self.training else 0.0,
|
| 95 |
+
)
|
| 96 |
+
return self.output(attended.transpose(1, 2).reshape(batch, length, -1))
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class MLPBlock(nn.Module):
|
| 100 |
+
def __init__(self, config):
|
| 101 |
+
super().__init__()
|
| 102 |
+
expanded = int(config.hidden_dim * config.mlp_expansion)
|
| 103 |
+
self.norm = nn.RMSNorm(config.hidden_dim)
|
| 104 |
+
self.input = nn.Linear(config.hidden_dim, expanded)
|
| 105 |
+
self.output = nn.Linear(expanded, config.hidden_dim)
|
| 106 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 107 |
+
nn.init.trunc_normal_(self.output.weight, std=1e-3)
|
| 108 |
+
nn.init.zeros_(self.output.bias)
|
| 109 |
+
|
| 110 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 111 |
+
return self.dropout(
|
| 112 |
+
self.output(F.gelu(self.input(self.norm(x)), approximate="tanh"))
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class SequenceBlock(nn.Module):
|
| 117 |
+
def __init__(self, config):
|
| 118 |
+
super().__init__()
|
| 119 |
+
self.attention = MultiHeadAttention(config)
|
| 120 |
+
self.mlp = MLPBlock(config)
|
| 121 |
+
|
| 122 |
+
def forward(self, x: Tensor, attention_bias: Tensor | None = None) -> Tensor:
|
| 123 |
+
x = x + self.attention(x, attention_bias)
|
| 124 |
+
return x + self.mlp(x)
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/alphagenome_50m/model.py
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Affordable multi-resolution baseline for the compact AlphaGenome task."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import asdict, dataclass, fields
|
| 6 |
+
import math
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any, Iterable
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from torch import Tensor, nn
|
| 12 |
+
from torch.nn import functional as F
|
| 13 |
+
from torch.utils.checkpoint import checkpoint
|
| 14 |
+
import yaml
|
| 15 |
+
|
| 16 |
+
from .layers import ConvBlock, SequenceBlock
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
DENSE_TRACKS = {
|
| 20 |
+
"atac": 167,
|
| 21 |
+
"dnase": 305,
|
| 22 |
+
"procap": 12,
|
| 23 |
+
"cage": 546,
|
| 24 |
+
"rna_seq": 667,
|
| 25 |
+
"chip_tf": 1_617,
|
| 26 |
+
"chip_histone": 1_116,
|
| 27 |
+
}
|
| 28 |
+
ALL_FAMILIES = (*DENSE_TRACKS, "splice_sites", "splice_usage", "junctions", "contact_maps")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass(frozen=True)
|
| 32 |
+
class ModelConfig:
|
| 33 |
+
input_length: int = 1_048_576
|
| 34 |
+
target_length: int = 196_608
|
| 35 |
+
dense_bin_size: int = 128
|
| 36 |
+
trunk_bin_size: int = 1_024
|
| 37 |
+
contact_bin_size: int = 2_048
|
| 38 |
+
stem_stride: int = 8
|
| 39 |
+
encoder_width: int = 32
|
| 40 |
+
channel_growth: int = 32
|
| 41 |
+
num_downsampling_blocks: int = 7
|
| 42 |
+
conv_kernel_size: int = 5
|
| 43 |
+
dna_kernel_size: int = 15
|
| 44 |
+
hidden_dim: int = 384
|
| 45 |
+
num_sequence_blocks: int = 6
|
| 46 |
+
num_attention_heads: int = 6
|
| 47 |
+
attention_head_dim: int = 64
|
| 48 |
+
mlp_expansion: float = 4.0
|
| 49 |
+
dropout: float = 0.0
|
| 50 |
+
head_hidden_size: int = 256
|
| 51 |
+
junction_rank: int = 32
|
| 52 |
+
splice_usage_tracks: int = 734
|
| 53 |
+
junction_tracks: int = 734
|
| 54 |
+
contact_tracks: int = 28
|
| 55 |
+
gradient_checkpointing: bool = True
|
| 56 |
+
enable_pairwise: bool = False
|
| 57 |
+
pair_width: int = 32
|
| 58 |
+
pair_downsample: int = 16
|
| 59 |
+
pair_update_interval: int = 2
|
| 60 |
+
|
| 61 |
+
def __post_init__(self) -> None:
|
| 62 |
+
downsample = self.stem_stride * 2**self.num_downsampling_blocks
|
| 63 |
+
if downsample != self.trunk_bin_size:
|
| 64 |
+
raise ValueError("stem_stride * 2**num_downsampling_blocks must equal trunk_bin_size")
|
| 65 |
+
for length in (self.input_length, self.target_length):
|
| 66 |
+
if length % self.trunk_bin_size:
|
| 67 |
+
raise ValueError("input and target lengths must divide by trunk_bin_size")
|
| 68 |
+
if self.trunk_bin_size % self.dense_bin_size:
|
| 69 |
+
raise ValueError("trunk_bin_size must divide by dense_bin_size")
|
| 70 |
+
if self.input_length % self.contact_bin_size:
|
| 71 |
+
raise ValueError("input_length must divide by contact_bin_size")
|
| 72 |
+
if self.hidden_dim <= 0 or self.num_attention_heads <= 0:
|
| 73 |
+
raise ValueError("hidden dimensions and attention heads must be positive")
|
| 74 |
+
|
| 75 |
+
@property
|
| 76 |
+
def trunk_bins(self) -> int:
|
| 77 |
+
return self.input_length // self.trunk_bin_size
|
| 78 |
+
|
| 79 |
+
@property
|
| 80 |
+
def target_trunk_bins(self) -> int:
|
| 81 |
+
return self.target_length // self.trunk_bin_size
|
| 82 |
+
|
| 83 |
+
@property
|
| 84 |
+
def dense_bins(self) -> int:
|
| 85 |
+
return self.target_length // self.dense_bin_size
|
| 86 |
+
|
| 87 |
+
@property
|
| 88 |
+
def dense_upsample(self) -> int:
|
| 89 |
+
return self.trunk_bin_size // self.dense_bin_size
|
| 90 |
+
|
| 91 |
+
@property
|
| 92 |
+
def contact_bins(self) -> int:
|
| 93 |
+
return self.input_length // self.contact_bin_size
|
| 94 |
+
|
| 95 |
+
@property
|
| 96 |
+
def encoder_output_width(self) -> int:
|
| 97 |
+
return self.encoder_width + self.channel_growth * self.num_downsampling_blocks
|
| 98 |
+
|
| 99 |
+
@classmethod
|
| 100 |
+
def from_yaml(cls, path: str | Path) -> "ModelConfig":
|
| 101 |
+
values: dict[str, Any] = yaml.safe_load(Path(path).read_text()) or {}
|
| 102 |
+
known = {field.name for field in fields(cls)}
|
| 103 |
+
unknown = sorted(values.keys() - known)
|
| 104 |
+
if unknown:
|
| 105 |
+
raise ValueError(f"Unknown model configuration keys: {unknown}")
|
| 106 |
+
return cls(**values)
|
| 107 |
+
|
| 108 |
+
def to_dict(self) -> dict[str, Any]:
|
| 109 |
+
return asdict(self)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class SequenceEncoder(nn.Module):
|
| 113 |
+
def __init__(self, config: ModelConfig):
|
| 114 |
+
super().__init__()
|
| 115 |
+
self.stem = nn.Conv1d(
|
| 116 |
+
4,
|
| 117 |
+
config.encoder_width,
|
| 118 |
+
config.dna_kernel_size,
|
| 119 |
+
stride=config.stem_stride,
|
| 120 |
+
padding=config.dna_kernel_size // 2,
|
| 121 |
+
)
|
| 122 |
+
blocks = []
|
| 123 |
+
width = config.encoder_width
|
| 124 |
+
for _ in range(config.num_downsampling_blocks):
|
| 125 |
+
output_width = width + config.channel_growth
|
| 126 |
+
blocks.append(ConvBlock(width, output_width, config.conv_kernel_size))
|
| 127 |
+
width = output_width
|
| 128 |
+
self.blocks = nn.ModuleList(blocks)
|
| 129 |
+
|
| 130 |
+
def forward(self, dna: Tensor) -> Tensor:
|
| 131 |
+
x = F.gelu(self.stem(dna.transpose(1, 2)), approximate="tanh")
|
| 132 |
+
for block in self.blocks:
|
| 133 |
+
x = F.max_pool1d(block(x), kernel_size=2, stride=2)
|
| 134 |
+
return x.transpose(1, 2)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class CompactModel(nn.Module):
|
| 138 |
+
"""One shared 1-kb trunk with representation-specific output heads."""
|
| 139 |
+
|
| 140 |
+
def __init__(self, config: ModelConfig | None = None):
|
| 141 |
+
super().__init__()
|
| 142 |
+
self.config = config or ModelConfig()
|
| 143 |
+
self.encoder = SequenceEncoder(self.config)
|
| 144 |
+
self.projection = nn.Linear(self.config.encoder_output_width, self.config.hidden_dim)
|
| 145 |
+
self.blocks = nn.ModuleList(
|
| 146 |
+
SequenceBlock(self.config) for _ in range(self.config.num_sequence_blocks)
|
| 147 |
+
)
|
| 148 |
+
self.final_norm = nn.RMSNorm(self.config.hidden_dim)
|
| 149 |
+
self.dense_decoder = nn.Sequential(
|
| 150 |
+
nn.RMSNorm(self.config.hidden_dim),
|
| 151 |
+
nn.Linear(self.config.hidden_dim, self.config.head_hidden_size),
|
| 152 |
+
nn.GELU(approximate="tanh"),
|
| 153 |
+
)
|
| 154 |
+
self.dense_heads = nn.ModuleDict(
|
| 155 |
+
{
|
| 156 |
+
family: nn.Linear(self.config.head_hidden_size, tracks)
|
| 157 |
+
for family, tracks in DENSE_TRACKS.items()
|
| 158 |
+
}
|
| 159 |
+
)
|
| 160 |
+
self.splice_site_head = nn.Linear(
|
| 161 |
+
self.config.head_hidden_size, self.config.dense_bin_size * 4
|
| 162 |
+
)
|
| 163 |
+
self.splice_usage_head = nn.Linear(
|
| 164 |
+
self.config.head_hidden_size, self.config.splice_usage_tracks
|
| 165 |
+
)
|
| 166 |
+
rank = self.config.junction_rank
|
| 167 |
+
self.junction_source = nn.Linear(self.config.head_hidden_size, rank)
|
| 168 |
+
self.junction_destination = nn.Linear(self.config.head_hidden_size, rank)
|
| 169 |
+
self.junction_track = nn.Embedding(self.config.junction_tracks, rank)
|
| 170 |
+
if self.config.junction_tracks % 2:
|
| 171 |
+
raise ValueError("junction tracks must split evenly into strand halves")
|
| 172 |
+
self.register_buffer(
|
| 173 |
+
"junction_track_half",
|
| 174 |
+
torch.arange(self.config.junction_tracks) // (self.config.junction_tracks // 2),
|
| 175 |
+
persistent=False,
|
| 176 |
+
)
|
| 177 |
+
self.contact_q = nn.Linear(self.config.hidden_dim, self.config.contact_tracks)
|
| 178 |
+
self.contact_k = nn.Linear(self.config.hidden_dim, self.config.contact_tracks)
|
| 179 |
+
row, column = torch.triu_indices(
|
| 180 |
+
self.config.contact_bins, self.config.contact_bins
|
| 181 |
+
)
|
| 182 |
+
self.register_buffer("contact_row", row, persistent=False)
|
| 183 |
+
self.register_buffer("contact_column", column, persistent=False)
|
| 184 |
+
|
| 185 |
+
def set_junction_track_halves(self, halves: Tensor) -> None:
|
| 186 |
+
halves = torch.as_tensor(halves, dtype=torch.long, device=self.junction_track_half.device)
|
| 187 |
+
if halves.shape != (self.config.junction_tracks,) or not torch.isin(
|
| 188 |
+
halves, torch.tensor([0, 1], device=halves.device)
|
| 189 |
+
).all():
|
| 190 |
+
raise ValueError("junction track halves must be a 734-element 0/1 mapping")
|
| 191 |
+
self.junction_track_half.copy_(halves)
|
| 192 |
+
|
| 193 |
+
def _trunk(self, dna: Tensor) -> Tensor:
|
| 194 |
+
if dna.ndim != 3 or dna.shape[1:] != (self.config.input_length, 4):
|
| 195 |
+
raise ValueError(
|
| 196 |
+
f"Expected DNA [B,{self.config.input_length},4], got {tuple(dna.shape)}"
|
| 197 |
+
)
|
| 198 |
+
x = self.projection(self.encoder(dna))
|
| 199 |
+
for block in self.blocks:
|
| 200 |
+
if self.config.gradient_checkpointing and self.training and x.requires_grad:
|
| 201 |
+
x = checkpoint(block, x, None, use_reentrant=False)
|
| 202 |
+
else:
|
| 203 |
+
x = block(x, None)
|
| 204 |
+
return self.final_norm(x)
|
| 205 |
+
|
| 206 |
+
def _dense_features(self, trunk: Tensor) -> Tensor:
|
| 207 |
+
start = (self.config.trunk_bins - self.config.target_trunk_bins) // 2
|
| 208 |
+
target = trunk[:, start : start + self.config.target_trunk_bins]
|
| 209 |
+
target = target.repeat_interleave(self.config.dense_upsample, dim=1)
|
| 210 |
+
return self.dense_decoder(target)
|
| 211 |
+
|
| 212 |
+
def _all_dense_features(self, trunk: Tensor) -> Tensor:
|
| 213 |
+
return self.dense_decoder(
|
| 214 |
+
trunk.repeat_interleave(self.config.dense_upsample, dim=1)
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
def _splice_site_logits(self, trunk: Tensor) -> Tensor:
|
| 218 |
+
logits = self.splice_site_head(self._all_dense_features(trunk))
|
| 219 |
+
return logits.view(len(trunk), self.config.input_length, 4).float()
|
| 220 |
+
|
| 221 |
+
@staticmethod
|
| 222 |
+
def select_junction_positions(site_logits: Tensor, limit: int = 512) -> Tensor:
|
| 223 |
+
"""Select each site type from model scores alone, then sort by coordinate.
|
| 224 |
+
|
| 225 |
+
This follows the four independent site classes in Google DeepMind's
|
| 226 |
+
AlphaGenome splicing implementation (pinned in docs/v3-author/PROTOCOL.md). Padding is
|
| 227 |
+
-1 when an input is shorter than ``limit``.
|
| 228 |
+
"""
|
| 229 |
+
count = min(limit, site_logits.shape[1])
|
| 230 |
+
selected = []
|
| 231 |
+
for site_type in range(4):
|
| 232 |
+
coordinates = torch.topk(site_logits[..., site_type], count, dim=1).indices
|
| 233 |
+
coordinates = coordinates.sort(dim=1).values
|
| 234 |
+
if count < limit:
|
| 235 |
+
coordinates = F.pad(coordinates, (0, limit - count), value=-1)
|
| 236 |
+
selected.append(coordinates)
|
| 237 |
+
return torch.stack(selected, dim=1)
|
| 238 |
+
|
| 239 |
+
@staticmethod
|
| 240 |
+
def _gather_bins(features: Tensor, positions: Tensor, bin_size: int) -> Tensor:
|
| 241 |
+
indices = torch.div(positions, bin_size, rounding_mode="floor")
|
| 242 |
+
indices = indices.clamp(0, features.shape[1] - 1)
|
| 243 |
+
return torch.gather(
|
| 244 |
+
features,
|
| 245 |
+
1,
|
| 246 |
+
indices[..., None].expand(-1, -1, features.shape[-1]),
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
def _junction_predictions(
|
| 250 |
+
self, trunk: Tensor, site_positions: Tensor, queries: Tensor
|
| 251 |
+
) -> Tensor:
|
| 252 |
+
row, column, track = queries.unbind(dim=-1)
|
| 253 |
+
half = self.junction_track_half[track]
|
| 254 |
+
batch = torch.arange(len(trunk), device=trunk.device)[:, None]
|
| 255 |
+
donor = site_positions[batch, 2 * half, row]
|
| 256 |
+
acceptor = site_positions[batch, 2 * half + 1, column]
|
| 257 |
+
source = self.dense_decoder(self._gather_bins(
|
| 258 |
+
trunk, donor.clamp(0, self.config.input_length - 1), self.config.trunk_bin_size
|
| 259 |
+
))
|
| 260 |
+
destination = self.dense_decoder(self._gather_bins(
|
| 261 |
+
trunk, acceptor.clamp(0, self.config.input_length - 1), self.config.trunk_bin_size
|
| 262 |
+
))
|
| 263 |
+
interaction = self.junction_source(source) * self.junction_destination(destination)
|
| 264 |
+
track_embedding = self.junction_track(track)
|
| 265 |
+
return (interaction * track_embedding).sum(dim=-1) / math.sqrt(
|
| 266 |
+
self.config.junction_rank
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
def junction_block(
|
| 270 |
+
self,
|
| 271 |
+
trunk: Tensor,
|
| 272 |
+
site_positions: Tensor,
|
| 273 |
+
row_start: int,
|
| 274 |
+
row_end: int,
|
| 275 |
+
column_start: int,
|
| 276 |
+
column_end: int,
|
| 277 |
+
track_start: int,
|
| 278 |
+
track_end: int,
|
| 279 |
+
site_factors: tuple[Tensor, Tensor] | None = None,
|
| 280 |
+
) -> Tensor:
|
| 281 |
+
"""Compute a bounded block of the full predicted-position junction cube."""
|
| 282 |
+
tracks = torch.arange(track_start, track_end, device=trunk.device)
|
| 283 |
+
halves = self.junction_track_half[tracks]
|
| 284 |
+
if site_factors is None:
|
| 285 |
+
site_factors = self.junction_site_factors(trunk, site_positions)
|
| 286 |
+
source_all, destination_all = site_factors
|
| 287 |
+
source = source_all[:, halves, row_start:row_end]
|
| 288 |
+
destination = destination_all[:, halves, column_start:column_end]
|
| 289 |
+
embedding = self.junction_track(tracks)[None, :, None, None, :]
|
| 290 |
+
values = (
|
| 291 |
+
source[:, :, :, None, :] * destination[:, :, None, :, :] * embedding
|
| 292 |
+
).sum(dim=-1) / math.sqrt(self.config.junction_rank)
|
| 293 |
+
return values.permute(0, 2, 3, 1).float()
|
| 294 |
+
|
| 295 |
+
def junction_site_factors(
|
| 296 |
+
self, trunk: Tensor, site_positions: Tensor
|
| 297 |
+
) -> tuple[Tensor, Tensor]:
|
| 298 |
+
"""Precompute the two strand-specific factors reused by all cube blocks."""
|
| 299 |
+
donor = torch.stack((site_positions[:, 0], site_positions[:, 2]), dim=1).clamp_min(0)
|
| 300 |
+
acceptor = torch.stack((site_positions[:, 1], site_positions[:, 3]), dim=1).clamp_min(0)
|
| 301 |
+
expanded = trunk[:, None].expand(-1, 2, -1, -1).reshape(
|
| 302 |
+
-1, trunk.shape[1], trunk.shape[2]
|
| 303 |
+
)
|
| 304 |
+
donor_features = self.dense_decoder(self._gather_bins(
|
| 305 |
+
expanded, donor.reshape(-1, donor.shape[-1]), self.config.trunk_bin_size,
|
| 306 |
+
)).reshape(len(trunk), 2, donor.shape[-1], -1)
|
| 307 |
+
acceptor_features = self.dense_decoder(self._gather_bins(
|
| 308 |
+
expanded, acceptor.reshape(-1, acceptor.shape[-1]), self.config.trunk_bin_size,
|
| 309 |
+
)).reshape(len(trunk), 2, acceptor.shape[-1], -1)
|
| 310 |
+
return self.junction_source(donor_features), self.junction_destination(acceptor_features)
|
| 311 |
+
|
| 312 |
+
def forward(
|
| 313 |
+
self,
|
| 314 |
+
dna: Tensor,
|
| 315 |
+
*,
|
| 316 |
+
families: Iterable[str] | None = None,
|
| 317 |
+
usage_positions: Tensor | None = None,
|
| 318 |
+
junction_site_positions: Tensor | None = None,
|
| 319 |
+
junction_queries: Tensor | None = None,
|
| 320 |
+
) -> dict[str, Tensor]:
|
| 321 |
+
requested = set(families or ALL_FAMILIES)
|
| 322 |
+
unknown = requested - set(ALL_FAMILIES)
|
| 323 |
+
if unknown:
|
| 324 |
+
raise ValueError(f"Unknown output families: {sorted(unknown)}")
|
| 325 |
+
trunk = self._trunk(dna)
|
| 326 |
+
needs_dense = bool(
|
| 327 |
+
requested.intersection((*DENSE_TRACKS, "splice_sites", "splice_usage", "junctions"))
|
| 328 |
+
)
|
| 329 |
+
features = self._dense_features(trunk) if needs_dense else None
|
| 330 |
+
outputs: dict[str, Tensor] = {}
|
| 331 |
+
for family in DENSE_TRACKS:
|
| 332 |
+
if family in requested:
|
| 333 |
+
outputs[family] = self.dense_heads[family](features).float()
|
| 334 |
+
if "splice_sites" in requested:
|
| 335 |
+
all_logits = self._splice_site_logits(trunk)
|
| 336 |
+
start = (self.config.input_length - self.config.target_length) // 2
|
| 337 |
+
outputs["splice_sites"] = all_logits[:, start:start + self.config.target_length]
|
| 338 |
+
if "splice_usage" in requested:
|
| 339 |
+
if usage_positions is None:
|
| 340 |
+
raise ValueError("splice_usage requires usage_positions")
|
| 341 |
+
gathered = self._gather_bins(
|
| 342 |
+
features, usage_positions, self.config.dense_bin_size
|
| 343 |
+
)
|
| 344 |
+
outputs["splice_usage"] = self.splice_usage_head(gathered).float()
|
| 345 |
+
if "junctions" in requested:
|
| 346 |
+
if junction_site_positions is None or junction_queries is None:
|
| 347 |
+
raise ValueError("junctions require site positions and query triples")
|
| 348 |
+
outputs["junctions"] = self._junction_predictions(
|
| 349 |
+
trunk, junction_site_positions, junction_queries
|
| 350 |
+
).float()
|
| 351 |
+
if "contact_maps" in requested:
|
| 352 |
+
contact = trunk.reshape(
|
| 353 |
+
len(dna), self.config.contact_bins, -1, self.config.hidden_dim
|
| 354 |
+
).mean(dim=2)
|
| 355 |
+
q, k = self.contact_q(contact), self.contact_k(contact)
|
| 356 |
+
row, column = self.contact_row, self.contact_column
|
| 357 |
+
outputs["contact_maps"] = (
|
| 358 |
+
0.5
|
| 359 |
+
* (
|
| 360 |
+
q[:, row] * k[:, column]
|
| 361 |
+
+ q[:, column] * k[:, row]
|
| 362 |
+
)
|
| 363 |
+
).float()
|
| 364 |
+
return outputs
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def count_parameters(model: nn.Module) -> int:
|
| 368 |
+
return sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad)
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/alphagenome_50m/reference_large.yaml
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
input_length: 1048576
|
| 2 |
+
target_length: 196608
|
| 3 |
+
dense_bin_size: 128
|
| 4 |
+
trunk_bin_size: 1024
|
| 5 |
+
contact_bin_size: 2048
|
| 6 |
+
stem_stride: 8
|
| 7 |
+
encoder_width: 96
|
| 8 |
+
channel_growth: 96
|
| 9 |
+
num_downsampling_blocks: 7
|
| 10 |
+
conv_kernel_size: 5
|
| 11 |
+
dna_kernel_size: 15
|
| 12 |
+
hidden_dim: 1024
|
| 13 |
+
num_sequence_blocks: 16
|
| 14 |
+
num_attention_heads: 16
|
| 15 |
+
attention_head_dim: 64
|
| 16 |
+
mlp_expansion: 4.0
|
| 17 |
+
dropout: 0.0
|
| 18 |
+
head_hidden_size: 768
|
| 19 |
+
junction_rank: 32
|
| 20 |
+
splice_usage_tracks: 734
|
| 21 |
+
junction_tracks: 734
|
| 22 |
+
contact_tracks: 28
|
| 23 |
+
gradient_checkpointing: true
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/alphagenome_50m/run_ddp.sh
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# run_ddp.sh DATA_DIR OUTPUT_DIR CONFIG EPOCHS [GPUS=8] [WORKERS_PER_GPU=12]
|
| 3 |
+
# Train the reference on every train interval with one example per GPU per step, then score
|
| 4 |
+
# validation with the verifier's own scorer. Runs inside the task image (torch, torchrun).
|
| 5 |
+
set -Eeuo pipefail
|
| 6 |
+
DATA=$1; OUT=$2; CONFIG=$3; EPOCHS=$4; GPUS=${5:-8}; WORKERS=${6:-12}
|
| 7 |
+
BASELINE=$(cd "$(dirname "$0")/../.." && pwd)
|
| 8 |
+
mkdir -p "$OUT"
|
| 9 |
+
cd "$BASELINE"
|
| 10 |
+
# Loopback rendezvous: works offline, where --standalone cannot resolve the hostname.
|
| 11 |
+
torchrun --nnodes 1 --nproc-per-node "$GPUS" --master-addr 127.0.0.1 --master-port "${MASTER_PORT:-29511}" -m reference.alphagenome_50m.train_eval train \
|
| 12 |
+
--input "$DATA" --config "$CONFIG" --output "$OUT" --epochs "$EPOCHS" --workers "$WORKERS" \
|
| 13 |
+
--log-every 200 --save-every 2000 2>&1 | tee -a "$OUT/train.log"
|
| 14 |
+
python predict.py "$DATA" "$OUT/valid-pred" --checkpoint "$OUT/last.pt" --split valid
|
| 15 |
+
python /workspace/evaluation/score.py --predictions "$OUT/valid-pred/predictions.zarr" \
|
| 16 |
+
--labels "$DATA" --split valid --output "$OUT/valid-score"
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/alphagenome_50m/tiny_overfit.yaml
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Keep the frozen 1-Mb input and every output track; shrink only learned widths.
|
| 2 |
+
input_length: 1048576
|
| 3 |
+
target_length: 196608
|
| 4 |
+
dense_bin_size: 128
|
| 5 |
+
trunk_bin_size: 1024
|
| 6 |
+
contact_bin_size: 2048
|
| 7 |
+
stem_stride: 8
|
| 8 |
+
encoder_width: 8
|
| 9 |
+
channel_growth: 4
|
| 10 |
+
num_downsampling_blocks: 7
|
| 11 |
+
conv_kernel_size: 5
|
| 12 |
+
dna_kernel_size: 15
|
| 13 |
+
hidden_dim: 32
|
| 14 |
+
num_sequence_blocks: 1
|
| 15 |
+
num_attention_heads: 2
|
| 16 |
+
attention_head_dim: 16
|
| 17 |
+
mlp_expansion: 2.0
|
| 18 |
+
dropout: 0.0
|
| 19 |
+
head_hidden_size: 32
|
| 20 |
+
junction_rank: 8
|
| 21 |
+
splice_usage_tracks: 734
|
| 22 |
+
junction_tracks: 734
|
| 23 |
+
contact_tracks: 28
|
| 24 |
+
gradient_checkpointing: false
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/reference/alphagenome_50m/train_eval.py
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Train and stream-evaluate the <=50M compact AlphaGenome baseline."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
import math
|
| 9 |
+
import os
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import time
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import torch
|
| 15 |
+
from torch import Tensor
|
| 16 |
+
from torch.nn import functional as F
|
| 17 |
+
from torch.utils.data import DataLoader, Subset
|
| 18 |
+
|
| 19 |
+
from .dataset import (
|
| 20 |
+
AlphaGenomeDataset,
|
| 21 |
+
DENSE_FAMILIES,
|
| 22 |
+
single_example_collate,
|
| 23 |
+
)
|
| 24 |
+
from .model import (
|
| 25 |
+
ALL_FAMILIES,
|
| 26 |
+
CompactModel,
|
| 27 |
+
ModelConfig,
|
| 28 |
+
count_parameters,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
DEFAULT_CONFIG = Path(__file__).with_name("alphagenome_50m.yaml")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _device(name: str) -> torch.device:
|
| 36 |
+
if name == "auto":
|
| 37 |
+
name = "cuda" if torch.cuda.is_available() else "cpu"
|
| 38 |
+
if name == "cuda" and not torch.cuda.is_available():
|
| 39 |
+
raise RuntimeError("--device cuda requested but CUDA is unavailable")
|
| 40 |
+
return torch.device(name)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _autocast(device: torch.device):
|
| 44 |
+
enabled = device.type == "cuda"
|
| 45 |
+
dtype = torch.bfloat16 if enabled and torch.cuda.is_bf16_supported() else torch.float16
|
| 46 |
+
return torch.autocast(device_type=device.type, dtype=dtype, enabled=enabled)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _distributed() -> tuple[int, int, int]:
|
| 50 |
+
"""(rank, local_rank, world_size) under torchrun; (0, 0, 1) otherwise."""
|
| 51 |
+
world = int(os.environ.get("WORLD_SIZE", "1"))
|
| 52 |
+
if world > 1 and not torch.distributed.is_initialized():
|
| 53 |
+
torch.distributed.init_process_group("nccl")
|
| 54 |
+
return int(os.environ.get("RANK", "0")), int(os.environ.get("LOCAL_RANK", "0")), world
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _loader(dataset, *, workers: int, shuffle: bool, sampler=None) -> DataLoader:
|
| 58 |
+
return DataLoader(
|
| 59 |
+
dataset,
|
| 60 |
+
batch_size=1,
|
| 61 |
+
shuffle=shuffle and sampler is None,
|
| 62 |
+
sampler=sampler,
|
| 63 |
+
num_workers=workers,
|
| 64 |
+
persistent_workers=workers > 0,
|
| 65 |
+
pin_memory=torch.cuda.is_available(),
|
| 66 |
+
collate_fn=single_example_collate,
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _to_device(value, device: torch.device):
|
| 71 |
+
if isinstance(value, Tensor):
|
| 72 |
+
return value.to(device, non_blocking=True)
|
| 73 |
+
if isinstance(value, dict):
|
| 74 |
+
return {key: _to_device(item, device) for key, item in value.items()}
|
| 75 |
+
return value
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _match_coordinate_queries(
|
| 79 |
+
scoring: dict[str, Tensor], positions: Tensor, track_halves: Tensor
|
| 80 |
+
) -> tuple[Tensor, Tensor, Tensor]:
|
| 81 |
+
"""Match trusted coordinate queries to typed position axes like the grader."""
|
| 82 |
+
device = positions.device
|
| 83 |
+
tracks = scoring["track"]
|
| 84 |
+
halves = track_halves[tracks]
|
| 85 |
+
queries = torch.zeros((len(tracks), 3), dtype=torch.int64, device=device)
|
| 86 |
+
queries[:, 2] = tracks
|
| 87 |
+
valid = scoring["valid"].clone()
|
| 88 |
+
missing = torch.ones(len(tracks), dtype=torch.bool, device=device)
|
| 89 |
+
position_rows = positions.detach().cpu().numpy()
|
| 90 |
+
halves_cpu = halves.detach().cpu().numpy()
|
| 91 |
+
donors_cpu = scoring["donor_position"].detach().cpu().numpy()
|
| 92 |
+
acceptors_cpu = scoring["acceptor_position"].detach().cpu().numpy()
|
| 93 |
+
valid_indices = np.flatnonzero(valid.detach().cpu().numpy())
|
| 94 |
+
lookups = [
|
| 95 |
+
{int(coordinate): index for index, coordinate in enumerate(axis) if coordinate >= 0}
|
| 96 |
+
for axis in position_rows
|
| 97 |
+
]
|
| 98 |
+
for index in valid_indices:
|
| 99 |
+
half = int(halves_cpu[index])
|
| 100 |
+
row = lookups[2 * half].get(int(donors_cpu[index]))
|
| 101 |
+
column = lookups[2 * half + 1].get(int(acceptors_cpu[index]))
|
| 102 |
+
if row is not None and column is not None:
|
| 103 |
+
queries[index, 0] = row
|
| 104 |
+
queries[index, 1] = column
|
| 105 |
+
missing[index] = False
|
| 106 |
+
return queries.unsqueeze(0), valid, missing
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _model_inputs(sample: dict) -> tuple[dict, Tensor, Tensor]:
|
| 110 |
+
queries, query_valid, missing = _match_coordinate_queries(
|
| 111 |
+
sample["junction_scoring"],
|
| 112 |
+
sample["site_positions"],
|
| 113 |
+
sample["junction_track_halves"],
|
| 114 |
+
)
|
| 115 |
+
if (query_valid & missing).any():
|
| 116 |
+
raise ValueError("trusted scoring coordinates do not match target positions")
|
| 117 |
+
junction_target = torch.asinh(
|
| 118 |
+
sample["junction_scoring"]["target_value"]
|
| 119 |
+
).unsqueeze(0)
|
| 120 |
+
return {
|
| 121 |
+
"dna": sample["dna"].unsqueeze(0),
|
| 122 |
+
"usage_positions": sample["usage_positions"].unsqueeze(0),
|
| 123 |
+
"junction_site_positions": sample["site_positions"].unsqueeze(0),
|
| 124 |
+
"junction_queries": queries,
|
| 125 |
+
}, junction_target, query_valid
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _losses(outputs: dict[str, Tensor], sample: dict, junction_target: Tensor,
|
| 129 |
+
junction_valid: Tensor) -> dict[str, Tensor]:
|
| 130 |
+
losses = {}
|
| 131 |
+
for family in DENSE_FAMILIES:
|
| 132 |
+
target = torch.asinh(sample["dense"][family]["values"]).unsqueeze(0)
|
| 133 |
+
mask = sample["dense"][family]["mask"].unsqueeze(0)
|
| 134 |
+
residual = torch.where(mask, outputs[family] - target, 0.0)
|
| 135 |
+
losses[family] = residual.square().sum() / mask.sum().clamp_min(1)
|
| 136 |
+
losses["splice_sites"] = F.binary_cross_entropy_with_logits(
|
| 137 |
+
outputs["splice_sites"], sample["splice_sites"].unsqueeze(0)
|
| 138 |
+
)
|
| 139 |
+
usage_target = torch.asinh(sample["splice_usage"]["values"]).unsqueeze(0)
|
| 140 |
+
usage_mask = sample["splice_usage"]["mask"].unsqueeze(0)
|
| 141 |
+
usage_residual = torch.where(usage_mask, outputs["splice_usage"] - usage_target, 0.0)
|
| 142 |
+
losses["splice_usage"] = usage_residual.square().sum() / usage_mask.sum().clamp_min(1)
|
| 143 |
+
junction_residual = outputs["junctions"][0] - junction_target[0]
|
| 144 |
+
losses["junctions"] = (
|
| 145 |
+
junction_residual[junction_valid].square().mean()
|
| 146 |
+
if junction_valid.any() else junction_residual.sum() * 0
|
| 147 |
+
)
|
| 148 |
+
contact_target = torch.asinh(sample["contact_maps"]).unsqueeze(0)
|
| 149 |
+
contact_mask = sample["contact_map_mask"].unsqueeze(0)
|
| 150 |
+
contact_residual = torch.where(
|
| 151 |
+
contact_mask, outputs["contact_maps"] - contact_target, 0.0
|
| 152 |
+
)
|
| 153 |
+
losses["contact_maps"] = contact_residual.square().sum() / contact_mask.sum().clamp_min(1)
|
| 154 |
+
losses["total"] = torch.stack([losses[name] for name in ALL_FAMILIES]).mean()
|
| 155 |
+
return losses
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _validation_inference(
|
| 159 |
+
model: CompactModel, sample: dict
|
| 160 |
+
) -> tuple[dict[str, Tensor], Tensor, Tensor, Tensor]:
|
| 161 |
+
"""Use the same predicted-position path as a formal v3 submission."""
|
| 162 |
+
trunk = model._trunk(sample["dna"].unsqueeze(0))
|
| 163 |
+
dense_features = model._dense_features(trunk)
|
| 164 |
+
outputs = {
|
| 165 |
+
family: model.dense_heads[family](dense_features).float()
|
| 166 |
+
for family in DENSE_FAMILIES
|
| 167 |
+
}
|
| 168 |
+
all_sites = model._splice_site_logits(trunk)
|
| 169 |
+
target_start = (model.config.input_length - model.config.target_length) // 2
|
| 170 |
+
outputs["splice_sites"] = all_sites[:, target_start:target_start + model.config.target_length]
|
| 171 |
+
usage_bins = model.splice_usage_head(dense_features).float()
|
| 172 |
+
usage_indices = torch.div(sample["usage_positions"], model.config.dense_bin_size,
|
| 173 |
+
rounding_mode="floor")
|
| 174 |
+
outputs["splice_usage"] = usage_bins[:, usage_indices]
|
| 175 |
+
predicted_positions = model.select_junction_positions(all_sites)
|
| 176 |
+
|
| 177 |
+
matched, valid, missing = _match_coordinate_queries(
|
| 178 |
+
sample["junction_scoring"],
|
| 179 |
+
predicted_positions[0],
|
| 180 |
+
sample["junction_track_halves"],
|
| 181 |
+
)
|
| 182 |
+
junction_target = torch.asinh(
|
| 183 |
+
sample["junction_scoring"]["target_value"]
|
| 184 |
+
).unsqueeze(0)
|
| 185 |
+
junction_prediction = torch.zeros(len(valid), device=valid.device)
|
| 186 |
+
if (~missing & valid).any():
|
| 187 |
+
selected = ~missing & valid
|
| 188 |
+
junction_prediction[selected] = model._junction_predictions(
|
| 189 |
+
trunk, predicted_positions, matched[:, selected]
|
| 190 |
+
)[0]
|
| 191 |
+
outputs["junctions"] = junction_prediction.unsqueeze(0)
|
| 192 |
+
|
| 193 |
+
contact = trunk.reshape(
|
| 194 |
+
1, model.config.contact_bins, -1, model.config.hidden_dim
|
| 195 |
+
).mean(dim=2)
|
| 196 |
+
q, k = model.contact_q(contact), model.contact_k(contact)
|
| 197 |
+
row, column = model.contact_row, model.contact_column
|
| 198 |
+
outputs["contact_maps"] = (0.5 * (q[:, row] * k[:, column] + q[:, column] * k[:, row])).float()
|
| 199 |
+
return outputs, junction_target, valid, missing
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _atomic_save(payload: dict, path: Path) -> None:
|
| 203 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 204 |
+
temporary = path.with_name(f".{path.name}.tmp")
|
| 205 |
+
torch.save(payload, temporary)
|
| 206 |
+
os.replace(temporary, path)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def _sha256(path: Path) -> str:
|
| 210 |
+
digest = hashlib.sha256()
|
| 211 |
+
with path.open("rb") as handle:
|
| 212 |
+
for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
|
| 213 |
+
digest.update(chunk)
|
| 214 |
+
return digest.hexdigest()
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def _resume_position(payload: dict, *, examples: int, epochs: int) -> tuple[int, int]:
|
| 218 |
+
epoch = int(payload["epoch"])
|
| 219 |
+
step = int(payload["global_step"])
|
| 220 |
+
kind = payload.get("checkpoint_kind")
|
| 221 |
+
if kind not in (None, "epoch") or step != epoch * examples:
|
| 222 |
+
raise ValueError("only a completed-epoch checkpoint can resume training")
|
| 223 |
+
if payload.get("examples", examples) != examples or payload.get("schedule_epochs", epochs) != epochs:
|
| 224 |
+
raise ValueError("checkpoint data size or training schedule differs from this run")
|
| 225 |
+
return epoch, step
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def train(args: argparse.Namespace) -> None:
|
| 229 |
+
# Multi-GPU with `torchrun --nproc-per-node N train_eval.py train ...`: one example per GPU per
|
| 230 |
+
# step (data parallel), rank 0 writes checkpoints and logs. Model size is bounded by the
|
| 231 |
+
# training budget, not by a parameter cap.
|
| 232 |
+
rank, local_rank, world = _distributed()
|
| 233 |
+
config = ModelConfig.from_yaml(args.config)
|
| 234 |
+
device = torch.device("cuda", local_rank) if world > 1 else _device(args.device)
|
| 235 |
+
if world > 1:
|
| 236 |
+
torch.cuda.set_device(device)
|
| 237 |
+
torch.manual_seed(args.seed)
|
| 238 |
+
model = CompactModel(config).to(device)
|
| 239 |
+
parameters = count_parameters(model)
|
| 240 |
+
optimizer = torch.optim.AdamW(
|
| 241 |
+
model.parameters(), lr=args.learning_rate, weight_decay=args.weight_decay
|
| 242 |
+
)
|
| 243 |
+
scaler = torch.amp.GradScaler("cuda", enabled=device.type == "cuda")
|
| 244 |
+
full_dataset = AlphaGenomeDataset(args.input, "train")
|
| 245 |
+
model.set_junction_track_halves(full_dataset.junction_track_halves)
|
| 246 |
+
size = min(len(full_dataset), args.max_examples or len(full_dataset))
|
| 247 |
+
dataset = Subset(full_dataset, range(size))
|
| 248 |
+
start_epoch, global_step = 0, 0
|
| 249 |
+
if args.resume:
|
| 250 |
+
payload = torch.load(args.resume, map_location="cpu", weights_only=True)
|
| 251 |
+
if payload.get("config") != config.to_dict():
|
| 252 |
+
raise ValueError("checkpoint configuration does not match --config")
|
| 253 |
+
model.load_state_dict(payload["model"], strict=True)
|
| 254 |
+
optimizer.load_state_dict(payload["optimizer"])
|
| 255 |
+
scaler.load_state_dict(payload.get("scaler", {}))
|
| 256 |
+
start_epoch, global_step = _resume_position(payload, examples=size, epochs=args.epochs)
|
| 257 |
+
per_rank = math.ceil(size / world)
|
| 258 |
+
steps = max(1, per_rank * args.epochs)
|
| 259 |
+
module = model
|
| 260 |
+
if world > 1:
|
| 261 |
+
model = torch.nn.parallel.DistributedDataParallel(
|
| 262 |
+
model, device_ids=[local_rank], find_unused_parameters=True)
|
| 263 |
+
sampler = (torch.utils.data.distributed.DistributedSampler(dataset, num_replicas=world, rank=rank,
|
| 264 |
+
shuffle=True, seed=args.seed)
|
| 265 |
+
if world > 1 else None)
|
| 266 |
+
stop_after_epoch = args.stop_after_epoch or args.epochs
|
| 267 |
+
output = args.output.resolve()
|
| 268 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 269 |
+
started = time.monotonic()
|
| 270 |
+
if rank == 0:
|
| 271 |
+
print(json.dumps({"event": "train_start", "parameters": parameters, "examples": size,
|
| 272 |
+
"device": str(device), "world_size": world}), flush=True)
|
| 273 |
+
|
| 274 |
+
for epoch in range(start_epoch, stop_after_epoch):
|
| 275 |
+
model.train()
|
| 276 |
+
if sampler is not None:
|
| 277 |
+
sampler.set_epoch(epoch)
|
| 278 |
+
loader = _loader(dataset, workers=args.workers, shuffle=True, sampler=sampler)
|
| 279 |
+
for sample in loader:
|
| 280 |
+
sample = _to_device(sample, device)
|
| 281 |
+
inputs, junction_target, junction_valid = _model_inputs(sample)
|
| 282 |
+
progress = min((global_step + 1) / steps, 1.0)
|
| 283 |
+
learning_rate = args.min_learning_rate + 0.5 * (
|
| 284 |
+
args.learning_rate - args.min_learning_rate
|
| 285 |
+
) * (1.0 + math.cos(math.pi * progress))
|
| 286 |
+
for group in optimizer.param_groups:
|
| 287 |
+
group["lr"] = learning_rate
|
| 288 |
+
optimizer.zero_grad(set_to_none=True)
|
| 289 |
+
with _autocast(device):
|
| 290 |
+
predictions = model(**inputs)
|
| 291 |
+
losses = _losses(predictions, sample, junction_target, junction_valid)
|
| 292 |
+
if not torch.isfinite(losses["total"]):
|
| 293 |
+
raise FloatingPointError(f"non-finite loss at step {global_step}")
|
| 294 |
+
scaler.scale(losses["total"]).backward()
|
| 295 |
+
scaler.unscale_(optimizer)
|
| 296 |
+
gradient_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_gradient_norm)
|
| 297 |
+
scaler.step(optimizer)
|
| 298 |
+
scaler.update()
|
| 299 |
+
global_step += 1
|
| 300 |
+
if rank == 0 and (global_step == 1 or global_step % args.log_every == 0):
|
| 301 |
+
print(
|
| 302 |
+
json.dumps(
|
| 303 |
+
{
|
| 304 |
+
"event": "train_step",
|
| 305 |
+
"epoch": epoch + 1,
|
| 306 |
+
"step": global_step,
|
| 307 |
+
"loss": float(losses["total"].detach()),
|
| 308 |
+
"gradient_norm": float(gradient_norm),
|
| 309 |
+
"learning_rate": learning_rate,
|
| 310 |
+
"elapsed_seconds": time.monotonic() - started,
|
| 311 |
+
}
|
| 312 |
+
),
|
| 313 |
+
flush=True,
|
| 314 |
+
)
|
| 315 |
+
if rank == 0 and global_step % args.save_every == 0:
|
| 316 |
+
_atomic_save(
|
| 317 |
+
{
|
| 318 |
+
"schema": "alphagenome-50m-real/v3",
|
| 319 |
+
"model": module.state_dict(),
|
| 320 |
+
"optimizer": optimizer.state_dict(),
|
| 321 |
+
"scaler": scaler.state_dict(),
|
| 322 |
+
"config": config.to_dict(),
|
| 323 |
+
"epoch": epoch,
|
| 324 |
+
"global_step": global_step,
|
| 325 |
+
"checkpoint_kind": "progress",
|
| 326 |
+
"examples": size,
|
| 327 |
+
"schedule_epochs": args.epochs,
|
| 328 |
+
},
|
| 329 |
+
output / "progress.pt",
|
| 330 |
+
)
|
| 331 |
+
if world > 1:
|
| 332 |
+
torch.distributed.barrier()
|
| 333 |
+
if rank != 0:
|
| 334 |
+
continue
|
| 335 |
+
_atomic_save(
|
| 336 |
+
{
|
| 337 |
+
"schema": "alphagenome-50m-real/v3",
|
| 338 |
+
"model": module.state_dict(),
|
| 339 |
+
"optimizer": optimizer.state_dict(),
|
| 340 |
+
"scaler": scaler.state_dict(),
|
| 341 |
+
"config": config.to_dict(),
|
| 342 |
+
"epoch": epoch + 1,
|
| 343 |
+
"global_step": global_step,
|
| 344 |
+
"checkpoint_kind": "epoch",
|
| 345 |
+
"examples": size,
|
| 346 |
+
"schedule_epochs": args.epochs,
|
| 347 |
+
},
|
| 348 |
+
output / "last.pt",
|
| 349 |
+
)
|
| 350 |
+
if world > 1:
|
| 351 |
+
torch.distributed.barrier()
|
| 352 |
+
torch.distributed.destroy_process_group()
|
| 353 |
+
if rank != 0:
|
| 354 |
+
return
|
| 355 |
+
checkpoint = output / "last.pt"
|
| 356 |
+
manifest = {
|
| 357 |
+
"schema": "alphagenome-50m-real/v3",
|
| 358 |
+
"checkpoint": {"path": checkpoint.name, "sha256": _sha256(checkpoint)},
|
| 359 |
+
"parameters": parameters,
|
| 360 |
+
"config": config.to_dict(),
|
| 361 |
+
"output_families": list(ALL_FAMILIES),
|
| 362 |
+
"epochs": args.epochs,
|
| 363 |
+
"completed_epochs": stop_after_epoch,
|
| 364 |
+
"global_step": global_step,
|
| 365 |
+
}
|
| 366 |
+
(output / "model_manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n")
|
| 367 |
+
print(json.dumps({"event": "train_complete", **manifest}), flush=True)
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
class PerTrackMoments:
|
| 371 |
+
def __init__(self, tracks: int):
|
| 372 |
+
self.n = np.zeros(tracks, dtype=np.int64)
|
| 373 |
+
self.sum_x = np.zeros(tracks, dtype=np.float64)
|
| 374 |
+
self.sum_y = np.zeros(tracks, dtype=np.float64)
|
| 375 |
+
self.sum_x2 = np.zeros(tracks, dtype=np.float64)
|
| 376 |
+
self.sum_y2 = np.zeros(tracks, dtype=np.float64)
|
| 377 |
+
self.sum_xy = np.zeros(tracks, dtype=np.float64)
|
| 378 |
+
|
| 379 |
+
def update(self, prediction: Tensor, target: Tensor, mask: Tensor | None = None) -> None:
|
| 380 |
+
x = prediction.detach().double().cpu().numpy().reshape(-1, prediction.shape[-1])
|
| 381 |
+
y = target.detach().double().cpu().numpy().reshape(-1, target.shape[-1])
|
| 382 |
+
valid = np.ones_like(y, dtype=bool) if mask is None else mask.detach().cpu().numpy().reshape(y.shape).astype(bool)
|
| 383 |
+
self.n += valid.sum(axis=0)
|
| 384 |
+
self.sum_x += np.where(valid, x, 0).sum(axis=0, dtype=np.float64)
|
| 385 |
+
self.sum_y += np.where(valid, y, 0).sum(axis=0, dtype=np.float64)
|
| 386 |
+
self.sum_x2 += np.where(valid, x * x, 0).sum(axis=0, dtype=np.float64)
|
| 387 |
+
self.sum_y2 += np.where(valid, y * y, 0).sum(axis=0, dtype=np.float64)
|
| 388 |
+
self.sum_xy += np.where(valid, x * y, 0).sum(axis=0, dtype=np.float64)
|
| 389 |
+
|
| 390 |
+
def update_indexed(self, prediction: Tensor, target: Tensor, track: Tensor) -> None:
|
| 391 |
+
x = prediction.detach().double().cpu().numpy().reshape(-1)
|
| 392 |
+
y = target.detach().double().cpu().numpy().reshape(-1)
|
| 393 |
+
indices = track.detach().cpu().numpy().reshape(-1).astype(np.int64)
|
| 394 |
+
self.n += np.bincount(indices, minlength=len(self.n))
|
| 395 |
+
self.sum_x += np.bincount(indices, weights=x, minlength=len(self.n))
|
| 396 |
+
self.sum_y += np.bincount(indices, weights=y, minlength=len(self.n))
|
| 397 |
+
self.sum_x2 += np.bincount(indices, weights=x * x, minlength=len(self.n))
|
| 398 |
+
self.sum_y2 += np.bincount(indices, weights=y * y, minlength=len(self.n))
|
| 399 |
+
self.sum_xy += np.bincount(indices, weights=x * y, minlength=len(self.n))
|
| 400 |
+
|
| 401 |
+
def report(self) -> dict:
|
| 402 |
+
numerator = self.n * self.sum_xy - self.sum_x * self.sum_y
|
| 403 |
+
denominator = np.sqrt(
|
| 404 |
+
np.maximum(self.n * self.sum_x2 - self.sum_x**2, 0)
|
| 405 |
+
* np.maximum(self.n * self.sum_y2 - self.sum_y**2, 0)
|
| 406 |
+
)
|
| 407 |
+
target_ss = np.maximum(self.n * self.sum_y2 - self.sum_y**2, 0)
|
| 408 |
+
scorable = (self.n >= 2) & (target_ss > 0)
|
| 409 |
+
pearson = np.full_like(numerator, np.nan)
|
| 410 |
+
nonconstant = scorable & (denominator > 0)
|
| 411 |
+
pearson[nonconstant] = numerator[nonconstant] / denominator[nonconstant]
|
| 412 |
+
pearson[scorable & ~nonconstant] = 0.0
|
| 413 |
+
return {
|
| 414 |
+
"mean_pearson": float(pearson[scorable].mean()) if scorable.any() else 0.0,
|
| 415 |
+
"valid_tracks": int(scorable.sum()),
|
| 416 |
+
"per_track_pearson": [float(value) if np.isfinite(value) else None for value in pearson],
|
| 417 |
+
"values_per_track": self.n.tolist(),
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def evaluate(args: argparse.Namespace) -> None:
|
| 422 |
+
device = _device(args.device)
|
| 423 |
+
payload = torch.load(args.checkpoint, map_location="cpu", weights_only=True)
|
| 424 |
+
config = ModelConfig(**payload["config"])
|
| 425 |
+
model = CompactModel(config).to(device)
|
| 426 |
+
model.load_state_dict(payload["model"], strict=True)
|
| 427 |
+
model.eval()
|
| 428 |
+
full_dataset = AlphaGenomeDataset(args.input, args.split)
|
| 429 |
+
model.set_junction_track_halves(full_dataset.junction_track_halves)
|
| 430 |
+
size = min(len(full_dataset), args.max_examples or len(full_dataset))
|
| 431 |
+
dataset = Subset(full_dataset, range(size))
|
| 432 |
+
metrics = {
|
| 433 |
+
**{family: PerTrackMoments(config_value) for family, config_value in {
|
| 434 |
+
"atac": 167, "dnase": 305, "procap": 12, "cage": 546,
|
| 435 |
+
"rna_seq": 667, "chip_tf": 1617, "chip_histone": 1116,
|
| 436 |
+
}.items()},
|
| 437 |
+
"splice_sites": PerTrackMoments(4),
|
| 438 |
+
"splice_usage": PerTrackMoments(config.splice_usage_tracks),
|
| 439 |
+
"junctions": PerTrackMoments(config.junction_tracks),
|
| 440 |
+
"contact_maps": PerTrackMoments(config.contact_tracks),
|
| 441 |
+
}
|
| 442 |
+
with torch.inference_mode():
|
| 443 |
+
for index, sample in enumerate(_loader(dataset, workers=args.workers, shuffle=False)):
|
| 444 |
+
sample = _to_device(sample, device)
|
| 445 |
+
outputs, junction_target, junction_valid, junction_missing = (
|
| 446 |
+
_validation_inference(model, sample)
|
| 447 |
+
)
|
| 448 |
+
# Match predict.py: FP32 inference is serialized to FP16 Zarr values.
|
| 449 |
+
outputs = {name: value.half().float() for name, value in outputs.items()}
|
| 450 |
+
for family in DENSE_FAMILIES:
|
| 451 |
+
metrics[family].update(
|
| 452 |
+
outputs[family][0],
|
| 453 |
+
torch.asinh(sample["dense"][family]["values"]),
|
| 454 |
+
sample["dense"][family]["mask"],
|
| 455 |
+
)
|
| 456 |
+
metrics["splice_sites"].update(outputs["splice_sites"][0], sample["splice_sites"])
|
| 457 |
+
metrics["splice_usage"].update(
|
| 458 |
+
outputs["splice_usage"][0],
|
| 459 |
+
torch.asinh(sample["splice_usage"]["values"]),
|
| 460 |
+
sample["splice_usage"]["mask"],
|
| 461 |
+
)
|
| 462 |
+
junction_track = sample["junction_scoring"]["track"]
|
| 463 |
+
metrics["junctions"].update_indexed(
|
| 464 |
+
outputs["junctions"][0][junction_valid],
|
| 465 |
+
junction_target[0][junction_valid],
|
| 466 |
+
junction_track[junction_valid],
|
| 467 |
+
)
|
| 468 |
+
metrics["contact_maps"].update(
|
| 469 |
+
outputs["contact_maps"][0],
|
| 470 |
+
torch.asinh(sample["contact_maps"]),
|
| 471 |
+
sample["contact_map_mask"],
|
| 472 |
+
)
|
| 473 |
+
if index == 0 or (index + 1) % args.log_every == 0 or index + 1 == size:
|
| 474 |
+
print(json.dumps({"event": "evaluate_progress", "examples": index + 1, "total": size}), flush=True)
|
| 475 |
+
families = {name: accumulator.report() for name, accumulator in metrics.items()}
|
| 476 |
+
valid_family_scores = [item["mean_pearson"] for item in families.values()]
|
| 477 |
+
report = {
|
| 478 |
+
"schema": "alphagenome-50m-evaluation/v3",
|
| 479 |
+
"split": args.split,
|
| 480 |
+
"examples": size,
|
| 481 |
+
"metric_space": (
|
| 482 |
+
"asinh continuous targets and binary splice-site targets; "
|
| 483 |
+
"junction Pearson uses hidden coordinate queries and predicted endpoints; "
|
| 484 |
+
"FP32 inference rounded to FP16 prediction values"
|
| 485 |
+
),
|
| 486 |
+
"families": families,
|
| 487 |
+
"overall_mean_family_pearson": float(np.mean(valid_family_scores)),
|
| 488 |
+
}
|
| 489 |
+
args.report.parent.mkdir(parents=True, exist_ok=True)
|
| 490 |
+
args.report.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")
|
| 491 |
+
print(json.dumps({"event": "evaluate_complete", "overall_mean_family_pearson": report["overall_mean_family_pearson"]}), flush=True)
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def main() -> None:
|
| 495 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 496 |
+
common = argparse.ArgumentParser(add_help=False)
|
| 497 |
+
common.add_argument("--input", required=True, type=Path)
|
| 498 |
+
common.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
|
| 499 |
+
common.add_argument("--workers", type=int, default=2)
|
| 500 |
+
common.add_argument("--max-examples", type=int, default=0)
|
| 501 |
+
common.add_argument("--device", choices=("auto", "cuda", "cpu"), default="auto")
|
| 502 |
+
common.add_argument("--log-every", type=int, default=25)
|
| 503 |
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
| 504 |
+
train_parser = subparsers.add_parser("train", parents=[common])
|
| 505 |
+
train_parser.add_argument("--output", required=True, type=Path)
|
| 506 |
+
train_parser.add_argument("--epochs", type=int, default=10)
|
| 507 |
+
train_parser.add_argument("--stop-after-epoch", type=int)
|
| 508 |
+
train_parser.add_argument("--learning-rate", type=float, default=2e-4)
|
| 509 |
+
train_parser.add_argument("--min-learning-rate", type=float, default=2e-5)
|
| 510 |
+
train_parser.add_argument("--weight-decay", type=float, default=1e-4)
|
| 511 |
+
train_parser.add_argument("--max-gradient-norm", type=float, default=5.0)
|
| 512 |
+
train_parser.add_argument("--save-every", type=int, default=250)
|
| 513 |
+
train_parser.add_argument("--seed", type=int, default=17)
|
| 514 |
+
train_parser.add_argument("--resume", type=Path)
|
| 515 |
+
train_parser.set_defaults(run=train)
|
| 516 |
+
evaluate_parser = subparsers.add_parser("evaluate", parents=[common])
|
| 517 |
+
evaluate_parser.add_argument("--checkpoint", required=True, type=Path)
|
| 518 |
+
evaluate_parser.add_argument("--split", choices=("train", "valid", "test"), required=True)
|
| 519 |
+
evaluate_parser.add_argument("--report", required=True, type=Path)
|
| 520 |
+
evaluate_parser.set_defaults(run=evaluate)
|
| 521 |
+
args = parser.parse_args()
|
| 522 |
+
if args.workers < 0 or args.max_examples < 0:
|
| 523 |
+
parser.error("workers/max-examples must be nonnegative")
|
| 524 |
+
if args.command == "train" and (
|
| 525 |
+
args.epochs < 1
|
| 526 |
+
or (args.stop_after_epoch is not None
|
| 527 |
+
and not 1 <= args.stop_after_epoch <= args.epochs)
|
| 528 |
+
):
|
| 529 |
+
parser.error("epochs must be positive and stop-after-epoch must be within the schedule")
|
| 530 |
+
args.run(args)
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
if __name__ == "__main__":
|
| 534 |
+
main()
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/validation_tracks.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S001/validation_variants.json
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"eqtl_sign": {
|
| 3 |
+
"rows": 17052,
|
| 4 |
+
"perturbations": 165,
|
| 5 |
+
"metric": "auroc",
|
| 6 |
+
"model": 0.4941389147398904,
|
| 7 |
+
"anchors": {
|
| 8 |
+
"AlphaGenome": 0.8263569969634328
|
| 9 |
+
}
|
| 10 |
+
},
|
| 11 |
+
"eqtl_causality": {
|
| 12 |
+
"rows": 17934,
|
| 13 |
+
"perturbations": 174,
|
| 14 |
+
"metric": "auroc",
|
| 15 |
+
"model": 0.6542302506588221,
|
| 16 |
+
"anchors": {
|
| 17 |
+
"AlphaGenome": 0.8325427468284611
|
| 18 |
+
}
|
| 19 |
+
},
|
| 20 |
+
"eqtl_coefficient": {
|
| 21 |
+
"rows": 8575,
|
| 22 |
+
"perturbations": 165,
|
| 23 |
+
"metric": "spearman",
|
| 24 |
+
"model": -0.04857778001776154,
|
| 25 |
+
"anchors": {
|
| 26 |
+
"AlphaGenome": 0.4133539365891599
|
| 27 |
+
}
|
| 28 |
+
},
|
| 29 |
+
"sqtl_causality": {
|
| 30 |
+
"rows": 21340,
|
| 31 |
+
"perturbations": 194,
|
| 32 |
+
"metric": "auprc",
|
| 33 |
+
"model": 0.8433797414542621,
|
| 34 |
+
"anchors": {
|
| 35 |
+
"AlphaGenome": 0.8447114201904594
|
| 36 |
+
}
|
| 37 |
+
},
|
| 38 |
+
"clinvar_noncoding": {
|
| 39 |
+
"rows": 199,
|
| 40 |
+
"perturbations": 199,
|
| 41 |
+
"metric": "auprc",
|
| 42 |
+
"model": 0.1946354697971151,
|
| 43 |
+
"anchors": {
|
| 44 |
+
"AlphaGenome": 0.9409857958177288
|
| 45 |
+
}
|
| 46 |
+
},
|
| 47 |
+
"clinvar_splice_region": {
|
| 48 |
+
"rows": 194,
|
| 49 |
+
"perturbations": 194,
|
| 50 |
+
"metric": "auprc",
|
| 51 |
+
"model": 0.17777922359375958,
|
| 52 |
+
"anchors": {
|
| 53 |
+
"AlphaGenome": 0.7224791623996103
|
| 54 |
+
}
|
| 55 |
+
},
|
| 56 |
+
"clinvar_missense": {
|
| 57 |
+
"rows": 199,
|
| 58 |
+
"perturbations": 199,
|
| 59 |
+
"metric": "auprc",
|
| 60 |
+
"model": 0.23303249002260132,
|
| 61 |
+
"anchors": {
|
| 62 |
+
"AlphaGenome": 0.373826292978903
|
| 63 |
+
}
|
| 64 |
+
},
|
| 65 |
+
"mfass": {
|
| 66 |
+
"rows": 195,
|
| 67 |
+
"perturbations": 195,
|
| 68 |
+
"metric": "auprc",
|
| 69 |
+
"model": 0.21772140965743444,
|
| 70 |
+
"anchors": {
|
| 71 |
+
"AlphaGenome": 0.7342557141920668
|
| 72 |
+
}
|
| 73 |
+
},
|
| 74 |
+
"caqtl": {
|
| 75 |
+
"rows": 198,
|
| 76 |
+
"perturbations": 198,
|
| 77 |
+
"metric": "auprc",
|
| 78 |
+
"model": 0.1636819584913644,
|
| 79 |
+
"anchors": {
|
| 80 |
+
"AlphaGenome": 0.8075760167741196
|
| 81 |
+
}
|
| 82 |
+
},
|
| 83 |
+
"bqtl_spi1": {
|
| 84 |
+
"rows": 160,
|
| 85 |
+
"perturbations": 160,
|
| 86 |
+
"metric": "auprc",
|
| 87 |
+
"model": 0.20768655997770985,
|
| 88 |
+
"anchors": {
|
| 89 |
+
"AlphaGenome": 0.8167450781363793
|
| 90 |
+
}
|
| 91 |
+
},
|
| 92 |
+
"enhancer_gene": {
|
| 93 |
+
"rows": 200,
|
| 94 |
+
"perturbations": 200,
|
| 95 |
+
"metric": "auprc",
|
| 96 |
+
"model": 0.4132730815910868,
|
| 97 |
+
"anchors": {
|
| 98 |
+
"AlphaGenome": 0.9594307235541584
|
| 99 |
+
}
|
| 100 |
+
},
|
| 101 |
+
"traitgym_mendelian": {
|
| 102 |
+
"rows": 292,
|
| 103 |
+
"perturbations": 292,
|
| 104 |
+
"metric": "auprc",
|
| 105 |
+
"model": 0.20918637590093828,
|
| 106 |
+
"anchors": {
|
| 107 |
+
"Borzoi_L2_L2.plus.all": 0.5026323772738239,
|
| 108 |
+
"Enformer_L2_L2.plus.all": 0.5452938267693526,
|
| 109 |
+
"CADD.plus.RawScore": 0.7189111372856957,
|
| 110 |
+
"GPN-MSA_absLLR.plus.score": 0.6729149139043132
|
| 111 |
+
}
|
| 112 |
+
},
|
| 113 |
+
"traitgym_complex": {
|
| 114 |
+
"rows": 299,
|
| 115 |
+
"perturbations": 299,
|
| 116 |
+
"metric": "auprc",
|
| 117 |
+
"model": 0.2001169301893302,
|
| 118 |
+
"anchors": {
|
| 119 |
+
"Borzoi_L2_L2.plus.all": 0.294501577162467,
|
| 120 |
+
"Enformer_L2_L2.plus.all": 0.269227301087889,
|
| 121 |
+
"CADD.plus.RawScore": 0.41341570280137435,
|
| 122 |
+
"GPN-MSA_absLLR.plus.score": 0.4213971415058371
|
| 123 |
+
}
|
| 124 |
+
}
|
| 125 |
+
}
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/README.md
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SeqFunc local01 — base-resolution residual path
|
| 2 |
+
|
| 3 |
+
A single 13,256,456-parameter model reads 1,048,576 bp and predicts all eleven output families.
|
| 4 |
+
Its global encoder and six 384-wide transformer blocks operate on 1,024 tokens. A parallel width-32
|
| 5 |
+
convolutional path keeps base resolution, with a 21-bp stem and four residual depthwise blocks at
|
| 6 |
+
dilations 1, 4, 16 and 64 (701-bp receptive field). Base logits augment splice predictions; average
|
| 7 |
+
and maximum pooling supply aligned 128-bp residual features to dense, usage and junction heads.
|
| 8 |
+
Contacts use the shared global trunk. Sparse sites and junctions come from model scores alone.
|
| 9 |
+
|
| 10 |
+
All weights originated from local random initialization with seed 17. The parent model trained
|
| 11 |
+
for 2,000 updates using a balanced splice objective; the new branch was attached with zero residual
|
| 12 |
+
outputs and trained for the next 2,000 updates. Parent parameters and optimizer moments were
|
| 13 |
+
preserved exactly at attachment. This checkpoint has seen 4,000 distinct eligible training intervals
|
| 14 |
+
(9.75% of the first epoch); complete training coverage is still in progress. All 41,020 intervals
|
| 15 |
+
are included in each deterministic epoch permutation. Data are AlphaGenome FOLD_0 train folds 2–7,
|
| 16 |
+
with the supplied quantized-target decoding. No pretrained parameters, test labels or test-derived
|
| 17 |
+
caches were used. Development labels are used only to evaluate and select models.
|
| 18 |
+
|
| 19 |
+
Training uses one H100 80 GB, at most 22 CPUs, eight loader workers, BF16, AdamW, a four-epoch
|
| 20 |
+
2e-4-to-2e-5 cosine schedule with 500-step warmup, weight decay 1e-4, and gradient clipping at 5.
|
| 21 |
+
The splice loss balances positives and negatives per type; the other family losses follow the
|
| 22 |
+
reference. A full-length mechanical benchmark measured about 0.09 seconds per steady training
|
| 23 |
+
step and 3.7 GiB peak allocated GPU memory. End-to-end training runs can share this same GPU with
|
| 24 |
+
validation inference of a frozen earlier checkpoint; no second GPU is used.
|
| 25 |
+
|
| 26 |
+
Both entry points read only public manifests and the pinned reference DNA. The complete Python,
|
| 27 |
+
PyTorch and CUDA-library environment is vendored in runtime.tar.gz and is extracted temporarily
|
| 28 |
+
offline. The host provides Linux, bash/tar/gzip and the NVIDIA driver. Model weights, source code,
|
| 29 |
+
checksums, and complete validation reports are included. Perturbation values use float32; track
|
| 30 |
+
values use float16. Both entry points use the same parameters and model functions.
|
| 31 |
+
|
| 32 |
+
All 200 validation intervals and all 2,697 development perturbations are scored with the verifier's
|
| 33 |
+
unmodified tools; results and published anchors are appended below. This early checkpoint remains
|
| 34 |
+
undertrained, has a short local receptive field, and retains a low-capacity contact/junction model.
|
| 35 |
+
The matched control continues the same parent on the same additional training intervals without
|
| 36 |
+
the local path; it is tracked separately in the research ledger.
|
| 37 |
+
|
| 38 |
+
## Measured validation results
|
| 39 |
+
|
| 40 |
+
Family-mean Pearson: **0.171715** on 200 validation intervals.
|
| 41 |
+
|
| 42 |
+
| Family | Pearson |
|
| 43 |
+
|---|---:|
|
| 44 |
+
| atac | 0.313440 |
|
| 45 |
+
| dnase | 0.488170 |
|
| 46 |
+
| procap | 0.267572 |
|
| 47 |
+
| cage | 0.130995 |
|
| 48 |
+
| rna_seq | 0.149987 |
|
| 49 |
+
| chip_tf | 0.254508 |
|
| 50 |
+
| chip_histone | 0.223019 |
|
| 51 |
+
| splice_sites | 0.030428 |
|
| 52 |
+
| splice_usage | 0.023365 |
|
| 53 |
+
| junctions | 0.004990 |
|
| 54 |
+
| contact_maps | 0.002394 |
|
| 55 |
+
|
| 56 |
+
| Development evaluation | Metric | Model | Published anchors on the same rows |
|
| 57 |
+
|---|---|---:|---|
|
| 58 |
+
| eqtl_sign | auroc | 0.4399 | AlphaGenome: 0.8264 |
|
| 59 |
+
| eqtl_causality | auroc | 0.6804 | AlphaGenome: 0.8325 |
|
| 60 |
+
| eqtl_coefficient | spearman | -0.1099 | AlphaGenome: 0.4134 |
|
| 61 |
+
| sqtl_causality | auprc | 0.6716 | AlphaGenome: 0.8447 |
|
| 62 |
+
| clinvar_noncoding | auprc | 0.1962 | AlphaGenome: 0.9410 |
|
| 63 |
+
| clinvar_splice_region | auprc | 0.2155 | AlphaGenome: 0.7225 |
|
| 64 |
+
| clinvar_missense | auprc | 0.2710 | AlphaGenome: 0.3738 |
|
| 65 |
+
| mfass | auprc | 0.1522 | AlphaGenome: 0.7343 |
|
| 66 |
+
| caqtl | auprc | 0.3468 | AlphaGenome: 0.8076 |
|
| 67 |
+
| bqtl_spi1 | auprc | 0.2619 | AlphaGenome: 0.8167 |
|
| 68 |
+
| enhancer_gene | auprc | 0.4727 | AlphaGenome: 0.9594 |
|
| 69 |
+
| traitgym_mendelian | auprc | 0.2523 | Borzoi_L2_L2.plus.all: 0.5026; Enformer_L2_L2.plus.all: 0.5453; CADD.plus.RawScore: 0.7189; GPN-MSA_absLLR.plus.score: 0.6729 |
|
| 70 |
+
| traitgym_complex | auprc | 0.1482 | Borzoi_L2_L2.plus.all: 0.2945; Enformer_L2_L2.plus.all: 0.2692; CADD.plus.RawScore: 0.4134; GPN-MSA_absLLR.plus.score: 0.4214 |
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/infer.sh
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
[[ $# == 2 ]] || { echo "usage: infer.sh INPUT_ROOT OUTPUT_ROOT" >&2; exit 2; }
|
| 4 |
+
package_dir=$(cd "$(dirname "$0")" && pwd)
|
| 5 |
+
runtime_dir=$(mktemp -d "${TMPDIR:-/tmp}/seqfunc-runtime.XXXXXXXX")
|
| 6 |
+
trap 'rm -rf "$runtime_dir"' EXIT
|
| 7 |
+
tar -xzf "$package_dir/runtime.tar.gz" -C "$runtime_dir"
|
| 8 |
+
unset PYTHONPATH
|
| 9 |
+
export PYTHONHOME="$runtime_dir" PYTHONNOUSERSITE=1 PYTHONDONTWRITEBYTECODE=1
|
| 10 |
+
export LD_LIBRARY_PATH="$runtime_dir/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
|
| 11 |
+
export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 NUMEXPR_NUM_THREADS=4
|
| 12 |
+
"$runtime_dir/bin/python" -s "$package_dir/predict.py" "$1" "$2" --checkpoint "$package_dir/last.pt"
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/package_manifest.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"parameters": 13256456,
|
| 3 |
+
"source_checkpoint_sha256": "2258257f7d405240c62d9f9faafba2c7f87da26041302f387dad790c2f123209",
|
| 4 |
+
"files": {
|
| 5 |
+
"README.md": "9d2854394e54a769b519e4e60aec257d83439eed1ed0f584f3b58999cbfb5905",
|
| 6 |
+
"infer.sh": "ef810532b1e72b85fbe283e4f52c177bb70025977dbb2345d75837c9bbd51e37",
|
| 7 |
+
"last.pt": "eb52b09e500dc3089b840c0ac471e4b449090889799d73e0741f61b787536756",
|
| 8 |
+
"perturb.py": "ba37a6f9f8b8eccb052903618bcb4c91d3f4cbed62dfe678ee362644dc80801e",
|
| 9 |
+
"perturb.sh": "113ec2383276a6e83fe1e4e8b0fa914f8d535d5dd0f5b2c34240140312dd5fb4",
|
| 10 |
+
"predict.py": "2725592456c55c188b22c376f0cb249e9f46b4ae1370d2226df7143da358a8b2",
|
| 11 |
+
"prediction_contract.py": "b11af8f7cff82b35afc6282be387358a48464b78bd1dfa44452dace26a5e0a83",
|
| 12 |
+
"reference/__init__.py": "45f3cf93f48859104e70bb58d717130dfd6521a45d2aba06b1a726afc0dc51dd",
|
| 13 |
+
"reference/alphagenome_50m/__init__.py": "a5a7e45d5940c3b201017c6322128e9f47efd37e1d29f717da2c1f787688eff9",
|
| 14 |
+
"reference/alphagenome_50m/alphagenome_50m.yaml": "3cac32e9f55e352dff78bb85ac892fdae1f9e412d9bba3e945750210c5252eee",
|
| 15 |
+
"reference/alphagenome_50m/dataset.py": "ad6670f742f4de9898064becc525d0aea98b402abe7b210bb1b26a9eee6402b9",
|
| 16 |
+
"reference/alphagenome_50m/layers.py": "26a116a72aa3f0e307a3606163547edbdecb7965f7fdcd96bc5f805cd21b3352",
|
| 17 |
+
"reference/alphagenome_50m/model.py": "2871dc8893879c3e14a526dea659701d72c8c4d0e2f835b0bfb857034a2c2e6d",
|
| 18 |
+
"reference/alphagenome_50m/reference_large.yaml": "68084d299b39418034c6bbf71db174c3ffa68bbeea8779c1694e44ec71f3529c",
|
| 19 |
+
"reference/alphagenome_50m/run_ddp.sh": "96d35a24a4e6789311501fb98203807ac0c4429375c44d5c6671908270c93bb0",
|
| 20 |
+
"reference/alphagenome_50m/tiny_overfit.yaml": "f7a104c3929de0530a9a8f73f66d794cca595aefad8ef262e09ecbeb9cfce6de",
|
| 21 |
+
"reference/alphagenome_50m/train_eval.py": "2547c9adbdb51ad1acf796a548724cc7770eba90a755f4cb3b37d6f591adf6ec",
|
| 22 |
+
"runtime.tar.gz": "718da4c374e0c552b6e429b226c90b2fded5c900d95577d190d4df520aaf3901",
|
| 23 |
+
"validation_tracks.json": "4cbc1f3246fd93e871c3b198e14d976fa3bca2e1c616160f606a5176d7e4a51e",
|
| 24 |
+
"validation_variants.json": "edc97df92a3954c3c57bdc9ed3354b57d5f03aa92057cdb7fcb28e3c89d9209c"
|
| 25 |
+
}
|
| 26 |
+
}
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/perturb.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Predict both sequences of every perturbation (contract: perturbations/v1).
|
| 2 |
+
|
| 3 |
+
python perturb.py INPUT_ROOT OUTPUT_ROOT --checkpoint last.pt
|
| 4 |
+
|
| 5 |
+
INPUT_ROOT holds `public/perturbations.parquet` and `reference/GRCh38.p13.genome.fa` (in the
|
| 6 |
+
workspace, `/workspace/data` works too: the queries are then read from `variant_evals/public/`). Each row is a
|
| 7 |
+
1,048,576-bp window starting at `input_start` and an edit spanning [edit_start, edit_end) in genomic
|
| 8 |
+
0-based coordinates:
|
| 9 |
+
|
| 10 |
+
- `snv`: sequence A carries `allele_a` at edit_start, sequence B carries `allele_b` (both are written
|
| 11 |
+
explicitly; either may differ from the reference genome);
|
| 12 |
+
- `mask`: sequence A is the reference, sequence B has the interval replaced by N.
|
| 13 |
+
|
| 14 |
+
For each perturbation the output group `perturbations/p{index:06d}` holds `a/<family>` and
|
| 15 |
+
`b/<family>` for every family in `families`: dense families sliced to bins
|
| 16 |
+
[dense_bin_start, dense_bin_end) of the central target window, and `splice_sites` sliced to bp
|
| 17 |
+
[splice_start, splice_end). Values are the same quantities as predictions.zarr (asinh space for
|
| 18 |
+
dense tracks, splice-site scores for splice_sites).
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import argparse
|
| 24 |
+
import json
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
from numcodecs import Blosc
|
| 28 |
+
import numpy as np
|
| 29 |
+
import pandas as pd
|
| 30 |
+
import pysam
|
| 31 |
+
import torch
|
| 32 |
+
import zarr
|
| 33 |
+
|
| 34 |
+
from reference.alphagenome_50m.dataset import AlphaGenomeDataset
|
| 35 |
+
from reference.alphagenome_50m.model import CompactModel, ModelConfig
|
| 36 |
+
|
| 37 |
+
PERTURBATION_SCHEMA = "genome-sequence-to-function-perturbations/v1"
|
| 38 |
+
COMPRESSOR = Blosc(cname="zstd", clevel=3, shuffle=Blosc.BITSHUFFLE)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def sequences(fasta, row) -> tuple[str, str]:
|
| 42 |
+
length = fasta.get_reference_length(row.chrom)
|
| 43 |
+
start, end = int(row.input_start), int(row.input_start) + 1_048_576
|
| 44 |
+
sequence = fasta.fetch(row.chrom, max(0, start), min(length, end)).upper()
|
| 45 |
+
sequence = "N" * max(0, -start) + sequence + "N" * max(0, end - length)
|
| 46 |
+
lo, hi = int(row.edit_start) - start, int(row.edit_end) - start
|
| 47 |
+
if row.edit == "snv":
|
| 48 |
+
return sequence[:lo] + row.allele_a + sequence[hi:], sequence[:lo] + row.allele_b + sequence[hi:]
|
| 49 |
+
if row.edit == "mask":
|
| 50 |
+
return sequence, sequence[:lo] + "N" * (hi - lo) + sequence[hi:]
|
| 51 |
+
raise ValueError(f"unknown edit {row.edit!r}")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def main(input_root: Path, output_root: Path, checkpoint: Path, queries: Path | None = None) -> None:
|
| 55 |
+
payload = torch.load(checkpoint, map_location="cpu", weights_only=True)
|
| 56 |
+
config = ModelConfig(**payload["config"])
|
| 57 |
+
model = CompactModel(config)
|
| 58 |
+
model.load_state_dict(payload["model"], strict=True)
|
| 59 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 60 |
+
model.to(device).eval()
|
| 61 |
+
if queries is None:
|
| 62 |
+
queries = input_root / "public/perturbations.parquet"
|
| 63 |
+
if not queries.exists():
|
| 64 |
+
queries = input_root / "variant_evals/public/perturbations.parquet"
|
| 65 |
+
rows = pd.read_parquet(queries)
|
| 66 |
+
fasta = pysam.FastaFile(str(input_root / "reference/GRCh38.p13.genome.fa"))
|
| 67 |
+
output_root.mkdir(parents=True, exist_ok=True)
|
| 68 |
+
root = zarr.open_group(str(output_root / "perturbations.zarr"), mode="w")
|
| 69 |
+
target_start = (config.input_length - config.target_length) // 2
|
| 70 |
+
with torch.inference_mode():
|
| 71 |
+
for index, row in enumerate(rows.itertuples(index=False)):
|
| 72 |
+
pair = sequences(fasta, row)
|
| 73 |
+
dna = torch.from_numpy(np.stack([AlphaGenomeDataset._one_hot(s) for s in pair])).to(device)
|
| 74 |
+
trunk = model._trunk(dna)
|
| 75 |
+
group = root.create_group(f"perturbations/p{index:06d}")
|
| 76 |
+
features = None
|
| 77 |
+
for family in row.families:
|
| 78 |
+
if family == "splice_sites":
|
| 79 |
+
logits = model._splice_site_logits(trunk)[:, target_start:target_start + config.target_length]
|
| 80 |
+
values = logits[:, row.splice_start:row.splice_end]
|
| 81 |
+
else:
|
| 82 |
+
features = model._dense_features(trunk) if features is None else features
|
| 83 |
+
values = model.dense_heads[family](features)[:, row.dense_bin_start:row.dense_bin_end]
|
| 84 |
+
# float32: one variant's effect is often below float16 resolution (about 0.004 at
|
| 85 |
+
# asinh values of 4-8), so A and B would round to the same numbers.
|
| 86 |
+
values = values.float().cpu().numpy()
|
| 87 |
+
for side, array in zip("ab", values):
|
| 88 |
+
group.create_dataset(f"{side}/{family}", data=array, compressor=COMPRESSOR)
|
| 89 |
+
print(json.dumps({"event": "perturb", "done": index + 1, "total": len(rows)}), flush=True)
|
| 90 |
+
root.attrs.update({"schema": PERTURBATION_SCHEMA,
|
| 91 |
+
"perturbation_ids": rows.perturbation_id.astype(str).tolist()})
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
if __name__ == "__main__":
|
| 95 |
+
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 96 |
+
parser.add_argument("input_root", type=Path)
|
| 97 |
+
parser.add_argument("output_root", type=Path)
|
| 98 |
+
parser.add_argument("--checkpoint", type=Path, default=Path(__file__).resolve().parent / "last.pt")
|
| 99 |
+
parser.add_argument("--queries", type=Path, help="another query table, e.g. the development split")
|
| 100 |
+
args = parser.parse_args()
|
| 101 |
+
main(args.input_root, args.output_root, args.checkpoint, args.queries)
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/perturb.sh
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
[[ $# == 2 ]] || { echo "usage: perturb.sh INPUT_ROOT OUTPUT_ROOT" >&2; exit 2; }
|
| 4 |
+
package_dir=$(cd "$(dirname "$0")" && pwd)
|
| 5 |
+
runtime_dir=$(mktemp -d "${TMPDIR:-/tmp}/seqfunc-runtime.XXXXXXXX")
|
| 6 |
+
trap 'rm -rf "$runtime_dir"' EXIT
|
| 7 |
+
tar -xzf "$package_dir/runtime.tar.gz" -C "$runtime_dir"
|
| 8 |
+
unset PYTHONPATH
|
| 9 |
+
export PYTHONHOME="$runtime_dir" PYTHONNOUSERSITE=1 PYTHONDONTWRITEBYTECODE=1
|
| 10 |
+
export LD_LIBRARY_PATH="$runtime_dir/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
|
| 11 |
+
export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 NUMEXPR_NUM_THREADS=4
|
| 12 |
+
"$runtime_dir/bin/python" -s "$package_dir/perturb.py" "$1" "$2" --checkpoint "$package_dir/last.pt"
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/predict.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Stream the single benchmark model into the sharded prediction contract."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
from numcodecs import Blosc
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
import zarr
|
| 14 |
+
|
| 15 |
+
from prediction_contract import DENSE_TRACKS, MAX_JUNCTION_PAIRS, MAX_USAGE_SITES, PREDICTION_SCHEMA
|
| 16 |
+
from reference.alphagenome_50m.dataset import AlphaGenomeDataset
|
| 17 |
+
from reference.alphagenome_50m.model import CompactModel, ModelConfig
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
COMPRESSOR = Blosc(cname="zstd", clevel=7, shuffle=Blosc.BITSHUFFLE)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def main(input_root: Path, output_root: Path, checkpoint: Path, split: str = "test") -> None:
|
| 24 |
+
payload = torch.load(checkpoint, map_location="cpu", weights_only=True)
|
| 25 |
+
config = ModelConfig(**payload["config"])
|
| 26 |
+
model = CompactModel(config)
|
| 27 |
+
model.load_state_dict(payload["model"], strict=True)
|
| 28 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 29 |
+
model.to(device).eval()
|
| 30 |
+
dataset = AlphaGenomeDataset(input_root, split, include_targets=False)
|
| 31 |
+
model.set_junction_track_halves(dataset.junction_track_halves)
|
| 32 |
+
output_root.mkdir(parents=True, exist_ok=True)
|
| 33 |
+
root = zarr.open_group(str(output_root / "predictions.zarr"), mode="w")
|
| 34 |
+
ids = []
|
| 35 |
+
with torch.inference_mode():
|
| 36 |
+
for sample in dataset:
|
| 37 |
+
example_id = sample["example_id"]
|
| 38 |
+
dna = sample["dna"][None].to(device)
|
| 39 |
+
trunk = model._trunk(dna)
|
| 40 |
+
dense_features = model._dense_features(trunk)
|
| 41 |
+
group = root.create_group(f"examples/{example_id}")
|
| 42 |
+
for family in DENSE_TRACKS:
|
| 43 |
+
values = model.dense_heads[family](dense_features)[0]
|
| 44 |
+
group.create_dataset(family, data=values.cpu().numpy().astype(np.float16), compressor=COMPRESSOR)
|
| 45 |
+
|
| 46 |
+
all_site_logits = model._splice_site_logits(trunk)
|
| 47 |
+
target_start = (config.input_length - config.target_length) // 2
|
| 48 |
+
group.create_dataset(
|
| 49 |
+
"splice_sites",
|
| 50 |
+
data=all_site_logits[0, target_start:target_start + config.target_length].cpu().numpy().astype(np.float16),
|
| 51 |
+
chunks=(4096, 4), compressor=COMPRESSOR,
|
| 52 |
+
)
|
| 53 |
+
predicted_positions = model.select_junction_positions(all_site_logits)[0]
|
| 54 |
+
|
| 55 |
+
# Usage at the model's own predicted sites (v4 is sparse; unlisted hidden sites score 0).
|
| 56 |
+
usage_bins = model.splice_usage_head(dense_features)[0].float()
|
| 57 |
+
sites = predicted_positions.cpu().numpy().astype(np.int64).reshape(-1)
|
| 58 |
+
sites = np.unique(sites[(sites >= target_start) & (sites < target_start + config.target_length)]
|
| 59 |
+
- target_start)[:MAX_USAGE_SITES]
|
| 60 |
+
group.create_dataset("splice_usage_positions", data=sites.astype(np.int32), compressor=COMPRESSOR)
|
| 61 |
+
usage = usage_bins[torch.as_tensor(sites // 128, device=usage_bins.device)] if len(sites) \
|
| 62 |
+
else usage_bins[:0]
|
| 63 |
+
group.create_dataset("splice_usage", data=usage.cpu().numpy().astype(np.float16),
|
| 64 |
+
chunks=(1024, 734), compressor=COMPRESSOR)
|
| 65 |
+
|
| 66 |
+
# Junctions: score every donor x acceptor pair of each strand, keep the strongest pairs.
|
| 67 |
+
positions_batch = predicted_positions[None]
|
| 68 |
+
site_factors = model.junction_site_factors(trunk, positions_batch)
|
| 69 |
+
halves = model.junction_track_half
|
| 70 |
+
candidates = []
|
| 71 |
+
for row_start in range(0, 512, 128):
|
| 72 |
+
for column_start in range(0, 512, 128):
|
| 73 |
+
block = torch.cat([
|
| 74 |
+
model.junction_block(
|
| 75 |
+
trunk, positions_batch, row_start, row_start + 128,
|
| 76 |
+
column_start, column_start + 128, track_start,
|
| 77 |
+
min(track_start + 64, config.junction_tracks), site_factors,
|
| 78 |
+
)[0]
|
| 79 |
+
for track_start in range(0, config.junction_tracks, 64)
|
| 80 |
+
], dim=-1).float() # [128, 128, 734]
|
| 81 |
+
for half in (0, 1):
|
| 82 |
+
donors = predicted_positions[2 * half, row_start:row_start + 128]
|
| 83 |
+
acceptors = predicted_positions[2 * half + 1, column_start:column_start + 128]
|
| 84 |
+
valid = (donors[:, None] >= 0) & (acceptors[None, :] >= 0)
|
| 85 |
+
strength = block[..., halves == half].amax(dim=-1).masked_fill(~valid, -torch.inf)
|
| 86 |
+
keep = min(MAX_JUNCTION_PAIRS // 2, int(valid.sum()))
|
| 87 |
+
if not keep:
|
| 88 |
+
continue
|
| 89 |
+
best = strength.flatten().topk(keep)
|
| 90 |
+
rows, columns = best.indices // 128, best.indices % 128
|
| 91 |
+
candidates.append((best.values, torch.full_like(rows, half), donors[rows],
|
| 92 |
+
acceptors[columns], block[rows, columns]))
|
| 93 |
+
if candidates:
|
| 94 |
+
score, half, donor, acceptor, values = (torch.cat(x) for x in zip(*candidates))
|
| 95 |
+
order = score.topk(min(MAX_JUNCTION_PAIRS, len(score))).indices
|
| 96 |
+
half, donor, acceptor, values = half[order], donor[order], acceptor[order], values[order]
|
| 97 |
+
else:
|
| 98 |
+
half = donor = acceptor = torch.zeros(0, dtype=torch.long)
|
| 99 |
+
values = torch.zeros(0, config.junction_tracks)
|
| 100 |
+
group.create_dataset("junction_half", data=half.cpu().numpy().astype(np.int8), compressor=COMPRESSOR)
|
| 101 |
+
group.create_dataset("junction_donor", data=donor.cpu().numpy().astype(np.int32), compressor=COMPRESSOR)
|
| 102 |
+
group.create_dataset("junction_acceptor", data=acceptor.cpu().numpy().astype(np.int32), compressor=COMPRESSOR)
|
| 103 |
+
group.create_dataset("junctions", data=values.cpu().numpy().astype(np.float16),
|
| 104 |
+
chunks=(4096, 734), compressor=COMPRESSOR)
|
| 105 |
+
|
| 106 |
+
contact = trunk.reshape(
|
| 107 |
+
1, config.contact_bins, -1, config.hidden_dim
|
| 108 |
+
).mean(dim=2)
|
| 109 |
+
q, k = model.contact_q(contact), model.contact_k(contact)
|
| 110 |
+
row, column = model.contact_row, model.contact_column
|
| 111 |
+
contact_values = 0.5 * (q[:, row] * k[:, column] + q[:, column] * k[:, row])
|
| 112 |
+
group.create_dataset(
|
| 113 |
+
"contact_maps", data=contact_values[0].cpu().numpy().astype(np.float16),
|
| 114 |
+
chunks=(8192, 28), compressor=COMPRESSOR,
|
| 115 |
+
)
|
| 116 |
+
ids.append(example_id)
|
| 117 |
+
print(json.dumps({"event": "predict", "example": len(ids), "total": len(dataset)}), flush=True)
|
| 118 |
+
root.attrs.update({"schema": PREDICTION_SCHEMA, "example_ids": ids})
|
| 119 |
+
(output_root / "example_ids.json").write_text(json.dumps(ids) + "\n")
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
if __name__ == "__main__":
|
| 123 |
+
parser = argparse.ArgumentParser()
|
| 124 |
+
parser.add_argument("input_root", type=Path)
|
| 125 |
+
parser.add_argument("output_root", type=Path)
|
| 126 |
+
parser.add_argument("--checkpoint", type=Path, default=Path(__file__).resolve().parent / "last.pt")
|
| 127 |
+
parser.add_argument("--split", default="test", choices=("valid", "test"),
|
| 128 |
+
help="manifest to predict; the verifier uses test, local validation uses valid")
|
| 129 |
+
args = parser.parse_args()
|
| 130 |
+
main(args.input_root, args.output_root, args.checkpoint, args.split)
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/prediction_contract.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Public prediction shapes; no trusted splice coordinates are exposed."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
DENSE_TRACKS = {
|
| 6 |
+
"atac": 167,
|
| 7 |
+
"dnase": 305,
|
| 8 |
+
"procap": 12,
|
| 9 |
+
"cage": 546,
|
| 10 |
+
"rna_seq": 667,
|
| 11 |
+
"chip_tf": 1_617,
|
| 12 |
+
"chip_histone": 1_116,
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
PREDICTION_SCHEMA = "genome-sequence-to-function-predictions/v4"
|
| 16 |
+
MAX_USAGE_SITES = 4_096
|
| 17 |
+
MAX_JUNCTION_PAIRS = 16_384
|
| 18 |
+
# Fixed-shape arrays per example; splice usage and junctions are sparse (see contract.md).
|
| 19 |
+
FIXED_SHAPES = {
|
| 20 |
+
**{name: (1_536, tracks) for name, tracks in DENSE_TRACKS.items()},
|
| 21 |
+
"splice_sites": (196_608, 4),
|
| 22 |
+
"contact_maps": (131_328, 28),
|
| 23 |
+
}
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""The reference model of the alphagenome-reference baseline."""
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/alphagenome_50m/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compact 1-Mb, eleven-family AlphaGenome reference model."""
|
| 2 |
+
|
| 3 |
+
from .model import CompactModel, ModelConfig, count_parameters
|
| 4 |
+
|
| 5 |
+
__all__ = ["CompactModel", "ModelConfig", "count_parameters"]
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/alphagenome_50m/alphagenome_50m.yaml
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
input_length: 1048576
|
| 2 |
+
target_length: 196608
|
| 3 |
+
dense_bin_size: 128
|
| 4 |
+
trunk_bin_size: 1024
|
| 5 |
+
contact_bin_size: 2048
|
| 6 |
+
stem_stride: 8
|
| 7 |
+
encoder_width: 32
|
| 8 |
+
channel_growth: 32
|
| 9 |
+
num_downsampling_blocks: 7
|
| 10 |
+
conv_kernel_size: 5
|
| 11 |
+
dna_kernel_size: 15
|
| 12 |
+
hidden_dim: 384
|
| 13 |
+
num_sequence_blocks: 6
|
| 14 |
+
num_attention_heads: 6
|
| 15 |
+
attention_head_dim: 64
|
| 16 |
+
mlp_expansion: 4.0
|
| 17 |
+
dropout: 0.0
|
| 18 |
+
head_hidden_size: 256
|
| 19 |
+
junction_rank: 32
|
| 20 |
+
splice_usage_tracks: 734
|
| 21 |
+
junction_tracks: 734
|
| 22 |
+
contact_tracks: 28
|
| 23 |
+
gradient_checkpointing: true
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/alphagenome_50m/dataset.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Streaming reader for the compact 1 Mb / eleven-family release."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections import OrderedDict
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import pysam
|
| 11 |
+
import torch
|
| 12 |
+
from torch.utils.data import Dataset
|
| 13 |
+
import zarr
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _open_part(path: Path):
|
| 17 |
+
if str(path).endswith(".zarr.zip"):
|
| 18 |
+
store = zarr.ZipStore(str(path), mode="r")
|
| 19 |
+
try:
|
| 20 |
+
return zarr.open_group(store=store, mode="r"), store
|
| 21 |
+
except BaseException:
|
| 22 |
+
store.close()
|
| 23 |
+
raise
|
| 24 |
+
return zarr.open_group(str(path), mode="r"), None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
DENSE_FAMILIES = (
|
| 28 |
+
"atac",
|
| 29 |
+
"dnase",
|
| 30 |
+
"procap",
|
| 31 |
+
"cage",
|
| 32 |
+
"rna_seq",
|
| 33 |
+
"chip_tf",
|
| 34 |
+
"chip_histone",
|
| 35 |
+
)
|
| 36 |
+
def normalize_splice_positions(value) -> np.ndarray:
|
| 37 |
+
"""Normalize Arrow's nested-list representation to the public [4, 512] array."""
|
| 38 |
+
|
| 39 |
+
outer = np.asarray(value, dtype=object).reshape(-1).tolist()
|
| 40 |
+
positions = np.stack([np.asarray(item, dtype=np.int64) for item in outer])
|
| 41 |
+
if positions.shape != (4, 512):
|
| 42 |
+
raise ValueError(f"splice_site_positions must have shape (4, 512), got {positions.shape}")
|
| 43 |
+
return positions
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class AlphaGenomeDataset(Dataset):
|
| 47 |
+
"""Resolve frozen coordinates to reference DNA and one Zarr example group."""
|
| 48 |
+
|
| 49 |
+
def __init__(
|
| 50 |
+
self,
|
| 51 |
+
data_root: str | Path,
|
| 52 |
+
split: str,
|
| 53 |
+
*,
|
| 54 |
+
max_open_parts: int = 8,
|
| 55 |
+
include_targets: bool = True,
|
| 56 |
+
) -> None:
|
| 57 |
+
self.root = Path(data_root)
|
| 58 |
+
self.split = split
|
| 59 |
+
manifest = self.root / "public" / f"{split}.parquet"
|
| 60 |
+
if not manifest.is_file():
|
| 61 |
+
raise FileNotFoundError(f"Missing materialized manifest: {manifest}")
|
| 62 |
+
self.rows = pd.read_parquet(manifest).reset_index(drop=True)
|
| 63 |
+
junction_tracks = pd.read_parquet(self.root / "public/junction_tracks.parquet")
|
| 64 |
+
junction_tracks = junction_tracks.sort_values("tensor_index")
|
| 65 |
+
self.junction_track_halves = torch.from_numpy(
|
| 66 |
+
junction_tracks.junction_channel_half.to_numpy(np.int64)
|
| 67 |
+
)
|
| 68 |
+
if include_targets:
|
| 69 |
+
labels_path = self.root / "labels" / f"{split}.parquet"
|
| 70 |
+
if not labels_path.is_file():
|
| 71 |
+
raise FileNotFoundError(f"Missing trusted labels manifest: {labels_path}")
|
| 72 |
+
labels = pd.read_parquet(labels_path).reset_index(drop=True)
|
| 73 |
+
if self.rows.example_id.astype(str).tolist() != labels.example_id.astype(str).tolist():
|
| 74 |
+
raise ValueError("public and labels manifests have different IDs/order")
|
| 75 |
+
self.rows = self.rows.merge(labels, on="example_id", validate="one_to_one", sort=False)
|
| 76 |
+
self.fasta_path = self.root / "reference" / "GRCh38.p13.genome.fa"
|
| 77 |
+
self.max_open_parts = max_open_parts
|
| 78 |
+
self.include_targets = include_targets
|
| 79 |
+
self._fasta = None
|
| 80 |
+
self._parts: OrderedDict[str, tuple[zarr.Group, object | None]] = OrderedDict()
|
| 81 |
+
|
| 82 |
+
def __len__(self) -> int:
|
| 83 |
+
return len(self.rows)
|
| 84 |
+
|
| 85 |
+
def _reference(self):
|
| 86 |
+
if self._fasta is None:
|
| 87 |
+
self._fasta = pysam.FastaFile(str(self.fasta_path))
|
| 88 |
+
return self._fasta
|
| 89 |
+
|
| 90 |
+
def _part(self, relative: str):
|
| 91 |
+
if relative in self._parts:
|
| 92 |
+
opened = self._parts.pop(relative)
|
| 93 |
+
self._parts[relative] = opened
|
| 94 |
+
return opened[0]
|
| 95 |
+
group, store = _open_part(self.root / relative)
|
| 96 |
+
if len(self._parts) >= self.max_open_parts:
|
| 97 |
+
_, (_, old_store) = self._parts.popitem(last=False)
|
| 98 |
+
if old_store is not None:
|
| 99 |
+
old_store.close()
|
| 100 |
+
self._parts[relative] = (group, store)
|
| 101 |
+
return group
|
| 102 |
+
|
| 103 |
+
@staticmethod
|
| 104 |
+
def _one_hot(sequence: str) -> np.ndarray:
|
| 105 |
+
encoded = np.frombuffer(sequence.upper().encode("ascii"), dtype=np.uint8)
|
| 106 |
+
output = np.zeros((len(encoded), 4), dtype=np.float32)
|
| 107 |
+
for index, letter in enumerate(b"ACGT"):
|
| 108 |
+
output[:, index] = encoded == letter
|
| 109 |
+
return output
|
| 110 |
+
|
| 111 |
+
def _sequence(self, row) -> tuple[np.ndarray, np.ndarray]:
|
| 112 |
+
reference = self._reference()
|
| 113 |
+
chromosome_length = reference.get_reference_length(str(row.chromosome))
|
| 114 |
+
start, end = int(row.input_start), int(row.input_end)
|
| 115 |
+
clipped_start, clipped_end = max(0, start), min(chromosome_length, end)
|
| 116 |
+
sequence = reference.fetch(str(row.chromosome), clipped_start, clipped_end)
|
| 117 |
+
left, right = clipped_start - start, end - clipped_end
|
| 118 |
+
if left or right:
|
| 119 |
+
sequence = "N" * left + sequence + "N" * right
|
| 120 |
+
valid = np.ones(end - start, dtype=bool)
|
| 121 |
+
if left:
|
| 122 |
+
valid[:left] = False
|
| 123 |
+
if right:
|
| 124 |
+
valid[-right:] = False
|
| 125 |
+
return self._one_hot(sequence), valid
|
| 126 |
+
|
| 127 |
+
@staticmethod
|
| 128 |
+
def _decode(example, name: str, *, asinh: bool) -> np.ndarray:
|
| 129 |
+
"""Train targets may be stored as 8-bit codes with per-track ranges; they are decoded
|
| 130 |
+
here, one example at a time, so the release stays compressed on disk."""
|
| 131 |
+
array = example[name]
|
| 132 |
+
if array.dtype != np.uint8:
|
| 133 |
+
return np.asarray(array, dtype=np.float32)
|
| 134 |
+
lo = np.asarray(example[f"{name}_lo"], dtype=np.float32)
|
| 135 |
+
hi = np.asarray(example[f"{name}_hi"], dtype=np.float32)
|
| 136 |
+
x = lo + np.asarray(array, dtype=np.float32) * ((hi - lo) / 255.0)
|
| 137 |
+
return np.sinh(x) if asinh else x
|
| 138 |
+
|
| 139 |
+
@staticmethod
|
| 140 |
+
def _dense_target(example, family: str) -> dict[str, torch.Tensor]:
|
| 141 |
+
values = AlphaGenomeDataset._decode(example, f"{family}/values", asinh=True)
|
| 142 |
+
mask = np.asarray(example[f"{family}/mask"], dtype=bool)
|
| 143 |
+
if mask.ndim == 1:
|
| 144 |
+
mask = np.broadcast_to(mask[None, :], values.shape).copy()
|
| 145 |
+
return {
|
| 146 |
+
"values": torch.from_numpy(values),
|
| 147 |
+
"mask": torch.from_numpy(mask),
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
def __getitem__(self, item: int):
|
| 151 |
+
row = self.rows.iloc[item]
|
| 152 |
+
dna, input_mask = self._sequence(row)
|
| 153 |
+
result = {
|
| 154 |
+
"example_id": str(row.example_id),
|
| 155 |
+
"dna": torch.from_numpy(dna),
|
| 156 |
+
"input_mask": torch.from_numpy(input_mask),
|
| 157 |
+
"junction_track_halves": self.junction_track_halves,
|
| 158 |
+
}
|
| 159 |
+
if not self.include_targets:
|
| 160 |
+
return result
|
| 161 |
+
|
| 162 |
+
part = self._part(str(row.target_shard))
|
| 163 |
+
example = part[str(row.target_group)]
|
| 164 |
+
result["dense"] = {
|
| 165 |
+
family: self._dense_target(example, family) for family in DENSE_FAMILIES
|
| 166 |
+
}
|
| 167 |
+
result["splice_sites"] = torch.from_numpy(
|
| 168 |
+
np.asarray(example["splice_sites/values"], dtype=np.float32)
|
| 169 |
+
)
|
| 170 |
+
result["splice_usage"] = {
|
| 171 |
+
"positions": torch.from_numpy(
|
| 172 |
+
np.asarray(example["splice_site_usage/positions"], dtype=np.int64)
|
| 173 |
+
),
|
| 174 |
+
"values": torch.from_numpy(
|
| 175 |
+
np.asarray(example["splice_site_usage/values"], dtype=np.float32)
|
| 176 |
+
),
|
| 177 |
+
"mask": torch.from_numpy(
|
| 178 |
+
np.asarray(example["splice_site_usage/mask"], dtype=bool)
|
| 179 |
+
),
|
| 180 |
+
}
|
| 181 |
+
result["usage_positions"] = result["splice_usage"]["positions"]
|
| 182 |
+
result["junctions"] = {
|
| 183 |
+
name: torch.from_numpy(
|
| 184 |
+
np.asarray(
|
| 185 |
+
example[f"splice_junctions/{name}"],
|
| 186 |
+
dtype=np.float32 if name == "value" else np.int64,
|
| 187 |
+
)
|
| 188 |
+
)
|
| 189 |
+
for name in ("row", "column", "track", "value")
|
| 190 |
+
}
|
| 191 |
+
result["junctions"]["site_positions"] = torch.from_numpy(
|
| 192 |
+
np.asarray(example["splice_junctions/site_positions"], dtype=np.int64)
|
| 193 |
+
)
|
| 194 |
+
site_positions = normalize_splice_positions(row.splice_site_positions)
|
| 195 |
+
result["site_positions"] = torch.from_numpy(site_positions)
|
| 196 |
+
if not torch.equal(result["junctions"]["site_positions"], result["site_positions"]):
|
| 197 |
+
raise ValueError(f"public/private splice positions differ for {row.example_id}")
|
| 198 |
+
scoring_path = self.root / "scoring" / self.split / f"part-{item:06d}.parquet"
|
| 199 |
+
scoring = pd.read_parquet(scoring_path)
|
| 200 |
+
if not (scoring.example_id.astype(str) == str(row.example_id)).all():
|
| 201 |
+
raise ValueError(f"scoring part ID differs for {row.example_id}")
|
| 202 |
+
result["junction_scoring"] = {
|
| 203 |
+
"donor_position": torch.from_numpy(
|
| 204 |
+
scoring.donor_position.to_numpy(np.int64)
|
| 205 |
+
),
|
| 206 |
+
"acceptor_position": torch.from_numpy(
|
| 207 |
+
scoring.acceptor_position.to_numpy(np.int64)
|
| 208 |
+
),
|
| 209 |
+
"track": torch.from_numpy(scoring.track.to_numpy(np.int64)),
|
| 210 |
+
"target_value": torch.from_numpy(
|
| 211 |
+
scoring.target_value.to_numpy(np.float32)
|
| 212 |
+
),
|
| 213 |
+
"valid": torch.from_numpy(scoring.valid.to_numpy(bool)),
|
| 214 |
+
}
|
| 215 |
+
result["contact_maps"] = torch.from_numpy(
|
| 216 |
+
self._decode(example, "contact_maps/upper_triangle", asinh=False)
|
| 217 |
+
)
|
| 218 |
+
result["contact_map_mask"] = torch.from_numpy(
|
| 219 |
+
np.asarray(example["contact_maps/mask"], dtype=bool)
|
| 220 |
+
)
|
| 221 |
+
return result
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def single_example_collate(items):
|
| 225 |
+
"""Keep variable-size event tensors intact; the reference currently trains at batch one."""
|
| 226 |
+
|
| 227 |
+
if len(items) != 1:
|
| 228 |
+
raise ValueError("The compact event loader currently requires batch_size=1")
|
| 229 |
+
return items[0]
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/alphagenome_50m/layers.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared neural-network layers for the single compact AlphaGenome model."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch import Tensor, nn
|
| 9 |
+
from torch.nn import functional as F
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ChannelRMSNorm(nn.Module):
|
| 13 |
+
def __init__(self, channels: int, eps: float = 1e-6):
|
| 14 |
+
super().__init__()
|
| 15 |
+
self.weight = nn.Parameter(torch.ones(channels))
|
| 16 |
+
self.eps = eps
|
| 17 |
+
|
| 18 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 19 |
+
variance = x.float().square().mean(dim=1, keepdim=True)
|
| 20 |
+
normalized = x * torch.rsqrt(variance + self.eps).to(x.dtype)
|
| 21 |
+
return normalized * self.weight[None, :, None].to(x.dtype)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class StandardizedConv1d(nn.Conv1d):
|
| 25 |
+
def __init__(self, in_channels: int, out_channels: int, kernel_size: int):
|
| 26 |
+
super().__init__(in_channels, out_channels, kernel_size, padding="same", bias=True)
|
| 27 |
+
self.scale = nn.Parameter(torch.ones(out_channels))
|
| 28 |
+
nn.init.trunc_normal_(self.weight, std=1.0 / math.sqrt(in_channels * kernel_size))
|
| 29 |
+
nn.init.trunc_normal_(self.bias, std=1e-4)
|
| 30 |
+
|
| 31 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 32 |
+
centered = self.weight - self.weight.mean(dim=(1, 2), keepdim=True)
|
| 33 |
+
variance = centered.float().square().mean(dim=(1, 2), keepdim=True)
|
| 34 |
+
fan_in = self.weight.shape[1] * self.weight.shape[2]
|
| 35 |
+
multiplier = self.scale[:, None, None] * torch.rsqrt(
|
| 36 |
+
(fan_in * variance).clamp_min(1e-4)
|
| 37 |
+
).to(self.weight.dtype)
|
| 38 |
+
return F.conv1d(x, centered * multiplier, self.bias, padding="same")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class ConvBlock(nn.Module):
|
| 42 |
+
def __init__(self, in_channels: int, out_channels: int, kernel_size: int):
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.norm = ChannelRMSNorm(in_channels)
|
| 45 |
+
self.conv = StandardizedConv1d(in_channels, out_channels, kernel_size)
|
| 46 |
+
|
| 47 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 48 |
+
return self.conv(F.gelu(self.norm(x), approximate="tanh"))
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _apply_rope(x: Tensor) -> Tensor:
|
| 52 |
+
rotary_dim = x.shape[-1] - x.shape[-1] % 2
|
| 53 |
+
if rotary_dim == 0:
|
| 54 |
+
return x
|
| 55 |
+
positions = torch.arange(x.shape[-2], device=x.device, dtype=torch.float32)
|
| 56 |
+
inverse_frequency = 1.0 / (
|
| 57 |
+
10_000 ** (
|
| 58 |
+
torch.arange(0, rotary_dim, 2, device=x.device, dtype=torch.float32)
|
| 59 |
+
/ rotary_dim
|
| 60 |
+
)
|
| 61 |
+
)
|
| 62 |
+
angles = torch.outer(positions, inverse_frequency)
|
| 63 |
+
cos = angles.cos()[None, None, :, :].to(x.dtype)
|
| 64 |
+
sin = angles.sin()[None, None, :, :].to(x.dtype)
|
| 65 |
+
even, odd = x[..., :rotary_dim:2], x[..., 1:rotary_dim:2]
|
| 66 |
+
rotated = torch.stack((even * cos - odd * sin, even * sin + odd * cos), dim=-1)
|
| 67 |
+
return torch.cat((rotated.flatten(-2), x[..., rotary_dim:]), dim=-1)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class MultiHeadAttention(nn.Module):
|
| 71 |
+
def __init__(self, config):
|
| 72 |
+
super().__init__()
|
| 73 |
+
self.num_heads = config.num_attention_heads
|
| 74 |
+
self.head_dim = config.attention_head_dim
|
| 75 |
+
inner_dim = self.num_heads * self.head_dim
|
| 76 |
+
self.norm = nn.RMSNorm(config.hidden_dim)
|
| 77 |
+
self.qkv = nn.Linear(config.hidden_dim, 3 * inner_dim, bias=False)
|
| 78 |
+
self.output = nn.Linear(inner_dim, config.hidden_dim)
|
| 79 |
+
self.dropout = config.dropout
|
| 80 |
+
nn.init.trunc_normal_(self.output.weight, std=1e-3)
|
| 81 |
+
nn.init.zeros_(self.output.bias)
|
| 82 |
+
|
| 83 |
+
def forward(self, x: Tensor, attention_bias: Tensor | None = None) -> Tensor:
|
| 84 |
+
batch, length, _ = x.shape
|
| 85 |
+
qkv = self.qkv(self.norm(x)).view(
|
| 86 |
+
batch, length, 3, self.num_heads, self.head_dim
|
| 87 |
+
)
|
| 88 |
+
q, k, value = qkv.unbind(dim=2)
|
| 89 |
+
attended = F.scaled_dot_product_attention(
|
| 90 |
+
_apply_rope(q.transpose(1, 2)),
|
| 91 |
+
_apply_rope(k.transpose(1, 2)),
|
| 92 |
+
value.transpose(1, 2),
|
| 93 |
+
attn_mask=attention_bias,
|
| 94 |
+
dropout_p=self.dropout if self.training else 0.0,
|
| 95 |
+
)
|
| 96 |
+
return self.output(attended.transpose(1, 2).reshape(batch, length, -1))
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class MLPBlock(nn.Module):
|
| 100 |
+
def __init__(self, config):
|
| 101 |
+
super().__init__()
|
| 102 |
+
expanded = int(config.hidden_dim * config.mlp_expansion)
|
| 103 |
+
self.norm = nn.RMSNorm(config.hidden_dim)
|
| 104 |
+
self.input = nn.Linear(config.hidden_dim, expanded)
|
| 105 |
+
self.output = nn.Linear(expanded, config.hidden_dim)
|
| 106 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 107 |
+
nn.init.trunc_normal_(self.output.weight, std=1e-3)
|
| 108 |
+
nn.init.zeros_(self.output.bias)
|
| 109 |
+
|
| 110 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 111 |
+
return self.dropout(
|
| 112 |
+
self.output(F.gelu(self.input(self.norm(x)), approximate="tanh"))
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class SequenceBlock(nn.Module):
|
| 117 |
+
def __init__(self, config):
|
| 118 |
+
super().__init__()
|
| 119 |
+
self.attention = MultiHeadAttention(config)
|
| 120 |
+
self.mlp = MLPBlock(config)
|
| 121 |
+
|
| 122 |
+
def forward(self, x: Tensor, attention_bias: Tensor | None = None) -> Tensor:
|
| 123 |
+
x = x + self.attention(x, attention_bias)
|
| 124 |
+
return x + self.mlp(x)
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/alphagenome_50m/model.py
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Affordable multi-resolution baseline for the compact AlphaGenome task."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import asdict, dataclass, fields
|
| 6 |
+
import math
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any, Iterable
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from torch import Tensor, nn
|
| 12 |
+
from torch.nn import functional as F
|
| 13 |
+
from torch.utils.checkpoint import checkpoint
|
| 14 |
+
import yaml
|
| 15 |
+
|
| 16 |
+
from .layers import ChannelRMSNorm, ConvBlock, SequenceBlock
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
DENSE_TRACKS = {
|
| 20 |
+
"atac": 167,
|
| 21 |
+
"dnase": 305,
|
| 22 |
+
"procap": 12,
|
| 23 |
+
"cage": 546,
|
| 24 |
+
"rna_seq": 667,
|
| 25 |
+
"chip_tf": 1_617,
|
| 26 |
+
"chip_histone": 1_116,
|
| 27 |
+
}
|
| 28 |
+
ALL_FAMILIES = (*DENSE_TRACKS, "splice_sites", "splice_usage", "junctions", "contact_maps")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass(frozen=True)
|
| 32 |
+
class ModelConfig:
|
| 33 |
+
input_length: int = 1_048_576
|
| 34 |
+
target_length: int = 196_608
|
| 35 |
+
dense_bin_size: int = 128
|
| 36 |
+
trunk_bin_size: int = 1_024
|
| 37 |
+
contact_bin_size: int = 2_048
|
| 38 |
+
stem_stride: int = 8
|
| 39 |
+
encoder_width: int = 32
|
| 40 |
+
channel_growth: int = 32
|
| 41 |
+
num_downsampling_blocks: int = 7
|
| 42 |
+
conv_kernel_size: int = 5
|
| 43 |
+
dna_kernel_size: int = 15
|
| 44 |
+
hidden_dim: int = 384
|
| 45 |
+
num_sequence_blocks: int = 6
|
| 46 |
+
num_attention_heads: int = 6
|
| 47 |
+
attention_head_dim: int = 64
|
| 48 |
+
mlp_expansion: float = 4.0
|
| 49 |
+
dropout: float = 0.0
|
| 50 |
+
head_hidden_size: int = 256
|
| 51 |
+
junction_rank: int = 32
|
| 52 |
+
splice_usage_tracks: int = 734
|
| 53 |
+
junction_tracks: int = 734
|
| 54 |
+
contact_tracks: int = 28
|
| 55 |
+
gradient_checkpointing: bool = True
|
| 56 |
+
enable_pairwise: bool = False
|
| 57 |
+
pair_width: int = 32
|
| 58 |
+
pair_downsample: int = 16
|
| 59 |
+
pair_update_interval: int = 2
|
| 60 |
+
local_width: int = 0
|
| 61 |
+
|
| 62 |
+
def __post_init__(self) -> None:
|
| 63 |
+
downsample = self.stem_stride * 2**self.num_downsampling_blocks
|
| 64 |
+
if downsample != self.trunk_bin_size:
|
| 65 |
+
raise ValueError("stem_stride * 2**num_downsampling_blocks must equal trunk_bin_size")
|
| 66 |
+
for length in (self.input_length, self.target_length):
|
| 67 |
+
if length % self.trunk_bin_size:
|
| 68 |
+
raise ValueError("input and target lengths must divide by trunk_bin_size")
|
| 69 |
+
if self.trunk_bin_size % self.dense_bin_size:
|
| 70 |
+
raise ValueError("trunk_bin_size must divide by dense_bin_size")
|
| 71 |
+
if self.input_length % self.contact_bin_size:
|
| 72 |
+
raise ValueError("input_length must divide by contact_bin_size")
|
| 73 |
+
if self.hidden_dim <= 0 or self.num_attention_heads <= 0:
|
| 74 |
+
raise ValueError("hidden dimensions and attention heads must be positive")
|
| 75 |
+
|
| 76 |
+
@property
|
| 77 |
+
def trunk_bins(self) -> int:
|
| 78 |
+
return self.input_length // self.trunk_bin_size
|
| 79 |
+
|
| 80 |
+
@property
|
| 81 |
+
def target_trunk_bins(self) -> int:
|
| 82 |
+
return self.target_length // self.trunk_bin_size
|
| 83 |
+
|
| 84 |
+
@property
|
| 85 |
+
def dense_bins(self) -> int:
|
| 86 |
+
return self.target_length // self.dense_bin_size
|
| 87 |
+
|
| 88 |
+
@property
|
| 89 |
+
def dense_upsample(self) -> int:
|
| 90 |
+
return self.trunk_bin_size // self.dense_bin_size
|
| 91 |
+
|
| 92 |
+
@property
|
| 93 |
+
def contact_bins(self) -> int:
|
| 94 |
+
return self.input_length // self.contact_bin_size
|
| 95 |
+
|
| 96 |
+
@property
|
| 97 |
+
def encoder_output_width(self) -> int:
|
| 98 |
+
return self.encoder_width + self.channel_growth * self.num_downsampling_blocks
|
| 99 |
+
|
| 100 |
+
@classmethod
|
| 101 |
+
def from_yaml(cls, path: str | Path) -> "ModelConfig":
|
| 102 |
+
values: dict[str, Any] = yaml.safe_load(Path(path).read_text()) or {}
|
| 103 |
+
known = {field.name for field in fields(cls)}
|
| 104 |
+
unknown = sorted(values.keys() - known)
|
| 105 |
+
if unknown:
|
| 106 |
+
raise ValueError(f"Unknown model configuration keys: {unknown}")
|
| 107 |
+
return cls(**values)
|
| 108 |
+
|
| 109 |
+
def to_dict(self) -> dict[str, Any]:
|
| 110 |
+
return asdict(self)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class SequenceEncoder(nn.Module):
|
| 114 |
+
def __init__(self, config: ModelConfig):
|
| 115 |
+
super().__init__()
|
| 116 |
+
self.stem = nn.Conv1d(
|
| 117 |
+
4,
|
| 118 |
+
config.encoder_width,
|
| 119 |
+
config.dna_kernel_size,
|
| 120 |
+
stride=config.stem_stride,
|
| 121 |
+
padding=config.dna_kernel_size // 2,
|
| 122 |
+
)
|
| 123 |
+
blocks = []
|
| 124 |
+
width = config.encoder_width
|
| 125 |
+
for _ in range(config.num_downsampling_blocks):
|
| 126 |
+
output_width = width + config.channel_growth
|
| 127 |
+
blocks.append(ConvBlock(width, output_width, config.conv_kernel_size))
|
| 128 |
+
width = output_width
|
| 129 |
+
self.blocks = nn.ModuleList(blocks)
|
| 130 |
+
|
| 131 |
+
def forward(self, dna: Tensor) -> Tensor:
|
| 132 |
+
x = F.gelu(self.stem(dna.transpose(1, 2)), approximate="tanh")
|
| 133 |
+
for block in self.blocks:
|
| 134 |
+
x = F.max_pool1d(block(x), kernel_size=2, stride=2)
|
| 135 |
+
return x.transpose(1, 2)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class LocalResidualBlock(nn.Module):
|
| 139 |
+
def __init__(self, width: int, dilation: int):
|
| 140 |
+
super().__init__()
|
| 141 |
+
self.norm = ChannelRMSNorm(width)
|
| 142 |
+
self.depthwise = nn.Conv1d(width, width, 9, dilation=dilation,
|
| 143 |
+
padding=4 * dilation, groups=width)
|
| 144 |
+
self.expand = nn.Conv1d(width, 2 * width, 1)
|
| 145 |
+
self.contract = nn.Conv1d(2 * width, width, 1)
|
| 146 |
+
|
| 147 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 148 |
+
update = self.depthwise(self.norm(x))
|
| 149 |
+
update = self.contract(F.gelu(self.expand(update), approximate='tanh'))
|
| 150 |
+
return x + update
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class LocalSequencePath(nn.Module):
|
| 154 |
+
"""Base-resolution motif path; 701-bp receptive field and aligned 128-bp pooling."""
|
| 155 |
+
def __init__(self, config: ModelConfig):
|
| 156 |
+
super().__init__()
|
| 157 |
+
width = config.local_width
|
| 158 |
+
self.stem = nn.Conv1d(4, width, 21, padding=10)
|
| 159 |
+
self.blocks = nn.Sequential(*(LocalResidualBlock(width, d) for d in [1, 4, 16, 64]))
|
| 160 |
+
self.norm = ChannelRMSNorm(width)
|
| 161 |
+
self.sites = nn.Conv1d(width, 4, 1)
|
| 162 |
+
self.bin_size = config.dense_bin_size
|
| 163 |
+
|
| 164 |
+
def forward(self, dna: Tensor) -> tuple[Tensor, Tensor]:
|
| 165 |
+
base = F.gelu(self.stem(dna), approximate='tanh')
|
| 166 |
+
base = F.gelu(self.norm(self.blocks(base)), approximate='tanh')
|
| 167 |
+
sites = self.sites(base).transpose(1, 2)
|
| 168 |
+
pooled = torch.cat((F.avg_pool1d(base, self.bin_size),
|
| 169 |
+
F.max_pool1d(base, self.bin_size)), dim=1).transpose(1, 2)
|
| 170 |
+
return sites, pooled
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class CompactModel(nn.Module):
|
| 174 |
+
"""One shared 1-kb trunk with representation-specific output heads."""
|
| 175 |
+
|
| 176 |
+
def __init__(self, config: ModelConfig | None = None):
|
| 177 |
+
super().__init__()
|
| 178 |
+
self.config = config or ModelConfig()
|
| 179 |
+
self.encoder = SequenceEncoder(self.config)
|
| 180 |
+
self.projection = nn.Linear(self.config.encoder_output_width, self.config.hidden_dim)
|
| 181 |
+
self.blocks = nn.ModuleList(
|
| 182 |
+
SequenceBlock(self.config) for _ in range(self.config.num_sequence_blocks)
|
| 183 |
+
)
|
| 184 |
+
self.final_norm = nn.RMSNorm(self.config.hidden_dim)
|
| 185 |
+
self.dense_decoder = nn.Sequential(
|
| 186 |
+
nn.RMSNorm(self.config.hidden_dim),
|
| 187 |
+
nn.Linear(self.config.hidden_dim, self.config.head_hidden_size),
|
| 188 |
+
nn.GELU(approximate="tanh"),
|
| 189 |
+
)
|
| 190 |
+
self.dense_heads = nn.ModuleDict(
|
| 191 |
+
{
|
| 192 |
+
family: nn.Linear(self.config.head_hidden_size, tracks)
|
| 193 |
+
for family, tracks in DENSE_TRACKS.items()
|
| 194 |
+
}
|
| 195 |
+
)
|
| 196 |
+
self.splice_site_head = nn.Linear(
|
| 197 |
+
self.config.head_hidden_size, self.config.dense_bin_size * 4
|
| 198 |
+
)
|
| 199 |
+
self.splice_usage_head = nn.Linear(
|
| 200 |
+
self.config.head_hidden_size, self.config.splice_usage_tracks
|
| 201 |
+
)
|
| 202 |
+
rank = self.config.junction_rank
|
| 203 |
+
self.junction_source = nn.Linear(self.config.head_hidden_size, rank)
|
| 204 |
+
self.junction_destination = nn.Linear(self.config.head_hidden_size, rank)
|
| 205 |
+
self.junction_track = nn.Embedding(self.config.junction_tracks, rank)
|
| 206 |
+
if self.config.junction_tracks % 2:
|
| 207 |
+
raise ValueError("junction tracks must split evenly into strand halves")
|
| 208 |
+
self.register_buffer(
|
| 209 |
+
"junction_track_half",
|
| 210 |
+
torch.arange(self.config.junction_tracks) // (self.config.junction_tracks // 2),
|
| 211 |
+
persistent=False,
|
| 212 |
+
)
|
| 213 |
+
self.contact_q = nn.Linear(self.config.hidden_dim, self.config.contact_tracks)
|
| 214 |
+
self.contact_k = nn.Linear(self.config.hidden_dim, self.config.contact_tracks)
|
| 215 |
+
row, column = torch.triu_indices(
|
| 216 |
+
self.config.contact_bins, self.config.contact_bins
|
| 217 |
+
)
|
| 218 |
+
self.register_buffer("contact_row", row, persistent=False)
|
| 219 |
+
self.register_buffer("contact_column", column, persistent=False)
|
| 220 |
+
if self.config.local_width:
|
| 221 |
+
self.local_path = LocalSequencePath(self.config)
|
| 222 |
+
self.local_projection = nn.Linear(2 * self.config.local_width, self.config.head_hidden_size)
|
| 223 |
+
# A new local path can be attached to our own checkpoint without changing its initial outputs.
|
| 224 |
+
nn.init.zeros_(self.local_path.sites.weight)
|
| 225 |
+
nn.init.zeros_(self.local_path.sites.bias)
|
| 226 |
+
nn.init.zeros_(self.local_projection.weight)
|
| 227 |
+
nn.init.zeros_(self.local_projection.bias)
|
| 228 |
+
self._local_sites = None
|
| 229 |
+
self._local_features = None
|
| 230 |
+
|
| 231 |
+
def set_junction_track_halves(self, halves: Tensor) -> None:
|
| 232 |
+
halves = torch.as_tensor(halves, dtype=torch.long, device=self.junction_track_half.device)
|
| 233 |
+
if halves.shape != (self.config.junction_tracks,) or not torch.isin(
|
| 234 |
+
halves, torch.tensor([0, 1], device=halves.device)
|
| 235 |
+
).all():
|
| 236 |
+
raise ValueError("junction track halves must be a 734-element 0/1 mapping")
|
| 237 |
+
self.junction_track_half.copy_(halves)
|
| 238 |
+
|
| 239 |
+
def _trunk(self, dna: Tensor) -> Tensor:
|
| 240 |
+
if dna.ndim != 3 or dna.shape[1:] != (self.config.input_length, 4):
|
| 241 |
+
raise ValueError(
|
| 242 |
+
f"Expected DNA [B,{self.config.input_length},4], got {tuple(dna.shape)}"
|
| 243 |
+
)
|
| 244 |
+
if self.config.local_width:
|
| 245 |
+
if self.config.gradient_checkpointing and self.training:
|
| 246 |
+
sites, pooled = checkpoint(self.local_path, dna.transpose(1, 2), use_reentrant=False)
|
| 247 |
+
else:
|
| 248 |
+
sites, pooled = self.local_path(dna.transpose(1, 2))
|
| 249 |
+
self._local_sites = sites
|
| 250 |
+
self._local_features = self.local_projection(pooled)
|
| 251 |
+
x = self.projection(self.encoder(dna))
|
| 252 |
+
for block in self.blocks:
|
| 253 |
+
if self.config.gradient_checkpointing and self.training and x.requires_grad:
|
| 254 |
+
x = checkpoint(block, x, None, use_reentrant=False)
|
| 255 |
+
else:
|
| 256 |
+
x = block(x, None)
|
| 257 |
+
return self.final_norm(x)
|
| 258 |
+
|
| 259 |
+
def _dense_features(self, trunk: Tensor) -> Tensor:
|
| 260 |
+
start = (self.config.trunk_bins - self.config.target_trunk_bins) // 2
|
| 261 |
+
target = trunk[:, start : start + self.config.target_trunk_bins]
|
| 262 |
+
target = target.repeat_interleave(self.config.dense_upsample, dim=1)
|
| 263 |
+
features = self.dense_decoder(target)
|
| 264 |
+
if self.config.local_width:
|
| 265 |
+
first_bin = (self.config.input_length - self.config.target_length) // (2 * self.config.dense_bin_size)
|
| 266 |
+
features = features + self._local_features[:, first_bin:first_bin + self.config.dense_bins]
|
| 267 |
+
return features
|
| 268 |
+
|
| 269 |
+
def _all_dense_features(self, trunk: Tensor) -> Tensor:
|
| 270 |
+
features = self.dense_decoder(
|
| 271 |
+
trunk.repeat_interleave(self.config.dense_upsample, dim=1)
|
| 272 |
+
)
|
| 273 |
+
return features + self._local_features if self.config.local_width else features
|
| 274 |
+
|
| 275 |
+
def _splice_site_logits(self, trunk: Tensor) -> Tensor:
|
| 276 |
+
logits = self.splice_site_head(self._all_dense_features(trunk))
|
| 277 |
+
logits = logits.view(len(trunk), self.config.input_length, 4)
|
| 278 |
+
if self.config.local_width:
|
| 279 |
+
logits = logits + self._local_sites
|
| 280 |
+
return logits.float()
|
| 281 |
+
|
| 282 |
+
def _position_features(self, trunk: Tensor, positions: Tensor) -> Tensor:
|
| 283 |
+
features = self.dense_decoder(self._gather_bins(trunk, positions, self.config.trunk_bin_size))
|
| 284 |
+
if self.config.local_width:
|
| 285 |
+
features = features + self._gather_bins(self._local_features, positions, self.config.dense_bin_size)
|
| 286 |
+
return features
|
| 287 |
+
|
| 288 |
+
@staticmethod
|
| 289 |
+
def select_junction_positions(site_logits: Tensor, limit: int = 512) -> Tensor:
|
| 290 |
+
"""Select each site type from model scores alone, then sort by coordinate.
|
| 291 |
+
|
| 292 |
+
This follows the four independent site classes in Google DeepMind's
|
| 293 |
+
AlphaGenome splicing implementation (pinned in docs/v3-author/PROTOCOL.md). Padding is
|
| 294 |
+
-1 when an input is shorter than ``limit``.
|
| 295 |
+
"""
|
| 296 |
+
count = min(limit, site_logits.shape[1])
|
| 297 |
+
selected = []
|
| 298 |
+
for site_type in range(4):
|
| 299 |
+
coordinates = torch.topk(site_logits[..., site_type], count, dim=1).indices
|
| 300 |
+
coordinates = coordinates.sort(dim=1).values
|
| 301 |
+
if count < limit:
|
| 302 |
+
coordinates = F.pad(coordinates, (0, limit - count), value=-1)
|
| 303 |
+
selected.append(coordinates)
|
| 304 |
+
return torch.stack(selected, dim=1)
|
| 305 |
+
|
| 306 |
+
@staticmethod
|
| 307 |
+
def _gather_bins(features: Tensor, positions: Tensor, bin_size: int) -> Tensor:
|
| 308 |
+
indices = torch.div(positions, bin_size, rounding_mode="floor")
|
| 309 |
+
indices = indices.clamp(0, features.shape[1] - 1)
|
| 310 |
+
return torch.gather(
|
| 311 |
+
features,
|
| 312 |
+
1,
|
| 313 |
+
indices[..., None].expand(-1, -1, features.shape[-1]),
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
def _junction_predictions(
|
| 317 |
+
self, trunk: Tensor, site_positions: Tensor, queries: Tensor
|
| 318 |
+
) -> Tensor:
|
| 319 |
+
row, column, track = queries.unbind(dim=-1)
|
| 320 |
+
half = self.junction_track_half[track]
|
| 321 |
+
batch = torch.arange(len(trunk), device=trunk.device)[:, None]
|
| 322 |
+
donor = site_positions[batch, 2 * half, row]
|
| 323 |
+
acceptor = site_positions[batch, 2 * half + 1, column]
|
| 324 |
+
source = self._position_features(trunk, donor.clamp(0, self.config.input_length - 1))
|
| 325 |
+
destination = self._position_features(trunk, acceptor.clamp(0, self.config.input_length - 1))
|
| 326 |
+
interaction = self.junction_source(source) * self.junction_destination(destination)
|
| 327 |
+
track_embedding = self.junction_track(track)
|
| 328 |
+
return (interaction * track_embedding).sum(dim=-1) / math.sqrt(
|
| 329 |
+
self.config.junction_rank
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
def junction_block(
|
| 333 |
+
self,
|
| 334 |
+
trunk: Tensor,
|
| 335 |
+
site_positions: Tensor,
|
| 336 |
+
row_start: int,
|
| 337 |
+
row_end: int,
|
| 338 |
+
column_start: int,
|
| 339 |
+
column_end: int,
|
| 340 |
+
track_start: int,
|
| 341 |
+
track_end: int,
|
| 342 |
+
site_factors: tuple[Tensor, Tensor] | None = None,
|
| 343 |
+
) -> Tensor:
|
| 344 |
+
"""Compute a bounded block of the full predicted-position junction cube."""
|
| 345 |
+
tracks = torch.arange(track_start, track_end, device=trunk.device)
|
| 346 |
+
halves = self.junction_track_half[tracks]
|
| 347 |
+
if site_factors is None:
|
| 348 |
+
site_factors = self.junction_site_factors(trunk, site_positions)
|
| 349 |
+
source_all, destination_all = site_factors
|
| 350 |
+
source = source_all[:, halves, row_start:row_end]
|
| 351 |
+
destination = destination_all[:, halves, column_start:column_end]
|
| 352 |
+
embedding = self.junction_track(tracks)[None, :, None, None, :]
|
| 353 |
+
values = (
|
| 354 |
+
source[:, :, :, None, :] * destination[:, :, None, :, :] * embedding
|
| 355 |
+
).sum(dim=-1) / math.sqrt(self.config.junction_rank)
|
| 356 |
+
return values.permute(0, 2, 3, 1).float()
|
| 357 |
+
|
| 358 |
+
def junction_site_factors(
|
| 359 |
+
self, trunk: Tensor, site_positions: Tensor
|
| 360 |
+
) -> tuple[Tensor, Tensor]:
|
| 361 |
+
"""Precompute the two strand-specific factors reused by all cube blocks."""
|
| 362 |
+
donor = torch.stack((site_positions[:, 0], site_positions[:, 2]), dim=1).clamp_min(0)
|
| 363 |
+
acceptor = torch.stack((site_positions[:, 1], site_positions[:, 3]), dim=1).clamp_min(0)
|
| 364 |
+
donor_features = self._position_features(trunk, donor.reshape(len(trunk), -1)).reshape(
|
| 365 |
+
len(trunk), 2, donor.shape[-1], -1)
|
| 366 |
+
acceptor_features = self._position_features(trunk, acceptor.reshape(len(trunk), -1)).reshape(
|
| 367 |
+
len(trunk), 2, acceptor.shape[-1], -1)
|
| 368 |
+
return self.junction_source(donor_features), self.junction_destination(acceptor_features)
|
| 369 |
+
|
| 370 |
+
def forward(
|
| 371 |
+
self,
|
| 372 |
+
dna: Tensor,
|
| 373 |
+
*,
|
| 374 |
+
families: Iterable[str] | None = None,
|
| 375 |
+
usage_positions: Tensor | None = None,
|
| 376 |
+
junction_site_positions: Tensor | None = None,
|
| 377 |
+
junction_queries: Tensor | None = None,
|
| 378 |
+
) -> dict[str, Tensor]:
|
| 379 |
+
requested = set(families or ALL_FAMILIES)
|
| 380 |
+
unknown = requested - set(ALL_FAMILIES)
|
| 381 |
+
if unknown:
|
| 382 |
+
raise ValueError(f"Unknown output families: {sorted(unknown)}")
|
| 383 |
+
trunk = self._trunk(dna)
|
| 384 |
+
needs_dense = bool(
|
| 385 |
+
requested.intersection((*DENSE_TRACKS, "splice_sites", "splice_usage", "junctions"))
|
| 386 |
+
)
|
| 387 |
+
features = self._dense_features(trunk) if needs_dense else None
|
| 388 |
+
outputs: dict[str, Tensor] = {}
|
| 389 |
+
for family in DENSE_TRACKS:
|
| 390 |
+
if family in requested:
|
| 391 |
+
outputs[family] = self.dense_heads[family](features).float()
|
| 392 |
+
if "splice_sites" in requested:
|
| 393 |
+
all_logits = self._splice_site_logits(trunk)
|
| 394 |
+
start = (self.config.input_length - self.config.target_length) // 2
|
| 395 |
+
outputs["splice_sites"] = all_logits[:, start:start + self.config.target_length]
|
| 396 |
+
if "splice_usage" in requested:
|
| 397 |
+
if usage_positions is None:
|
| 398 |
+
raise ValueError("splice_usage requires usage_positions")
|
| 399 |
+
gathered = self._gather_bins(
|
| 400 |
+
features, usage_positions, self.config.dense_bin_size
|
| 401 |
+
)
|
| 402 |
+
outputs["splice_usage"] = self.splice_usage_head(gathered).float()
|
| 403 |
+
if "junctions" in requested:
|
| 404 |
+
if junction_site_positions is None or junction_queries is None:
|
| 405 |
+
raise ValueError("junctions require site positions and query triples")
|
| 406 |
+
outputs["junctions"] = self._junction_predictions(
|
| 407 |
+
trunk, junction_site_positions, junction_queries
|
| 408 |
+
).float()
|
| 409 |
+
if "contact_maps" in requested:
|
| 410 |
+
contact = trunk.reshape(
|
| 411 |
+
len(dna), self.config.contact_bins, -1, self.config.hidden_dim
|
| 412 |
+
).mean(dim=2)
|
| 413 |
+
q, k = self.contact_q(contact), self.contact_k(contact)
|
| 414 |
+
row, column = self.contact_row, self.contact_column
|
| 415 |
+
outputs["contact_maps"] = (
|
| 416 |
+
0.5
|
| 417 |
+
* (
|
| 418 |
+
q[:, row] * k[:, column]
|
| 419 |
+
+ q[:, column] * k[:, row]
|
| 420 |
+
)
|
| 421 |
+
).float()
|
| 422 |
+
return outputs
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def count_parameters(model: nn.Module) -> int:
|
| 426 |
+
return sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad)
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/alphagenome_50m/reference_large.yaml
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
input_length: 1048576
|
| 2 |
+
target_length: 196608
|
| 3 |
+
dense_bin_size: 128
|
| 4 |
+
trunk_bin_size: 1024
|
| 5 |
+
contact_bin_size: 2048
|
| 6 |
+
stem_stride: 8
|
| 7 |
+
encoder_width: 96
|
| 8 |
+
channel_growth: 96
|
| 9 |
+
num_downsampling_blocks: 7
|
| 10 |
+
conv_kernel_size: 5
|
| 11 |
+
dna_kernel_size: 15
|
| 12 |
+
hidden_dim: 1024
|
| 13 |
+
num_sequence_blocks: 16
|
| 14 |
+
num_attention_heads: 16
|
| 15 |
+
attention_head_dim: 64
|
| 16 |
+
mlp_expansion: 4.0
|
| 17 |
+
dropout: 0.0
|
| 18 |
+
head_hidden_size: 768
|
| 19 |
+
junction_rank: 32
|
| 20 |
+
splice_usage_tracks: 734
|
| 21 |
+
junction_tracks: 734
|
| 22 |
+
contact_tracks: 28
|
| 23 |
+
gradient_checkpointing: true
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/alphagenome_50m/run_ddp.sh
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# run_ddp.sh DATA_DIR OUTPUT_DIR CONFIG EPOCHS [GPUS=8] [WORKERS_PER_GPU=12]
|
| 3 |
+
# Train the reference on every train interval with one example per GPU per step, then score
|
| 4 |
+
# validation with the verifier's own scorer. Runs inside the task image (torch, torchrun).
|
| 5 |
+
set -Eeuo pipefail
|
| 6 |
+
DATA=$1; OUT=$2; CONFIG=$3; EPOCHS=$4; GPUS=${5:-8}; WORKERS=${6:-12}
|
| 7 |
+
BASELINE=$(cd "$(dirname "$0")/../.." && pwd)
|
| 8 |
+
mkdir -p "$OUT"
|
| 9 |
+
cd "$BASELINE"
|
| 10 |
+
# Loopback rendezvous: works offline, where --standalone cannot resolve the hostname.
|
| 11 |
+
torchrun --nnodes 1 --nproc-per-node "$GPUS" --master-addr 127.0.0.1 --master-port "${MASTER_PORT:-29511}" -m reference.alphagenome_50m.train_eval train \
|
| 12 |
+
--input "$DATA" --config "$CONFIG" --output "$OUT" --epochs "$EPOCHS" --workers "$WORKERS" \
|
| 13 |
+
--log-every 200 --save-every 2000 2>&1 | tee -a "$OUT/train.log"
|
| 14 |
+
python predict.py "$DATA" "$OUT/valid-pred" --checkpoint "$OUT/last.pt" --split valid
|
| 15 |
+
python /workspace/evaluation/score.py --predictions "$OUT/valid-pred/predictions.zarr" \
|
| 16 |
+
--labels "$DATA" --split valid --output "$OUT/valid-score"
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/alphagenome_50m/tiny_overfit.yaml
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Keep the frozen 1-Mb input and every output track; shrink only learned widths.
|
| 2 |
+
input_length: 1048576
|
| 3 |
+
target_length: 196608
|
| 4 |
+
dense_bin_size: 128
|
| 5 |
+
trunk_bin_size: 1024
|
| 6 |
+
contact_bin_size: 2048
|
| 7 |
+
stem_stride: 8
|
| 8 |
+
encoder_width: 8
|
| 9 |
+
channel_growth: 4
|
| 10 |
+
num_downsampling_blocks: 7
|
| 11 |
+
conv_kernel_size: 5
|
| 12 |
+
dna_kernel_size: 15
|
| 13 |
+
hidden_dim: 32
|
| 14 |
+
num_sequence_blocks: 1
|
| 15 |
+
num_attention_heads: 2
|
| 16 |
+
attention_head_dim: 16
|
| 17 |
+
mlp_expansion: 2.0
|
| 18 |
+
dropout: 0.0
|
| 19 |
+
head_hidden_size: 32
|
| 20 |
+
junction_rank: 8
|
| 21 |
+
splice_usage_tracks: 734
|
| 22 |
+
junction_tracks: 734
|
| 23 |
+
contact_tracks: 28
|
| 24 |
+
gradient_checkpointing: false
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/reference/alphagenome_50m/train_eval.py
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Train and stream-evaluate the <=50M compact AlphaGenome baseline."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
import math
|
| 9 |
+
import os
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import time
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import torch
|
| 15 |
+
from torch import Tensor
|
| 16 |
+
from torch.nn import functional as F
|
| 17 |
+
from torch.utils.data import DataLoader, Subset
|
| 18 |
+
|
| 19 |
+
from .dataset import (
|
| 20 |
+
AlphaGenomeDataset,
|
| 21 |
+
DENSE_FAMILIES,
|
| 22 |
+
single_example_collate,
|
| 23 |
+
)
|
| 24 |
+
from .model import (
|
| 25 |
+
ALL_FAMILIES,
|
| 26 |
+
CompactModel,
|
| 27 |
+
ModelConfig,
|
| 28 |
+
count_parameters,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
DEFAULT_CONFIG = Path(__file__).with_name("alphagenome_50m.yaml")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _device(name: str) -> torch.device:
|
| 36 |
+
if name == "auto":
|
| 37 |
+
name = "cuda" if torch.cuda.is_available() else "cpu"
|
| 38 |
+
if name == "cuda" and not torch.cuda.is_available():
|
| 39 |
+
raise RuntimeError("--device cuda requested but CUDA is unavailable")
|
| 40 |
+
return torch.device(name)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _autocast(device: torch.device):
|
| 44 |
+
enabled = device.type == "cuda"
|
| 45 |
+
dtype = torch.bfloat16 if enabled and torch.cuda.is_bf16_supported() else torch.float16
|
| 46 |
+
return torch.autocast(device_type=device.type, dtype=dtype, enabled=enabled)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _distributed() -> tuple[int, int, int]:
|
| 50 |
+
"""(rank, local_rank, world_size) under torchrun; (0, 0, 1) otherwise."""
|
| 51 |
+
world = int(os.environ.get("WORLD_SIZE", "1"))
|
| 52 |
+
if world > 1 and not torch.distributed.is_initialized():
|
| 53 |
+
torch.distributed.init_process_group("nccl")
|
| 54 |
+
return int(os.environ.get("RANK", "0")), int(os.environ.get("LOCAL_RANK", "0")), world
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _loader(dataset, *, workers: int, shuffle: bool, sampler=None) -> DataLoader:
|
| 58 |
+
return DataLoader(
|
| 59 |
+
dataset,
|
| 60 |
+
batch_size=1,
|
| 61 |
+
shuffle=shuffle and sampler is None,
|
| 62 |
+
sampler=sampler,
|
| 63 |
+
num_workers=workers,
|
| 64 |
+
persistent_workers=workers > 0,
|
| 65 |
+
pin_memory=torch.cuda.is_available(),
|
| 66 |
+
collate_fn=single_example_collate,
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _to_device(value, device: torch.device):
|
| 71 |
+
if isinstance(value, Tensor):
|
| 72 |
+
return value.to(device, non_blocking=True)
|
| 73 |
+
if isinstance(value, dict):
|
| 74 |
+
return {key: _to_device(item, device) for key, item in value.items()}
|
| 75 |
+
return value
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _match_coordinate_queries(
|
| 79 |
+
scoring: dict[str, Tensor], positions: Tensor, track_halves: Tensor
|
| 80 |
+
) -> tuple[Tensor, Tensor, Tensor]:
|
| 81 |
+
"""Match trusted coordinate queries to typed position axes like the grader."""
|
| 82 |
+
device = positions.device
|
| 83 |
+
tracks = scoring["track"]
|
| 84 |
+
halves = track_halves[tracks]
|
| 85 |
+
queries = torch.zeros((len(tracks), 3), dtype=torch.int64, device=device)
|
| 86 |
+
queries[:, 2] = tracks
|
| 87 |
+
valid = scoring["valid"].clone()
|
| 88 |
+
missing = torch.ones(len(tracks), dtype=torch.bool, device=device)
|
| 89 |
+
position_rows = positions.detach().cpu().numpy()
|
| 90 |
+
halves_cpu = halves.detach().cpu().numpy()
|
| 91 |
+
donors_cpu = scoring["donor_position"].detach().cpu().numpy()
|
| 92 |
+
acceptors_cpu = scoring["acceptor_position"].detach().cpu().numpy()
|
| 93 |
+
valid_indices = np.flatnonzero(valid.detach().cpu().numpy())
|
| 94 |
+
lookups = [
|
| 95 |
+
{int(coordinate): index for index, coordinate in enumerate(axis) if coordinate >= 0}
|
| 96 |
+
for axis in position_rows
|
| 97 |
+
]
|
| 98 |
+
for index in valid_indices:
|
| 99 |
+
half = int(halves_cpu[index])
|
| 100 |
+
row = lookups[2 * half].get(int(donors_cpu[index]))
|
| 101 |
+
column = lookups[2 * half + 1].get(int(acceptors_cpu[index]))
|
| 102 |
+
if row is not None and column is not None:
|
| 103 |
+
queries[index, 0] = row
|
| 104 |
+
queries[index, 1] = column
|
| 105 |
+
missing[index] = False
|
| 106 |
+
return queries.unsqueeze(0), valid, missing
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _model_inputs(sample: dict) -> tuple[dict, Tensor, Tensor]:
|
| 110 |
+
queries, query_valid, missing = _match_coordinate_queries(
|
| 111 |
+
sample["junction_scoring"],
|
| 112 |
+
sample["site_positions"],
|
| 113 |
+
sample["junction_track_halves"],
|
| 114 |
+
)
|
| 115 |
+
if (query_valid & missing).any():
|
| 116 |
+
raise ValueError("trusted scoring coordinates do not match target positions")
|
| 117 |
+
junction_target = torch.asinh(
|
| 118 |
+
sample["junction_scoring"]["target_value"]
|
| 119 |
+
).unsqueeze(0)
|
| 120 |
+
return {
|
| 121 |
+
"dna": sample["dna"].unsqueeze(0),
|
| 122 |
+
"usage_positions": sample["usage_positions"].unsqueeze(0),
|
| 123 |
+
"junction_site_positions": sample["site_positions"].unsqueeze(0),
|
| 124 |
+
"junction_queries": queries,
|
| 125 |
+
}, junction_target, query_valid
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _losses(outputs: dict[str, Tensor], sample: dict, junction_target: Tensor,
|
| 129 |
+
junction_valid: Tensor) -> dict[str, Tensor]:
|
| 130 |
+
losses = {}
|
| 131 |
+
for family in DENSE_FAMILIES:
|
| 132 |
+
target = torch.asinh(sample["dense"][family]["values"]).unsqueeze(0)
|
| 133 |
+
mask = sample["dense"][family]["mask"].unsqueeze(0)
|
| 134 |
+
residual = torch.where(mask, outputs[family] - target, 0.0)
|
| 135 |
+
losses[family] = residual.square().sum() / mask.sum().clamp_min(1)
|
| 136 |
+
losses["splice_sites"] = F.binary_cross_entropy_with_logits(
|
| 137 |
+
outputs["splice_sites"], sample["splice_sites"].unsqueeze(0)
|
| 138 |
+
)
|
| 139 |
+
usage_target = torch.asinh(sample["splice_usage"]["values"]).unsqueeze(0)
|
| 140 |
+
usage_mask = sample["splice_usage"]["mask"].unsqueeze(0)
|
| 141 |
+
usage_residual = torch.where(usage_mask, outputs["splice_usage"] - usage_target, 0.0)
|
| 142 |
+
losses["splice_usage"] = usage_residual.square().sum() / usage_mask.sum().clamp_min(1)
|
| 143 |
+
junction_residual = outputs["junctions"][0] - junction_target[0]
|
| 144 |
+
losses["junctions"] = (
|
| 145 |
+
junction_residual[junction_valid].square().mean()
|
| 146 |
+
if junction_valid.any() else junction_residual.sum() * 0
|
| 147 |
+
)
|
| 148 |
+
contact_target = torch.asinh(sample["contact_maps"]).unsqueeze(0)
|
| 149 |
+
contact_mask = sample["contact_map_mask"].unsqueeze(0)
|
| 150 |
+
contact_residual = torch.where(
|
| 151 |
+
contact_mask, outputs["contact_maps"] - contact_target, 0.0
|
| 152 |
+
)
|
| 153 |
+
losses["contact_maps"] = contact_residual.square().sum() / contact_mask.sum().clamp_min(1)
|
| 154 |
+
losses["total"] = torch.stack([losses[name] for name in ALL_FAMILIES]).mean()
|
| 155 |
+
return losses
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _validation_inference(
|
| 159 |
+
model: CompactModel, sample: dict
|
| 160 |
+
) -> tuple[dict[str, Tensor], Tensor, Tensor, Tensor]:
|
| 161 |
+
"""Use the same predicted-position path as a formal v3 submission."""
|
| 162 |
+
trunk = model._trunk(sample["dna"].unsqueeze(0))
|
| 163 |
+
dense_features = model._dense_features(trunk)
|
| 164 |
+
outputs = {
|
| 165 |
+
family: model.dense_heads[family](dense_features).float()
|
| 166 |
+
for family in DENSE_FAMILIES
|
| 167 |
+
}
|
| 168 |
+
all_sites = model._splice_site_logits(trunk)
|
| 169 |
+
target_start = (model.config.input_length - model.config.target_length) // 2
|
| 170 |
+
outputs["splice_sites"] = all_sites[:, target_start:target_start + model.config.target_length]
|
| 171 |
+
usage_bins = model.splice_usage_head(dense_features).float()
|
| 172 |
+
usage_indices = torch.div(sample["usage_positions"], model.config.dense_bin_size,
|
| 173 |
+
rounding_mode="floor")
|
| 174 |
+
outputs["splice_usage"] = usage_bins[:, usage_indices]
|
| 175 |
+
predicted_positions = model.select_junction_positions(all_sites)
|
| 176 |
+
|
| 177 |
+
matched, valid, missing = _match_coordinate_queries(
|
| 178 |
+
sample["junction_scoring"],
|
| 179 |
+
predicted_positions[0],
|
| 180 |
+
sample["junction_track_halves"],
|
| 181 |
+
)
|
| 182 |
+
junction_target = torch.asinh(
|
| 183 |
+
sample["junction_scoring"]["target_value"]
|
| 184 |
+
).unsqueeze(0)
|
| 185 |
+
junction_prediction = torch.zeros(len(valid), device=valid.device)
|
| 186 |
+
if (~missing & valid).any():
|
| 187 |
+
selected = ~missing & valid
|
| 188 |
+
junction_prediction[selected] = model._junction_predictions(
|
| 189 |
+
trunk, predicted_positions, matched[:, selected]
|
| 190 |
+
)[0]
|
| 191 |
+
outputs["junctions"] = junction_prediction.unsqueeze(0)
|
| 192 |
+
|
| 193 |
+
contact = trunk.reshape(
|
| 194 |
+
1, model.config.contact_bins, -1, model.config.hidden_dim
|
| 195 |
+
).mean(dim=2)
|
| 196 |
+
q, k = model.contact_q(contact), model.contact_k(contact)
|
| 197 |
+
row, column = model.contact_row, model.contact_column
|
| 198 |
+
outputs["contact_maps"] = (0.5 * (q[:, row] * k[:, column] + q[:, column] * k[:, row])).float()
|
| 199 |
+
return outputs, junction_target, valid, missing
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _atomic_save(payload: dict, path: Path) -> None:
|
| 203 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 204 |
+
temporary = path.with_name(f".{path.name}.tmp")
|
| 205 |
+
torch.save(payload, temporary)
|
| 206 |
+
os.replace(temporary, path)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def _sha256(path: Path) -> str:
|
| 210 |
+
digest = hashlib.sha256()
|
| 211 |
+
with path.open("rb") as handle:
|
| 212 |
+
for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
|
| 213 |
+
digest.update(chunk)
|
| 214 |
+
return digest.hexdigest()
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def _resume_position(payload: dict, *, examples: int, epochs: int) -> tuple[int, int]:
|
| 218 |
+
epoch = int(payload["epoch"])
|
| 219 |
+
step = int(payload["global_step"])
|
| 220 |
+
kind = payload.get("checkpoint_kind")
|
| 221 |
+
if kind not in (None, "epoch") or step != epoch * examples:
|
| 222 |
+
raise ValueError("only a completed-epoch checkpoint can resume training")
|
| 223 |
+
if payload.get("examples", examples) != examples or payload.get("schedule_epochs", epochs) != epochs:
|
| 224 |
+
raise ValueError("checkpoint data size or training schedule differs from this run")
|
| 225 |
+
return epoch, step
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def train(args: argparse.Namespace) -> None:
|
| 229 |
+
# Multi-GPU with `torchrun --nproc-per-node N train_eval.py train ...`: one example per GPU per
|
| 230 |
+
# step (data parallel), rank 0 writes checkpoints and logs. Model size is bounded by the
|
| 231 |
+
# training budget, not by a parameter cap.
|
| 232 |
+
rank, local_rank, world = _distributed()
|
| 233 |
+
config = ModelConfig.from_yaml(args.config)
|
| 234 |
+
device = torch.device("cuda", local_rank) if world > 1 else _device(args.device)
|
| 235 |
+
if world > 1:
|
| 236 |
+
torch.cuda.set_device(device)
|
| 237 |
+
torch.manual_seed(args.seed)
|
| 238 |
+
model = CompactModel(config).to(device)
|
| 239 |
+
parameters = count_parameters(model)
|
| 240 |
+
optimizer = torch.optim.AdamW(
|
| 241 |
+
model.parameters(), lr=args.learning_rate, weight_decay=args.weight_decay
|
| 242 |
+
)
|
| 243 |
+
scaler = torch.amp.GradScaler("cuda", enabled=device.type == "cuda")
|
| 244 |
+
full_dataset = AlphaGenomeDataset(args.input, "train")
|
| 245 |
+
model.set_junction_track_halves(full_dataset.junction_track_halves)
|
| 246 |
+
size = min(len(full_dataset), args.max_examples or len(full_dataset))
|
| 247 |
+
dataset = Subset(full_dataset, range(size))
|
| 248 |
+
start_epoch, global_step = 0, 0
|
| 249 |
+
if args.resume:
|
| 250 |
+
payload = torch.load(args.resume, map_location="cpu", weights_only=True)
|
| 251 |
+
if payload.get("config") != config.to_dict():
|
| 252 |
+
raise ValueError("checkpoint configuration does not match --config")
|
| 253 |
+
model.load_state_dict(payload["model"], strict=True)
|
| 254 |
+
optimizer.load_state_dict(payload["optimizer"])
|
| 255 |
+
scaler.load_state_dict(payload.get("scaler", {}))
|
| 256 |
+
start_epoch, global_step = _resume_position(payload, examples=size, epochs=args.epochs)
|
| 257 |
+
per_rank = math.ceil(size / world)
|
| 258 |
+
steps = max(1, per_rank * args.epochs)
|
| 259 |
+
module = model
|
| 260 |
+
if world > 1:
|
| 261 |
+
model = torch.nn.parallel.DistributedDataParallel(
|
| 262 |
+
model, device_ids=[local_rank], find_unused_parameters=True)
|
| 263 |
+
sampler = (torch.utils.data.distributed.DistributedSampler(dataset, num_replicas=world, rank=rank,
|
| 264 |
+
shuffle=True, seed=args.seed)
|
| 265 |
+
if world > 1 else None)
|
| 266 |
+
stop_after_epoch = args.stop_after_epoch or args.epochs
|
| 267 |
+
output = args.output.resolve()
|
| 268 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 269 |
+
started = time.monotonic()
|
| 270 |
+
if rank == 0:
|
| 271 |
+
print(json.dumps({"event": "train_start", "parameters": parameters, "examples": size,
|
| 272 |
+
"device": str(device), "world_size": world}), flush=True)
|
| 273 |
+
|
| 274 |
+
for epoch in range(start_epoch, stop_after_epoch):
|
| 275 |
+
model.train()
|
| 276 |
+
if sampler is not None:
|
| 277 |
+
sampler.set_epoch(epoch)
|
| 278 |
+
loader = _loader(dataset, workers=args.workers, shuffle=True, sampler=sampler)
|
| 279 |
+
for sample in loader:
|
| 280 |
+
sample = _to_device(sample, device)
|
| 281 |
+
inputs, junction_target, junction_valid = _model_inputs(sample)
|
| 282 |
+
progress = min((global_step + 1) / steps, 1.0)
|
| 283 |
+
learning_rate = args.min_learning_rate + 0.5 * (
|
| 284 |
+
args.learning_rate - args.min_learning_rate
|
| 285 |
+
) * (1.0 + math.cos(math.pi * progress))
|
| 286 |
+
for group in optimizer.param_groups:
|
| 287 |
+
group["lr"] = learning_rate
|
| 288 |
+
optimizer.zero_grad(set_to_none=True)
|
| 289 |
+
with _autocast(device):
|
| 290 |
+
predictions = model(**inputs)
|
| 291 |
+
losses = _losses(predictions, sample, junction_target, junction_valid)
|
| 292 |
+
if not torch.isfinite(losses["total"]):
|
| 293 |
+
raise FloatingPointError(f"non-finite loss at step {global_step}")
|
| 294 |
+
scaler.scale(losses["total"]).backward()
|
| 295 |
+
scaler.unscale_(optimizer)
|
| 296 |
+
gradient_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_gradient_norm)
|
| 297 |
+
scaler.step(optimizer)
|
| 298 |
+
scaler.update()
|
| 299 |
+
global_step += 1
|
| 300 |
+
if rank == 0 and (global_step == 1 or global_step % args.log_every == 0):
|
| 301 |
+
print(
|
| 302 |
+
json.dumps(
|
| 303 |
+
{
|
| 304 |
+
"event": "train_step",
|
| 305 |
+
"epoch": epoch + 1,
|
| 306 |
+
"step": global_step,
|
| 307 |
+
"loss": float(losses["total"].detach()),
|
| 308 |
+
"gradient_norm": float(gradient_norm),
|
| 309 |
+
"learning_rate": learning_rate,
|
| 310 |
+
"elapsed_seconds": time.monotonic() - started,
|
| 311 |
+
}
|
| 312 |
+
),
|
| 313 |
+
flush=True,
|
| 314 |
+
)
|
| 315 |
+
if rank == 0 and global_step % args.save_every == 0:
|
| 316 |
+
_atomic_save(
|
| 317 |
+
{
|
| 318 |
+
"schema": "alphagenome-50m-real/v3",
|
| 319 |
+
"model": module.state_dict(),
|
| 320 |
+
"optimizer": optimizer.state_dict(),
|
| 321 |
+
"scaler": scaler.state_dict(),
|
| 322 |
+
"config": config.to_dict(),
|
| 323 |
+
"epoch": epoch,
|
| 324 |
+
"global_step": global_step,
|
| 325 |
+
"checkpoint_kind": "progress",
|
| 326 |
+
"examples": size,
|
| 327 |
+
"schedule_epochs": args.epochs,
|
| 328 |
+
},
|
| 329 |
+
output / "progress.pt",
|
| 330 |
+
)
|
| 331 |
+
if world > 1:
|
| 332 |
+
torch.distributed.barrier()
|
| 333 |
+
if rank != 0:
|
| 334 |
+
continue
|
| 335 |
+
_atomic_save(
|
| 336 |
+
{
|
| 337 |
+
"schema": "alphagenome-50m-real/v3",
|
| 338 |
+
"model": module.state_dict(),
|
| 339 |
+
"optimizer": optimizer.state_dict(),
|
| 340 |
+
"scaler": scaler.state_dict(),
|
| 341 |
+
"config": config.to_dict(),
|
| 342 |
+
"epoch": epoch + 1,
|
| 343 |
+
"global_step": global_step,
|
| 344 |
+
"checkpoint_kind": "epoch",
|
| 345 |
+
"examples": size,
|
| 346 |
+
"schedule_epochs": args.epochs,
|
| 347 |
+
},
|
| 348 |
+
output / "last.pt",
|
| 349 |
+
)
|
| 350 |
+
if world > 1:
|
| 351 |
+
torch.distributed.barrier()
|
| 352 |
+
torch.distributed.destroy_process_group()
|
| 353 |
+
if rank != 0:
|
| 354 |
+
return
|
| 355 |
+
checkpoint = output / "last.pt"
|
| 356 |
+
manifest = {
|
| 357 |
+
"schema": "alphagenome-50m-real/v3",
|
| 358 |
+
"checkpoint": {"path": checkpoint.name, "sha256": _sha256(checkpoint)},
|
| 359 |
+
"parameters": parameters,
|
| 360 |
+
"config": config.to_dict(),
|
| 361 |
+
"output_families": list(ALL_FAMILIES),
|
| 362 |
+
"epochs": args.epochs,
|
| 363 |
+
"completed_epochs": stop_after_epoch,
|
| 364 |
+
"global_step": global_step,
|
| 365 |
+
}
|
| 366 |
+
(output / "model_manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n")
|
| 367 |
+
print(json.dumps({"event": "train_complete", **manifest}), flush=True)
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
class PerTrackMoments:
|
| 371 |
+
def __init__(self, tracks: int):
|
| 372 |
+
self.n = np.zeros(tracks, dtype=np.int64)
|
| 373 |
+
self.sum_x = np.zeros(tracks, dtype=np.float64)
|
| 374 |
+
self.sum_y = np.zeros(tracks, dtype=np.float64)
|
| 375 |
+
self.sum_x2 = np.zeros(tracks, dtype=np.float64)
|
| 376 |
+
self.sum_y2 = np.zeros(tracks, dtype=np.float64)
|
| 377 |
+
self.sum_xy = np.zeros(tracks, dtype=np.float64)
|
| 378 |
+
|
| 379 |
+
def update(self, prediction: Tensor, target: Tensor, mask: Tensor | None = None) -> None:
|
| 380 |
+
x = prediction.detach().double().cpu().numpy().reshape(-1, prediction.shape[-1])
|
| 381 |
+
y = target.detach().double().cpu().numpy().reshape(-1, target.shape[-1])
|
| 382 |
+
valid = np.ones_like(y, dtype=bool) if mask is None else mask.detach().cpu().numpy().reshape(y.shape).astype(bool)
|
| 383 |
+
self.n += valid.sum(axis=0)
|
| 384 |
+
self.sum_x += np.where(valid, x, 0).sum(axis=0, dtype=np.float64)
|
| 385 |
+
self.sum_y += np.where(valid, y, 0).sum(axis=0, dtype=np.float64)
|
| 386 |
+
self.sum_x2 += np.where(valid, x * x, 0).sum(axis=0, dtype=np.float64)
|
| 387 |
+
self.sum_y2 += np.where(valid, y * y, 0).sum(axis=0, dtype=np.float64)
|
| 388 |
+
self.sum_xy += np.where(valid, x * y, 0).sum(axis=0, dtype=np.float64)
|
| 389 |
+
|
| 390 |
+
def update_indexed(self, prediction: Tensor, target: Tensor, track: Tensor) -> None:
|
| 391 |
+
x = prediction.detach().double().cpu().numpy().reshape(-1)
|
| 392 |
+
y = target.detach().double().cpu().numpy().reshape(-1)
|
| 393 |
+
indices = track.detach().cpu().numpy().reshape(-1).astype(np.int64)
|
| 394 |
+
self.n += np.bincount(indices, minlength=len(self.n))
|
| 395 |
+
self.sum_x += np.bincount(indices, weights=x, minlength=len(self.n))
|
| 396 |
+
self.sum_y += np.bincount(indices, weights=y, minlength=len(self.n))
|
| 397 |
+
self.sum_x2 += np.bincount(indices, weights=x * x, minlength=len(self.n))
|
| 398 |
+
self.sum_y2 += np.bincount(indices, weights=y * y, minlength=len(self.n))
|
| 399 |
+
self.sum_xy += np.bincount(indices, weights=x * y, minlength=len(self.n))
|
| 400 |
+
|
| 401 |
+
def report(self) -> dict:
|
| 402 |
+
numerator = self.n * self.sum_xy - self.sum_x * self.sum_y
|
| 403 |
+
denominator = np.sqrt(
|
| 404 |
+
np.maximum(self.n * self.sum_x2 - self.sum_x**2, 0)
|
| 405 |
+
* np.maximum(self.n * self.sum_y2 - self.sum_y**2, 0)
|
| 406 |
+
)
|
| 407 |
+
target_ss = np.maximum(self.n * self.sum_y2 - self.sum_y**2, 0)
|
| 408 |
+
scorable = (self.n >= 2) & (target_ss > 0)
|
| 409 |
+
pearson = np.full_like(numerator, np.nan)
|
| 410 |
+
nonconstant = scorable & (denominator > 0)
|
| 411 |
+
pearson[nonconstant] = numerator[nonconstant] / denominator[nonconstant]
|
| 412 |
+
pearson[scorable & ~nonconstant] = 0.0
|
| 413 |
+
return {
|
| 414 |
+
"mean_pearson": float(pearson[scorable].mean()) if scorable.any() else 0.0,
|
| 415 |
+
"valid_tracks": int(scorable.sum()),
|
| 416 |
+
"per_track_pearson": [float(value) if np.isfinite(value) else None for value in pearson],
|
| 417 |
+
"values_per_track": self.n.tolist(),
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def evaluate(args: argparse.Namespace) -> None:
|
| 422 |
+
device = _device(args.device)
|
| 423 |
+
payload = torch.load(args.checkpoint, map_location="cpu", weights_only=True)
|
| 424 |
+
config = ModelConfig(**payload["config"])
|
| 425 |
+
model = CompactModel(config).to(device)
|
| 426 |
+
model.load_state_dict(payload["model"], strict=True)
|
| 427 |
+
model.eval()
|
| 428 |
+
full_dataset = AlphaGenomeDataset(args.input, args.split)
|
| 429 |
+
model.set_junction_track_halves(full_dataset.junction_track_halves)
|
| 430 |
+
size = min(len(full_dataset), args.max_examples or len(full_dataset))
|
| 431 |
+
dataset = Subset(full_dataset, range(size))
|
| 432 |
+
metrics = {
|
| 433 |
+
**{family: PerTrackMoments(config_value) for family, config_value in {
|
| 434 |
+
"atac": 167, "dnase": 305, "procap": 12, "cage": 546,
|
| 435 |
+
"rna_seq": 667, "chip_tf": 1617, "chip_histone": 1116,
|
| 436 |
+
}.items()},
|
| 437 |
+
"splice_sites": PerTrackMoments(4),
|
| 438 |
+
"splice_usage": PerTrackMoments(config.splice_usage_tracks),
|
| 439 |
+
"junctions": PerTrackMoments(config.junction_tracks),
|
| 440 |
+
"contact_maps": PerTrackMoments(config.contact_tracks),
|
| 441 |
+
}
|
| 442 |
+
with torch.inference_mode():
|
| 443 |
+
for index, sample in enumerate(_loader(dataset, workers=args.workers, shuffle=False)):
|
| 444 |
+
sample = _to_device(sample, device)
|
| 445 |
+
outputs, junction_target, junction_valid, junction_missing = (
|
| 446 |
+
_validation_inference(model, sample)
|
| 447 |
+
)
|
| 448 |
+
# Match predict.py: FP32 inference is serialized to FP16 Zarr values.
|
| 449 |
+
outputs = {name: value.half().float() for name, value in outputs.items()}
|
| 450 |
+
for family in DENSE_FAMILIES:
|
| 451 |
+
metrics[family].update(
|
| 452 |
+
outputs[family][0],
|
| 453 |
+
torch.asinh(sample["dense"][family]["values"]),
|
| 454 |
+
sample["dense"][family]["mask"],
|
| 455 |
+
)
|
| 456 |
+
metrics["splice_sites"].update(outputs["splice_sites"][0], sample["splice_sites"])
|
| 457 |
+
metrics["splice_usage"].update(
|
| 458 |
+
outputs["splice_usage"][0],
|
| 459 |
+
torch.asinh(sample["splice_usage"]["values"]),
|
| 460 |
+
sample["splice_usage"]["mask"],
|
| 461 |
+
)
|
| 462 |
+
junction_track = sample["junction_scoring"]["track"]
|
| 463 |
+
metrics["junctions"].update_indexed(
|
| 464 |
+
outputs["junctions"][0][junction_valid],
|
| 465 |
+
junction_target[0][junction_valid],
|
| 466 |
+
junction_track[junction_valid],
|
| 467 |
+
)
|
| 468 |
+
metrics["contact_maps"].update(
|
| 469 |
+
outputs["contact_maps"][0],
|
| 470 |
+
torch.asinh(sample["contact_maps"]),
|
| 471 |
+
sample["contact_map_mask"],
|
| 472 |
+
)
|
| 473 |
+
if index == 0 or (index + 1) % args.log_every == 0 or index + 1 == size:
|
| 474 |
+
print(json.dumps({"event": "evaluate_progress", "examples": index + 1, "total": size}), flush=True)
|
| 475 |
+
families = {name: accumulator.report() for name, accumulator in metrics.items()}
|
| 476 |
+
valid_family_scores = [item["mean_pearson"] for item in families.values()]
|
| 477 |
+
report = {
|
| 478 |
+
"schema": "alphagenome-50m-evaluation/v3",
|
| 479 |
+
"split": args.split,
|
| 480 |
+
"examples": size,
|
| 481 |
+
"metric_space": (
|
| 482 |
+
"asinh continuous targets and binary splice-site targets; "
|
| 483 |
+
"junction Pearson uses hidden coordinate queries and predicted endpoints; "
|
| 484 |
+
"FP32 inference rounded to FP16 prediction values"
|
| 485 |
+
),
|
| 486 |
+
"families": families,
|
| 487 |
+
"overall_mean_family_pearson": float(np.mean(valid_family_scores)),
|
| 488 |
+
}
|
| 489 |
+
args.report.parent.mkdir(parents=True, exist_ok=True)
|
| 490 |
+
args.report.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")
|
| 491 |
+
print(json.dumps({"event": "evaluate_complete", "overall_mean_family_pearson": report["overall_mean_family_pearson"]}), flush=True)
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def main() -> None:
|
| 495 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 496 |
+
common = argparse.ArgumentParser(add_help=False)
|
| 497 |
+
common.add_argument("--input", required=True, type=Path)
|
| 498 |
+
common.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
|
| 499 |
+
common.add_argument("--workers", type=int, default=2)
|
| 500 |
+
common.add_argument("--max-examples", type=int, default=0)
|
| 501 |
+
common.add_argument("--device", choices=("auto", "cuda", "cpu"), default="auto")
|
| 502 |
+
common.add_argument("--log-every", type=int, default=25)
|
| 503 |
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
| 504 |
+
train_parser = subparsers.add_parser("train", parents=[common])
|
| 505 |
+
train_parser.add_argument("--output", required=True, type=Path)
|
| 506 |
+
train_parser.add_argument("--epochs", type=int, default=10)
|
| 507 |
+
train_parser.add_argument("--stop-after-epoch", type=int)
|
| 508 |
+
train_parser.add_argument("--learning-rate", type=float, default=2e-4)
|
| 509 |
+
train_parser.add_argument("--min-learning-rate", type=float, default=2e-5)
|
| 510 |
+
train_parser.add_argument("--weight-decay", type=float, default=1e-4)
|
| 511 |
+
train_parser.add_argument("--max-gradient-norm", type=float, default=5.0)
|
| 512 |
+
train_parser.add_argument("--save-every", type=int, default=250)
|
| 513 |
+
train_parser.add_argument("--seed", type=int, default=17)
|
| 514 |
+
train_parser.add_argument("--resume", type=Path)
|
| 515 |
+
train_parser.set_defaults(run=train)
|
| 516 |
+
evaluate_parser = subparsers.add_parser("evaluate", parents=[common])
|
| 517 |
+
evaluate_parser.add_argument("--checkpoint", required=True, type=Path)
|
| 518 |
+
evaluate_parser.add_argument("--split", choices=("train", "valid", "test"), required=True)
|
| 519 |
+
evaluate_parser.add_argument("--report", required=True, type=Path)
|
| 520 |
+
evaluate_parser.set_defaults(run=evaluate)
|
| 521 |
+
args = parser.parse_args()
|
| 522 |
+
if args.workers < 0 or args.max_examples < 0:
|
| 523 |
+
parser.error("workers/max-examples must be nonnegative")
|
| 524 |
+
if args.command == "train" and (
|
| 525 |
+
args.epochs < 1
|
| 526 |
+
or (args.stop_after_epoch is not None
|
| 527 |
+
and not 1 <= args.stop_after_epoch <= args.epochs)
|
| 528 |
+
):
|
| 529 |
+
parser.error("epochs must be positive and stop-after-epoch must be within the schedule")
|
| 530 |
+
args.run(args)
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
if __name__ == "__main__":
|
| 534 |
+
main()
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/validation_tracks.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S003/validation_variants.json
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"eqtl_sign": {
|
| 3 |
+
"rows": 17052,
|
| 4 |
+
"perturbations": 165,
|
| 5 |
+
"metric": "auroc",
|
| 6 |
+
"model": 0.4398601030917572,
|
| 7 |
+
"anchors": {
|
| 8 |
+
"AlphaGenome": 0.8263569969634328
|
| 9 |
+
}
|
| 10 |
+
},
|
| 11 |
+
"eqtl_causality": {
|
| 12 |
+
"rows": 17934,
|
| 13 |
+
"perturbations": 174,
|
| 14 |
+
"metric": "auroc",
|
| 15 |
+
"model": 0.6803609732181162,
|
| 16 |
+
"anchors": {
|
| 17 |
+
"AlphaGenome": 0.8325427468284611
|
| 18 |
+
}
|
| 19 |
+
},
|
| 20 |
+
"eqtl_coefficient": {
|
| 21 |
+
"rows": 8575,
|
| 22 |
+
"perturbations": 165,
|
| 23 |
+
"metric": "spearman",
|
| 24 |
+
"model": -0.1098670364215773,
|
| 25 |
+
"anchors": {
|
| 26 |
+
"AlphaGenome": 0.4133539365891599
|
| 27 |
+
}
|
| 28 |
+
},
|
| 29 |
+
"sqtl_causality": {
|
| 30 |
+
"rows": 21340,
|
| 31 |
+
"perturbations": 194,
|
| 32 |
+
"metric": "auprc",
|
| 33 |
+
"model": 0.6716153991373395,
|
| 34 |
+
"anchors": {
|
| 35 |
+
"AlphaGenome": 0.8447114201904594
|
| 36 |
+
}
|
| 37 |
+
},
|
| 38 |
+
"clinvar_noncoding": {
|
| 39 |
+
"rows": 199,
|
| 40 |
+
"perturbations": 199,
|
| 41 |
+
"metric": "auprc",
|
| 42 |
+
"model": 0.19618952824625902,
|
| 43 |
+
"anchors": {
|
| 44 |
+
"AlphaGenome": 0.9409857958177288
|
| 45 |
+
}
|
| 46 |
+
},
|
| 47 |
+
"clinvar_splice_region": {
|
| 48 |
+
"rows": 194,
|
| 49 |
+
"perturbations": 194,
|
| 50 |
+
"metric": "auprc",
|
| 51 |
+
"model": 0.21548331119454472,
|
| 52 |
+
"anchors": {
|
| 53 |
+
"AlphaGenome": 0.7224791623996103
|
| 54 |
+
}
|
| 55 |
+
},
|
| 56 |
+
"clinvar_missense": {
|
| 57 |
+
"rows": 199,
|
| 58 |
+
"perturbations": 199,
|
| 59 |
+
"metric": "auprc",
|
| 60 |
+
"model": 0.2709509046987323,
|
| 61 |
+
"anchors": {
|
| 62 |
+
"AlphaGenome": 0.373826292978903
|
| 63 |
+
}
|
| 64 |
+
},
|
| 65 |
+
"mfass": {
|
| 66 |
+
"rows": 195,
|
| 67 |
+
"perturbations": 195,
|
| 68 |
+
"metric": "auprc",
|
| 69 |
+
"model": 0.15220958146626407,
|
| 70 |
+
"anchors": {
|
| 71 |
+
"AlphaGenome": 0.7342557141920668
|
| 72 |
+
}
|
| 73 |
+
},
|
| 74 |
+
"caqtl": {
|
| 75 |
+
"rows": 198,
|
| 76 |
+
"perturbations": 198,
|
| 77 |
+
"metric": "auprc",
|
| 78 |
+
"model": 0.3468004299934636,
|
| 79 |
+
"anchors": {
|
| 80 |
+
"AlphaGenome": 0.8075760167741196
|
| 81 |
+
}
|
| 82 |
+
},
|
| 83 |
+
"bqtl_spi1": {
|
| 84 |
+
"rows": 160,
|
| 85 |
+
"perturbations": 160,
|
| 86 |
+
"metric": "auprc",
|
| 87 |
+
"model": 0.2618951286619208,
|
| 88 |
+
"anchors": {
|
| 89 |
+
"AlphaGenome": 0.8167450781363793
|
| 90 |
+
}
|
| 91 |
+
},
|
| 92 |
+
"enhancer_gene": {
|
| 93 |
+
"rows": 200,
|
| 94 |
+
"perturbations": 200,
|
| 95 |
+
"metric": "auprc",
|
| 96 |
+
"model": 0.4727432591017893,
|
| 97 |
+
"anchors": {
|
| 98 |
+
"AlphaGenome": 0.9594307235541584
|
| 99 |
+
}
|
| 100 |
+
},
|
| 101 |
+
"traitgym_mendelian": {
|
| 102 |
+
"rows": 292,
|
| 103 |
+
"perturbations": 292,
|
| 104 |
+
"metric": "auprc",
|
| 105 |
+
"model": 0.2523424968266569,
|
| 106 |
+
"anchors": {
|
| 107 |
+
"Borzoi_L2_L2.plus.all": 0.5026323772738239,
|
| 108 |
+
"Enformer_L2_L2.plus.all": 0.5452938267693526,
|
| 109 |
+
"CADD.plus.RawScore": 0.7189111372856957,
|
| 110 |
+
"GPN-MSA_absLLR.plus.score": 0.6729149139043132
|
| 111 |
+
}
|
| 112 |
+
},
|
| 113 |
+
"traitgym_complex": {
|
| 114 |
+
"rows": 299,
|
| 115 |
+
"perturbations": 299,
|
| 116 |
+
"metric": "auprc",
|
| 117 |
+
"model": 0.14815618473839376,
|
| 118 |
+
"anchors": {
|
| 119 |
+
"Borzoi_L2_L2.plus.all": 0.294501577162467,
|
| 120 |
+
"Enformer_L2_L2.plus.all": 0.269227301087889,
|
| 121 |
+
"CADD.plus.RawScore": 0.41341570280137435,
|
| 122 |
+
"GPN-MSA_absLLR.plus.score": 0.4213971415058371
|
| 123 |
+
}
|
| 124 |
+
}
|
| 125 |
+
}
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/README.md
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SeqFunc local01 at step 14,000
|
| 2 |
+
|
| 3 |
+
One model with **13,256,456 parameters** serves every family and both entry points. It reads the entire
|
| 4 |
+
1,048,576-bp DNA window through a convolutional encoder and 6 transformer
|
| 5 |
+
blocks of width 384 over 1,024 tokens. Dense heads predict 128-bp bins over the central
|
| 6 |
+
196,608 bp; other heads predict splice sites, sparse usage/junctions and full-window contacts.
|
| 7 |
+
A width-32 base-resolution path uses a 21-bp stem and four dilated residual depthwise blocks (701-bp receptive field). Average/max pooling provides aligned 128-bp residual features to dense, usage and junction heads. Splice logits combine local base-resolution logits with the reference offset decoder. Junction values use low-rank donor/acceptor factors; contacts use a symmetric
|
| 8 |
+
product of global features. Sites and junction endpoints are selected from model scores alone.
|
| 9 |
+
|
| 10 |
+
All weights originate from local random initialization (seed 17) and locally trained
|
| 11 |
+
checkpoints. The global parent trained for the first 2,000 updates. The local path was attached with zero residual outputs at step 2,000, retaining every parent parameter and optimizer moment, then training continued. This is the matched control for the uniform splice-context fork.
|
| 12 |
+
|
| 13 |
+
This checkpoint records **14,000 updates**, 0 complete training permutations and
|
| 14 |
+
14,000 intervals into the next permutation. Each permutation includes all **41,020**
|
| 15 |
+
eligible FOLD_0 training intervals (folds 2–7), shuffled deterministically without replacement.
|
| 16 |
+
Quantized train targets are decoded by the supplied reader. Validation is fold 0; no test labels,
|
| 17 |
+
test-derived caches or pretrained model parameters were used. Development labels only evaluate
|
| 18 |
+
and select models. Checkpoints before a complete permutation remain intermediate milestones.
|
| 19 |
+
|
| 20 |
+
Training uses one H100 80 GB and at most 22 CPUs. The current loader uses 6 workers
|
| 21 |
+
and 2 torch CPU threads. BF16 training uses AdamW (weight decay 1e-4), gradient
|
| 22 |
+
clipping at 5, and a 4-epoch cosine learning-rate schedule from
|
| 23 |
+
0.0002 to 2e-05, with
|
| 24 |
+
500 warmup updates. The splice objective is `balanced_splice`;
|
| 25 |
+
other family losses follow the reference. Recorded accumulated training-loop wall time is
|
| 26 |
+
35.3 minutes, including inherited parent time. Runs can share this
|
| 27 |
+
same physical GPU with experiments or evaluation. Setup, evaluation and discarded mechanical checks
|
| 28 |
+
are additional research compute, documented in the research ledger. Matching training junction queries
|
| 29 |
+
uses a verified, bit-identical CPU index construction followed by a bulk GPU transfer.
|
| 30 |
+
|
| 31 |
+
The package contains model code, weights, training source/configuration/provenance, SHA-256 checksums,
|
| 32 |
+
and the complete CPython 3.11 / PyTorch 2.7.1 CUDA 12.6 Python runtime archive. Both executable entry
|
| 33 |
+
points take INPUT_ROOT and OUTPUT_ROOT, extract the vendored runtime temporarily, and run offline.
|
| 34 |
+
The host supplies Linux, bash/tar/gzip and the NVIDIA driver. Inference reads only public manifests
|
| 35 |
+
and the pinned reference FASTA. No target, splice-coordinate or prediction cache is packaged or read.
|
| 36 |
+
Track outputs use float16; perturbation outputs use float32 to preserve small A/B differences.
|
| 37 |
+
|
| 38 |
+
The appended validation results cover all 200 intervals and all 2,697 development perturbations,
|
| 39 |
+
scored by the unmodified verifier tools. Published anchors use the same label rows. All results,
|
| 40 |
+
including regressions, are retained in the package's JSON reports. Limitations include incomplete
|
| 41 |
+
training at intermediate checkpoints, a 701-bp local receptive field, pooled usage/junction features,
|
| 42 |
+
low-rank contact modeling, and uneven variant performance. Functional readouts do not provide the
|
| 43 |
+
evolutionary constraint information used by conservation-based variant scorers.
|
| 44 |
+
|
| 45 |
+
## Measured validation results
|
| 46 |
+
|
| 47 |
+
Family-mean Pearson: **0.255588** on 200 validation intervals.
|
| 48 |
+
|
| 49 |
+
| Family | Pearson |
|
| 50 |
+
|---|---:|
|
| 51 |
+
| atac | 0.449029 |
|
| 52 |
+
| dnase | 0.581962 |
|
| 53 |
+
| procap | 0.331749 |
|
| 54 |
+
| cage | 0.180663 |
|
| 55 |
+
| rna_seq | 0.200977 |
|
| 56 |
+
| chip_tf | 0.366987 |
|
| 57 |
+
| chip_histone | 0.352559 |
|
| 58 |
+
| splice_sites | 0.039608 |
|
| 59 |
+
| splice_usage | 0.130403 |
|
| 60 |
+
| junctions | 0.158050 |
|
| 61 |
+
| contact_maps | 0.019487 |
|
| 62 |
+
|
| 63 |
+
| Development evaluation | Metric | Model | Published anchors on the same rows |
|
| 64 |
+
|---|---|---:|---|
|
| 65 |
+
| eqtl_sign | auroc | 0.3964 | AlphaGenome: 0.8264 |
|
| 66 |
+
| eqtl_causality | auroc | 0.6965 | AlphaGenome: 0.8325 |
|
| 67 |
+
| eqtl_coefficient | spearman | -0.1779 | AlphaGenome: 0.4134 |
|
| 68 |
+
| sqtl_causality | auprc | 0.7404 | AlphaGenome: 0.8447 |
|
| 69 |
+
| clinvar_noncoding | auprc | 0.2576 | AlphaGenome: 0.9410 |
|
| 70 |
+
| clinvar_splice_region | auprc | 0.2616 | AlphaGenome: 0.7225 |
|
| 71 |
+
| clinvar_missense | auprc | 0.2667 | AlphaGenome: 0.3738 |
|
| 72 |
+
| mfass | auprc | 0.1634 | AlphaGenome: 0.7343 |
|
| 73 |
+
| caqtl | auprc | 0.2635 | AlphaGenome: 0.8076 |
|
| 74 |
+
| bqtl_spi1 | auprc | 0.1972 | AlphaGenome: 0.8167 |
|
| 75 |
+
| enhancer_gene | auprc | 0.5022 | AlphaGenome: 0.9594 |
|
| 76 |
+
| traitgym_mendelian | auprc | 0.1633 | Borzoi_L2_L2.plus.all: 0.5026; Enformer_L2_L2.plus.all: 0.5453; CADD.plus.RawScore: 0.7189; GPN-MSA_absLLR.plus.score: 0.6729 |
|
| 77 |
+
| traitgym_complex | auprc | 0.1851 | Borzoi_L2_L2.plus.all: 0.2945; Enformer_L2_L2.plus.all: 0.2692; CADD.plus.RawScore: 0.4134; GPN-MSA_absLLR.plus.score: 0.4214 |
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/attach_local.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Attach a zero-initialized local residual path to a checkpoint trained in this workspace."""
|
| 2 |
+
import argparse
|
| 3 |
+
from dataclasses import replace
|
| 4 |
+
import hashlib
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import yaml
|
| 9 |
+
|
| 10 |
+
from reference.alphagenome_50m.model import CompactModel, ModelConfig, count_parameters
|
| 11 |
+
from reference.alphagenome_50m.train_eval import _atomic_save
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def main():
|
| 15 |
+
p = argparse.ArgumentParser(description=__doc__)
|
| 16 |
+
p.add_argument('checkpoint', type=Path)
|
| 17 |
+
p.add_argument('output', type=Path)
|
| 18 |
+
p.add_argument('--width', type=int, default=32)
|
| 19 |
+
args = p.parse_args()
|
| 20 |
+
state = torch.load(args.checkpoint, map_location='cpu', weights_only=True)
|
| 21 |
+
assert state['schema'] == 'seqfunc-single/v1', 'only locally trained single-GPU checkpoints'
|
| 22 |
+
parent_config = ModelConfig(**state['config'])
|
| 23 |
+
assert parent_config.local_width == 0
|
| 24 |
+
torch.manual_seed(state['seed'])
|
| 25 |
+
parent = CompactModel(parent_config)
|
| 26 |
+
config = replace(parent_config, local_width=args.width)
|
| 27 |
+
model = CompactModel(config)
|
| 28 |
+
result = model.load_state_dict(state['model'], strict=False)
|
| 29 |
+
assert not result.unexpected_keys
|
| 30 |
+
assert all(k.startswith(('local_path.', 'local_projection.')) for k in result.missing_keys)
|
| 31 |
+
parent_names = list(dict(parent.named_parameters()))
|
| 32 |
+
names = list(dict(model.named_parameters()))
|
| 33 |
+
assert names[:len(parent_names)] == parent_names, 'optimizer parameter order changed'
|
| 34 |
+
assert len(state['optimizer']['param_groups']) == 1
|
| 35 |
+
group = state['optimizer']['param_groups'][0]
|
| 36 |
+
assert group['params'] == list(range(len(parent_names)))
|
| 37 |
+
group['params'] = list(range(len(names)))
|
| 38 |
+
state['model'] = model.state_dict()
|
| 39 |
+
state['config'] = config.to_dict()
|
| 40 |
+
state['intervention'] = {
|
| 41 |
+
'kind': 'base_resolution_local_path', 'width': args.width,
|
| 42 |
+
'parent_sha256': hashlib.sha256(args.checkpoint.read_bytes()).hexdigest(),
|
| 43 |
+
'attachment_step': state['global_step'], 'initial_outputs_unchanged': True,
|
| 44 |
+
}
|
| 45 |
+
args.output.mkdir(parents=True, exist_ok=False)
|
| 46 |
+
(args.output / 'config.yaml').write_text(yaml.safe_dump(config.to_dict()))
|
| 47 |
+
_atomic_save(state, args.output / 'attached.pt')
|
| 48 |
+
print({'parameters': count_parameters(model), **state['intervention']})
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
if __name__ == '__main__':
|
| 52 |
+
main()
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/infer.sh
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
[[ $# == 2 ]] || { echo "usage: infer.sh INPUT_ROOT OUTPUT_ROOT" >&2; exit 2; }
|
| 4 |
+
package_dir=$(cd "$(dirname "$0")" && pwd)
|
| 5 |
+
runtime_dir=$(mktemp -d "${TMPDIR:-/tmp}/seqfunc-runtime.XXXXXXXX")
|
| 6 |
+
trap 'rm -rf "$runtime_dir"' EXIT
|
| 7 |
+
tar -xzf "$package_dir/runtime.tar.gz" -C "$runtime_dir"
|
| 8 |
+
unset PYTHONPATH
|
| 9 |
+
export PYTHONHOME="$runtime_dir" PYTHONNOUSERSITE=1 PYTHONDONTWRITEBYTECODE=1
|
| 10 |
+
export LD_LIBRARY_PATH="$runtime_dir/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
|
| 11 |
+
export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 NUMEXPR_NUM_THREADS=4
|
| 12 |
+
"$runtime_dir/bin/python" -s "$package_dir/predict.py" "$1" "$2" --checkpoint "$package_dir/last.pt"
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/package_manifest.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"parameters": 13256456,
|
| 3 |
+
"source_checkpoint_sha256": "af8060229a79fbcb3e5ce34ee559af3724268ea7dc8e321bd12ce9d5f2d27e3a",
|
| 4 |
+
"files": {
|
| 5 |
+
"README.md": "101f591999fec21fdb5f09cabdab1e58f3d50ac366bc30458b67c4ce27c6b5f2",
|
| 6 |
+
"attach_local.py": "d0774e2711840783267914789ed303a3b61b64381b72d61f0886edbc04974f15",
|
| 7 |
+
"infer.sh": "ef810532b1e72b85fbe283e4f52c177bb70025977dbb2345d75837c9bbd51e37",
|
| 8 |
+
"last.pt": "fdef062e6c8de5ac6f73c764d638d6cd994fd001370628e19bf4365db4d57d86",
|
| 9 |
+
"perturb.py": "ba37a6f9f8b8eccb052903618bcb4c91d3f4cbed62dfe678ee362644dc80801e",
|
| 10 |
+
"perturb.sh": "113ec2383276a6e83fe1e4e8b0fa914f8d535d5dd0f5b2c34240140312dd5fb4",
|
| 11 |
+
"predict.py": "2725592456c55c188b22c376f0cb249e9f46b4ae1370d2226df7143da358a8b2",
|
| 12 |
+
"prediction_contract.py": "b11af8f7cff82b35afc6282be387358a48464b78bd1dfa44452dace26a5e0a83",
|
| 13 |
+
"reference/__init__.py": "45f3cf93f48859104e70bb58d717130dfd6521a45d2aba06b1a726afc0dc51dd",
|
| 14 |
+
"reference/alphagenome_50m/__init__.py": "a5a7e45d5940c3b201017c6322128e9f47efd37e1d29f717da2c1f787688eff9",
|
| 15 |
+
"reference/alphagenome_50m/alphagenome_50m.yaml": "3cac32e9f55e352dff78bb85ac892fdae1f9e412d9bba3e945750210c5252eee",
|
| 16 |
+
"reference/alphagenome_50m/dataset.py": "ad6670f742f4de9898064becc525d0aea98b402abe7b210bb1b26a9eee6402b9",
|
| 17 |
+
"reference/alphagenome_50m/layers.py": "26a116a72aa3f0e307a3606163547edbdecb7965f7fdcd96bc5f805cd21b3352",
|
| 18 |
+
"reference/alphagenome_50m/model.py": "2871dc8893879c3e14a526dea659701d72c8c4d0e2f835b0bfb857034a2c2e6d",
|
| 19 |
+
"reference/alphagenome_50m/reference_large.yaml": "68084d299b39418034c6bbf71db174c3ffa68bbeea8779c1694e44ec71f3529c",
|
| 20 |
+
"reference/alphagenome_50m/run_ddp.sh": "96d35a24a4e6789311501fb98203807ac0c4429375c44d5c6671908270c93bb0",
|
| 21 |
+
"reference/alphagenome_50m/tiny_overfit.yaml": "f7a104c3929de0530a9a8f73f66d794cca595aefad8ef262e09ecbeb9cfce6de",
|
| 22 |
+
"reference/alphagenome_50m/train_eval.py": "95d2dad279b23ed9c0c8a4f070035cf53c27eb8fe27da64c441343717174f784",
|
| 23 |
+
"runtime.tar.gz": "718da4c374e0c552b6e429b226c90b2fded5c900d95577d190d4df520aaf3901",
|
| 24 |
+
"train_single.py": "a6653431e850d448c414f48cc65cbaaec8c17a430c08376b281441a6f6bce987",
|
| 25 |
+
"training_config.yaml": "deab298b32f0aef33e66ddf538541ec470eee0c05a6ebc983684f2575287d791",
|
| 26 |
+
"training_provenance.json": "1a721e47432865cf50c2ff1a14ac3cc97b2926da28dff75023e7d008c55a9793",
|
| 27 |
+
"validation_tracks.json": "c8a25d419cc2df7c7d834d49d89cf7fe9f2975374c0048dca7035b0c20dc4420",
|
| 28 |
+
"validation_variants.json": "41cd2d3e0548c520def53c102fbb8e99c5c7c473d807d62b0d5bc0376f7adbd4"
|
| 29 |
+
}
|
| 30 |
+
}
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/perturb.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Predict both sequences of every perturbation (contract: perturbations/v1).
|
| 2 |
+
|
| 3 |
+
python perturb.py INPUT_ROOT OUTPUT_ROOT --checkpoint last.pt
|
| 4 |
+
|
| 5 |
+
INPUT_ROOT holds `public/perturbations.parquet` and `reference/GRCh38.p13.genome.fa` (in the
|
| 6 |
+
workspace, `/workspace/data` works too: the queries are then read from `variant_evals/public/`). Each row is a
|
| 7 |
+
1,048,576-bp window starting at `input_start` and an edit spanning [edit_start, edit_end) in genomic
|
| 8 |
+
0-based coordinates:
|
| 9 |
+
|
| 10 |
+
- `snv`: sequence A carries `allele_a` at edit_start, sequence B carries `allele_b` (both are written
|
| 11 |
+
explicitly; either may differ from the reference genome);
|
| 12 |
+
- `mask`: sequence A is the reference, sequence B has the interval replaced by N.
|
| 13 |
+
|
| 14 |
+
For each perturbation the output group `perturbations/p{index:06d}` holds `a/<family>` and
|
| 15 |
+
`b/<family>` for every family in `families`: dense families sliced to bins
|
| 16 |
+
[dense_bin_start, dense_bin_end) of the central target window, and `splice_sites` sliced to bp
|
| 17 |
+
[splice_start, splice_end). Values are the same quantities as predictions.zarr (asinh space for
|
| 18 |
+
dense tracks, splice-site scores for splice_sites).
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import argparse
|
| 24 |
+
import json
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
from numcodecs import Blosc
|
| 28 |
+
import numpy as np
|
| 29 |
+
import pandas as pd
|
| 30 |
+
import pysam
|
| 31 |
+
import torch
|
| 32 |
+
import zarr
|
| 33 |
+
|
| 34 |
+
from reference.alphagenome_50m.dataset import AlphaGenomeDataset
|
| 35 |
+
from reference.alphagenome_50m.model import CompactModel, ModelConfig
|
| 36 |
+
|
| 37 |
+
PERTURBATION_SCHEMA = "genome-sequence-to-function-perturbations/v1"
|
| 38 |
+
COMPRESSOR = Blosc(cname="zstd", clevel=3, shuffle=Blosc.BITSHUFFLE)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def sequences(fasta, row) -> tuple[str, str]:
|
| 42 |
+
length = fasta.get_reference_length(row.chrom)
|
| 43 |
+
start, end = int(row.input_start), int(row.input_start) + 1_048_576
|
| 44 |
+
sequence = fasta.fetch(row.chrom, max(0, start), min(length, end)).upper()
|
| 45 |
+
sequence = "N" * max(0, -start) + sequence + "N" * max(0, end - length)
|
| 46 |
+
lo, hi = int(row.edit_start) - start, int(row.edit_end) - start
|
| 47 |
+
if row.edit == "snv":
|
| 48 |
+
return sequence[:lo] + row.allele_a + sequence[hi:], sequence[:lo] + row.allele_b + sequence[hi:]
|
| 49 |
+
if row.edit == "mask":
|
| 50 |
+
return sequence, sequence[:lo] + "N" * (hi - lo) + sequence[hi:]
|
| 51 |
+
raise ValueError(f"unknown edit {row.edit!r}")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def main(input_root: Path, output_root: Path, checkpoint: Path, queries: Path | None = None) -> None:
|
| 55 |
+
payload = torch.load(checkpoint, map_location="cpu", weights_only=True)
|
| 56 |
+
config = ModelConfig(**payload["config"])
|
| 57 |
+
model = CompactModel(config)
|
| 58 |
+
model.load_state_dict(payload["model"], strict=True)
|
| 59 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 60 |
+
model.to(device).eval()
|
| 61 |
+
if queries is None:
|
| 62 |
+
queries = input_root / "public/perturbations.parquet"
|
| 63 |
+
if not queries.exists():
|
| 64 |
+
queries = input_root / "variant_evals/public/perturbations.parquet"
|
| 65 |
+
rows = pd.read_parquet(queries)
|
| 66 |
+
fasta = pysam.FastaFile(str(input_root / "reference/GRCh38.p13.genome.fa"))
|
| 67 |
+
output_root.mkdir(parents=True, exist_ok=True)
|
| 68 |
+
root = zarr.open_group(str(output_root / "perturbations.zarr"), mode="w")
|
| 69 |
+
target_start = (config.input_length - config.target_length) // 2
|
| 70 |
+
with torch.inference_mode():
|
| 71 |
+
for index, row in enumerate(rows.itertuples(index=False)):
|
| 72 |
+
pair = sequences(fasta, row)
|
| 73 |
+
dna = torch.from_numpy(np.stack([AlphaGenomeDataset._one_hot(s) for s in pair])).to(device)
|
| 74 |
+
trunk = model._trunk(dna)
|
| 75 |
+
group = root.create_group(f"perturbations/p{index:06d}")
|
| 76 |
+
features = None
|
| 77 |
+
for family in row.families:
|
| 78 |
+
if family == "splice_sites":
|
| 79 |
+
logits = model._splice_site_logits(trunk)[:, target_start:target_start + config.target_length]
|
| 80 |
+
values = logits[:, row.splice_start:row.splice_end]
|
| 81 |
+
else:
|
| 82 |
+
features = model._dense_features(trunk) if features is None else features
|
| 83 |
+
values = model.dense_heads[family](features)[:, row.dense_bin_start:row.dense_bin_end]
|
| 84 |
+
# float32: one variant's effect is often below float16 resolution (about 0.004 at
|
| 85 |
+
# asinh values of 4-8), so A and B would round to the same numbers.
|
| 86 |
+
values = values.float().cpu().numpy()
|
| 87 |
+
for side, array in zip("ab", values):
|
| 88 |
+
group.create_dataset(f"{side}/{family}", data=array, compressor=COMPRESSOR)
|
| 89 |
+
print(json.dumps({"event": "perturb", "done": index + 1, "total": len(rows)}), flush=True)
|
| 90 |
+
root.attrs.update({"schema": PERTURBATION_SCHEMA,
|
| 91 |
+
"perturbation_ids": rows.perturbation_id.astype(str).tolist()})
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
if __name__ == "__main__":
|
| 95 |
+
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 96 |
+
parser.add_argument("input_root", type=Path)
|
| 97 |
+
parser.add_argument("output_root", type=Path)
|
| 98 |
+
parser.add_argument("--checkpoint", type=Path, default=Path(__file__).resolve().parent / "last.pt")
|
| 99 |
+
parser.add_argument("--queries", type=Path, help="another query table, e.g. the development split")
|
| 100 |
+
args = parser.parse_args()
|
| 101 |
+
main(args.input_root, args.output_root, args.checkpoint, args.queries)
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/perturb.sh
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
[[ $# == 2 ]] || { echo "usage: perturb.sh INPUT_ROOT OUTPUT_ROOT" >&2; exit 2; }
|
| 4 |
+
package_dir=$(cd "$(dirname "$0")" && pwd)
|
| 5 |
+
runtime_dir=$(mktemp -d "${TMPDIR:-/tmp}/seqfunc-runtime.XXXXXXXX")
|
| 6 |
+
trap 'rm -rf "$runtime_dir"' EXIT
|
| 7 |
+
tar -xzf "$package_dir/runtime.tar.gz" -C "$runtime_dir"
|
| 8 |
+
unset PYTHONPATH
|
| 9 |
+
export PYTHONHOME="$runtime_dir" PYTHONNOUSERSITE=1 PYTHONDONTWRITEBYTECODE=1
|
| 10 |
+
export LD_LIBRARY_PATH="$runtime_dir/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
|
| 11 |
+
export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 NUMEXPR_NUM_THREADS=4
|
| 12 |
+
"$runtime_dir/bin/python" -s "$package_dir/perturb.py" "$1" "$2" --checkpoint "$package_dir/last.pt"
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/predict.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Stream the single benchmark model into the sharded prediction contract."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
from numcodecs import Blosc
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
import zarr
|
| 14 |
+
|
| 15 |
+
from prediction_contract import DENSE_TRACKS, MAX_JUNCTION_PAIRS, MAX_USAGE_SITES, PREDICTION_SCHEMA
|
| 16 |
+
from reference.alphagenome_50m.dataset import AlphaGenomeDataset
|
| 17 |
+
from reference.alphagenome_50m.model import CompactModel, ModelConfig
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
COMPRESSOR = Blosc(cname="zstd", clevel=7, shuffle=Blosc.BITSHUFFLE)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def main(input_root: Path, output_root: Path, checkpoint: Path, split: str = "test") -> None:
|
| 24 |
+
payload = torch.load(checkpoint, map_location="cpu", weights_only=True)
|
| 25 |
+
config = ModelConfig(**payload["config"])
|
| 26 |
+
model = CompactModel(config)
|
| 27 |
+
model.load_state_dict(payload["model"], strict=True)
|
| 28 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 29 |
+
model.to(device).eval()
|
| 30 |
+
dataset = AlphaGenomeDataset(input_root, split, include_targets=False)
|
| 31 |
+
model.set_junction_track_halves(dataset.junction_track_halves)
|
| 32 |
+
output_root.mkdir(parents=True, exist_ok=True)
|
| 33 |
+
root = zarr.open_group(str(output_root / "predictions.zarr"), mode="w")
|
| 34 |
+
ids = []
|
| 35 |
+
with torch.inference_mode():
|
| 36 |
+
for sample in dataset:
|
| 37 |
+
example_id = sample["example_id"]
|
| 38 |
+
dna = sample["dna"][None].to(device)
|
| 39 |
+
trunk = model._trunk(dna)
|
| 40 |
+
dense_features = model._dense_features(trunk)
|
| 41 |
+
group = root.create_group(f"examples/{example_id}")
|
| 42 |
+
for family in DENSE_TRACKS:
|
| 43 |
+
values = model.dense_heads[family](dense_features)[0]
|
| 44 |
+
group.create_dataset(family, data=values.cpu().numpy().astype(np.float16), compressor=COMPRESSOR)
|
| 45 |
+
|
| 46 |
+
all_site_logits = model._splice_site_logits(trunk)
|
| 47 |
+
target_start = (config.input_length - config.target_length) // 2
|
| 48 |
+
group.create_dataset(
|
| 49 |
+
"splice_sites",
|
| 50 |
+
data=all_site_logits[0, target_start:target_start + config.target_length].cpu().numpy().astype(np.float16),
|
| 51 |
+
chunks=(4096, 4), compressor=COMPRESSOR,
|
| 52 |
+
)
|
| 53 |
+
predicted_positions = model.select_junction_positions(all_site_logits)[0]
|
| 54 |
+
|
| 55 |
+
# Usage at the model's own predicted sites (v4 is sparse; unlisted hidden sites score 0).
|
| 56 |
+
usage_bins = model.splice_usage_head(dense_features)[0].float()
|
| 57 |
+
sites = predicted_positions.cpu().numpy().astype(np.int64).reshape(-1)
|
| 58 |
+
sites = np.unique(sites[(sites >= target_start) & (sites < target_start + config.target_length)]
|
| 59 |
+
- target_start)[:MAX_USAGE_SITES]
|
| 60 |
+
group.create_dataset("splice_usage_positions", data=sites.astype(np.int32), compressor=COMPRESSOR)
|
| 61 |
+
usage = usage_bins[torch.as_tensor(sites // 128, device=usage_bins.device)] if len(sites) \
|
| 62 |
+
else usage_bins[:0]
|
| 63 |
+
group.create_dataset("splice_usage", data=usage.cpu().numpy().astype(np.float16),
|
| 64 |
+
chunks=(1024, 734), compressor=COMPRESSOR)
|
| 65 |
+
|
| 66 |
+
# Junctions: score every donor x acceptor pair of each strand, keep the strongest pairs.
|
| 67 |
+
positions_batch = predicted_positions[None]
|
| 68 |
+
site_factors = model.junction_site_factors(trunk, positions_batch)
|
| 69 |
+
halves = model.junction_track_half
|
| 70 |
+
candidates = []
|
| 71 |
+
for row_start in range(0, 512, 128):
|
| 72 |
+
for column_start in range(0, 512, 128):
|
| 73 |
+
block = torch.cat([
|
| 74 |
+
model.junction_block(
|
| 75 |
+
trunk, positions_batch, row_start, row_start + 128,
|
| 76 |
+
column_start, column_start + 128, track_start,
|
| 77 |
+
min(track_start + 64, config.junction_tracks), site_factors,
|
| 78 |
+
)[0]
|
| 79 |
+
for track_start in range(0, config.junction_tracks, 64)
|
| 80 |
+
], dim=-1).float() # [128, 128, 734]
|
| 81 |
+
for half in (0, 1):
|
| 82 |
+
donors = predicted_positions[2 * half, row_start:row_start + 128]
|
| 83 |
+
acceptors = predicted_positions[2 * half + 1, column_start:column_start + 128]
|
| 84 |
+
valid = (donors[:, None] >= 0) & (acceptors[None, :] >= 0)
|
| 85 |
+
strength = block[..., halves == half].amax(dim=-1).masked_fill(~valid, -torch.inf)
|
| 86 |
+
keep = min(MAX_JUNCTION_PAIRS // 2, int(valid.sum()))
|
| 87 |
+
if not keep:
|
| 88 |
+
continue
|
| 89 |
+
best = strength.flatten().topk(keep)
|
| 90 |
+
rows, columns = best.indices // 128, best.indices % 128
|
| 91 |
+
candidates.append((best.values, torch.full_like(rows, half), donors[rows],
|
| 92 |
+
acceptors[columns], block[rows, columns]))
|
| 93 |
+
if candidates:
|
| 94 |
+
score, half, donor, acceptor, values = (torch.cat(x) for x in zip(*candidates))
|
| 95 |
+
order = score.topk(min(MAX_JUNCTION_PAIRS, len(score))).indices
|
| 96 |
+
half, donor, acceptor, values = half[order], donor[order], acceptor[order], values[order]
|
| 97 |
+
else:
|
| 98 |
+
half = donor = acceptor = torch.zeros(0, dtype=torch.long)
|
| 99 |
+
values = torch.zeros(0, config.junction_tracks)
|
| 100 |
+
group.create_dataset("junction_half", data=half.cpu().numpy().astype(np.int8), compressor=COMPRESSOR)
|
| 101 |
+
group.create_dataset("junction_donor", data=donor.cpu().numpy().astype(np.int32), compressor=COMPRESSOR)
|
| 102 |
+
group.create_dataset("junction_acceptor", data=acceptor.cpu().numpy().astype(np.int32), compressor=COMPRESSOR)
|
| 103 |
+
group.create_dataset("junctions", data=values.cpu().numpy().astype(np.float16),
|
| 104 |
+
chunks=(4096, 734), compressor=COMPRESSOR)
|
| 105 |
+
|
| 106 |
+
contact = trunk.reshape(
|
| 107 |
+
1, config.contact_bins, -1, config.hidden_dim
|
| 108 |
+
).mean(dim=2)
|
| 109 |
+
q, k = model.contact_q(contact), model.contact_k(contact)
|
| 110 |
+
row, column = model.contact_row, model.contact_column
|
| 111 |
+
contact_values = 0.5 * (q[:, row] * k[:, column] + q[:, column] * k[:, row])
|
| 112 |
+
group.create_dataset(
|
| 113 |
+
"contact_maps", data=contact_values[0].cpu().numpy().astype(np.float16),
|
| 114 |
+
chunks=(8192, 28), compressor=COMPRESSOR,
|
| 115 |
+
)
|
| 116 |
+
ids.append(example_id)
|
| 117 |
+
print(json.dumps({"event": "predict", "example": len(ids), "total": len(dataset)}), flush=True)
|
| 118 |
+
root.attrs.update({"schema": PREDICTION_SCHEMA, "example_ids": ids})
|
| 119 |
+
(output_root / "example_ids.json").write_text(json.dumps(ids) + "\n")
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
if __name__ == "__main__":
|
| 123 |
+
parser = argparse.ArgumentParser()
|
| 124 |
+
parser.add_argument("input_root", type=Path)
|
| 125 |
+
parser.add_argument("output_root", type=Path)
|
| 126 |
+
parser.add_argument("--checkpoint", type=Path, default=Path(__file__).resolve().parent / "last.pt")
|
| 127 |
+
parser.add_argument("--split", default="test", choices=("valid", "test"),
|
| 128 |
+
help="manifest to predict; the verifier uses test, local validation uses valid")
|
| 129 |
+
args = parser.parse_args()
|
| 130 |
+
main(args.input_root, args.output_root, args.checkpoint, args.split)
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/prediction_contract.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Public prediction shapes; no trusted splice coordinates are exposed."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
DENSE_TRACKS = {
|
| 6 |
+
"atac": 167,
|
| 7 |
+
"dnase": 305,
|
| 8 |
+
"procap": 12,
|
| 9 |
+
"cage": 546,
|
| 10 |
+
"rna_seq": 667,
|
| 11 |
+
"chip_tf": 1_617,
|
| 12 |
+
"chip_histone": 1_116,
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
PREDICTION_SCHEMA = "genome-sequence-to-function-predictions/v4"
|
| 16 |
+
MAX_USAGE_SITES = 4_096
|
| 17 |
+
MAX_JUNCTION_PAIRS = 16_384
|
| 18 |
+
# Fixed-shape arrays per example; splice usage and junctions are sparse (see contract.md).
|
| 19 |
+
FIXED_SHAPES = {
|
| 20 |
+
**{name: (1_536, tracks) for name, tracks in DENSE_TRACKS.items()},
|
| 21 |
+
"splice_sites": (196_608, 4),
|
| 22 |
+
"contact_maps": (131_328, 28),
|
| 23 |
+
}
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/reference/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""The reference model of the alphagenome-reference baseline."""
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/reference/alphagenome_50m/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compact 1-Mb, eleven-family AlphaGenome reference model."""
|
| 2 |
+
|
| 3 |
+
from .model import CompactModel, ModelConfig, count_parameters
|
| 4 |
+
|
| 5 |
+
__all__ = ["CompactModel", "ModelConfig", "count_parameters"]
|
tasks/genome-sequence-to-function/genome-sequence-to-function-astra-xhigh-1h100-48h-20261022a/submissions/S004/reference/alphagenome_50m/alphagenome_50m.yaml
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
input_length: 1048576
|
| 2 |
+
target_length: 196608
|
| 3 |
+
dense_bin_size: 128
|
| 4 |
+
trunk_bin_size: 1024
|
| 5 |
+
contact_bin_size: 2048
|
| 6 |
+
stem_stride: 8
|
| 7 |
+
encoder_width: 32
|
| 8 |
+
channel_growth: 32
|
| 9 |
+
num_downsampling_blocks: 7
|
| 10 |
+
conv_kernel_size: 5
|
| 11 |
+
dna_kernel_size: 15
|
| 12 |
+
hidden_dim: 384
|
| 13 |
+
num_sequence_blocks: 6
|
| 14 |
+
num_attention_heads: 6
|
| 15 |
+
attention_head_dim: 64
|
| 16 |
+
mlp_expansion: 4.0
|
| 17 |
+
dropout: 0.0
|
| 18 |
+
head_hidden_size: 256
|
| 19 |
+
junction_rank: 32
|
| 20 |
+
splice_usage_tracks: 734
|
| 21 |
+
junction_tracks: 734
|
| 22 |
+
contact_tracks: 28
|
| 23 |
+
gradient_checkpointing: true
|