# SPDX-License-Identifier: Apache-2.0 """Validate the website contract and plan checkpoint-aware, bounded GPU work.""" from __future__ import annotations import json import math from collections import defaultdict from dataclasses import dataclass from typing import Any from scripts.config import LIMITS, ModelSpec, ResourceLimits, select_model from scripts.errors import RequestError from scripts.mutations import PointMutation, mutation_window, parse_mutant, validate_reference @dataclass(frozen=True) class Variant: label: str mutations: tuple[PointMutation, ...] start: int end: int @property def positions(self) -> tuple[int, ...]: return tuple(item.position for item in self.mutations) @dataclass(frozen=True) class Record: id: str sequence: str # normalized internal A/C/G/T/N sequence model: ModelSpec positions: tuple[int, ...] = () variants: tuple[Variant, ...] = () @dataclass(frozen=True) class Job: task: str records: tuple[Record, ...] forward_lengths: tuple[int, ...] # real nucleotide lengths, one per mask pattern @property def forward_tokens(self) -> int: return sum(length + 2 for length in self.forward_lengths) @property def attention_cells(self) -> int: return sum((length + 2) ** 2 for length in self.forward_lengths) @property def estimated_seconds(self) -> int: # Initial conservative heuristic, not a measured latency. Keep fixed # coefficients in sync with the website's planner. Never clip a job # into a reservation shorter than its own estimate. estimate = 15 + self.forward_tokens / 2048 + 75 * self.attention_cells / (8 * 10242**2) return max(20, math.ceil(estimate)) def normalize_sequence(value: Any, *, allow_mask: bool = False) -> str: """Normalize RNA to the original tokenizer's T-based internal vocabulary.""" if not isinstance(value, str) or not value: raise ValueError("sequence must be a nonempty string") seq = value.upper().replace("U", "T") alphabet = set("ACGTN" if allow_mask else "ACGT") if set(seq) - alphabet: raise ValueError("sequence contains unsupported nucleotide symbols") return seq def _parse_positions(value: Any, sequence: str) -> tuple[int, ...]: if not isinstance(value, list) or not value: raise ValueError("positions must contain at least one zero-based masked site") if any(type(pos) is not int or pos < 0 or pos >= len(sequence) for pos in value): raise ValueError("masked positions must be integer indices within the sequence") if len(set(value)) != len(value): raise ValueError("duplicate masked positions") if set(value) != {i for i, nt in enumerate(sequence) if nt == "N"}: raise ValueError("positions must match the N sites in the input sequence") return tuple(sorted(value)) def group_variants(record: Record) -> list[tuple[tuple[int, int, tuple[int, ...]], list[Variant]]]: """Variants sharing the reference, crop and mask pattern reuse a forward pass.""" groups: dict[tuple[int, int, tuple[int, ...]], list[Variant]] = defaultdict(list) for variant in record.variants: groups[(variant.start, variant.end, variant.positions)].append(variant) return list(groups.items()) def normalize_payload(payload: Any) -> dict[str, Any]: """Accept a JSON object from the API or serialized JSON from the editor.""" # Some Gradio component/version combinations forward JSON as a string. # Decode only JSON, never eval; preserve all explicit client fields. for _ in range(2): if not isinstance(payload, str): break try: payload = json.loads(payload) except (TypeError, ValueError): raise ValueError("request is not valid JSON; paste a JSON object") from None if not isinstance(payload, dict): raise ValueError("request must be a JSON object containing sequences") return payload def parse_job(task: str, payload: Any, limits: ResourceLimits = LIMITS) -> Job: """Validate one request before inference; keep input order and exact labels.""" if task not in {"embed", "fill", "variant"}: raise ValueError("unsupported task") payload = normalize_payload(payload) if payload.get("model_id", "auto") != "auto": raise ValueError('model_id must be "auto"') if task == "embed" and payload.get("output", "both") != "both": raise ValueError('embedding output must be "both"') raw = payload.get("sequences") if not isinstance(raw, list) or not raw: raise ValueError("submit at least one sequence record") if len(raw) > limits.max_records: raise RequestError("max_records", f"Received {len(raw):,} sequences; the limit is {limits.max_records:,} per request. Split the batch.") records: list[Record] = [] lengths: list[int] = [] ids: set[str] = set() total_nt = 0 total_variants = 0 total_sites = 0 variant_chars = 0 for item in raw: if not isinstance(item, dict): raise ValueError("each sequence record must be an object") record_id = item.get("id") if not isinstance(record_id, str) or not record_id.strip() or len(record_id) > 256 or record_id in ids: raise ValueError("sequence IDs must be nonempty, unique, and at most 256 characters") ids.add(record_id) seq = normalize_sequence(item.get("sequence"), allow_mask=task == "fill") total_nt += len(seq) if total_nt > limits.max_total_nt: raise RequestError("max_total_nt", f"Input contains at least {total_nt:,} nucleotides; the limit is {limits.max_total_nt:,} total nucleotides per request. Split the batch.") model = select_model(task, len(seq)) if task != "variant" and len(seq) > model.trained_context_window: raise RequestError("native_context", f"A sequence is {len(seq):,} nt; the native context is {model.trained_context_window:,} nt. Shorten the sequence.") positions: tuple[int, ...] = () variants: list[Variant] = [] if task == "fill": positions = _parse_positions(item.get("positions"), seq) total_sites += len(positions) if total_sites > limits.max_masked_sites: raise RequestError("max_masked_sites", f"Input exceeds {limits.max_masked_sites:,} masked sites per GPU job. Split the batch.") elif task == "variant": raw_variants = item.get("variants") if not isinstance(raw_variants, list) or not raw_variants: raise ValueError("variants must be a nonempty list of substitution strings") total_variants += len(raw_variants) if total_variants > limits.max_variants: raise RequestError("max_variants", f"Input contains at least {total_variants:,} variants; the limit is {limits.max_variants:,} variants per request. Split the variant list.") labels: set[str] = set() for raw_variant in raw_variants: if not isinstance(raw_variant, str): raise ValueError("variants must be substitution strings") variant_chars += len(raw_variant) if variant_chars > limits.max_variant_chars: raise RequestError("max_variant_chars", f"Variant labels exceed {limits.max_variant_chars:,} characters per GPU job. Split the variant list.") parsed = parse_mutant(raw_variant) validate_reference(seq, parsed) label = ",".join(mutation.as_rna() for mutation in parsed) if label in labels: raise ValueError("duplicate variant in a sequence record") labels.add(label) span = parsed[-1].position - parsed[0].position + 1 if span > model.trained_context_window: raise RequestError("variant_span", f"A variant spans {span:,} nt; the native context is {model.trained_context_window:,} nt. Use variants within a single native window.") start, end = mutation_window( len(seq), [mutation.position for mutation in parsed], max_nucleotides=model.trained_context_window, ) variants.append(Variant(label=label, mutations=tuple(parsed), start=start, end=end)) record = Record(record_id, seq, model, positions, tuple(variants)) records.append(record) if task == "variant": lengths.extend(end - start for (start, end, _), _ in group_variants(record)) else: lengths.append(len(seq)) job = Job(task=task, records=tuple(records), forward_lengths=tuple(lengths)) if task == "variant" and len(lengths) > limits.max_mask_patterns: raise RequestError("max_mask_patterns", f"Received {len(lengths):,} distinct mask patterns; the limit is {limits.max_mask_patterns:,} per request. Split the variant list.") if job.forward_tokens > limits.max_forward_tokens: raise RequestError("max_forward_tokens", f"Estimated workload is {job.forward_tokens:,} forward tokens; the limit is {limits.max_forward_tokens:,} per request. Split the batch.") if job.attention_cells > limits.max_attention_cells: raise RequestError("max_attention_cells", f"Estimated attention workload is {job.attention_cells:,} cells; the limit is {limits.max_attention_cells:,} per request. Split the batch or use shorter inputs.") if job.estimated_seconds > limits.max_gpu_seconds: raise RequestError("max_gpu_duration", f"Estimated GPU reservation is {job.estimated_seconds:,} s; the limit is {limits.max_gpu_seconds:,} s per job. Split the batch.") return job def estimate_duration(task: str, payload: Any) -> int: """Conservative initial GPU reservation (seconds), to be calibrated live.""" try: job = parse_job(task, payload) except (TypeError, ValueError, OverflowError): return 10 return job.estimated_seconds