Terra-2.5-Vision / loading.py
openmodelai's picture
Upload 13 files
f048c45 verified
Raw History Blame Contribute Delete
2.49 kB
"""Explicit loaders for the released Terra text model and a local ViT encoder."""
from __future__ import annotations
from pathlib import Path
from typing import Any
import torch
from .model import TerraVisionModel
def load_terra_vision(
terra_dir: str | Path,
vision_model_id: str | Path,
*,
image_token_count: int = 32,
local_files_only: bool = True,
torch_dtype: Any = "auto",
freeze_vision: bool = True,
freeze_text: bool = True,
):
"""Load Terra 2.5 plus a pretrained Transformers vision encoder.
``vision_model_id`` must identify a model whose ``AutoModel`` output has a
``last_hidden_state``. A ViT checkpoint is the tested architecture target.
No network access is attempted unless ``local_files_only=False`` is passed.
"""
try:
from transformers import AutoImageProcessor, AutoModel, AutoModelForCausalLM, AutoTokenizer
except ImportError as exc: # pragma: no cover - exercised in dependency-light installs
raise RuntimeError("Install terra_vision/requirements.txt to load HF models") from exc
if isinstance(torch_dtype, str) and torch_dtype != "auto":
try:
torch_dtype = getattr(torch, torch_dtype)
except AttributeError as exc:
raise ValueError("torch_dtype must be 'auto', 'float32', 'float16', or 'bfloat16'") from exc
text_model = AutoModelForCausalLM.from_pretrained(
str(terra_dir), local_files_only=local_files_only, torch_dtype=torch_dtype
)
tokenizer = AutoTokenizer.from_pretrained(str(terra_dir), local_files_only=local_files_only)
vision_model = AutoModel.from_pretrained(
str(vision_model_id), local_files_only=local_files_only
)
image_processor = AutoImageProcessor.from_pretrained(
str(vision_model_id), local_files_only=local_files_only
)
vision_config = getattr(vision_model.config, "vision_config", vision_model.config)
vision_width = getattr(vision_config, "hidden_size", None)
if vision_width is None:
vision_width = getattr(vision_config, "embed_dim", None)
if vision_width is None:
raise ValueError("Cannot infer vision width; configure an encoder with hidden_size")
model = TerraVisionModel(
text_model,
vision_model,
vision_width=int(vision_width),
image_token_count=image_token_count,
freeze_vision=freeze_vision,
freeze_text=freeze_text,
)
return model, tokenizer, image_processor