Token Classification
Transformers
Safetensors
generanno
dna
genomics
biology
genome-annotation
custom_code
Run this model with HF Jobs
Run HuggingFaceBio/Carbon-A-1.2B on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/HuggingFaceBio/Carbon-A-1.2B. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/HuggingFaceBio/Carbon-A-1.2B on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use HuggingFaceBio/Carbon-A-1.2B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use HuggingFaceBio/Carbon-A-1.2B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="HuggingFaceBio/Carbon-A-1.2B", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForTokenClassification model = AutoModelForTokenClassification.from_pretrained("HuggingFaceBio/Carbon-A-1.2B", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Support long records and write raw probabilities as Arrow IPC files
Browse filesFiles changed (17)
- README.md+1-1
- annotation_pipeline/README.md+8-6
- annotation_pipeline/run_annotation.sh+17-6
- annotation_pipeline/src/confidence_network.py+109-46
- annotation_pipeline/src/constants.py+33-22
- annotation_pipeline/src/model_inference.py+119-75
- annotation_pipeline/src/post_processing.py+141-85
- annotation_pipeline/src/tcn.py+21-19
- annotation_pipeline/src/transition_network.py+21-15
- annotation_pipeline/src/utils.py+159-108
- annotation_pipeline/src/viterbi.py+110-111
- annotation_pipeline/src/viterbi_backends/viterbi_cpu.cpp+123-684
- annotation_pipeline/src/viterbi_backends/decode_cpu.py → annotation_pipeline/src/viterbi_backends/viterbi_cpu.pyRenamed+15-26
- annotation_pipeline/src/viterbi_backends/viterbi_gpu.cu
- annotation_pipeline/src/viterbi_backends/decode_gpu.py → annotation_pipeline/src/viterbi_backends/viterbi_gpu.pyRenamed+39-83
- annotation_pipeline/src/viterbi_backends/viterbi_grammar.hAdded+705
- requirements.txt-1
56 unmodified lines5758596061626356 unmodified lines- `prediction.gff`: genes, mRNAs, and CDS. Every gene carries a model-derived `confidence` score for its predicted structure; higher values indicate greater model confidence.- `prediction.fna` and `prediction.faa`: the CDS and protein sequences.- `*.raw_probs.parquet`: the per-base CDS probabilities.All genes are written. The reported results count the genes with a confidence of at least 0.1.56 unmodified lines5758596061626356 unmodified lines- `prediction.gff`: genes, mRNAs, and CDS. Every gene carries a model-derived `confidence` score for its predicted structure; higher values indicate greater model confidence.- `prediction.fna` and `prediction.faa`: the CDS and protein sequences.- `*.raw_probs.arrow` or `*.raw_probs.parquet`: the per-base CDS probabilities.All genes are written. The reported results count the genes with a confidence of at least 0.1.
96 unmodified lines9798991001011021038 unmodified lines11211311411511611711811914 unmodified lines1341351361371381391402 unmodified lines14314414514614714814998 unmodified lines24824925025125225325496 unmodified lines```textresults/<accession>/*.raw_probs.parquetprediction.gffprediction.fnaprediction.faa8 unmodified linesthe number of threads. `--model` selects another model, aHub id or a local directory (default: `CARBON_A_MODEL`, otherwise`HuggingFaceBio/Carbon-A-1.2B`), and `--revision` a branch, tag, or commit of amodel on the Hub (default: the latest). `run_annotation.sh --help` lists everyoption.When the codon-table check described below fails, the post-processing itselfappends the warning to `results/WARNINGS.txt` (time, accession, message with14 unmodified linespost-processing excludes records shorter than 100,000 bp and spliced CDSmodels shorter than 96 bp. Set `--min-record-length 0` or `--min-cds-length 0`to disable the corresponding filter. Use `--skip-inference` to rerun onlypost-processing from an existing raw-probability Parquet file.Post-processing options: `--transition-network FILE` and`--confidence-network FILE` select other weight files and `--tcn-device DEVICE`2 unmodified linesOn CUDA the networks run under bfloat16 autocast, the precision used for allreported results; on CPU they run in float32. `--viterbi-backend` selects theViterbi backend. `src/post_processing.py` can also be run directly on araw-probability Parquet file.`GCF_000189635.1` (Tetrahymena thermophila) automatically uses NCBI translationtable 6. Other accessions use the standard translation table unless an98 unmodified lines```textresults/<accession>/*.raw_probs.parquetprediction.gffprediction.fnaprediction.faa96 unmodified lines9798991001011021038 unmodified lines11211311411511611711811912012114 unmodified lines1361371381391401411422 unmodified lines14514614714814915015198 unmodified lines25025125225325425525696 unmodified lines```textresults/<accession>/*.raw_probs.arrowprediction.gffprediction.fnaprediction.faa8 unmodified linesthe number of threads. `--model` selects another model, aHub id or a local directory (default: `CARBON_A_MODEL`, otherwise`HuggingFaceBio/Carbon-A-1.2B`), and `--revision` a branch, tag, or commit of amodel on the Hub (default: the latest). The raw probabilities are written as anArrow IPC file; `--raw-probs-format parquet` writes a Parquet file(`*.raw_probs.parquet`) instead, for records of at most 1,000,000,000 bp.`run_annotation.sh --help` lists every option.When the codon-table check described below fails, the post-processing itselfappends the warning to `results/WARNINGS.txt` (time, accession, message with14 unmodified linespost-processing excludes records shorter than 100,000 bp and spliced CDSmodels shorter than 96 bp. Set `--min-record-length 0` or `--min-cds-length 0`to disable the corresponding filter. Use `--skip-inference` to rerun onlypost-processing from an existing raw-probability file.Post-processing options: `--transition-network FILE` and`--confidence-network FILE` select other weight files and `--tcn-device DEVICE`2 unmodified linesOn CUDA the networks run under bfloat16 autocast, the precision used for allreported results; on CPU they run in float32. `--viterbi-backend` selects theViterbi backend. `src/post_processing.py` can also be run directly on araw-probability file.`GCF_000189635.1` (Tetrahymena thermophila) automatically uses NCBI translationtable 6. Other accessions use the standard translation table unless an98 unmodified lines```textresults/<accession>/*.raw_probs.arrowprediction.gffprediction.fnaprediction.faa
23 unmodified lines2425262728292 unmodified lines3233343536373826 unmodified lines656667686970717 unmodified lines79808182838485104 unmodified lines19019119219319419574 unmodified lines2702712722732742753 unmodified lines27928028128228328428528628713 unmodified lines30130230330430530630730830931023 unmodified linesBATCH_SIZE="1"DISPATCH_CHUNK_SIZE="4"ATTN_IMPLEMENTATION="flash_attention_2"SKIP_INFERENCE=0TRANSITION_NETWORK=""2 unmodified linesMIN_RECORD_LENGTH="100000"MIN_CDS_LENGTH="96"MAX_BOUNDARY_INTRON_LENGTH="20000"CHUNK_MBP="500"PREDICTION_PREFIX=""RAW_PROBS=""26 unmodified lines--dispatch-chunk-size N Per-GPU dispatch chunk size (default: 4).--attn-implementation NAME flash_attention_2 (default; used for all reported results)or sdpa (needs no flash-attn package; not bit-identical).--skip-inference Reuse the newest *.raw_probs.parquet in --output-dir.Post-processing:--viterbi-backend NAME Viterbi backend: auto, gpu, cpu, or numba (default: auto).7 unmodified lines--min-cds-length N Minimum spliced CDS length (default: 96).--max-boundary-intron-length NMaximum boundary intron length (default: 20000).--chunk-mbp N Post-processing chunk size in Mbp (default: 500).-h, --help Show this help message.EOF104 unmodified linesATTN_IMPLEMENTATION="$2"shift 2;;--skip-inference)SKIP_INFERENCE=1shift74 unmodified lines--batch_size "$BATCH_SIZE"--dispatch_chunk_size "$DISPATCH_CHUNK_SIZE"--attn_implementation "$ATTN_IMPLEMENTATION")[[ -n "$MODEL" ]] && inference_args+=(--model_name "$MODEL")[[ -n "$REVISION" ]] && inference_args+=(--revision "$REVISION")3 unmodified lines}select_raw_probs() {local candidates=("$OUTPUT_DIR"/*.raw_probs.parquet)(( ${#candidates[@]} > 0 )) || \die "no raw-probability Parquet found in $OUTPUT_DIR"RAW_PROBS="${candidates[0]}"local candidate13 unmodified lines--viterbi_backend "$VITERBI_BACKEND"--codon_table "$CODON_TABLE"--max_boundary_intron_length "$MAX_BOUNDARY_INTRON_LENGTH"--chunk_mbp "$CHUNK_MBP"--min_record_length "$MIN_RECORD_LENGTH"--min_cds_length "$MIN_CDS_LENGTH")[[ -n "$TRANSITION_NETWORK" ]] && postprocess_args+=(--transition_network "$TRANSITION_NETWORK")[[ -n "$CONFIDENCE_NETWORK" ]] && postprocess_args+=(--confidence_network "$CONFIDENCE_NETWORK")[[ -n "$TCN_DEVICE" ]] && postprocess_args+=(--tcn_device "$TCN_DEVICE")23 unmodified lines242526272829302 unmodified lines3334353637383926 unmodified lines666768697071727374757 unmodified lines8384858687888990104 unmodified lines19519619719819920020120220320420574 unmodified lines2802812822832842852863 unmodified lines29029129229329429529629729813 unmodified lines31231331431531631731831932032123 unmodified linesBATCH_SIZE="1"DISPATCH_CHUNK_SIZE="4"ATTN_IMPLEMENTATION="flash_attention_2"RAW_PROBS_FORMAT="arrow"SKIP_INFERENCE=0TRANSITION_NETWORK=""2 unmodified linesMIN_RECORD_LENGTH="100000"MIN_CDS_LENGTH="96"MAX_BOUNDARY_INTRON_LENGTH="20000"CHUNK_MBP=""PREDICTION_PREFIX=""RAW_PROBS=""26 unmodified lines--dispatch-chunk-size N Per-GPU dispatch chunk size (default: 4).--attn-implementation NAME flash_attention_2 (default; used for all reported results)or sdpa (needs no flash-attn package; not bit-identical).--raw-probs-format NAME arrow (default; Arrow IPC, *.raw_probs.arrow) or parquet(*.raw_probs.parquet; records of at most 1,000,000,000 bp).--skip-inference Reuse the newest *.raw_probs.arrow or *.raw_probs.parquetin --output-dir.Post-processing:--viterbi-backend NAME Viterbi backend: auto, gpu, cpu, or numba (default: auto).7 unmodified lines--min-cds-length N Minimum spliced CDS length (default: 96).--max-boundary-intron-length NMaximum boundary intron length (default: 20000).--chunk-mbp N Post-processing chunk size in Mbp (default: 25, or 1000with the CPU Viterbi backend).-h, --help Show this help message.EOF104 unmodified linesATTN_IMPLEMENTATION="$2"shift 2;;--raw-probs-format|--raw_probs_format)require_value "$1" "$#"RAW_PROBS_FORMAT="$2"shift 2;;--skip-inference)SKIP_INFERENCE=1shift74 unmodified lines--batch_size "$BATCH_SIZE"--dispatch_chunk_size "$DISPATCH_CHUNK_SIZE"--attn_implementation "$ATTN_IMPLEMENTATION"--raw_probs_format "$RAW_PROBS_FORMAT")[[ -n "$MODEL" ]] && inference_args+=(--model_name "$MODEL")[[ -n "$REVISION" ]] && inference_args+=(--revision "$REVISION")3 unmodified lines}select_raw_probs() {local candidates=("$OUTPUT_DIR"/*.raw_probs.arrow "$OUTPUT_DIR"/*.raw_probs.parquet)(( ${#candidates[@]} > 0 )) || \die "no raw-probability file found in $OUTPUT_DIR"RAW_PROBS="${candidates[0]}"local candidate13 unmodified lines--viterbi_backend "$VITERBI_BACKEND"--codon_table "$CODON_TABLE"--max_boundary_intron_length "$MAX_BOUNDARY_INTRON_LENGTH"--min_record_length "$MIN_RECORD_LENGTH"--min_cds_length "$MIN_CDS_LENGTH")[[ -n "$CHUNK_MBP" ]] && postprocess_args+=(--chunk_mbp "$CHUNK_MBP")[[ -n "$TRANSITION_NETWORK" ]] && postprocess_args+=(--transition_network "$TRANSITION_NETWORK")[[ -n "$CONFIDENCE_NETWORK" ]] && postprocess_args+=(--confidence_network "$CONFIDENCE_NETWORK")[[ -n "$TCN_DEVICE" ]] && postprocess_args+=(--tcn_device "$TCN_DEVICE")
11 unmodified lines1213141516171819202122232425262728293031323316 unmodified lines5051525354555626 unmodified lines838485868788899091929394959697989910010110210310410510610710810915 unmodified lines12512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416515 unmodified lines18118218318418518618718818919019119232 unmodified lines22522622722822923023123211 unmodified linesare pooled by two attention heads and an MLP maps the pooled vectors to theconfidence logit; the sigmoid of the logit is the confidence.``inference`` does this for a strand of any length without holding the wholestrand on the device: a feature vector depends only on the strand within thenetwork's context radius of its base, so only the windows of that radiusaround the scored exons are read, concatenated and processed in chunks theway the transition network reads a record (tcn.chunked_inference). Onlycomplete genes are scored; a gene truncated by a record edge has no completestructure to judge, but its decoded bases still give roles to the strand forits neighbours."""import numpy as npimport torchfrom torch import nnfrom constants import NETWORK_CHUNK_BPfrom tcn import TCN, chunked_inference, coding_log_odds, load_weightsCONFIDENCE_NETWORK_TYPE = "confidence_network"16 unmodified linesif probabilities.ndim != 2 or roles.shape != probabilities.shape:raise ValueError("probabilities and roles must both have shape [batch, bases]")log_odds = coding_log_odds(probabilities)role_tracks = nn.functional.one_hot(roles, num_classes=len(ROLE_NAMES)).to(log_odds.dtype)sign = role_tracks[..., ROLE_EXON] * 2 - 1return torch.cat(((log_odds * sign)[:, None, :], role_tracks.transpose(1, 2)), dim=1)26 unmodified lines"""Return the ``[bases, channels]`` features of a strand, or a chunk of one, given as ``[bases]`` tensors."""return self.encoder(input_tracks(probabilities[None, :], roles[None, :]))[0]def gene_logits(self, exon_features):"""Return one confidence logit per gene from the features at its exon bases.``exon_features`` holds one ``[exon_bases, channels]`` tensor per gene.Each head gives every exon base an attention logit; the softmax overthe bases of one gene weights their feature vectors into one pooledvector per head. Genes are pooled side by side with segment sums, sono gene is padded to the length of another."""exon_features = tuple(exon_features)if not exon_features:raise ValueError("at least one gene is required")for features in exon_features:if features.ndim != 2 or not len(features):raise ValueError("a gene must contain at least one exon base")lengths = torch.as_tensor([len(features) for features in exon_features],dtype=torch.long, device=exon_features[0].device,)features = torch.cat(exon_features)# The gene every base belongs to, repeated for every head.gene_of_base = torch.repeat_interleave(torch.arange(len(lengths), device=lengths.device), lengths)gene_of_base_per_head = gene_of_base[:, None].expand(-1, self.attention_heads)15 unmodified linesreturn self.readout(pooled.flatten(1)).squeeze(1)@torch.inference_mode()def inference(self, probabilities, exons_by_gene, scored, chunk_bp=NETWORK_CHUNK_BP):"""Return the confidence of each scored gene of one strand.``probabilities`` is the strand's coding-probability track in decoderorientation; ``exons_by_gene`` holds the inclusive exon intervals, intranscript order, of every gene decoded on the strand; ``scored`` liststhe positions in ``exons_by_gene`` of the complete genes to score.Every decoded gene gives roles to the strand. The confidences come backas a float64 array in the order of ``scored``."""scored = list(scored)if not scored:return np.zeros(0, dtype=np.float64)device = next(self.parameters()).deviceprobabilities = np.asarray(probabilities)roles = strand_roles(exons_by_gene, len(probabilities))scored_exons = [exons_by_gene[index] for index in scored]# 1. Keep only the bases a scored exon can see: the window of one# context radius around every scored exon, merged, in strand order.windows = exon_windows(scored_exons, len(probabilities), self.context_radius)window_probabilities = np.concatenate([probabilities[start:stop] for start, stop in windows])window_roles = np.concatenate([roles[start:stop] for start, stop in windows])# 2. Where each gene's exon bases lie in the concatenated windows, in transcript order.positions_by_gene = [positions_in_windows(exon_positions(oriented_exons), windows) for oriented_exons in scored_exons]# 3. Encode the concatenated windows in chunks; keep the features at the exon bases.features = chunked_inference(self.encode, self.context_radius, (window_probabilities, window_roles), device, chunk_bp,)exon_features = [torch.as_tensor(features[positions]).to(device) for positions in positions_by_gene]# 4. Pool each gene's exon features into its confidence.logits = self.gene_logits(exon_features).to(torch.float64)return torch.sigmoid(logits).cpu().numpy()def load_confidence_network(path, device):15 unmodified linesdef strand_roles(exons_by_gene, record_length):"""Return the role of every base of a strand from the oriented exons of its decoded genes.A base inside a gene's span is intron unless some gene has an exon there;every other base is intergenic. Every decoded gene counts, complete or not."""roles = np.full(record_length, ROLE_INTERGENIC, dtype=np.int64)for oriented_exons in exons_by_gene:roles[oriented_exons[0][0]:oriented_exons[-1][1] + 1] = ROLE_INTRONfor oriented_exons in exons_by_gene:32 unmodified linesdef positions_in_windows(positions, windows):"""Map sorted strand positions inside ``windows`` to positions in the concatenated windows."""window_starts = np.asarray([start for start, _ in windows], dtype=np.int64)concatenated_starts = np.concatenate(([0], np.cumsum([stop - start for start, stop in windows])[:-1]))window = np.searchsorted(window_starts, positions, side="right") - 1return positions - window_starts[window] + concatenated_starts[window]11 unmodified lines1213141516171819202122232425262728293031323334353616 unmodified lines5354555657585926 unmodified lines868788899091929394959697989910010110210310410510610710810911011115 unmodified lines12712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420515 unmodified lines22122222322422522622722822923023123232 unmodified lines26526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429511 unmodified linesare pooled by two attention heads and an MLP maps the pooled vectors to theconfidence logit; the sigmoid of the logit is the confidence.``inference`` does this for a strand of any length within a bounded amount ofdevice memory. A feature vector depends only on the strand within thenetwork's context radius of its base, so only the windows of that radiusaround the scored exons are read, concatenated and processed in chunks theway the transition network reads a record (tcn.chunked_inference), and onlythe features at exon bases are kept. The genes are pooled in groups whoseexon bases fit the device memory budget; a strand whose genes fit in onegroup is scored in one pass. Only complete genes are scored; a gene truncatedby a record edge has no complete structure to judge, but its decoded basesstill give roles to the strand for its neighbours."""import numpy as npimport torchfrom torch import nnfrom constants import CONFIDENCE_NETWORK_BYTES_PER_EXON_BASE, GPU_MEMORY_FRACTION, NETWORK_CHUNK_BPfrom tcn import TCN, chunked_inference, coding_log_odds, load_weightsfrom utils import validate_memory_budget_bytesCONFIDENCE_NETWORK_TYPE = "confidence_network"16 unmodified linesif probabilities.ndim != 2 or roles.shape != probabilities.shape:raise ValueError("probabilities and roles must both have shape [batch, bases]")log_odds = coding_log_odds(probabilities)role_tracks = nn.functional.one_hot(roles.long(), num_classes=len(ROLE_NAMES)).to(log_odds.dtype)sign = role_tracks[..., ROLE_EXON] * 2 - 1return torch.cat(((log_odds * sign)[:, None, :], role_tracks.transpose(1, 2)), dim=1)26 unmodified lines"""Return the ``[bases, channels]`` features of a strand, or a chunk of one, given as ``[bases]`` tensors."""return self.encoder(input_tracks(probabilities[None, :], roles[None, :]))[0]def gene_logits(self, features, exon_base_counts):"""Return one confidence logit per gene from the features at its exon bases.``features`` is the ``[exon_bases, channels]`` tensor of the features atthe exon bases of the genes, gene after gene; ``exon_base_counts``gives the number of exon bases of each gene. Each head gives everyexon base an attention logit; the softmax over the bases of one geneweights their feature vectors into one pooled vector per head. Genesare pooled side by side with segment sums, so no gene is padded to thelength of another."""exon_base_counts = [int(count) for count in exon_base_counts]if not exon_base_counts:raise ValueError("at least one gene is required")if min(exon_base_counts) < 1:raise ValueError("a gene must contain at least one exon base")if features.ndim != 2 or len(features) != sum(exon_base_counts):raise ValueError("features must hold one row per exon base of the genes")lengths = torch.as_tensor(exon_base_counts, dtype=torch.long, device=features.device)# The gene every base belongs to, repeated for every head.gene_of_base = torch.repeat_interleave(torch.arange(len(lengths), device=lengths.device), lengths)gene_of_base_per_head = gene_of_base[:, None].expand(-1, self.attention_heads)15 unmodified linesreturn self.readout(pooled.flatten(1)).squeeze(1)@torch.inference_mode()def inference(self, probabilities, exons_by_gene, scored, chunk_bp=NETWORK_CHUNK_BP, memory_budget_bytes=None):"""Return the confidence of each scored gene of one strand.``probabilities`` is the strand's coding-probability track in transcriptorientation; ``exons_by_gene`` holds the inclusive exon intervals, intranscript order, of every gene decoded on the strand; ``scored`` liststhe positions in ``exons_by_gene`` of the complete genes to score.Every decoded gene gives roles to the strand. The scored genes aretaken in the order of ``scored``, in groups whose exon bases fit``memory_budget_bytes`` of device memory atCONFIDENCE_NETWORK_BYTES_PER_EXON_BASE each; a gene too large for thebudget forms a group alone. ``None`` takes GPU_MEMORY_FRACTION of thefree memory of a CUDA device, and scores all genes in one group on theCPU. The confidences come back as a float64 array in the order of``scored``."""scored = list(scored)memory_budget_bytes = validate_memory_budget_bytes(memory_budget_bytes)if not scored:return np.zeros(0, dtype=np.float64)device = next(self.parameters()).deviceif memory_budget_bytes is None and device.type == "cuda":# Memory that torch has cached but does not use is free for the network's tensors.free_bytes = (torch.cuda.mem_get_info(device)[0]+ torch.cuda.memory_reserved(device) - torch.cuda.memory_allocated(device))memory_budget_bytes = int(free_bytes * GPU_MEMORY_FRACTION)max_group_exon_bases = (None if memory_budget_bytes is None else memory_budget_bytes // CONFIDENCE_NETWORK_BYTES_PER_EXON_BASE)probabilities = np.asarray(probabilities)roles = strand_roles(exons_by_gene, len(probabilities))scored_exons = [exons_by_gene[index] for index in scored]exon_base_counts = [sum(exon_stop_inclusive - exon_start + 1 for exon_start, exon_stop_inclusive in oriented_exons)for oriented_exons in scored_exons]logits = torch.cat([self.group_logits(probabilities, roles, scored_exons[start:stop], exon_base_counts[start:stop], chunk_bp)for start, stop in gene_groups(exon_base_counts, max_group_exon_bases)])return torch.sigmoid(logits.to(torch.float64)).cpu().numpy()def group_logits(self, probabilities, roles, group_exons, exon_base_counts, chunk_bp):"""Return the confidence logits of a group of genes of one strand.``roles`` holds the decoded role of every base of the strand(``strand_roles``), ``group_exons`` the oriented exons of the genes ofthe group, and ``exon_base_counts`` their numbers of exon bases."""device = next(self.parameters()).device# 1. Keep only the bases an exon of the group can see: the window of one# context radius around every exon, merged, in strand order.windows = exon_windows(group_exons, len(probabilities), self.context_radius)window_probabilities = np.concatenate([probabilities[start:stop] for start, stop in windows])window_roles = np.concatenate([roles[start:stop] for start, stop in windows])# 2. Where the exon bases lie in the concatenated windows, gene after# gene in transcript order, and the same positions in increasing order.positions = positions_in_windows(np.concatenate([exon_positions(oriented_exons) for oriented_exons in group_exons]), windows,)order = np.argsort(positions, kind="stable")sorted_positions = positions[order]# 3. Encode the concatenated windows in chunks; keep the features at the exon bases only.features = np.empty((len(positions), self.encoder.channels), dtype=np.float32)for start, stop, chunk_features in chunked_inference(self.encode, self.context_radius, (window_probabilities, window_roles), device, chunk_bp,):first, last = np.searchsorted(sorted_positions, (start, stop))features[order[first:last]] = chunk_features[sorted_positions[first:last] - start]# 4. Pool each gene's exon features into its confidence logit.return self.gene_logits(torch.as_tensor(features).to(device), exon_base_counts)def load_confidence_network(path, device):15 unmodified linesdef strand_roles(exons_by_gene, record_length):"""Return the int8 role of every base of a strand from the oriented exons of its decoded genes.A base inside a gene's span is intron unless some gene has an exon there;every other base is intergenic. Every decoded gene counts, complete or not."""roles = np.full(record_length, ROLE_INTERGENIC, dtype=np.int8)for oriented_exons in exons_by_gene:roles[oriented_exons[0][0]:oriented_exons[-1][1] + 1] = ROLE_INTRONfor oriented_exons in exons_by_gene:32 unmodified linesdef positions_in_windows(positions, windows):"""Map strand positions inside ``windows`` to positions in the concatenated windows."""window_starts = np.asarray([start for start, _ in windows], dtype=np.int64)concatenated_starts = np.concatenate(([0], np.cumsum([stop - start for start, stop in windows])[:-1]))window = np.searchsorted(window_starts, positions, side="right") - 1return positions - window_starts[window] + concatenated_starts[window]def gene_groups(exon_base_counts, max_group_exon_bases):"""Split genes, in order, into consecutive groups of at most ``max_group_exon_bases`` exon bases.``exon_base_counts`` gives the number of exon bases of each gene. A genewith more exon bases than the limit forms a group alone; ``None`` puts allgenes in one group. Returns the groups as ``(start, stop)`` ranges ofpositions in ``exon_base_counts``."""groups = []start = group_exon_bases = 0for position, count in enumerate(exon_base_counts):if (max_group_exon_bases is not None and position > startand group_exon_bases + count > max_group_exon_bases):groups.append((start, position))start, group_exon_bases = position, 0group_exon_bases += countif start < len(exon_base_counts):groups.append((start, len(exon_base_counts)))return groups
123456783 unmodified lines9192939495969798991001 unmodified line102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137"""Shared constants for the Carbon-A annotation pipeline.Keep cross-module data contracts and tunable pipeline parameters here. Privateimplementation details, such as decoder state ids and evaluation regexes, staywith the modules that own them."""83 unmodified linesWEIGHTS_DIRECTORY = PROJECT_DIRECTORY / "weights"TRANSITION_NETWORK_PATH = WEIGHTS_DIRECTORY / "transition_network.safetensors"CONFIDENCE_NETWORK_PATH = WEIGHTS_DIRECTORY / "confidence_network.safetensors"# Per-base transition probability tracks handed to the Viterbi backends, in# this column order. They are stored as log-odds against staying in the# backends' fixed-point units; the native backends and the Numba reference# share the layout.TRANSITION_NAMES = ("enter_gene", "leave_gene", "enter_intron", "leave_intron")TRANSITION_COUNT = len(TRANSITION_NAMES)ENTER_GENE, LEAVE_GENE, ENTER_INTRON, LEAVE_INTRON = range(TRANSITION_COUNT)1 unmodified line# Both networks read long tracks in chunks of this many bases, each evaluated# with the network's full context on both sides (tcn.chunked_inference), so a# chromosome never has to fit in GPU memory at once. (The post-processing# driver separately groups whole records into host-side chunks, chunk_mbp.)NETWORK_CHUNK_BP = 262_144# Native Viterbi implementations accumulate int32 fixed-point scores.# Transition probabilities are exchanged as log-odds in the same units: nats# multiplied by this scale and rounded.FIXED_POINT_SCORE_SCALE = 16384.0# Boundary introns model genes truncated at a record edge. A finite limit# prevents an incomplete path from hiding a long region as one intron.MAX_BOUNDARY_INTRON_LENGTH_BP = 20_000# Records shorter than this are skipped. Host-side chunks can exceed their# target size because a sequence record is never split.MIN_RECORD_LENGTH_BP = 100_000CHUNK_SIZE_MBP = 25PARQUET_BATCH_ROWS = 1CODON_TABLE_PATH = PROJECT_DIRECTORY / "codon_tables" / "standard.json"# GPU Viterbi backend memory and batching parameters.GPU_SEGMENT_LENGTH = 2000GPU_MEMORY_FRACTION = 0.70GPU_MIN_BATCH_BASES = 20_000_000# The CUDA preprocessing kernel indexes packed bases with int32. Record offsets# remain int64, so this limits a sub-batch rather than the input file.GPU_MAX_BATCH_BASES = (1 << 31) - 1# Covers packed inputs, per-base scores and paths, the four int32 transition# score tracks, segment matrices, and allocation headroom while CUDA windows# the backpointer array internally.GPU_ESTIMATED_BYTES_PER_BASE = 34# Gene-level results count the predicted genes whose confidence reaches this123456783 unmodified lines9192939495969798991001 unmodified line102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148"""Shared constants for the Carbon-A annotation pipeline.Keep cross-module data contracts and tunable pipeline parameters here. Privateimplementation details, such as Viterbi state ids and evaluation regexes, staywith the modules that own them."""83 unmodified linesWEIGHTS_DIRECTORY = PROJECT_DIRECTORY / "weights"TRANSITION_NETWORK_PATH = WEIGHTS_DIRECTORY / "transition_network.safetensors"CONFIDENCE_NETWORK_PATH = WEIGHTS_DIRECTORY / "confidence_network.safetensors"# Per-base transition tracks handed to the Viterbi backends, in this column# order. They are stored as log-odds against staying in the backends'# fixed-point units; the native backends and the Numba reference share the# layout.TRANSITION_NAMES = ("enter_gene", "leave_gene", "enter_intron", "leave_intron")TRANSITION_COUNT = len(TRANSITION_NAMES)ENTER_GENE, LEAVE_GENE, ENTER_INTRON, LEAVE_INTRON = range(TRANSITION_COUNT)1 unmodified line# Both networks read long tracks in chunks of this many bases, each evaluated# with the network's full context on both sides (tcn.chunked_inference), so a# chromosome never has to fit in GPU memory at once. (The post-processing# driver separately groups whole strands into host-side chunks, chunk_mbp.)NETWORK_CHUNK_BP = 262_144# Device memory the shipped confidence network needs per exon base of the# genes it pools at once. The peak is in the attention MLP: the base's 32# float32 features, the 32 float32 hidden values before and the 32 after GELU,# and the base's int64 gene index. The genes of a strand are pooled in groups# whose exon bases fit GPU_MEMORY_FRACTION of the free device memory at this# size.CONFIDENCE_NETWORK_BYTES_PER_EXON_BASE = 392# Native Viterbi implementations accumulate int32 fixed-point scores.# Transition log-odds are exchanged in the same units: nats multiplied by# this scale and rounded.FIXED_POINT_SCORE_SCALE = 16384.0# Boundary introns model genes truncated at a record edge. A finite limit# prevents an incomplete path from hiding a long region as one intron.MAX_BOUNDARY_INTRON_LENGTH_BP = 20_000# Records shorter than this are skipped.MIN_RECORD_LENGTH_BP = 100_000# Host-side chunk size in megabases by Viterbi backend. Post-processing takes# about 50 MB of host memory per megabase of its largest chunk. The CPU# backend decodes the strands of a chunk in parallel, one thread each, so it# is given large chunks; the other backends gain nothing from them. A strand# is never split: one longer than the chunk size is a chunk of its own.CHUNK_SIZE_MBP = {"gpu": 25, "cpu": 1000, "numba": 25}PARQUET_BATCH_ROWS = 1PARQUET_READ_BUFFER_BYTES = 8 << 20CODON_TABLE_PATH = PROJECT_DIRECTORY / "codon_tables" / "standard.json"# GPU Viterbi backend parameters.# Bases per segment; a batch whose transition log-odds are too large for this# length to keep segment scores within int32 gets the longest length that does.GPU_SEGMENT_LENGTH = 300# Segments per group in stage 3 of the GPU backend; 0 takes the square root of# the longest record's segment count, rounded up.GPU_SEGMENT_GROUP_LENGTH = 0# The device memory budget of a GPU Viterbi call and of the confidence# network's pooling, as a fraction of the free device memory.GPU_MEMORY_FRACTION = 0.90# Gene-level results count the predicted genes whose confidence reaches this
9 unmodified lines10111213141516171819202122232425269 unmodified lines3637383940412 unmodified lines4445464748495073 unmodified lines124125126127128129130117 unmodified lines248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326672 unmodified lines99910001001100210031004100510061007100810091010101156 unmodified lines10681069107010711072107314 unmodified lines10881089109010911092109310941095109610971098109911001101110211039 unmodified linesfrom typing import Any, Dict, IO, List, Optional, Sequence, Tupleimport numpy as npimport pandas as pdtry:import pyarrow as paimport pyarrow.parquet as pqHAS_PYARROW = Trueexcept ImportError:pa = Nonepq = NoneHAS_PYARROW = Falseimport torchimport torch.multiprocessing as mpfrom tqdm import tqdm9 unmodified linesHEAD_NAMES,MODEL_NAME,OVERLAP_LENGTH,)FASTA_SUFFIXES = (".fasta", ".fa", ".fna", ".ffn", ".faa", ".fas")2 unmodified linesdef parse_arguments() -> argparse.Namespace:parser = argparse.ArgumentParser(description="Pure model inference for CDS annotation. Outputs raw softmax probabilities to parquet.",)parser.add_argument(73 unmodified linestype=str,choices=["float16", "float32"],default="float16",help="Data type for saved CDS probabilities in parquet",)parser.add_argument("--save_non_coding_prob",117 unmodified linesreturn text.split()[0] if text else "record"def pyarrow_list_array_from_ndarrays(arrays: Sequence[np.ndarray], value_type: "pa.DataType") -> "pa.Array":assert HAS_PYARROW and pa is not Nonereturn pa.array([pa.array(np.asarray(arr), type=value_type) for arr in arrays],type=pa.list_(value_type),)def write_prob_parquet(records: Sequence[Tuple[str, str]],probs_per_head: Sequence[Sequence[np.ndarray]],head_names: Sequence[str],output_path: str,prob_dtype: str,save_non_coding_prob: bool,) -> None:if not probs_per_head:raise ValueError("No probabilities to write.")os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)np_dtype = np.float16 if prob_dtype == "float16" else np.float32record_names = [get_record_name(h) for h, _ in records]sequences = [seq for _, seq in records]if HAS_PYARROW and pa is not None and pq is not None:value_type = pa.float16() if prob_dtype == "float16" else pa.float32()cols: Dict[str, Any] = {}cols["record_name"] = pa.array(record_names, type=pa.string())cols["sequence"] = pa.array(sequences, type=pa.string())for h, head_name in enumerate(head_names):cds_arrays = [np.asarray(arr, dtype=np_dtype) for arr in probs_per_head[h]]cols[f"pred_prob_{head_name}_cds"] = pyarrow_list_array_from_ndarrays(cds_arrays, value_type)if save_non_coding_prob:nc_arrays = [np.asarray(1.0 - arr, dtype=np_dtype) for arr in cds_arrays]cols[f"pred_prob_{head_name}_non_coding"] = (pyarrow_list_array_from_ndarrays(nc_arrays, value_type))table = pa.table(cols)pq.write_table(table,output_path,compression="zstd",write_page_index=False,)else:data: List[Dict[str, Any]] = []for i in range(len(records)):row: Dict[str, Any] = {"record_name": record_names[i],"sequence": sequences[i],}for h, head_name in enumerate(head_names):row[f"pred_prob_{head_name}_cds"] = np.asarray(probs_per_head[h][i], dtype=np_dtype).tolist()if save_non_coding_prob:row[f"pred_prob_{head_name}_non_coding"] = np.asarray(1.0 - probs_per_head[h][i], dtype=np_dtype).tolist()data.append(row)df = pd.DataFrame(data)df.to_parquet(output_path, index=False)print(f"✅ Raw probability parquet written to {output_path}")def select_inference_devices(672 unmodified linesreturn recordsdef make_output_parquet_path(output_dir: str, input_path: str, run_timestamp: str) -> str:input_filename = strip_gzip_suffix(os.path.basename(input_path))base_input_name = os.path.splitext(input_filename)[0]return os.path.join(output_dir, f"{base_input_name}_{run_timestamp}.raw_probs.parquet")56 unmodified linesif not records:print("⚠️ No sequences found, skipping.")continueprobs_per_head = infer_records(records=records,14 unmodified linesif len(probs_per_head) == 2else [f"head_{i}" for i in range(len(probs_per_head))])output_parquet_path = make_output_parquet_path(args.output_path, input_path, run_timestamp)write_prob_parquet(records=records,probs_per_head=probs_per_head,head_names=head_names,output_path=output_parquet_path,prob_dtype=args.prob_dtype,save_non_coding_prob=args.save_non_coding_prob,)except KeyboardInterrupt:interrupted = True9 unmodified lines10111213141516179 unmodified lines27282930313233342 unmodified lines3738394041424373 unmodified lines117118119120121122123124125126127128129130131132133134117 unmodified lines252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367672 unmodified lines104010411042104310441045104610471048104910501051105256 unmodified lines1109111011111112111311141115111614 unmodified lines113111321133113411351136113711381139114011411142114311441145114611479 unmodified linesfrom typing import Any, Dict, IO, List, Optional, Sequence, Tupleimport numpy as npimport pyarrow as paimport pyarrow.parquet as pqimport torchimport torch.multiprocessing as mpfrom tqdm import tqdm9 unmodified linesHEAD_NAMES,MODEL_NAME,OVERLAP_LENGTH,RECORD_ID_COLUMN,SEQUENCE_COLUMN,)FASTA_SUFFIXES = (".fasta", ".fa", ".fna", ".ffn", ".faa", ".fas")2 unmodified linesdef parse_arguments() -> argparse.Namespace:parser = argparse.ArgumentParser(description="Pure model inference for CDS annotation. Outputs raw softmax probabilities to an Arrow IPC or Parquet file.",)parser.add_argument(73 unmodified linestype=str,choices=["float16", "float32"],default="float16",help="Data type for saved CDS probabilities",)parser.add_argument("--raw_probs_format",type=str,choices=["arrow", "parquet"],default="arrow",help=("File format of the raw probabilities: arrow (Arrow IPC, *.raw_probs.arrow) or parquet ""(*.raw_probs.parquet; records of at most 1,000,000,000 bases, 500,000,000 with ""--prob_dtype float32)"),)parser.add_argument("--save_non_coding_prob",117 unmodified linesreturn text.split()[0] if text else "record"# Consecutive records share a record batch of an Arrow IPC raw-probability# file, or a row group of a Parquet one, up to this many bases; a longer# record forms one of its own.RAW_PROBS_BATCH_BASES = 1 << 20# Parquet keeps the probabilities of a record in one data page (pyarrow 23 and# later), and a data page holds less than 2 GiB: a float16 probability takes# at most about 2 bytes there and a float32 one about 4, so these limits keep# the page below 2 GiB. Longer records are refused before inference; the Arrow# IPC format has no such limit.PARQUET_MAX_RECORD_BASES = {"float16": 1_000_000_000, "float32": 500_000_000}def check_parquet_record_lengths(records: Sequence[Tuple[str, str]], prob_dtype: str) -> None:"""Raise ValueError for the first record too long for a Parquet raw-probability file."""max_bases = PARQUET_MAX_RECORD_BASES[prob_dtype]for header, sequence in records:if len(sequence) > max_bases:raise ValueError(f"record {get_record_name(header)!r} has {len(sequence):,} bases; a Parquet "f"raw-probability file holds records of at most {max_bases:,} bases with "f"--prob_dtype {prob_dtype}. Use --raw_probs_format arrow.")def write_raw_probs(records: Sequence[Tuple[str, str]],probs_per_head: Sequence[Sequence[np.ndarray]],head_names: Sequence[str],output_path: str,prob_dtype: str,save_non_coding_prob: bool,raw_probs_format: str,) -> None:"""Write every record and its probabilities to a zstd-compressed raw-probability file.The file holds one row per record: the record name, the sequence and, forevery head, ``pred_prob_<head>_cds`` (with ``save_non_coding_prob`` also``pred_prob_<head>_non_coding``) as a list of ``prob_dtype`` values, oneper base. ``raw_probs_format`` selects the file: ``arrow``, an Arrow IPCfile with large strings and lists, whose 64-bit offsets let a recordexceed 2**31 bases; or ``parquet``, a Parquet file with strings and lists,for records of at most PARQUET_MAX_RECORD_BASES bases."""if not probs_per_head:raise ValueError("No probabilities to write.")os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)np_dtype = np.float16 if prob_dtype == "float16" else np.float32value_type = pa.float16() if prob_dtype == "float16" else pa.float32()large_types = raw_probs_format == "arrow"string_type = pa.large_string() if large_types else pa.string()list_type = pa.large_list(value_type) if large_types else pa.list_(value_type)offset_type = pa.int64() if large_types else pa.int32()list_array_type = pa.LargeListArray if large_types else pa.ListArray# (column name, head index, whether the column holds P(non-coding))probability_columns: List[Tuple[str, int, bool]] = []for h, head_name in enumerate(head_names):probability_columns.append((f"pred_prob_{head_name}_cds", h, False))if save_non_coding_prob:probability_columns.append((f"pred_prob_{head_name}_non_coding", h, True))schema = pa.schema([(RECORD_ID_COLUMN, string_type), (SEQUENCE_COLUMN, string_type)]+ [(name, list_type) for name, _, _ in probability_columns])def probability_array(h: int, non_coding: bool, start: int, stop: int) -> pa.Array:"""Return the probabilities of records start to stop - 1 as one list array."""arrays = [np.asarray(arr, dtype=np_dtype) for arr in probs_per_head[h][start:stop]]if non_coding:arrays = [np.asarray(1.0 - arr, dtype=np_dtype) for arr in arrays]offsets = np.zeros(len(arrays) + 1, dtype=np.int64)np.cumsum([len(arr) for arr in arrays], out=offsets[1:])values = arrays[0] if len(arrays) == 1 else np.concatenate(arrays)return list_array_type.from_arrays(pa.array(offsets, type=offset_type), pa.array(values, type=value_type))def record_batches():"""Yield record batches of whole records, at most RAW_PROBS_BATCH_BASES bases unless one record is longer."""start = 0while start < len(records):stop, batch_bases = start + 1, len(records[start][1])while stop < len(records) and batch_bases + len(records[stop][1]) <= RAW_PROBS_BATCH_BASES:batch_bases += len(records[stop][1])stop += 1batch_records = records[start:stop]yield pa.record_batch([pa.array([get_record_name(header) for header, _ in batch_records], type=string_type),pa.array([sequence for _, sequence in batch_records], type=string_type),]+ [probability_array(h, non_coding, start, stop) for _, h, non_coding in probability_columns],schema=schema,)start = stopif raw_probs_format == "arrow":# The IPC format needs 64-bit lengths for arrays of 2**31 or more values.options = pa.ipc.IpcWriteOptions(compression="zstd", allow_64bit=True)with pa.ipc.new_file(output_path, schema, options=options) as writer:for batch in record_batches():writer.write_batch(batch)else:# Every record batch becomes one row group.with pq.ParquetWriter(output_path, schema, compression="zstd") as writer:for batch in record_batches():writer.write_batch(batch)print(f"✅ Raw probabilities written to {output_path}")def select_inference_devices(672 unmodified linesreturn recordsdef make_raw_probs_path(output_dir: str, input_path: str, run_timestamp: str, raw_probs_format: str) -> str:input_filename = strip_gzip_suffix(os.path.basename(input_path))base_input_name = os.path.splitext(input_filename)[0]return os.path.join(output_dir, f"{base_input_name}_{run_timestamp}.raw_probs.{raw_probs_format}")56 unmodified linesif not records:print("⚠️ No sequences found, skipping.")continueif args.raw_probs_format == "parquet":check_parquet_record_lengths(records, args.prob_dtype)probs_per_head = infer_records(records=records,14 unmodified linesif len(probs_per_head) == 2else [f"head_{i}" for i in range(len(probs_per_head))])raw_probs_path = make_raw_probs_path(args.output_path, input_path, run_timestamp, args.raw_probs_format)write_raw_probs(records=records,probs_per_head=probs_per_head,head_names=head_names,output_path=raw_probs_path,prob_dtype=args.prob_dtype,save_non_coding_prob=args.save_non_coding_prob,raw_probs_format=args.raw_probs_format,)except KeyboardInterrupt:interrupted = True
67 unmodified lines6869707172733 unmodified lines777879808182835 unmodified lines89909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271284 unmodified lines1331341351361371381391403 unmodified lines1441451461471481491501511521531541551561571581591601611621631641651661671681691707 unmodified lines1781791801811821831841851861871881891901911921931941951961 unmodified line19819920020120220330 unmodified lines2342352362372382392402418 unmodified lines25025125225325425525638 unmodified lines2952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273284 unmodified lines33333433533633733833934034134234334434534634734834935035135235335435535635735835948 unmodified lines4084094104114124134146 unmodified lines42142242342442542642726 unmodified lines45445545645745845946046167 unmodified linesMIN_RECORD_LENGTH_BP,NEGATIVE_STRAND_PROBABILITY_COLUMN,PARQUET_BATCH_ROWS,POSITIVE_STRAND_PROBABILITY_COLUMN,RECORD_ID_COLUMN,SEQUENCE_COLUMN,3 unmodified lines)from utils import (load_codon_table, stop_codons_from_table,probability_vector_from_parquet,validate_max_boundary_intron_length,encode_both_strands,assemble_gene_model,5 unmodified linesfrom viterbi import choose_viterbi_backend, decode_paths, iter_gene_exons_with_statesdef default_output_prefix(input_path):"""Return the default output prefix for one raw-probability parquet file."""if input_path.endswith(".raw_probs.parquet"):return input_path[:-len(".raw_probs.parquet")] + ".predicted"return os.path.splitext(input_path)[0] + ".predicted"def iter_probability_chunks(parquet_file, record_id_col, sequence_col,positive_col, negative_col, max_chunk_bp,min_record_length=0, filter_stats=None,):"""Read and encode strand tracks in approximately ``max_chunk_bp`` chunks.Each record yields two tracks in transcript orientation, ``(codingprobabilities, encoded bases)`` for the forward strand and for the reversecomplement, together with a ``(record_id, sequence, strand, length)``context. A sequence record is never split, and each yielded base countincludes both tracks."""required_columns = [record_id_col, sequence_col, positive_col, negative_col]tracks = []track_contexts = []chunk_bp = 0for batch in parquet_file.iter_batches(batch_size=PARQUET_BATCH_ROWS, columns=required_columns):columns_by_name = {column_name: batch.column(column_index)for column_index, column_name in enumerate(batch.schema.names)}record_ids = columns_by_name[record_id_col]sequences = columns_by_name[sequence_col]positive_probabilities = columns_by_name[positive_col]negative_probabilities = columns_by_name[negative_col]for row_index in range(batch.num_rows):sequence = sequences[row_index].as_py().upper()4 unmodified linesfilter_stats["record_count"] += 1filter_stats["bp"] += record_lengthcontinuepositive = probability_vector_from_parquet(positive_probabilities[row_index])negative = probability_vector_from_parquet(negative_probabilities[row_index])if len(positive) < record_length or len(negative) < record_length:raise ValueError(f"record {record_id!r} has {record_length} bases but "3 unmodified linespositive = positive[:record_length]negative = negative[:record_length]forward_bases, reverse_bases = encode_both_strands(sequence)tracks.append((positive, forward_bases))track_contexts.append((record_id, sequence, "+", record_length))tracks.append((np.ascontiguousarray(negative[::-1]), reverse_bases))track_contexts.append((record_id, sequence, "-", record_length))chunk_bp += 2 * record_lengthif chunk_bp >= max_chunk_bp:yield tracks, track_contexts, chunk_bptracks = []track_contexts = []chunk_bp = 0if tracks:yield tracks, track_contexts, chunk_bpdef iter_prefetched_chunks(chunks):"""Prepare one chunk ahead while the caller decodes the current chunk.The one-item lookahead overlaps Parquet decoding with GPU/CPU work whilekeeping memory use bounded to one current and one prepared chunk."""chunk_iterator = iter(chunks)with ThreadPoolExecutor(max_workers=1) as executor:7 unmodified linesdef decode_chunk_genes(tracks, track_contexts, transition_probabilities, viterbi_backend, stop_codons,max_boundary_intron_length, min_cds_length, confidence_network,):"""Decode one chunk under one stop-codon set and score its complete genes.Returns ``(chunk_genes, short_gene_count, viterbi_seconds,confidence_seconds)``; each entry of ``chunk_genes`` is ``(gene,probabilities, oriented_exons)``."""stage_started = time.perf_counter()state_paths = decode_paths(tracks,transition_probabilities,viterbi_backend,stop_taa="TAA" in stop_codons,stop_tag="TAG" in stop_codons,1 unmodified linemax_boundary_intron_length=max_boundary_intron_length,)viterbi_seconds = time.perf_counter() - stage_startedif len(state_paths) != len(track_contexts):raise RuntimeError(f"{viterbi_backend} Viterbi backend returned {len(state_paths)} paths "30 unmodified lineschunk_genes.append((gene, probabilities, oriented_exons))strand_gene_indices.append((probabilities, gene_indices))# Confidence of every complete gene of the chunk, strand by strand. Every# written gene gives roles to its strand; only the complete ones are scored.stage_started = time.perf_counter()for probabilities, gene_indices in strand_gene_indices:scored = [8 unmodified linesfor position, confidence in zip(scored, confidences):chunk_genes[gene_indices[position]][0]["confidence"] = float(confidence)confidence_seconds = time.perf_counter() - stage_startedreturn chunk_genes, short_gene_count, viterbi_seconds, confidence_secondsdef record_codon_table_warning(output_prefix, warning, stop_codons):38 unmodified linesdef post_process_probability_file(input_path, output_prefix, viterbi_backend, codon_to_amino_acid,transition_network, confidence_network,max_boundary_intron_length, chunk_mbp,min_record_length=MIN_RECORD_LENGTH_BP,min_cds_length=MIN_CDS_LENGTH_BP,):"""Post-process one raw-probability parquet into GFF3, CDS FASTA, and protein FASTA.``viterbi_backend`` is the name returned by ``choose_viterbi_backend``.When the confidences of the complete genes contradict the codon table(utils.codon_table_mismatch), the warning is printed and recorded in thedirectory layout by ``record_codon_table_warning``."""import pyarrow.parquet as pqfile_started = time.perf_counter()stop_codons = tuple(stop_codons_from_table(codon_to_amino_acid))parquet_file = pq.ParquetFile(input_path)required_columns = {RECORD_ID_COLUMN,SEQUENCE_COLUMN,POSITIVE_STRAND_PROBABILITY_COLUMN,NEGATIVE_STRAND_PROBABILITY_COLUMN,}missing_columns = required_columns - set(parquet_file.schema_arrow.names)if missing_columns:raise ValueError("raw probability parquet is missing columns: "+ ", ".join(sorted(missing_columns)))genes = []short_gene_count = 04 unmodified linesfilter_stats = {"record_count": 0, "bp": 0}input_chunks = iter_probability_chunks(parquet_file, RECORD_ID_COLUMN, SEQUENCE_COLUMN,POSITIVE_STRAND_PROBABILITY_COLUMN, NEGATIVE_STRAND_PROBABILITY_COLUMN,chunk_mbp * 1_000_000,min_record_length=min_record_length,filter_stats=filter_stats,)for tracks, track_contexts, chunk_bp in iter_prefetched_chunks(input_chunks):# Stage 1: transition probabilities for every oriented track of the chunk.stage_started = time.perf_counter()transition_probabilities = [transition_network.inference(probabilities)for probabilities, _ in tracks]transition_seconds += time.perf_counter() - stage_started# Stages 2 and 3: the Viterbi algorithm, gene models, and their confidences.chunk_genes, chunk_short_gene_count, chunk_viterbi_seconds, chunk_confidence_seconds = decode_chunk_genes(tracks, track_contexts, transition_probabilities, viterbi_backend, stop_codons,max_boundary_intron_length, min_cds_length, confidence_network,)short_gene_count += chunk_short_gene_countviterbi_seconds += chunk_viterbi_secondsconfidence_seconds += chunk_confidence_seconds48 unmodified linesdef parse_args():"""Parse command-line arguments."""parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)parser.add_argument("--input", required=True, help="one *.raw_probs.parquet file")parser.add_argument("--output", default=None, help="output prefix; defaults to <input>.predicted")parser.add_argument("--viterbi_backend",6 unmodified linesdefault=str(CODON_TABLE_PATH),help=("JSON object mapping all 64 ATCG codons to amino acids; '*' marks ""decoder stop codons"),)parser.add_argument(26 unmodified linesparser.add_argument("--chunk_mbp",type=int,default=CHUNK_SIZE_MBP,help="target host-side chunk size in megabases; sequence records are never split",)parser.add_argument("--min_record_length",67 unmodified lines686970717273743 unmodified lines787980818283845 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701714 unmodified lines1761771781791801811821833 unmodified lines1871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292307 unmodified lines2382392402412422432442452462472482492502512522532542552562572582592602612622631 unmodified line26526626726826927027130 unmodified lines3023033043053063073083093108 unmodified lines31932032132232332432538 unmodified lines3643653663673683693703713723733743753763773783793803813823833843854 unmodified lines39039139239339439539639739839940040140240340440540640740840941048 unmodified lines4594604614624634644656 unmodified lines47247347447547647747826 unmodified lines50550650750850951051151251351451551651767 unmodified linesMIN_RECORD_LENGTH_BP,NEGATIVE_STRAND_PROBABILITY_COLUMN,PARQUET_BATCH_ROWS,PARQUET_READ_BUFFER_BYTES,POSITIVE_STRAND_PROBABILITY_COLUMN,RECORD_ID_COLUMN,SEQUENCE_COLUMN,3 unmodified lines)from utils import (load_codon_table, stop_codons_from_table,probability_vector_from_arrow,validate_max_boundary_intron_length,encode_both_strands,assemble_gene_model,5 unmodified linesfrom viterbi import choose_viterbi_backend, decode_paths, iter_gene_exons_with_statesRAW_PROBABILITY_COLUMNS = (RECORD_ID_COLUMN, SEQUENCE_COLUMN,POSITIVE_STRAND_PROBABILITY_COLUMN, NEGATIVE_STRAND_PROBABILITY_COLUMN,)def default_output_prefix(input_path):"""Return the default output prefix for one raw-probability file."""for suffix in (".raw_probs.arrow", ".raw_probs.parquet"):if input_path.endswith(suffix):return input_path[:-len(suffix)] + ".predicted"return os.path.splitext(input_path)[0] + ".predicted"def read_probability_batches(input_path):"""Return an iterator over the record batches of a raw-probability file.The batches hold RAW_PROBABILITY_COLUMNS. The suffix selects the format:``.arrow`` is an Arrow IPC file, as written by model inference, read onerecord batch at a time; ``.parquet`` is a Parquet file with the samecolumns, read PARQUET_BATCH_ROWS rows at a time."""import pyarrow as paimport pyarrow.parquet as pqdef check_columns(schema):missing_columns = [column for column in RAW_PROBABILITY_COLUMNS if column not in schema.names]if missing_columns:raise ValueError(f"raw-probability file {input_path} is missing columns: " + ", ".join(missing_columns))if input_path.endswith(".arrow"):reader = pa.ipc.open_file(pa.memory_map(input_path))check_columns(reader.schema)# Whole batches are read: selecting fields while reading copies the# compressed batch into memory first.return (reader.get_batch(index).select(list(RAW_PROBABILITY_COLUMNS))for index in range(reader.num_record_batches))if input_path.endswith(".parquet"):# Each column chunk is read through a buffer instead of whole, so a large# row group is not held in memory at once; pyarrow's pre-buffering is# off, since iter_prefetched_chunks already reads ahead.parquet_file = pq.ParquetFile(input_path, pre_buffer=False, buffer_size=PARQUET_READ_BUFFER_BYTES)check_columns(parquet_file.schema_arrow)return parquet_file.iter_batches(batch_size=PARQUET_BATCH_ROWS, columns=list(RAW_PROBABILITY_COLUMNS))raise ValueError(f"raw-probability file {input_path} must end in .arrow (Arrow IPC) or .parquet")def iter_probability_chunks(batches, max_chunk_bp, min_record_length=0, filter_stats=None):"""Read and encode strand tracks in chunks of at most ``max_chunk_bp`` bases.``batches`` are record batches of RAW_PROBABILITY_COLUMNS(read_probability_batches). Each record yields two tracks in transcriptorientation, ``(coding probabilities, encoded bases)`` for the forwardstrand and for the reverse complement, each with a ``(record_id,sequence, strand, length)`` context. A record whose two tracks hold atmost ``max_chunk_bp`` bases together joins a chunk with both, which theCPU backend then decodes in parallel; a longer record joins one track at atime, so that its two strands need not be held at once. Tracks thatexceed what is left of the open chunk start the next one, so a chunkholds more than ``max_chunk_bp`` bases only when it is a single longertrack; a track is never split. Yields ``(tracks, track_contexts,chunk_bp)``."""tracks = []track_contexts = []chunk_bp = 0for batch in batches:record_ids = batch.column(RECORD_ID_COLUMN)sequences = batch.column(SEQUENCE_COLUMN)positive_probabilities = batch.column(POSITIVE_STRAND_PROBABILITY_COLUMN)negative_probabilities = batch.column(NEGATIVE_STRAND_PROBABILITY_COLUMN)for row_index in range(batch.num_rows):sequence = sequences[row_index].as_py().upper()4 unmodified linesfilter_stats["record_count"] += 1filter_stats["bp"] += record_lengthcontinuepositive = probability_vector_from_arrow(positive_probabilities[row_index])negative = probability_vector_from_arrow(negative_probabilities[row_index])if len(positive) < record_length or len(negative) < record_length:raise ValueError(f"record {record_id!r} has {record_length} bases but "3 unmodified linespositive = positive[:record_length]negative = negative[:record_length]forward_bases, reverse_bases = encode_both_strands(sequence)strand_tracks = [((positive, forward_bases), "+"),((np.ascontiguousarray(negative[::-1]), reverse_bases), "-"),]if 2 * record_length <= max_chunk_bp:units = [strand_tracks]else:units = [[strand_track] for strand_track in strand_tracks]for unit in units:unit_bp = len(unit) * record_length# Tracks that do not fit in the open chunk start the next one.if tracks and chunk_bp + unit_bp > max_chunk_bp:yield tracks, track_contexts, chunk_bptracks = []track_contexts = []chunk_bp = 0for track, strand in unit:tracks.append(track)track_contexts.append((record_id, sequence, strand, record_length))chunk_bp += unit_bp# A full chunk is handed over before the next record is read.if chunk_bp >= max_chunk_bp:yield tracks, track_contexts, chunk_bptracks = []track_contexts = []chunk_bp = 0if tracks:yield tracks, track_contexts, chunk_bpdef iter_prefetched_chunks(chunks):"""Prepare the next chunk in a background thread while the caller processes the current one.Reading and encoding the input overlaps the networks and the Viterbialgorithm. Besides the current chunk, at most one prepared chunk is held;while the last strand of a record is processed, that is the next recordread ahead."""chunk_iterator = iter(chunks)with ThreadPoolExecutor(max_workers=1) as executor:7 unmodified linesdef decode_chunk_genes(tracks, track_contexts, transition_network, viterbi_backend, stop_codons,max_boundary_intron_length, min_cds_length, confidence_network,):"""Run the three post-processing stages on one chunk under one stop-codon set.The chunk's transition log-odds are released once its Viterbi paths aredecoded. Returns ``(chunk_genes, short_gene_count, transition_seconds,viterbi_seconds, confidence_seconds)``; each entry of ``chunk_genes`` is``(gene, probabilities, oriented_exons)``."""# Stage 1: transition log-odds for every oriented track of the chunk.stage_started = time.perf_counter()transition_log_odds = [transition_network.inference(probabilities) for probabilities, _ in tracks]transition_seconds = time.perf_counter() - stage_started# Stage 2: the Viterbi algorithm.stage_started = time.perf_counter()state_paths = decode_paths(tracks,transition_log_odds,viterbi_backend,stop_taa="TAA" in stop_codons,stop_tag="TAG" in stop_codons,1 unmodified linemax_boundary_intron_length=max_boundary_intron_length,)viterbi_seconds = time.perf_counter() - stage_starteddel transition_log_oddsif len(state_paths) != len(track_contexts):raise RuntimeError(f"{viterbi_backend} Viterbi backend returned {len(state_paths)} paths "30 unmodified lineschunk_genes.append((gene, probabilities, oriented_exons))strand_gene_indices.append((probabilities, gene_indices))# Stage 3: the confidence of every complete gene of the chunk, strand by# strand. Every written gene gives roles to its strand; only the complete# ones are scored.stage_started = time.perf_counter()for probabilities, gene_indices in strand_gene_indices:scored = [8 unmodified linesfor position, confidence in zip(scored, confidences):chunk_genes[gene_indices[position]][0]["confidence"] = float(confidence)confidence_seconds = time.perf_counter() - stage_startedreturn chunk_genes, short_gene_count, transition_seconds, viterbi_seconds, confidence_secondsdef record_codon_table_warning(output_prefix, warning, stop_codons):38 unmodified linesdef post_process_probability_file(input_path, output_prefix, viterbi_backend, codon_to_amino_acid,transition_network, confidence_network,max_boundary_intron_length, chunk_mbp=None,min_record_length=MIN_RECORD_LENGTH_BP,min_cds_length=MIN_CDS_LENGTH_BP,):"""Post-process one raw-probability file into GFF3, CDS FASTA, and protein FASTA.``viterbi_backend`` is the name returned by ``choose_viterbi_backend``;``chunk_mbp`` defaults to the backend's chunk size (CHUNK_SIZE_MBP).When the confidences of the complete genes contradict the codon table(utils.codon_table_mismatch), the warning is printed and recorded in thedirectory layout by ``record_codon_table_warning``."""file_started = time.perf_counter()stop_codons = tuple(stop_codons_from_table(codon_to_amino_acid))if chunk_mbp is None:chunk_mbp = CHUNK_SIZE_MBP[viterbi_backend]genes = []short_gene_count = 04 unmodified linesfilter_stats = {"record_count": 0, "bp": 0}input_chunks = iter_probability_chunks(read_probability_batches(input_path),chunk_mbp * 1_000_000,min_record_length=min_record_length,filter_stats=filter_stats,)for tracks, track_contexts, chunk_bp in iter_prefetched_chunks(input_chunks):(chunk_genes, chunk_short_gene_count,chunk_transition_seconds, chunk_viterbi_seconds, chunk_confidence_seconds,) = decode_chunk_genes(tracks, track_contexts, transition_network, viterbi_backend, stop_codons,max_boundary_intron_length, min_cds_length, confidence_network,)short_gene_count += chunk_short_gene_counttransition_seconds += chunk_transition_secondsviterbi_seconds += chunk_viterbi_secondsconfidence_seconds += chunk_confidence_seconds48 unmodified linesdef parse_args():"""Parse command-line arguments."""parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)parser.add_argument("--input", required=True, help="one *.raw_probs.arrow or *.raw_probs.parquet file")parser.add_argument("--output", default=None, help="output prefix; defaults to <input>.predicted")parser.add_argument("--viterbi_backend",6 unmodified linesdefault=str(CODON_TABLE_PATH),help=("JSON object mapping all 64 ATCG codons to amino acids; '*' marks ""stop codons"),)parser.add_argument(26 unmodified linesparser.add_argument("--chunk_mbp",type=int,default=None,help=(f"host-side chunk size in megabases (default: {CHUNK_SIZE_MBP['gpu']}, or "f"{CHUNK_SIZE_MBP['cpu']} with the CPU Viterbi backend, which decodes the strands ""of a chunk in parallel); post-processing takes about 50 MB of memory per megabase ""of its largest chunk; a strand is never split, so a longer one is a chunk of its own"),)parser.add_argument("--min_record_length",
86 unmodified lines878889909192939495969798991001011021034 unmodified lines10810911011111211311411511611711811912012112212312412512612786 unmodified linesdef chunked_inference(network, context_radius, tracks, device, chunk_bp=NETWORK_CHUNK_BP):"""Run a per-base network over long tracks, one chunk at a time.``tracks`` are per-base arrays of one common length in decoderorientation. ``network(*chunks)`` receives corresponding chunks of them astensors on ``device`` and returns one output row per base; each outputdepends on the inputs within ``context_radius`` bases of its base. Thetracks are processed in chunks of at most ``chunk_bp`` bases, eachevaluated with ``context_radius`` extra bases on both sides, clipped tothe tracks, so the outputs equal those of one pass over the whole trackswhile only one chunk is ever on the device. Returns the float32``[bases, ...]`` outputs as one CPU array. On CUDA the network runs underbfloat16 autocast, the precision used for all reported results; on CPU itruns in float32."""tracks = [np.asarray(track) for track in tracks]if not tracks or any(track.ndim != 1 for track in tracks) or len({len(track) for track in tracks}) != 1:4 unmodified linesif chunk_bp < 1:raise ValueError("chunk size must be positive")outputs = Nonefor start in range(0, length, chunk_bp):stop = min(start + chunk_bp, length)window_start = max(0, start - context_radius)window_stop = min(length, stop + context_radius)with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):window_outputs = network(*(torch.as_tensor(track[window_start:window_stop]).to(device) for track in tracks))chunk_outputs = window_outputs[start - window_start:stop - window_start].float().cpu().numpy()if outputs is None:outputs = np.empty((length,) + chunk_outputs.shape[1:], dtype=np.float32)outputs[start:stop] = chunk_outputsreturn outputsdef load_weights(path):86 unmodified lines878889909192939495969798991001011021031041054 unmodified lines11011111211311411511611711811912012112212312412512612712812986 unmodified linesdef chunked_inference(network, context_radius, tracks, device, chunk_bp=NETWORK_CHUNK_BP):"""Run a per-base network over long tracks, one chunk at a time.``tracks`` are per-base arrays of one common length in transcriptorientation. ``network(*chunks)`` receives corresponding chunks of them astensors on ``device`` and returns one output row per base; each outputdepends on the inputs within ``context_radius`` bases of its base. Thetracks are processed in chunks of at most ``chunk_bp`` bases, eachevaluated with ``context_radius`` extra bases on both sides, clipped tothe tracks, so the outputs equal those of one pass over the whole trackswhile only one chunk is ever on the device. Returns an iterator over``(start, stop, outputs)``, one per chunk in track order: ``outputs`` isthe float32 CPU array of the output rows of bases ``start`` to``stop - 1``, and the caller keeps what it needs of it. On CUDA thenetwork runs under bfloat16 autocast, the precision used for all reportedresults; on CPU it runs in float32."""tracks = [np.asarray(track) for track in tracks]if not tracks or any(track.ndim != 1 for track in tracks) or len({len(track) for track in tracks}) != 1:4 unmodified linesif chunk_bp < 1:raise ValueError("chunk size must be positive")def chunk_outputs():for start in range(0, length, chunk_bp):stop = min(start + chunk_bp, length)window_start = max(0, start - context_radius)window_stop = min(length, stop + context_radius)# Every window is copied: tracks read from a raw-probability file# are read-only views of its buffers.with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):window_outputs = network(*(torch.tensor(track[window_start:window_stop], device=device) for track in tracks))yield start, stop, window_outputs[start - window_start:stop - window_start].float().cpu().numpy()return chunk_outputs()def load_weights(path):
15 unmodified lines1617181920212223243 unmodified lines282930313233343511 unmodified lines47484950515233 unmodified lines868788899091929394959697989910010110210310410510610710810915 unmodified linesThe Viterbi algorithm (viterbi.py) adds the log-probability of thepossibility it selects at every boundary to the path score. Because every pathselects exactly one per boundary, subtracting log P(stay) at eachboundary changes the score of every path by the same constant, so the decodersreceive each transition as its log-odds relative to staying, and staying costsnothing. The four log-odds are attached to the base where the new segmentbegins or, for leaving a gene, to the base that closes it:enter_gene(i) = log P(enter_gene | boundary i) - log P(stay | boundary i)3 unmodified linesRecords are scored in chunks read with the network's full context on bothsides (tcn.chunked_inference), so a chromosome never has to fit in GPU memoryat once. The scores leave this module in nats; the Viterbi implementationsquantize them to their own fixed-point units (utils.prepare_transition_probabilities)."""import numpy as np11 unmodified linesTRANSITION_NAMES,)from tcn import TCN, chunked_inference, coding_log_odds, load_weightsTRANSITION_NETWORK_TYPE = "transition_network"33 unmodified lines@torch.inference_mode()def inference(self, probabilities, chunk_bp=NETWORK_CHUNK_BP):"""Return the transition probabilities of one oriented coding-probability track.The result is a float32 ``(bases, 4)`` array in ``TRANSITION_NAMES``column order, each value the transition's log-odds against staying, innats. The track is processed in ``chunk_bp`` chunks with the network'sfull context on both sides (tcn.chunked_inference), so the values equalthose of scoring the whole record at once."""probabilities = np.asarray(probabilities, dtype=np.float32)if probabilities.ndim != 1 or len(probabilities) == 0:raise ValueError("probabilities must be a nonempty vector")def network(chunk):return self(chunk[None, :])[0]return chunked_inference(network, self.context_radius, (probabilities,), next(self.parameters()).device, chunk_bp,)def transition_log_odds_from_logits(transition_logits):15 unmodified lines1617181920212223243 unmodified lines28293031323334353611 unmodified lines4849505152535433 unmodified lines88899091929394959697989910010110210310410510610710810911011111211311411515 unmodified linesThe Viterbi algorithm (viterbi.py) adds the log-probability of thepossibility it selects at every boundary to the path score. Because every pathselects exactly one per boundary, subtracting log P(stay) at eachboundary changes the score of every path by the same constant, so Viterbireceives each transition as its log-odds relative to staying, and stayingcosts nothing. The four log-odds are attached to the base where the new segmentbegins or, for leaving a gene, to the base that closes it:enter_gene(i) = log P(enter_gene | boundary i) - log P(stay | boundary i)3 unmodified linesRecords are scored in chunks read with the network's full context on bothsides (tcn.chunked_inference), so a chromosome never has to fit in GPU memoryat once. Every chunk of scores is converted to the Viterbi backends'fixed-point units as it is computed (utils.quantize_transition_log_odds), andthe scores leave this module as int32 arrays."""import numpy as np11 unmodified linesTRANSITION_NAMES,)from tcn import TCN, chunked_inference, coding_log_odds, load_weightsfrom utils import quantize_transition_log_oddsTRANSITION_NETWORK_TYPE = "transition_network"33 unmodified lines@torch.inference_mode()def inference(self, probabilities, chunk_bp=NETWORK_CHUNK_BP):"""Return the transition log-odds of one oriented coding-probability track.The result is an int32 ``(bases, 4)`` array in ``TRANSITION_NAMES``column order, each value the transition's log-odds against staying inthe Viterbi backends' fixed-point units. The track is processed in``chunk_bp`` chunks with the network's full context on both sides(tcn.chunked_inference), so the values equal those of scoring thewhole record at once; each chunk is quantized as it is computed."""probabilities = np.asarray(probabilities)if probabilities.ndim != 1 or len(probabilities) == 0:raise ValueError("probabilities must be a nonempty vector")def network(chunk):return self(chunk[None, :])[0]transition_log_odds = np.empty((len(probabilities), TRANSITION_COUNT), dtype=np.int32)for start, stop, chunk_log_odds in chunked_inference(network, self.context_radius, (probabilities,), next(self.parameters()).device, chunk_bp,):transition_log_odds[start:stop] = quantize_transition_log_odds(chunk_log_odds)return transition_log_oddsdef transition_log_odds_from_logits(transition_logits):
81 unmodified lines828384858687888943 unmodified lines13313413513613713813958 unmodified lines19819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630717 unmodified lines3253263273283293303315 unmodified lines33733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839912 unmodified lines4124134144154164174184194204214224234244254266 unmodified lines43343443543643743843922 unmodified lines462463464465466467468167 unmodified lines63663763863964064164210 unmodified lines6536546556566576586592 unmodified lines6626636646656666676686696706716726736 unmodified lines68068168268368468568681 unmodified linesreturn value# Codon tables are flat JSON objects: all 64 concrete codons map to one-letter# amino acid symbols, and "*" selects the decoder's enabled stop codons.ALL_CODONS = frozenset(first + second + thirdfor first in CODON_BASES43 unmodified lines)if unsupported_stop_codons:raise ValueError("decoder stop codons must be a subset of TAA,TAG,TGA: "+ ",".join(unsupported_stop_codons))58 unmodified linesreturn lookup# Decoder state schema. The active sequence-conditioned decoder uses 30 states.PREFIX_TYPE_COUNT = 6STATE_COUNT = 30# Prefix type ids carried by exon and intron states. Codon phase is the number# of CDS bases already consumed in the current codon. Prefix types retain the# additional bases needed to recognize a standard stop on the next emission.PREFIX_TYPE_0 = 0 # codon phase 0; codon boundary, no open prefixPREFIX_TYPE_1 = 1 # codon phase 1; one-base prefix TPREFIX_TYPE_2 = 2 # codon phase 1; one-base prefix otherPREFIX_TYPE_3 = 3 # codon phase 2; two-base prefix TAPREFIX_TYPE_4 = 4 # codon phase 2; two-base prefix TGPREFIX_TYPE_5 = 5 # codon phase 2; two-base prefix other# Numeric state ids. Keep the layout grouped by biological role rather than by# historical patches; lookup tables below make prefix-type mapping explicit.INTERGENIC = 0START_A = 1START_AT = 2EXON_PREFIX_TYPE_0 = 3EXON_PREFIX_TYPE_1 = 4EXON_PREFIX_TYPE_2 = 5EXON_PREFIX_TYPE_3 = 6EXON_PREFIX_TYPE_4 = 7EXON_PREFIX_TYPE_5 = 8STOP = 9GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_0 = 10GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_1 = 11GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_2 = 12GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_3 = 13GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_4 = 14GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_5 = 15GT_GC_AG_INTRON_READY_PREFIX_TYPE_0 = 16GT_GC_AG_INTRON_READY_PREFIX_TYPE_1 = 17GT_GC_AG_INTRON_READY_PREFIX_TYPE_2 = 18GT_GC_AG_INTRON_READY_PREFIX_TYPE_3 = 19GT_GC_AG_INTRON_READY_PREFIX_TYPE_4 = 20GT_GC_AG_INTRON_READY_PREFIX_TYPE_5 = 21AT_AC_INTRON_PREFIX_TYPE_0 = 22AT_AC_INTRON_PREFIX_TYPE_1 = 23AT_AC_INTRON_PREFIX_TYPE_2 = 24AT_AC_INTRON_PREFIX_TYPE_3 = 25AT_AC_INTRON_PREFIX_TYPE_4 = 26AT_AC_INTRON_PREFIX_TYPE_5 = 27LEADING_BOUNDARY_INTRON = 28TRAILING_BOUNDARY_INTRON = 29EXON_STATE_BY_PREFIX_TYPE = np.array((EXON_PREFIX_TYPE_0,EXON_PREFIX_TYPE_1,EXON_PREFIX_TYPE_2,EXON_PREFIX_TYPE_3,EXON_PREFIX_TYPE_4,EXON_PREFIX_TYPE_5,), dtype=np.int64)GT_GC_AG_INTRON_FIRST_STATE_BY_PREFIX_TYPE = np.array((GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_0,GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_1,GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_2,GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_3,GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_4,GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_5,), dtype=np.int64)GT_GC_AG_INTRON_READY_STATE_BY_PREFIX_TYPE = np.array((GT_GC_AG_INTRON_READY_PREFIX_TYPE_0,GT_GC_AG_INTRON_READY_PREFIX_TYPE_1,GT_GC_AG_INTRON_READY_PREFIX_TYPE_2,GT_GC_AG_INTRON_READY_PREFIX_TYPE_3,GT_GC_AG_INTRON_READY_PREFIX_TYPE_4,GT_GC_AG_INTRON_READY_PREFIX_TYPE_5,), dtype=np.int64)AT_AC_INTRON_STATE_BY_PREFIX_TYPE = np.array((AT_AC_INTRON_PREFIX_TYPE_0,AT_AC_INTRON_PREFIX_TYPE_1,AT_AC_INTRON_PREFIX_TYPE_2,AT_AC_INTRON_PREFIX_TYPE_3,AT_AC_INTRON_PREFIX_TYPE_4,AT_AC_INTRON_PREFIX_TYPE_5,), dtype=np.int64)# Unlike codon phase above, GFF3 phase is the number of visible bases to skip at# the beginning of a CDS feature before reaching the first complete codon. A# boundary-truncated gene's first state retains enough information to recover it.INITIAL_CDS_PHASE_BY_STATE = {START_A: 0,START_AT: 2,EXON_PREFIX_TYPE_0: 1,EXON_PREFIX_TYPE_1: 0,EXON_PREFIX_TYPE_2: 0,EXON_PREFIX_TYPE_3: 2,EXON_PREFIX_TYPE_4: 2,EXON_PREFIX_TYPE_5: 2,STOP: 1,}def initial_cds_phase_from_state(state):"""Return the initial GFF3 phase encoded by the first visible CDS state."""try:return INITIAL_CDS_PHASE_BY_STATE[int(state)]except KeyError as exc:raise ValueError(f"state {state} does not emit CDS") from exc17 unmodified linesreturn forward_bases, reverse_basesdef probability_vector_from_parquet(value):"""Convert one PyArrow list cell to a 1D float16 probability array."""if not hasattr(value, "values"):raise TypeError("probability column must contain PyArrow list values")5 unmodified linesdef prepare_decode_tasks(tasks):"""Normalize decoder tasks and reject invalid shapes or lengths."""prepared_tasks = []for task_index, (probabilities, encoded_bases) in enumerate(tasks):probability_array = np.ascontiguousarray(probabilities, dtype=np.float16)base_array = np.ascontiguousarray(encoded_bases, dtype=np.int8)if probability_array.ndim != 1:raise ValueError(f"decoder task {task_index} probabilities must be 1D, "f"got {probability_array.shape}")if base_array.ndim != 1:raise ValueError(f"decoder task {task_index} encoded bases must be 1D, "f"got {base_array.shape}")if len(probability_array) != len(base_array):raise ValueError(f"decoder task {task_index} has {len(probability_array)} "f"probabilities but {len(base_array)} encoded bases")if len(probability_array) == 0:raise ValueError(f"decoder task {task_index} is empty")prepared_tasks.append((probability_array, base_array))return prepared_tasksdef prepare_transition_probabilities(transition_probabilities, prepared_tasks):"""Quantize one ``(bases, 4)`` transition-probability array per task for the decoders.The columns follow ``TRANSITION_NAMES``: enter gene, leave gene, enterintron, leave intron. Each value is the transition network's log-oddsagainst staying, in nats, aligned base by base with the task'sprobabilities. The Viterbi implementations accumulate int32 fixed-pointscores, so the values come back rounded to ``FIXED_POINT_SCORE_SCALE``units as contiguous int32 arrays."""transition_probabilities = list(transition_probabilities)if len(transition_probabilities) != len(prepared_tasks):raise ValueError(f"{len(transition_probabilities)} transition-probability arrays for "f"{len(prepared_tasks)} decoder tasks")limits = np.iinfo(np.int32)prepared_scores = []for task_index, (log_odds, (probabilities, _)) in enumerate(zip(transition_probabilities, prepared_tasks)):scaled = np.rint(np.asarray(log_odds, dtype=np.float64) * FIXED_POINT_SCORE_SCALE)if scaled.shape != (len(probabilities), TRANSITION_COUNT):raise ValueError(f"decoder task {task_index} transition probabilities must have shape "f"{(len(probabilities), TRANSITION_COUNT)}, got {scaled.shape}")if not np.all(np.isfinite(scaled)) or scaled.min() < limits.min or scaled.max() > limits.max:raise OverflowError(f"decoder task {task_index} transition log-odds exceed the int32 fixed-point range")prepared_scores.append(np.ascontiguousarray(scaled, dtype=np.int32))return prepared_scoresdef build_cds_sequence(genome_sequence, transcript_order_exons, strand):12 unmodified linesreturn reverse_complement(genomic_order_sequence)def compute_gff_cds_phases(transcript_order_exons, initial_cds_phase=0):"""Return GFF3 phases, preserving the first visible codon's phase."""if initial_cds_phase not in (0, 1, 2):raise ValueError("initial CDS phase must be 0, 1, or 2")phases = []consumed_bases = 0for start, end in transcript_order_exons:phase = (initial_cds_phase - consumed_bases) % 3phases.append(phase)consumed_bases += end - start + 1return phases6 unmodified lines):"""Return whether a translated CDS contains a non-terminal stop codon.This is a diagnostic check: the decoder grammar should normally make theresult false. A stop is terminal only when its third base is the final CDSbase; a stop before an incomplete trailing codon is still internal."""22 unmodified linesReasons are comma-separated so boundary-truncated predictions can stateevery visible problem inside one GFF3 attribute, for example``no_start,no_stop``. ``short_intron``records a decoder path with fewer than four bases between adjacent exons.Start and stop presence comes from the decoded states, then the sequenceis checked as a consistency guard."""167 unmodified linesstop_codons=STOP_CODONS,):"""Build one output gene from its exons and boundary CDS states."""initial_cds_phase = initial_cds_phase_from_state(first_cds_state)if strand == "+":transcript_order_exons = [(int(start), int(end)) for start, end in oriented_exons10 unmodified linestranscript_order_phases = compute_gff_cds_phases(transcript_order_exons,initial_cds_phase,)genomic_order = sorted(zip(transcript_order_exons, transcript_order_phases),2 unmodified linesassert not has_internal_stop_codon(cds_sequence,initial_cds_phase,stop_codons,), ("decoder produced an internal stop codon: "f"record_id={record_id!r}, strand={strand}, "f"phase={initial_cds_phase}, exons={transcript_order_exons}")complete, incomplete_reason = classify_cds_completion(cds_sequence,6 unmodified lines"record_id": record_id,"strand": strand,"cds": cds_sequence,"translation_frame": initial_cds_phase,"complete": complete,"incomplete_reason": incomplete_reason,"exons": [exon for exon, phase in genomic_order],81 unmodified lines82838485868788899091929394959697989910010110243 unmodified lines14614714814915015115258 unmodified lines21121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932017 unmodified lines3383393403413423433445 unmodified lines35035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945012 unmodified lines4634644654664674684694704714724734744754764776 unmodified lines48448548648748848949022 unmodified lines513514515516517518519167 unmodified lines68768868969069169269310 unmodified lines7047057067077087097102 unmodified lines7137147157167177187197207217227237246 unmodified lines73173273373473573673781 unmodified linesreturn valuedef validate_memory_budget_bytes(value):"""Return a device memory budget in bytes, or ``None`` for the default."""if value is None:return Nonetry:value = operator.index(value)except TypeError as exc:raise TypeError("memory_budget_bytes must be an integer or None") from excif value <= 0:raise ValueError("memory_budget_bytes must be positive or None")return value# Codon tables are flat JSON objects: all 64 concrete codons map to one-letter# amino acid symbols, and "*" marks the stop codons Viterbi recognizes.ALL_CODONS = frozenset(first + second + thirdfor first in CODON_BASES43 unmodified lines)if unsupported_stop_codons:raise ValueError("codon table stop codons must be a subset of TAA,TAG,TGA: "+ ",".join(unsupported_stop_codons))58 unmodified linesreturn lookup# The Viterbi states (State design in viterbi.py).PREFIX_TYPE_COUNT = 6STATE_COUNT = 30# Prefix type ids carried by exon and intron states. Codon phase is the number# of CDS bases already consumed in the current codon. Prefix types retain the# additional bases needed to recognize a standard stop on the next emission.PHASE0 = 0 # codon phase 0; codon boundary, no open prefixPHASE1_PREFIX_T = 1 # codon phase 1; one-base prefix TPHASE1_PREFIX_OTHER = 2 # codon phase 1; one-base prefix otherPHASE2_PREFIX_TA = 3 # codon phase 2; prefix TA, so A/G completes TAA/TAGPHASE2_PREFIX_TG = 4 # codon phase 2; prefix TG, so A completes TGAPHASE2_PREFIX_OTHER = 5 # codon phase 2; other prefix, so no stop can be completed# State ids, grouped by biological role. The tables below map each prefix type# to its exon and intron states.INTERGENIC = 0START_A = 1START_AT = 2EXON_PHASE0 = 3EXON_PHASE1_PREFIX_T = 4EXON_PHASE1_PREFIX_OTHER = 5EXON_PHASE2_PREFIX_TA = 6EXON_PHASE2_PREFIX_TG = 7EXON_PHASE2_PREFIX_OTHER = 8STOP = 9GT_GC_AG_INTRON_FIRST_PHASE0 = 10GT_GC_AG_INTRON_FIRST_PHASE1_PREFIX_T = 11GT_GC_AG_INTRON_FIRST_PHASE1_PREFIX_OTHER = 12GT_GC_AG_INTRON_FIRST_PHASE2_PREFIX_TA = 13GT_GC_AG_INTRON_FIRST_PHASE2_PREFIX_TG = 14GT_GC_AG_INTRON_FIRST_PHASE2_PREFIX_OTHER = 15GT_GC_AG_INTRON_READY_PHASE0 = 16GT_GC_AG_INTRON_READY_PHASE1_PREFIX_T = 17GT_GC_AG_INTRON_READY_PHASE1_PREFIX_OTHER = 18GT_GC_AG_INTRON_READY_PHASE2_PREFIX_TA = 19GT_GC_AG_INTRON_READY_PHASE2_PREFIX_TG = 20GT_GC_AG_INTRON_READY_PHASE2_PREFIX_OTHER = 21AT_AC_INTRON_PHASE0 = 22AT_AC_INTRON_PHASE1_PREFIX_T = 23AT_AC_INTRON_PHASE1_PREFIX_OTHER = 24AT_AC_INTRON_PHASE2_PREFIX_TA = 25AT_AC_INTRON_PHASE2_PREFIX_TG = 26AT_AC_INTRON_PHASE2_PREFIX_OTHER = 27LEADING_BOUNDARY_INTRON = 28TRAILING_BOUNDARY_INTRON = 29EXON_STATE_BY_PREFIX_TYPE = np.array((EXON_PHASE0,EXON_PHASE1_PREFIX_T,EXON_PHASE1_PREFIX_OTHER,EXON_PHASE2_PREFIX_TA,EXON_PHASE2_PREFIX_TG,EXON_PHASE2_PREFIX_OTHER,), dtype=np.int64)GT_GC_AG_INTRON_FIRST_STATE_BY_PREFIX_TYPE = np.array((GT_GC_AG_INTRON_FIRST_PHASE0,GT_GC_AG_INTRON_FIRST_PHASE1_PREFIX_T,GT_GC_AG_INTRON_FIRST_PHASE1_PREFIX_OTHER,GT_GC_AG_INTRON_FIRST_PHASE2_PREFIX_TA,GT_GC_AG_INTRON_FIRST_PHASE2_PREFIX_TG,GT_GC_AG_INTRON_FIRST_PHASE2_PREFIX_OTHER,), dtype=np.int64)GT_GC_AG_INTRON_READY_STATE_BY_PREFIX_TYPE = np.array((GT_GC_AG_INTRON_READY_PHASE0,GT_GC_AG_INTRON_READY_PHASE1_PREFIX_T,GT_GC_AG_INTRON_READY_PHASE1_PREFIX_OTHER,GT_GC_AG_INTRON_READY_PHASE2_PREFIX_TA,GT_GC_AG_INTRON_READY_PHASE2_PREFIX_TG,GT_GC_AG_INTRON_READY_PHASE2_PREFIX_OTHER,), dtype=np.int64)AT_AC_INTRON_STATE_BY_PREFIX_TYPE = np.array((AT_AC_INTRON_PHASE0,AT_AC_INTRON_PHASE1_PREFIX_T,AT_AC_INTRON_PHASE1_PREFIX_OTHER,AT_AC_INTRON_PHASE2_PREFIX_TA,AT_AC_INTRON_PHASE2_PREFIX_TG,AT_AC_INTRON_PHASE2_PREFIX_OTHER,), dtype=np.int64)# Unlike codon phase above, GFF3 phase is the number of visible bases to skip at# the beginning of a CDS feature before reaching the first complete codon. A# boundary-truncated gene's first state retains enough information to recover it.INITIAL_GFF3_PHASE_BY_STATE = {START_A: 0,START_AT: 2,EXON_PHASE0: 1,EXON_PHASE1_PREFIX_T: 0,EXON_PHASE1_PREFIX_OTHER: 0,EXON_PHASE2_PREFIX_TA: 2,EXON_PHASE2_PREFIX_TG: 2,EXON_PHASE2_PREFIX_OTHER: 2,STOP: 1,}def initial_gff3_phase_from_state(state):"""Return the initial GFF3 phase encoded by the first visible CDS state."""try:return INITIAL_GFF3_PHASE_BY_STATE[int(state)]except KeyError as exc:raise ValueError(f"state {state} does not emit CDS") from exc17 unmodified linesreturn forward_bases, reverse_basesdef probability_vector_from_arrow(value):"""Convert one PyArrow list cell to a 1D float16 probability array."""if not hasattr(value, "values"):raise TypeError("probability column must contain PyArrow list values")5 unmodified linesdef prepare_decode_tasks(tasks):"""Normalize Viterbi tasks and reject invalid shapes or lengths."""prepared_tasks = []for task_index, (probabilities, encoded_bases) in enumerate(tasks):probability_array = np.ascontiguousarray(probabilities, dtype=np.float16)base_array = np.ascontiguousarray(encoded_bases, dtype=np.int8)if probability_array.ndim != 1:raise ValueError(f"Viterbi task {task_index} probabilities must be 1D, "f"got {probability_array.shape}")if base_array.ndim != 1:raise ValueError(f"Viterbi task {task_index} encoded bases must be 1D, "f"got {base_array.shape}")if len(probability_array) != len(base_array):raise ValueError(f"Viterbi task {task_index} has {len(probability_array)} "f"probabilities but {len(base_array)} encoded bases")if len(probability_array) == 0:raise ValueError(f"Viterbi task {task_index} is empty")prepared_tasks.append((probability_array, base_array))return prepared_tasksdef pack_decode_tasks(prepared_tasks, prepared_transition_log_odds):"""Return prepared Viterbi tasks as one batch for a native backend.The batch is the P(CDS) bits (uint16), the encoded bases, the int32transition scores, and the record offsets, one more than the tasks. Asingle task is passed on without a copy."""record_offsets = np.zeros(len(prepared_tasks) + 1, np.int64)np.cumsum([len(encoded_bases) for _, encoded_bases in prepared_tasks], out=record_offsets[1:])if len(prepared_tasks) == 1:[(probabilities, encoded_bases)] = prepared_tasks[transition_scores] = prepared_transition_log_oddselse:probabilities = np.concatenate([probabilities for probabilities, _ in prepared_tasks])encoded_bases = np.concatenate([encoded_bases for _, encoded_bases in prepared_tasks])transition_scores = np.concatenate(prepared_transition_log_odds)return probabilities.view(np.uint16), encoded_bases, transition_scores, record_offsetsdef quantize_transition_log_odds(log_odds):"""Return transition log-odds in nats as the Viterbi backends' int32 fixed-point scores.Every value is multiplied by ``FIXED_POINT_SCORE_SCALE`` and rounded tothe nearest integer. float16 and float32 values are scaled in float32,other values in float64; the scale is a power of two, so the product isexact and rounds to the same integer in either precision."""log_odds = np.asarray(log_odds)exact_dtype = np.float32 if log_odds.dtype in (np.float16, np.float32) else np.float64scaled = np.rint(log_odds.astype(exact_dtype, copy=False) * exact_dtype(FIXED_POINT_SCORE_SCALE))limits = np.iinfo(np.int32)# As Python floats the extremes compare exactly with the int32 limits; NaN fails.if scaled.size and not limits.min <= float(scaled.min()) <= float(scaled.max()) <= limits.max:raise OverflowError("transition log-odds exceed the int32 fixed-point range")return scaled.astype(np.int32)def prepare_transition_log_odds(transition_log_odds, prepared_tasks):"""Check one ``(bases, 4)`` int32 transition log-odds array per task for the Viterbi backends.The columns follow ``TRANSITION_NAMES``: enter gene, leave gene, enterintron, leave intron. Each value is the transition network's log-oddsagainst staying in ``FIXED_POINT_SCORE_SCALE`` units(``quantize_transition_log_odds``), aligned base by base with the task'sprobabilities. The arrays come back C-contiguous."""transition_log_odds = list(transition_log_odds)if len(transition_log_odds) != len(prepared_tasks):raise ValueError(f"{len(transition_log_odds)} transition log-odds arrays for "f"{len(prepared_tasks)} Viterbi tasks")prepared_log_odds = []for task_index, (log_odds, (probabilities, _)) in enumerate(zip(transition_log_odds, prepared_tasks)):log_odds = np.asarray(log_odds)if log_odds.shape != (len(probabilities), TRANSITION_COUNT):raise ValueError(f"Viterbi task {task_index} transition log-odds must have shape "f"{(len(probabilities), TRANSITION_COUNT)}, got {log_odds.shape}")if log_odds.dtype != np.int32:raise TypeError(f"Viterbi task {task_index} transition log-odds must be int32 fixed-point scores, "f"got {log_odds.dtype}")prepared_log_odds.append(np.ascontiguousarray(log_odds))return prepared_log_oddsdef build_cds_sequence(genome_sequence, transcript_order_exons, strand):12 unmodified linesreturn reverse_complement(genomic_order_sequence)def compute_gff_cds_phases(transcript_order_exons, initial_gff3_phase=0):"""Return GFF3 phases, preserving the first visible codon's phase."""if initial_gff3_phase not in (0, 1, 2):raise ValueError("initial GFF3 phase must be 0, 1, or 2")phases = []consumed_bases = 0for start, end in transcript_order_exons:phase = (initial_gff3_phase - consumed_bases) % 3phases.append(phase)consumed_bases += end - start + 1return phases6 unmodified lines):"""Return whether a translated CDS contains a non-terminal stop codon.This is a diagnostic check: the Viterbi grammar should normally make theresult false. A stop is terminal only when its third base is the final CDSbase; a stop before an incomplete trailing codon is still internal."""22 unmodified linesReasons are comma-separated so boundary-truncated predictions can stateevery visible problem inside one GFF3 attribute, for example``no_start,no_stop``. ``short_intron``records a Viterbi path with fewer than four bases between adjacent exons.Start and stop presence comes from the decoded states, then the sequenceis checked as a consistency guard."""167 unmodified linesstop_codons=STOP_CODONS,):"""Build one output gene from its exons and boundary CDS states."""initial_gff3_phase = initial_gff3_phase_from_state(first_cds_state)if strand == "+":transcript_order_exons = [(int(start), int(end)) for start, end in oriented_exons10 unmodified linestranscript_order_phases = compute_gff_cds_phases(transcript_order_exons,initial_gff3_phase,)genomic_order = sorted(zip(transcript_order_exons, transcript_order_phases),2 unmodified linesassert not has_internal_stop_codon(cds_sequence,initial_gff3_phase,stop_codons,), ("Viterbi produced an internal stop codon: "f"record_id={record_id!r}, strand={strand}, "f"phase={initial_gff3_phase}, exons={transcript_order_exons}")complete, incomplete_reason = classify_cds_completion(cds_sequence,6 unmodified lines"record_id": record_id,"strand": strand,"cds": cds_sequence,"translation_frame": initial_gff3_phase,"complete": complete,"incomplete_reason": incomplete_reason,"exons": [exon for exon, phase in genomic_order],
21 unmodified lines22232425262728293031323334353637384 unmodified lines434445464748495051525354555657585960616263646566676869707172737475767778798081828384854 unmodified lines9091929394959610 unmodified lines10710810911011111211311478 unmodified lines19319419519619719819920020120220320420520620733 unmodified lines24124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028142 unmodified lines32432532632732832933024 unmodified lines3553563573583593603613623633643653663673683693703713721 unmodified line37437537637737837938011 unmodified lines3923933943953963973983994004014024031 unmodified line4054064074084094104114124134144154 unmodified lines42042142242342442542642742842967 unmodified lines49749849950050150250328 unmodified lines5325335345355365375381 unmodified line54054154254354454554612 unmodified lines55956056156256356456556656756856949 unmodified lines619620621622623624625626627628629105 unmodified lines7357367377387397407413 unmodified lines7457467477487497507519 unmodified lines761762763764765766767768769770771772773774775776777778779780781782783784785786130 unmodified lines9179189199209219229234 unmodified lines92892993093193293393493593693793893994021 unmodified linesState design:To recognize stop codons, the decoder only needs to remember which stopprefix, if any, has already been seen inside the current codon. That memoryis stored as one of six prefix types. Codon phase here means how many CDSbases, 0, 1, or 2, have been consumed in the current codon:prefix type 0: codon phase 0; codon boundary, no open prefixprefix type 1: codon phase 1; one-base prefix Tprefix type 2: codon phase 1; one-base prefix otherprefix type 3: codon phase 2; prefix TA, so A/G completes TAA/TAGprefix type 4: codon phase 2; prefix TG, so A completes TGAprefix type 5: codon phase 2; other prefix, so no stop can be completedGFF3 phase uses a different convention: it records how many visible basesto skip before the next complete codon, rather than bases already consumed.4 unmodified linesstate table because both exit at AG, but each uses its own intron prior.AT-AC uses a separate state table because it exits at AC.The active state ids are defined in utils.py:0 INTERGENIC non-coding outside genes1 START_A first base of start codon ATG2 START_AT first two bases of start codon ATG3 EXON_PREFIX_TYPE_0 CDS, carries prefix type 04 EXON_PREFIX_TYPE_1 CDS, carries prefix type 15 EXON_PREFIX_TYPE_2 CDS, carries prefix type 26 EXON_PREFIX_TYPE_3 CDS, carries prefix type 37 EXON_PREFIX_TYPE_4 CDS, carries prefix type 48 EXON_PREFIX_TYPE_5 CDS, carries prefix type 59 STOP terminal in-frame stop codon10 GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_0 first GT/GC-AG intron base, carries prefix type 011 GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_1 first GT/GC-AG intron base, carries prefix type 112 GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_2 first GT/GC-AG intron base, carries prefix type 213 GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_3 first GT/GC-AG intron base, carries prefix type 314 GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_4 first GT/GC-AG intron base, carries prefix type 415 GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_5 first GT/GC-AG intron base, carries prefix type 516 GT_GC_AG_INTRON_READY_PREFIX_TYPE_0 later GT/GC-AG intron base, carries prefix type 017 GT_GC_AG_INTRON_READY_PREFIX_TYPE_1 later GT/GC-AG intron base, carries prefix type 118 GT_GC_AG_INTRON_READY_PREFIX_TYPE_2 later GT/GC-AG intron base, carries prefix type 219 GT_GC_AG_INTRON_READY_PREFIX_TYPE_3 later GT/GC-AG intron base, carries prefix type 320 GT_GC_AG_INTRON_READY_PREFIX_TYPE_4 later GT/GC-AG intron base, carries prefix type 421 GT_GC_AG_INTRON_READY_PREFIX_TYPE_5 later GT/GC-AG intron base, carries prefix type 522 AT_AC_INTRON_PREFIX_TYPE_0 AT-AC intron, carries prefix type 023 AT_AC_INTRON_PREFIX_TYPE_1 AT-AC intron, carries prefix type 124 AT_AC_INTRON_PREFIX_TYPE_2 AT-AC intron, carries prefix type 225 AT_AC_INTRON_PREFIX_TYPE_3 AT-AC intron, carries prefix type 326 AT_AC_INTRON_PREFIX_TYPE_4 AT-AC intron, carries prefix type 427 AT_AC_INTRON_PREFIX_TYPE_5 AT-AC intron, carries prefix type 528 LEADING_BOUNDARY_INTRON intron extending from the left record boundary29 TRAILING_BOUNDARY_INTRON intron extending to the right record boundaryTransition rules:INTERGENIC self-loops or starts a start codon ATG. START_A -> START_AT ->exon prefix type 0. Exons consume coding bases and update prefix type;selected stops enter STOP. STOP exits to INTERGENIC. Exons may enterGT-AG/GC-AG introns at G followed by T/C, or AT-AC introns at A followedby T. GT/GC-AG introns enter FIRST, then must consume one more intron base4 unmodified linesOpening an intron adds the explicit log prior for its splice class. Thesupported frequencies are 0.990 for GT-AG, 0.009 for GC-AG, and 0.001 forAT-AC, each divided by the 0.99 GT-AG baseline before taking the logarithm.The GT-AG prior is therefore exactly zero, but remains an explicit decoderparameter in the Numba, CPU, and CUDA implementations.Except for the two boundary-intron guards described below, a sequence base10 unmodified linesscores at both ends of the intron and still pays the splice-class prior. Ifit wins, the model strongly prefers those bases to be non-coding, while theambiguous sequence provides too little evidence for a reliable repair. The path is retained and its gene is reported asincomplete with reason short_intron instead of expanding the decoder statespace solely for this rare condition.The transition network's four probabilities enter the score as log-oddsagainst staying, charged on the base where the new segment begins or, for78 unmodified linesMIN_PROB,)from utils import (PREFIX_TYPE_0, PREFIX_TYPE_1, PREFIX_TYPE_2,PREFIX_TYPE_3, PREFIX_TYPE_4, PREFIX_TYPE_5, PREFIX_TYPE_COUNT,STATE_COUNT, INTERGENIC, START_A, START_AT, EXON_PREFIX_TYPE_0, STOP,LEADING_BOUNDARY_INTRON, TRAILING_BOUNDARY_INTRON,EXON_STATE_BY_PREFIX_TYPE,GT_GC_AG_INTRON_FIRST_STATE_BY_PREFIX_TYPE,GT_GC_AG_INTRON_READY_STATE_BY_PREFIX_TYPE,AT_AC_INTRON_STATE_BY_PREFIX_TYPE,prepare_decode_tasks, prepare_transition_probabilities,validate_max_boundary_intron_length,)33 unmodified lines@njit(cache=True, inline="always")def next_coding_state_after_base(prefix_type, base, stop_taa, stop_tag, stop_tga):"""Return the exon/STOP state after emitting one coding base."""# Prefix type 0 means the previous coding base ended a codon. A new T can# still become TAA/TAG/TGA; every other base cannot start a stop codon.if prefix_type == PREFIX_TYPE_0:if base == BASE_T:return EXON_STATE_BY_PREFIX_TYPE[PREFIX_TYPE_1]return EXON_STATE_BY_PREFIX_TYPE[PREFIX_TYPE_2]# Prefix type 1 means the current codon prefix is exactly T.if prefix_type == PREFIX_TYPE_1:if base == BASE_A:return EXON_STATE_BY_PREFIX_TYPE[PREFIX_TYPE_3]if base == BASE_G:return EXON_STATE_BY_PREFIX_TYPE[PREFIX_TYPE_4]return EXON_STATE_BY_PREFIX_TYPE[PREFIX_TYPE_5]# Prefix type 2 is a one-base prefix other than T, so the second base cannot# create a possible standard stop prefix.if prefix_type == PREFIX_TYPE_2:return EXON_STATE_BY_PREFIX_TYPE[PREFIX_TYPE_5]# Prefix type 3 is TA. A or G completes TAA/TAG if those stops are enabled.if prefix_type == PREFIX_TYPE_3:if base == BASE_A and stop_taa:return STOPif base == BASE_G and stop_tag:return STOPreturn EXON_PREFIX_TYPE_0# Prefix type 4 is TG. A completes TGA if that stop is enabled.if prefix_type == PREFIX_TYPE_4:if base == BASE_A and stop_tga:return STOPreturn EXON_PREFIX_TYPE_0return EXON_PREFIX_TYPE_0@njit(cache=True, inline="always")42 unmodified lines@njit(cache=True)def initialize_first_base_scores(coding_scores, noncoding_scores, transition_probabilities, bases, record_length,stop_taa, stop_tag, stop_tga, boundary_introns_enabled,current_scores,):24 unmodified lines# observed base and unknown bases to the left of the record boundary. They# remain legal when boundary introns are disabled, allowing a record to# begin inside an exon.current_scores[EXON_STATE_BY_PREFIX_TYPE[PREFIX_TYPE_0]] = coding_scorecurrent_scores[EXON_STATE_BY_PREFIX_TYPE[PREFIX_TYPE_5]] = coding_scoreif base == BASE_N:for prefix_type in range(PREFIX_TYPE_COUNT):current_scores[EXON_STATE_BY_PREFIX_TYPE[prefix_type]] = coding_scoreelse:one_base_prefix_type = PREFIX_TYPE_1 if base == BASE_T else PREFIX_TYPE_2current_scores[EXON_STATE_BY_PREFIX_TYPE[one_base_prefix_type]] = coding_scoreif base == BASE_A:current_scores[EXON_STATE_BY_PREFIX_TYPE[PREFIX_TYPE_3]] = coding_scoreelif base == BASE_G:current_scores[EXON_STATE_BY_PREFIX_TYPE[PREFIX_TYPE_4]] = coding_score# The record may begin with the last observed base of a stop codon whose# first two bases lie outside the left boundary.1 unmodified linebase_matches(base, BASE_A) and (stop_taa or stop_tga)) or (base_matches(base, BASE_G) and stop_tag)if can_end_stop:current_scores[STOP] = coding_score + transition_probabilities[0, LEAVE_GENE]if boundary_introns_enabled:# A record that starts inside an intron has no observable preceding11 unmodified linesand third_start_base_matches)if has_atg_start:current_scores[START_A] = coding_score + transition_probabilities[0, ENTER_GENE]@njit(cache=True)def run_viterbi_forward(coding_scores, noncoding_scores, transition_probabilities, bases, record_length,stop_taa, stop_tag, stop_tga,gt_ag_intron_log_prior, gc_ag_intron_log_prior, at_ac_intron_log_prior,max_boundary_intron_length,1 unmodified line):"""Run the source-state Viterbi forward pass and fill backpointers.``transition_probabilities`` is the ``(record_length, 4)`` array of transitionnetwork scores in nats, in ``TRANSITION_NAMES`` column order."""initialize_first_base_scores(coding_scores, noncoding_scores, transition_probabilities, bases, record_length,stop_taa, stop_tag, stop_tga, max_boundary_intron_length != 0,current_scores,)4 unmodified linesbase = bases[position]coding_score = coding_scores[position]noncoding_score = noncoding_scores[position]enter_gene_log_odds = transition_probabilities[position, ENTER_GENE]leave_gene_log_odds = transition_probabilities[position, LEAVE_GENE]enter_intron_log_odds = transition_probabilities[position, ENTER_INTRON]leave_intron_log_odds = transition_probabilities[position, LEAVE_INTRON]# Donor tests look at the current and next base. At the final base the# unavailable next base may complete a donor outside the record.67 unmodified lines))can_enter_trailing_boundary_intron = (boundary_introns_enabledand (boundary_intron_length_is_unlimitedor record_length - position <= max_boundary_intron_length28 unmodified linesSTOP,)# 3. Start codon ATG consumes T and G, then enters exon prefix type 0.if current_scores[START_A] != -np.inf:keep_best_transition(next_scores, predecessors, START_AT,1 unmodified line)if current_scores[START_AT] != -np.inf:keep_best_transition(next_scores, predecessors, EXON_PREFIX_TYPE_0,current_scores[START_AT] + coding_score,START_AT,)12 unmodified linescurrent_scores[LEADING_BOUNDARY_INTRON] + noncoding_score,LEADING_BOUNDARY_INTRON,)can_exit_leading_intron = ((has_ag_acceptor or has_ac_acceptor)and not has_exact_acceptor_followed_by_atg)if can_exit_leading_intron:for prefix_type in range(PREFIX_TYPE_COUNT):emit_coding_base(current_scores, next_scores, predecessors,49 unmodified linesexon_state,)if (has_any_donorand not has_exact_enabled_stop_followed_by_donorand can_enter_trailing_boundary_intron):if has_gt_ag_donor:keep_best_transition(next_scores, predecessors,105 unmodified lines@njit(cache=True, nogil=True)def decode_one_track(coding_scores, noncoding_scores, transition_probabilities, bases, record_length,stop_taa, stop_tag, stop_tga,gt_ag_intron_log_prior, gc_ag_intron_log_prior, at_ac_intron_log_prior,max_boundary_intron_length,3 unmodified linescurrent_scores = np.empty(STATE_COUNT, np.float64)backpointers = np.empty((record_length, STATE_COUNT), np.int8)run_viterbi_forward(coding_scores, noncoding_scores, transition_probabilities, bases, record_length,stop_taa, stop_tag, stop_tga,gt_ag_intron_log_prior, gc_ag_intron_log_prior, at_ac_intron_log_prior,max_boundary_intron_length,9 unmodified linesdef decode_paths_with_numba(tasks,transition_probabilities,stop_taa=True, stop_tag=True, stop_tga=True,gt_ag_intron_log_prior=GT_AG_INTRON_LOG_PRIOR,gc_ag_intron_log_prior=GC_AG_INTRON_LOG_PRIOR,at_ac_intron_log_prior=AT_AC_INTRON_LOG_PRIOR,max_boundary_intron_length=MAX_BOUNDARY_INTRON_LENGTH_BP,):"""Decode ``[(probabilities, encoded_bases), ...]`` with the reference Numba decoder.``transition_probabilities`` holds one ``(bases, 4)`` array per task witheach transition's log-odds against staying, in nats. They are quantized tothe backends' int32 fixed point (``prepare_transition_probabilities``) anddivided by ``FIXED_POINT_SCORE_SCALE`` again, so the reference sees exactlythe values the native backends accumulate."""max_boundary_intron_length = validate_max_boundary_intron_length(max_boundary_intron_length)tasks = prepare_decode_tasks(tasks)transition_probabilities = prepare_transition_probabilities(transition_probabilities, tasks)paths = []for (probabilities, encoded_bases), fixed_point_scores in zip(tasks, transition_probabilities):coding_probabilities = probabilities.astype(np.float64)np.clip(coding_probabilities, MIN_PROB, MAX_PROB, out=coding_probabilities)record_length = coding_probabilities.shape[0]130 unmodified linesreturn "numba"try:module = importlib.import_module(f"viterbi_backends.decode_{backend}")ok, reason = module.available()if ok:return backend4 unmodified linesraise RuntimeError("no Viterbi backend available: " + "; ".join(reasons))def decode_paths(tasks, transition_probabilities, viterbi_backend, **options):"""Run the Viterbi algorithm on ``viterbi_backend`` (``gpu``, ``cpu``, or ``numba``).Every backend takes the arguments of ``decode_paths_with_numba`` andreturns identical state paths."""if viterbi_backend == "numba":return decode_paths_with_numba(tasks, transition_probabilities, **options)module = importlib.import_module(f"viterbi_backends.decode_{viterbi_backend}")return module.decode_paths(tasks, transition_probabilities, **options)21 unmodified lines22232425262728293031323334353637384 unmodified lines43444546474849505152535455565758596061626364656667686970717273747576777879808182838485864 unmodified lines9192939495969710 unmodified lines10810911011111211311411578 unmodified lines19419519619719819920020120220320420520620720833 unmodified lines24224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128242 unmodified lines32532632732832933033124 unmodified lines3563573583593603613623633643653663673683693703713723731 unmodified line37537637737837938038111 unmodified lines3933943953963973983994004014024034041 unmodified line4064074084094104114124134144154164 unmodified lines42142242342442542642742842943067 unmodified lines49849950050150250350450550628 unmodified lines5355365375385395405411 unmodified line54354454554654754854912 unmodified lines56256356456556656756856957057157249 unmodified lines622623624625626627628105 unmodified lines7347357367377387397403 unmodified lines7447457467477487497509 unmodified lines760761762763764765766767768769770771772773774775776777778779780781782783784785130 unmodified lines9169179189199209219224 unmodified lines92792892993093193293393493593693793893921 unmodified linesState design:To recognize stop codons, a state only needs to record which stop prefix,if any, has already been seen inside the current codon. That memory isstored as one of six prefix types. Codon phase here means how many CDSbases, 0, 1, or 2, have been consumed in the current codon:PHASE0 codon phase 0; codon boundary, no open prefixPHASE1_PREFIX_T codon phase 1; one-base prefix TPHASE1_PREFIX_OTHER codon phase 1; one-base prefix otherPHASE2_PREFIX_TA codon phase 2; prefix TA, so A/G completes TAA/TAGPHASE2_PREFIX_TG codon phase 2; prefix TG, so A completes TGAPHASE2_PREFIX_OTHER codon phase 2; other prefix, so no stop can be completedGFF3 phase uses a different convention: it records how many visible basesto skip before the next complete codon, rather than bases already consumed.4 unmodified linesstate table because both exit at AG, but each uses its own intron prior.AT-AC uses a separate state table because it exits at AC.The state ids are defined in utils.py. Exon and intron state names end inthe prefix type the state carries:0 INTERGENIC non-coding outside genes1 START_A A of start codon ATG2 START_AT T of start codon ATG; its G is EXON_PHASE03 EXON_PHASE0 CDS base that completes a codon4 EXON_PHASE1_PREFIX_T first codon base T5 EXON_PHASE1_PREFIX_OTHER first codon base A, C, or G6 EXON_PHASE2_PREFIX_TA second codon base A after T7 EXON_PHASE2_PREFIX_TG second codon base G after T8 EXON_PHASE2_PREFIX_OTHER second codon base; no stop can be completed9 STOP last base of the terminal in-frame stop codon10 GT_GC_AG_INTRON_FIRST_PHASE0 first GT/GC-AG intron base11 GT_GC_AG_INTRON_FIRST_PHASE1_PREFIX_T first GT/GC-AG intron base12 GT_GC_AG_INTRON_FIRST_PHASE1_PREFIX_OTHER first GT/GC-AG intron base13 GT_GC_AG_INTRON_FIRST_PHASE2_PREFIX_TA first GT/GC-AG intron base14 GT_GC_AG_INTRON_FIRST_PHASE2_PREFIX_TG first GT/GC-AG intron base15 GT_GC_AG_INTRON_FIRST_PHASE2_PREFIX_OTHER first GT/GC-AG intron base16 GT_GC_AG_INTRON_READY_PHASE0 later GT/GC-AG intron base17 GT_GC_AG_INTRON_READY_PHASE1_PREFIX_T later GT/GC-AG intron base18 GT_GC_AG_INTRON_READY_PHASE1_PREFIX_OTHER later GT/GC-AG intron base19 GT_GC_AG_INTRON_READY_PHASE2_PREFIX_TA later GT/GC-AG intron base20 GT_GC_AG_INTRON_READY_PHASE2_PREFIX_TG later GT/GC-AG intron base21 GT_GC_AG_INTRON_READY_PHASE2_PREFIX_OTHER later GT/GC-AG intron base22 AT_AC_INTRON_PHASE0 AT-AC intron base23 AT_AC_INTRON_PHASE1_PREFIX_T AT-AC intron base24 AT_AC_INTRON_PHASE1_PREFIX_OTHER AT-AC intron base25 AT_AC_INTRON_PHASE2_PREFIX_TA AT-AC intron base26 AT_AC_INTRON_PHASE2_PREFIX_TG AT-AC intron base27 AT_AC_INTRON_PHASE2_PREFIX_OTHER AT-AC intron base28 LEADING_BOUNDARY_INTRON intron extending from the left record boundary29 TRAILING_BOUNDARY_INTRON intron extending to the right record boundaryTransition rules:INTERGENIC self-loops or starts a start codon ATG. START_A -> START_AT ->EXON_PHASE0. Exons consume coding bases and update prefix type;selected stops enter STOP. STOP exits to INTERGENIC. Exons may enterGT-AG/GC-AG introns at G followed by T/C, or AT-AC introns at A followedby T. GT/GC-AG introns enter FIRST, then must consume one more intron base4 unmodified linesOpening an intron adds the explicit log prior for its splice class. Thesupported frequencies are 0.990 for GT-AG, 0.009 for GC-AG, and 0.001 forAT-AC, each divided by the 0.99 GT-AG baseline before taking the logarithm.The GT-AG prior is therefore exactly zero, but remains an explicitparameter in the Numba, CPU, and CUDA implementations.Except for the two boundary-intron guards described below, a sequence base10 unmodified linesscores at both ends of the intron and still pays the splice-class prior. Ifit wins, the model strongly prefers those bases to be non-coding, while theambiguous sequence provides too little evidence for a reliable repair. The path is retained and its gene is reported asincomplete with reason short_intron instead of expanding the state spacesolely for this rare condition.The transition network's four probabilities enter the score as log-oddsagainst staying, charged on the base where the new segment begins or, for78 unmodified linesMIN_PROB,)from utils import (PHASE0, PHASE1_PREFIX_T, PHASE1_PREFIX_OTHER,PHASE2_PREFIX_TA, PHASE2_PREFIX_TG, PHASE2_PREFIX_OTHER, PREFIX_TYPE_COUNT,STATE_COUNT, INTERGENIC, START_A, START_AT, EXON_PHASE0, STOP,LEADING_BOUNDARY_INTRON, TRAILING_BOUNDARY_INTRON,EXON_STATE_BY_PREFIX_TYPE,GT_GC_AG_INTRON_FIRST_STATE_BY_PREFIX_TYPE,GT_GC_AG_INTRON_READY_STATE_BY_PREFIX_TYPE,AT_AC_INTRON_STATE_BY_PREFIX_TYPE,prepare_decode_tasks, prepare_transition_log_odds,validate_max_boundary_intron_length,)33 unmodified lines@njit(cache=True, inline="always")def next_coding_state_after_base(prefix_type, base, stop_taa, stop_tag, stop_tga):"""Return the exon/STOP state after emitting one coding base."""# PHASE0 means the previous coding base ended a codon. A new T can still# become TAA/TAG/TGA; every other base cannot start a stop codon.if prefix_type == PHASE0:if base == BASE_T:return EXON_STATE_BY_PREFIX_TYPE[PHASE1_PREFIX_T]return EXON_STATE_BY_PREFIX_TYPE[PHASE1_PREFIX_OTHER]# PHASE1_PREFIX_T means the current codon prefix is exactly T.if prefix_type == PHASE1_PREFIX_T:if base == BASE_A:return EXON_STATE_BY_PREFIX_TYPE[PHASE2_PREFIX_TA]if base == BASE_G:return EXON_STATE_BY_PREFIX_TYPE[PHASE2_PREFIX_TG]return EXON_STATE_BY_PREFIX_TYPE[PHASE2_PREFIX_OTHER]# PHASE1_PREFIX_OTHER is a one-base prefix other than T, so the second base# cannot create a possible standard stop prefix.if prefix_type == PHASE1_PREFIX_OTHER:return EXON_STATE_BY_PREFIX_TYPE[PHASE2_PREFIX_OTHER]# PHASE2_PREFIX_TA is TA. A or G completes TAA/TAG if those stops are enabled.if prefix_type == PHASE2_PREFIX_TA:if base == BASE_A and stop_taa:return STOPif base == BASE_G and stop_tag:return STOPreturn EXON_PHASE0# PHASE2_PREFIX_TG is TG. A completes TGA if that stop is enabled.if prefix_type == PHASE2_PREFIX_TG:if base == BASE_A and stop_tga:return STOPreturn EXON_PHASE0return EXON_PHASE0@njit(cache=True, inline="always")42 unmodified lines@njit(cache=True)def initialize_first_base_scores(coding_scores, noncoding_scores, transition_log_odds, bases, record_length,stop_taa, stop_tag, stop_tga, boundary_introns_enabled,current_scores,):24 unmodified lines# observed base and unknown bases to the left of the record boundary. They# remain legal when boundary introns are disabled, allowing a record to# begin inside an exon.current_scores[EXON_STATE_BY_PREFIX_TYPE[PHASE0]] = coding_scorecurrent_scores[EXON_STATE_BY_PREFIX_TYPE[PHASE2_PREFIX_OTHER]] = coding_scoreif base == BASE_N:for prefix_type in range(PREFIX_TYPE_COUNT):current_scores[EXON_STATE_BY_PREFIX_TYPE[prefix_type]] = coding_scoreelse:one_base_prefix_type = PHASE1_PREFIX_T if base == BASE_T else PHASE1_PREFIX_OTHERcurrent_scores[EXON_STATE_BY_PREFIX_TYPE[one_base_prefix_type]] = coding_scoreif base == BASE_A:current_scores[EXON_STATE_BY_PREFIX_TYPE[PHASE2_PREFIX_TA]] = coding_scoreelif base == BASE_G:current_scores[EXON_STATE_BY_PREFIX_TYPE[PHASE2_PREFIX_TG]] = coding_score# The record may begin with the last observed base of a stop codon whose# first two bases lie outside the left boundary.1 unmodified linebase_matches(base, BASE_A) and (stop_taa or stop_tga)) or (base_matches(base, BASE_G) and stop_tag)if can_end_stop:current_scores[STOP] = coding_score + transition_log_odds[0, LEAVE_GENE]if boundary_introns_enabled:# A record that starts inside an intron has no observable preceding11 unmodified linesand third_start_base_matches)if has_atg_start:current_scores[START_A] = coding_score + transition_log_odds[0, ENTER_GENE]@njit(cache=True)def run_viterbi_forward(coding_scores, noncoding_scores, transition_log_odds, bases, record_length,stop_taa, stop_tag, stop_tga,gt_ag_intron_log_prior, gc_ag_intron_log_prior, at_ac_intron_log_prior,max_boundary_intron_length,1 unmodified line):"""Run the source-state Viterbi forward pass and fill backpointers.``transition_log_odds`` is the ``(record_length, 4)`` array of transitionnetwork scores in nats, in ``TRANSITION_NAMES`` column order."""initialize_first_base_scores(coding_scores, noncoding_scores, transition_log_odds, bases, record_length,stop_taa, stop_tag, stop_tga, max_boundary_intron_length != 0,current_scores,)4 unmodified linesbase = bases[position]coding_score = coding_scores[position]noncoding_score = noncoding_scores[position]enter_gene_log_odds = transition_log_odds[position, ENTER_GENE]leave_gene_log_odds = transition_log_odds[position, LEAVE_GENE]enter_intron_log_odds = transition_log_odds[position, ENTER_INTRON]leave_intron_log_odds = transition_log_odds[position, LEAVE_INTRON]# Donor tests look at the current and next base. At the final base the# unavailable next base may complete a donor outside the record.67 unmodified lines))can_enter_trailing_boundary_intron = (has_any_donorand not has_exact_enabled_stop_followed_by_donorand boundary_introns_enabledand (boundary_intron_length_is_unlimitedor record_length - position <= max_boundary_intron_length28 unmodified linesSTOP,)# 3. Start codon ATG consumes T and G, then enters EXON_PHASE0.if current_scores[START_A] != -np.inf:keep_best_transition(next_scores, predecessors, START_AT,1 unmodified line)if current_scores[START_AT] != -np.inf:keep_best_transition(next_scores, predecessors, EXON_PHASE0,current_scores[START_AT] + coding_score,START_AT,)12 unmodified linescurrent_scores[LEADING_BOUNDARY_INTRON] + noncoding_score,LEADING_BOUNDARY_INTRON,)can_exit_leading_boundary_intron = ((has_ag_acceptor or has_ac_acceptor)and not has_exact_acceptor_followed_by_atg)if can_exit_leading_boundary_intron:for prefix_type in range(PREFIX_TYPE_COUNT):emit_coding_base(current_scores, next_scores, predecessors,49 unmodified linesexon_state,)if can_enter_trailing_boundary_intron:if has_gt_ag_donor:keep_best_transition(next_scores, predecessors,105 unmodified lines@njit(cache=True, nogil=True)def decode_one_track(coding_scores, noncoding_scores, transition_log_odds, bases, record_length,stop_taa, stop_tag, stop_tga,gt_ag_intron_log_prior, gc_ag_intron_log_prior, at_ac_intron_log_prior,max_boundary_intron_length,3 unmodified linescurrent_scores = np.empty(STATE_COUNT, np.float64)backpointers = np.empty((record_length, STATE_COUNT), np.int8)run_viterbi_forward(coding_scores, noncoding_scores, transition_log_odds, bases, record_length,stop_taa, stop_tag, stop_tga,gt_ag_intron_log_prior, gc_ag_intron_log_prior, at_ac_intron_log_prior,max_boundary_intron_length,9 unmodified linesdef decode_paths_with_numba(tasks,transition_log_odds,stop_taa=True, stop_tag=True, stop_tga=True,gt_ag_intron_log_prior=GT_AG_INTRON_LOG_PRIOR,gc_ag_intron_log_prior=GC_AG_INTRON_LOG_PRIOR,at_ac_intron_log_prior=AT_AC_INTRON_LOG_PRIOR,max_boundary_intron_length=MAX_BOUNDARY_INTRON_LENGTH_BP,):"""Decode ``[(probabilities, encoded_bases), ...]`` with the Numba reference implementation.``transition_log_odds`` holds one ``(bases, 4)`` int32 array per task witheach transition's log-odds against staying in ``FIXED_POINT_SCORE_SCALE``units (``utils.quantize_transition_log_odds``), the values the nativebackends accumulate. The reference divides them by``FIXED_POINT_SCORE_SCALE`` to work in nats."""max_boundary_intron_length = validate_max_boundary_intron_length(max_boundary_intron_length)tasks = prepare_decode_tasks(tasks)transition_log_odds = prepare_transition_log_odds(transition_log_odds, tasks)paths = []for (probabilities, encoded_bases), fixed_point_scores in zip(tasks, transition_log_odds):coding_probabilities = probabilities.astype(np.float64)np.clip(coding_probabilities, MIN_PROB, MAX_PROB, out=coding_probabilities)record_length = coding_probabilities.shape[0]130 unmodified linesreturn "numba"try:module = importlib.import_module(f"viterbi_backends.viterbi_{backend}")ok, reason = module.available()if ok:return backend4 unmodified linesraise RuntimeError("no Viterbi backend available: " + "; ".join(reasons))def decode_paths(tasks, transition_log_odds, viterbi_backend, **options):"""Run the Viterbi algorithm on ``viterbi_backend`` (``gpu``, ``cpu``, or ``numba``).Every backend takes the arguments of ``decode_paths_with_numba`` andreturns identical state paths."""if viterbi_backend == "numba":return decode_paths_with_numba(tasks, transition_log_odds, **options)module = importlib.import_module(f"viterbi_backends.viterbi_{viterbi_backend}")return module.decode_paths(tasks, transition_log_odds, **options)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167171 unmodified line7197207217227237247251 unmodified line7277287297307317327337347357367377385 unmodified lines7447457467477487497507517527537547557567578 unmodified lines7667677687697707717721 unmodified line7747757767777787797807817827837847857867877887897907917927937947957964 unmodified lines801802803804805806// viterbi_cpu.cpp -- CPU Viterbi backend: C++/OpenMP implementation of the algorithm in viterbi.py.//// This file implements the same 30-state decoder grammar as viterbi.py:// - six exon prefix types for stop-codon detection;// - GT/GC-AG introns enter FIRST, then move to READY before AG exit;// - AT-AC introns use one state table because AT cannot overlap AC;// - Python supplies explicit GT-AG, GC-AG, and AT-AC log priors;// - N freely matches any concrete base in codons and splice signals;// - dedicated leading/trailing states represent introns crossing a record edge;// - the transition network supplies the probabilities of the four permitted// transitions per base (enter gene, leave gene, enter intron, leave// intron) as log-odds in the decoder's fixed-point units;// - stop read-through is disabled.//// Per-base log-probability and transition increments are int32 fixed-point// values from a fp16 log LUT. Accumulated path scores use int64 and are kept// unnormalized, so this implementation does not discard a state just because// it temporarily falls behind the current best state. Long records keep score// checkpoints at reconstruction-batch boundaries, so backpointer memory does// not grow with the complete record length.#include <cstdint>#include <cmath>#include <cstring>#include <stdexcept>#include <vector>#include <omp.h>using AccumulatedScore = int64_t;using StepScore = int32_t;static const double SCORE_SCALE = 16384.0;static inline StepScore score_from_nats(double nats) {return static_cast<StepScore>(std::llround(nats * SCORE_SCALE));}// Fixed-point code uses this sentinel in place of IEEE -inf.static const AccumulatedScore UNREACHABLE_ACCUMULATED_SCORE = -4'000'000'000'000'000'000LL;static const int64_t DEFAULT_RECONSTRUCTION_BATCH_SIZE = 8'000'000;static const int STATE_COUNT = 30;static const int PREFIX_TYPE_COUNT = 6;static const int INTERGENIC = 0;static const int START_A = 1;static const int START_AT = 2;static const int EXON_PREFIX_TYPE_0 = 3;static const int STOP = 9;static const int GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_0 = 10;static const int GT_GC_AG_INTRON_READY_PREFIX_TYPE_0 = 16;static const int AT_AC_INTRON_PREFIX_TYPE_0 = 22;static const int LEADING_BOUNDARY_INTRON = 28;static const int TRAILING_BOUNDARY_INTRON = 29;// State layout matches viterbi.py and viterbi_gpu.cu:// 0 intergenic; 1..2 ATG start; 3..8 exon prefix types; 9 stop;// 10..15 GT/GC-AG FIRST; 16..21 GT/GC-AG READY; 22..27 AT-AC;// 28 leading boundary intron; 29 trailing boundary intron.static const int BASE_A = 0;static const int BASE_T = 1;static const int BASE_C = 2;static const int BASE_G = 3;static const int BASE_N = 4;// Transition probability tracks per base, in the column order of constants.py.// They arrive from Python as log-odds against staying, already quantized to// the decoder's fixed-point units, so they add directly to path scores.static const int ENTER_GENE = 0;static const int LEAVE_GENE = 1;static const int ENTER_INTRON = 2;static const int LEAVE_INTRON = 3;static const int TRANSITION_COUNT = 4;static inline bool is_exon_state(int state) {return state >= EXON_PREFIX_TYPE_0&& state < EXON_PREFIX_TYPE_0 + PREFIX_TYPE_COUNT;}static inline bool is_gt_gc_intron_entry_state(int state) {return state >= GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_0&& state < GT_GC_AG_INTRON_READY_PREFIX_TYPE_0;}static inline bool is_gt_gc_acceptor_state(int state) {return state >= GT_GC_AG_INTRON_READY_PREFIX_TYPE_0&& state < AT_AC_INTRON_PREFIX_TYPE_0;}static inline bool is_at_ac_intron_state(int state) {return state >= AT_AC_INTRON_PREFIX_TYPE_0&& state < LEADING_BOUNDARY_INTRON;}// Transition log-odds of one legal state change. Each value is attached to the// base where the new segment begins: the first start-codon base (enter gene),// the last stop-codon base (leave gene, charged on the base that closes the// gene), the first intron base (enter intron), or the first exon base after an// intron (leave intron). Introns that cross a record edge are entered and left// the same way.static inline StepScore transition_log_odds(int source_state, int target_state, const StepScore* position_transition_probabilities) {if (source_state == INTERGENIC && target_state == START_A) {return position_transition_probabilities[ENTER_GENE];}// Leaving the gene takes precedence when an intron exit completes a stop// codon that was split by the intron.if (target_state == STOP) return position_transition_probabilities[LEAVE_GENE];if (is_exon_state(source_state)&& (is_gt_gc_intron_entry_state(target_state)|| is_at_ac_intron_state(target_state)|| target_state == TRAILING_BOUNDARY_INTRON)) {return position_transition_probabilities[ENTER_INTRON];}if ((is_gt_gc_acceptor_state(source_state)|| is_at_ac_intron_state(source_state)|| source_state == LEADING_BOUNDARY_INTRON)&& is_exon_state(target_state)) {return position_transition_probabilities[LEAVE_INTRON];}return StepScore(0);}static inline bool base_matches(int observed_base, int expected_base) {return observed_base == expected_base || observed_base == BASE_N;}static inline bool is_exact_enabled_stop_codon(int first_base, int second_base, int third_base,bool stop_taa, bool stop_tag, bool stop_tga) {if (first_base != BASE_T) return false;if (second_base == BASE_A) {if (third_base == BASE_A && stop_taa) return true;if (third_base == BASE_G && stop_tag) return true;}return second_base == BASE_G&& third_base == BASE_A&& stop_tga;}static StepScore coding_score_lookup[65536], noncoding_score_lookup[65536];static double half_bits_to_double(uint16_t half_bits) {uint32_t sign = static_cast<uint32_t>(half_bits & 0x8000) << 16;uint32_t exponent = (half_bits >> 10) & 0x1F;uint32_t mantissa = half_bits & 0x3FF;uint32_t float_bits;if (exponent == 0) {if (mantissa == 0) {float_bits = sign;} else {int normalization_shift = -1;do {normalization_shift++;mantissa <<= 1;} while (!(mantissa & 0x400));float_bits = sign| (static_cast<uint32_t>(127 - 15 - normalization_shift) << 23)| ((mantissa & 0x3FF) << 13);}} else if (exponent == 0x1F) {float_bits = sign | 0x7F800000u | (mantissa << 13);} else {float_bits = sign | ((exponent + (127 - 15)) << 23) | (mantissa << 13);}float value;memcpy(&value, &float_bits, sizeof(value));return static_cast<double>(value);}static bool build_log_score_lookup() {for (int index = 0; index < 65536; index++) {double probability = half_bits_to_double(static_cast<uint16_t>(index));if (probability < 1e-6) probability = 1e-6;else if (probability > 1.0 - 1e-6) probability = 1.0 - 1e-6;coding_score_lookup[index] = score_from_nats(log(probability));noncoding_score_lookup[index] = score_from_nats(log(1.0 - probability));}return true;}static inline int exon_state_for_prefix(int prefix_type) {return EXON_PREFIX_TYPE_0 + prefix_type;}static inline int next_coding_state_after_base(int prefix_type, int base,bool stop_taa, bool stop_tag, bool stop_tga) {if (prefix_type == 0) return base == BASE_T ? exon_state_for_prefix(1) : exon_state_for_prefix(2);if (prefix_type == 1) {if (base == BASE_A) return exon_state_for_prefix(3);if (base == BASE_G) return exon_state_for_prefix(4);return exon_state_for_prefix(5);}if (prefix_type == 2) return exon_state_for_prefix(5);if (prefix_type == 3) {if (base == BASE_A && stop_taa) return STOP;if (base == BASE_G && stop_tag) return STOP;return exon_state_for_prefix(0);}if (prefix_type == 4) {if (base == BASE_A && stop_tga) return STOP;return exon_state_for_prefix(0);}return exon_state_for_prefix(0);}static inline void keep_best_transition(AccumulatedScore* next_scores, int8_t* predecessors,int target_state, AccumulatedScore candidate_score, int source_state,const StepScore* position_transition_probabilities) {candidate_score += transition_log_odds(source_state, target_state, position_transition_probabilities);if (candidate_score > next_scores[target_state]) {next_scores[target_state] = candidate_score;predecessors[target_state] = static_cast<int8_t>(source_state);}}static inline void emit_coding_base(const AccumulatedScore* current_scores, AccumulatedScore* next_scores,int8_t* predecessors, int source_state, int prefix_type,StepScore coding_score, const StepScore* position_transition_probabilities, int base,bool stop_taa, bool stop_tag, bool stop_tga) {AccumulatedScore source_score = current_scores[source_state];if (source_score == UNREACHABLE_ACCUMULATED_SCORE) return;AccumulatedScore candidate_score = source_score + coding_score;if (base == BASE_N) {for (int resolved_base = BASE_A; resolved_base <= BASE_G; resolved_base++) {int target_state = next_coding_state_after_base(prefix_type, resolved_base, stop_taa, stop_tag, stop_tga);keep_best_transition(next_scores, predecessors, target_state, candidate_score, source_state,position_transition_probabilities);}} else {int target_state = next_coding_state_after_base(prefix_type, base, stop_taa, stop_tag, stop_tga);keep_best_transition(next_scores, predecessors, target_state, candidate_score, source_state,position_transition_probabilities);}}// Transitions across the left record edge are charged like interior ones: a// start codon beginning at the first base is charged enter_gene[0] and a stop// codon completed there is charged leave_gene[0]; every other first-base state// is charged nothing.static void initialize_first_base_scores(const uint16_t* probability_bits, const StepScore* transition_probabilities,const int8_t* bases, int record_length,bool stop_taa, bool stop_tag, bool stop_tga,bool boundary_introns_enabled, AccumulatedScore* current_scores) {StepScore coding_score = coding_score_lookup[probability_bits[0]];StepScore noncoding_score = noncoding_score_lookup[probability_bits[0]];int base = bases[0];for (int state = 0; state < STATE_COUNT; state++) {current_scores[state] = UNREACHABLE_ACCUMULATED_SCORE;}current_scores[INTERGENIC] = noncoding_score;current_scores[exon_state_for_prefix(0)] = coding_score;current_scores[exon_state_for_prefix(5)] = coding_score;if (base == BASE_N) {for (int prefix_type = 0; prefix_type < PREFIX_TYPE_COUNT; prefix_type++) {current_scores[exon_state_for_prefix(prefix_type)] = coding_score;}} else {int one_base_prefix_type = base == BASE_T ? 1 : 2;current_scores[exon_state_for_prefix(one_base_prefix_type)] = coding_score;if (base == BASE_A) current_scores[exon_state_for_prefix(3)] = coding_score;else if (base == BASE_G) current_scores[exon_state_for_prefix(4)] = coding_score;}if ((base_matches(base, BASE_A) && (stop_taa || stop_tga))|| (base_matches(base, BASE_G) && stop_tag)) {current_scores[STOP] = static_cast<AccumulatedScore>(coding_score)+ transition_probabilities[LEAVE_GENE];}if (boundary_introns_enabled) {current_scores[LEADING_BOUNDARY_INTRON] = noncoding_score;}bool second_start_base_matches = record_length == 1 || base_matches(bases[1], BASE_T);bool third_start_base_matches = record_length <= 2 || base_matches(bases[2], BASE_G);bool has_atg_start = base_matches(base, BASE_A)&& second_start_base_matches&& third_start_base_matches;if (has_atg_start) {current_scores[START_A] = static_cast<AccumulatedScore>(coding_score)+ transition_probabilities[ENTER_GENE];}}static void run_viterbi_forward(const uint16_t* probability_bits, const int8_t* bases,const StepScore* transition_probabilities, int record_length,int segment_start, int segment_end, bool is_record_start,StepScore gt_ag_intron_score, StepScore gc_ag_intron_score, StepScore at_ac_intron_score,int max_boundary_intron_length,bool stop_taa, bool stop_tag, bool stop_tga,int8_t* backpointers, AccumulatedScore* output_scores,const AccumulatedScore* input_scores = nullptr) {AccumulatedScore current_buffer[STATE_COUNT];AccumulatedScore next_buffer[STATE_COUNT];AccumulatedScore* current_scores = current_buffer;AccumulatedScore* next_scores = next_buffer;if (is_record_start) {initialize_first_base_scores(probability_bits, transition_probabilities, bases, record_length,stop_taa, stop_tag, stop_tga,max_boundary_intron_length != 0,current_scores);} else {for (int state = 0; state < STATE_COUNT; state++) {current_scores[state] = input_scores[state];}}for (int position = segment_start + 1; position <= segment_end; position++) {int base = bases[position];StepScore coding_score = coding_score_lookup[probability_bits[position]];StepScore noncoding_score = noncoding_score_lookup[probability_bits[position]];const StepScore* position_transition_probabilities =transition_probabilities + static_cast<size_t>(position) * TRANSITION_COUNT;// Missing motif bases at record edges are unknown. Internal positions// still require the complete start, donor, or acceptor motif.bool next_base_is_missing = position + 1 == record_length;int next_base = next_base_is_missing ? -1 : bases[position + 1];bool has_gt_ag_donor = base_matches(base, BASE_G)&& (next_base_is_missing || base_matches(next_base, BASE_T));bool has_gc_ag_donor = base_matches(base, BASE_G)&& (next_base_is_missing || base_matches(next_base, BASE_C));bool acceptor_first_base_matches = position == 1|| base_matches(bases[position - 2], BASE_A);bool has_ag_acceptor = acceptor_first_base_matches&& base_matches(bases[position - 1], BASE_G);bool has_ac_acceptor = acceptor_first_base_matches&& base_matches(bases[position - 1], BASE_C);bool third_start_base_matches = position + 2 >= record_length|| base_matches(bases[position + 2], BASE_G);bool has_atg_start = base_matches(base, BASE_A)&& (next_base_is_missing || base_matches(next_base, BASE_T))&& third_start_base_matches;// Boundary guards require exact five-base patterns. N and missing// edge context remain valid for ordinary motif matching only.bool has_exact_acceptor_followed_by_atg = position >= 2&& position + 2 < record_length&& bases[position - 2] == BASE_A&& (bases[position - 1] == BASE_G || bases[position - 1] == BASE_C)&& base == BASE_A&& next_base == BASE_T&& bases[position + 2] == BASE_G;bool has_at_ac_donor = base_matches(base, BASE_A)&& (next_base_is_missing || base_matches(next_base, BASE_T));bool has_any_donor = has_gt_ag_donor || has_gc_ag_donor || has_at_ac_donor;bool has_exact_donor = position + 1 < record_length&& ((base == BASE_G && (next_base == BASE_T || next_base == BASE_C))|| (base == BASE_A && next_base == BASE_T));bool has_exact_enabled_stop_followed_by_donor = false;if (has_exact_donor && position >= 3) {has_exact_enabled_stop_followed_by_donor = is_exact_enabled_stop_codon(bases[position - 3], bases[position - 2], bases[position - 1],stop_taa, stop_tag, stop_tga);}// A leading self-loop into position makes its run position + 1 bases.// A trailing entry here emits record_length - position bases through// the right edge, so both limits follow directly from coordinates.bool boundary_introns_enabled = max_boundary_intron_length != 0;bool boundary_intron_length_is_unlimited = max_boundary_intron_length == -1;bool can_extend_leading_boundary_intron =boundary_introns_enabled&& (boundary_intron_length_is_unlimited|| position < max_boundary_intron_length);bool can_enter_trailing_boundary_intron =boundary_introns_enabled&& (boundary_intron_length_is_unlimited|| record_length - position <= max_boundary_intron_length);int8_t local_predecessors[STATE_COUNT];int8_t* predecessors = backpointers? &backpointers[static_cast<size_t>(position - segment_start - 1) * STATE_COUNT]: local_predecessors;for (int state = 0; state < STATE_COUNT; state++) {next_scores[state] = UNREACHABLE_ACCUMULATED_SCORE;predecessors[state] = 0;}// Intergenic, stop, and start-codon transitions.if (current_scores[INTERGENIC] != UNREACHABLE_ACCUMULATED_SCORE) {keep_best_transition(next_scores, predecessors, INTERGENIC,current_scores[INTERGENIC] + noncoding_score, INTERGENIC,position_transition_probabilities);if (has_atg_start) {keep_best_transition(next_scores, predecessors, START_A,current_scores[INTERGENIC] + coding_score,INTERGENIC,position_transition_probabilities);}}if (current_scores[STOP] != UNREACHABLE_ACCUMULATED_SCORE) {keep_best_transition(next_scores, predecessors, INTERGENIC,current_scores[STOP] + noncoding_score, STOP,position_transition_probabilities);}if (current_scores[START_A] != UNREACHABLE_ACCUMULATED_SCORE) {keep_best_transition(next_scores, predecessors, START_AT,current_scores[START_A] + coding_score, START_A,position_transition_probabilities);}if (current_scores[START_AT] != UNREACHABLE_ACCUMULATED_SCORE) {keep_best_transition(next_scores, predecessors, exon_state_for_prefix(0),current_scores[START_AT] + coding_score, START_AT,position_transition_probabilities);}// Every prefix type is allowed when the leading boundary intron exits,// so the state carries none. Only an exact acceptor followed by an// exact ATG activates the guard; N leaves both paths available.if (current_scores[LEADING_BOUNDARY_INTRON] != UNREACHABLE_ACCUMULATED_SCORE) {if (can_extend_leading_boundary_intron) {keep_best_transition(next_scores, predecessors, LEADING_BOUNDARY_INTRON,current_scores[LEADING_BOUNDARY_INTRON] + noncoding_score,LEADING_BOUNDARY_INTRON,position_transition_probabilities);}bool can_exit_leading_intron =(has_ag_acceptor || has_ac_acceptor)&& !has_exact_acceptor_followed_by_atg;if (can_exit_leading_intron) {for (int prefix_type = 0; prefix_type < PREFIX_TYPE_COUNT; prefix_type++) {emit_coding_base(current_scores, next_scores, predecessors,LEADING_BOUNDARY_INTRON, prefix_type,coding_score, position_transition_probabilities,base, stop_taa, stop_tag, stop_tga);}}}// Exons emit coding bases, open an ordinary internal intron, or enter// the trailing state when the intron continues beyond the record.for (int prefix_type = 0; prefix_type < PREFIX_TYPE_COUNT; prefix_type++) {int exon_state = exon_state_for_prefix(prefix_type);AccumulatedScore exon_score = current_scores[exon_state];if (exon_score == UNREACHABLE_ACCUMULATED_SCORE) continue;emit_coding_base(current_scores, next_scores, predecessors,exon_state, prefix_type,coding_score, position_transition_probabilities,base, stop_taa, stop_tag, stop_tga);if (has_gt_ag_donor) {keep_best_transition(next_scores, predecessors,GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_0 + prefix_type,exon_score + noncoding_score + gt_ag_intron_score,exon_state,position_transition_probabilities);}if (has_gc_ag_donor) {keep_best_transition(next_scores, predecessors,GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_0 + prefix_type,exon_score + noncoding_score + gc_ag_intron_score,exon_state,position_transition_probabilities);}if (has_at_ac_donor) {keep_best_transition(next_scores, predecessors, AT_AC_INTRON_PREFIX_TYPE_0 + prefix_type,exon_score + noncoding_score + at_ac_intron_score,exon_state,position_transition_probabilities);}if (has_any_donor&& !has_exact_enabled_stop_followed_by_donor&& can_enter_trailing_boundary_intron) {if (has_gt_ag_donor) {keep_best_transition(next_scores, predecessors, TRAILING_BOUNDARY_INTRON,exon_score + noncoding_score + gt_ag_intron_score,exon_state,position_transition_probabilities);}if (has_gc_ag_donor) {keep_best_transition(next_scores, predecessors, TRAILING_BOUNDARY_INTRON,exon_score + noncoding_score + gc_ag_intron_score,exon_state,position_transition_probabilities);}if (has_at_ac_donor) {keep_best_transition(next_scores, predecessors, TRAILING_BOUNDARY_INTRON,exon_score + noncoding_score + at_ac_intron_score,exon_state,position_transition_probabilities);}}}// FIRST consumes one additional base before AG exit is legal.for (int prefix_type = 0; prefix_type < PREFIX_TYPE_COUNT; prefix_type++) {int intron_state = GT_GC_AG_INTRON_FIRST_PREFIX_TYPE_0 + prefix_type;if (current_scores[intron_state] == UNREACHABLE_ACCUMULATED_SCORE) continue;keep_best_transition(next_scores, predecessors,GT_GC_AG_INTRON_READY_PREFIX_TYPE_0 + prefix_type,current_scores[intron_state] + noncoding_score, intron_state,position_transition_probabilities);}// READY self-loops or exits a GT/GC-AG intron after AG.for (int prefix_type = 0; prefix_type < PREFIX_TYPE_COUNT; prefix_type++) {int intron_state = GT_GC_AG_INTRON_READY_PREFIX_TYPE_0 + prefix_type;if (current_scores[intron_state] == UNREACHABLE_ACCUMULATED_SCORE) continue;keep_best_transition(next_scores, predecessors, intron_state,current_scores[intron_state] + noncoding_score, intron_state,position_transition_probabilities);if (has_ag_acceptor) {emit_coding_base(current_scores, next_scores, predecessors,intron_state, prefix_type,coding_score, position_transition_probabilities,base, stop_taa, stop_tag, stop_tga);}}// AT-AC introns self-loop or exit after AC.for (int prefix_type = 0; prefix_type < PREFIX_TYPE_COUNT; prefix_type++) {int intron_state = AT_AC_INTRON_PREFIX_TYPE_0 + prefix_type;if (current_scores[intron_state] == UNREACHABLE_ACCUMULATED_SCORE) continue;keep_best_transition(next_scores, predecessors, intron_state,current_scores[intron_state] + noncoding_score, intron_state,position_transition_probabilities);if (has_ac_acceptor) {emit_coding_base(current_scores, next_scores, predecessors,intron_state, prefix_type,coding_score, position_transition_probabilities,base, stop_taa, stop_tag, stop_tga);}}// A trailing boundary intron cannot return to an exon.if (current_scores[TRAILING_BOUNDARY_INTRON] != UNREACHABLE_ACCUMULATED_SCORE) {keep_best_transition(next_scores, predecessors, TRAILING_BOUNDARY_INTRON,current_scores[TRAILING_BOUNDARY_INTRON] + noncoding_score,TRAILING_BOUNDARY_INTRON,position_transition_probabilities);}AccumulatedScore* previous_scores = current_scores;current_scores = next_scores;next_scores = previous_scores;}if (output_scores) {for (int state = 0; state < STATE_COUNT; state++) {output_scores[state] = current_scores[state];}}}static int best_final_state(const AccumulatedScore* current_scores) {int best_state = INTERGENIC;for (int state = START_A; state <= STOP; state++) {if (current_scores[state] > current_scores[best_state]) best_state = state;}if (current_scores[TRAILING_BOUNDARY_INTRON] > current_scores[best_state]) {best_state = TRAILING_BOUNDARY_INTRON;}return best_state;}static void decode_one_track(const uint16_t* probability_bits, const int8_t* bases,const StepScore* transition_probabilities, int record_length,StepScore gt_ag_intron_score, StepScore gc_ag_intron_score, StepScore at_ac_intron_score,int max_boundary_intron_length,bool stop_taa, bool stop_tag, bool stop_tga,int64_t reconstruction_batch_size, int8_t* path,std::vector<int8_t>& backpointer_buffer,std::vector<AccumulatedScore>& checkpoints) {if (record_length <= 0) return;if (static_cast<int64_t>(record_length) <= reconstruction_batch_size) {backpointer_buffer.assign(static_cast<size_t>(record_length) * STATE_COUNT, 0);AccumulatedScore final_scores[STATE_COUNT];run_viterbi_forward(probability_bits, bases, transition_probabilities, record_length, 0, record_length - 1, true,gt_ag_intron_score, gc_ag_intron_score, at_ac_intron_score,max_boundary_intron_length,stop_taa, stop_tag, stop_tga,backpointer_buffer.data(), final_scores);int state = best_final_state(final_scores);for (int64_t position = record_length - 1; position >= 1; position--) {path[position] = static_cast<int8_t>(state);state = static_cast<int>(backpointer_buffer[static_cast<size_t>(position - 1) * STATE_COUNT + state]);}path[0] = static_cast<int8_t>(state);return;}int64_t window_count = (record_length - 1 + reconstruction_batch_size - 1) / reconstruction_batch_size;if (window_count < 1) window_count = 1;checkpoints.assign(static_cast<size_t>(window_count + 1) * STATE_COUNT, 0);// First pass keeps only the score vector at each window boundary.AccumulatedScore current_scores[STATE_COUNT];initialize_first_base_scores(probability_bits, transition_probabilities, bases, record_length,stop_taa, stop_tag, stop_tga,max_boundary_intron_length != 0,current_scores);for (int64_t window = 0; window < window_count; window++) {for (int state = 0; state < STATE_COUNT; state++) {checkpoints[static_cast<size_t>(window) * STATE_COUNT + state] =current_scores[state];}int64_t segment_start = window * reconstruction_batch_size;int64_t segment_end = segment_start + reconstruction_batch_size;if (segment_end > record_length - 1) segment_end = record_length - 1;run_viterbi_forward(probability_bits, bases, transition_probabilities, record_length,static_cast<int>(segment_start), static_cast<int>(segment_end), window == 0,gt_ag_intron_score, gc_ag_intron_score, at_ac_intron_score,max_boundary_intron_length,stop_taa, stop_tag, stop_tga,nullptr, current_scores, current_scores);}for (int state = 0; state < STATE_COUNT; state++) {checkpoints[static_cast<size_t>(window_count) * STATE_COUNT + state] =current_scores[state];}int state = best_final_state(current_scores);backpointer_buffer.assign(static_cast<size_t>(reconstruction_batch_size) * STATE_COUNT, 0);// Recompute one window at a time and immediately backtrace it.for (int64_t window = window_count - 1; window >= 0; window--) {int64_t segment_start = window * reconstruction_batch_size;int64_t segment_end = segment_start + reconstruction_batch_size;if (segment_end > record_length - 1) segment_end = record_length - 1;run_viterbi_forward(probability_bits, bases, transition_probabilities, record_length,static_cast<int>(segment_start), static_cast<int>(segment_end), window == 0,gt_ag_intron_score, gc_ag_intron_score, at_ac_intron_score,max_boundary_intron_length,stop_taa, stop_tag, stop_tga,backpointer_buffer.data(), nullptr,&checkpoints[static_cast<size_t>(window) * STATE_COUNT]);for (int64_t position = segment_end; position >= segment_start + 1; position--) {path[position] = static_cast<int8_t>(state);state = static_cast<int>(backpointer_buffer[static_cast<size_t>(position - segment_start - 1) * STATE_COUNT + state]);}}path[0] = static_cast<int8_t>(state);1 unmodified lineextern "C" void decode_batch_on_cpu(const uint16_t* probability_bits, const int8_t* bases,const StepScore* transition_probabilities,const int64_t* record_offsets, int record_count,int stop_taa, int stop_tag, int stop_tga,double gt_ag_intron_log_prior, double gc_ag_intron_log_prior,1 unmodified lineint max_boundary_intron_length,int64_t requested_reconstruction_batch_size, int8_t* output_paths) {static const bool score_lookup_ready = build_log_score_lookup();(void)score_lookup_ready;const StepScore gt_ag_intron_score = score_from_nats(gt_ag_intron_log_prior);const StepScore gc_ag_intron_score = score_from_nats(gc_ag_intron_log_prior);const StepScore at_ac_intron_score = score_from_nats(at_ac_intron_log_prior);int64_t reconstruction_batch_size = requested_reconstruction_batch_size == 0? DEFAULT_RECONSTRUCTION_BATCH_SIZE: requested_reconstruction_batch_size;5 unmodified lines#pragma omp for schedule(dynamic, 1)for (int record = 0; record < record_count; record++) {int64_t offset = record_offsets[record];int record_length = static_cast<int>(record_offsets[record + 1] - offset);decode_one_track(probability_bits + offset, bases + offset,transition_probabilities + static_cast<size_t>(offset) * TRANSITION_COUNT,record_length,gt_ag_intron_score, gc_ag_intron_score, at_ac_intron_score,max_boundary_intron_length,stop_taa != 0, stop_tag != 0, stop_tga != 0,reconstruction_batch_size, output_paths + offset,backpointer_buffer, checkpoints);8 unmodified linesstatic py::array_t<int8_t> decode_packed_paths(py::array_t<unsigned short> probability_array, py::array_t<int8_t> encoded_bases,py::array_t<StepScore> transition_probabilities,py::array_t<int64_t> record_offsets_array,int stop_taa, int stop_tag, int stop_tga,double gt_ag_intron_log_prior, double gc_ag_intron_log_prior,1 unmodified lineint max_boundary_intron_length,int64_t reconstruction_batch_size) {if (transition_probabilities.size() != encoded_bases.size() * TRANSITION_COUNT) {throw std::invalid_argument("transition probabilities must contain four values per encoded base");}int record_count = static_cast<int>(record_offsets_array.size()) - 1;auto state_paths = py::array_t<int8_t>(encoded_bases.size());const uint16_t* probability_bits = probability_array.data();const int8_t* base_data = encoded_bases.data();const StepScore* transition_probability_data = transition_probabilities.data();const int64_t* record_offsets = record_offsets_array.data();int8_t* output_paths = state_paths.mutable_data();{// Let the Python reader prepare the next input chunk during CPU work.py::gil_scoped_release release;decode_batch_on_cpu(probability_bits, base_data, transition_probability_data, record_offsets, record_count,stop_taa, stop_tag, stop_tga,gt_ag_intron_log_prior, gc_ag_intron_log_prior, at_ac_intron_log_prior,max_boundary_intron_length,4 unmodified lines}PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {m.def("decode", &decode_packed_paths, "Decode a batch with the 30-state CDS decoder");}#endif1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511 unmodified line1531541551561571581591 unmodified line1611621631641651661671681691701711721731741751761771781795 unmodified lines1851861871881891901911921931941958 unmodified lines2042052062072082092101 unmodified line2122132142152162172182192202212222232242252262272282292302312322332342354 unmodified lines240241242243244245// viterbi_cpu.cpp -- CPU Viterbi backend (C++/OpenMP).//// The grammar comes from viterbi_grammar.h. OpenMP threads decode records in// parallel, one record per thread at a time. For each base the recursion asks// best_transition_to_state for all 30 targets; path scores are int64 and are// never renormalized, so no state is dropped for falling behind the best one.//// A record is decoded in windows of reconstruction_batch_size bases, in two// passes. The forward pass runs the recursion over the whole record, keeps the// 30 path scores at the first base of every window, and records backpointers// in the last window only. The backward pass visits the windows from last to// first: it reruns the recursion over every window but the last from the// window's scores, recording backpointers, and traces the path through the// window from the state chosen at its right end. Backpointer memory is one// window whatever the record length, and a record of one window takes one// pass.#include <algorithm>#include <cstdint>#include <stdexcept>#include <utility>#include <vector>#include "viterbi_grammar.h"static const int64_t DEFAULT_RECONSTRUCTION_BATCH_SIZE = 8'000'000;static StepScore coding_score_table[EMISSION_TABLE_SIZE];static StepScore noncoding_score_table[EMISSION_TABLE_SIZE];// The 30 path scores at base 0 of a record.static void initialize_first_base_scores(const uint16_t* probability_bits, const int8_t* bases,const StepScore* transition_log_odds, int64_t record_length,const ViterbiConfig& config, AccumulatedScore* current_scores) {StepScore coding_score = coding_score_table[probability_bits[0]];StepScore noncoding_score = noncoding_score_table[probability_bits[0]];for (int state = 0; state < STATE_COUNT; state++) {current_scores[state] = first_base_score<AccumulatedScore>(state, bases, 0, record_length, coding_score, noncoding_score,transition_log_odds, config);}}// Runs the recursion from base start to base end of a record. scores holds// the 30 path scores at start on entry and those at end on return. With// backpointers, row p - start - 1 receives the best predecessor of every state// at base p.static void run_viterbi_forward(const uint16_t* probability_bits, const int8_t* bases,const StepScore* transition_log_odds, int64_t record_length,int64_t start, int64_t end, const ViterbiConfig& config,AccumulatedScore* scores, int8_t* backpointers) {AccumulatedScore current_buffer[STATE_COUNT];AccumulatedScore next_buffer[STATE_COUNT];AccumulatedScore* current_scores = current_buffer;AccumulatedScore* next_scores = next_buffer;std::copy(scores, scores + STATE_COUNT, current_scores);for (int64_t position = start + 1; position <= end; position++) {PositionSignals signals = compute_position_signals(bases, 0, record_length, position,coding_score_table[probability_bits[position]],noncoding_score_table[probability_bits[position]],transition_log_odds + position * TRANSITION_COUNT,config);int8_t* predecessors = backpointers? &backpointers[static_cast<size_t>(position - start - 1) * STATE_COUNT]: nullptr;#if defined(__GNUC__)#pragma GCC unroll 30#endiffor (int target_state = 0; target_state < STATE_COUNT; target_state++) {TransitionChoice<AccumulatedScore> best = best_transition_to_state(target_state, current_scores, signals, config);next_scores[target_state] = best.score;if (predecessors) predecessors[target_state] = static_cast<int8_t>(best.source_state);}std::swap(current_scores, next_scores);}std::copy(current_scores, current_scores + STATE_COUNT, scores);}static void decode_one_track(const uint16_t* probability_bits, const int8_t* bases,const StepScore* transition_log_odds, int64_t record_length,const ViterbiConfig& config,int64_t reconstruction_batch_size, int8_t* path,std::vector<int8_t>& backpointer_buffer,std::vector<AccumulatedScore>& checkpoints) {if (record_length <= 0) return;// Window w runs the recursion from base w * reconstruction_batch_size to// the first base of window w + 1, or to the record's last base.const int64_t last_base = record_length - 1;int64_t window_count = (last_base + reconstruction_batch_size - 1) / reconstruction_batch_size;if (window_count < 1) window_count = 1;auto window_start = [&](int64_t window) { return window * reconstruction_batch_size; };auto window_end = [&](int64_t window) {return std::min(window_start(window) + reconstruction_batch_size, last_base);};checkpoints.resize(static_cast<size_t>(window_count) * STATE_COUNT);backpointer_buffer.resize(static_cast<size_t>(std::min(reconstruction_batch_size, last_base)) * STATE_COUNT);// Forward pass.AccumulatedScore scores[STATE_COUNT];initialize_first_base_scores(probability_bits, bases, transition_log_odds, record_length, config, scores);for (int64_t window = 0; window < window_count; window++) {std::copy(scores, scores + STATE_COUNT, &checkpoints[static_cast<size_t>(window) * STATE_COUNT]);const bool is_last_window = window == window_count - 1;run_viterbi_forward(probability_bits, bases, transition_log_odds, record_length,window_start(window), window_end(window), config,scores, is_last_window ? backpointer_buffer.data() : nullptr);}// Backward pass.int state = best_final_state(scores);for (int64_t window = window_count - 1; window >= 0; window--) {const int64_t start = window_start(window);const int64_t end = window_end(window);if (window < window_count - 1) {std::copy(&checkpoints[static_cast<size_t>(window) * STATE_COUNT],&checkpoints[static_cast<size_t>(window + 1) * STATE_COUNT], scores);run_viterbi_forward(probability_bits, bases, transition_log_odds, record_length,start, end, config, scores, backpointer_buffer.data());}for (int64_t position = end; position > start; position--) {path[position] = static_cast<int8_t>(state);state = static_cast<int>(backpointer_buffer[static_cast<size_t>(position - start - 1) * STATE_COUNT + state]);}}path[0] = static_cast<int8_t>(state);1 unmodified lineextern "C" void decode_batch_on_cpu(const uint16_t* probability_bits, const int8_t* bases,const StepScore* transition_log_odds,const int64_t* record_offsets, int record_count,int stop_taa, int stop_tag, int stop_tga,double gt_ag_intron_log_prior, double gc_ag_intron_log_prior,1 unmodified lineint max_boundary_intron_length,int64_t requested_reconstruction_batch_size, int8_t* output_paths) {static const bool emission_tables_ready = [] {build_emission_score_tables(coding_score_table, noncoding_score_table);return true;}();(void)emission_tables_ready;const ViterbiConfig config = {stop_taa != 0, stop_tag != 0, stop_tga != 0,score_from_nats(gt_ag_intron_log_prior),score_from_nats(gc_ag_intron_log_prior),score_from_nats(at_ac_intron_log_prior),max_boundary_intron_length,};int64_t reconstruction_batch_size = requested_reconstruction_batch_size == 0? DEFAULT_RECONSTRUCTION_BATCH_SIZE: requested_reconstruction_batch_size;5 unmodified lines#pragma omp for schedule(dynamic, 1)for (int record = 0; record < record_count; record++) {int64_t offset = record_offsets[record];int64_t record_length = record_offsets[record + 1] - offset;decode_one_track(probability_bits + offset, bases + offset,transition_log_odds + static_cast<size_t>(offset) * TRANSITION_COUNT,record_length, config,reconstruction_batch_size, output_paths + offset,backpointer_buffer, checkpoints);8 unmodified linesstatic py::array_t<int8_t> decode_packed_paths(py::array_t<unsigned short> probability_array, py::array_t<int8_t> encoded_bases,py::array_t<StepScore> transition_log_odds,py::array_t<int64_t> record_offsets_array,int stop_taa, int stop_tag, int stop_tga,double gt_ag_intron_log_prior, double gc_ag_intron_log_prior,1 unmodified lineint max_boundary_intron_length,int64_t reconstruction_batch_size) {if (transition_log_odds.size() != encoded_bases.size() * TRANSITION_COUNT) {throw std::invalid_argument("transition log-odds must contain four values per encoded base");}int record_count = static_cast<int>(record_offsets_array.size()) - 1;auto state_paths = py::array_t<int8_t>(encoded_bases.size());const uint16_t* probability_bits = probability_array.data();const int8_t* base_data = encoded_bases.data();const StepScore* transition_log_odds_data = transition_log_odds.data();const int64_t* record_offsets = record_offsets_array.data();int8_t* output_paths = state_paths.mutable_data();{// The batch is decoded without the GIL, so the Python reader can prepare// the next input chunk meanwhile.py::gil_scoped_release release;decode_batch_on_cpu(probability_bits, base_data, transition_log_odds_data, record_offsets, record_count,stop_taa, stop_tag, stop_tga,gt_ag_intron_log_prior, gc_ag_intron_log_prior, at_ac_intron_log_prior,max_boundary_intron_length,4 unmodified lines}PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {m.def("decode", &decode_packed_paths, "Run Viterbi on a batch of tracks");}#endif
2 unmodified lines3456789101112138 unmodified lines222324252627282932 unmodified lines626364656667683 unmodified lines727374757677787980818283848586878889909192939495969798991001011021031041 unmodified line1061071081091101111122 unmodified linesThe C++ extension is JIT-compiled by torch.utils.cpp_extension.load on firstuse and cached under ~/.cache/torch_extensions. Tasks are``(P(CDS), encoded_bases)`` pairs; every task is accompanied by a``(bases, 4)`` array holding the transition network's log-odds against stayingfor the four permitted transitions, in nats, quantized here to the kernel'sint32 fixed point (``prepare_transition_probabilities``). Stopcodons, all three intron-class priors, and the boundary-intron length limitare explicit across every Viterbi backend."""import osimport sys8 unmodified linesMAX_BOUNDARY_INTRON_LENGTH_BP,)from utils import (prepare_decode_tasks,prepare_transition_probabilities,validate_max_boundary_intron_length,validate_reconstruction_batch_size,)32 unmodified linesdef decode_paths(tasks,transition_probabilities,stop_taa=True, stop_tag=True, stop_tga=True,gt_ag_intron_log_prior=GT_AG_INTRON_LOG_PRIOR,gc_ag_intron_log_prior=GC_AG_INTRON_LOG_PRIOR,3 unmodified lines):"""Decode probability/base tasks with the CPU Viterbi backend.``transition_probabilities`` holds one ``(bases, 4)`` array per task ofnat-valued log-odds in ``TRANSITION_NAMES`` column order.``reconstruction_batch_size`` is the number of bases processed togetherduring final path reconstruction. ``None`` uses the backend default."""max_boundary_intron_length = validate_max_boundary_intron_length(max_boundary_intron_length)reconstruction_batch_size = validate_reconstruction_batch_size(reconstruction_batch_size)tasks = prepare_decode_tasks(tasks)transition_probabilities = prepare_transition_probabilities(transition_probabilities, tasks)if not tasks:return []module = _load()record_offsets = np.zeros(len(tasks) + 1, np.int64)for index, (_, encoded_bases) in enumerate(tasks):record_offsets[index + 1] = record_offsets[index] + len(encoded_bases)probability_bits = np.ascontiguousarray(np.concatenate([np.asarray(probabilities, np.float16) for probabilities, _ in tasks])).view(np.uint16)encoded_bases = np.ascontiguousarray(np.concatenate([np.asarray(bases, np.int8) for _, bases in tasks]),dtype=np.int8,)packed_transition_probabilities = np.ascontiguousarray(np.concatenate(transition_probabilities), dtype=np.int32)combined_path = np.asarray(module.decode(probability_bits, encoded_bases, packed_transition_probabilities, record_offsets,int(stop_taa), int(stop_tag), int(stop_tga),float(gt_ag_intron_log_prior), float(gc_ag_intron_log_prior),float(at_ac_intron_log_prior),1 unmodified line0 if reconstruction_batch_size is None else reconstruction_batch_size,))return [combined_path[int(record_offsets[index]):int(record_offsets[index + 1])]for index in range(len(tasks))]2 unmodified lines3456789101112138 unmodified lines22232425262728293032 unmodified lines636465666768693 unmodified lines7374757677787980818283848586878889909192939495961 unmodified line98991001012 unmodified linesThe C++ extension is JIT-compiled by torch.utils.cpp_extension.load on firstuse and cached under ~/.cache/torch_extensions. Tasks are``(P(CDS), encoded_bases)`` pairs; every task is accompanied by a``(bases, 4)`` int32 array holding the transition network's log-odds againststaying for the four permitted transitions, in the kernel's fixed-point units(``utils.quantize_transition_log_odds``). Stop codons, all three intron-classpriors, and the boundary-intron length limit are explicit across everyViterbi backend."""import osimport sys8 unmodified linesMAX_BOUNDARY_INTRON_LENGTH_BP,)from utils import (pack_decode_tasks,prepare_decode_tasks,prepare_transition_log_odds,validate_max_boundary_intron_length,validate_reconstruction_batch_size,)32 unmodified linesdef decode_paths(tasks,transition_log_odds,stop_taa=True, stop_tag=True, stop_tga=True,gt_ag_intron_log_prior=GT_AG_INTRON_LOG_PRIOR,gc_ag_intron_log_prior=GC_AG_INTRON_LOG_PRIOR,3 unmodified lines):"""Decode probability/base tasks with the CPU Viterbi backend.``transition_log_odds`` holds one ``(bases, 4)`` int32 array per task offixed-point log-odds in ``TRANSITION_NAMES`` column order.``reconstruction_batch_size`` is the number of bases processed togetherduring final path reconstruction. ``None`` uses the backend default."""max_boundary_intron_length = validate_max_boundary_intron_length(max_boundary_intron_length)reconstruction_batch_size = validate_reconstruction_batch_size(reconstruction_batch_size)tasks = prepare_decode_tasks(tasks)transition_log_odds = prepare_transition_log_odds(transition_log_odds, tasks)if not tasks:return []module = _load()probability_bits, encoded_bases, transition_scores, record_offsets = pack_decode_tasks(tasks, transition_log_odds)combined_path = np.asarray(module.decode(probability_bits, encoded_bases, transition_scores, record_offsets,int(stop_taa), int(stop_tag), int(stop_tga),float(gt_ag_intron_log_prior), float(gc_ag_intron_log_prior),float(at_ac_intron_log_prior),1 unmodified line0 if reconstruction_batch_size is None else reconstruction_batch_size,))return np.split(combined_path, record_offsets[1:-1])
1 unmodified line23456789101112131415164 unmodified lines21222324252627282930313233343536373828 unmodified lines6768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361373 unmodified lines1411421431441451461471481491501511521531541551561571581591601611621631641651661671 unmodified lineThe CUDA extension is JIT-compiled by torch.utils.cpp_extension.load on firstuse. Tasks are ``(P(CDS), encoded_bases)`` pairs; every task is accompanied bya ``(bases, 4)`` array holding the transition network's log-odds againststaying for the four permitted transitions, in nats, quantized here to thekernel's int32 fixed point (``prepare_transition_probabilities``). Stopcodons, all three intron-class priors, and the boundary-intron length limitare explicit across every Viterbi backend.decode_paths packs tasks into sub-batches sized by available VRAM. The kernelwindows the backpointer array internally, so a single long chromosome can bedecoded without materializing a genome-sized backpointer buffer."""import osimport sys4 unmodified linesfrom constants import (AT_AC_INTRON_LOG_PRIOR,GC_AG_INTRON_LOG_PRIOR,GPU_ESTIMATED_BYTES_PER_BASE,GPU_MAX_BATCH_BASES,GPU_MEMORY_FRACTION,GPU_MIN_BATCH_BASES,GPU_SEGMENT_LENGTH,GT_AG_INTRON_LOG_PRIOR,MAX_BOUNDARY_INTRON_LENGTH_BP,)from utils import (prepare_decode_tasks,prepare_transition_probabilities,validate_max_boundary_intron_length,validate_reconstruction_batch_size,)28 unmodified linesreturn False, f"{type(exc).__name__}: {exc}"def batch_base_budget(free_bytes):"""Return a VRAM-based sub-batch size that also fits CUDA int32 indexing."""memory_budget = max(GPU_MIN_BATCH_BASES,int(free_bytes * GPU_MEMORY_FRACTION / GPU_ESTIMATED_BYTES_PER_BASE),)return min(memory_budget, GPU_MAX_BATCH_BASES)def _decode_batch(module, tasks, transition_probabilities, reconstruction_batch_size):"""Pack and decode one GPU sub-batch."""record_offsets = np.zeros(len(tasks) + 1, np.int64)for index, (_, encoded_bases) in enumerate(tasks):record_offsets[index + 1] = record_offsets[index] + len(encoded_bases)probability_bits = np.ascontiguousarray(np.concatenate([np.asarray(probabilities, np.float16) for probabilities, _ in tasks])).view(np.uint16)encoded_bases = np.ascontiguousarray(np.concatenate([np.asarray(bases, np.int8) for _, bases in tasks]),dtype=np.int8,)packed_transition_probabilities = np.ascontiguousarray(np.concatenate(transition_probabilities), dtype=np.int32)combined_path = np.asarray(module.decode(probability_bits, encoded_bases, packed_transition_probabilities, record_offsets,GPU_SEGMENT_LENGTH,0 if reconstruction_batch_size is None else reconstruction_batch_size,))return [combined_path[int(record_offsets[index]):int(record_offsets[index + 1])]for index in range(len(tasks))]def decode_paths(tasks,transition_probabilities,stop_taa=True, stop_tag=True, stop_tga=True,gt_ag_intron_log_prior=GT_AG_INTRON_LOG_PRIOR,gc_ag_intron_log_prior=GC_AG_INTRON_LOG_PRIOR,at_ac_intron_log_prior=AT_AC_INTRON_LOG_PRIOR,max_boundary_intron_length=MAX_BOUNDARY_INTRON_LENGTH_BP,reconstruction_batch_size=None,):"""Decode probability/base tasks with the GPU Viterbi backend.``transition_probabilities`` holds one ``(bases, 4)`` array per task ofnat-valued log-odds in ``TRANSITION_NAMES`` column order.``reconstruction_batch_size`` is the number of bases processed togetherduring final path reconstruction. ``None`` lets CUDA size it from VRAM."""max_boundary_intron_length = validate_max_boundary_intron_length(max_boundary_intron_length)reconstruction_batch_size = validate_reconstruction_batch_size(reconstruction_batch_size)tasks = prepare_decode_tasks(tasks)transition_probabilities = prepare_transition_probabilities(transition_probabilities, tasks)if not tasks:return []for _, encoded_bases in tasks:if len(encoded_bases) > GPU_MAX_BATCH_BASES:raise ValueError(f"one GPU Viterbi backend record has {len(encoded_bases)} bases; "f"the maximum supported length is {GPU_MAX_BATCH_BASES}")import torchmodule = _load()3 unmodified linesfloat(at_ac_intron_log_prior),int(max_boundary_intron_length),)free_bytes = torch.cuda.mem_get_info()[0]base_budget = batch_base_budget(free_bytes)decoded_paths = []batch_start = 0while batch_start < len(tasks):batch_end = batch_startbatch_bases = 0while batch_end < len(tasks):next_record_bases = len(tasks[batch_end][1])if batch_end > batch_start and batch_bases + next_record_bases > base_budget:breakbatch_bases += next_record_basesbatch_end += 1decoded_paths.extend(_decode_batch(module, tasks[batch_start:batch_end],transition_probabilities[batch_start:batch_end], reconstruction_batch_size,))batch_start = batch_endreturn decoded_paths1 unmodified line2345678910111213141516174 unmodified lines22232425262728293031323334353637383928 unmodified lines68697071727374757677787980818283848586878889909192939495969798991003 unmodified lines1041051061071081091101111121131141151161171181191201211221231 unmodified lineThe CUDA extension is JIT-compiled by torch.utils.cpp_extension.load on firstuse. Tasks are ``(P(CDS), encoded_bases)`` pairs; every task is accompanied bya ``(bases, 4)`` int32 array holding the transition network's log-odds againststaying for the four permitted transitions, in the kernel's fixed-point units(``utils.quantize_transition_log_odds``). Stop codons, all three intron-classpriors, and the boundary-intron length limit are explicit across everyViterbi backend.decode_paths decodes all tasks in one call. The CUDA code keeps its devicememory within a budget, by default GPU_MEMORY_FRACTION of the free devicememory, by decoding the batch in windows (viterbi_gpu.cu), so records of anylength fit."""import osimport sys4 unmodified linesfrom constants import (AT_AC_INTRON_LOG_PRIOR,GC_AG_INTRON_LOG_PRIOR,GPU_MEMORY_FRACTION,GPU_SEGMENT_GROUP_LENGTH,GPU_SEGMENT_LENGTH,GT_AG_INTRON_LOG_PRIOR,MAX_BOUNDARY_INTRON_LENGTH_BP,)from utils import (pack_decode_tasks,prepare_decode_tasks,prepare_transition_log_odds,validate_max_boundary_intron_length,validate_memory_budget_bytes,validate_reconstruction_batch_size,)28 unmodified linesreturn False, f"{type(exc).__name__}: {exc}"def decode_paths(tasks,transition_log_odds,stop_taa=True, stop_tag=True, stop_tga=True,gt_ag_intron_log_prior=GT_AG_INTRON_LOG_PRIOR,gc_ag_intron_log_prior=GC_AG_INTRON_LOG_PRIOR,at_ac_intron_log_prior=AT_AC_INTRON_LOG_PRIOR,max_boundary_intron_length=MAX_BOUNDARY_INTRON_LENGTH_BP,reconstruction_batch_size=None,memory_budget_bytes=None,):"""Decode probability/base tasks with the GPU Viterbi backend.``transition_log_odds`` holds one ``(bases, 4)`` int32 array per task offixed-point log-odds in ``TRANSITION_NAMES`` column order.``reconstruction_batch_size`` is the number of bases whose backpointersare held at once during path reconstruction; ``None`` sizes it from thememory budget. ``memory_budget_bytes`` bounds the device memory of thecall; ``None`` takes ``GPU_MEMORY_FRACTION`` of the free device memory."""max_boundary_intron_length = validate_max_boundary_intron_length(max_boundary_intron_length)reconstruction_batch_size = validate_reconstruction_batch_size(reconstruction_batch_size)memory_budget_bytes = validate_memory_budget_bytes(memory_budget_bytes)tasks = prepare_decode_tasks(tasks)transition_log_odds = prepare_transition_log_odds(transition_log_odds, tasks)if not tasks:return []import torchmodule = _load()3 unmodified linesfloat(at_ac_intron_log_prior),int(max_boundary_intron_length),)if memory_budget_bytes is None:# Memory that torch has cached but does not use counts as free.torch.cuda.empty_cache()memory_budget_bytes = int(torch.cuda.mem_get_info()[0] * GPU_MEMORY_FRACTION)probability_bits, encoded_bases, transition_scores, record_offsets = pack_decode_tasks(tasks, transition_log_odds)combined_path = np.asarray(module.decode(probability_bits, encoded_bases, transition_scores, record_offsets,GPU_SEGMENT_LENGTH, GPU_SEGMENT_GROUP_LENGTH,0 if reconstruction_batch_size is None else reconstruction_batch_size,memory_budget_bytes,))return np.split(combined_path, record_offsets[1:-1])
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705// viterbi_grammar.h -- the Viterbi grammar shared by the CPU and GPU backends.//// viterbi.py describes Viterbi in full: the score of a labeling, the 30// states, the transition rules, and the handling of record boundaries. This// header implements the same grammar, with the same state ids, for// viterbi_cpu.cpp and viterbi_gpu.cu. Both backends take every decision about// which state changes are legal and what they score from the functions here;// they differ only in how they organize the recursion along a record. The// functions compile as host code under g++ and as host and device code under// nvcc.//// States (ids as in utils.py; the State design section of viterbi.py// describes each one)://// 0 INTERGENIC non-coding outside genes// 1 START_A A of start codon ATG// 2 START_AT T of start codon ATG; its G is EXON_PHASE0// 3..8 EXON_<prefix type> CDS base// 9 STOP last base of the terminal in-frame stop codon// 10..15 GT_GC_AG_INTRON_FIRST_<prefix type> first GT/GC-AG intron base// 16..21 GT_GC_AG_INTRON_READY_<prefix type> later GT/GC-AG intron base// 22..27 AT_AC_INTRON_<prefix type> AT-AC intron base// 28 LEADING_BOUNDARY_INTRON intron extending from the left record boundary// 29 TRAILING_BOUNDARY_INTRON intron extending to the right record boundary//// The prefix type records how much of the current codon has been read and// whether it can still become a stop codon. Within each family the states// follow the prefix types in this order://// PHASE0 codon phase 0; codon boundary, no open prefix// PHASE1_PREFIX_T codon phase 1; one-base prefix T// PHASE1_PREFIX_OTHER codon phase 1; one-base prefix other// PHASE2_PREFIX_TA codon phase 2; prefix TA, so A/G completes TAA/TAG// PHASE2_PREFIX_TG codon phase 2; prefix TG, so A completes TGA// PHASE2_PREFIX_OTHER codon phase 2; other prefix, so no stop can be completed//// Exon states carry the current prefix type while emitting coding bases.// Intron states carry the prefix type from the exon before the donor, so// the acceptor resumes CDS in the same frame.//// Scores://// Scores are integers: nats multiplied by 16,384 (FIXED_POINT_SCORE_SCALE// in constants.py) and rounded. Base p scores coding = log P(CDS) in// START_A through STOP and noncoding = log(1 - P(CDS)) in every other// state, with P clipped to [1e-6, 1 - 1e-6]. build_emission_score_tables// computes both for all 65,536 fp16 bit patterns of P; both backends read// emission scores from these tables. The intron priors and the transition// network's log-odds are in the same units. Path scores are int64 on the// CPU; the CUDA backend keeps int32 scores within a segment and int64// scores across segments. A state that no path reaches holds a sentinel// below every reachable score and is never extended.//// Recursion://// Both backends advance the Viterbi recursion one base at a time://// score[p][t] = max over the predecessors s of t at base p of// score[p - 1][s] + added(s -> t, p)//// best_transition_to_state evaluates this for one target state t. It// visits the predecessors of t in the order of the table below and keeps// the first best one, so equal scores resolve to the predecessor listed// first. The Numba reference in viterbi.py offers the same candidates in// the same order. The CPU backend calls it for the 30 targets in turn; the// CUDA kernels call it for all 30 targets from one thread, or for one// target in each lane of a warp.//// compute_position_signals reads bases p - 3 through p + 2 and returns// every condition the table tests at base p, with the emission scores and// the four transition log-odds of base p. A motif base outside the record// matches any base. The two boundary-intron guards, a concrete acceptor// followed by ATG and a concrete enabled stop codon followed by a donor,// apply only when every base of their pattern is inside the record and// concrete (Transition rules and Record boundaries in viterbi.py).//// Predecessors://// The predecessors of each target state at base p, listed in the order// that breaks ties, and the score each adds. EXON_* stands for the six// exon states in prefix-type order, and likewise for the intron families;// <prefix type> is the prefix type of the target.//// INTERGENIC// INTERGENIC noncoding// STOP noncoding// START_A// INTERGENIC, if an ATG starts at p coding + enter gene// START_AT// START_A coding// EXON_<prefix type>// START_AT, for EXON_PHASE0 coding// LEADING_BOUNDARY_INTRON, if it can exit at p coding + leave intron// EXON_*, by the coding table coding// GT_GC_AG_INTRON_READY_*, by the coding table, coding + leave intron// if an AG acceptor ends at p - 1// AT_AC_INTRON_*, by the coding table, coding + leave intron// if an AC acceptor ends at p - 1// STOP// as for EXON_<prefix type>, without START_AT coding + leave gene// GT_GC_AG_INTRON_FIRST_<prefix type>// EXON_<prefix type>, if a GT or GC donor noncoding + prior + enter intron// starts at p// GT_GC_AG_INTRON_READY_<prefix type>// GT_GC_AG_INTRON_FIRST_<prefix type> noncoding// GT_GC_AG_INTRON_READY_<prefix type> noncoding// AT_AC_INTRON_<prefix type>// EXON_<prefix type>, if an AT donor starts at p noncoding + prior + enter intron// AT_AC_INTRON_<prefix type> noncoding// LEADING_BOUNDARY_INTRON// LEADING_BOUNDARY_INTRON, if it can extend to p noncoding// TRAILING_BOUNDARY_INTRON// EXON_*, if it can be entered at p noncoding + prior + enter intron// TRAILING_BOUNDARY_INTRON noncoding//// prior is the log prior of the intron's splice class. When the donor at// p fits more than one class that leads to the target, which needs an N// at p or p + 1 or p at the last base, the highest of their priors counts.//// LEADING_BOUNDARY_INTRON can exit at p when an AG or AC acceptor ends at// p - 1, the acceptor/ATG guard does not apply, and the coding table// reaches the target from at least one prefix type. It can extend to p// while bases 0 through p number at most max_boundary_intron_length.// TRAILING_BOUNDARY_INTRON can be entered at p when a donor starts at p,// the stop/donor guard does not apply, and bases p through the record end// number at most max_boundary_intron_length.//// Coding table://// A coding base moves an exon from one prefix type to the next (State// design in viterbi.py). Read backwards, this rule gives the prefix types// that reach each coding target with the base at p://// EXON_PHASE0 from PHASE2_PREFIX_TA with T, C, A unless TAA is enabled,// or G unless TAG is enabled// from PHASE2_PREFIX_TG with T, C, G, or A unless TGA is enabled// from PHASE2_PREFIX_OTHER with any base// EXON_PHASE1_PREFIX_T from PHASE0 with T// EXON_PHASE1_PREFIX_OTHER from PHASE0 with A, C, or G// EXON_PHASE2_PREFIX_TA from PHASE1_PREFIX_T with A// EXON_PHASE2_PREFIX_TG from PHASE1_PREFIX_T with G// EXON_PHASE2_PREFIX_OTHER from PHASE1_PREFIX_T with C or T// from PHASE1_PREFIX_OTHER with any base// STOP from PHASE2_PREFIX_TA with A if TAA is enabled,// or G if TAG is enabled// from PHASE2_PREFIX_TG with A if TGA is enabled//// N matches every base, so it meets every condition that names a base.// EXON_*, GT_GC_AG_INTRON_READY_*, and AT_AC_INTRON_* are each read through// this table in increasing prefix type.//// Record boundaries://// first_base_score gives each state's score at base 0, as// initialize_first_base_scores does in viterbi.py. best_final_state// chooses the state that ends the record: the highest-scoring of// INTERGENIC, START_A through STOP, and TRAILING_BOUNDARY_INTRON, the// first in this order on a tie.//// ViterbiConfig holds the enabled stop codons, the three intron log priors in// score units, and max_boundary_intron_length (0 disables both// boundary-intron states, -1 removes the limit).#pragma once
#include <cmath>#include <cstdint>#include <cstring>
#if defined(__CUDACC__)#define VITERBI_INLINE __host__ __device__ __forceinline__#elif defined(__GNUC__)// GCC and Clang both define __GNUC__.#define VITERBI_INLINE inline __attribute__((always_inline))#else#define VITERBI_INLINE inline#endif
// ---------------------------------------------------------------------------// Scores// ---------------------------------------------------------------------------
// One base's emission score, intron prior, or transition log-odds.using StepScore = int32_t;// Path scores inside one GPU segment.using SegmentScore = int32_t;// Path scores accumulated over a record.using AccumulatedScore = int64_t;
constexpr double FIXED_POINT_SCORE_SCALE = 16384.0;constexpr double MIN_PROB = 1e-6;
// Every reachable score stays far above these sentinels: a GPU segment is// short enough to keep its path scores above -1.8e9.constexpr SegmentScore UNREACHABLE_SEGMENT_SCORE = -2000000000;constexpr AccumulatedScore UNREACHABLE_ACCUMULATED_SCORE = -4000000000000000000LL;
VITERBI_INLINE SegmentScore unreachable_score(SegmentScore) { return UNREACHABLE_SEGMENT_SCORE; }VITERBI_INLINE AccumulatedScore unreachable_score(AccumulatedScore) { return UNREACHABLE_ACCUMULATED_SCORE;}
template <typename Score>VITERBI_INLINE bool is_unreachable(Score score) { return score == unreachable_score(Score{});}
inline StepScore score_from_nats(double nats) { return static_cast<StepScore>(std::llround(nats * FIXED_POINT_SCORE_SCALE));}
// ---------------------------------------------------------------------------// States, bases, and transition columns// ---------------------------------------------------------------------------
constexpr int STATE_COUNT = 30;constexpr int PREFIX_TYPE_COUNT = 6;
constexpr int PHASE0 = 0;constexpr int PHASE1_PREFIX_T = 1;constexpr int PHASE1_PREFIX_OTHER = 2;constexpr int PHASE2_PREFIX_TA = 3;constexpr int PHASE2_PREFIX_TG = 4;constexpr int PHASE2_PREFIX_OTHER = 5;
constexpr int INTERGENIC = 0;constexpr int START_A = 1;constexpr int START_AT = 2;constexpr int EXON_PHASE0 = 3;constexpr int EXON_PHASE1_PREFIX_T = 4;constexpr int EXON_PHASE1_PREFIX_OTHER = 5;constexpr int EXON_PHASE2_PREFIX_TA = 6;constexpr int EXON_PHASE2_PREFIX_TG = 7;constexpr int EXON_PHASE2_PREFIX_OTHER = 8;constexpr int STOP = 9;constexpr int GT_GC_AG_INTRON_FIRST_PHASE0 = 10;constexpr int GT_GC_AG_INTRON_READY_PHASE0 = 16;constexpr int AT_AC_INTRON_PHASE0 = 22;constexpr int LEADING_BOUNDARY_INTRON = 28;constexpr int TRAILING_BOUNDARY_INTRON = 29;
constexpr int BASE_A = 0;constexpr int BASE_T = 1;constexpr int BASE_C = 2;constexpr int BASE_G = 3;constexpr int BASE_N = 4;
// Columns of the per-base transition log-odds, in the order of constants.py.constexpr int ENTER_GENE = 0;constexpr int LEAVE_GENE = 1;constexpr int ENTER_INTRON = 2;constexpr int LEAVE_INTRON = 3;constexpr int TRANSITION_COUNT = 4;
struct ViterbiConfig { bool stop_taa; bool stop_tag; bool stop_tga; StepScore gt_ag_intron_log_prior; StepScore gc_ag_intron_log_prior; StepScore at_ac_intron_log_prior; int max_boundary_intron_length;};
// ---------------------------------------------------------------------------// Emission scores// ---------------------------------------------------------------------------
constexpr int EMISSION_TABLE_SIZE = 65536;
// The value of an fp16 bit pattern, exact for every pattern.inline double half_bits_to_double(uint16_t half_bits) { uint32_t sign = static_cast<uint32_t>(half_bits & 0x8000) << 16; uint32_t exponent = (half_bits >> 10) & 0x1F; uint32_t mantissa = half_bits & 0x3FF; uint32_t float_bits; if (exponent == 0) { if (mantissa == 0) { float_bits = sign; } else { int normalization_shift = -1; do { normalization_shift++; mantissa <<= 1; } while (!(mantissa & 0x400)); float_bits = sign | (static_cast<uint32_t>(127 - 15 - normalization_shift) << 23) | ((mantissa & 0x3FF) << 13); } } else if (exponent == 0x1F) { float_bits = sign | 0x7F800000u | (mantissa << 13); } else { float_bits = sign | ((exponent + (127 - 15)) << 23) | (mantissa << 13); } float value; std::memcpy(&value, &float_bits, sizeof(value)); return static_cast<double>(value);}
// coding_scores[bits] = log P and noncoding_scores[bits] = log(1 - P), where P// is the fp16 value of bits clipped to [MIN_PROB, 1 - MIN_PROB].inline void build_emission_score_tables(StepScore* coding_scores, StepScore* noncoding_scores) { for (int bits = 0; bits < EMISSION_TABLE_SIZE; bits++) { double probability = half_bits_to_double(static_cast<uint16_t>(bits)); if (probability < MIN_PROB) probability = MIN_PROB; else if (probability > 1.0 - MIN_PROB) probability = 1.0 - MIN_PROB; coding_scores[bits] = score_from_nats(std::log(probability)); noncoding_scores[bits] = score_from_nats(std::log(1.0 - probability)); }}
// ---------------------------------------------------------------------------// Position signals// ---------------------------------------------------------------------------
VITERBI_INLINE bool base_matches(int observed_base, int expected_base) { return observed_base == expected_base || observed_base == BASE_N;}
VITERBI_INLINE bool is_exact_enabled_stop_codon( int first_base, int second_base, int third_base, const ViterbiConfig& config) { if (first_base != BASE_T) return false; if (second_base == BASE_A) { if (third_base == BASE_A && config.stop_taa) return true; if (third_base == BASE_G && config.stop_tag) return true; } return second_base == BASE_G && third_base == BASE_A && config.stop_tga;}
// Everything the predecessor table reads at base p.struct PositionSignals { StepScore coding_score; StepScore noncoding_score; StepScore enter_gene_log_odds; StepScore leave_gene_log_odds; StepScore enter_intron_log_odds; StepScore leave_intron_log_odds;
bool has_gt_ag_donor; // GT starts at p bool has_gc_ag_donor; // GC starts at p bool has_at_ac_donor; // AT starts at p bool has_ag_acceptor; // AG ends at p - 1 bool has_ac_acceptor; // AC ends at p - 1 bool has_atg_start; // ATG starts at p // The highest prior among the GT-AG and GC-AG donors at p, and among all // donors at p. StepScore gt_gc_ag_donor_log_prior; StepScore any_donor_log_prior;
bool can_exit_leading_boundary_intron; bool can_extend_leading_boundary_intron; bool can_enter_trailing_boundary_intron;
// The coding table: moves_x_to_y is whether base p moves prefix type x to // prefix type y (phase0, t, phase1_other, ta, tg, phase2_other) or to STOP. // PHASE1_PREFIX_OTHER -> PHASE2_PREFIX_OTHER and PHASE2_PREFIX_OTHER -> // PHASE0 take every base. bool moves_phase0_to_t; bool moves_phase0_to_phase1_other; bool moves_t_to_ta; bool moves_t_to_tg; bool moves_t_to_phase2_other; bool moves_ta_to_phase0; bool moves_tg_to_phase0; bool moves_ta_to_stop; bool moves_tg_to_stop;};
// bases[record_offset + q] is base q of the record, and transitions points at// the four log-odds of base position; 1 <= position < record_length.VITERBI_INLINE PositionSignals compute_position_signals( const int8_t* bases, int64_t record_offset, int64_t record_length, int64_t position, StepScore coding_score, StepScore noncoding_score, const StepScore* transitions, const ViterbiConfig& config) { auto base_at = [&](int64_t record_position) -> int { return bases[record_offset + record_position]; }; PositionSignals signals; signals.coding_score = coding_score; signals.noncoding_score = noncoding_score; signals.enter_gene_log_odds = transitions[ENTER_GENE]; signals.leave_gene_log_odds = transitions[LEAVE_GENE]; signals.enter_intron_log_odds = transitions[ENTER_INTRON]; signals.leave_intron_log_odds = transitions[LEAVE_INTRON];
const int base = base_at(position); const bool next_base_is_missing = position + 1 == record_length; const int next_base = next_base_is_missing ? -1 : base_at(position + 1);
// Motifs. A base outside the record matches any base. signals.has_gt_ag_donor = base_matches(base, BASE_G) && (next_base_is_missing || base_matches(next_base, BASE_T)); signals.has_gc_ag_donor = base_matches(base, BASE_G) && (next_base_is_missing || base_matches(next_base, BASE_C)); signals.has_at_ac_donor = base_matches(base, BASE_A) && (next_base_is_missing || base_matches(next_base, BASE_T)); const bool acceptor_first_base_matches = position == 1 || base_matches(base_at(position - 2), BASE_A); signals.has_ag_acceptor = acceptor_first_base_matches && base_matches(base_at(position - 1), BASE_G); signals.has_ac_acceptor = acceptor_first_base_matches && base_matches(base_at(position - 1), BASE_C); const bool third_start_base_matches = position + 2 >= record_length || base_matches(base_at(position + 2), BASE_G); signals.has_atg_start = base_matches(base, BASE_A) && (next_base_is_missing || base_matches(next_base, BASE_T)) && third_start_base_matches;
StepScore gt_gc_ag_donor_log_prior = UNREACHABLE_SEGMENT_SCORE; if (signals.has_gt_ag_donor) gt_gc_ag_donor_log_prior = config.gt_ag_intron_log_prior; if (signals.has_gc_ag_donor && config.gc_ag_intron_log_prior > gt_gc_ag_donor_log_prior) { gt_gc_ag_donor_log_prior = config.gc_ag_intron_log_prior; } StepScore any_donor_log_prior = gt_gc_ag_donor_log_prior; if (signals.has_at_ac_donor && config.at_ac_intron_log_prior > any_donor_log_prior) { any_donor_log_prior = config.at_ac_intron_log_prior; } signals.gt_gc_ag_donor_log_prior = gt_gc_ag_donor_log_prior; signals.any_donor_log_prior = any_donor_log_prior;
// The boundary-intron guards need concrete bases inside the record. const bool has_exact_acceptor_followed_by_atg = position >= 2 && position + 2 < record_length && base_at(position - 2) == BASE_A && (base_at(position - 1) == BASE_G || base_at(position - 1) == BASE_C) && base == BASE_A && next_base == BASE_T && base_at(position + 2) == BASE_G; const bool has_exact_donor = position + 1 < record_length && ((base == BASE_G && (next_base == BASE_T || next_base == BASE_C)) || (base == BASE_A && next_base == BASE_T)); const bool has_exact_enabled_stop_followed_by_donor = has_exact_donor && position >= 3 && is_exact_enabled_stop_codon( base_at(position - 3), base_at(position - 2), base_at(position - 1), config );
// A leading intron through p is p + 1 bases long; a trailing intron // entered at p is record_length - p bases long. const bool boundary_introns_enabled = config.max_boundary_intron_length != 0; const bool boundary_intron_length_is_unlimited = config.max_boundary_intron_length == -1; signals.can_exit_leading_boundary_intron = (signals.has_ag_acceptor || signals.has_ac_acceptor) && !has_exact_acceptor_followed_by_atg; signals.can_extend_leading_boundary_intron = boundary_introns_enabled && (boundary_intron_length_is_unlimited || position < config.max_boundary_intron_length); signals.can_enter_trailing_boundary_intron = (signals.has_gt_ag_donor || signals.has_gc_ag_donor || signals.has_at_ac_donor) && !has_exact_enabled_stop_followed_by_donor && boundary_introns_enabled && (boundary_intron_length_is_unlimited || record_length - position <= config.max_boundary_intron_length);
const bool base_is_a = base_matches(base, BASE_A); const bool base_is_c = base_matches(base, BASE_C); const bool base_is_g = base_matches(base, BASE_G); const bool base_is_t = base_matches(base, BASE_T); signals.moves_phase0_to_t = base_is_t; signals.moves_phase0_to_phase1_other = base_is_a || base_is_c || base_is_g; signals.moves_t_to_ta = base_is_a; signals.moves_t_to_tg = base_is_g; signals.moves_t_to_phase2_other = base_is_c || base_is_t; signals.moves_ta_to_phase0 = base_is_t || base_is_c || (base_is_a && !config.stop_taa) || (base_is_g && !config.stop_tag); signals.moves_tg_to_phase0 = base_is_t || base_is_c || base_is_g || (base_is_a && !config.stop_tga); signals.moves_ta_to_stop = (base_is_a && config.stop_taa) || (base_is_g && config.stop_tag); signals.moves_tg_to_stop = base_is_a && config.stop_tga; return signals;}
// ---------------------------------------------------------------------------// The predecessor table// ---------------------------------------------------------------------------
template <typename Score>struct TransitionChoice { Score score; int source_state;};
template <typename Score>VITERBI_INLINE void consider_predecessor( TransitionChoice<Score>& best, const Score* scores, int source_state, Score added_score) { Score source_score = scores[source_state]; if (is_unreachable(source_score)) return; Score candidate_score = source_score + added_score; if (candidate_score > best.score) { best.score = candidate_score; best.source_state = source_state; }}
// The members of one source group that the coding table moves into// target_state, in increasing prefix type. The member of prefix type t is// state first_state + stride * t. LEADING_BOUNDARY_INTRON resumes with any// prefix type, so it is the group with first_state LEADING_BOUNDARY_INTRON// and stride 0.template <typename Score>VITERBI_INLINE void consider_coding_predecessors( TransitionChoice<Score>& best, const Score* scores, int target_state, int first_state, int stride, Score added_score, const PositionSignals& signals) { switch (target_state) { case EXON_PHASE0: if (signals.moves_ta_to_phase0) { consider_predecessor(best, scores, first_state + PHASE2_PREFIX_TA * stride, added_score); } if (signals.moves_tg_to_phase0) { consider_predecessor(best, scores, first_state + PHASE2_PREFIX_TG * stride, added_score); } consider_predecessor(best, scores, first_state + PHASE2_PREFIX_OTHER * stride, added_score); break; case EXON_PHASE1_PREFIX_T: if (signals.moves_phase0_to_t) { consider_predecessor(best, scores, first_state + PHASE0 * stride, added_score); } break; case EXON_PHASE1_PREFIX_OTHER: if (signals.moves_phase0_to_phase1_other) { consider_predecessor(best, scores, first_state + PHASE0 * stride, added_score); } break; case EXON_PHASE2_PREFIX_TA: if (signals.moves_t_to_ta) { consider_predecessor(best, scores, first_state + PHASE1_PREFIX_T * stride, added_score); } break; case EXON_PHASE2_PREFIX_TG: if (signals.moves_t_to_tg) { consider_predecessor(best, scores, first_state + PHASE1_PREFIX_T * stride, added_score); } break; case EXON_PHASE2_PREFIX_OTHER: if (signals.moves_t_to_phase2_other) { consider_predecessor(best, scores, first_state + PHASE1_PREFIX_T * stride, added_score); } consider_predecessor(best, scores, first_state + PHASE1_PREFIX_OTHER * stride, added_score); break; case STOP: if (signals.moves_ta_to_stop) { consider_predecessor(best, scores, first_state + PHASE2_PREFIX_TA * stride, added_score); } if (signals.moves_tg_to_stop) { consider_predecessor(best, scores, first_state + PHASE2_PREFIX_TG * stride, added_score); } break; }}
// The best predecessor of target_state at base p and the path score it gives;// an unreachable score if no predecessor is reachable.template <typename Score>VITERBI_INLINE TransitionChoice<Score> best_transition_to_state( int target_state, const Score* scores, const PositionSignals& signals, const ViterbiConfig& config) { TransitionChoice<Score> best = {unreachable_score(Score{}), 0}; const Score coding = signals.coding_score; const Score noncoding = signals.noncoding_score;
if (target_state == INTERGENIC) { consider_predecessor(best, scores, INTERGENIC, noncoding); consider_predecessor(best, scores, STOP, noncoding); } else if (target_state == START_A) { if (signals.has_atg_start) { consider_predecessor(best, scores, INTERGENIC, coding + signals.enter_gene_log_odds); } } else if (target_state == START_AT) { consider_predecessor(best, scores, START_A, coding); } else if (target_state <= STOP) { // An exon state or STOP. Every transition into STOP is charged leave gene. const Score from_exon = target_state == STOP ? coding + signals.leave_gene_log_odds : coding; const Score from_intron = target_state == STOP ? coding + signals.leave_gene_log_odds : coding + signals.leave_intron_log_odds; if (target_state == EXON_PHASE0) { consider_predecessor(best, scores, START_AT, coding); } if (signals.can_exit_leading_boundary_intron) { consider_coding_predecessors( best, scores, target_state, LEADING_BOUNDARY_INTRON, 0, from_intron, signals ); } consider_coding_predecessors( best, scores, target_state, EXON_PHASE0, 1, from_exon, signals ); if (signals.has_ag_acceptor) { consider_coding_predecessors( best, scores, target_state, GT_GC_AG_INTRON_READY_PHASE0, 1, from_intron, signals ); } if (signals.has_ac_acceptor) { consider_coding_predecessors( best, scores, target_state, AT_AC_INTRON_PHASE0, 1, from_intron, signals ); } } else if (target_state < GT_GC_AG_INTRON_READY_PHASE0) { const int prefix_type = target_state - GT_GC_AG_INTRON_FIRST_PHASE0; if (signals.has_gt_ag_donor || signals.has_gc_ag_donor) { consider_predecessor( best, scores, EXON_PHASE0 + prefix_type, noncoding + signals.gt_gc_ag_donor_log_prior + signals.enter_intron_log_odds ); } } else if (target_state < AT_AC_INTRON_PHASE0) { const int prefix_type = target_state - GT_GC_AG_INTRON_READY_PHASE0; consider_predecessor( best, scores, GT_GC_AG_INTRON_FIRST_PHASE0 + prefix_type, noncoding ); consider_predecessor(best, scores, target_state, noncoding); } else if (target_state < LEADING_BOUNDARY_INTRON) { const int prefix_type = target_state - AT_AC_INTRON_PHASE0; if (signals.has_at_ac_donor) { consider_predecessor( best, scores, EXON_PHASE0 + prefix_type, noncoding + config.at_ac_intron_log_prior + signals.enter_intron_log_odds ); } consider_predecessor(best, scores, target_state, noncoding); } else if (target_state == LEADING_BOUNDARY_INTRON) { if (signals.can_extend_leading_boundary_intron) { consider_predecessor(best, scores, LEADING_BOUNDARY_INTRON, noncoding); } } else { if (signals.can_enter_trailing_boundary_intron) { const Score from_exon = noncoding + signals.any_donor_log_prior + signals.enter_intron_log_odds; consider_predecessor(best, scores, EXON_PHASE0, from_exon); consider_predecessor(best, scores, EXON_PHASE1_PREFIX_T, from_exon); consider_predecessor(best, scores, EXON_PHASE1_PREFIX_OTHER, from_exon); consider_predecessor(best, scores, EXON_PHASE2_PREFIX_TA, from_exon); consider_predecessor(best, scores, EXON_PHASE2_PREFIX_TG, from_exon); consider_predecessor(best, scores, EXON_PHASE2_PREFIX_OTHER, from_exon); } consider_predecessor(best, scores, TRAILING_BOUNDARY_INTRON, noncoding); } return best;}
// ---------------------------------------------------------------------------// Record boundaries// ---------------------------------------------------------------------------
// The score of state at base 0. bases[record_offset + q] is base q of the// record, and transitions points at the four log-odds of base 0. A record may// begin anywhere in a gene, so every state that base 0 and unknown bases// before it allow is reachable.template <typename Score>VITERBI_INLINE Score first_base_score( int state, const int8_t* bases, int64_t record_offset, int64_t record_length, StepScore coding_score, StepScore noncoding_score, const StepScore* transitions, const ViterbiConfig& config) { const int base = bases[record_offset]; const Score coding = coding_score; const Score noncoding = noncoding_score; const Score unreachable = unreachable_score(Score{}); switch (state) { case INTERGENIC: return noncoding; case START_A: { // The start codon may continue beyond the right edge. const bool has_atg_start = base_matches(base, BASE_A) && (record_length == 1 || base_matches(bases[record_offset + 1], BASE_T)) && (record_length <= 2 || base_matches(bases[record_offset + 2], BASE_G)); return has_atg_start ? coding + transitions[ENTER_GENE] : unreachable; } case EXON_PHASE0: case EXON_PHASE2_PREFIX_OTHER: return coding; case EXON_PHASE1_PREFIX_T: return base_matches(base, BASE_T) ? coding : unreachable; case EXON_PHASE1_PREFIX_OTHER: return base != BASE_T ? coding : unreachable; case EXON_PHASE2_PREFIX_TA: return base_matches(base, BASE_A) ? coding : unreachable; case EXON_PHASE2_PREFIX_TG: return base_matches(base, BASE_G) ? coding : unreachable; case STOP: { // The last base of a stop codon that began before the record. const bool can_end_stop = (base_matches(base, BASE_A) && (config.stop_taa || config.stop_tga)) || (base_matches(base, BASE_G) && config.stop_tag); return can_end_stop ? coding + transitions[LEAVE_GENE] : unreachable; } case LEADING_BOUNDARY_INTRON: return config.max_boundary_intron_length != 0 ? noncoding : unreachable; default: return unreachable; }}
template <typename Score>VITERBI_INLINE int best_final_state(const Score* scores) { int best_state = INTERGENIC; for (int state = START_A; state <= STOP; state++) { if (scores[state] > scores[best_state]) best_state = state; } if (scores[TRAILING_BOUNDARY_INTRON] > scores[best_state]) { best_state = TRAILING_BOUNDARY_INTRON; } return best_state;}7 unmodified lines8910111213147 unmodified linesbiopython>=1.83,<2# Annotation pipeline (annotation_pipeline/, Linux only)pandaspyarrowtqdmnumba7 unmodified lines89101112137 unmodified linesbiopython>=1.83,<2# Annotation pipeline (annotation_pipeline/, Linux only)pyarrowtqdmnumba
README.md+1-1
annotation_pipeline/README.md+8-6
annotation_pipeline/run_annotation.sh+17-6
annotation_pipeline/src/confidence_network.py+109-46
annotation_pipeline/src/constants.py+33-22
annotation_pipeline/src/model_inference.py+119-75
annotation_pipeline/src/post_processing.py+141-85
annotation_pipeline/src/tcn.py+21-19
annotation_pipeline/src/transition_network.py+21-15
annotation_pipeline/src/utils.py+159-108
annotation_pipeline/src/viterbi.py+110-111
annotation_pipeline/src/viterbi_backends/viterbi_cpu.cpp+123-684
annotation_pipeline/src/viterbi_backends/decode_cpu.py → annotation_pipeline/src/viterbi_backends/viterbi_cpu.pyRenamed+15-26
annotation_pipeline/src/viterbi_backends/viterbi_gpu.cu
annotation_pipeline/src/viterbi_backends/decode_gpu.py → annotation_pipeline/src/viterbi_backends/viterbi_gpu.pyRenamed+39-83
annotation_pipeline/src/viterbi_backends/viterbi_grammar.hAdded+705
requirements.txt-1