# BridgeRNA BridgeRNA is a bulk RNA-seq foundation model for gene expression imputation, sample embeddings and downstream prediction. It was developed at NASA Ames Research Center with funding from NASA's Biological and Physical Sciences Division (BPS). ## Model BRIDGE uses a 45.6-million-parameter Transformer with 12 layers, eight attention heads and 512-dimensional gene representations. Learned gene identity vectors are combined with sinusoidal expression encodings. Attention uses PyTorch's scaled-dot-product implementation with Flash kernels where supported. The model accepts **15,165 genes in a fixed order**, predicts natural `log1p(TPM)` expression and produces **512-dimensional sample embeddings** by averaging final-layer gene representations. It was trained with 15% masking. Mouse inputs use one-to-one human orthologs. ## Installation Python 3.10+ is required; Python 3.11 is tested. Install a PyTorch build appropriate for your hardware. A CUDA GPU is recommended for full-length inference. From the AI4LS repository root: ```bash python -m pip install -e ./BridgeRNA ``` Or from this directory: ```bash python -m pip install -e . ``` For tests and notebook support, install `python -m pip install -e '.[dev]'`. ## Load the model Pretrained weights will be available at [nasa-compbio/NASA-BridgeRNA-Foundation-Model](https://huggingface.co/nasa-compbio/NASA-BridgeRNA-Foundation-Model). Until uploaded, use a local model bundle. ```python from bridgerna import from_pretrained model = from_pretrained("/path/to/model_bundle", device="cuda") # Once weights are available on Hugging Face: # model = from_pretrained("nasa-compbio/NASA-BridgeRNA-Foundation-Model", device="cuda") ``` A model bundle contains `model.pt`, `config.json`, `canonical_genes.csv` and `preprocessing.json`. Loading verifies the gene order and checkpoint structure. ## Prepare expression data Provide a DataFrame with **samples as rows and genes as columns**. Inputs are converted to float32 natural `log1p(TPM)` and aligned to the canonical vocabulary. ```python import pandas as pd from bridgerna import prepare_expression expression = pd.read_csv("samples_by_genes_tpm.csv", index_col=0) x, audit = prepare_expression(expression, input_type="tpm", species="human") print(audit["matched_canonical_genes"]) ``` - Input types: `counts`, `tpm` or `log1p_tpm`. - Select `gene_id_type="ensembl"` for Ensembl identifiers; the default is gene symbols. - Raw counts require species-correct exon lengths. Bundled human and mouse length tables are used by default. TPM normalization includes supplied genes with valid lengths before ortholog restriction. - Missing canonical genes are zero-filled and reported in `audit`; duplicate or ambiguous mappings are rejected. Inspect mapping losses before analysis. - For mouse data, set `species="mouse"`. Mouse lengths are applied before mapping to human orthologs. ## Impute missing expression Use an explicit boolean mask to identify missing values. Observed zero expression is valid data. The model uses **−10** as its mask token; do not renormalize after masking. ```python import numpy as np from bridgerna import impute mask = np.zeros(x.shape, dtype=bool) mask[:, 10:20] = True # replace with your missing-gene positions completed = impute(model, x, mask, batch_size=1) ``` `impute` preserves observed values. Outputs remain in natural `log1p(TPM)` space and can be negative; they are not clipped or renormalized automatically. ## Extract embeddings ```python from bridgerna import extract_embeddings embeddings = extract_embeddings(model, x, batch_size=1) # samples × 512 ``` Set `normalize=True` for L2-normalized sample embeddings. ## Examples and downstream prediction The scripts in `examples/` demonstrate the API with synthetic inputs. Run them with `--bundle /path/to/model_bundle --device cuda`. | File | Purpose | | --- | --- | | `load_model.py` | Load weights and inspect model dimensions. | | `gene_imputation.py` | Reconstruct explicitly masked genes. | | `extract_embeddings.py` | Extract sample embeddings. | | `train_prediction_head.py` | Train a linear prediction head with the backbone frozen. | | `preprocess.py` | Prepare a samples-by-genes CSV and save gene/sample manifests. | | `quickstart.ipynb` | Walk through loading, embeddings and imputation. | For real prediction tasks, use study-disjoint training and evaluation sets. `training/masked_reconstruction.py --help` provides a continued-training recipe. An optional GTEx-trained Hallmark head maps sample embeddings to 50 predicted pathway scores through `bridgerna.inference.hallmark.score_hallmarks`. These are predicted expression-derived scores, not direct measurements of pathway activity. ## Benchmarks The [benchmark suite](benchmarks/README.md) includes executed reports, numerical results and analysis code for imputation, representation analysis, gene-function prediction, tissue/cancer classification, survival, drug response, drug discovery, retrieval geometry, Hallmark retrieval, cross-species epilepsy and lung organoid exposure. ```bash python -m pip install -e '.[benchmarks]' python benchmarks/run_reports.py # Run a selected report: python benchmarks/run_reports.py --benchmark hallmark_retrieval ``` Reports run from included saved evidence. Full analysis scripts and external data requirements are documented in each benchmark's `INPUTS.md`. For a new imputation cohort, use `python benchmarks/imputation/evaluate.py --help`. Run software tests with `python -m pytest`. ## Repository structure ```text BridgeRNA/ ├── bridgerna/ # model, preprocessing and inference ├── configs/ # model and preprocessing settings ├── examples/ # usage scripts and quickstart notebook ├── benchmarks/ # evaluation tools ├── training/ # continued-training recipe ├── tests/ # software and numerical checks └── docs/ # technical documentation ``` ## Limitations BridgeRNA is intended for research on bulk RNA-seq. Validate new assays, species, gene coverage and missingness patterns before use. It is not a clinical diagnostic or a validated batch-correction method. Embedding similarity and predicted Hallmark scores do not establish causal biological mechanisms. ## Authors and citation See [AUTHORS.md](AUTHORS.md) for authors and affiliations. Manuscript in preparation; a public citation will be added when available. ## License Source code, pretrained weights and the frozen Hallmark head are licensed under [Apache 2.0](LICENSE). See [NOTICE](NOTICE) for attribution and [annotation resources](docs/ANNOTATION_RESOURCES.md) for third-party terms.