File size: 2,489 Bytes
f048c45 | 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 | """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
|