Upload 13 files
Browse files- ADD_PRETRAINED_VIT_HERE.txt +1 -0
- ADD_TERRA_2_5_HF_WEIGHTS_HERE.txt +1 -0
- README.md +104 -3
- __init__.py +5 -0
- chat.py +72 -0
- loading.py +63 -0
- model.py +185 -0
- model.safetensors +3 -0
- package_hf.py +149 -0
- requirements-dev.txt +2 -0
- requirements.txt +3 -0
- test_terra_vision.py +120 -0
- train_adapter.py +181 -0
ADD_PRETRAINED_VIT_HERE.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Place a pretrained Transformers ViT checkpoint here, or pass another local directory to --vision-dir.
|
ADD_TERRA_2_5_HF_WEIGHTS_HERE.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Extract Terra 2.5 HF files into this directory. Required: config.json, tokenizer files, and model.safetensors (or equivalent).
|
README.md
CHANGED
|
@@ -1,3 +1,104 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Terra 2.5 Vision
|
| 2 |
+
|
| 3 |
+
This code uses the **existing Terra 2.5 350M text checkpoint from this
|
| 4 |
+
repository** as its language model and adds an image encoder plus a trainable
|
| 5 |
+
visual projector. It does not replace or alter Terra's released text weights.
|
| 6 |
+
|
| 7 |
+
A text checkpoint has no image knowledge or image-processing layers. The
|
| 8 |
+
released Terra ZIP is a `GPT2LMHeadModel` text model, so image understanding
|
| 9 |
+
requires a separate pretrained vision encoder and training the connector on
|
| 10 |
+
image/question/answer examples. The files here implement that real integration;
|
| 11 |
+
the adapter checkpoint must be trained before image answers are meaningful.
|
| 12 |
+
|
| 13 |
+
## 1. Install and prepare checkpoints
|
| 14 |
+
|
| 15 |
+
Python 3.10+, PyTorch 2.2+, Transformers 4.44+, Pillow 10+:
|
| 16 |
+
|
| 17 |
+
```bash
|
| 18 |
+
python -m pip install -r terra_vision/requirements.txt
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
Extract `terra-2.5-350m-hf.zip` from this repository's GitHub Release on your
|
| 22 |
+
machine. Also prepare a Transformers-compatible ViT checkpoint, e.g.
|
| 23 |
+
`google/vit-base-patch16-224-in21k`; it must return `last_hidden_state` from
|
| 24 |
+
`AutoModel`. You can pass local directories for offline use. The code defaults
|
| 25 |
+
to `local_files_only=True`, and only downloads models when `--allow-download`
|
| 26 |
+
is explicitly supplied.
|
| 27 |
+
|
| 28 |
+
## 2. Train the vision connector
|
| 29 |
+
|
| 30 |
+
Prepare licensed image/question/answer training examples as JSON Lines. Each
|
| 31 |
+
image path is relative to `--image-root`:
|
| 32 |
+
|
| 33 |
+
```json
|
| 34 |
+
{"image":"train/cat-001.jpg","question":"Что изображено на картинке?","answer":"На картинке кошка."}
|
| 35 |
+
{"image":"train/street-002.jpg","question":"How many cars are visible?","answer":"There are two cars."}
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
Then run from the repository root:
|
| 39 |
+
|
| 40 |
+
```bash
|
| 41 |
+
python -m terra_vision.train_adapter \
|
| 42 |
+
--terra-dir /models/terra-2.5-350m \
|
| 43 |
+
--vision-dir /models/vit-base-patch16-224-in21k \
|
| 44 |
+
--manifest /data/train.jsonl \
|
| 45 |
+
--image-root /data \
|
| 46 |
+
--output /models/terra-vision-projector.pt \
|
| 47 |
+
--epochs 3 --batch-size 1 --device cuda
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
The released Terra language model and ViT are frozen; only the visual projector
|
| 51 |
+
is trained. This preserves the existing model weights and lowers optimizer
|
| 52 |
+
memory, but still requires backpropagating through Terra. Use a properly varied,
|
| 53 |
+
licensed dataset and held-out validation before claiming quality. The script
|
| 54 |
+
writes a projector state dict and a companion JSON metadata file; neither is
|
| 55 |
+
included in Git.
|
| 56 |
+
|
| 57 |
+
## 3. Ask a question about an image
|
| 58 |
+
|
| 59 |
+
```bash
|
| 60 |
+
python -m terra_vision.chat \
|
| 61 |
+
--terra-dir /models/terra-2.5-350m \
|
| 62 |
+
--vision-dir /models/vit-base-patch16-224-in21k \
|
| 63 |
+
--adapter /models/terra-vision-projector.pt \
|
| 64 |
+
--image /data/test.jpg \
|
| 65 |
+
--question "Что изображено на картинке?" \
|
| 66 |
+
--max-new-tokens 64 --device cuda
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
The inference path preprocesses the image with the ViT's own image processor,
|
| 70 |
+
projects its visual features into 32 learned prefix embeddings, and calls the
|
| 71 |
+
Terra model's `generate()` method. The prefix consumes 32 positions from
|
| 72 |
+
Terra's 256-token context; generation is capped to the remaining context.
|
| 73 |
+
|
| 74 |
+
## 4. Build the Hugging Face upload folder and ZIP
|
| 75 |
+
|
| 76 |
+
After training, create a complete bundle containing Terra weights, ViT weights,
|
| 77 |
+
the processor, trained projector, source, config, model card, and checksums:
|
| 78 |
+
|
| 79 |
+
```bash
|
| 80 |
+
python -m terra_vision.package_hf \
|
| 81 |
+
--terra-dir /models/terra-2.5-350m \
|
| 82 |
+
--vision-dir /models/vit-base-patch16-224-in21k \
|
| 83 |
+
--adapter /models/terra-vision-projector.pt \
|
| 84 |
+
--output-dir /models/terra-2.5-vision-hf \
|
| 85 |
+
--zip /models/terra-2.5-vision-hf.zip
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
The output directory is suitable for uploading as a Hugging Face model
|
| 89 |
+
repository. The script refuses to package a missing or mismatched trained
|
| 90 |
+
adapter; it does not put random projector weights in a release.
|
| 91 |
+
|
| 92 |
+
## Current scope and validation
|
| 93 |
+
|
| 94 |
+
This is the first multimodal training/inference and packaging path, not an
|
| 95 |
+
officially released or benchmarked Terra Vision checkpoint. Image understanding
|
| 96 |
+
quality depends on the encoder and adapter training data. No vision weights or
|
| 97 |
+
image dataset are bundled. Generation uses Transformers' `inputs_embeds` path;
|
| 98 |
+
run the included tests in the pinned environment and smoke-test against the
|
| 99 |
+
actual extracted Terra checkpoint before deployment.
|
| 100 |
+
|
| 101 |
+
```bash
|
| 102 |
+
python -m pip install -r terra_vision/requirements-dev.txt
|
| 103 |
+
python -m pytest tests/test_terra_vision.py -q
|
| 104 |
+
```
|
__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Experimental image-conditioning components for Terra 2.5."""
|
| 2 |
+
|
| 3 |
+
from .model import TerraVisionModel
|
| 4 |
+
|
| 5 |
+
__all__ = ["TerraVisionModel"]
|
chat.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Image-question answering with an extracted Terra ZIP and a trained adapter."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from PIL import Image
|
| 10 |
+
|
| 11 |
+
from .loading import load_terra_vision
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def main() -> None:
|
| 15 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 16 |
+
parser.add_argument("--terra-dir", required=True, help="Folder containing Terra HF config and weights")
|
| 17 |
+
parser.add_argument("--vision-dir", required=True, help="Local pretrained ViT directory or Hub ID")
|
| 18 |
+
parser.add_argument("--adapter", required=True, help="Projector checkpoint created by train_adapter")
|
| 19 |
+
parser.add_argument("--image", required=True, type=Path)
|
| 20 |
+
parser.add_argument("--question", required=True)
|
| 21 |
+
parser.add_argument("--image-tokens", type=int, default=32)
|
| 22 |
+
parser.add_argument("--max-new-tokens", type=int, default=64)
|
| 23 |
+
parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
|
| 24 |
+
parser.add_argument("--dtype", choices=("auto", "float32", "float16", "bfloat16"), default="auto")
|
| 25 |
+
parser.add_argument("--allow-download", action="store_true", help="Allow Transformers to fetch model files")
|
| 26 |
+
args = parser.parse_args()
|
| 27 |
+
if args.max_new_tokens < 1:
|
| 28 |
+
parser.error("--max-new-tokens must be positive")
|
| 29 |
+
|
| 30 |
+
model, tokenizer, processor = load_terra_vision(
|
| 31 |
+
args.terra_dir,
|
| 32 |
+
args.vision_dir,
|
| 33 |
+
image_token_count=args.image_tokens,
|
| 34 |
+
local_files_only=not args.allow_download,
|
| 35 |
+
torch_dtype=args.dtype,
|
| 36 |
+
)
|
| 37 |
+
metadata_path = Path(str(args.adapter) + ".json")
|
| 38 |
+
if not metadata_path.is_file():
|
| 39 |
+
raise FileNotFoundError(f"Missing adapter metadata file: {metadata_path}")
|
| 40 |
+
adapter_metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
|
| 41 |
+
if adapter_metadata.get("image_token_count") != args.image_tokens:
|
| 42 |
+
raise ValueError("--image-tokens does not match the adapter metadata")
|
| 43 |
+
adapter_state = torch.load(args.adapter, map_location="cpu", weights_only=True)
|
| 44 |
+
model.projector.load_state_dict(adapter_state, strict=True)
|
| 45 |
+
device = torch.device(args.device)
|
| 46 |
+
model.to(device).eval()
|
| 47 |
+
|
| 48 |
+
image = Image.open(args.image).convert("RGB")
|
| 49 |
+
pixel_values = processor(images=image, return_tensors="pt").pixel_values.to(device)
|
| 50 |
+
question = args.question.strip()
|
| 51 |
+
if any("\u3400" <= ch <= "\u9fff" for ch in question):
|
| 52 |
+
prompt = f"问题:{question}\n回答:"
|
| 53 |
+
elif any("\u0400" <= ch <= "\u04ff" for ch in question):
|
| 54 |
+
prompt = f"Вопрос: {question}\nОтвет:"
|
| 55 |
+
else:
|
| 56 |
+
prompt = f"Question: {question}\nAnswer:"
|
| 57 |
+
input_ids = tokenizer(prompt, return_tensors="pt", add_special_tokens=False).input_ids.to(device)
|
| 58 |
+
eos_id = tokenizer.eos_token_id
|
| 59 |
+
pad_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else eos_id
|
| 60 |
+
generated = model.generate(
|
| 61 |
+
pixel_values=pixel_values,
|
| 62 |
+
input_ids=input_ids,
|
| 63 |
+
max_new_tokens=args.max_new_tokens,
|
| 64 |
+
do_sample=False,
|
| 65 |
+
eos_token_id=eos_id,
|
| 66 |
+
pad_token_id=pad_id,
|
| 67 |
+
)
|
| 68 |
+
print(tokenizer.decode(generated[0], skip_special_tokens=True).strip())
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
if __name__ == "__main__":
|
| 72 |
+
main()
|
loading.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Explicit loaders for the released Terra text model and a local ViT encoder."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
from .model import TerraVisionModel
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def load_terra_vision(
|
| 13 |
+
terra_dir: str | Path,
|
| 14 |
+
vision_model_id: str | Path,
|
| 15 |
+
*,
|
| 16 |
+
image_token_count: int = 32,
|
| 17 |
+
local_files_only: bool = True,
|
| 18 |
+
torch_dtype: Any = "auto",
|
| 19 |
+
freeze_vision: bool = True,
|
| 20 |
+
freeze_text: bool = True,
|
| 21 |
+
):
|
| 22 |
+
"""Load Terra 2.5 plus a pretrained Transformers vision encoder.
|
| 23 |
+
|
| 24 |
+
``vision_model_id`` must identify a model whose ``AutoModel`` output has a
|
| 25 |
+
``last_hidden_state``. A ViT checkpoint is the tested architecture target.
|
| 26 |
+
No network access is attempted unless ``local_files_only=False`` is passed.
|
| 27 |
+
"""
|
| 28 |
+
try:
|
| 29 |
+
from transformers import AutoImageProcessor, AutoModel, AutoModelForCausalLM, AutoTokenizer
|
| 30 |
+
except ImportError as exc: # pragma: no cover - exercised in dependency-light installs
|
| 31 |
+
raise RuntimeError("Install terra_vision/requirements.txt to load HF models") from exc
|
| 32 |
+
|
| 33 |
+
if isinstance(torch_dtype, str) and torch_dtype != "auto":
|
| 34 |
+
try:
|
| 35 |
+
torch_dtype = getattr(torch, torch_dtype)
|
| 36 |
+
except AttributeError as exc:
|
| 37 |
+
raise ValueError("torch_dtype must be 'auto', 'float32', 'float16', or 'bfloat16'") from exc
|
| 38 |
+
text_model = AutoModelForCausalLM.from_pretrained(
|
| 39 |
+
str(terra_dir), local_files_only=local_files_only, torch_dtype=torch_dtype
|
| 40 |
+
)
|
| 41 |
+
tokenizer = AutoTokenizer.from_pretrained(str(terra_dir), local_files_only=local_files_only)
|
| 42 |
+
vision_model = AutoModel.from_pretrained(
|
| 43 |
+
str(vision_model_id), local_files_only=local_files_only
|
| 44 |
+
)
|
| 45 |
+
image_processor = AutoImageProcessor.from_pretrained(
|
| 46 |
+
str(vision_model_id), local_files_only=local_files_only
|
| 47 |
+
)
|
| 48 |
+
vision_config = getattr(vision_model.config, "vision_config", vision_model.config)
|
| 49 |
+
vision_width = getattr(vision_config, "hidden_size", None)
|
| 50 |
+
if vision_width is None:
|
| 51 |
+
vision_width = getattr(vision_config, "embed_dim", None)
|
| 52 |
+
if vision_width is None:
|
| 53 |
+
raise ValueError("Cannot infer vision width; configure an encoder with hidden_size")
|
| 54 |
+
|
| 55 |
+
model = TerraVisionModel(
|
| 56 |
+
text_model,
|
| 57 |
+
vision_model,
|
| 58 |
+
vision_width=int(vision_width),
|
| 59 |
+
image_token_count=image_token_count,
|
| 60 |
+
freeze_vision=freeze_vision,
|
| 61 |
+
freeze_text=freeze_text,
|
| 62 |
+
)
|
| 63 |
+
return model, tokenizer, image_processor
|
model.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Experimental image-prefix adapter for the Terra 2.5 causal LM.
|
| 2 |
+
|
| 3 |
+
The text model and vision encoder are injected by the caller so this module does
|
| 4 |
+
not silently download checkpoints or require a particular Transformers class.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from torch import nn
|
| 12 |
+
from torch.nn import functional as F
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class TerraVisionModel(nn.Module):
|
| 16 |
+
"""Condition a causal language model on an image using projected visual tokens.
|
| 17 |
+
|
| 18 |
+
The vision encoder must return ``last_hidden_state`` shaped ``(batch, tokens,
|
| 19 |
+
vision_width)``. Its sequence is adaptively pooled to ``image_token_count``
|
| 20 |
+
tokens, projected to the language model's embedding width, and prepended to
|
| 21 |
+
the text embeddings. Image and prompt positions are ignored by the LM loss;
|
| 22 |
+
only the caller-provided text labels contribute to training.
|
| 23 |
+
|
| 24 |
+
This is a simple, auditable baseline, not a pretrained Terra vision model.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
text_model: nn.Module,
|
| 30 |
+
vision_model: nn.Module,
|
| 31 |
+
vision_width: int,
|
| 32 |
+
image_token_count: int = 32,
|
| 33 |
+
freeze_vision: bool = True,
|
| 34 |
+
freeze_text: bool = True,
|
| 35 |
+
) -> None:
|
| 36 |
+
super().__init__()
|
| 37 |
+
if vision_width < 1:
|
| 38 |
+
raise ValueError("vision_width must be positive")
|
| 39 |
+
if image_token_count < 1:
|
| 40 |
+
raise ValueError("image_token_count must be positive")
|
| 41 |
+
if not hasattr(text_model, "get_input_embeddings"):
|
| 42 |
+
raise TypeError("text_model must expose get_input_embeddings()")
|
| 43 |
+
embeddings = text_model.get_input_embeddings()
|
| 44 |
+
if embeddings is None or not hasattr(embeddings, "embedding_dim"):
|
| 45 |
+
raise TypeError("text_model input embeddings must expose embedding_dim")
|
| 46 |
+
|
| 47 |
+
self.text_model = text_model
|
| 48 |
+
self.vision_model = vision_model
|
| 49 |
+
self.image_token_count = image_token_count
|
| 50 |
+
self.freeze_vision = freeze_vision
|
| 51 |
+
self.freeze_text = freeze_text
|
| 52 |
+
self.projector = nn.Sequential(
|
| 53 |
+
nn.LayerNorm(vision_width),
|
| 54 |
+
nn.Linear(vision_width, embeddings.embedding_dim),
|
| 55 |
+
)
|
| 56 |
+
if freeze_vision:
|
| 57 |
+
self.vision_model.requires_grad_(False)
|
| 58 |
+
self.vision_model.eval()
|
| 59 |
+
if freeze_text:
|
| 60 |
+
self.text_model.requires_grad_(False)
|
| 61 |
+
self.text_model.eval()
|
| 62 |
+
|
| 63 |
+
def train(self, mode: bool = True) -> "TerraVisionModel":
|
| 64 |
+
super().train(mode)
|
| 65 |
+
if self.freeze_vision:
|
| 66 |
+
self.vision_model.eval()
|
| 67 |
+
if self.freeze_text:
|
| 68 |
+
self.text_model.eval()
|
| 69 |
+
return self
|
| 70 |
+
|
| 71 |
+
def _encode_image(self, pixel_values: torch.Tensor) -> torch.Tensor:
|
| 72 |
+
if pixel_values.ndim != 4:
|
| 73 |
+
raise ValueError("pixel_values must have shape (batch, channels, height, width)")
|
| 74 |
+
if self.freeze_vision:
|
| 75 |
+
with torch.no_grad():
|
| 76 |
+
vision_output = self.vision_model(pixel_values=pixel_values)
|
| 77 |
+
else:
|
| 78 |
+
vision_output = self.vision_model(pixel_values=pixel_values)
|
| 79 |
+
|
| 80 |
+
hidden = getattr(vision_output, "last_hidden_state", None)
|
| 81 |
+
if not isinstance(hidden, torch.Tensor) or hidden.ndim != 3:
|
| 82 |
+
raise ValueError("vision_model must return last_hidden_state with shape (batch, tokens, width)")
|
| 83 |
+
if hidden.shape[0] != pixel_values.shape[0]:
|
| 84 |
+
raise ValueError("vision_model changed the image batch size")
|
| 85 |
+
if hidden.shape[-1] != self.projector[0].normalized_shape[0]:
|
| 86 |
+
raise ValueError("vision output width does not match vision_width")
|
| 87 |
+
# Pool over the sequence axis, not the feature axis. Works for both CLS
|
| 88 |
+
# token based encoders and patch-only encoders, and stays differentiable.
|
| 89 |
+
pooled = F.adaptive_avg_pool1d(
|
| 90 |
+
hidden.transpose(1, 2), output_size=self.image_token_count
|
| 91 |
+
).transpose(1, 2)
|
| 92 |
+
projector_dtype = self.projector[0].weight.dtype
|
| 93 |
+
return self.projector(pooled.to(dtype=projector_dtype))
|
| 94 |
+
|
| 95 |
+
def _prepare_multimodal_inputs(
|
| 96 |
+
self,
|
| 97 |
+
pixel_values: torch.Tensor,
|
| 98 |
+
input_ids: torch.Tensor,
|
| 99 |
+
attention_mask: torch.Tensor | None,
|
| 100 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 101 |
+
if input_ids.ndim != 2:
|
| 102 |
+
raise ValueError("input_ids must have shape (batch, sequence)")
|
| 103 |
+
if pixel_values.ndim != 4 or pixel_values.shape[0] != input_ids.shape[0]:
|
| 104 |
+
raise ValueError("pixel_values must be rank 4 and image/text batch sizes must match")
|
| 105 |
+
if attention_mask is not None and attention_mask.shape != input_ids.shape:
|
| 106 |
+
raise ValueError("attention_mask must have the same shape as input_ids")
|
| 107 |
+
text_embeddings = self.text_model.get_input_embeddings()(input_ids)
|
| 108 |
+
image_embeddings = self._encode_image(pixel_values).to(
|
| 109 |
+
device=text_embeddings.device, dtype=text_embeddings.dtype
|
| 110 |
+
)
|
| 111 |
+
inputs_embeds = torch.cat((image_embeddings, text_embeddings), dim=1)
|
| 112 |
+
if attention_mask is None:
|
| 113 |
+
attention_mask = torch.ones_like(input_ids)
|
| 114 |
+
image_mask = torch.ones(
|
| 115 |
+
(input_ids.shape[0], self.image_token_count),
|
| 116 |
+
dtype=attention_mask.dtype,
|
| 117 |
+
device=attention_mask.device,
|
| 118 |
+
)
|
| 119 |
+
combined_attention_mask = torch.cat((image_mask, attention_mask), dim=1)
|
| 120 |
+
return inputs_embeds, combined_attention_mask
|
| 121 |
+
|
| 122 |
+
def forward(
|
| 123 |
+
self,
|
| 124 |
+
pixel_values: torch.Tensor,
|
| 125 |
+
input_ids: torch.Tensor,
|
| 126 |
+
attention_mask: torch.Tensor | None = None,
|
| 127 |
+
labels: torch.Tensor | None = None,
|
| 128 |
+
**text_model_kwargs: Any,
|
| 129 |
+
) -> Any:
|
| 130 |
+
if labels is not None and labels.shape != input_ids.shape:
|
| 131 |
+
raise ValueError("labels must have the same shape as input_ids")
|
| 132 |
+
inputs_embeds, combined_attention_mask = self._prepare_multimodal_inputs(
|
| 133 |
+
pixel_values, input_ids, attention_mask
|
| 134 |
+
)
|
| 135 |
+
combined_labels = None
|
| 136 |
+
if labels is not None:
|
| 137 |
+
ignored_image_labels = torch.full(
|
| 138 |
+
(labels.shape[0], self.image_token_count),
|
| 139 |
+
-100,
|
| 140 |
+
dtype=labels.dtype,
|
| 141 |
+
device=labels.device,
|
| 142 |
+
)
|
| 143 |
+
combined_labels = torch.cat((ignored_image_labels, labels), dim=1)
|
| 144 |
+
return self.text_model(
|
| 145 |
+
inputs_embeds=inputs_embeds,
|
| 146 |
+
attention_mask=combined_attention_mask,
|
| 147 |
+
labels=combined_labels,
|
| 148 |
+
**text_model_kwargs,
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
@torch.inference_mode()
|
| 152 |
+
def generate(
|
| 153 |
+
self,
|
| 154 |
+
pixel_values: torch.Tensor,
|
| 155 |
+
input_ids: torch.Tensor,
|
| 156 |
+
attention_mask: torch.Tensor | None = None,
|
| 157 |
+
**generation_kwargs: Any,
|
| 158 |
+
) -> torch.Tensor:
|
| 159 |
+
"""Generate continuation token IDs from image and text prompt.
|
| 160 |
+
|
| 161 |
+
Transformers' decoder-only generation returns newly generated IDs when
|
| 162 |
+
bootstrapped from ``inputs_embeds``. Use a Transformers version tested
|
| 163 |
+
with the chosen text model and pass generation settings such as
|
| 164 |
+
``max_new_tokens`` and ``eos_token_id`` explicitly.
|
| 165 |
+
"""
|
| 166 |
+
if not hasattr(self.text_model, "generate"):
|
| 167 |
+
raise TypeError("wrapped text_model must implement generate()")
|
| 168 |
+
inputs_embeds, combined_attention_mask = self._prepare_multimodal_inputs(
|
| 169 |
+
pixel_values, input_ids, attention_mask
|
| 170 |
+
)
|
| 171 |
+
config = getattr(self.text_model, "config", None)
|
| 172 |
+
context_limit = getattr(config, "max_position_embeddings", None)
|
| 173 |
+
if context_limit is None:
|
| 174 |
+
context_limit = getattr(config, "n_positions", None)
|
| 175 |
+
prompt_length = inputs_embeds.shape[1]
|
| 176 |
+
if context_limit is not None:
|
| 177 |
+
if prompt_length >= context_limit:
|
| 178 |
+
raise ValueError("image and prompt consume the full model context")
|
| 179 |
+
requested = generation_kwargs.get("max_new_tokens", 32)
|
| 180 |
+
generation_kwargs["max_new_tokens"] = min(requested, context_limit - prompt_length)
|
| 181 |
+
return self.text_model.generate(
|
| 182 |
+
inputs_embeds=inputs_embeds,
|
| 183 |
+
attention_mask=combined_attention_mask,
|
| 184 |
+
**generation_kwargs,
|
| 185 |
+
)
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:28fd4efa0e724ca0e3d0e040455f17442673efaf37f450a8c13f8ca812cacb29
|
| 3 |
+
size 700079760
|
package_hf.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build a Hugging Face upload folder and ZIP from trained local checkpoints."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
import shutil
|
| 8 |
+
import zipfile
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
from .loading import load_terra_vision
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def sha256(path: Path) -> str:
|
| 17 |
+
digest = hashlib.sha256()
|
| 18 |
+
with path.open("rb") as stream:
|
| 19 |
+
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
| 20 |
+
digest.update(chunk)
|
| 21 |
+
return digest.hexdigest()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def main() -> None:
|
| 25 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 26 |
+
parser.add_argument("--terra-dir", required=True, help="Extracted Terra 2.5 HF checkpoint")
|
| 27 |
+
parser.add_argument("--vision-dir", required=True, help="Local pretrained ViT checkpoint")
|
| 28 |
+
parser.add_argument("--adapter", required=True, type=Path, help="Trained projector state_dict")
|
| 29 |
+
parser.add_argument("--output-dir", required=True, type=Path, help="New folder for the HF repository")
|
| 30 |
+
parser.add_argument("--zip", required=True, type=Path, help="Output ZIP path")
|
| 31 |
+
parser.add_argument("--image-tokens", type=int, default=32)
|
| 32 |
+
parser.add_argument("--dtype", choices=("auto", "float32", "float16", "bfloat16"), default="auto")
|
| 33 |
+
args = parser.parse_args()
|
| 34 |
+
if args.output_dir.exists():
|
| 35 |
+
parser.error(f"output-dir already exists; choose a new path: {args.output_dir}")
|
| 36 |
+
if args.zip.exists():
|
| 37 |
+
parser.error(f"ZIP already exists; choose a new path: {args.zip}")
|
| 38 |
+
if args.zip.resolve().is_relative_to(args.output_dir.resolve()):
|
| 39 |
+
parser.error("ZIP must be outside output-dir")
|
| 40 |
+
|
| 41 |
+
metadata_path = Path(str(args.adapter) + ".json")
|
| 42 |
+
if not metadata_path.is_file():
|
| 43 |
+
parser.error(f"missing adapter metadata: {metadata_path}")
|
| 44 |
+
adapter_metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
|
| 45 |
+
if adapter_metadata.get("image_token_count") != args.image_tokens:
|
| 46 |
+
parser.error("--image-tokens does not match the trained adapter metadata")
|
| 47 |
+
|
| 48 |
+
model, tokenizer, processor = load_terra_vision(
|
| 49 |
+
args.terra_dir,
|
| 50 |
+
args.vision_dir,
|
| 51 |
+
image_token_count=args.image_tokens,
|
| 52 |
+
local_files_only=True,
|
| 53 |
+
torch_dtype=args.dtype,
|
| 54 |
+
freeze_vision=True,
|
| 55 |
+
freeze_text=True,
|
| 56 |
+
)
|
| 57 |
+
adapter_state = torch.load(args.adapter, map_location="cpu", weights_only=True)
|
| 58 |
+
model.projector.load_state_dict(adapter_state, strict=True)
|
| 59 |
+
|
| 60 |
+
root = args.output_dir
|
| 61 |
+
terra_out = root / "terra"
|
| 62 |
+
vision_out = root / "vision_encoder"
|
| 63 |
+
terra_out.mkdir(parents=True)
|
| 64 |
+
vision_out.mkdir(parents=True)
|
| 65 |
+
model.text_model.save_pretrained(terra_out, safe_serialization=True)
|
| 66 |
+
tokenizer.save_pretrained(terra_out)
|
| 67 |
+
model.vision_model.save_pretrained(vision_out, safe_serialization=True)
|
| 68 |
+
processor.save_pretrained(vision_out)
|
| 69 |
+
torch.save(
|
| 70 |
+
{key: value.detach().cpu() for key, value in model.projector.state_dict().items()},
|
| 71 |
+
root / "vision_projector.pt",
|
| 72 |
+
)
|
| 73 |
+
public_adapter_metadata = {
|
| 74 |
+
key: value for key, value in adapter_metadata.items()
|
| 75 |
+
if key not in {"terra_dir", "vision_dir"}
|
| 76 |
+
}
|
| 77 |
+
(root / "vision_projector.pt.json").write_text(
|
| 78 |
+
json.dumps(public_adapter_metadata, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
|
| 79 |
+
)
|
| 80 |
+
source_dir = Path(__file__).resolve().parent
|
| 81 |
+
package_dir = root / "terra_vision"
|
| 82 |
+
package_dir.mkdir()
|
| 83 |
+
for filename in ("__init__.py", "model.py", "loading.py"):
|
| 84 |
+
shutil.copy2(source_dir / filename, package_dir / filename)
|
| 85 |
+
|
| 86 |
+
config = {
|
| 87 |
+
"model_type": "terra_2_5_vision_adapter",
|
| 88 |
+
"base_model": "Terra 2.5 350M",
|
| 89 |
+
"text_model_path": "terra/",
|
| 90 |
+
"vision_encoder_path": "vision_encoder/",
|
| 91 |
+
"projector_path": "vision_projector.pt",
|
| 92 |
+
"image_token_count": args.image_tokens,
|
| 93 |
+
"text_model_parameters": sum(parameter.numel() for parameter in model.text_model.parameters()),
|
| 94 |
+
"vision_encoder_parameters": sum(parameter.numel() for parameter in model.vision_model.parameters()),
|
| 95 |
+
"projector_parameters": sum(parameter.numel() for parameter in model.projector.parameters()),
|
| 96 |
+
"trained_adapter_metadata": public_adapter_metadata,
|
| 97 |
+
"loading_note": "Load with terra_vision.loading.load_terra_vision, then load vision_projector.pt.",
|
| 98 |
+
}
|
| 99 |
+
(root / "terra_vision_config.json").write_text(
|
| 100 |
+
json.dumps(config, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
|
| 101 |
+
)
|
| 102 |
+
(root / "requirements.txt").write_text(
|
| 103 |
+
"torch>=2.2,<3\ntransformers>=4.44,<5\nPillow>=10,<13\n", encoding="utf-8"
|
| 104 |
+
)
|
| 105 |
+
(root / "README.md").write_text(
|
| 106 |
+
"---\n"
|
| 107 |
+
"language:\n- ru\n- en\n- zh\n"
|
| 108 |
+
"pipeline_tag: image-to-text\n"
|
| 109 |
+
"tags:\n- terra\n- vision\n- experimental\n"
|
| 110 |
+
"---\n\n"
|
| 111 |
+
"# Terra 2.5 Vision (experimental)\n\n"
|
| 112 |
+
"Terra 2.5 is the text decoder; the ViT encoder and learned projector add image conditioning. "
|
| 113 |
+
"This repository contains separate, standard Transformers checkpoints under `terra/` and "
|
| 114 |
+
"`vision_encoder/`, plus `vision_projector.pt`. It is not a single `AutoModel` architecture.\n\n"
|
| 115 |
+
"## Load locally\n\n"
|
| 116 |
+
"```python\n"
|
| 117 |
+
"import torch\nfrom PIL import Image\nfrom transformers import AutoTokenizer\n"
|
| 118 |
+
"from terra_vision.loading import load_terra_vision\n\n"
|
| 119 |
+
"model, tokenizer, processor = load_terra_vision(\n"
|
| 120 |
+
" 'terra', 'vision_encoder', image_token_count=" + str(args.image_tokens) + ", local_files_only=True\n)\n"
|
| 121 |
+
"state = torch.load('vision_projector.pt', map_location='cpu', weights_only=True)\n"
|
| 122 |
+
"model.projector.load_state_dict(state)\nmodel.eval()\n"
|
| 123 |
+
"image = Image.open('example.jpg').convert('RGB')\n"
|
| 124 |
+
"pixels = processor(images=image, return_tensors='pt').pixel_values\n"
|
| 125 |
+
"ids = tokenizer('Question: What is in the image?\\nAnswer:', return_tensors='pt').input_ids\n"
|
| 126 |
+
"result = model.generate(pixels, ids, max_new_tokens=48, do_sample=False,\n"
|
| 127 |
+
" eos_token_id=tokenizer.eos_token_id,\n"
|
| 128 |
+
" pad_token_id=(tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id))\n"
|
| 129 |
+
"print(tokenizer.decode(result[0], skip_special_tokens=True))\n``\n\n"
|
| 130 |
+
"Only publish this model if the adapter was trained and evaluated on appropriately licensed data. "
|
| 131 |
+
"The Terra 350M base is a text model; the image capability depends on the included ViT and trained projector.\n",
|
| 132 |
+
encoding="utf-8",
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
files = sorted(path for path in root.rglob("*") if path.is_file())
|
| 136 |
+
manifest = {path.relative_to(root).as_posix(): sha256(path) for path in files}
|
| 137 |
+
(root / "manifest.json").write_text(
|
| 138 |
+
json.dumps(manifest, indent=2) + "\n", encoding="utf-8"
|
| 139 |
+
)
|
| 140 |
+
args.zip.parent.mkdir(parents=True, exist_ok=True)
|
| 141 |
+
with zipfile.ZipFile(args.zip, "w", compression=zipfile.ZIP_STORED) as archive:
|
| 142 |
+
for path in sorted(root.rglob("*")):
|
| 143 |
+
if path.is_file():
|
| 144 |
+
archive.write(path, path.relative_to(root).as_posix())
|
| 145 |
+
print(json.dumps({"folder": str(root), "zip": str(args.zip), "files": len(manifest) + 1}, indent=2))
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
if __name__ == "__main__":
|
| 149 |
+
main()
|
requirements-dev.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-r requirements.txt
|
| 2 |
+
pytest>=8,<9
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.2,<3
|
| 2 |
+
transformers>=4.44,<5
|
| 3 |
+
Pillow>=10,<13
|
test_terra_vision.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from types import SimpleNamespace
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
|
| 7 |
+
from terra_vision import TerraVisionModel
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class FakeVision(nn.Module):
|
| 11 |
+
def __init__(self, width=6, tokens=5):
|
| 12 |
+
super().__init__()
|
| 13 |
+
self.width = width
|
| 14 |
+
self.tokens = tokens
|
| 15 |
+
self.projection = nn.Linear(3, width)
|
| 16 |
+
|
| 17 |
+
def forward(self, pixel_values):
|
| 18 |
+
pooled = pixel_values.mean(dim=(-2, -1))
|
| 19 |
+
token_features = self.projection(pooled).unsqueeze(1)
|
| 20 |
+
hidden = token_features.expand(-1, self.tokens, -1)
|
| 21 |
+
return SimpleNamespace(last_hidden_state=hidden)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class FakeCausalLM(nn.Module):
|
| 25 |
+
def __init__(self, vocab_size=19, width=8):
|
| 26 |
+
super().__init__()
|
| 27 |
+
self.embedding = nn.Embedding(vocab_size, width)
|
| 28 |
+
self.config = SimpleNamespace(n_positions=16)
|
| 29 |
+
self.seen = None
|
| 30 |
+
|
| 31 |
+
def get_input_embeddings(self):
|
| 32 |
+
return self.embedding
|
| 33 |
+
|
| 34 |
+
def forward(self, inputs_embeds, attention_mask, labels=None, **kwargs):
|
| 35 |
+
self.seen = {
|
| 36 |
+
"inputs_embeds": inputs_embeds,
|
| 37 |
+
"attention_mask": attention_mask,
|
| 38 |
+
"labels": labels,
|
| 39 |
+
"kwargs": kwargs,
|
| 40 |
+
}
|
| 41 |
+
return SimpleNamespace(loss=inputs_embeds.square().mean())
|
| 42 |
+
|
| 43 |
+
def generate(self, inputs_embeds, attention_mask, **kwargs):
|
| 44 |
+
self.seen = {
|
| 45 |
+
"inputs_embeds": inputs_embeds,
|
| 46 |
+
"attention_mask": attention_mask,
|
| 47 |
+
"kwargs": kwargs,
|
| 48 |
+
}
|
| 49 |
+
return torch.tensor([[7, 8]])
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def make_model(freeze_vision=True):
|
| 53 |
+
return TerraVisionModel(
|
| 54 |
+
text_model=FakeCausalLM(),
|
| 55 |
+
vision_model=FakeVision(),
|
| 56 |
+
vision_width=6,
|
| 57 |
+
image_token_count=3,
|
| 58 |
+
freeze_vision=freeze_vision,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_prepends_image_tokens_and_masks_image_loss():
|
| 63 |
+
model = make_model()
|
| 64 |
+
pixel_values = torch.randn(2, 3, 8, 8)
|
| 65 |
+
input_ids = torch.tensor([[1, 2, 3, 0], [4, 5, 0, 0]])
|
| 66 |
+
attention_mask = torch.tensor([[1, 1, 1, 0], [1, 1, 0, 0]])
|
| 67 |
+
labels = torch.tensor([[-100, -100, 3, -100], [-100, 5, -100, -100]])
|
| 68 |
+
|
| 69 |
+
model(pixel_values, input_ids, attention_mask=attention_mask, labels=labels)
|
| 70 |
+
seen = model.text_model.seen
|
| 71 |
+
|
| 72 |
+
assert seen["inputs_embeds"].shape == (2, 7, 8)
|
| 73 |
+
assert torch.equal(
|
| 74 |
+
seen["attention_mask"],
|
| 75 |
+
torch.tensor([[1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0, 0]]),
|
| 76 |
+
)
|
| 77 |
+
assert torch.equal(seen["labels"][:, :3], torch.full((2, 3), -100))
|
| 78 |
+
assert torch.equal(seen["labels"][:, 3:], labels)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def test_frozen_vision_encoder_stays_eval_but_projector_trains():
|
| 82 |
+
model = make_model(freeze_vision=True)
|
| 83 |
+
model.train()
|
| 84 |
+
assert not model.vision_model.training
|
| 85 |
+
assert all(not parameter.requires_grad for parameter in model.vision_model.parameters())
|
| 86 |
+
assert not model.text_model.training
|
| 87 |
+
assert all(not parameter.requires_grad for parameter in model.text_model.parameters())
|
| 88 |
+
|
| 89 |
+
loss = model(torch.randn(1, 3, 8, 8), torch.tensor([[1, 2]])).loss
|
| 90 |
+
loss.backward()
|
| 91 |
+
assert all(parameter.grad is not None for parameter in model.projector.parameters())
|
| 92 |
+
assert all(parameter.grad is None for parameter in model.vision_model.parameters())
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def test_unfrozen_vision_encoder_receives_gradients():
|
| 96 |
+
model = make_model(freeze_vision=False)
|
| 97 |
+
model.train()
|
| 98 |
+
model(torch.randn(1, 3, 8, 8), torch.tensor([[1, 2]])).loss.backward()
|
| 99 |
+
assert any(parameter.grad is not None for parameter in model.vision_model.parameters())
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def test_generation_uses_visual_prefix_and_respects_context_budget():
|
| 103 |
+
model = make_model()
|
| 104 |
+
generated = model.generate(
|
| 105 |
+
torch.randn(1, 3, 8, 8),
|
| 106 |
+
torch.tensor([[1, 2]]),
|
| 107 |
+
max_new_tokens=30,
|
| 108 |
+
do_sample=False,
|
| 109 |
+
)
|
| 110 |
+
assert torch.equal(generated, torch.tensor([[7, 8]]))
|
| 111 |
+
assert model.text_model.seen["inputs_embeds"].shape == (1, 5, 8)
|
| 112 |
+
assert model.text_model.seen["kwargs"]["max_new_tokens"] == 11
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def test_rejects_mismatched_shapes_and_vision_width():
|
| 116 |
+
model = make_model()
|
| 117 |
+
with pytest.raises(ValueError, match="batch sizes"):
|
| 118 |
+
model(torch.randn(1, 3, 8, 8), torch.ones((2, 4), dtype=torch.long))
|
| 119 |
+
with pytest.raises(ValueError, match="vision_width"):
|
| 120 |
+
TerraVisionModel(FakeCausalLM(), FakeVision(width=7), vision_width=6)
|
train_adapter.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Train Terra's small visual projector on a local image/question/answer JSONL."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from PIL import Image
|
| 10 |
+
from torch.nn.utils.rnn import pad_sequence
|
| 11 |
+
from torch.utils.data import DataLoader, Dataset
|
| 12 |
+
|
| 13 |
+
from .loading import load_terra_vision
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def language(question: str) -> str:
|
| 17 |
+
if any("\u3400" <= ch <= "\u9fff" for ch in question):
|
| 18 |
+
return "zh"
|
| 19 |
+
if any("\u0400" <= ch <= "\u04ff" for ch in question):
|
| 20 |
+
return "ru"
|
| 21 |
+
return "en"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def format_prompt(question: str) -> str:
|
| 25 |
+
lang = language(question)
|
| 26 |
+
if lang == "ru":
|
| 27 |
+
return f"Вопрос: {question.strip()}\nОтвет:"
|
| 28 |
+
if lang == "zh":
|
| 29 |
+
return f"问题:{question.strip()}\n回答:"
|
| 30 |
+
return f"Question: {question.strip()}\nAnswer:"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class ImageQADataset(Dataset):
|
| 34 |
+
def __init__(self, manifest: Path, image_root: Path, tokenizer, processor, context_limit: int, image_tokens: int):
|
| 35 |
+
self.image_root = image_root.resolve()
|
| 36 |
+
self.tokenizer = tokenizer
|
| 37 |
+
self.processor = processor
|
| 38 |
+
self.context_limit = context_limit
|
| 39 |
+
self.image_tokens = image_tokens
|
| 40 |
+
self.rows = []
|
| 41 |
+
for line_number, line in enumerate(manifest.read_text(encoding="utf-8").splitlines(), 1):
|
| 42 |
+
if not line.strip():
|
| 43 |
+
continue
|
| 44 |
+
row = json.loads(line)
|
| 45 |
+
if not all(isinstance(row.get(key), str) and row[key].strip() for key in ("image", "question", "answer")):
|
| 46 |
+
raise ValueError(f"{manifest}:{line_number}: expected non-empty image, question, and answer")
|
| 47 |
+
image_path = (self.image_root / row["image"]).resolve()
|
| 48 |
+
if not image_path.is_relative_to(self.image_root):
|
| 49 |
+
raise ValueError(f"{manifest}:{line_number}: image path escapes image-root")
|
| 50 |
+
prompt_ids = tokenizer(format_prompt(row["question"]), add_special_tokens=False).input_ids
|
| 51 |
+
answer_ids = tokenizer(" " + row["answer"].strip(), add_special_tokens=False).input_ids
|
| 52 |
+
if tokenizer.eos_token_id is not None:
|
| 53 |
+
answer_ids.append(tokenizer.eos_token_id)
|
| 54 |
+
if len(prompt_ids) + len(answer_ids) + image_tokens > context_limit:
|
| 55 |
+
raise ValueError(f"{manifest}:{line_number}: text plus image prefix exceeds context limit")
|
| 56 |
+
self.rows.append((image_path, prompt_ids, answer_ids))
|
| 57 |
+
if not self.rows:
|
| 58 |
+
raise ValueError(f"No image QA examples in {manifest}")
|
| 59 |
+
|
| 60 |
+
def __len__(self):
|
| 61 |
+
return len(self.rows)
|
| 62 |
+
|
| 63 |
+
def __getitem__(self, index):
|
| 64 |
+
image_path, prompt_ids, answer_ids = self.rows[index]
|
| 65 |
+
with Image.open(image_path) as image:
|
| 66 |
+
pixels = self.processor(images=image.convert("RGB"), return_tensors="pt").pixel_values[0]
|
| 67 |
+
ids = torch.tensor(prompt_ids + answer_ids, dtype=torch.long)
|
| 68 |
+
labels = torch.tensor([-100] * len(prompt_ids) + answer_ids, dtype=torch.long)
|
| 69 |
+
return pixels, ids, labels
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def collate(rows, pad_token_id: int):
|
| 73 |
+
pixels, ids, labels = zip(*rows)
|
| 74 |
+
lengths = torch.tensor([item.numel() for item in ids], dtype=torch.long)
|
| 75 |
+
padded_ids = pad_sequence(ids, batch_first=True, padding_value=pad_token_id)
|
| 76 |
+
padded_labels = pad_sequence(labels, batch_first=True, padding_value=-100)
|
| 77 |
+
mask = torch.arange(padded_ids.shape[1]).unsqueeze(0) < lengths.unsqueeze(1)
|
| 78 |
+
return torch.stack(pixels), padded_ids, mask.long(), padded_labels
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def main() -> None:
|
| 82 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 83 |
+
parser.add_argument("--terra-dir", required=True, help="Folder containing extracted Terra HF model")
|
| 84 |
+
parser.add_argument("--vision-dir", required=True, help="Local pretrained ViT directory or Hub ID")
|
| 85 |
+
parser.add_argument("--manifest", required=True, type=Path, help="JSONL with image, question, answer fields")
|
| 86 |
+
parser.add_argument("--image-root", required=True, type=Path, help="Root directory for manifest image paths")
|
| 87 |
+
parser.add_argument("--output", required=True, type=Path, help="Projector state_dict output path")
|
| 88 |
+
parser.add_argument("--image-tokens", type=int, default=32)
|
| 89 |
+
parser.add_argument("--epochs", type=int, default=1)
|
| 90 |
+
parser.add_argument("--batch-size", type=int, default=1)
|
| 91 |
+
parser.add_argument("--learning-rate", type=float, default=1e-4)
|
| 92 |
+
parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
|
| 93 |
+
parser.add_argument("--dtype", choices=("auto", "float32", "float16", "bfloat16"), default="auto")
|
| 94 |
+
parser.add_argument("--allow-download", action="store_true", help="Allow Transformers to fetch model files")
|
| 95 |
+
args = parser.parse_args()
|
| 96 |
+
if min(args.epochs, args.batch_size, args.image_tokens) < 1 or args.learning_rate <= 0:
|
| 97 |
+
parser.error("epochs, batch-size, image-tokens and learning-rate must be positive")
|
| 98 |
+
|
| 99 |
+
model, tokenizer, processor = load_terra_vision(
|
| 100 |
+
args.terra_dir,
|
| 101 |
+
args.vision_dir,
|
| 102 |
+
image_token_count=args.image_tokens,
|
| 103 |
+
local_files_only=not args.allow_download,
|
| 104 |
+
torch_dtype=args.dtype,
|
| 105 |
+
freeze_vision=True,
|
| 106 |
+
freeze_text=True,
|
| 107 |
+
)
|
| 108 |
+
device = torch.device(args.device)
|
| 109 |
+
model.to(device)
|
| 110 |
+
if hasattr(model.text_model, "gradient_checkpointing_enable"):
|
| 111 |
+
model.text_model.gradient_checkpointing_enable(
|
| 112 |
+
gradient_checkpointing_kwargs={"use_reentrant": False}
|
| 113 |
+
)
|
| 114 |
+
model.text_model.config.use_cache = False
|
| 115 |
+
context_limit = getattr(model.text_model.config, "n_positions", None)
|
| 116 |
+
if context_limit is None:
|
| 117 |
+
context_limit = getattr(model.text_model.config, "max_position_embeddings", 256)
|
| 118 |
+
pad_id = tokenizer.pad_token_id
|
| 119 |
+
if pad_id is None:
|
| 120 |
+
pad_id = tokenizer.eos_token_id
|
| 121 |
+
dataset = ImageQADataset(
|
| 122 |
+
args.manifest, args.image_root, tokenizer, processor, context_limit, args.image_tokens
|
| 123 |
+
)
|
| 124 |
+
generator = torch.Generator().manual_seed(42)
|
| 125 |
+
loader = DataLoader(
|
| 126 |
+
dataset,
|
| 127 |
+
batch_size=args.batch_size,
|
| 128 |
+
shuffle=True,
|
| 129 |
+
generator=generator,
|
| 130 |
+
collate_fn=lambda rows: collate(rows, pad_id),
|
| 131 |
+
)
|
| 132 |
+
optimizer = torch.optim.AdamW(model.projector.parameters(), lr=args.learning_rate)
|
| 133 |
+
model.train()
|
| 134 |
+
step = 0
|
| 135 |
+
for epoch in range(args.epochs):
|
| 136 |
+
total_loss = 0.0
|
| 137 |
+
for pixels, input_ids, attention_mask, labels in loader:
|
| 138 |
+
pixels = pixels.to(device)
|
| 139 |
+
input_ids = input_ids.to(device)
|
| 140 |
+
attention_mask = attention_mask.to(device)
|
| 141 |
+
labels = labels.to(device)
|
| 142 |
+
optimizer.zero_grad(set_to_none=True)
|
| 143 |
+
output = model(
|
| 144 |
+
pixel_values=pixels,
|
| 145 |
+
input_ids=input_ids,
|
| 146 |
+
attention_mask=attention_mask,
|
| 147 |
+
labels=labels,
|
| 148 |
+
use_cache=False,
|
| 149 |
+
)
|
| 150 |
+
loss = output.loss
|
| 151 |
+
if not torch.isfinite(loss):
|
| 152 |
+
raise RuntimeError(f"Non-finite loss at step {step + 1}")
|
| 153 |
+
loss.backward()
|
| 154 |
+
torch.nn.utils.clip_grad_norm_(model.projector.parameters(), 1.0)
|
| 155 |
+
optimizer.step()
|
| 156 |
+
step += 1
|
| 157 |
+
total_loss += float(loss.detach())
|
| 158 |
+
print(json.dumps({"epoch": epoch + 1, "steps": step, "mean_loss": total_loss / len(loader)}), flush=True)
|
| 159 |
+
|
| 160 |
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
| 161 |
+
torch.save({key: value.detach().cpu() for key, value in model.projector.state_dict().items()}, args.output)
|
| 162 |
+
metadata = {
|
| 163 |
+
"terra_dir": str(args.terra_dir),
|
| 164 |
+
"vision_dir": str(args.vision_dir),
|
| 165 |
+
"image_token_count": args.image_tokens,
|
| 166 |
+
"training_examples": len(dataset),
|
| 167 |
+
"epochs": args.epochs,
|
| 168 |
+
"steps": step,
|
| 169 |
+
"learning_rate": args.learning_rate,
|
| 170 |
+
"vision_frozen": True,
|
| 171 |
+
"text_model_frozen": True,
|
| 172 |
+
"note": "Experimental projector only; this is not a standalone vision model.",
|
| 173 |
+
}
|
| 174 |
+
args.output.with_suffix(args.output.suffix + ".json").write_text(
|
| 175 |
+
json.dumps(metadata, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
|
| 176 |
+
)
|
| 177 |
+
print(f"Saved projector: {args.output}")
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
if __name__ == "__main__":
|
| 181 |
+
main()
|