Upload 31 files
Browse filesFiles changed (31)
- .gitattributes+37-35
- README.md+73-1
- added_tokens.jsonAdded+40
- config.jsonAdded+13
- config.pyAdded+94
- configuration_moondream.pyAdded+96
- fourier_features.pyAdded+18
- generation_config.jsonAdded+4
- handler.pyAdded+58
- hf_moondream.pyAdded+183
- image_crops.pyAdded+231
- layers.pyAdded+166
- lora.pyAdded+82
- merges.txtAdded
- model.safetensorsAdded+3
- modeling_phi.pyAdded+1463
- moondream.pyAdded+986
- region.pyAdded+136
- region_model.pyAdded+43
- requirements.txtAdded+3
- rope.pyAdded+48
- special_tokens_map.jsonAdded+5
- text.pyAdded+221
- tokenizer.jsonAdded
- tokenizer_config.jsonAdded+323
- utils.pyAdded+41
- versions.txtAdded+12
- vision.pyAdded+147
- vision_encoder.pyAdded+325
- vocab.jsonAdded
- weights.pyAdded+292
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text12345678910111213141516171819202122232425262728293031323334353637*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textmoondream2-mmproj-f16.gguf filter=lfs diff=lfs merge=lfs -textmoondream2-text-model-f16.gguf filter=lfs diff=lfs merge=lfs -text
123---license: cc-by-nc-sa-4.0---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475---license: apache-2.0pipeline_tag: image-text-to-text---Moondream is a small vision language model designed to run efficiently everywhere.[Website](https://moondream.ai/) / [Demo](https://moondream.ai/playground) / [GitHub](https://github.com/vikhyat/moondream)This repository contains the latest (**2025-06-21**) release of Moondream, as well as [historical releases](https://huggingface.co/vikhyatk/moondream2/blob/main/versions.txt). The model is updated frequently, so we recommend specifying a revision as shown below if you're using it in a production application.### Usage```pythonfrom transformers import AutoModelForCausalLM, AutoTokenizerfrom PIL import Imagemodel = AutoModelForCausalLM.from_pretrained("vikhyatk/moondream2",revision="2025-06-21",trust_remote_code=True,# Uncomment to run on GPU.# device_map={"": "cuda"})# Captioningprint("Short caption:")print(model.caption(image, length="short")["caption"])print("\nNormal caption:")for t in model.caption(image, length="normal", stream=True)["caption"]:# Streaming generation example, supported for caption() and detect()print(t, end="", flush=True)print(model.caption(image, length="normal"))# Visual Queryingprint("\nVisual query: 'How many people are in the image?'")print(model.query(image, "How many people are in the image?")["answer"])# Object Detectionprint("\nObject detection: 'face'")objects = model.detect(image, "face")["objects"]print(f"Found {len(objects)} face(s)")# Pointingprint("\nPointing: 'person'")points = model.point(image, "person")["points"]print(f"Found {len(points)} person(s)")```### Changelog**2025-06-21**(release notes coming soon)**2025-04-15** ([full release notes](https://moondream.ai/blog/moondream-2025-04-14-release))1. Improved chart understanding (ChartQA up from 74.8 to 77.5, 82.2 with PoT)2. Added temperature and nucleus sampling to reduce repetitive outputs3. Better OCR for documents and tables (prompt with “Transcribe the text” or “Transcribe the text in natural reading order”)4. Object detection supports document layout detection (figure, formula, text, etc)5. UI understanding (ScreenSpot F1\@0.5 up from 53.3 to 60.3)6. Improved text understanding (DocVQA up from 76.5 to 79.3, TextVQA up from 74.6 to 76.3)**2025-03-27** ([full release notes](https://moondream.ai/blog/moondream-2025-03-27-release))1. Added support for long-form captioning2. Open vocabulary image tagging3. Improved counting accuracy (e.g. CountBenchQA increased from 80 to 86.4)4. Improved text understanding (e.g. OCRBench increased from 58.3 to 61.2)5. Improved object detection, especially for small objects (e.g. COCO up from 30.5 to 51.2)6. Fixed token streaming bug affecting multi-byte unicode characters7. gpt-fast style `compile()` now supported in HF Transformers implementation
12345678910111213141516171819202122232425262728293031323334353637383940{
"\t\t": 50294,
"\t\t\t": 50293,
"\t\t\t\t": 50292,
"\t\t\t\t\t": 50291,
"\t\t\t\t\t\t": 50290,
"\t\t\t\t\t\t\t": 50289,
"\t\t\t\t\t\t\t\t": 50288,
"\t\t\t\t\t\t\t\t\t": 50287,
" ": 50286,
" ": 50285,
" ": 50284,
" ": 50283,
" ": 50282,
" ": 50281,
" ": 50280,
" ": 50279,
" ": 50278,
" ": 50277,
" ": 50276,
" ": 50275,
" ": 50274,
" ": 50273,
" ": 50272,
" ": 50271,
" ": 50270,
" ": 50269,
" ": 50268,
" ": 50267,
" ": 50266,
" ": 50265,
" ": 50264,
" ": 50263,
" ": 50262,
" ": 50261,
" ": 50260,
" ": 50259,
" ": 50258,
" ": 50257
}12345678910111213{
"architectures": [
"HfMoondream"
],
"auto_map": {
"AutoConfig": "hf_moondream.HfConfig",
"AutoModelForCausalLM": "hf_moondream.HfMoondream"
},
"config": {},
"model_type": "moondream1",
"torch_dtype": "bfloat16",
"transformers_version": "4.52.4"
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394from dataclasses import dataclass, field
from typing import Dict, List, Optional
@dataclass(frozen=True)
class TextConfig:
dim: int = 2048
ff_dim: int = 8192
n_layers: int = 24
vocab_size: int = 51200
max_context: int = 2048
n_heads: int = 32
n_kv_heads: int = 32
prefix_attn: int = 730
group_size: Optional[int] = None
@dataclass(frozen=True)
class VisionConfig:
enc_dim: int = 1152
enc_patch_size: int = 14
enc_n_layers: int = 27
enc_ff_dim: int = 4304
enc_n_heads: int = 16
proj_out_dim: int = 2048
crop_size: int = 378
in_channels: int = 3
max_crops: int = 12
overlap_margin: int = 4
proj_inner_dim: int = 8192
@dataclass(frozen=True)
class RegionConfig:
dim: int = 2048
coord_feat_dim: int = 256
coord_out_dim: int = 1024
size_feat_dim: int = 512
size_out_dim: int = 2048
inner_dim: int = 8192
group_size: Optional[int] = None
@dataclass(frozen=True)
class TokenizerConfig:
bos_id: int = 0
eos_id: int = 0
answer_id: int = 3
thinking_id: int = 4
coord_id: int = 5
size_id: int = 6
start_ground_points_id: int = 7
end_ground_id: int = 9
templates: Dict[str, Optional[Dict[str, List[int]]]] = field(
default_factory=lambda: {
"caption": {
"short": [1, 32708, 2, 12492, 3],
"normal": [1, 32708, 2, 6382, 3],
"long": [1, 32708, 2, 4059, 3],
},
"query": {"prefix": [1, 15381, 2], "suffix": [3]},
"detect": {"prefix": [1, 7235, 476, 2], "suffix": [3]},
"point": {"prefix": [1, 2581, 2], "suffix": [3]},
}
)
@dataclass(frozen=True)
class MoondreamConfig:
text: TextConfig = TextConfig()
vision: VisionConfig = VisionConfig()
region: RegionConfig = RegionConfig()
tokenizer: TokenizerConfig = TokenizerConfig()
@classmethod
def from_dict(cls, config_dict: dict):
text_config = TextConfig(**config_dict.get("text", {}))
vision_config = VisionConfig(**config_dict.get("vision", {}))
region_config = RegionConfig(**config_dict.get("region", {}))
tokenizer_config = TokenizerConfig(**config_dict.get("tokenizer", {}))
return cls(
text=text_config,
vision=vision_config,
region=region_config,
tokenizer=tokenizer_config,
)
def to_dict(self):
return {
"text": self.text.__dict__,
"vision": self.vision.__dict__,
"region": self.region.__dict__,
"tokenizer": self.tokenizer.__dict__,
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596from transformers import PretrainedConfig
class PhiConfig(PretrainedConfig):
model_type = "phi"
keys_to_ignore_at_inference = ["past_key_values"]
def __init__(
self,
vocab_size=51200,
hidden_size=2048,
intermediate_size=8192,
num_hidden_layers=24,
num_attention_heads=32,
num_key_value_heads=None,
resid_pdrop=0.0,
embd_pdrop=0.0,
attention_dropout=0.0,
hidden_act="gelu_new",
max_position_embeddings=2048,
initializer_range=0.02,
layer_norm_eps=1e-5,
use_cache=True,
tie_word_embeddings=False,
rope_theta=10000.0,
rope_scaling=None,
partial_rotary_factor=0.5,
bos_token_id=1,
eos_token_id=2,
**kwargs,
):
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
if num_key_value_heads is None:
num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.resid_pdrop = resid_pdrop
self.embd_pdrop = embd_pdrop
self.attention_dropout = attention_dropout
self.hidden_act = hidden_act
self.max_position_embeddings = max_position_embeddings
self.initializer_range = initializer_range
self.layer_norm_eps = layer_norm_eps
self.use_cache = use_cache
self.rope_theta = rope_theta
self.rope_scaling = rope_scaling
self.partial_rotary_factor = partial_rotary_factor
self._rope_scaling_validation()
super().__init__(
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
# Copied from transformers.models.llama.configuration_llama.LlamaConfig._rope_scaling_validation
def _rope_scaling_validation(self):
"""
Validate the `rope_scaling` configuration.
"""
if self.rope_scaling is None:
return
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
raise ValueError(
"`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
f"got {self.rope_scaling}"
)
rope_scaling_type = self.rope_scaling.get("type", None)
rope_scaling_factor = self.rope_scaling.get("factor", None)
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
raise ValueError(
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
)
if (
rope_scaling_factor is None
or not isinstance(rope_scaling_factor, float)
or rope_scaling_factor <= 1.0
):
raise ValueError(
f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}"
)
class MoondreamConfig(PretrainedConfig):
model_type = "moondream1"
def __init__(self, **kwargs):
self.text_config = PhiConfig(**kwargs.pop("text_config", {}))
super().__init__(**kwargs)123456789101112131415161718# Adopted from https://github.com/crowsonkb/k-diffusion/blob/transformer-model-v2/k_diffusion/layers.py
import torch
import torch.nn as nn
import math
class FourierFeatures(nn.Module):
def __init__(self, in_features, out_features, std=1.0):
super().__init__()
assert out_features % 2 == 0
self.register_buffer(
"weight", torch.randn([out_features // 2, in_features]) * std
)
def forward(self, input):
f = 2 * math.pi * input @ self.weight.T
return torch.cat([f.cos(), f.sin()], dim=-1)1234{
"_from_model_config": true,
"transformers_version": "4.44.0"
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758from transformers import AutoModelForCausalLM, AutoTokenizer
from PIL import Image
import torch
from io import BytesIO
import base64
class EndpointHandler:
def __init__(self, model_dir):
self.model_id = "vikhyatk/moondream2"
self.model = AutoModelForCausalLM.from_pretrained(self.model_id, trust_remote_code=True)
self.tokenizer = AutoTokenizer.from_pretrained("vikhyatk/moondream2", trust_remote_code=True)
# Check if CUDA (GPU support) is available and then set the device to GPU or CPU
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model.to(self.device)
def preprocess_image(self, encoded_image):
"""Decode and preprocess the input image."""
decoded_image = base64.b64decode(encoded_image)
img = Image.open(BytesIO(decoded_image)).convert("RGB")
return img
def __call__(self, data):
"""Handle the incoming request."""
try:
# Extract the inputs from the data
inputs = data.pop("inputs", data)
input_image = inputs['image']
question = inputs.get('question', "move to the red ball")
# Preprocess the image
img = self.preprocess_image(input_image)
# Perform inference
enc_image = self.model.encode_image(img).to(self.device)
answer = self.model.answer_question(enc_image, question, self.tokenizer)
# If the output is a tensor, move it back to CPU and convert to list
if isinstance(answer, torch.Tensor):
answer = answer.cpu().numpy().tolist()
# Create the response
response = {
"statusCode": 200,
"body": {
"answer": answer
}
}
return response
except Exception as e:
# Handle any errors
response = {
"statusCode": 500,
"body": {
"error": str(e)
}
}
return response123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183import torch
import torch.nn as nn
from transformers import PreTrainedModel, PretrainedConfig
from typing import Union
from .config import MoondreamConfig
from .moondream import MoondreamModel
# Files sometimes don't get loaded without these...
from .image_crops import *
from .vision import *
from .text import *
from .region import *
from .utils import *
def extract_question(text):
prefix = "<image>\n\nQuestion: "
suffix = "\n\nAnswer:"
if text.startswith(prefix) and text.endswith(suffix):
return text[len(prefix) : -len(suffix)]
else:
return None
class HfConfig(PretrainedConfig):
_auto_class = "AutoConfig"
model_type = "moondream1"
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.config = {}
class HfMoondream(PreTrainedModel):
_auto_class = "AutoModelForCausalLM"
config_class = HfConfig
def __init__(self, config):
super().__init__(config)
self.model = MoondreamModel(
MoondreamConfig.from_dict(config.config), setup_caches=False
)
self._is_kv_cache_setup = False
def _setup_caches(self):
if not self._is_kv_cache_setup:
self.model._setup_caches()
self._is_kv_cache_setup = True
@property
def encode_image(self):
self._setup_caches()
return self.model.encode_image
@property
def query(self):
self._setup_caches()
return self.model.query
@property
def caption(self):
self._setup_caches()
return self.model.caption
@property
def detect(self):
self._setup_caches()
return self.model.detect
@property
def point(self):
self._setup_caches()
return self.model.point
@property
def detect_gaze(self):
self._setup_caches()
return self.model.detect_gaze
def answer_question(
self,
image_embeds,
question,
tokenizer=None,
chat_history="",
result_queue=None,
max_new_tokens=256,
**kwargs
):
answer = self.query(image_embeds, question)["answer"].strip()
if result_queue is not None:
result_queue.put(answer)
return answer
def batch_answer(self, images, prompts, tokenizer=None, **kwargs):
answers = []
for image, prompt in zip(images, prompts):
answers.append(self.query(image, prompt)["answer"].strip())
return answers
def _unsupported_exception(self):
raise NotImplementedError(
"This method is not supported in the latest version of moondream. "
"Consider upgrading to the updated API spec, or alternately pin "
"to 'revision=2024-08-26'."
)
def generate(self, image_embeds, prompt, tokenizer, max_new_tokens=128, **kwargs):
"""
Function definition remains unchanged for backwards compatibility.
Be aware that tokenizer, max_new_takens, and kwargs are ignored.
"""
prompt_extracted = extract_question(prompt)
if prompt_extracted is not None:
answer = self.model.query(
image=image_embeds, question=prompt_extracted, stream=False
)["answer"]
else:
image_embeds = self.encode_image(image_embeds)
prompt_tokens = torch.tensor(
[self.model.tokenizer.encode(prompt).ids],
device=self.device,
)
def generator():
for token in self.model._generate_answer(
prompt_tokens,
image_embeds.kv_cache,
image_embeds.pos,
max_new_tokens,
):
yield token
answer = "".join(list(generator()))
return [answer]
def get_input_embeddings(self) -> nn.Embedding:
"""
Lazily wrap the raw parameter `self.model.text.wte` in a real
`nn.Embedding` layer so that HF mix-ins recognise it. The wrapper
**shares** the weight tensor—no copy is made.
"""
if not hasattr(self, "_input_embeddings"):
self._input_embeddings = nn.Embedding.from_pretrained(
self.model.text.wte, # tensor created in text.py
freeze=True, # set to False if you need it trainable
)
return self._input_embeddings
def set_input_embeddings(self, value: Union[nn.Embedding, nn.Module]) -> None:
"""
Lets HF functions (e.g. `resize_token_embeddings`) replace or resize the
embeddings and keeps everything tied to `self.model.text.wte`.
"""
# 1. point the low-level parameter to the new weight matrix
self.model.text.wte = value.weight
# 2. keep a reference for get_input_embeddings()
self._input_embeddings = value
def input_embeds(
self,
input_ids: Union[torch.LongTensor, list, tuple],
*,
device: torch.device | None = None
) -> torch.FloatTensor:
"""
Back-compat wrapper that turns token IDs into embeddings.
Example:
ids = torch.tensor([[1, 2, 3]])
embeds = model.input_embeds(ids) # (1, 3, hidden_dim)
"""
if not torch.is_tensor(input_ids):
input_ids = torch.as_tensor(input_ids)
if device is not None:
input_ids = input_ids.to(device)
return self.get_input_embeddings()(input_ids)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231import math
import numpy as np
import torch
from typing import TypedDict
try:
import pyvips
HAS_VIPS = True
except:
from PIL import Image
HAS_VIPS = False
def select_tiling(
height: int, width: int, crop_size: int, max_crops: int
) -> tuple[int, int]:
"""
Determine the optimal number of tiles to cover an image with overlapping crops.
"""
if height <= crop_size or width <= crop_size:
return (1, 1)
# Minimum required tiles in each dimension
min_h = math.ceil(height / crop_size)
min_w = math.ceil(width / crop_size)
# If minimum required tiles exceed max_crops, return proportional distribution
if min_h * min_w > max_crops:
ratio = math.sqrt(max_crops / (min_h * min_w))
return (max(1, math.floor(min_h * ratio)), max(1, math.floor(min_w * ratio)))
# Perfect aspect-ratio tiles that satisfy max_crops
h_tiles = math.floor(math.sqrt(max_crops * height / width))
w_tiles = math.floor(math.sqrt(max_crops * width / height))
# Ensure we meet minimum tile requirements
h_tiles = max(h_tiles, min_h)
w_tiles = max(w_tiles, min_w)
# If we exceeded max_crops, scale down the larger dimension
if h_tiles * w_tiles > max_crops:
if w_tiles > h_tiles:
w_tiles = math.floor(max_crops / h_tiles)
else:
h_tiles = math.floor(max_crops / w_tiles)
return (max(1, h_tiles), max(1, w_tiles))
class OverlapCropOutput(TypedDict):
crops: np.ndarray
tiling: tuple[int, int]
def overlap_crop_image(
image: np.ndarray,
overlap_margin: int,
max_crops: int,
base_size: tuple[int, int] = (378, 378),
patch_size: int = 14,
) -> OverlapCropOutput:
"""
Process an image using an overlap-and-resize cropping strategy with margin handling.
This function takes an input image and creates multiple overlapping crops with
consistent margins. It produces:
1. A single global crop resized to base_size
2. Multiple overlapping local crops that maintain high resolution details
3. A patch ordering matrix that tracks correspondence between crops
The overlap strategy ensures:
- Smooth transitions between adjacent crops
- No loss of information at crop boundaries
- Proper handling of features that cross crop boundaries
- Consistent patch indexing across the full image
Args:
image (np.ndarray): Input image as numpy array with shape (H,W,C)
base_size (tuple[int,int]): Target size for crops, default (378,378)
patch_size (int): Size of patches in pixels, default 14
overlap_margin (int): Margin size in patch units, default 4
max_crops (int): Maximum number of crops allowed, default 12
Returns:
OverlapCropOutput: Dictionary containing:
- crops: A numpy array containing the global crop of the full image (index 0)
followed by the overlapping cropped regions (indices 1+)
- tiling: Tuple of (height,width) tile counts
"""
original_h, original_w = image.shape[:2]
# Convert margin from patch units to pixels
margin_pixels = patch_size * overlap_margin
total_margin_pixels = margin_pixels * 2 # Both sides
# Calculate crop parameters
crop_patches = base_size[0] // patch_size # patches per crop dimension
crop_window_patches = crop_patches - (2 * overlap_margin) # usable patches
crop_window_size = crop_window_patches * patch_size # usable size in pixels
# Determine tiling
tiling = select_tiling(
original_h - total_margin_pixels,
original_w - total_margin_pixels,
crop_window_size,
max_crops,
)
# Pre-allocate crops.
n_crops = tiling[0] * tiling[1] + 1 # 1 = global crop
crops = np.zeros(
(n_crops, base_size[0], base_size[1], image.shape[2]), dtype=np.uint8
)
# Resize image to fit tiling
target_size = (
tiling[0] * crop_window_size + total_margin_pixels,
tiling[1] * crop_window_size + total_margin_pixels,
)
if HAS_VIPS:
# Convert to vips for resizing
vips_image = pyvips.Image.new_from_array(image)
scale_x = target_size[1] / image.shape[1]
scale_y = target_size[0] / image.shape[0]
resized = vips_image.resize(scale_x, vscale=scale_y)
image = resized.numpy()
# Create global crop
scale_x = base_size[1] / vips_image.width
scale_y = base_size[0] / vips_image.height
global_vips = vips_image.resize(scale_x, vscale=scale_y)
crops[0] = global_vips.numpy()
else:
# Fallback to PIL
pil_img = Image.fromarray(image)
resized = pil_img.resize(
(int(target_size[1]), int(target_size[0])),
resample=Image.Resampling.LANCZOS,
)
image = np.asarray(resized)
# Create global crop
global_pil = pil_img.resize(
(int(base_size[1]), int(base_size[0])), resample=Image.Resampling.LANCZOS
)
crops[0] = np.asarray(global_pil)
for i in range(tiling[0]):
for j in range(tiling[1]):
# Calculate crop coordinates
y0 = i * crop_window_size
x0 = j * crop_window_size
# Extract crop with padding if needed
y_end = min(y0 + base_size[0], image.shape[0])
x_end = min(x0 + base_size[1], image.shape[1])
crop_region = image[y0:y_end, x0:x_end]
crops[
1 + i * tiling[1] + j, : crop_region.shape[0], : crop_region.shape[1]
] = crop_region
return {"crops": crops, "tiling": tiling}
def reconstruct_from_crops(
crops: torch.Tensor,
tiling: tuple[int, int],
overlap_margin: int,
patch_size: int = 14,
) -> torch.Tensor:
"""
Reconstruct the original image from overlapping crops into a single seamless image.
Takes a list of overlapping image crops along with their positional metadata and
reconstructs them into a single coherent image by carefully stitching together
non-overlapping regions. Handles both numpy arrays and PyTorch tensors.
Args:
crops: List of image crops as numpy arrays or PyTorch tensors with shape
(H,W,C)
tiling: Tuple of (height,width) indicating crop grid layout
patch_size: Size in pixels of each patch, default 14
overlap_margin: Number of overlapping patches on each edge, default 4
Returns:
Reconstructed image as numpy array or PyTorch tensor matching input type,
with shape (H,W,C) where H,W are the original image dimensions
"""
tiling_h, tiling_w = tiling
crop_height, crop_width = crops[0].shape[:2]
margin_pixels = overlap_margin * patch_size
# Calculate output size (only adding margins once)
output_h = (crop_height - 2 * margin_pixels) * tiling_h + 2 * margin_pixels
output_w = (crop_width - 2 * margin_pixels) * tiling_w + 2 * margin_pixels
reconstructed = torch.zeros(
(output_h, output_w, crops[0].shape[2]),
device=crops[0].device,
dtype=crops[0].dtype,
)
for i, crop in enumerate(crops):
tile_y = i // tiling_w
tile_x = i % tiling_w
# For each tile, determine which part to keep
# Keep left margin only for first column
x_start = 0 if tile_x == 0 else margin_pixels
# Keep right margin only for last column
x_end = crop_width if tile_x == tiling_w - 1 else crop_width - margin_pixels
# Keep top margin only for first row
y_start = 0 if tile_y == 0 else margin_pixels
# Keep bottom margin only for last row
y_end = crop_height if tile_y == tiling_h - 1 else crop_height - margin_pixels
# Calculate where this piece belongs in the output
out_x = tile_x * (crop_width - 2 * margin_pixels)
out_y = tile_y * (crop_height - 2 * margin_pixels)
# Place the piece
reconstructed[
out_y + y_start : out_y + y_end, out_x + x_start : out_x + x_end
] = crop[y_start:y_end, x_start:x_end]
return reconstructed123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166import torch
import torch.nn as nn
import torch.nn.functional as F
from dataclasses import dataclass
from typing import Literal, Optional
try:
from torchao import quantize_
from torchao.quantization import int4_weight_only
except ImportError:
def quantize_(model, quant_mode):
raise ImportError(
"torchao is not installed. Please install it with `pip install torchao`."
)
def int4_weight_only(group_size):
raise ImportError(
"torchao is not installed. Please install it with `pip install torchao`."
)
def gelu_approx(x):
return F.gelu(x, approximate="tanh")
@dataclass
class LinearWeights:
weight: torch.Tensor
bias: torch.Tensor
def linear(x: torch.Tensor, w: LinearWeights) -> torch.Tensor:
return F.linear(x, w.weight, w.bias)
def dequantize_tensor(W_q, scale, zero, orig_shape, dtype=torch.bfloat16):
_step = W_q.shape[0]
W_r = torch.empty([2 * _step, W_q.shape[1]], dtype=dtype, device=W_q.device)
W_r[:_step] = (W_q & 0b11110000) >> 4
W_r[_step:] = W_q & 0b00001111
W_r.sub_(zero).mul_(scale)
return W_r.reshape(orig_shape)
class QuantizedLinear(nn.Module):
def __init__(
self,
in_features: int,
out_features: int,
dtype: torch.dtype,
):
# TODO: Take group_size as an input instead of hardcoding it here.
super().__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = nn.ParameterDict(
{
"packed": nn.Parameter(
torch.empty(
out_features * in_features // (128 * 2), 128, dtype=torch.uint8
),
requires_grad=False,
),
"scale": nn.Parameter(
torch.empty(out_features * in_features // 128, 1),
requires_grad=False,
),
"zero_point": nn.Parameter(
torch.empty(out_features * in_features // 128, 1),
requires_grad=False,
),
}
)
self.bias = nn.Parameter(torch.empty(out_features), requires_grad=False)
self.unpacked = False
def unpack(self):
if self.unpacked:
return
self.weight = nn.Parameter(
dequantize_tensor(
self.weight["packed"],
self.weight["scale"],
self.weight["zero_point"],
(self.out_features, self.in_features),
torch.bfloat16,
)
)
with torch.device("meta"):
self.linear = nn.Linear(
self.in_features, self.out_features, dtype=torch.bfloat16
)
self.linear.weight = self.weight
self.linear.bias = nn.Parameter(
self.bias.to(torch.bfloat16), requires_grad=False
)
del self.weight, self.bias
quantize_(self, int4_weight_only(group_size=128))
self.unpacked = True
torch.cuda.empty_cache()
def forward(self, x: torch.Tensor) -> torch.Tensor:
if not self.unpacked:
self.unpack()
return self.linear(x)
@dataclass
class LayerNormWeights:
weight: torch.Tensor
bias: torch.Tensor
def layer_norm(x: torch.Tensor, w: LayerNormWeights) -> torch.Tensor:
return F.layer_norm(x, w.bias.shape, w.weight, w.bias)
@dataclass
class MLPWeights:
fc1: LinearWeights
fc2: LinearWeights
act: Literal["gelu_approx"] = "gelu_approx"
def mlp(x: torch.Tensor, w: MLPWeights, lora: Optional[dict] = None) -> torch.Tensor:
x0 = w.fc1(x)
if lora is not None:
x1 = F.linear(F.linear(x, lora["fc1"]["A"]), lora["fc1"]["B"])
x = x0 + x1
else:
x = x0
x = gelu_approx(x)
x0 = w.fc2(x)
if lora is not None:
x1 = F.linear(F.linear(x, lora["fc2"]["A"]), lora["fc2"]["B"])
x = x0 + x1
else:
x = x0
return x
@dataclass
class AttentionWeights:
qkv: LinearWeights
proj: LinearWeights
def attn(x: torch.Tensor, w: AttentionWeights, n_heads: int) -> torch.Tensor:
bsz, q_len, d_model = x.shape
head_dim = d_model // n_heads
q, k, v = [
t.view(bsz, q_len, n_heads, head_dim).transpose(1, 2)
for t in linear(x, w.qkv).chunk(3, dim=-1)
]
out = F.scaled_dot_product_attention(q, k, v)
out = out.transpose(1, 2).reshape(bsz, q_len, d_model)
out = linear(out, w.proj)
return out12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182import functools
import os
import shutil
import torch
from pathlib import Path
from urllib.request import Request, urlopen
from typing import Optional
def variant_cache_dir():
hf_hub_cache = os.environ.get("HF_HUB_CACHE")
if hf_hub_cache is not None:
return Path(hf_hub_cache) / "md_variants"
hf_home = os.environ.get("HF_HOME")
if hf_home is not None:
return Path(hf_home) / "hub" / "md_variants"
return Path("~/.cache/huggingface/hub").expanduser() / "md_variants"
def cached_variant_path(variant_id: str):
variant, *rest = variant_id.split("/", 1)
step = rest[0] if rest else "final"
cache_dir = variant_cache_dir() / variant
os.makedirs(cache_dir, exist_ok=True)
dest = cache_dir / f"{step}.pt"
if dest.exists():
return dest
md_endpoint = os.getenv("MOONDREAM_ENDPOINT", "https://api.moondream.ai")
headers = {"User-Agent": "moondream-torch"}
api_key = os.getenv("MOONDREAM_API_KEY")
if api_key is not None:
headers["X-Moondream-Auth"] = api_key
req = Request(f"{md_endpoint}/v1/variants/{variant_id}/download", headers=headers)
with urlopen(req) as r, open(dest, "wb") as f:
shutil.copyfileobj(r, f)
return dest
def nest(flat):
tree = {}
for k, v in flat.items():
parts = k.split(".")
d = tree
for p in parts[:-1]:
d = d.setdefault(p, {})
d[parts[-1]] = v
return tree
@functools.lru_cache(maxsize=5)
def variant_state_dict(variant_id: Optional[str] = None, device: str = "cpu"):
if variant_id is None:
return None
state_dict = torch.load(
cached_variant_path(variant_id), map_location=device, weights_only=True
)
# TODO: Move these into the training code that saves checkpoints...
rename_rules = [
("text_model.transformer.h", "text.blocks"),
(".mixer", ".attn"),
(".out_proj", ".proj"),
(".Wqkv", ".qkv"),
(".parametrizations.weight.0", ""),
]
new_state_dict = {}
for key, tensor in state_dict.items():
new_key = key
for old, new in rename_rules:
if old in new_key:
new_key = new_key.replace(old, new)
new_state_dict[new_key] = tensor
return nest(new_state_dict)123version https://git-lfs.github.com/spec/v1oid sha256:2329af3a8706e93cd82d0556cb3df5d5da70ccc4a8385a8ec1423af45272f431size 385453896812345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463# coding=utf-8
# Copyright 2023 Microsoft and the HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""PyTorch Phi model."""
import math
from typing import List, Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from packaging import version
from torch import nn
from torch.nn import CrossEntropyLoss
from transformers.activations import ACT2FN
from transformers.cache_utils import Cache, DynamicCache, StaticCache
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
)
from transformers.modeling_utils import PreTrainedModel
from transformers.utils import (
add_start_docstrings,
add_start_docstrings_to_model_forward,
get_torch_version,
is_flash_attn_2_available,
is_flash_attn_greater_or_equal_2_10,
is_torchdynamo_compiling,
logging,
replace_return_docstrings,
)
from .configuration_moondream import PhiConfig
if is_flash_attn_2_available():
from transformers.modeling_flash_attention_utils import _flash_attention_forward
logger = logging.get_logger(__name__)
_CONFIG_FOR_DOC = "PhiConfig"
# Copied from transformers.models.llama.modeling_llama._prepare_4d_causal_attention_mask_with_cache_position
def _prepare_4d_causal_attention_mask_with_cache_position(
attention_mask: torch.Tensor,
sequence_length: int,
target_length: int,
dtype: torch.dtype,
device: torch.device,
min_dtype: float,
cache_position: torch.Tensor,
batch_size: int,
):
"""
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
Args:
attention_mask (`torch.Tensor`):
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
sequence_length (`int`):
The sequence length being processed.
target_length (`int`):
The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
dtype (`torch.dtype`):
The dtype to use for the 4D attention mask.
device (`torch.device`):
The device to plcae the 4D attention mask on.
min_dtype (`float`):
The minimum value representable with the dtype `dtype`.
cache_position (`torch.Tensor`):
Indices depicting the position of the input sequence tokens in the sequence.
batch_size (`torch.Tensor`):
Batch size.
"""
if attention_mask is not None and attention_mask.dim() == 4:
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
causal_mask = attention_mask
else:
causal_mask = torch.full(
(sequence_length, target_length),
fill_value=min_dtype,
dtype=dtype,
device=device,
)
if sequence_length != 1:
causal_mask = torch.triu(causal_mask, diagonal=1)
causal_mask *= torch.arange(
target_length, device=device
) > cache_position.reshape(-1, 1)
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
if attention_mask is not None:
causal_mask = (
causal_mask.clone()
) # copy to contiguous memory for in-place edit
mask_length = attention_mask.shape[-1]
padding_mask = (
causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
)
padding_mask = padding_mask == 0
causal_mask[:, :, :, :mask_length] = causal_mask[
:, :, :, :mask_length
].masked_fill(padding_mask, min_dtype)
return causal_mask
# Copied from transformers.models.mixtral.modeling_mixtral.MixtralRotaryEmbedding with Mixtral->Phi
class PhiRotaryEmbedding(nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
super().__init__()
self.dim = dim
self.max_position_embeddings = max_position_embeddings
self.base = base
inv_freq = 1.0 / (
self.base
** (
torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device)
/ self.dim
)
)
self.register_buffer("inv_freq", inv_freq, persistent=False)
# Build here to make `torch.jit.trace` work.
self._set_cos_sin_cache(
seq_len=max_position_embeddings,
device=self.inv_freq.device,
dtype=torch.get_default_dtype(),
)
def _set_cos_sin_cache(self, seq_len, device, dtype):
self.max_seq_len_cached = seq_len
t = torch.arange(
self.max_seq_len_cached, device=device, dtype=torch.int64
).type_as(self.inv_freq)
freqs = torch.outer(t, self.inv_freq)
# Different from paper, but it uses a different permutation in order to obtain the same calculation
emb = torch.cat((freqs, freqs), dim=-1)
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
def forward(self, x, seq_len=None):
# x: [bs, num_attention_heads, seq_len, head_size]
if seq_len > self.max_seq_len_cached:
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
return (
self.cos_cached[:seq_len].to(dtype=x.dtype),
self.sin_cached[:seq_len].to(dtype=x.dtype),
)
# Copied from transformers.models.falcon.modeling_falcon.FalconLinearScalingRotaryEmbedding with Falcon->Phi
class PhiLinearScalingRotaryEmbedding(PhiRotaryEmbedding):
"""PhiRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
def __init__(
self,
dim,
max_position_embeddings=2048,
base=10000,
device=None,
scaling_factor=1.0,
):
self.scaling_factor = scaling_factor
super().__init__(dim, max_position_embeddings, base, device)
def _set_cos_sin_cache(self, seq_len, device, dtype):
self.max_seq_len_cached = seq_len
t = torch.arange(
self.max_seq_len_cached, device=device, dtype=torch.int64
).type_as(self.inv_freq)
t = t / self.scaling_factor
freqs = torch.outer(t, self.inv_freq)
# Different from paper, but it uses a different permutation in order to obtain the same calculation
emb = torch.cat((freqs, freqs), dim=-1)
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
# Copied from transformers.models.falcon.modeling_falcon.FalconDynamicNTKScalingRotaryEmbedding with Falcon->Phi
class PhiDynamicNTKScalingRotaryEmbedding(PhiRotaryEmbedding):
"""PhiRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
def __init__(
self,
dim,
max_position_embeddings=2048,
base=10000,
device=None,
scaling_factor=1.0,
):
self.scaling_factor = scaling_factor
super().__init__(dim, max_position_embeddings, base, device)
def _set_cos_sin_cache(self, seq_len, device, dtype):
self.max_seq_len_cached = seq_len
if seq_len > self.max_position_embeddings:
base = self.base * (
(self.scaling_factor * seq_len / self.max_position_embeddings)
- (self.scaling_factor - 1)
) ** (self.dim / (self.dim - 2))
inv_freq = 1.0 / (
base
** (
torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device)
/ self.dim
)
)
self.register_buffer("inv_freq", inv_freq, persistent=False)
t = torch.arange(
self.max_seq_len_cached, device=device, dtype=torch.int64
).type_as(self.inv_freq)
freqs = torch.outer(t, self.inv_freq)
# Different from paper, but it uses a different permutation in order to obtain the same calculation
emb = torch.cat((freqs, freqs), dim=-1)
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
# Copied from transformers.models.llama.modeling_llama.rotate_half
def rotate_half(x):
"""Rotates half the hidden dims of the input."""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
# Copied from transformers.models.mixtral.modeling_mixtral.apply_rotary_pos_emb
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
"""Applies Rotary Position Embedding to the query and key tensors.
Args:
q (`torch.Tensor`): The query tensor.
k (`torch.Tensor`): The key tensor.
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
position_ids (`torch.Tensor`):
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
used to pass offsetted position ids when working with a KV-cache.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Phi
class PhiMLP(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.activation_fn = ACT2FN[config.hidden_act]
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.fc1(hidden_states)
hidden_states = self.activation_fn(hidden_states)
hidden_states = self.fc2(hidden_states)
return hidden_states
# Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
"""
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
if n_rep == 1:
return hidden_states
hidden_states = hidden_states[:, :, None, :, :].expand(
batch, num_key_value_heads, n_rep, slen, head_dim
)
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
class PhiAttention(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: PhiConfig, layer_idx: Optional[int] = None):
super().__init__()
self.config = config
self.layer_idx = layer_idx
if layer_idx is None:
logger.warning_once(
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
"when creating this class."
)
self.attention_dropout = config.attention_dropout
self.hidden_size = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = self.hidden_size // self.num_heads
self.num_key_value_heads = config.num_key_value_heads
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
self.max_position_embeddings = config.max_position_embeddings
self.rope_theta = config.rope_theta
self.partial_rotary_factor = config.partial_rotary_factor
self.is_causal = True
if (self.head_dim * self.num_heads) != self.hidden_size:
raise ValueError(
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
f" and `num_heads`: {self.num_heads})."
)
self.Wqkv = nn.Linear(
self.hidden_size, 3 * self.num_heads * self.head_dim, bias=True
)
self.out_proj = nn.Linear(
self.num_heads * self.head_dim, self.hidden_size, bias=True
)
self._init_rope()
def _init_rope(self):
if self.config.rope_scaling is None:
self.rotary_emb = PhiRotaryEmbedding(
int(self.partial_rotary_factor * self.head_dim),
max_position_embeddings=self.max_position_embeddings,
base=self.rope_theta,
)
else:
scaling_type = self.config.rope_scaling["type"]
scaling_factor = self.config.rope_scaling["factor"]
if scaling_type == "linear":
self.rotary_emb = PhiLinearScalingRotaryEmbedding(
int(self.partial_rotary_factor * self.head_dim),
max_position_embeddings=self.max_position_embeddings,
scaling_factor=scaling_factor,
base=self.rope_theta,
)
elif scaling_type == "dynamic":
self.rotary_emb = PhiDynamicNTKScalingRotaryEmbedding(
int(self.partial_rotary_factor * self.head_dim),
max_position_embeddings=self.max_position_embeddings,
scaling_factor=scaling_factor,
base=self.rope_theta,
)
else:
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_value: Optional[Cache] = None,
output_attentions: bool = False,
use_cache: bool = False,
cache_position: Optional[torch.LongTensor] = None,
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
bsz, q_len, _ = hidden_states.size()
query_states, key_states, value_states = self.Wqkv(hidden_states).chunk(
3, dim=-1
)
query_states = query_states.view(
bsz, q_len, self.num_heads, self.head_dim
).transpose(1, 2)
key_states = key_states.view(
bsz, q_len, self.num_key_value_heads, self.head_dim
).transpose(1, 2)
value_states = value_states.view(
bsz, q_len, self.num_key_value_heads, self.head_dim
).transpose(1, 2)
kv_seq_len = key_states.shape[-2]
if past_key_value is not None:
if self.layer_idx is None:
raise ValueError(
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
"with a layer index."
)
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
# Partial rotary embedding
query_rot, query_pass = (
query_states[..., : self.rotary_emb.dim],
query_states[..., self.rotary_emb.dim :],
)
key_rot, key_pass = (
key_states[..., : self.rotary_emb.dim],
key_states[..., self.rotary_emb.dim :],
)
# [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
query_rot, key_rot = apply_rotary_pos_emb(
query_rot, key_rot, cos, sin, position_ids
)
# [batch_size, seq_length, num_heads, head_dim]
query_states = torch.cat((query_rot, query_pass), dim=-1)
key_states = torch.cat((key_rot, key_pass), dim=-1)
if past_key_value is not None:
cache_kwargs = {
"sin": sin,
"cos": cos,
"partial_rotation_size": self.rotary_emb.dim,
"cache_position": cache_position,
}
key_states, value_states = past_key_value.update(
key_states, value_states, self.layer_idx, cache_kwargs
)
key_states = repeat_kv(key_states, self.num_key_value_groups)
value_states = repeat_kv(value_states, self.num_key_value_groups)
# Queries and keys upcast to fp32 is required by Phi-2 to avoid overflow
attn_weights = torch.matmul(
query_states.to(torch.float32), key_states.to(torch.float32).transpose(2, 3)
) / math.sqrt(self.head_dim)
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
raise ValueError(
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
f" {attn_weights.size()}"
)
if attention_mask is not None:
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
attn_weights += causal_mask
# upcast attention to fp32
attn_weights = nn.functional.softmax(
attn_weights, dim=-1, dtype=torch.float32
).to(value_states.dtype)
attn_weights = nn.functional.dropout(
attn_weights, p=self.attention_dropout, training=self.training
)
attn_output = torch.matmul(attn_weights, value_states)
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
raise ValueError(
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
f" {attn_output.size()}"
)
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
attn_output = self.out_proj(attn_output)
if not output_attentions:
attn_weights = None
return attn_output, attn_weights, past_key_value
class PhiFlashAttention2(PhiAttention):
"""
Phi flash attention module. This module inherits from `PhiAttention` as the weights of the module stays
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
flash attention and deal with padding tokens in case the input contains any of them.
"""
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_value: Optional[Cache] = None,
output_attentions: bool = False,
use_cache: bool = False,
cache_position: Optional[torch.LongTensor] = None,
**kwargs,
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
# PhiFlashAttention2 attention does not support output_attentions
output_attentions = False
bsz, q_len, _ = hidden_states.size()
query_states, key_states, value_states = self.Wqkv(hidden_states).chunk(
3, dim=-1
)
# Flash attention requires the input to have the shape
# batch_size x seq_length x head_dim x hidden_dim
# therefore we just need to keep the original shape
query_states = query_states.view(
bsz, q_len, self.num_heads, self.head_dim
).transpose(1, 2)
key_states = key_states.view(
bsz, q_len, self.num_key_value_heads, self.head_dim
).transpose(1, 2)
value_states = value_states.view(
bsz, q_len, self.num_key_value_heads, self.head_dim
).transpose(1, 2)
kv_seq_len = key_states.shape[-2]
if past_key_value is not None:
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
# Partial rotary embedding
query_rot, query_pass = (
query_states[..., : self.rotary_emb.dim],
query_states[..., self.rotary_emb.dim :],
)
key_rot, key_pass = (
key_states[..., : self.rotary_emb.dim],
key_states[..., self.rotary_emb.dim :],
)
# [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
query_rot, key_rot = apply_rotary_pos_emb(
query_rot, key_rot, cos, sin, position_ids
)
# [batch_size, seq_length, num_heads, head_dim]
query_states = torch.cat((query_rot, query_pass), dim=-1)
key_states = torch.cat((key_rot, key_pass), dim=-1)
if past_key_value is not None:
cache_kwargs = {
"sin": sin,
"cos": cos,
"partial_rotation_size": self.rotary_emb.dim,
"cache_position": cache_position,
}
key_states, value_states = past_key_value.update(
key_states, value_states, self.layer_idx, cache_kwargs
)
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
# to be able to avoid many of these transpose/reshape/view.
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
value_states = value_states.transpose(1, 2)
attn_dropout = self.attention_dropout if self.training else 0.0
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
# therefore the input hidden states gets silently casted in float32. Hence, we need
# cast them back in the correct dtype just to be sure everything works as expected.
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
# in fp32.
if query_states.dtype == torch.float32:
if torch.is_autocast_enabled():
target_dtype = torch.get_autocast_gpu_dtype()
# Handle the case where the model is quantized
elif hasattr(self.config, "_pre_quantization_dtype"):
target_dtype = self.config._pre_quantization_dtype
else:
target_dtype = self.q_proj.weight.dtype
logger.warning_once(
f"The input hidden states seems to be silently casted in float32, this might be related to"
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
f" {target_dtype}."
)
query_states = query_states.to(target_dtype)
key_states = key_states.to(target_dtype)
value_states = value_states.to(target_dtype)
attn_output = _flash_attention_forward(
query_states,
key_states,
value_states,
attention_mask,
q_len,
position_ids=position_ids,
dropout=attn_dropout,
softmax_scale=None,
use_top_left_mask=self._flash_attn_uses_top_left_mask,
is_causal=self.is_causal,
)
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
attn_output = self.out_proj(attn_output)
if not output_attentions:
attn_weights = None
return attn_output, attn_weights, past_key_value
class PhiSdpaAttention(PhiAttention):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.require_contiguous_qkv = version.parse(
get_torch_version()
) < version.parse("2.2.0")
"""
SDPA attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
`PhiAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
SDPA API.
"""
# Adapted from PhiAttention.forward
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_value: Optional[Cache] = None,
output_attentions: bool = False,
use_cache: bool = False,
cache_position: Optional[torch.LongTensor] = None,
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
if output_attentions:
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
logger.warning_once(
"PhiModel is using PhiSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not "
"support `output_attentions=True`. Falling back to the manual attention implementation, but specifying "
"the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can "
'be removed using the argument `attn_implementation="eager"` when loading the model.'
)
return super().forward(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_value=past_key_value,
output_attentions=output_attentions,
use_cache=use_cache,
)
bsz, q_len, _ = hidden_states.size()
query_states, key_states, value_states = self.Wqkv(hidden_states).chunk(
3, dim=-1
)
query_states = query_states.view(
bsz, q_len, self.num_heads, self.head_dim
).transpose(1, 2)
key_states = key_states.view(
bsz, q_len, self.num_key_value_heads, self.head_dim
).transpose(1, 2)
value_states = value_states.view(
bsz, q_len, self.num_key_value_heads, self.head_dim
).transpose(1, 2)
kv_seq_len = key_states.shape[-2]
if past_key_value is not None:
if self.layer_idx is None:
raise ValueError(
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
"with a layer index."
)
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
# Partial rotary embedding
query_rot, query_pass = (
query_states[..., : self.rotary_emb.dim],
query_states[..., self.rotary_emb.dim :],
)
key_rot, key_pass = (
key_states[..., : self.rotary_emb.dim],
key_states[..., self.rotary_emb.dim :],
)
# [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
query_rot, key_rot = apply_rotary_pos_emb(
query_rot, key_rot, cos, sin, position_ids
)
# [batch_size, seq_length, num_heads, head_dim]
query_states = torch.cat((query_rot, query_pass), dim=-1)
key_states = torch.cat((key_rot, key_pass), dim=-1)
if past_key_value is not None:
cache_kwargs = {
"sin": sin,
"cos": cos,
"partial_rotation_size": self.rotary_emb.dim,
"cache_position": cache_position,
}
key_states, value_states = past_key_value.update(
key_states, value_states, self.layer_idx, cache_kwargs
)
key_states = repeat_kv(key_states, self.num_key_value_groups)
value_states = repeat_kv(value_states, self.num_key_value_groups)
causal_mask = attention_mask
if attention_mask is not None:
causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
# SDPA with memory-efficient backend is broken in torch==2.1.2 when using non-contiguous inputs and a custom
# attn_mask, so we need to call `.contiguous()` here. This was fixed in torch==2.2.0.
# Reference: https://github.com/pytorch/pytorch/issues/112577
if (
self.require_contiguous_qkv
and query_states.device.type == "cuda"
and attention_mask is not None
):
query_states = query_states.contiguous()
key_states = key_states.contiguous()
value_states = value_states.contiguous()
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
is_causal = True if causal_mask is None and q_len > 1 else False
attn_output = torch.nn.functional.scaled_dot_product_attention(
query_states,
key_states,
value_states,
attn_mask=causal_mask,
dropout_p=self.attention_dropout if self.training else 0.0,
is_causal=is_causal,
)
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
attn_output = self.out_proj(attn_output)
return attn_output, None, past_key_value
PHI_ATTENTION_CLASSES = {
"eager": PhiAttention,
"flash_attention_2": PhiFlashAttention2,
"sdpa": PhiSdpaAttention,
}
class PhiDecoderLayer(nn.Module):
def __init__(self, config: PhiConfig, layer_idx: int):
super().__init__()
self.mixer = PHI_ATTENTION_CLASSES[config._attn_implementation](
config, layer_idx=layer_idx
)
self.mlp = PhiMLP(config)
self.ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.resid_dropout = nn.Dropout(config.resid_pdrop)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
output_attentions: Optional[bool] = False,
use_cache: Optional[bool] = False,
past_key_value: Optional[Tuple[torch.Tensor]] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs,
) -> Tuple[
torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
]:
"""
Args:
hidden_states (`torch.FloatTensor`):
input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
`[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
use_cache (`bool`, *optional*):
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
(see `past_key_values`).
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
Indices depicting the position of the input sequence tokens in the sequence
kwargs (`dict`, *optional*):
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
into the model
"""
residual = hidden_states
hidden_states = self.ln(hidden_states)
# Self Attention
attn_outputs, self_attn_weights, present_key_value = self.mixer(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_value=past_key_value,
output_attentions=output_attentions,
use_cache=use_cache,
cache_position=cache_position,
)
attn_outputs = self.resid_dropout(attn_outputs)
feed_forward_hidden_states = self.resid_dropout(self.mlp(hidden_states))
hidden_states = attn_outputs + feed_forward_hidden_states + residual
outputs = (hidden_states,)
if output_attentions:
outputs += (self_attn_weights,)
if use_cache:
outputs += (present_key_value,)
return outputs
PHI_START_DOCSTRING = r"""
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.)
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.
Parameters:
config ([`PhiConfig`]):
Model configuration class with all the parameters of the model. Initializing with a config file does not
load the weights associated with the model, only the configuration. Check out the
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""
@add_start_docstrings(
"The bare Phi Model outputting raw hidden-states without any specific head on top.",
PHI_START_DOCSTRING,
)
class PhiPreTrainedModel(PreTrainedModel):
config_class = PhiConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["PhiDecoderLayer"]
_skip_keys_device_placement = "past_key_values"
_supports_flash_attn_2 = True
_supports_sdpa = True
_supports_cache_class = True
def _init_weights(self, module):
std = self.config.initializer_range
if isinstance(module, nn.Linear):
module.weight.data.normal_(mean=0.0, std=std)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0, std=std)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
class Embedding(nn.Module):
def __init__(self, config: PhiConfig):
super().__init__()
self.wte = nn.Embedding(
config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id
)
def forward(self, input_ids: torch.LongTensor) -> torch.FloatTensor:
return self.wte(input_ids)
PHI_INPUTS_DOCSTRING = r"""
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
it.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
`past_key_values`).
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
information on the default strategy.
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
config.n_positions - 1]`.
[What are position IDs?](../glossary#position-ids)
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
Two formats are allowed:
- a [`~cache_utils.Cache`] instance;
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
cache format.
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
legacy cache format will be returned.
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
of shape `(batch_size, sequence_length)`.
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
model's internal embedding lookup matrix.
use_cache (`bool`, *optional*):
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
`past_key_values`).
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
the complete sequence length.
"""
@add_start_docstrings(
"The bare Phi Model outputting raw hidden-states without any specific head on top.",
PHI_START_DOCSTRING,
)
class PhiModel(PhiPreTrainedModel):
"""
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PhiDecoderLayer`]
Args:
config: PhiConfig
"""
def __init__(self, config: PhiConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embd = Embedding(config)
self.embed_dropout = nn.Dropout(config.embd_pdrop)
self.h = nn.ModuleList(
[
PhiDecoderLayer(config, layer_idx)
for layer_idx in range(config.num_hidden_layers)
]
)
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
self._use_sdpa = config._attn_implementation == "sdpa"
self.gradient_checkpointing = False
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.embd.wte
def set_input_embeddings(self, value):
self.embd.wte = value
@add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
def forward(
self,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[List[torch.FloatTensor]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
) -> Union[Tuple, BaseModelOutputWithPast]:
output_attentions = (
output_attentions
if output_attentions is not None
else self.config.output_attentions
)
output_hidden_states = (
output_hidden_states
if output_hidden_states is not None
else self.config.output_hidden_states
)
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = (
return_dict if return_dict is not None else self.config.use_return_dict
)
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError(
"You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
)
if self.gradient_checkpointing and self.training:
if use_cache:
logger.warning_once(
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
)
use_cache = False
use_legacy_cache = False
if use_cache and not isinstance(past_key_values, Cache) and not self.training:
use_legacy_cache = True
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
logger.warning_once(
"We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. "
"Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/internal/generation_utils#transformers.Cache)"
)
if inputs_embeds is None:
inputs_embeds = self.embd(input_ids)
if cache_position is None:
past_seen_tokens = (
past_key_values.get_seq_length() if past_key_values is not None else 0
)
cache_position = torch.arange(
past_seen_tokens,
past_seen_tokens + inputs_embeds.shape[1],
device=inputs_embeds.device,
)
if position_ids is None:
position_ids = cache_position.unsqueeze(0)
causal_mask = self._update_causal_mask(
attention_mask,
inputs_embeds,
cache_position,
past_key_values,
output_attentions,
)
hidden_states = inputs_embeds
# decoder layers
all_hidden_states = () if output_hidden_states else None
all_self_attns = () if output_attentions else None
next_decoder_cache = None
for decoder_layer in self.h:
if output_hidden_states:
all_hidden_states += (hidden_states,)
if self.gradient_checkpointing and self.training:
layer_outputs = self._gradient_checkpointing_func(
decoder_layer.__call__,
hidden_states,
causal_mask,
position_ids,
output_attentions,
use_cache,
past_key_values,
cache_position,
)
else:
layer_outputs = decoder_layer(
hidden_states,
attention_mask=causal_mask,
position_ids=position_ids,
past_key_value=past_key_values,
output_attentions=output_attentions,
use_cache=use_cache,
cache_position=cache_position,
)
hidden_states = layer_outputs[0]
if use_cache:
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
if output_attentions:
all_self_attns += (layer_outputs[1],)
# add hidden states from the last decoder layer
if output_hidden_states:
all_hidden_states += (hidden_states,)
next_cache = None
if use_cache:
next_cache = (
next_decoder_cache.to_legacy_cache()
if use_legacy_cache
else next_decoder_cache
)
if not return_dict:
return tuple(
v
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
if v is not None
)
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=next_cache,
hidden_states=all_hidden_states,
attentions=all_self_attns,
)
# Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
def _update_causal_mask(
self,
attention_mask: torch.Tensor,
input_tensor: torch.Tensor,
cache_position: torch.Tensor,
past_key_values: Cache,
output_attentions: bool,
):
# TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
# KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
# (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
# `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
if self.config._attn_implementation == "flash_attention_2":
if attention_mask is not None and 0.0 in attention_mask:
return attention_mask
return None
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
# to infer the attention mask.
past_seen_tokens = (
past_key_values.get_seq_length() if past_key_values is not None else 0
)
using_static_cache = isinstance(past_key_values, StaticCache)
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
if (
self.config._attn_implementation == "sdpa"
and not using_static_cache
and not output_attentions
):
if AttentionMaskConverter._ignore_causal_mask_sdpa(
attention_mask,
inputs_embeds=input_tensor,
past_key_values_length=past_seen_tokens,
is_training=self.training,
):
return None
dtype, device = input_tensor.dtype, input_tensor.device
min_dtype = torch.finfo(dtype).min
sequence_length = input_tensor.shape[1]
if using_static_cache:
target_length = past_key_values.get_max_length()
else:
target_length = (
attention_mask.shape[-1]
if isinstance(attention_mask, torch.Tensor)
else past_seen_tokens + sequence_length + 1
)
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
causal_mask = _prepare_4d_causal_attention_mask_with_cache_position(
attention_mask,
sequence_length=sequence_length,
target_length=target_length,
dtype=dtype,
device=device,
min_dtype=min_dtype,
cache_position=cache_position,
batch_size=input_tensor.shape[0],
)
if (
self.config._attn_implementation == "sdpa"
and attention_mask is not None
and attention_mask.device.type == "cuda"
and not output_attentions
):
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
# Details: https://github.com/pytorch/pytorch/issues/110213
causal_mask = AttentionMaskConverter._unmask_unattended(
causal_mask, min_dtype
)
return causal_mask
class CausalLMHead(nn.Module):
"""Causal Language Modeling head. Simplified version."""
def __init__(self, config):
super().__init__()
self.ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.linear = nn.Linear(config.hidden_size, config.vocab_size)
def forward(self, hidden_states):
return self.linear(self.ln(hidden_states))
class PhiForCausalLM(PhiPreTrainedModel):
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi,bias=False->bias=True
def __init__(self, config):
super().__init__(config)
self.transformer = PhiModel(config)
self.vocab_size = config.vocab_size
self.lm_head = CausalLMHead(config)
# Initialize weights and apply final processing
self.post_init()
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
def get_input_embeddings(self):
return self.transformer.embd.wte
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
def set_input_embeddings(self, value):
self.transformer.embd.wte = value
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
def get_output_embeddings(self):
return self.lm_head.linear
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
def set_output_embeddings(self, new_embeddings):
self.lm_head.linear = new_embeddings
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
def set_decoder(self, decoder):
self.model = decoder
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
def get_decoder(self):
return self.model
@add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
@replace_return_docstrings(
output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
)
def forward(
self,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[List[torch.FloatTensor]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
num_logits_to_keep: int = 0,
) -> Union[Tuple, CausalLMOutputWithPast]:
r"""
Args:
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
num_logits_to_keep (`int`, *optional*):
Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
Returns:
Example:
```python
>>> from transformers import AutoTokenizer, PhiForCausalLM
>>> model = PhiForCausalLM.from_pretrained("microsoft/phi-1")
>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-1")
>>> prompt = "This is an example script ."
>>> inputs = tokenizer(prompt, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
'This is an example script .\n\n\n\nfrom typing import List\n\ndef find_most_common_letter(words: List[str'
```"""
output_attentions = (
output_attentions
if output_attentions is not None
else self.config.output_attentions
)
output_hidden_states = (
output_hidden_states
if output_hidden_states is not None
else self.config.output_hidden_states
)
return_dict = (
return_dict if return_dict is not None else self.config.use_return_dict
)
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
outputs = self.transformer(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
cache_position=cache_position,
)
hidden_states = outputs[0]
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :]).float()
loss = None
if labels is not None:
# Upcast to float if we need to compute the loss to avoid potential precision issues
logits = logits.float()
# Shift so that tokens < n predict n
shift_logits = logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
# Flatten the tokens
loss_fct = CrossEntropyLoss()
shift_logits = shift_logits.view(-1, self.config.vocab_size)
shift_labels = shift_labels.view(-1)
# Enable model parallelism
shift_labels = shift_labels.to(shift_logits.device)
loss = loss_fct(shift_logits, shift_labels)
if not return_dict:
output = (logits,) + outputs[1:]
return (loss,) + output if loss is not None else output
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.prepare_inputs_for_generation
def prepare_inputs_for_generation(
self,
input_ids,
past_key_values=None,
attention_mask=None,
inputs_embeds=None,
cache_position=None,
position_ids=None,
use_cache=True,
num_logits_to_keep=0,
**kwargs,
):
# If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
# Exception 1: when passing input_embeds, input_ids may be missing entries
# Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
if past_key_values is not None:
if inputs_embeds is not None: # Exception 1
input_ids = input_ids[:, -cache_position.shape[0] :]
elif (
input_ids.shape[1] != cache_position.shape[0]
): # Default case (the "else", a no op, is Exception 2)
input_ids = input_ids[:, cache_position]
if attention_mask is not None and position_ids is None:
# create position_ids on the fly for batch generation
position_ids = attention_mask.long().cumsum(-1) - 1
position_ids.masked_fill_(attention_mask == 0, 1)
if past_key_values:
position_ids = position_ids[:, -input_ids.shape[1] :]
# This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
position_ids = position_ids.clone(memory_format=torch.contiguous_format)
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
if inputs_embeds is not None and cache_position[0] == 0:
model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
else:
# The clone here is for the same reason as for `position_ids`.
model_inputs = {
"input_ids": input_ids.clone(memory_format=torch.contiguous_format),
"inputs_embeds": None,
}
if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:
if model_inputs["inputs_embeds"] is not None:
batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
device = model_inputs["inputs_embeds"].device
else:
batch_size, sequence_length = model_inputs["input_ids"].shape
device = model_inputs["input_ids"].device
dtype = self.lm_head.weight.dtype
min_dtype = torch.finfo(dtype).min
attention_mask = _prepare_4d_causal_attention_mask_with_cache_position(
attention_mask,
sequence_length=sequence_length,
target_length=past_key_values.get_max_length(),
dtype=dtype,
device=device,
min_dtype=min_dtype,
cache_position=cache_position,
batch_size=batch_size,
)
model_inputs.update(
{
"position_ids": position_ids,
"cache_position": cache_position,
"past_key_values": past_key_values,
"use_cache": use_cache,
"attention_mask": attention_mask,
"num_logits_to_keep": num_logits_to_keep,
}
)
return model_inputs123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986import torch
import torch.nn as nn
import random
from typing import Literal, Tuple, TypedDict, Union, Dict, Any, Optional, List
from PIL import Image
from dataclasses import dataclass
from tokenizers import Tokenizer
from .config import MoondreamConfig
from .image_crops import reconstruct_from_crops
from .vision import vision_encoder, vision_projection, prepare_crops, build_vision_model
from .text import build_text_model, text_encoder, lm_head, text_decoder
from .region import (
decode_coordinate,
encode_coordinate,
decode_size,
encode_size,
encode_spatial_refs,
SpatialRefs,
)
from .layers import QuantizedLinear
from .lora import variant_state_dict
from .utils import remove_outlier_points
ImageEncodingSettings = TypedDict(
"ImageEncodingSettings",
{"variant": str},
total=False,
)
TextSamplingSettings = TypedDict(
"TextSamplingSettings",
{
"max_tokens": int,
"temperature": float,
"top_p": float,
"variant": str,
},
total=False,
)
ObjectSamplingSettings = TypedDict(
"ObjectSamplingSettings",
{"max_objects": int, "variant": str},
total=False,
)
DEFAULT_MAX_TOKENS = 768
DEFAULT_TEMPERATURE = 0.5
DEFAULT_TOP_P = 0.3
DEFAULT_MAX_OBJECTS = 50
@dataclass(frozen=True)
class EncodedImage:
pos: int
caches: List[Tuple[torch.Tensor, torch.Tensor]]
class KVCache(nn.Module):
def __init__(self, n_heads, n_kv_heads, max_context, dim, device, dtype):
super().__init__()
cache_shape = (1, n_kv_heads, max_context, dim // n_heads)
self.register_buffer(
"k_cache", torch.zeros(*cache_shape, device=device, dtype=dtype)
)
self.register_buffer(
"v_cache", torch.zeros(*cache_shape, device=device, dtype=dtype)
)
def update(self, pos_ids, k, v):
kout, vout = self.k_cache, self.v_cache
kout[:, :, pos_ids, :] = k
vout[:, :, pos_ids, :] = v
return kout, vout
class MoondreamModel(nn.Module):
def __init__(
self, config: MoondreamConfig, dtype=torch.bfloat16, setup_caches=True
):
super().__init__()
self.config = config
self.tokenizer = Tokenizer.from_pretrained("moondream/starmie-v1")
self.vision = build_vision_model(config.vision, dtype)
self.text = build_text_model(config.text, dtype)
# Region Model
linear_cls = (
QuantizedLinear if config.region.group_size is not None else nn.Linear
)
self.region = nn.ModuleDict(
{
"coord_encoder": linear_cls(
config.region.coord_feat_dim, config.region.dim, dtype=dtype
),
"coord_decoder": nn.ModuleDict(
{
"fc1": linear_cls(
config.region.dim, config.region.inner_dim, dtype=dtype
),
"fc2": linear_cls(
config.region.inner_dim,
config.region.coord_out_dim,
dtype=dtype,
),
}
),
"size_encoder": linear_cls(
config.region.size_feat_dim, config.region.dim, dtype=dtype
),
"size_decoder": nn.ModuleDict(
{
"fc1": linear_cls(
config.region.dim, config.region.inner_dim, dtype=dtype
),
"fc2": linear_cls(
config.region.inner_dim,
config.region.size_out_dim,
dtype=dtype,
),
}
),
}
)
self.region.coord_features = nn.Parameter(
torch.empty(config.region.coord_feat_dim // 2, 1, dtype=dtype).T
)
self.region.size_features = nn.Parameter(
torch.empty(config.region.size_feat_dim // 2, 2, dtype=dtype).T
)
attn_mask = torch.tril(
torch.ones(
1, 1, config.text.max_context, config.text.max_context, dtype=torch.bool
)
)
patch_w = config.vision.crop_size // config.vision.enc_patch_size
prefix_attn_len = 1 + patch_w**2
attn_mask[..., :prefix_attn_len, :prefix_attn_len] = 1
self.register_buffer("attn_mask", attn_mask, persistent=False)
# Initialize KV caches.
if setup_caches:
self._setup_caches()
def _setup_caches(self):
c = self.config.text
for b in self.text.blocks:
b.kv_cache = KVCache(
c.n_heads,
c.n_kv_heads,
c.max_context,
c.dim,
device=self.device,
dtype=self.vision.pos_emb.dtype,
)
@property
def device(self):
return self.vision.pos_emb.device
def _vis_enc(self, x: torch.Tensor):
return vision_encoder(x, self.vision, self.config.vision)
def _vis_proj(self, g: torch.Tensor, r: torch.Tensor):
return vision_projection(g, r, self.vision, self.config.vision)
def _prefill(
self,
x: torch.Tensor,
attn_mask: torch.Tensor,
pos_ids: torch.Tensor,
lora: Optional[torch.Tensor],
):
return text_decoder(x, self.text, attn_mask, pos_ids, self.config.text, lora)
def _decode_one_tok(
self,
x: torch.Tensor,
attn_mask: torch.Tensor,
pos_ids: torch.Tensor,
lora: Optional[torch.Tensor],
):
hidden = text_decoder(x, self.text, attn_mask, pos_ids, self.config.text, lora)
logits = lm_head(hidden, self.text)
return logits, hidden
def compile(self):
for module in self.modules():
if isinstance(module, QuantizedLinear):
module.unpack()
# TODO: vision_projection is not being compiled
self._vis_enc = torch.compile(self._vis_enc, fullgraph=True)
self._prefill = torch.compile(self._prefill, fullgraph=True)
self._decode_one_tok = torch.compile(
self._decode_one_tok, fullgraph=True, mode="reduce-overhead"
)
def _run_vision_encoder(self, image: Image.Image) -> torch.Tensor:
all_crops, tiling = prepare_crops(image, self.config.vision, device=self.device)
torch._dynamo.mark_dynamic(all_crops, 0)
outputs = self._vis_enc(all_crops)
global_features = outputs[0]
local_features = outputs[1:].view(
-1,
self.config.vision.enc_n_layers,
self.config.vision.enc_n_layers,
self.config.vision.enc_dim,
)
reconstructed = reconstruct_from_crops(
local_features,
tiling,
patch_size=1,
overlap_margin=self.config.vision.overlap_margin,
)
return self._vis_proj(global_features, reconstructed)
def encode_image(
self,
image: Union[Image.Image, EncodedImage],
settings: Optional[ImageEncodingSettings] = None,
) -> EncodedImage:
if isinstance(image, EncodedImage):
return image
elif not isinstance(image, Image.Image):
raise ValueError("image must be a PIL Image or EncodedImage")
lora = (
variant_state_dict(settings["variant"], device=self.device)
if settings is not None and settings["variant"] is not None
else None
)
# Run through text model in addition to the vision encoder, to minimize
# re-computation if multiple queries are performed on this image.
with torch.inference_mode():
img_emb = self._run_vision_encoder(image)
bos_emb = text_encoder(
torch.tensor([[self.config.tokenizer.bos_id]], device=self.device),
self.text,
)
inputs_embeds = torch.cat([bos_emb, img_emb[None]], dim=1)
mask = self.attn_mask[:, :, 0 : inputs_embeds.size(1), :]
pos_ids = torch.arange(inputs_embeds.size(1), dtype=torch.long)
self._prefill(inputs_embeds, mask, pos_ids, lora)
return EncodedImage(
pos=inputs_embeds.size(1),
caches=[
(
b.kv_cache.k_cache[:, :, : inputs_embeds.size(1), :].clone(),
b.kv_cache.v_cache[:, :, : inputs_embeds.size(1), :].clone(),
)
for b in self.text.blocks
],
)
def _apply_top_p(self, probs: torch.Tensor, top_p: float):
probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True)
probs_sum = torch.cumsum(probs_sort, dim=-1)
mask = probs_sum - probs_sort > top_p
probs_sort[mask] = 0.0
probs_sort.div_(probs_sort.sum(dim=-1, keepdim=True))
next_probs = torch.zeros_like(probs)
next_probs.scatter_(dim=-1, index=probs_idx, src=probs_sort)
return next_probs
def _prefill_prompt(
self,
prompt_tokens: torch.Tensor,
pos: int,
temperature: float,
top_p: float,
spatial_refs: Optional[SpatialRefs] = None,
attn_mask: Optional[torch.Tensor] = None,
lora: Optional[dict] = None,
):
with torch.inference_mode():
prompt_emb = text_encoder(prompt_tokens, self.text)
if spatial_refs:
encoded_refs = encode_spatial_refs(spatial_refs, self.region)
prompt_emb[prompt_tokens == self.config.tokenizer.coord_id] = (
encoded_refs["coords"]
)
if encoded_refs["sizes"] is not None:
prompt_emb[prompt_tokens == self.config.tokenizer.size_id] = (
encoded_refs["sizes"]
)
torch._dynamo.mark_dynamic(prompt_emb, 1)
if attn_mask is None:
attn_mask = self.attn_mask
mask = attn_mask[:, :, pos : pos + prompt_emb.size(1), :]
pos_ids = torch.arange(pos, pos + prompt_emb.size(1), dtype=torch.long)
hidden_BC = self._prefill(prompt_emb, mask, pos_ids, lora)
logits_BV = lm_head(hidden_BC, self.text)
if temperature == 0:
next_token = torch.argmax(logits_BV, dim=-1).unsqueeze(1)
else:
probs = torch.softmax(logits_BV / temperature, dim=-1)
probs = self._apply_top_p(probs, top_p)
next_token = torch.multinomial(probs, num_samples=1)
pos = pos + prompt_emb.size(1)
return logits_BV, hidden_BC, next_token, pos
def _generate_reasoning(
self,
prompt_tokens,
pos,
settings: Optional[TextSamplingSettings] = None,
spatial_refs: Optional[SpatialRefs] = None,
attn_mask: Optional[torch.Tensor] = None,
) -> Tuple[int, str, List[dict]]:
max_tokens = (
settings.get("max_tokens", DEFAULT_MAX_TOKENS)
if settings
else DEFAULT_MAX_TOKENS
)
temperature = (
settings.get("temperature", DEFAULT_TEMPERATURE)
if settings
else DEFAULT_TEMPERATURE
)
lora = (
variant_state_dict(settings["variant"], device=self.device)
if settings is not None and "variant" in settings
else None
)
top_p = settings.get("top_p", DEFAULT_TOP_P) if settings else DEFAULT_TOP_P
eos_id = self.config.tokenizer.answer_id
_, last_hidden_BC, next_token, pos = self._prefill_prompt(
prompt_tokens,
pos,
temperature,
top_p,
spatial_refs,
attn_mask=attn_mask,
lora=lora,
)
text_token_chunks = [[]]
grounding_chunks = [[]]
mask = torch.zeros(1, 1, 2048, device=self.device, dtype=torch.bool)
mask[:, :, :pos] = 1
pos_ids = torch.tensor([pos], device=self.device, dtype=torch.long)
generated_tokens = 0
while (
next_token_id := next_token.item()
) != eos_id and generated_tokens < max_tokens:
if (
next_token_id == self.config.tokenizer.start_ground_points_id
or next_token_id == self.config.tokenizer.end_ground_id
):
text_token_chunks.append([])
grounding_chunks.append([])
text_token_chunks[-1].append(next_token_id)
with torch.inference_mode():
if next_token_id == self.config.tokenizer.coord_id:
coord_logits = decode_coordinate(last_hidden_BC, self.region)
coord = torch.argmax(coord_logits, dim=-1) / coord_logits.size(-1)
grounding_chunks[-1].append(coord.item())
next_emb = encode_coordinate(
coord.to(dtype=coord_logits.dtype), self.region
).unsqueeze(0)
else:
next_emb = text_encoder(next_token, self.text)
mask[:, :, pos], pos_ids[0] = 1, pos
logits_BV, last_hidden_BC = self._decode_one_tok(
next_emb, mask, pos_ids, lora
)
logits_BV[:, self.config.tokenizer.eos_id] = float("-inf")
logits_BV[:, self.config.tokenizer.size_id] = float("-inf")
pos += 1
if temperature == 0:
next_token = torch.argmax(logits_BV, dim=-1).unsqueeze(1) # (1, 1)
else:
probs = torch.softmax(logits_BV / temperature, dim=-1) # (1, V)
probs = self._apply_top_p(probs, top_p)
next_token = torch.multinomial(probs, num_samples=1) # (1, 1)
generated_tokens += 1
text_chunks = [
self.tokenizer.decode(chunk_tokens) for chunk_tokens in text_token_chunks
]
text = "".join(text_chunks)
start_idx = 0
grounding = []
for text_chunk, grounding_chunk in zip(text_chunks, grounding_chunks):
if len(grounding_chunk) > 1:
points = []
for i in range(0, len(grounding_chunk) - (len(grounding_chunk) % 2), 2):
points.append((grounding_chunk[i], grounding_chunk[i + 1]))
grounding.append(
{
"start_idx": start_idx,
"end_idx": start_idx + len(text_chunk),
"points": points,
}
)
start_idx += len(text_chunk)
return pos, text, grounding
def _generate_answer(
self,
prompt_tokens: torch.Tensor,
pos: int,
settings: Optional[TextSamplingSettings] = None,
spatial_refs: Optional[SpatialRefs] = None,
eos_id: Optional[int] = None,
attn_mask: Optional[torch.Tensor] = None,
):
max_tokens = (
settings.get("max_tokens", DEFAULT_MAX_TOKENS)
if settings
else DEFAULT_MAX_TOKENS
)
temperature = (
settings.get("temperature", DEFAULT_TEMPERATURE)
if settings
else DEFAULT_TEMPERATURE
)
top_p = settings.get("top_p", DEFAULT_TOP_P) if settings else DEFAULT_TOP_P
eos_id = eos_id if eos_id is not None else self.config.tokenizer.eos_id
lora = (
variant_state_dict(settings["variant"], device=self.device)
if settings is not None and "variant" in settings
else None
)
_, _, next_token, pos = self._prefill_prompt(
prompt_tokens,
pos,
temperature,
top_p,
spatial_refs,
attn_mask=attn_mask,
lora=lora,
)
def generator(next_token, pos):
mask = torch.zeros(1, 1, 2048, device=self.device, dtype=torch.bool)
mask[:, :, :pos] = 1
pos_ids = torch.tensor([pos], device=self.device, dtype=torch.long)
generated_tokens = 0
# For properly handling token streaming with Unicode
token_cache = []
print_len = 0
while (
next_token_id := next_token.item()
) != eos_id and generated_tokens < max_tokens:
# Add token to our cache
token_cache.append(next_token_id)
# Decode all tokens collected so far
text = self.tokenizer.decode(token_cache)
# After a newline, we flush the cache completely
if text.endswith("\n"):
printable_text = text[print_len:]
token_cache = []
print_len = 0
if printable_text:
yield printable_text
# If the last token is a CJK character, we can safely print it
elif len(text) > 0 and _is_cjk_char(ord(text[-1])):
printable_text = text[print_len:]
print_len += len(printable_text)
if printable_text:
yield printable_text
# Otherwise, only yield up to the last space to avoid cutting words
else:
last_space_idx = text.rfind(" ", print_len)
if last_space_idx >= print_len:
printable_text = text[print_len : last_space_idx + 1]
print_len += len(printable_text)
if printable_text:
yield printable_text
with torch.inference_mode():
next_emb = text_encoder(next_token, self.text)
mask[:, :, pos], pos_ids[0] = 1, pos
logits_BV, _ = self._decode_one_tok(next_emb, mask, pos_ids, lora)
logits_BV[:, self.config.tokenizer.answer_id] = float("-inf")
pos += 1
if temperature == 0:
next_token = torch.argmax(logits_BV, dim=-1).unsqueeze(
1
) # (1, 1)
else:
probs = torch.softmax(logits_BV / temperature, dim=-1) # (1, V)
probs = self._apply_top_p(probs, top_p)
next_token = torch.multinomial(probs, num_samples=1) # (1, 1)
generated_tokens += 1
# Flush any remaining text in the cache
if token_cache:
text = self.tokenizer.decode(token_cache)
printable_text = text[print_len:]
if printable_text:
yield printable_text
return generator(next_token, pos)
def query(
self,
image: Optional[Union[Image.Image, EncodedImage]] = None,
question: str = None,
reasoning: bool = False,
spatial_refs: Optional[SpatialRefs] = None,
stream: bool = False,
settings: Optional[TextSamplingSettings] = None,
):
if self.config.tokenizer.templates["query"] is None:
raise NotImplementedError("Model does not support querying.")
if question is None:
raise ValueError("question must be provided.")
if spatial_refs and image is None:
raise ValueError("spatial_refs can only be used with an image.")
attn_mask = self.attn_mask
if image is not None:
image = self.encode_image(image, settings)
self.load_encoded_image(image)
pos = image.pos
prompt_toks = self.config.tokenizer.templates["query"]["prefix"]
else:
self._setup_caches()
pos = 0
prompt_toks = [
self.config.tokenizer.bos_id
] + self.config.tokenizer.templates["query"]["prefix"]
max_context = self.config.text.max_context
attn_mask = torch.tril(
torch.ones(1, 1, max_context, max_context, dtype=torch.bool)
).to(self.device)
spatial_toks = []
if spatial_refs:
for ref in spatial_refs:
coord_id = self.config.tokenizer.coord_id
size_id = self.config.tokenizer.size_id
if len(ref) == 2:
spatial_toks.extend([coord_id, coord_id])
else:
spatial_toks.extend([coord_id, coord_id, size_id])
prompt_tokens = [
prompt_toks
+ spatial_toks
+ self.tokenizer.encode(question).ids
+ self.config.tokenizer.templates["query"]["suffix"]
]
if reasoning:
prompt_tokens[0] += [self.config.tokenizer.thinking_id]
prompt_tokens = torch.tensor(prompt_tokens, device=self.device)
pos, reasoning_text, reasoning_grounding = self._generate_reasoning(
prompt_tokens, pos, settings, spatial_refs, attn_mask=attn_mask
)
prompt_tokens = [self.config.tokenizer.templates["query"]["suffix"]]
reasoning_dict = {
"reasoning": {"text": reasoning_text, "grounding": reasoning_grounding}
}
else:
prompt_tokens[0] += self.config.tokenizer.templates["query"]["suffix"]
reasoning_dict = {}
prompt_tokens = torch.tensor(prompt_tokens, device=self.device)
def generator():
for token in self._generate_answer(
prompt_tokens, pos, settings, spatial_refs, attn_mask=attn_mask
):
yield token
if stream:
return {**reasoning_dict, "answer": generator()}
else:
return {**reasoning_dict, "answer": "".join(list(generator()))}
def load_encoded_image(self, encoded_image: EncodedImage):
for b, (k, v) in zip(self.text.blocks, encoded_image.caches):
b.kv_cache.k_cache[:, :, : k.size(2), :] = k
b.kv_cache.v_cache[:, :, : v.size(2), :] = v
def caption(
self,
image: Union[Image.Image, EncodedImage],
length: Literal["normal", "short", "long"] = "normal",
stream: bool = False,
settings: Optional[TextSamplingSettings] = None,
):
if self.config.tokenizer.templates["caption"] is None:
raise NotImplementedError("Model does not support captioning.")
if length not in self.config.tokenizer.templates["caption"]:
raise ValueError(f"Model does not support caption length '{length}'.")
image = self.encode_image(image, settings)
self.load_encoded_image(image)
prompt_tokens = torch.tensor(
[self.config.tokenizer.templates["caption"][length]], device=self.device
)
def generator():
for token in self._generate_answer(prompt_tokens, image.pos, settings):
yield token
if stream:
return {"caption": generator()}
else:
return {"caption": "".join(list(generator()))}
def _generate_points(
self,
hidden: torch.Tensor,
next_token: torch.Tensor,
pos: int,
include_size: bool = True,
max_objects: int = DEFAULT_MAX_OBJECTS,
lora: Optional[dict] = None,
):
out = []
mask = torch.zeros(1, 1, 2048, device=self.device, dtype=torch.bool)
mask[:, :, :pos] = 1
pos_ids = torch.tensor([pos], device=self.device, dtype=torch.long)
with torch.inference_mode():
while (
next_token.item() != self.config.tokenizer.eos_id
and len(out) < max_objects
):
x_logits = decode_coordinate(hidden, self.region)
x_center = torch.argmax(x_logits, dim=-1) / x_logits.size(-1)
next_emb = encode_coordinate(
x_center.to(dtype=x_logits.dtype), self.region
).unsqueeze(0)
# Decode y-coordinate
mask[:, :, pos], pos_ids[0] = 1, pos
_, hidden = self._decode_one_tok(next_emb, mask, pos_ids, lora)
pos += 1
y_logits = decode_coordinate(hidden, self.region)
y_center = torch.argmax(y_logits, dim=-1) / y_logits.size(-1)
next_emb = encode_coordinate(
y_center.to(dtype=y_logits.dtype), self.region
).unsqueeze(0)
# Decode size
if include_size:
mask[:, :, pos], pos_ids[0] = 1, pos
logits, hidden = self._decode_one_tok(next_emb, mask, pos_ids, lora)
pos += 1
size_logits = decode_size(hidden, self.region)
# Get bin indices from the logits
w_bin = torch.argmax(size_logits[0], dim=-1)
h_bin = torch.argmax(size_logits[1], dim=-1)
# Convert from bin indices to actual size values using the inverse of the log-scale mapping
# Formula: size = 2^((bin / 1023.0) * 10.0 - 10.0)
w = torch.pow(2.0, (w_bin.float() / 1023.0) * 10.0 - 10.0)
h = torch.pow(2.0, (h_bin.float() / 1023.0) * 10.0 - 10.0)
next_emb = (
encode_size(
torch.tensor(
[w, h], device=self.device, dtype=size_logits.dtype
),
self.region,
)
.unsqueeze(0)
.unsqueeze(0)
)
# Add object
out.append(
{
"x_min": x_center.item() - w.item() / 2,
"y_min": y_center.item() - h.item() / 2,
"x_max": x_center.item() + w.item() / 2,
"y_max": y_center.item() + h.item() / 2,
}
)
else:
out.append({"x": x_center.item(), "y": y_center.item()})
# Decode next token (x-coordinate, or eos)
mask[:, :, pos], pos_ids[0] = 1, pos
logits, hidden = self._decode_one_tok(next_emb, mask, pos_ids, lora)
pos += 1
next_token = torch.argmax(logits, dim=-1)
return out
def detect(
self,
image: Union[Image.Image, EncodedImage],
object: str,
settings: Optional[ObjectSamplingSettings] = None,
):
if self.config.tokenizer.templates["detect"] is None:
raise NotImplementedError("Model does not support object detection.")
image = self.encode_image(image, settings)
self.load_encoded_image(image)
prompt_tokens = torch.tensor(
[
self.config.tokenizer.templates["detect"]["prefix"]
+ self.tokenizer.encode(" " + object).ids
+ self.config.tokenizer.templates["detect"]["suffix"]
],
device=self.device,
)
lora = (
variant_state_dict(settings["variant"], device=self.device)
if settings is not None and "variant" in settings
else None
)
_, hidden, next_token, pos = self._prefill_prompt(
prompt_tokens, image.pos, temperature=0, top_p=0, lora=lora
)
hidden = hidden[:, -1:, :]
max_objects = (
settings.get("max_objects", DEFAULT_MAX_OBJECTS)
if settings
else DEFAULT_MAX_OBJECTS
)
objects = self._generate_points(
hidden,
next_token,
pos,
include_size=True,
max_objects=max_objects,
lora=lora,
)
return {"objects": objects}
def point(
self,
image: Union[Image.Image, EncodedImage],
object: str,
settings: Optional[ObjectSamplingSettings] = None,
):
if self.config.tokenizer.templates["point"] is None:
raise NotImplementedError("Model does not support pointing.")
image = self.encode_image(image, settings)
self.load_encoded_image(image)
prompt_tokens = torch.tensor(
[
self.config.tokenizer.templates["point"]["prefix"]
+ self.tokenizer.encode(" " + object).ids
+ self.config.tokenizer.templates["point"]["suffix"]
],
device=self.device,
)
lora = (
variant_state_dict(settings["variant"], device=self.device)
if settings is not None and "variant" in settings
else None
)
_, hidden, next_token, pos = self._prefill_prompt(
prompt_tokens, image.pos, temperature=0, top_p=0, lora=lora
)
hidden = hidden[:, -1:, :]
max_objects = (
settings.get("max_objects", DEFAULT_MAX_OBJECTS)
if settings
else DEFAULT_MAX_OBJECTS
)
objects = self._generate_points(
hidden,
next_token,
pos,
include_size=False,
max_objects=max_objects,
lora=lora,
)
return {"points": objects}
def _detect_gaze(
self,
image: EncodedImage,
source: Tuple[float, float],
force_detect: bool = False,
):
with torch.inference_mode():
before_emb = text_encoder(
torch.tensor(
[self.tokenizer.encode("\n\nPoint:").ids], device=self.device
),
self.text,
)
after_emb = text_encoder(
torch.tensor(
[self.tokenizer.encode(" gaze\n\n").ids], device=self.device
),
self.text,
)
x_emb = encode_coordinate(
torch.tensor([[[source[0]]]], device=self.device, dtype=torch.bfloat16),
self.region,
)
y_emb = encode_coordinate(
torch.tensor([[[source[1]]]], device=self.device, dtype=torch.bfloat16),
self.region,
)
prompt_emb = torch.cat([before_emb, x_emb, y_emb, after_emb], dim=1)
self.load_encoded_image(image)
mask = self.attn_mask[:, :, image.pos : image.pos + prompt_emb.size(1), :]
pos_ids = torch.arange(
image.pos, image.pos + prompt_emb.size(1), dtype=torch.long
)
hidden = self._prefill(prompt_emb, mask, pos_ids, lora=None)
logits = lm_head(hidden, self.text)
next_token = torch.argmax(logits, dim=-1)
pos = image.pos + prompt_emb.size(1)
hidden = hidden[:, -1:, :]
if force_detect:
next_token = torch.tensor([[0]], device=self.device)
if next_token.item() == self.config.tokenizer.eos_id:
return None
gaze = self._generate_points(
hidden, next_token, pos, include_size=False, max_objects=1
)
return gaze[0]
def detect_gaze(
self,
image: Union[Image.Image, EncodedImage],
eye: Optional[Tuple[float, float]] = None,
face: Optional[Dict[str, float]] = None,
unstable_settings: Dict[str, Any] = {},
):
if "force_detect" in unstable_settings:
force_detect = unstable_settings["force_detect"]
else:
force_detect = False
if "prioritize_accuracy" in unstable_settings:
prioritize_accuracy = unstable_settings["prioritize_accuracy"]
else:
prioritize_accuracy = False
if not prioritize_accuracy:
if eye is None:
raise ValueError("eye must be provided when prioritize_accuracy=False")
image = self.encode_image(image)
return {"gaze": self._detect_gaze(image, eye, force_detect=force_detect)}
else:
if (
not isinstance(image, Image.Image)
and "flip_enc_img" not in unstable_settings
):
raise ValueError(
"image must be a PIL Image when prioritize_accuracy=True, "
"or flip_enc_img must be provided"
)
if face is None:
raise ValueError("face must be provided when prioritize_accuracy=True")
encoded_image = self.encode_image(image)
if (
isinstance(image, Image.Image)
and "flip_enc_img" not in unstable_settings
):
flipped_pil = image.copy()
flipped_pil = flipped_pil.transpose(method=Image.FLIP_LEFT_RIGHT)
encoded_flipped_image = self.encode_image(flipped_pil)
else:
encoded_flipped_image = unstable_settings["flip_enc_img"]
N = 10
detections = [
self._detect_gaze(
encoded_image,
(
random.uniform(face["x_min"], face["x_max"]),
random.uniform(face["y_min"], face["y_max"]),
),
force_detect=force_detect,
)
for _ in range(N)
]
detections = [
(gaze["x"], gaze["y"]) for gaze in detections if gaze is not None
]
flipped_detections = [
self._detect_gaze(
encoded_flipped_image,
(
1 - random.uniform(face["x_min"], face["x_max"]),
random.uniform(face["y_min"], face["y_max"]),
),
force_detect=force_detect,
)
for _ in range(N)
]
detections.extend(
[
(1 - gaze["x"], gaze["y"])
for gaze in flipped_detections
if gaze is not None
]
)
if len(detections) < N:
return {"gaze": None}
detections = remove_outlier_points(detections)
mean_gaze = (
sum(gaze[0] for gaze in detections) / len(detections),
sum(gaze[1] for gaze in detections) / len(detections),
)
return {"gaze": {"x": mean_gaze[0], "y": mean_gaze[1]}}
def _is_cjk_char(cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
if (
(cp >= 0x4E00 and cp <= 0x9FFF)
or (cp >= 0x3400 and cp <= 0x4DBF)
or (cp >= 0x2F800 and cp <= 0x2FA1F)
):
return True
return False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136import torch
import torch.nn as nn
import math
from typing import List, Tuple, Union
from .layers import mlp
SpatialRefs = List[Union[Tuple[float, float], Tuple[float, float, float, float]]]
def fourier_features(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
"""
Applies Fourier feature mapping to input tensor x using frequency matrix w. This
projects inputs through sinusoidal functions to create higher dimensional features
that help mitigate spectral bias - the tendency of neural networks to learn
low-frequency functions more easily than high-frequency ones. By explicitly
mapping inputs to higher frequencies through sin/cos transformations, we enable
better learning of fine details and higher frequency patterns.
Args:
x: Input tensor to transform
w: Matrix of frequencies for the Fourier features transformation
Returns:
Concatenated cosine and sine transformed features as a tensor
"""
f = 2 * math.pi * x @ w
return torch.cat([f.cos(), f.sin()], dim=-1)
def encode_coordinate(coord: torch.Tensor, w: nn.Module) -> torch.Tensor:
"""
Takes as input a tensor containing a single float coordinate value (x or y)
and encodes it into hidden states for input to the text model.
Args:
coord: Tensor with single float coordinate value
Returns:
Encoded hidden states tensor for input to text model
"""
return w.coord_encoder(fourier_features(coord, w.coord_features))
def decode_coordinate(hidden_state: torch.Tensor, w: nn.Module) -> torch.Tensor:
"""
Takes as input the last hidden state from the text model and outputs a single logit
representing either an x or y coordinate prediction.
Args:
hidden_state: The final hidden state tensor from the text model.
Returns:
A single logit representing the predicted coordinate value (x or y)
"""
return mlp(hidden_state, w.coord_decoder)
def encode_size(size: torch.Tensor, w: nn.Module) -> torch.Tensor:
"""
Takes a tensor containing width and height values and encodes them into
hidden states for input to the text model.
Args:
size: Tensor with two floats for width and height
Returns:
Encoded hidden states tensor for input to text model
"""
return w.size_encoder(fourier_features(size, w.size_features))
def decode_size(hidden_state: torch.Tensor, w: nn.Module) -> torch.Tensor:
"""
Takes as input the last hidden state from the text model and outputs logits
for 1024 bins representing width and height in log-scale.
The bins are distributed according to the formula:
bin = (log2(size) + 10.0) / 10.0 * 1023.0
where size values are clamped to be at least 1/1024.
To convert from bin back to size:
size = 2^((bin / 1023.0) * 10.0 - 10.0)
Args:
hidden_state: The final hidden state tensor from the text model.
Returns:
A tensor containing logits for 1024 bins for width and height.
Shape is (2, 1024) where the first dimension corresponds to width and height.
"""
return mlp(hidden_state, w.size_decoder).view(2, -1)
def encode_spatial_refs(spatial_refs: SpatialRefs, w: nn.Module) -> torch.Tensor:
"""
Takes a list of spatial references (points or regions) and encodes them into
hidden states for input to the text model.
Args:
spatial_refs: List of spatial references (points or boxes)
- Points are represented as normalized (x, y) tuples
- Boxes are represented as normalized (x_min, y_min, x_max, y_max) tuples
Returns:
{"coords": torch.Tensor, "sizes": Optional[torch.Tensor]}
"""
coords, sizes = [], []
for ref in spatial_refs:
if len(ref) == 2:
coords.append(ref[0])
coords.append(ref[1])
else:
x_c = (ref[0] + ref[2]) / 2
y_c = (ref[1] + ref[3]) / 2
width = ref[2] - ref[0]
height = ref[3] - ref[1]
coords.append(x_c)
coords.append(y_c)
sizes.append([width, height])
coords = torch.tensor(
coords, device=w.coord_features.device, dtype=w.coord_features.dtype
).view(-1, 1)
coords = encode_coordinate(coords, w)
if sizes:
sizes = torch.tensor(
sizes, device=w.size_features.device, dtype=w.size_features.dtype
)
sizes = encode_size(sizes, w)
else:
sizes = None
return {"coords": coords, "sizes": sizes}12345678910111213141516171819202122232425262728293031323334353637383940414243import torch
import torch.nn as nn
from .fourier_features import FourierFeatures
class RegionModel(nn.Module):
def __init__(self):
super().__init__()
self.position_features = FourierFeatures(2, 256)
self.position_encoder = nn.Linear(256, 2048)
self.size_features = FourierFeatures(2, 256)
self.size_encoder = nn.Linear(256, 2048)
self.position_decoder = nn.Linear(2048, 2)
self.size_decoder = nn.Linear(2048, 2)
self.confidence_decoder = nn.Linear(2048, 1)
def encode_position(self, position):
return self.position_encoder(self.position_features(position))
def encode_size(self, size):
return self.size_encoder(self.size_features(size))
def decode_position(self, x):
return self.position_decoder(x)
def decode_size(self, x):
return self.size_decoder(x)
def decode_confidence(self, x):
return self.confidence_decoder(x)
def encode(self, position, size):
return torch.stack(
[self.encode_position(position), self.encode_size(size)], dim=0
)
def decode(self, position_logits, size_logits):
return (
self.decode_position(position_logits),
self.decode_size(size_logits),
self.decode_confidence(size_logits),
)123einops
pyvips-binary==8.16.0
pyvips==2.2.3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748# Ethically sourced from https://github.com/xjdr-alt/entropix
import torch
def precompute_freqs_cis(
dim: int,
end: int,
theta: float = 10000.0,
use_scaled: bool = False,
dtype: torch.dtype = torch.float32,
) -> torch.Tensor:
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=dtype)[: (dim // 2)] / dim))
t = torch.arange(end, dtype=dtype).unsqueeze(1)
freqs = t * freqs.unsqueeze(0)
freqs = torch.exp(1j * freqs)
return torch.stack([freqs.real, freqs.imag], dim=-1)
def apply_rotary_emb(
x: torch.Tensor,
freqs_cis: torch.Tensor,
position_ids: torch.Tensor,
num_heads: int,
rot_dim: int = 32,
interleave: bool = False,
) -> torch.Tensor:
assert rot_dim == freqs_cis.shape[-2] * 2
assert num_heads == x.shape[1]
x_rot, x_pass = x[..., :rot_dim], x[..., rot_dim:]
if interleave:
xq_r = x_rot.float().reshape(*x_rot.shape[:-1], -1, 2)[..., 0]
xq_i = x_rot.float().reshape(*x_rot.shape[:-1], -1, 2)[..., 1]
else:
d_q = x_rot.shape[-1] // 2
xq_r, xq_i = x_rot[..., :d_q], x_rot[..., d_q:]
freqs_cos = freqs_cis[..., 0][position_ids, :].unsqueeze(0).unsqueeze(0)
freqs_sin = freqs_cis[..., 1][position_ids, :].unsqueeze(0).unsqueeze(0)
# Complex multiplication: (a + bi) * (c + di) = (ac - bd) + (ad + bc)i
xq_out_r = xq_r * freqs_cos - xq_i * freqs_sin
xq_out_i = xq_r * freqs_sin + xq_i * freqs_cos
xq_out = torch.stack((xq_out_r, xq_out_i), dim=-1).flatten(-2)
return torch.cat([xq_out.to(x.dtype), x_pass], dim=-1)12345{
"bos_token": "<|endoftext|>",
"eos_token": "<|endoftext|>",
"unk_token": "<|endoftext|>"
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221import torch
import torch.nn as nn
from torch.nn import functional as F
from typing import Optional
from .layers import layer_norm, mlp, QuantizedLinear
from .rope import apply_rotary_emb, precompute_freqs_cis
from .config import TextConfig
def text_encoder(input_ids: torch.Tensor, w: nn.Module):
return F.embedding(input_ids, w.wte)
def attn(
x: torch.Tensor,
w: nn.Module,
freqs_cis: torch.Tensor,
kv_cache: nn.Module,
attn_mask: torch.Tensor,
n_heads: int,
n_kv_heads: int,
position_ids: torch.Tensor,
lora: Optional[dict],
):
bsz, q_len, d_model = x.shape
head_dim = d_model // n_heads
qkv_out = w.qkv(x) # shape: (bsz, q_len, (n_heads + 2*n_kv_heads)*head_dim)
if lora is not None:
qkv_out += F.linear(F.linear(x, lora["qkv"]["A"]), lora["qkv"]["B"])
q_dim = n_heads * head_dim
kv_dim = n_kv_heads * head_dim
q, k, v = qkv_out.split([q_dim, kv_dim, kv_dim], dim=-1)
del qkv_out
q = q.view(bsz, q_len, n_heads, head_dim).transpose(1, 2)
k = k.view(bsz, q_len, n_kv_heads, head_dim).transpose(1, 2)
v = v.view(bsz, q_len, n_kv_heads, head_dim).transpose(1, 2)
q = apply_rotary_emb(q, freqs_cis, position_ids, n_heads)
k = apply_rotary_emb(k, freqs_cis, position_ids, n_kv_heads)
if kv_cache is not None:
k, v = kv_cache.update(position_ids, k, v)
out = F.scaled_dot_product_attention(
q, k, v, attn_mask=attn_mask, enable_gqa=n_heads != n_kv_heads
)
out = out.transpose(1, 2).reshape(bsz, q_len, d_model)
out0 = w.proj(out)
if lora is not None:
out1 = F.linear(F.linear(x, lora["proj"]["A"]), lora["proj"]["B"])
out = out0 + out1
else:
out = out0
return out
def _attn(
x: torch.Tensor,
w: torch.Tensor,
freqs_cis: torch.Tensor,
attn_mask: torch.Tensor,
n_heads: int,
n_kv_heads: int,
):
bsz, q_len, d_model = x.shape
head_dim = d_model // n_heads
pos = 0
qkv_out = w.qkv(x) # shape: (bsz, q_len, (n_heads + 2*n_kv_heads)*head_dim)
q_dim = n_heads * head_dim
kv_dim = n_kv_heads * head_dim
q = qkv_out[..., :q_dim].view(bsz, q_len, n_heads, head_dim).transpose(1, 2)
k = (
qkv_out[..., q_dim : q_dim + kv_dim]
.view(bsz, q_len, n_kv_heads, head_dim)
.transpose(1, 2)
)
v = (
qkv_out[..., q_dim + kv_dim :]
.view(bsz, q_len, n_kv_heads, head_dim)
.transpose(1, 2)
)
position_ids = torch.arange(pos, pos + q_len, dtype=torch.long)
q = apply_rotary_emb(q, freqs_cis, position_ids, n_heads)
k = apply_rotary_emb(k, freqs_cis, position_ids, n_kv_heads)
out = F.scaled_dot_product_attention(
q, k, v, attn_mask=attn_mask, enable_gqa=n_heads != n_kv_heads
)
out = out.transpose(1, 2).reshape(bsz, q_len, d_model)
out = w.proj(out)
return out
def _produce_hidden(inputs_embeds: torch.Tensor, w: nn.Module, config: TextConfig):
hidden_BTC = inputs_embeds
bsz, q_len, d_model = inputs_embeds.shape
attn_mask = torch.zeros(q_len, q_len)
attn_mask[:730, :730] = 1
for i in range(730, q_len):
attn_mask[i, : i + 1] = 1
attn_mask = attn_mask.to(dtype=torch.bool)
for i, block in enumerate(w.blocks):
l_in = layer_norm(hidden_BTC, block.ln)
l_attn = _attn(
x=l_in,
w=block.attn,
freqs_cis=w.freqs_cis,
attn_mask=attn_mask,
n_heads=config.n_heads,
n_kv_heads=config.n_kv_heads,
)
l_mlp = mlp(l_in, block.mlp)
hidden_BTC = hidden_BTC + l_attn + l_mlp
return hidden_BTC
def text_decoder(
x: torch.Tensor,
w: nn.Module,
attn_mask: torch.Tensor,
position_ids: torch.Tensor,
config: TextConfig,
lora: Optional[dict],
):
for i, block in enumerate(w.blocks):
if lora is not None:
layer_lora = lora["text"]["blocks"][str(i)]
mlp_lora = layer_lora["mlp"]
attn_lora = layer_lora["attn"]
else:
mlp_lora = None
attn_lora = None
l_in = layer_norm(x, block.ln)
l_attn = attn(
l_in,
block.attn,
freqs_cis=w.freqs_cis,
kv_cache=block.kv_cache,
attn_mask=attn_mask,
n_heads=config.n_heads,
n_kv_heads=config.n_kv_heads,
position_ids=position_ids,
lora=attn_lora,
)
l_mlp = mlp(l_in, block.mlp, lora=mlp_lora)
x = x + l_attn + l_mlp
return x
def lm_head(hidden_BTC: torch.Tensor, w: nn.Module):
hidden_BC = hidden_BTC[:, -1, :]
hidden_BC = layer_norm(hidden_BC, w.post_ln)
logits = w.lm_head(hidden_BC)
return logits
def _lm_head(hidden_BTC: torch.Tensor, w: nn.Module):
hidden_BTC = layer_norm(hidden_BTC, w.post_ln)
logits = w.lm_head(hidden_BTC)
return logits
def build_text_model(config: TextConfig, dtype: torch.dtype) -> nn.Module:
qkv_dim = int(config.dim * (1 + 2 * config.n_kv_heads / config.n_heads))
linear_cls = QuantizedLinear if config.group_size is not None else nn.Linear
text = nn.ModuleDict(
{
"blocks": nn.ModuleList(
[
nn.ModuleDict(
{
"ln": nn.LayerNorm(config.dim, dtype=dtype),
"attn": nn.ModuleDict(
{
"qkv": linear_cls(config.dim, qkv_dim, dtype=dtype),
"proj": linear_cls(
config.dim, config.dim, dtype=dtype
),
}
),
"mlp": nn.ModuleDict(
{
"fc1": linear_cls(
config.dim, config.ff_dim, dtype=dtype
),
"fc2": linear_cls(
config.ff_dim, config.dim, dtype=dtype
),
}
),
}
)
for _ in range(config.n_layers)
]
),
"post_ln": nn.LayerNorm(config.dim, dtype=dtype),
"lm_head": nn.Linear(config.dim, config.vocab_size, dtype=dtype),
}
)
text.wte = nn.Parameter(torch.empty(config.vocab_size, config.dim, dtype=dtype))
text.register_buffer(
"freqs_cis",
precompute_freqs_cis(config.dim // (2 * config.n_heads), config.max_context),
persistent=False,
)
return text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323{
"add_prefix_space": false,
"added_tokens_decoder": {
"50256": {
"content": "<|endoftext|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"50257": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50258": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50259": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50260": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50261": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50262": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50263": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50264": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50265": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50266": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50267": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50268": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50269": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50270": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50271": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50272": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50273": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50274": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50275": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50276": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50277": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50278": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50279": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50280": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50281": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50282": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50283": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50284": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50285": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50286": {
"content": " ",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50287": {
"content": "\t\t\t\t\t\t\t\t\t",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50288": {
"content": "\t\t\t\t\t\t\t\t",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50289": {
"content": "\t\t\t\t\t\t\t",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50290": {
"content": "\t\t\t\t\t\t",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50291": {
"content": "\t\t\t\t\t",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50292": {
"content": "\t\t\t\t",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50293": {
"content": "\t\t\t",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
},
"50294": {
"content": "\t\t",
"lstrip": false,
"normalized": true,
"rstrip": false,
"single_word": false,
"special": false
}
},
"bos_token": "<|endoftext|>",
"clean_up_tokenization_spaces": true,
"eos_token": "<|endoftext|>",
"model_max_length": 2048,
"tokenizer_class": "CodeGenTokenizer",
"unk_token": "<|endoftext|>"
}1234567891011121314151617181920212223242526272829303132333435363738394041import numpy as np
def remove_outlier_points(points_tuples, k_nearest=2, threshold=2.0):
"""
Robust outlier detection for list of (x,y) tuples.
Only requires numpy.
Args:
points_tuples: list of (x,y) tuples
k_nearest: number of neighbors to consider
threshold: multiplier for median distance
Returns:
list: filtered list of (x,y) tuples with outliers removed
list: list of booleans indicating which points were kept (True = kept)
"""
points = np.array(points_tuples)
n_points = len(points)
# Calculate pairwise distances manually
dist_matrix = np.zeros((n_points, n_points))
for i in range(n_points):
for j in range(i + 1, n_points):
# Euclidean distance between points i and j
dist = np.sqrt(np.sum((points[i] - points[j]) ** 2))
dist_matrix[i, j] = dist
dist_matrix[j, i] = dist
# Get k nearest neighbors' distances
k = min(k_nearest, n_points - 1)
neighbor_distances = np.partition(dist_matrix, k, axis=1)[:, :k]
avg_neighbor_dist = np.mean(neighbor_distances, axis=1)
# Calculate mask using median distance
median_dist = np.median(avg_neighbor_dist)
mask = avg_neighbor_dist <= threshold * median_dist
# Return filtered tuples and mask
filtered_tuples = [t for t, m in zip(points_tuples, mask) if m]
return filtered_tuples1234567891011122024-03-04
2024-03-06
2024-03-13
2024-04-02
2024-05-08
2024-05-20
2024-07-23
2024-08-26
2025-01-09
2025-03-27
2025-04-14
2025-06-21123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from typing import Union, Tuple
from PIL import Image
from .layers import attn, layer_norm, mlp
from .image_crops import overlap_crop_image
from .config import VisionConfig
if torch.backends.mps.is_available():
# Non-divisible input sizes are not implemented on MPS device yet.
# https://github.com/pytorch/pytorch/issues/96056
def adaptive_avg_pool2d(input, output_size):
return F.adaptive_avg_pool2d(input.to("cpu"), output_size).to("mps")
else:
adaptive_avg_pool2d = F.adaptive_avg_pool2d
DeviceLike = Union[str, torch.device, int]
def prepare_crops(
image: Image.Image, config: VisionConfig, device: DeviceLike
) -> Tuple[torch.Tensor, Tuple[int, int]]:
np_image = np.array(image.convert("RGB"))
overlap_crops = overlap_crop_image(
np_image, max_crops=config.max_crops, overlap_margin=config.overlap_margin
)
all_crops = overlap_crops["crops"]
all_crops = np.transpose(all_crops, (0, 3, 1, 2))
all_crops = (
torch.from_numpy(all_crops)
.to(device=device, dtype=torch.bfloat16)
.div_(255.0)
.sub_(0.5)
.div_(0.5)
)
return all_crops, overlap_crops["tiling"]
def create_patches(x, patch_size):
# Original shape: [B, C, H, W]
B, C, H, W = x.shape
P1 = P2 = patch_size
# Step 1: Split H and W dimensions into patches
# [B, C, H/P1, P1, W/P2, P2]
x = x.reshape(B, C, H // P1, P1, W // P2, P2)
# Step 2: Rearrange dimensions to match target shape
# [B, H/P1, W/P2, C, P1, P2]
x = x.permute(0, 2, 4, 1, 3, 5)
# Step 3: Combine dimensions to get final shape
# [B, (H/P1)*(W/P2), C*P1*P2]
x = x.reshape(B, (H // P1) * (W // P2), C * P1 * P2)
return x
def vision_encoder(input_BCHW: torch.Tensor, w: nn.Module, config: VisionConfig):
x = create_patches(input_BCHW, config.enc_patch_size)
x = w.patch_emb(x)
x = x + w.pos_emb
for block in w.blocks:
x = x + attn(layer_norm(x, block.ln1), block.attn, n_heads=config.enc_n_heads)
x = x + mlp(layer_norm(x, block.ln2), block.mlp)
x = layer_norm(x, w.post_ln)
return x
def vision_projection(
global_features: torch.Tensor,
reconstructed: torch.Tensor,
w: nn.Module,
config: VisionConfig,
):
reconstructed = reconstructed.permute(2, 0, 1)
reconstructed = adaptive_avg_pool2d(
reconstructed, output_size=(config.enc_n_layers, config.enc_n_layers)
)
reconstructed = reconstructed.permute(1, 2, 0).view(729, config.enc_dim)
final_features = torch.cat([global_features, reconstructed], dim=-1)
return mlp(final_features, w.proj_mlp)
def build_vision_model(config: VisionConfig, dtype: torch.dtype):
patch_dim = config.enc_patch_size * config.enc_patch_size * config.in_channels
grid_size = config.crop_size // config.enc_patch_size
num_patches = grid_size * grid_size
vision = nn.ModuleDict(
{
"patch_emb": nn.Linear(patch_dim, config.enc_dim, dtype=dtype),
"blocks": nn.ModuleList(
[
nn.ModuleDict(
{
"ln1": nn.LayerNorm(config.enc_dim, dtype=dtype),
"attn": nn.ModuleDict(
{
"qkv": nn.Linear(
config.enc_dim, 3 * config.enc_dim, dtype=dtype
),
"proj": nn.Linear(
config.enc_dim, config.enc_dim, dtype=dtype
),
}
),
"ln2": nn.LayerNorm(config.enc_dim, dtype=dtype),
"mlp": nn.ModuleDict(
{
"fc1": nn.Linear(
config.enc_dim, config.enc_ff_dim, dtype=dtype
),
"fc2": nn.Linear(
config.enc_ff_dim, config.enc_dim, dtype=dtype
),
}
),
}
)
for _ in range(config.enc_n_layers)
]
),
"post_ln": nn.LayerNorm(config.enc_dim, dtype=dtype),
"proj_mlp": nn.ModuleDict(
{
"fc1": nn.Linear(
config.enc_dim * 2, config.proj_inner_dim, dtype=dtype
),
"fc2": nn.Linear(
config.proj_inner_dim, config.proj_out_dim, dtype=dtype
),
}
),
}
)
vision.pos_emb = nn.Parameter(
torch.zeros(1, num_patches, config.enc_dim, dtype=dtype)
)
return vision123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325from typing import Union
import PIL.Image
import torch
import torch.nn.functional as F
from torch import nn
from einops import rearrange
import PIL
from torchvision.transforms.v2 import (
Compose,
Resize,
InterpolationMode,
ToImage,
ToDtype,
Normalize,
)
from transformers.utils import is_flash_attn_2_available
try:
if is_flash_attn_2_available():
from flash_attn.modules.mha import FlashSelfAttention
else:
FlashSelfAttention = None
except ImportError:
FlashSelfAttention = None
class Attention(nn.Module):
def __init__(self, dim, num_heads=16, use_flash_attn=False):
super().__init__()
assert dim % num_heads == 0, "dim should be divisible by num_heads"
self.num_heads = num_heads
self.head_dim = dim // num_heads
self.qkv = nn.Linear(dim, dim * 3)
self.proj = nn.Linear(dim, dim)
if use_flash_attn and FlashSelfAttention is not None:
self.flash_attn = FlashSelfAttention()
else:
self.flash_attn = None
torch.nn.init.kaiming_normal_(
self.qkv.weight, mode="fan_in", nonlinearity="relu"
)
torch.nn.init.kaiming_normal_(
self.proj.weight, mode="fan_in", nonlinearity="relu"
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
if self.flash_attn is not None:
qkv = self.qkv(x)
qkv = rearrange(
qkv, "... (three h d) -> ... three h d", three=3, h=self.num_heads
)
attn_output = self.flash_attn(qkv)
output = rearrange(attn_output, "... h d -> ... (h d)")
output = self.proj(output)
return output
else:
B, N, C = x.shape
qkv = (
self.qkv(x)
.reshape(B, N, 3, self.num_heads, self.head_dim)
.permute(2, 0, 3, 1, 4)
)
q, k, v = qkv.unbind(0)
x = F.scaled_dot_product_attention(q, k, v)
x = x.transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
return x
class VitBlock(nn.Module):
def __init__(self, embed_dim, use_flash_attn=False):
super().__init__()
self.attn = Attention(embed_dim, use_flash_attn=use_flash_attn)
self.mlp = MLP(embed_dim, 4304)
self.norm1 = nn.LayerNorm(embed_dim)
self.norm2 = nn.LayerNorm(embed_dim)
def forward(self, x):
x = x + self.attn(self.norm1(x))
x = x + self.mlp(self.norm2(x))
return x
class VisionTransformer(nn.Module):
def __init__(self, use_flash_attn=False):
super().__init__()
embed_len = 729
embed_dim = 1152
self.patch_embed = LinearPatchEmbedding()
self.pos_embed = nn.Parameter(torch.randn(1, embed_len, embed_dim) * 0.02)
self.blocks = nn.Sequential(
*[VitBlock(embed_dim, use_flash_attn=use_flash_attn) for _ in range(27)]
)
self.norm = nn.LayerNorm(embed_dim)
def forward(self, x):
x = self.patch_embed(x)
x = x + self.pos_embed
for block in self.blocks:
x = block(x)
return self.norm(x)
class EncoderWrapper(nn.Module):
def __init__(self, use_flash_attn=False):
super().__init__()
self.model = nn.ModuleDict({"visual": VisionTransformer(use_flash_attn)})
def forward(self, x):
return self.model["visual"](x)
class LinearPatchEmbedding(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(588, 1152)
def forward(self, x):
b, c, hp1, wp2 = x.shape
p1, p2 = 14, 14
h, w = hp1 // p1, wp2 // p2
x = x.reshape(b, c, h, p1, w, p2)
x = x.permute(0, 2, 4, 1, 3, 5)
x = x.reshape(b, h * w, c * p1 * p2)
return self.linear(x)
class MLP(nn.Module):
def __init__(
self,
in_features: int,
hidden_features: int = None,
out_features: int = None,
) -> None:
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = nn.GELU(approximate="tanh")
self.fc2 = nn.Linear(hidden_features, out_features)
torch.nn.init.kaiming_normal_(
self.fc1.weight, mode="fan_in", nonlinearity="relu"
)
torch.nn.init.kaiming_normal_(
self.fc2.weight, mode="fan_in", nonlinearity="relu"
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.fc1(x)
x = self.act(x)
x = self.fc2(x)
return x
class VisionProjection(nn.Module):
def __init__(self):
super().__init__()
image_embedding_dim = 1152
model_dim = 2048
hidden_dim = model_dim * 4
self.mlp = MLP(image_embedding_dim * 2, hidden_dim, model_dim)
@property
def device(self):
return self.mlp.fc1.weight.device
def forward(self, x):
return self.mlp(x)
def create_patches(image, patch_size=(378, 378)):
assert image.dim() == 3, "Image must be in CHW format"
_, height, width = image.shape # Channels, Height, Width
patch_height, patch_width = patch_size
if height == patch_height and width == patch_width:
return []
# Iterate over the image and create patches
patches = []
for i in range(0, height, patch_height):
row_patches = []
for j in range(0, width, patch_width):
patch = image[:, i : i + patch_height, j : j + patch_width]
row_patches.append(patch)
patches.append(torch.stack(row_patches))
return patches
class VisionEncoder(nn.Module):
def __init__(self, use_flash_attn=False):
super().__init__()
self.encoder = EncoderWrapper(use_flash_attn)
self.projection = VisionProjection()
self.supported_sizes = [(378, 378), (378, 756), (756, 378), (756, 756)]
@property
def device(self):
return self.projection.mlp.fc1.weight.device
@property
def dtype(self):
return self.projection.mlp.fc1.weight.dtype
def preprocess(self, image: PIL.Image.Image):
width, height = image.size
max_dim = max(width, height)
if max_dim < 512:
im_size = (378, 378)
else:
aspect_ratio = width / height
im_size = min(
self.supported_sizes,
key=lambda size: (
abs((size[1] / size[0]) - aspect_ratio),
abs(size[0] - width) + abs(size[1] - height),
),
)
return Compose(
[
Resize(size=im_size, interpolation=InterpolationMode.BICUBIC),
ToImage(),
ToDtype(torch.float32, scale=True),
Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
]
)(image)
def forward(
self, images: Union[PIL.Image.Image, list[PIL.Image.Image], torch.Tensor]
) -> torch.Tensor:
im_list = None
if isinstance(images, torch.Tensor):
# Input must have dimensions (B, C, H, W)
assert (
len(images.shape) == 4
), "Tensor input must have dimensions (B, C, H, W)"
im_list = list(images)
elif isinstance(images, PIL.Image.Image):
im_list = [images]
elif isinstance(images, list):
im_list = images
else:
raise ValueError(
"Input must be a PIL image, list of PIL images, or a tensor"
)
# Preprocess unless the images are already tensors (indicating that
# they have already been preprocessed)
if not isinstance(im_list[0], torch.Tensor):
im_list = [self.preprocess(im.convert("RGB")) for im in im_list]
patches = [create_patches(im) for im in im_list]
flat_patches = [patch for image_patches in patches for patch in image_patches]
# Images may be variable size, and need to be resized to a common size after
# creating patches.
resized_images = [
F.interpolate(im.unsqueeze(0), size=(378, 378), mode="bilinear")
for im in im_list
]
combined_images = torch.cat([*resized_images, *flat_patches], dim=0)
combined_images = combined_images.to(self.device, dtype=self.dtype)
combined_features = self.encoder(combined_images)
full_img_features = combined_features[: len(im_list)]
patch_features = (
combined_features[len(im_list) :].transpose(1, 2).view(-1, 1152, 27, 27)
)
# Reshape patch features back to their original structure
reshaped_patch_features = []
patch_idx = 0
for i, patch_set in enumerate(patches):
if len(patch_set) == 0:
reshaped_patch_features.append(
full_img_features[i].transpose(0, 1).view(1152, 27, 27)
)
else:
sample_features = []
for row_patches in patch_set:
row_len = len(row_patches)
row_features = patch_features[
patch_idx : patch_idx + row_len
] # row_len, T, C
row_features = torch.cat(
list(row_features), dim=2
) # T, C * row_len
patch_idx += row_len
sample_features.append(row_features)
sample_features = torch.cat(sample_features, dim=1)
sample_features = F.interpolate(
sample_features.unsqueeze(0), size=(27, 27), mode="bilinear"
).squeeze(0)
reshaped_patch_features.append(sample_features)
reshaped_patch_features = (
torch.stack(reshaped_patch_features).view(-1, 1152, 729).transpose(1, 2)
)
final_features = torch.cat([full_img_features, reshaped_patch_features], dim=2)
return self.projection(final_features)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292import safetensors
import torch
import torch.nn as nn
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Callable, List
from .layers import AttentionWeights, LayerNormWeights, LinearWeights, MLPWeights
@dataclass
class VisionBlock:
ln1: LayerNormWeights
attn: AttentionWeights
ln2: LayerNormWeights
mlp: MLPWeights
@dataclass
class VisionModel:
patch_emb: LinearWeights
pos_emb: torch.Tensor
blocks: List[VisionBlock]
post_ln: LayerNormWeights
proj_mlp: MLPWeights
@dataclass
class TextBlock:
ln: LayerNormWeights
attn: AttentionWeights
mlp: MLPWeights
@dataclass
class TextModel:
wte: torch.Tensor
blocks: List[TextBlock]
post_ln: LayerNormWeights
lm_head: LinearWeights
@dataclass
class RegionModel:
coord_features: torch.Tensor
coord_encoder: LinearWeights
coord_decoder: MLPWeights
size_features: torch.Tensor
size_encoder: LinearWeights
size_decoder: MLPWeights
@dataclass
class MoondreamModel:
vision: VisionModel
text: TextModel
region: RegionModel
@contextmanager
def safetensors_open(safetensors_file: str):
"""
Simplify interfacing with safetensors files. Eliminates the need to ignore
type errors when using the `safe_open` function.
"""
with safetensors.safe_open(
safetensors_file, framework="pt"
) as st: # pyright: ignore
def get_tensor(name: str) -> torch.Tensor:
return st.get_tensor(name)
def get_keys() -> List[str]:
return st.keys()
get_tensor.keys = get_keys
yield get_tensor
def _load_weights(get_tensor: Callable[[str], torch.Tensor], model: nn.Module) -> None:
"""Internal function to load weights using a tensor getter function."""
model = model.to(dtype=torch.float16)
# Vision Model
model.vision["patch_emb"].weight.data.copy_(
get_tensor("vision_encoder.encoder.model.visual.patch_embed.linear.weight")
)
model.vision["patch_emb"].bias.data.copy_(
get_tensor("vision_encoder.encoder.model.visual.patch_embed.linear.bias")
)
model.vision.pos_emb.data.copy_(
get_tensor("vision_encoder.encoder.model.visual.pos_embed")
)
for i in range(len(model.vision["blocks"])):
prefix = f"vision_encoder.encoder.model.visual.blocks.{i}"
# Layer norms
model.vision["blocks"][i]["ln1"].weight.data.copy_(
get_tensor(f"{prefix}.norm1.weight")
)
model.vision["blocks"][i]["ln1"].bias.data.copy_(
get_tensor(f"{prefix}.norm1.bias")
)
model.vision["blocks"][i]["ln2"].weight.data.copy_(
get_tensor(f"{prefix}.norm2.weight")
)
model.vision["blocks"][i]["ln2"].bias.data.copy_(
get_tensor(f"{prefix}.norm2.bias")
)
# Attention
model.vision["blocks"][i]["attn"]["qkv"].weight.data.copy_(
get_tensor(f"{prefix}.attn.qkv.weight")
)
model.vision["blocks"][i]["attn"]["qkv"].bias.data.copy_(
get_tensor(f"{prefix}.attn.qkv.bias")
)
model.vision["blocks"][i]["attn"]["proj"].weight.data.copy_(
get_tensor(f"{prefix}.attn.proj.weight")
)
model.vision["blocks"][i]["attn"]["proj"].bias.data.copy_(
get_tensor(f"{prefix}.attn.proj.bias")
)
# MLP
model.vision["blocks"][i]["mlp"]["fc1"].weight.data.copy_(
get_tensor(f"{prefix}.mlp.fc1.weight")
)
model.vision["blocks"][i]["mlp"]["fc1"].bias.data.copy_(
get_tensor(f"{prefix}.mlp.fc1.bias")
)
model.vision["blocks"][i]["mlp"]["fc2"].weight.data.copy_(
get_tensor(f"{prefix}.mlp.fc2.weight")
)
model.vision["blocks"][i]["mlp"]["fc2"].bias.data.copy_(
get_tensor(f"{prefix}.mlp.fc2.bias")
)
model.vision["post_ln"].weight.data.copy_(
get_tensor("vision_encoder.encoder.model.visual.norm.weight")
)
model.vision["post_ln"].bias.data.copy_(
get_tensor("vision_encoder.encoder.model.visual.norm.bias")
)
model.vision["proj_mlp"]["fc1"].weight.data.copy_(
get_tensor("vision_encoder.projection.mlp.fc1.weight")
)
model.vision["proj_mlp"]["fc1"].bias.data.copy_(
get_tensor("vision_encoder.projection.mlp.fc1.bias")
)
model.vision["proj_mlp"]["fc2"].weight.data.copy_(
get_tensor("vision_encoder.projection.mlp.fc2.weight")
)
model.vision["proj_mlp"]["fc2"].bias.data.copy_(
get_tensor("vision_encoder.projection.mlp.fc2.bias")
)
# Text Model
model.text.wte.data.copy_(get_tensor("text_model.transformer.embd.wte.weight"))
for i in range(len(model.text["blocks"])):
prefix = f"text_model.transformer.h.{i}"
# Layer norm
model.text["blocks"][i]["ln"].weight.data.copy_(
get_tensor(f"{prefix}.ln.weight")
)
model.text["blocks"][i]["ln"].bias.data.copy_(get_tensor(f"{prefix}.ln.bias"))
# Attention
model.text["blocks"][i]["attn"]["qkv"].weight.data.copy_(
get_tensor(f"{prefix}.mixer.Wqkv.weight")
)
model.text["blocks"][i]["attn"]["qkv"].bias.data.copy_(
get_tensor(f"{prefix}.mixer.Wqkv.bias")
)
model.text["blocks"][i]["attn"]["proj"].weight.data.copy_(
get_tensor(f"{prefix}.mixer.out_proj.weight")
)
model.text["blocks"][i]["attn"]["proj"].bias.data.copy_(
get_tensor(f"{prefix}.mixer.out_proj.bias")
)
# MLP
model.text["blocks"][i]["mlp"]["fc1"].weight.data.copy_(
get_tensor(f"{prefix}.mlp.fc1.weight")
)
model.text["blocks"][i]["mlp"]["fc1"].bias.data.copy_(
get_tensor(f"{prefix}.mlp.fc1.bias")
)
model.text["blocks"][i]["mlp"]["fc2"].weight.data.copy_(
get_tensor(f"{prefix}.mlp.fc2.weight")
)
model.text["blocks"][i]["mlp"]["fc2"].bias.data.copy_(
get_tensor(f"{prefix}.mlp.fc2.bias")
)
model.text["post_ln"].weight.data.copy_(get_tensor("text_model.lm_head.ln.weight"))
model.text["post_ln"].bias.data.copy_(get_tensor("text_model.lm_head.ln.bias"))
model.text["lm_head"].weight.data.copy_(
get_tensor("text_model.lm_head.linear.weight")
)
model.text["lm_head"].bias.data.copy_(get_tensor("text_model.lm_head.linear.bias"))
# Region Model
model.region.coord_features.data.copy_(
get_tensor("region_model.coordinate_features.weight").T
)
model.region["coord_encoder"].weight.data.copy_(
get_tensor("region_model.coordinate_encoder.weight")
)
model.region["coord_encoder"].bias.data.copy_(
get_tensor("region_model.coordinate_encoder.bias")
)
model.region["coord_decoder"]["fc1"].weight.data.copy_(
get_tensor("region_model.coordinate_decoder.fc1.weight")
)
model.region["coord_decoder"]["fc1"].bias.data.copy_(
get_tensor("region_model.coordinate_decoder.fc1.bias")
)
model.region["coord_decoder"]["fc2"].weight.data.copy_(
get_tensor("region_model.coordinate_decoder.fc2.weight")
)
model.region["coord_decoder"]["fc2"].bias.data.copy_(
get_tensor("region_model.coordinate_decoder.fc2.bias")
)
model.region.size_features.data.copy_(
get_tensor("region_model.size_features.weight").T
)
model.region["size_encoder"].weight.data.copy_(
get_tensor("region_model.size_encoder.weight")
)
model.region["size_encoder"].bias.data.copy_(
get_tensor("region_model.size_encoder.bias")
)
model.region["size_decoder"]["fc1"].weight.data.copy_(
get_tensor("region_model.size_decoder.fc1.weight")
)
model.region["size_decoder"]["fc1"].bias.data.copy_(
get_tensor("region_model.size_decoder.fc1.bias")
)
model.region["size_decoder"]["fc2"].weight.data.copy_(
get_tensor("region_model.size_decoder.fc2.weight")
)
model.region["size_decoder"]["fc2"].bias.data.copy_(
get_tensor("region_model.size_decoder.fc2.bias")
)
def load_weights_from_safetensors(weights_file: str, model: nn.Module) -> None:
"""Load weights from a safetensors file into a MoondreamModel instance."""
with safetensors_open(weights_file) as get_tensor:
# Wrap the get_tensor function to handle key normalization
name_map = {k.replace("._orig_mod", ""): k for k in get_tensor.keys()}
_load_weights(lambda x: get_tensor(name_map[x]).to(dtype=torch.float16), model)
def load_weights_from_pt(weights_file: str, model: nn.Module) -> None:
"""Load weights from a PyTorch file into a MoondreamModel instance."""
device = str(torch.empty(0).device)
tensors = torch.load(weights_file, map_location=device, weights_only=True)
tensors = {
k.replace("._orig_mod", ""): v.to(dtype=torch.float16)
for k, v in tensors.items()
}
_load_weights(lambda x: tensors[x], model)
def load_weights_into_model(weights_file: str, model: nn.Module) -> None:
"""
Load weights from either a safetensors or PyTorch file directly into a MoondreamModel instance.
Args:
weights_file: Path to weights file (either .safetensors or .pt)
model: MoondreamModel instance to load weights into
"""
if weights_file.endswith(".safetensors"):
load_weights_from_safetensors(weights_file, model)
else:
load_weights_from_pt(weights_file, model)
# Make all parameters contiguous
for param in model.parameters():
param.data = param.data.contiguous().gitattributes+37-35
README.md+73-1
added_tokens.jsonAdded+40
config.jsonAdded+13
config.pyAdded+94
configuration_moondream.pyAdded+96
fourier_features.pyAdded+18
generation_config.jsonAdded+4
handler.pyAdded+58
hf_moondream.pyAdded+183
image_crops.pyAdded+231
layers.pyAdded+166
lora.pyAdded+82
merges.txtAdded
model.safetensorsAdded+3
modeling_phi.pyAdded+1463
moondream.pyAdded+986
region.pyAdded+136
region_model.pyAdded+43
requirements.txtAdded+3
rope.pyAdded+48
special_tokens_map.jsonAdded+5
text.pyAdded+221
tokenizer.jsonAdded
tokenizer_config.jsonAdded+323
utils.pyAdded+41
versions.txtAdded+12
vision.pyAdded+147
vision_encoder.pyAdded+325
vocab.jsonAdded
weights.pyAdded+292