Spaces:
Running on Zero

File size: 4,290 Bytes
0a96270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# SPDX-License-Identifier: Apache-2.0
"""Load the official RIBOSPAN MaskedLM checkpoints for ZeroGPU inference."""

from __future__ import annotations

import os
from contextlib import nullcontext
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import torch
from huggingface_hub import snapshot_download

from scripts.config import MODEL_REGISTRY, ModelSpec
from scripts.model_src import ensure_import_path


SUPPORTED_DTYPES = {
    "float32": torch.float32,
    "bfloat16": torch.bfloat16,
    "float16": torch.float16,
}


@dataclass
class LoadedRiboSpan:
    spec: ModelSpec
    model: Any
    tokenizer: Any
    device: torch.device
    dtype: torch.dtype
    runtime_max_length: int

    def encode(self, sequence: str, positions: tuple[int, ...] = ()) -> list[int]:
        """The original benchmark maps nucleotides directly, with CLS/SEP."""

        if len(sequence) > self.spec.trained_context_window:
            raise ValueError("sequence exceeds the checkpoint's native context")
        nt_ids = [self.tokenizer.token_to_id(nt) for nt in sequence]
        if any(value is None or value == self.tokenizer.unk_token_id for value in nt_ids):
            raise ValueError("tokenizer cannot encode one or more nucleotides")
        for position in positions:
            nt_ids[position] = self.tokenizer.mask_token_id
        return [self.tokenizer.cls_token_id, *nt_ids, self.tokenizer.sep_token_id]

    def autocast(self):
        if self.device.type == "cuda" and self.dtype != torch.float32:
            return torch.autocast(device_type="cuda", dtype=self.dtype)
        return nullcontext()


def load_ribospan(spec: ModelSpec, *, device: torch.device) -> LoadedRiboSpan:
    """Download only official model material and reserve CLS/SEP positions."""

    ensure_import_path()
    import ribospan
    from ribospan import RiboSpanConfig, RiboSpanForMaskedLM, RiboSpanTokenizer

    weight_dtype = SUPPORTED_DTYPES[os.environ.get("RIBOSPAN_WEIGHT_DTYPE", "bfloat16")]
    autocast_dtype = SUPPORTED_DTYPES[os.environ.get("RIBOSPAN_AUTOCAST_DTYPE", "bfloat16")]
    if device.type == "cpu":
        weight_dtype = autocast_dtype = torch.float32

    token = os.environ.get("HF_TOKEN") or None
    print(f"load {spec.name} from {spec.repo_id}@{spec.revision}", flush=True)
    location = snapshot_download(
        repo_id=spec.repo_id,
        revision=spec.revision,
        token=token,
        allow_patterns=["config.json", "*.safetensors", "*.safetensors.index.json", "pytorch_model*.bin", "pytorch_model*.bin.index.json"],
    )
    tokenizer = RiboSpanTokenizer(str(Path(ribospan.__file__).with_name("vocab.txt")))
    config = RiboSpanConfig.from_pretrained(location, local_files_only=True)
    config_max = int(config.max_position_embeddings)
    runtime_max = max(config_max, spec.trained_context_window + 2)
    if runtime_max > config_max and config.position_embedding_type != "rope":
        raise RuntimeError("only RoPE checkpoints support additional special-token positions")
    config.max_position_embeddings = runtime_max
    config.output_attentions = False
    config.output_hidden_states = False
    # Let from_pretrained initialize the requested dtype. Do not recast RoPE
    # buffers with a global .to(dtype=...) after initialization.
    model = RiboSpanForMaskedLM.from_pretrained(
        location,
        config=config,
        torch_dtype=weight_dtype,
        local_files_only=True,
    ).eval()
    model.to(device)
    print(f"loaded {spec.name}: runtime context {runtime_max}, weight dtype {weight_dtype}", flush=True)
    return LoadedRiboSpan(spec, model, tokenizer, device, autocast_dtype, runtime_max)


def load_registry(*, device: torch.device) -> dict[str, LoadedRiboSpan]:
    """Load configured models once at module startup, not per GPU request."""

    configured = os.environ.get("RIBOSPAN_ENABLED_MODELS")
    names = list(MODEL_REGISTRY) if not configured else [name.strip() for name in configured.split(",") if name.strip()]
    if not names or len(names) != len(set(names)) or set(names) - MODEL_REGISTRY.keys():
        raise ValueError("RIBOSPAN_ENABLED_MODELS contains an unsupported checkpoint")
    return {name: load_ribospan(MODEL_REGISTRY[name], device=device) for name in names}