File size: 5,985 Bytes
815acd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb4dacd
815acd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0510d86
815acd7
0510d86
815acd7
 
 
 
 
 
 
0510d86
815acd7
bb4dacd
 
815acd7
 
 
 
 
 
 
 
 
 
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
104
105
106
107
108
109
110
111
112
113
114
"""Public Hub model loading with pinned downloads and bounded resource use."""
from gpu_runtime import ZERO_GPU
import gc
import os
from pathlib import Path
import shutil
from urllib.parse import urlsplit

from huggingface_hub import HfApi, snapshot_download
from huggingface_hub.utils import validate_repo_id
import torch
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer

CACHE = Path(__file__).parent / ".model-cache"
MODEL_LABELS = {
    "HuggingFaceTB/SmolLM2-135M": "SmolLM2 135M / base / quick CPU start",
    "HuggingFaceTB/SmolLM2-360M": "SmolLM2 360M / base",
    "openai-community/gpt2": "GPT-2 / classic base model",
    "Qwen/Qwen3-0.6B-Base": "Qwen3 0.6B / base / multilingual",
    "Qwen/Qwen3-0.6B": "Qwen3 0.6B / instruction tuned / Token Visualiser option",
    "Qwen/Qwen2.5-0.5B": "Qwen2.5 0.5B / base / multilingual",
    "unsloth/gemma-3-1b-pt": "Gemma 3 1B / base / larger CPU model",
    "unsloth/gemma-3-1b-it": "Gemma 3 1B / instruction tuned / safetensors",
}
if ZERO_GPU:
    MODEL_LABELS["openai-community/gpt2-xl"] = "GPT-2 XL / 1.5B / larger prose base model"
PRESETS = list(MODEL_LABELS)


def repository(value):
    value = value.strip()
    # Accept labels from older/cached dropdown UIs as well as canonical IDs.
    value = {label: repo for repo, label in MODEL_LABELS.items()}.get(value, value)
    if "://" in value:
        url = urlsplit(value)
        if url.scheme != "https" or url.netloc != "huggingface.co":
            raise ValueError("Enter a Hugging Face model repository URL or owner/model.")
        parts = url.path.strip("/").split("/")
        if parts[0] in ("spaces", "datasets") or len(parts) != 2:
            raise ValueError("Use the model's main repository URL, without a file path.")
        value = "/".join(parts)
    validate_repo_id(value)
    return value


class ModelStore:
    def __init__(self):
        self.model = self.tokenizer = None
        self.key = ""
        self.projection = None
        self.attention_modules = []
        self.description = "No model loaded."
        self.english_prior = None

    def load(self, value):
        repo = repository(value)
        info = HfApi().model_info(repo, files_metadata=True, token=False)
        if info.private or info.gated:
            raise ValueError("This version supports public, ungated models.")
        patterns = ["*.json", "*.safetensors", "*.model", "*.txt", "*.tiktoken"]
        import fnmatch
        files = [f for f in info.siblings if any(fnmatch.fnmatch(f.rfilename, p) for p in patterns)
                 and "/" not in f.rfilename]
        if not any(f.rfilename.endswith(".safetensors") for f in files):
            raise ValueError("Choose a model with safetensors weights. GGUF is not supported yet.")
        size = sum(f.size or 0 for f in files)
        if any(f.size is None for f in files):
            raise ValueError("Cannot determine the model download size.")
        max_bytes = float(os.environ.get("FLOW_MAX_DOWNLOAD_GB", "8" if ZERO_GPU else "2")) * 1024**3
        if size > max_bytes:
            raise ValueError(f"Download is {size / 1024**3:.2f} GB; the limit is {max_bytes / 1024**3:g} GB.")
        CACHE.mkdir(exist_ok=True)
        if shutil.disk_usage(CACHE).free < size + 1024**3:
            raise ValueError("Insufficient disk space; leave at least 1 GB free after download.")
        config = AutoConfig.from_pretrained(repo, revision=info.sha, token=False,
                                            trust_remote_code=False, cache_dir=CACHE)
        if getattr(config, "is_encoder_decoder", False):
            raise ValueError("Choose a decoder-only text-generation model.")
        # Release the previous model before allocating the next one.
        self.model = self.tokenizer = None
        self.projection = None
        self.attention_modules = []
        self.key = ""
        gc.collect()
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
        path = snapshot_download(repo, revision=info.sha, token=False, cache_dir=CACHE,
                                 allow_patterns=[f.rfilename for f in files])
        tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=False)
        compute_dtype = (torch.bfloat16 if str(config.model_type).startswith("gemma") else torch.float16) if ZERO_GPU else torch.float32
        model = AutoModelForCausalLM.from_pretrained(path, config=config, use_safetensors=True,
                                                    trust_remote_code=False, torch_dtype=compute_dtype,
                                                    attn_implementation="eager")
        model.eval()
        from engine import start_id
        initial = start_id(model, tokenizer)
        from token_space import TokenProjection
        self.projection = TokenProjection(model.get_input_embeddings().weight)
        if ZERO_GPU or torch.cuda.is_available():
            model = model.to(device="cuda", dtype=compute_dtype if ZERO_GPU else torch.float16)
            self.projection.weights = model.get_input_embeddings().weight
        from english_bias import build_prior
        self.english_prior = build_prior(tokenizer, model.get_output_embeddings().weight.shape[0])
        self.model, self.tokenizer = model, tokenizer
        from attention_view import attention_modules
        self.attention_modules = attention_modules(model)
        self.key = f"{repo}@{info.sha}"
        device = "GPU" if torch.cuda.is_available() else "CPU"
        self.description = (f"{repo} · {info.sha[:8]} · {device} · "
                            f"{size / 1024**2:.0f} MB download · starting token ID {initial} · "
                            f"{len(self.attention_modules)} attention layers · "
                            f"{getattr(config, 'num_attention_heads', '?')} heads")
        return self.description