Instructions to use moondream/moondream3-preview with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use moondream/moondream3-preview with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="moondream/moondream3-preview", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("moondream/moondream3-preview", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use moondream/moondream3-preview with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "moondream/moondream3-preview" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "moondream/moondream3-preview", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/moondream/moondream3-preview
- SGLang
How to use moondream/moondream3-preview with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "moondream/moondream3-preview" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "moondream/moondream3-preview", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "moondream/moondream3-preview" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "moondream/moondream3-preview", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use moondream/moondream3-preview with Docker Model Runner:
docker model run hf.co/moondream/moondream3-preview
Update BF16 weights + code to modelv2 shards (region LN + finetune support)
Browse filesSummary
This PR updates `moondream/moondream3-preview` to the new BF16 codepath, adds region‑head LN, enables finetune adapters (LoRA), and fixes spatial‑ref handling so spatial refs can be provided as inputs without re-encoding during answer generation.
New weights
- Added `modelv2-00001-of-00004.safetensors` … `modelv2-00004-of-00004.safetensors`
- Updated `model.safetensors.index.json` to point to `modelv2-*` as the new default
- Legacy `model-0000x-of-00004.safetensors` are retained for hard‑coded URL compatibility
Region model update
- Region head now applies LN before coord/size decoders (matches the new weights and backend parity)
Finetune / LoRA support
- Adapters are resolved via `finetune_id@step` and fetched from the finetune endpoint
- API-style `model` strings are supported (prefix ignored; `/<finetune_id>@<step>` is parsed)
- Example request format (API):
{ "model": "moondream3-preview/01K...@80", "question": "...", "image_url": "..." }
- Example model usage:
model.query(image, question, settings={"adapter": "01K...@80"})
Files changed (11)
- hf_moondream.py-1
- layers.py+38-13
- lora.py+411-56
- model.safetensors.index.json
- modelv2-00001-of-00004.safetensorsAdded+3
- modelv2-00002-of-00004.safetensorsAdded+3
- modelv2-00003-of-00004.safetensorsAdded+3
- modelv2-00004-of-00004.safetensorsAdded+3
- moondream.py+35-29
- region.py+2
- text.py+12-23
123456import torchimport torch.nn as nnfrom transformers import PreTrainedModel, PretrainedConfigfrom typing import Union12345import torchimport torch.nn as nnfrom transformers import PreTrainedModel, PretrainedConfigfrom typing import Union
4 unmodified lines5678910115 unmodified lines1261271281291301311321331341351361 unmodified line1381391401411421431441451 unmodified line14714814915015115215313 unmodified lines16716816917017117217317417517617717817918018118218318418518618715 unmodified lines2032042052062072082092102112124 unmodified linesfrom dataclasses import dataclassfrom typing import Literal, Optionaltry:from torchao import quantize_from torchao.quantization import int4_weight_only115 unmodified linesact: 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 + x1else:x = x01 unmodified linex0 = w.fc2(x)if lora is not None:x1 = F.linear(F.linear(x, lora["fc2"]["A"]), lora["fc2"]["B"])x = x0 + x1else:x = x01 unmodified linedef moe_mlp(x: torch.Tensor, mlp_module: nn.Module, experts_per_token: int) -> torch.Tensor:B, T, C = x.shapex = x.reshape(-1, C)13 unmodified linesflat_weights = topk_weights.view(-1) # [T*A]# Select expert weightsw1_selected = w1_weight[flat_idxs] # [T*A, H, D]w2_selected = w2_weight[flat_idxs] # [T*A, D, H]# Expand input for all token-expert pairsx_expanded = x.unsqueeze(1).expand(-1, top_k, -1).reshape(-1, C) # [T*A, D]# First linear layer with GeGLU: [T*A, H, D] @ [T*A, D, 1] -> [T*A, H]x1_full = torch.bmm(w1_selected, x_expanded.unsqueeze(-1)).squeeze(-1) # [T*A, H]x1, g = x1_full.chunk(2, dim=-1)x1 = F.gelu(x1) * (g + 1)# Second linear layer: [T*A, D, H] @ [T*A, H, 1] -> [T*A, D]expert_outs = torch.bmm(w2_selected, x1.unsqueeze(-1)).squeeze(-1) # [T*A, D]# Apply weights and reshapeweighted_outs = expert_outs * flat_weights.unsqueeze(-1) # [T*A, D]15 unmodified linesx_tok = x.index_select(0, token_pos)gate_tok = topk_weights[token_pos, which_k]h_full = F.linear(x_tok, mlp_module.fc1.weight[expert_id])h, g = h_full.chunk(2, dim=-1)h = F.gelu(h) * (g + 1)y = F.linear(h, mlp_module.fc2.weight[expert_id])y.mul_(gate_tok.unsqueeze(-1))out.index_add_(0, token_pos, y)4 unmodified lines56789101112131415161718115 unmodified lines1341351361371381391401411421431441451 unmodified line1471481491501511521531 unmodified line15515615715815916016116216316413 unmodified lines17817918018118218318418518618718818919019119219319419519619719819920015 unmodified lines2162172182192202212222232242252262272282292302312322332342352362374 unmodified linesfrom dataclasses import dataclassfrom typing import Literal, Optionalfrom .lora import (DenseLoRALayer,MoELoRALayer,apply_dense_lora,apply_moe_lora_fc1_flat,apply_moe_lora_fc2_flat,)try:from torchao import quantize_from torchao.quantization import int4_weight_only115 unmodified linesact: Literal["gelu_approx"] = "gelu_approx"def mlp(x: torch.Tensor, w: MLPWeights, lora: Optional[DenseLoRALayer] = None) -> torch.Tensor:x0 = w.fc1(x)if lora is not None:x = x0 + apply_dense_lora(x, lora.up_a, lora.up_b)else:x = x01 unmodified linex0 = w.fc2(x)if lora is not None:x = x0 + apply_dense_lora(x, lora.down_a, lora.down_b)else:x = x01 unmodified linedef moe_mlp(x: torch.Tensor,mlp_module: nn.Module,experts_per_token: int,lora: Optional[MoELoRALayer] = None,) -> torch.Tensor:B, T, C = x.shapex = x.reshape(-1, C)13 unmodified linesflat_weights = topk_weights.view(-1) # [T*A]# Select expert weightsw1_selected = w1_weight[flat_idxs]w2_selected = w2_weight[flat_idxs]# Expand input for all token-expert pairsx_expanded = x.unsqueeze(1).expand(-1, top_k, -1).reshape(-1, C) # [T*A, D]# First linear layer with GeGLU: [T*A, H, D] @ [T*A, D, 1] -> [T*A, H]x1_full = torch.bmm(w1_selected, x_expanded.unsqueeze(-1)).squeeze(-1) # [T*A, H]if lora is not None:x1_full = x1_full + apply_moe_lora_fc1_flat(x_expanded, lora, flat_idxs)x1, g = x1_full.chunk(2, dim=-1)x1 = F.gelu(x1) * (g + 1)# Second linear layer: [T*A, D, H] @ [T*A, H, 1] -> [T*A, D]expert_outs = torch.bmm(w2_selected, x1.unsqueeze(-1)).squeeze(-1) # [T*A, D]if lora is not None:expert_outs = expert_outs + apply_moe_lora_fc2_flat(x1, lora, flat_idxs)# Apply weights and reshapeweighted_outs = expert_outs * flat_weights.unsqueeze(-1) # [T*A, D]15 unmodified linesx_tok = x.index_select(0, token_pos)gate_tok = topk_weights[token_pos, which_k]w1 = mlp_module.fc1.weight[expert_id]h_full = F.linear(x_tok, w1)if lora is not None:lora_up_a = lora.up_a[expert_id]lora_up_b = lora.up_b[expert_id]lora_mid = F.linear(x_tok, lora_up_a)h_full = h_full + F.linear(lora_mid, lora_up_b)h, g = h_full.chunk(2, dim=-1)h = F.gelu(h) * (g + 1)w2 = mlp_module.fc2.weight[expert_id]y = F.linear(h, w2)if lora is not None:lora_down_a = lora.down_a[expert_id]lora_down_b = lora.down_b[expert_id]lora_mid = F.linear(h, lora_down_a)y = y + F.linear(lora_mid, lora_down_b)y.mul_(gate_tok.unsqueeze(-1))out.index_add_(0, token_pos, y)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182import functoolsimport osimport shutilimport torchfrom pathlib import Pathfrom urllib.request import Request, urlopenfrom typing import Optionaldef 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() / variantos.makedirs(cache_dir, exist_ok=True)dest = cache_dir / f"{step}.pt"if dest.exists():return destmd_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_keyreq = 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 destdef nest(flat):tree = {}for k, v in flat.items():parts = k.split(".")d = treefor p in parts[:-1]:d = d.setdefault(p, {})d[parts[-1]] = vreturn tree@functools.lru_cache(maxsize=5)def variant_state_dict(variant_id: Optional[str] = None, device: str = "cpu"):if variant_id is None:return Nonestate_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 = keyfor old, new in rename_rules:if old in new_key:new_key = new_key.replace(old, new)new_state_dict[new_key] = tensorreturn nest(new_state_dict)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437import jsonimport osimport reimport shutilfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Dict, Optional, Tuplefrom urllib.request import Request, urlopenimport torchfrom .config import TextConfigclass AdapterLoadError(RuntimeError):passdef _cache_root() -> Path:hf_hub_cache = os.environ.get("HF_HUB_CACHE")if hf_hub_cache:return Path(hf_hub_cache)hf_home = os.environ.get("HF_HOME")if hf_home:return Path(hf_home) / "hub"return Path("~/.cache/huggingface/hub").expanduser()def adapter_cache_dir() -> Path:return _cache_root() / "md_finetunes"def normalize_adapter_id(value: Optional[str]) -> Optional[str]:if not value:return Nonetail = value.split("/")[-1].strip()if "@" not in tail:return Nonereturn taildef parse_adapter_id(adapter_id: str) -> Tuple[str, str]:if not adapter_id or "@" not in adapter_id:raise AdapterLoadError(f"Invalid adapter id '{adapter_id}'. Expected 'finetune_id@step'.")finetune_id, step = adapter_id.split("@", 1)if not finetune_id or not step:raise AdapterLoadError(f"Invalid adapter id '{adapter_id}'. Expected 'finetune_id@step'.")return finetune_id, stepdef _fetch_presigned_url(finetune_id: str, step: str) -> str:endpoint = os.getenv("MOONDREAM_ENDPOINT", "https://api.moondream.ai").rstrip("/")api_key = os.getenv("MOONDREAM_API_KEY")if not api_key:raise AdapterLoadError("MOONDREAM_API_KEY is required to load finetune adapters.")headers = {"User-Agent": "moondream-torch", "X-Moondream-Auth": api_key}url = f"{endpoint}/v1/tuning/finetunes/{finetune_id}/checkpoints/{step}/download"req = Request(url, headers=headers)try:with urlopen(req) as r:payload = json.loads(r.read().decode("utf-8"))except Exception as e:raise AdapterLoadError(f"Failed to fetch adapter URL: {e}") from epresigned = payload.get("url")if not presigned:raise AdapterLoadError("Adapter URL response missing 'url' field.")return presigneddef cached_adapter_path(adapter_id: str) -> Path:finetune_id, step = parse_adapter_id(adapter_id)cache_dir = adapter_cache_dir() / finetune_id / stepcache_dir.mkdir(parents=True, exist_ok=True)for name in ("adapter.pt", "adapter.safetensors"):path = cache_dir / nameif path.exists() and path.stat().st_size > 0:return pathpresigned_url = _fetch_presigned_url(finetune_id, step)dest = cache_dir / "adapter.pt"try:with urlopen(presigned_url) as r, open(dest, "wb") as f:shutil.copyfileobj(r, f)except Exception as e:raise AdapterLoadError(f"Failed to download adapter: {e}") from ereturn destdef _load_state_dict(path: Path, device: torch.device) -> Dict[str, Any]:if path.suffix == ".safetensors":try:from safetensors.torch import safe_openexcept Exception as e:raise AdapterLoadError("safetensors is required to load .safetensors adapters.") from edata = {}with safe_open(str(path), framework="pt") as f:for key in f.keys():data[key] = f.get_tensor(key).to(device=device)return datatry:return torch.load(path, map_location=device, weights_only=True)except TypeError:return torch.load(path, map_location=device)@dataclassclass DenseLoRALayer:up_a: torch.Tensorup_b: torch.Tensordown_a: torch.Tensordown_b: torch.Tensor@dataclassclass MoELoRALayer:up_a: torch.Tensorup_b: torch.Tensordown_a: torch.Tensordown_b: torch.Tensorclass TextLoRA:def __init__(self,text_config: TextConfig,*,rank: int,max_rank: int,dtype: torch.dtype,device: torch.device,adapter_id: Optional[str] = None,) -> None:if rank <= 0:raise AdapterLoadError("LoRA rank must be positive.")if max_rank < rank:raise AdapterLoadError("max_rank must be >= rank.")self.text_config = text_configself.rank = rankself.max_rank = max_rankself.adapter_id = adapter_idmoe_cfg = text_config.moeself.start_layer = moe_cfg.start_layer if moe_cfg else text_config.n_layersif moe_cfg is not None:self.rank_per_expert = rank // moe_cfg.experts_per_tokenif self.rank_per_expert < 1:raise AdapterLoadError(f"rank ({rank}) must be >= experts_per_token ({moe_cfg.experts_per_token})")self.max_rank_per_expert = max_rank // moe_cfg.experts_per_tokenif self.max_rank_per_expert < 1:raise AdapterLoadError(f"max_rank ({max_rank}) must be >= experts_per_token ({moe_cfg.experts_per_token})")else:self.rank_per_expert = 0self.max_rank_per_expert = 0d_model = text_config.dimd_ffn = text_config.ff_dimself.dense: list[DenseLoRALayer] = []for _ in range(self.start_layer):self.dense.append(DenseLoRALayer(up_a=torch.zeros((max_rank, d_model), device=device, dtype=dtype),up_b=torch.zeros((d_ffn, max_rank), device=device, dtype=dtype),down_a=torch.zeros((max_rank, d_ffn), device=device, dtype=dtype),down_b=torch.zeros((d_model, max_rank), device=device, dtype=dtype),))self.moe: list[MoELoRALayer] = []if moe_cfg is not None:num_experts = moe_cfg.num_expertsd_expert = moe_cfg.expert_inner_dimfor _ in range(text_config.n_layers - self.start_layer):self.moe.append(MoELoRALayer(up_a=torch.zeros((num_experts, self.max_rank_per_expert, d_model),device=device,dtype=dtype,),up_b=torch.zeros((num_experts, d_expert * 2, self.max_rank_per_expert),device=device,dtype=dtype,),down_a=torch.zeros((num_experts, self.max_rank_per_expert, d_expert),device=device,dtype=dtype,),down_b=torch.zeros((num_experts, d_model, self.max_rank_per_expert),device=device,dtype=dtype,),))def dense_layer(self, layer_idx: int) -> Optional[DenseLoRALayer]:if layer_idx < len(self.dense):return self.dense[layer_idx]return Nonedef moe_layer(self, layer_idx: int) -> Optional[MoELoRALayer]:moe_idx = layer_idx - self.start_layerif 0 <= moe_idx < len(self.moe):return self.moe[moe_idx]return None@staticmethoddef _pad_axis(tensor: torch.Tensor, target: int, axis: int) -> torch.Tensor:if tensor.shape[axis] == target:return tensorif tensor.shape[axis] > target:raise AdapterLoadError(f"LoRA tensor rank {tensor.shape[axis]} exceeds max {target}")pad_shape = list(tensor.shape)pad_shape[axis] = target - tensor.shape[axis]pad = torch.zeros(pad_shape, device=tensor.device, dtype=tensor.dtype)return torch.cat([tensor, pad], dim=axis)@staticmethoddef detect_rank(state_dict: Dict[str, Any], text_config: TextConfig) -> int:for key, tensor in state_dict.items():if "dense" in key and "up_a" in key:return int(tensor.shape[0])for key, tensor in state_dict.items():if "moe" in key and "up_a" in key:rank_per_expert = int(tensor.shape[1])moe_cfg = text_config.moeif moe_cfg:return rank_per_expert * moe_cfg.experts_per_tokenreturn rank_per_expertraise AdapterLoadError("Could not detect LoRA rank from state dict.")@classmethoddef from_state_dict(cls,state_dict: Dict[str, Any],*,text_config: TextConfig,max_rank: int,dtype: torch.dtype,device: torch.device,adapter_id: Optional[str] = None,) -> "TextLoRA":rank = cls.detect_rank(state_dict, text_config)if rank > max_rank:raise AdapterLoadError(f"Adapter rank ({rank}) exceeds max_rank ({max_rank}).")lora = cls(text_config,rank=rank,max_rank=max_rank,dtype=dtype,device=device,adapter_id=adapter_id,)dense_seen = set()moe_seen = set()pattern = re.compile(r"(dense|moe)\.(\d+)\.(up_a|up_b|down_a|down_b)$")for key, tensor in state_dict.items():match = pattern.search(key)if not match:continuekind, idx_str, name = match.group(1), match.group(2), match.group(3)idx = int(idx_str)arr = tensor.to(device=device, dtype=dtype)if kind == "dense":if idx >= len(lora.dense):raise AdapterLoadError(f"Dense LoRA layer index {idx} out of range.")layer = lora.dense[idx]if name in ("up_a", "down_a"):arr = cls._pad_axis(arr, lora.max_rank, axis=0)else:arr = cls._pad_axis(arr, lora.max_rank, axis=1)setattr(layer, name, arr)dense_seen.add((idx, name))else:if idx >= len(lora.moe):raise AdapterLoadError(f"MoE LoRA layer index {idx} out of range.")layer = lora.moe[idx]if name in ("up_a", "down_a"):arr = cls._pad_axis(arr, lora.max_rank_per_expert, axis=1)else:arr = cls._pad_axis(arr, lora.max_rank_per_expert, axis=2)setattr(layer, name, arr)moe_seen.add((idx, name))for layer_idx in range(len(lora.dense)):for name in ("up_a", "up_b", "down_a", "down_b"):if (layer_idx, name) not in dense_seen:raise AdapterLoadError(f"Adapter missing dense LoRA for layer {layer_idx} ({name}).")for layer_idx in range(len(lora.moe)):for name in ("up_a", "up_b", "down_a", "down_b"):if (layer_idx, name) not in moe_seen:raise AdapterLoadError(f"Adapter missing MoE LoRA for layer {layer_idx} ({name}).")return loradef select_layer_lora(lora: Optional[TextLoRA], layer_idx: int, *, is_moe: bool) -> Optional[object]:if lora is None:return Nonereturn lora.moe_layer(layer_idx) if is_moe else lora.dense_layer(layer_idx)def apply_dense_lora(x: torch.Tensor, lora_a: torch.Tensor, lora_b: torch.Tensor) -> torch.Tensor:b, t, c = x.shapex_flat = x.reshape(-1, c)lora_mid = torch.matmul(x_flat, lora_a.t())lora_out = torch.matmul(lora_mid, lora_b.t())return lora_out.reshape(b, t, -1)def apply_moe_lora_fc1_flat(x_expanded: torch.Tensor, lora: MoELoRALayer, flat_idxs: torch.Tensor) -> torch.Tensor:lora_up_a = lora.up_a[flat_idxs]lora_up_b = lora.up_b[flat_idxs]lora_mid = torch.bmm(lora_up_a, x_expanded.unsqueeze(-1)).squeeze(-1)lora_up = torch.bmm(lora_up_b, lora_mid.unsqueeze(-1)).squeeze(-1)return lora_updef apply_moe_lora_fc2_flat(h: torch.Tensor, lora: MoELoRALayer, flat_idxs: torch.Tensor) -> torch.Tensor:lora_down_a = lora.down_a[flat_idxs]lora_down_b = lora.down_b[flat_idxs]lora_mid = torch.bmm(lora_down_a, h.unsqueeze(-1)).squeeze(-1)lora_down = torch.bmm(lora_down_b, lora_mid.unsqueeze(-1)).squeeze(-1)return lora_down_ADAPTER_CACHE: Dict[Tuple[str, str, str, Tuple], TextLoRA] = {}_CACHE_ORDER: list[Tuple[str, str, str, Tuple]] = []_CACHE_SIZE = 8def _config_key(text_config: TextConfig) -> Tuple:moe = text_config.moemoe_key = Noneif moe is not None:moe_key = (moe.num_experts,moe.start_layer,moe.experts_per_token,moe.expert_inner_dim,)return (text_config.dim,text_config.ff_dim,text_config.n_layers,moe_key,)def load_adapter(adapter_id: Optional[str],*,text_config: TextConfig,device: torch.device,dtype: torch.dtype,max_rank: int = 16,) -> Optional[TextLoRA]:if adapter_id is None:return Noneadapter_id = normalize_adapter_id(adapter_id)if adapter_id is None:return Nonekey = (adapter_id, str(device), str(dtype), _config_key(text_config))cached = _ADAPTER_CACHE.get(key)if cached is not None:return cachedpath = cached_adapter_path(adapter_id)checkpoint = _load_state_dict(path, device)if not isinstance(checkpoint, dict):raise AdapterLoadError("Invalid adapter checkpoint format.")state_dict = checkpoint.get("lora_state_dict", checkpoint)if not isinstance(state_dict, dict):raise AdapterLoadError("Adapter checkpoint missing lora_state_dict.")lora = TextLoRA.from_state_dict(state_dict,text_config=text_config,max_rank=max_rank,dtype=dtype,device=device,adapter_id=adapter_id,)_ADAPTER_CACHE[key] = lora_CACHE_ORDER.append(key)if len(_CACHE_ORDER) > _CACHE_SIZE:old = _CACHE_ORDER.pop(0)_ADAPTER_CACHE.pop(old, None)return lora
123version https://git-lfs.github.com/spec/v1oid sha256:79006ed488cca15b173cd5c0c7c1a467c20aaf5508e13934c36378d071d48c13size 4907406296123version https://git-lfs.github.com/spec/v1oid sha256:40202c61286ec7386d9bbce31d87af3064e42931b10323ed4b3e44158c0521e3size 4736548872123version https://git-lfs.github.com/spec/v1oid sha256:ff46835f23bac47c7409032391e02a095821e274f3faaeea3f826a960db9bf80size 4502742464123version https://git-lfs.github.com/spec/v1oid sha256:0a4d39e1bcb0ab835b9a00c7f458dedca4faf8741fc0b23fd2caf2af4547bca6size 439062876020 unmodified lines2122232425262728293031323 unmodified lines363738394041424344454647484970 unmodified lines12012112212312412555 unmodified lines181182183184185186116 unmodified lines30330430530630730830931031131231394 unmodified lines408409410411412413414415416417418105 unmodified lines524525526527528529530531532533534136 unmodified lines671672673674675676157 unmodified lines83483583683783883984084184284384437 unmodified lines88288388488588688788888989089189220 unmodified linesSpatialRefs,)from .layers import QuantizedLinearfrom .lora import variant_state_dictfrom .utils import remove_outlier_pointsImageEncodingSettings = TypedDict("ImageEncodingSettings",{"variant": str},total=False,)3 unmodified lines"max_tokens": int,"temperature": float,"top_p": float,"variant": str,},total=False,)ObjectSamplingSettings = TypedDict("ObjectSamplingSettings",{"max_objects": int, "variant": str},total=False,)70 unmodified lines"size_decoder": linear_cls(config.region.dim, config.region.size_out_dim, dtype=dtype),})self.region.coord_features = nn.Parameter(55 unmodified linesdtype=self.vision.pos_emb.dtype,)@propertydef device(self):return self.vision.pos_emb.device116 unmodified lineselif 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 "variant" in settingselse None)# Run through text model in addition to the vision encoder, to minimize# re-computation if multiple queries are performed on this image.94 unmodified linesif settingselse DEFAULT_TEMPERATURE)lora = (variant_state_dict(settings["variant"], device=self.device)if settings is not None and "variant" in settingselse None)top_p = settings.get("top_p", DEFAULT_TOP_P) if settings else DEFAULT_TOP_Peos_id = self.config.tokenizer.answer_id105 unmodified lines)top_p = settings.get("top_p", DEFAULT_TOP_P) if settings else DEFAULT_TOP_Peos_id = eos_id if eos_id is not None else self.config.tokenizer.eos_idlora = (variant_state_dict(settings["variant"], device=self.device)if settings is not None and "variant" in settingselse None)_, _, next_token, pos = self._prefill_prompt(prompt_tokens,136 unmodified linesreasoning_dict = {"reasoning": {"text": reasoning_text, "grounding": reasoning_grounding}}else:prompt_tokens[0] += self.config.tokenizer.templates["query"]["suffix"]reasoning_dict = {}157 unmodified linesdevice=self.device,)lora = (variant_state_dict(settings["variant"], device=self.device)if settings is not None and "variant" in settingselse None)_, hidden, next_token, pos = self._prefill_prompt(prompt_tokens, image.pos, temperature=0, top_p=0, lora=lora37 unmodified linesdevice=self.device,)lora = (variant_state_dict(settings["variant"], device=self.device)if settings is not None and "variant" in settingselse None)_, hidden, next_token, pos = self._prefill_prompt(prompt_tokens, image.pos, temperature=0, top_p=0, lora=lora20 unmodified lines2122232425262728293031323 unmodified lines36373839404142434445464748495070 unmodified lines12112212312412512612755 unmodified lines183184185186187188189190191192193194195196197198199200201202203204205206207208209210211116 unmodified lines32832933033133233333494 unmodified lines429430431432433434435105 unmodified lines541542543544545546547136 unmodified lines684685686687688689690157 unmodified lines84884985085185285385437 unmodified lines89289389489589689789820 unmodified linesSpatialRefs,)from .layers import QuantizedLinearfrom .lora import load_adapter, normalize_adapter_idfrom .utils import remove_outlier_pointsImageEncodingSettings = TypedDict("ImageEncodingSettings",{"adapter": str, "model": str},total=False,)3 unmodified lines"max_tokens": int,"temperature": float,"top_p": float,"adapter": str,"model": str,},total=False,)ObjectSamplingSettings = TypedDict("ObjectSamplingSettings",{"max_objects": int, "adapter": str, "model": str},total=False,)70 unmodified lines"size_decoder": linear_cls(config.region.dim, config.region.size_out_dim, dtype=dtype),"ln": nn.LayerNorm(config.region.dim, dtype=dtype),})self.region.coord_features = nn.Parameter(55 unmodified linesdtype=self.vision.pos_emb.dtype,)def _adapter_id_from_settings(self, settings: Optional[dict]) -> Optional[str]:if settings is None:return Noneadapter = settings.get("adapter")if adapter is not None:return normalize_adapter_id(adapter)model_value = settings.get("model")if isinstance(model_value, str):return normalize_adapter_id(model_value)return Nonedef _resolve_lora(self, settings: Optional[dict]) -> Optional[object]:adapter_id = self._adapter_id_from_settings(settings)if adapter_id is None:return Nonereturn load_adapter(adapter_id,text_config=self.config.text,device=self.device,dtype=self.vision.pos_emb.dtype,)@propertydef device(self):return self.vision.pos_emb.device116 unmodified lineselif not isinstance(image, Image.Image):raise ValueError("image must be a PIL Image or EncodedImage")lora = self._resolve_lora(settings)# Run through text model in addition to the vision encoder, to minimize# re-computation if multiple queries are performed on this image.94 unmodified linesif settingselse DEFAULT_TEMPERATURE)lora = self._resolve_lora(settings)top_p = settings.get("top_p", DEFAULT_TOP_P) if settings else DEFAULT_TOP_Peos_id = self.config.tokenizer.answer_id105 unmodified lines)top_p = settings.get("top_p", DEFAULT_TOP_P) if settings else DEFAULT_TOP_Peos_id = eos_id if eos_id is not None else self.config.tokenizer.eos_idlora = self._resolve_lora(settings)_, _, next_token, pos = self._prefill_prompt(prompt_tokens,136 unmodified linesreasoning_dict = {"reasoning": {"text": reasoning_text, "grounding": reasoning_grounding}}spatial_refs = Noneelse:prompt_tokens[0] += self.config.tokenizer.templates["query"]["suffix"]reasoning_dict = {}157 unmodified linesdevice=self.device,)lora = self._resolve_lora(settings)_, hidden, next_token, pos = self._prefill_prompt(prompt_tokens, image.pos, temperature=0, top_p=0, lora=lora37 unmodified linesdevice=self.device,)lora = self._resolve_lora(settings)_, hidden, next_token, pos = self._prefill_prompt(prompt_tokens, image.pos, temperature=0, top_p=0, lora=lora
51 unmodified lines52535455565730 unmodified lines88899091929351 unmodified linesReturns:A single logit representing the predicted coordinate value (x or y)"""return w.coord_decoder(hidden_state)30 unmodified linesA tensor containing logits for 1024 bins for width and height.Shape is (2, 1024) where the first dimension corresponds to width and height."""return w.size_decoder(hidden_state).view(2, -1)51 unmodified lines5253545556575830 unmodified lines8990919293949551 unmodified linesReturns:A single logit representing the predicted coordinate value (x or y)"""hidden_state = w.ln(hidden_state)return w.coord_decoder(hidden_state)30 unmodified linesA tensor containing logits for 1024 bins for width and height.Shape is (2, 1024) where the first dimension corresponds to width and height."""hidden_state = w.ln(hidden_state)return w.size_decoder(hidden_state).view(2, -1)
7 unmodified lines89101112139 unmodified lines23242526272829303132333435363731 unmodified lines69707172737475767778798081822 unmodified lines8586878889909192939495969798991001015 unmodified lines10710810911011111211311411511611711811912024 unmodified lines14514614714814915015112 unmodified lines1641651661671681697 unmodified linesfrom .layers import layer_norm, mlp, QuantizedLinear, moe_mlpfrom .rope import apply_rotary_emb, precompute_freqs_cisfrom .config import TextConfigdef text_encoder(input_ids: torch.Tensor, w: nn.Module):9 unmodified linesn_heads: int,n_kv_heads: int,position_ids: torch.Tensor,lora: Optional[dict] = None,flex_block_mask_slice=None,):bsz, q_len, d_model = x.shapehead_dim = d_model // n_headsqkv_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_dimkv_dim = n_kv_heads * head_dimq, k, v = qkv_out.split([q_dim, kv_dim, kv_dim], dim=-1)31 unmodified linesout = 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 + out1else:out = out0return outdef text_decoder(2 unmodified linesattn_mask: torch.Tensor,position_ids: torch.Tensor,config: TextConfig,lora: Optional[dict] = None,flex_block_mask_slice=None,):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 = Noneattn_lora = Nonel_in = layer_norm(x, block.ln)l_attn = attn(5 unmodified linesn_heads=config.n_heads,n_kv_heads=config.n_kv_heads,position_ids=position_ids,lora=attn_lora,flex_block_mask_slice=flex_block_mask_slice,)if config.moe is not None and i >= config.moe.start_layer:l_mlp = moe_mlp(l_in, block.mlp, config.moe.experts_per_token)else:l_mlp = mlp(l_in, block.mlp, lora=mlp_lora)x = x + l_attn + l_mlp24 unmodified linesdef build_moe_mlp(d_model, d_ffn, n_experts, dtype):# For GeGLU, fc1 needs to output 2 * d_ffn (for gating)return nn.ModuleDict({"router": nn.Linear(d_model, n_experts, dtype=dtype),"fc1": nn.ParameterDict(12 unmodified lines),})def build_text_model(config: TextConfig, dtype: torch.dtype) -> nn.Module:7 unmodified lines8910111213149 unmodified lines24252627282930313233343531 unmodified lines676869707172732 unmodified lines767778798081828384858687885 unmodified lines94959697989910010110210310410510610710824 unmodified lines13313413513613713813912 unmodified lines1521531541551561571587 unmodified linesfrom .layers import layer_norm, mlp, QuantizedLinear, moe_mlpfrom .rope import apply_rotary_emb, precompute_freqs_cisfrom .config import TextConfigfrom .lora import select_layer_loradef text_encoder(input_ids: torch.Tensor, w: nn.Module):9 unmodified linesn_heads: int,n_kv_heads: int,position_ids: torch.Tensor,flex_block_mask_slice=None,):bsz, q_len, d_model = x.shapehead_dim = d_model // n_headsqkv_out = w.qkv(x) # shape: (bsz, q_len, (n_heads + 2*n_kv_heads)*head_dim)q_dim = n_heads * head_dimkv_dim = n_kv_heads * head_dimq, k, v = qkv_out.split([q_dim, kv_dim, kv_dim], dim=-1)31 unmodified linesout = out.transpose(1, 2).reshape(bsz, q_len, d_model)return w.proj(out)def text_decoder(2 unmodified linesattn_mask: torch.Tensor,position_ids: torch.Tensor,config: TextConfig,lora: Optional[object] = None,flex_block_mask_slice=None,):for i, block in enumerate(w.blocks):layer_lora = select_layer_lora(lora, i, is_moe=config.moe is not None and i >= config.moe.start_layer)l_in = layer_norm(x, block.ln)l_attn = attn(5 unmodified linesn_heads=config.n_heads,n_kv_heads=config.n_kv_heads,position_ids=position_ids,flex_block_mask_slice=flex_block_mask_slice,)if config.moe is not None and i >= config.moe.start_layer:l_mlp = moe_mlp(l_in, block.mlp, config.moe.experts_per_token, lora=layer_lora)else:l_mlp = mlp(l_in, block.mlp, lora=layer_lora)x = x + l_attn + l_mlp24 unmodified linesdef build_moe_mlp(d_model, d_ffn, n_experts, dtype):# For GeGLU, fc1 needs to output 2 * d_ffn (for gating)mlp = nn.ModuleDict({"router": nn.Linear(d_model, n_experts, dtype=dtype),"fc1": nn.ParameterDict(12 unmodified lines),})return mlpdef build_text_model(config: TextConfig, dtype: torch.dtype) -> nn.Module: