# SPDX-License-Identifier: Apache-2.0 """Representation extraction and masked nucleotide prediction for website jobs.""" from __future__ import annotations import os import re import shutil import tempfile import time from pathlib import Path from typing import Any import numpy as np from scripts.batching import batches, with_oom_retry from scripts.config import LIMITS from scripts.errors import RequestError from scripts.logits import MLMScorer, MaskPattern from scripts.model_io import LoadedRiboSpan from scripts.requests import Job OUTPUT_ROOT = Path(tempfile.gettempdir()) / "ribospan-inference-outputs" BASES = ("A", "C", "G", "U") def _prune_outputs() -> None: OUTPUT_ROOT.mkdir(parents=True, exist_ok=True, mode=0o700) deadline = time.time() - LIMITS.file_ttl_seconds for path in OUTPUT_ROOT.iterdir(): if path.is_dir() and not path.is_symlink() and path.name.startswith("job-") and path.stat().st_mtime < deadline: shutil.rmtree(path, ignore_errors=True) def ensure_embedding_capacity(job: Job) -> None: """Reserve disk headroom for NPZ output and possible Gradio cache copies.""" _prune_outputs() # Float16 nucleotide matrices, float32 pooled vectors and NPZ headers. # Gradio may copy files into its own cache; allow room for both copies. required = 2 * sum(len(record.sequence) * 4096 + 8192 + 4096 for record in job.records) if shutil.disk_usage(OUTPUT_ROOT).free < required + LIMITS.min_free_disk_bytes: raise RequestError("output_storage", "Temporary embedding storage is nearly full. Download completed files promptly, then try again after old results expire.") def _output_directory() -> Path: _prune_outputs() return Path(tempfile.mkdtemp(prefix="job-", dir=OUTPUT_ROOT)) def embed_job(job: Job, models: dict[str, LoadedRiboSpan]) -> tuple[dict[str, Any], list[str]]: """Return per-record pooled JSON and one binary per-nucleotide matrix.""" output = _output_directory() metadata: dict[str, dict[str, Any]] = {} # Track file ordering explicitly, regardless of batch execution order. order = {record.id: i for i, record in enumerate(job.records)} files = [""] * len(job.records) try: for chunk in batches(job.records, key=lambda record: (record.model.name, len(record.sequence) + 2)): scorer = MLMScorer(models[chunk[0].model.name]) values = with_oom_retry(lambda part: scorer.representations([record.sequence for record in part]), chunk) for record, (pooled, matrix) in zip(chunk, values, strict=True): index = order[record.id] if matrix.shape != (len(record.sequence), 2048) or pooled.shape != (2048,): raise RuntimeError("unexpected RIBOSPAN representation shape") if not np.isfinite(pooled).all() or not np.isfinite(matrix).all(): raise RuntimeError("non-finite RIBOSPAN representation") label = re.sub(r"[^A-Za-z0-9._-]+", "_", record.id).strip("._")[:80] or "rna" path = output / f"{index:03d}-{label}.npz" # Uncompressed NPZ is intentional: CPU compression can dominate # GPU wall time for large embeddings. Dtype remains explicit. np.savez(path, matrix=matrix, pooled=pooled.astype(np.float32)) files[index] = str(path) metadata[record.id] = { "id": record.id, "model_id": record.model.name, "length": len(record.sequence), "dim": 2048, "pooled": pooled.astype(np.float32).tolist(), "matrix_file_index": index, "matrix_dtype": "float16", } return {"results": [metadata[record.id] for record in job.records]}, files except BaseException: shutil.rmtree(output, ignore_errors=True) raise def fill_job(job: Job, models: dict[str, LoadedRiboSpan]) -> dict[str, Any]: """Mask all requested sites jointly and return four-base probabilities.""" metadata: dict[str, dict[str, Any]] = {} for chunk in batches(job.records, key=lambda record: (record.model.name, len(record.sequence) + 2)): scorer = MLMScorer(models[chunk[0].model.name]) values = with_oom_retry( lambda part: scorer.base_probabilities([MaskPattern(record.sequence, record.positions) for record in part]), chunk, ) for record, probs in zip(chunk, values, strict=True): if probs.shape != (len(record.positions), 4) or not np.isfinite(probs).all(): raise RuntimeError("unexpected masked-nucleotide probabilities") metadata[record.id] = { "id": record.id, "model_id": record.model.name, "sites": [ {"position": position, "probabilities": {base: float(value) for base, value in zip(BASES, row, strict=True)}} for position, row in zip(record.positions, probs, strict=True) ], } return {"results": [metadata[record.id] for record in job.records]}