Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

MiMo-V2.6: native image input (vision tower in torch, image_url parts, --no-vision, 400 without a tower)

YanissAmzafabd8384ae8
diff --git a/tools/mimo/serve.py b/tools/mimo/serve.py
index 0e5d6f7..db0f73d 100644
--- a/tools/mimo/serve.py
+++ b/tools/mimo/serve.py
@@ -15,6 +15,10 @@ from __future__ import annotations
import traceback
import argparse
import asyncio
+import base64
+import collections
+import hashlib
+import io
import json
import os
import re
@@ -45,6 +49,66 @@ SERVE_DEFAULTS: dict[str, Any] = {"temperature": 1.0, "top_p": 0.95, "reasoning_
# The model's own template plus a medium effort level (the model defines none).
DEFAULT_TEMPLATE = Path(__file__).with_name("chat_template.jinja")
+# ---- image input -----------------------------------------------------------------------------------
+# The chat template writes <|vision_start|><|image_pad|><|vision_end|> per image part; the engine swaps each
+# <|image_pad|> for the embedding's alias, which the tokenizer expands to one slot per vision token.
+IMAGE_PAD = "<|image_pad|>"
+MAX_IMAGE_BYTES = 32 * 1024**2
+IMAGE_CACHE_SIZE = 8 # embeddings kept by content hash: a later turn that re-sends the image reuses the KV cache
+
+
+def _bad(reason: str) -> web.HTTPBadRequest:
+ return web.HTTPBadRequest(reason=reason)
+
+
+def extract_images(messages: list[dict[str, Any]]) -> list[str]:
+ """Image URLs of the messages in prompt order (OpenAI image_url parts). Video and audio parts are refused:
+ this server has no such tower, and dropping them silently would let the model invent an answer."""
+ urls = []
+ for m in messages:
+ content = m.get("content") if isinstance(m, dict) else None
+ if not isinstance(content, list):
+ continue
+ for part in content:
+ if not isinstance(part, dict):
+ continue
+ kind = part.get("type")
+ if kind in ("video", "video_url", "audio", "audio_url", "input_audio"):
+ raise _bad(f"{kind} input is not supported by this server (images only)")
+ if kind in ("image_url", "image"):
+ ref = part.get("image_url", part.get("image"))
+ url = ref.get("url") if isinstance(ref, dict) else ref
+ if not isinstance(url, str) or not url:
+ raise _bad("image_url needs a url")
+ urls.append(url)
+ return urls
+
+
+def load_image(url: str) -> tuple[Any, str]:
+ """(PIL image, content hash) from a data: URI, a file:// URL or a local file path."""
+ from PIL import Image
+ if url.startswith("data:"):
+ try:
+ raw = base64.b64decode(url.split(",", 1)[1], validate=False)
+ except Exception as exc: # noqa: BLE001
+ raise _bad(f"bad data URI: {exc}") from exc
+ elif url.startswith(("http://", "https://")):
+ raise _bad("image url must be a data: URI or a local file path (the server does not fetch remote images)")
+ else:
+ path = Path(url[7:] if url.startswith("file://") else url).expanduser()
+ try:
+ if path.stat().st_size > MAX_IMAGE_BYTES:
+ raise _bad("image too large")
+ raw = path.read_bytes()
+ except OSError as exc:
+ raise _bad(f"cannot read image file: {exc}") from exc
+ if len(raw) > MAX_IMAGE_BYTES:
+ raise _bad("image too large")
+ try:
+ return Image.open(io.BytesIO(raw)).convert("RGB"), hashlib.sha256(raw).hexdigest()
+ except Exception as exc: # noqa: BLE001
+ raise _bad(f"cannot decode image: {exc}") from exc
+
def pack_sampling(model_dir: str) -> dict[str, float]:
"""temperature / top_p of the pack's generation_config.json, when it has them."""
@@ -248,7 +312,7 @@ class ResidentEngine:
def __init__(self, model_path: str, drafter_path: str | None = None, ndt: int = DEFAULT_NDT,
spec_gate: bool = False, ctx: int | None = None,
reset_gate_per_request: bool = False,
- dynamic_draft: bool = True, draft_confidence: float = 0.6):
+ dynamic_draft: bool = True, draft_confidence: float = 0.6, vision: bool = True):
# Lossless speculation: every verify row uses the exact R=1 arithmetic, so
# speculative output equals plain greedy output (20/20 prompts). Costs about 5 % chat and
# 12 % code tok/s. EXL3_MIMO_LOSSLESS=0 restores the fast, not bit-identical verify.
@@ -306,6 +370,46 @@ class ResidentEngine:
self.Job = Job
self.ctx = ctx or config_max_position(self.config)
self.num_draft = self.ndt
+ self.vision = None
+ self.emb_cache: collections.OrderedDict = collections.OrderedDict()
+ if vision:
+ self.vision = self._load_vision()
+ self.supports_vision = self.vision is not None
+
+ def _load_vision(self):
+ """The vision tower from <model>/vision/vision.safetensors; None, with a log line, when the pack has none."""
+ t0 = time.perf_counter()
+ try:
+ from vision import load_tower
+ cfg = json.loads((Path(self.model_path) / "config.json").read_text())["vision_config"]
+ startup_health.stage("vision tower")
+ tower = load_tower(self.model_path, cfg, device="cuda:0")
+ except Exception as exc: # noqa: BLE001
+ print(f"msrv: vision tower not loaded ({type(exc).__name__}: {exc}); image input disabled", flush=True)
+ return None
+ print(f"msrv: vision tower loaded in {time.perf_counter() - t0:.1f} s ({tower.nbytes / 2**30:.2f} GiB)", flush=True)
+ return tower
+
+ def image_tokens(self, image: Any) -> int:
+ """Vision tokens one image takes (the tower's resize rule, no GPU)."""
+ from vision import image_grid
+ return image_grid(image.size, self.vision.min_pixels)[2]
+
+ def _embed(self, images: list[tuple[Any, str]]) -> list:
+ """One MMEmbedding per image. The same bytes give the same embedding object (same pseudo token ids), so a
+ history turn that repeats an image still matches the paged KV cache; one prompt never holds an object twice."""
+ out, used = [], set()
+ for image, key in images:
+ emb = self.emb_cache.get(key) if key not in used else None
+ if emb is None:
+ emb = self.vision.get_image_embeddings(image)
+ self.emb_cache[key] = emb
+ self.emb_cache.move_to_end(key)
+ used.add(key)
+ out.append(emb)
+ while len(self.emb_cache) > IMAGE_CACHE_SIZE:
+ self.emb_cache.popitem(last=False)
+ return out
def count_tokens(self, text: str) -> int:
return int(self.tokenizer.encode(text, encode_special_tokens=True).numel())
@@ -324,16 +428,28 @@ class ResidentEngine:
async def generate(self, prompt: str, *, max_tokens: int, temperature: float, top_p: float,
stop: list[str], reset_gate: bool = False,
- cancel: asyncio.Event | None = None) -> AsyncIterator[str]:
+ cancel: asyncio.Event | None = None,
+ images: list | None = None) -> AsyncIterator[str]:
"""Yield incremental decoded text. The caller serializes access to this method.
When `cancel` is set (client gone) the job is cancelled between two generator steps. A step is one
prefill chunk or one decode step, so a drop during prefill stops at the next chunk boundary."""
import torch # noqa: F401 (keeps the ROCm runtime loaded for the worker thread)
from exllamav3.generator.sampler import ComboSampler, GreedySampler
- ids = self.tokenizer.encode(prompt, encode_special_tokens=True)
- if getattr(self, "slot_store", None) is not None:
- self.slot_store.note_prompt(prompt, ids)
+ embs = []
+ if images:
+ embs = await asyncio.get_running_loop().run_in_executor(None, self._embed, images)
+ for emb in embs:
+ prompt = prompt.replace(IMAGE_PAD, emb.text_alias, 1)
+ ids = self.tokenizer.encode(prompt, encode_special_tokens=True, embeddings=embs)
+ if getattr(self, "slot_store", None) is not None:
+ self.slot_store.erase() # embedding ids are per process: a saved image slot could never be matched again
+ room = reply_room(self, int(ids.numel()))
+ max_tokens = min(max_tokens, room) if room else max_tokens
+ else:
+ ids = self.tokenizer.encode(prompt, encode_special_tokens=True)
+ if getattr(self, "slot_store", None) is not None:
+ self.slot_store.note_prompt(prompt, ids)
self.last_stats = {}
if cancel is not None and cancel.is_set():
return # the client left while the request was queued: no prefill
@@ -342,7 +458,7 @@ class ResidentEngine:
if reset_gate:
self.reset_gate()
job = self.Job(input_ids=ids, max_new_tokens=max_tokens, sampler=sampler,
- stop_conditions=list(self.config.eos_token_id_list) + stop)
+ stop_conditions=list(self.config.eos_token_id_list) + stop, embeddings=embs or None)
self.generator.enqueue(job)
loop = asyncio.get_running_loop()
self.last_rounds = 0
@@ -420,6 +536,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
except Exception: # noqa: BLE001
gate = None
return web.json_response({"status": "ok", "source": "kyojin", "model": model_id,
+ "vision": bool(getattr(engine, "supports_vision", False)),
"generator": getattr(engine, "generator", None) is not None,
**startup_health.compiler_health(),
"spec_gate": gate})
@@ -445,7 +562,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
temperature=body.get("temperature", SERVE_DEFAULTS["temperature"]),
top_p=body.get("top_p", SERVE_DEFAULTS["top_p"]), stop=body.get("_stop", []),
reset_gate=body.get("_reset_gate", False),
- cancel=body.get("_cancel")):
+ cancel=body.get("_cancel"), **({"images": body["_images"]} if body.get("_images") else {})):
out.put_nowait(delta)
request_stats.update(getattr(engine, "last_stats", None) or {})
if request_stats:
@@ -501,8 +618,15 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
stops = body.get("stop", [])
body["_stop"] = [stops] if isinstance(stops, str) else list(stops)
body["_reset_gate"] = bool(getattr(app["engine"], "reset_gate_per_request", False))
+ urls = extract_images(body["messages"])
+ if urls and not getattr(engine, "supports_vision", False):
+ raise web.HTTPBadRequest(reason="this server runs without the vision tower (--no-vision or no vision weights in the model folder): it cannot read images")
prompt = render_prompt(template, body["messages"], body.get("tools"), **template_kwargs(body))
- prompt_tokens = engine.count_tokens(prompt)
+ if len(urls) != prompt.count(IMAGE_PAD):
+ raise web.HTTPBadRequest(reason="image parts and image placeholders do not match (the chat template must write one image placeholder per image part)")
+ images = [load_image(u) for u in urls]
+ body["_images"] = images or None
+ prompt_tokens = engine.count_tokens(prompt) + sum(engine.image_tokens(im) - 1 for im, _ in images)
body["_prompt_tokens"] = prompt_tokens
body["_room"] = reply_room(engine, prompt_tokens)
body["_prompt"] = prompt
@@ -786,6 +910,7 @@ def main() -> None:
parser.add_argument("--model-id", default=DEFAULT_MODEL_ID)
parser.add_argument("--drafter", default=None,
help="drafter directory (default: $MIMO_DRAFTER, <model>/drafter, then <model>-drafter)")
+ parser.add_argument("--no-vision", action="store_true", help="do not load the vision tower (saves 1.5 GB; image requests get HTTP 400)")
parser.add_argument("--ctx", "-c", type=int, default=0,
help="KV cache size in tokens; 0 = min(config max_position, 131072)")
parser.add_argument("--ndt", type=int, default=DEFAULT_NDT)
@@ -837,7 +962,7 @@ def main() -> None:
print(f"msrv: no drafter found ({explicit or 'looked in <model>/drafter and <model>-drafter'}); "
"decoding without speculation", flush=True)
- stages = (["drafter weights"] if drafter else []) + ["target weights", "engine setup"]
+ stages = (["drafter weights"] if drafter else []) + ["target weights", "engine setup"] + ([] if args.no_vision else ["vision tower"])
startup_health.check_model_dir("msrv", args.model)
startup_health.start("mimo", stages, args.host, args.port, routes=ROUTES)
startup_health.report_compiler()
@@ -847,17 +972,24 @@ def main() -> None:
ctx = args.ctx or min(config_max_position(probe), 131072)
engine = ResidentEngine(args.model, drafter, ndt=args.ndt, spec_gate=args.spec_gate, ctx=ctx,
reset_gate_per_request=args.spec_gate_reset_per_request,
- dynamic_draft=args.dynamic_draft, draft_confidence=args.draft_confidence)
+ dynamic_draft=args.dynamic_draft, draft_confidence=args.draft_confidence,
+ vision=not args.no_vision)
from exllamav3.generator.slot_store import SlotStore
engine.slot_store = SlotStore(engine.generator, [c for c in (engine.cache, engine.draft_cache) if c is not None],
args.slot_save_path, args.model_id)
template = Path(args.chat_template or DEFAULT_TEMPLATE).expanduser().read_text(encoding="utf-8")
+ if engine.supports_vision: # the first tower pass pays kernel setup and allocator growth: not on the first user image
+ from PIL import Image
+ t0 = time.perf_counter()
+ engine._embed([(Image.new("RGB", (448, 448), (127, 127, 127)), "warmup")])
+ engine.emb_cache.clear()
+ print(f"msrv: vision warm-up {time.perf_counter() - t0:.1f} s", flush=True)
except BaseException as exc: # noqa: BLE001
startup_health.abort(f"{type(exc).__name__}: {exc}")
raise
print(f"msrv: model={args.model} drafter={drafter} ndt={args.ndt} "
f"spec_gate={engine.spec_gate_on} ctx={ctx} "
- f"max_position={config_max_position(engine.config)}", flush=True)
+ f"max_position={config_max_position(engine.config)} vision={engine.supports_vision}", flush=True)
app = create_app(engine, args.model_id, template)
sock = startup_health.finish() # the early listener's open socket: no refused connection
if sock is not None:
diff --git a/tools/mimo/test_serve.py b/tools/mimo/test_serve.py
index a6976c6..3b85ebc 100644
--- a/tools/mimo/test_serve.py
+++ b/tools/mimo/test_serve.py
@@ -558,5 +558,39 @@ class ServeTests(unittest.TestCase):
self.assertEqual(v["llamacpp:prompt_tokens_total"], float(sum(engine.count_tokens(p) for p in engine.prompts)))
+ def test_image_request_without_a_tower_is_a_clear_400_never_dropped(self):
+ from aiohttp.test_utils import TestClient, TestServer
+ tpl = ("{% for m in messages %}<|im_start|>{{ m.role }}\n{% for p in m.content %}"
+ "{% if p.type == 'image_url' %}<|vision_start|><|image_pad|><|vision_end|>{% else %}{{ p.text }}{% endif %}"
+ "{% endfor %}<|im_end|>{% endfor %}<|im_start|>assistant\n")
+ msgs = [{"role": "user", "content": [{"type": "text", "text": "what is this"},
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}]}]
+
+ async def check():
+ eng = FakeEngine("x") # no supports_vision attribute: a text-only server
+ client = TestClient(TestServer(serve.create_app(eng, "m", tpl)))
+ await client.start_server()
+ r = await client.post("/v1/chat/completions", json={"model": "m", "messages": msgs})
+ out = (r.status, await r.json(), eng.prompts)
+ await client.close()
+ return out
+
+ status, body, prompts = run(check())
+ self.assertEqual(status, 400)
+ self.assertIn("without the vision tower", body["error"]["message"])
+ self.assertEqual(prompts, [])
+
+ def test_video_and_audio_parts_are_refused(self):
+ for kind in ("video_url", "input_audio"):
+ with self.assertRaises(Exception):
+ serve.extract_images([{"role": "user", "content": [{"type": kind, kind: {"url": "x"}}]}])
+
+ def test_extract_images_keeps_prompt_order(self):
+ msgs = [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "a"}}, {"type": "text", "text": "t"}]},
+ {"role": "assistant", "content": "ok"},
+ {"role": "user", "content": [{"type": "image_url", "image_url": "b"}]}]
+ self.assertEqual(serve.extract_images(msgs), ["a", "b"])
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tools/mimo/vision.py b/tools/mimo/vision.py
new file mode 100644
index 0000000..44b6546
--- /dev/null
+++ b/tools/mimo/vision.py
@@ -0,0 +1,219 @@
+"""MiMo-V2.6 native image input: the vision tower, the image preprocessing and the embedding builder.
+
+The tower (28 blocks, hidden 1280, 4 full-attention blocks and 24 sliding-window blocks with attention sinks, a
+2x2 spatial merger onto the 4096-wide text embeddings) is re-implemented here from the reference code in the
+pack (`modeling_mimo_v2.py`, class MiMoVisionTransformer). Its weights are not part of the EXL3 text pack: they sit
+in `<model dir>/vision/vision.safetensors` (bf16, tensors `visual.*`, 1.46 GB, cut from the upstream
+`model_pp0_ep0_shard0.safetensors`). The tower runs in plain torch, outside the quantised model.
+
+Preprocessing follows the Qwen2-VL image processor that the sibling MiMo-V2.5 release publishes
+(`preprocessor_config.json`: patch 16, temporal patch 2, merge 2, CLIP mean/std); the pack has no such file.
+
+Memory: 1.46 GB of bf16 weights. Time: one forward over S = (H/16)*(W/16) patches; S is capped by MIMO_IMAGE_MAX_PIXELS.
+"""
+from __future__ import annotations
+
+import math
+import os
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+
+VISION_FILE = os.path.join("vision", "vision.safetensors")
+IMAGE_MEAN = (0.48145466, 0.4578275, 0.40821073)
+IMAGE_STD = (0.26862954, 0.26130258, 0.27577711)
+PATCH, TEMPORAL, MERGE = 16, 2, 2
+FACTOR = PATCH * MERGE
+# The pack config allows 8 388 608 pixels (32 768 patches); one tower pass at that size needs far more
+# attention memory than is worth it on the box. 2 097 152 pixels = 8192 patches = 2048 text tokens.
+DEFAULT_MAX_PIXELS = 2_097_152
+
+
+def max_pixels(config_max: int | None = None) -> int:
+ cap = int(os.environ.get("MIMO_IMAGE_MAX_PIXELS", DEFAULT_MAX_PIXELS))
+ return min(cap, config_max) if config_max else cap
+
+
+def smart_resize(height: int, width: int, min_pixels: int, max_px: int) -> tuple[int, int]:
+ """(new height, new width): multiples of 32, pixel count in [min_pixels, max_px], aspect kept."""
+ if height < FACTOR or width < FACTOR:
+ # too small: scale up so that the short side reaches the factor
+ s = FACTOR / min(height, width)
+ height, width = math.ceil(height * s), math.ceil(width * s)
+ if max(height, width) / min(height, width) > 200:
+ raise ValueError("image aspect ratio must be smaller than 200")
+ h = round(height / FACTOR) * FACTOR
+ w = round(width / FACTOR) * FACTOR
+ if h * w > max_px:
+ beta = math.sqrt(height * width / max_px)
+ h = max(FACTOR, math.floor(height / beta / FACTOR) * FACTOR)
+ w = max(FACTOR, math.floor(width / beta / FACTOR) * FACTOR)
+ elif h * w < min_pixels:
+ beta = math.sqrt(min_pixels / (height * width))
+ h = math.ceil(height * beta / FACTOR) * FACTOR
+ w = math.ceil(width * beta / FACTOR) * FACTOR
+ return h, w
+
+
+def image_grid(size: tuple[int, int], min_pixels: int = 8192, max_px: int | None = None):
+ """(grid_h, grid_w, text tokens) for a PIL size (width, height), without touching the pixels."""
+ h, w = smart_resize(size[1], size[0], min_pixels, max_px or max_pixels())
+ gh, gw = h // PATCH, w // PATCH
+ return gh, gw, (gh // MERGE) * (gw // MERGE)
+
+
+def preprocess(image, min_pixels: int = 8192, max_px: int | None = None):
+ """PIL image -> (patches [S, 1536] float32, (grid_t, grid_h, grid_w)). Patch order: merge-group major."""
+ from PIL import Image
+ if image.mode != "RGB":
+ rgba = image.convert("RGBA")
+ bg = Image.new("RGBA", rgba.size, "WHITE")
+ bg.paste(rgba, (0, 0), rgba)
+ image = bg.convert("RGB")
+ h, w = smart_resize(image.height, image.width, min_pixels, max_px or max_pixels())
+ if (w, h) != image.size:
+ image = image.resize((w, h), resample=Image.BICUBIC)
+ a = np.asarray(image, dtype=np.float32) / 255.0
+ a = (a - np.array(IMAGE_MEAN, np.float32)) / np.array(IMAGE_STD, np.float32)
+ a = a.transpose(2, 0, 1) # C H W
+ a = np.tile(a[None], (TEMPORAL, 1, 1, 1)) # T C H W (a still image is repeated)
+ gh, gw = h // PATCH, w // PATCH
+ a = a.reshape(1, TEMPORAL, 3, gh // MERGE, MERGE, PATCH, gw // MERGE, MERGE, PATCH)
+ a = a.transpose(0, 3, 6, 4, 7, 2, 1, 5, 8) # t, h/m, w/m, m, m, C, T, p, p
+ return torch.from_numpy(np.ascontiguousarray(a.reshape(gh * gw, 3 * TEMPORAL * PATCH * PATCH))), (1, gh, gw)
+
+
+class VisionTower:
+ """Plain-torch MiMo vision tower. Weights are loaded once, forward() maps patches to text-width embeddings."""
+
+ def __init__(self, path: str, cfg: dict, device: str = "cuda", dtype: torch.dtype = torch.bfloat16):
+ from safetensors import safe_open
+ self.device, self.dtype = device, dtype
+ self.depth = cfg["depth"]
+ self.dim = cfg["hidden_size"]
+ self.heads = cfg["num_heads"]
+ self.kv_heads = cfg.get("num_key_value_heads", self.heads)
+ self.head_dim = cfg.get("qk_channels", 64)
+ self.full = set(cfg.get("fullatt_block_indexes", []))
+ self.types = cfg.get("vit_window_attn_types") or [-1] * self.depth
+ self.window = cfg.get("visual_token_window_size", -1)
+ self.sinks = bool(cfg.get("use_sink", False))
+ self.eps = 1e-6
+ self.min_pixels = 8192
+ w = {}
+ with safe_open(path, framework="pt", device="cpu") as f:
+ for k in f.keys():
+ w[k] = f.get_tensor(k).to(device=device, dtype=dtype)
+ self.w = w
+ self.conv = w["visual.patch_embed.proj.weight"].reshape(self.dim, -1) # kernel = stride: a linear map
+ self.inv_freq = 1.0 / (10000.0 ** (torch.arange(0, self.head_dim // 2, 2, dtype=torch.float) / (self.head_dim // 2)))
+ self.nbytes = sum(t.numel() * t.element_size() for t in w.values())
+
+ # -- helpers (mirror MiMoVisionTransformer) ---------------------------------------------------------------
+ @staticmethod
+ def _rot_half(x):
+ h = x.shape[-1] // 2
+ return torch.cat((-x[..., h:], x[..., :h]), dim=-1)
+
+ def _pos_emb(self, gh: int, gw: int):
+ m = MERGE
+ hp = torch.arange(gh).unsqueeze(1).expand(-1, gw).reshape(gh // m, m, gw // m, m).permute(0, 2, 1, 3).flatten()
+ wp = torch.arange(gw).unsqueeze(0).expand(gh, -1).reshape(gh // m, m, gw // m, m).permute(0, 2, 1, 3).flatten()
+ pos = torch.stack([hp, wp], dim=-1)
+ table = torch.outer(torch.arange(max(gh, gw), dtype=torch.float), self.inv_freq)
+ r = table[pos].flatten(1)
+ return torch.cat((r, r), dim=-1)
+
+ @staticmethod
+ def _apply_index(x, index):
+ return x.unflatten(0, (-1, MERGE * MERGE))[index].flatten(0, 1)
+
+ def _ln(self, x, w): # RMSNorm
+ xf = x.float()
+ return (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps)).to(x.dtype) * w
+
+ def _attn(self, x, i, cos, sin, full_attn):
+ W, S = self.w, x.shape[0]
+ p = f"visual.blocks.{i}.attn."
+ qkv = F.linear(x, W[p + "qkv.weight"], W[p + "qkv.bias"])
+ qd, kd = self.heads * self.head_dim, self.kv_heads * self.head_dim
+ q = qkv[:, :qd].view(S, self.heads, self.head_dim)
+ k = qkv[:, qd:qd + kd].view(S, self.kv_heads, self.head_dim)
+ v = qkv[:, qd + kd:].view(S, self.kv_heads, self.head_dim)
+ c, s = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float()
+ q = (q.float() * c + self._rot_half(q.float()) * s).to(x.dtype)
+ k = (k.float() * c + self._rot_half(k.float()) * s).to(x.dtype)
+ g = self.heads // self.kv_heads
+ if g > 1:
+ k, v = k.repeat_interleave(g, dim=1), v.repeat_interleave(g, dim=1)
+ q, k, v = q.transpose(0, 1), k.transpose(0, 1), v.transpose(0, 1) # H S D
+ sink = W.get(p + "sinks") if (self.sinks and not full_attn) else None
+ win = self.window if (not full_attn and self.window > 0) else 0
+ scale = self.head_dim ** -0.5
+ out = torch.empty_like(q)
+ cols = torch.arange(S, device=x.device)
+ blk = max(64, int(2**27 // max(S, 1) // self.heads)) # query rows per chunk (bounded scores buffer)
+ for a in range(0, S, blk):
+ b = min(S, a + blk)
+ sc = torch.matmul(q[:, a:b].float(), k.float().transpose(1, 2)) * scale # H R S
+ if win:
+ rows = torch.arange(a, b, device=x.device).unsqueeze(1)
+ sc = sc.masked_fill(((rows - cols).abs() > win).unsqueeze(0), float("-inf"))
+ if sink is not None:
+ sc[:, :, 0] += sink.float().view(-1, 1)
+ out[:, a:b] = torch.matmul(torch.softmax(sc, dim=-1).to(v.dtype), v)
+ o = out.transpose(0, 1).reshape(S, -1)
+ return F.linear(o, W[p + "proj.weight"], W[p + "proj.bias"])
+
+ @torch.no_grad()
+ def forward(self, patches: torch.Tensor, grid: tuple[int, int, int]) -> torch.Tensor:
+ """patches [S, 1536] from preprocess(), grid (t, h, w) -> embeddings [S/4, 4096] in the original token order."""
+ W = self.w
+ t, gh, gw = grid
+ assert t == 1, "still images only"
+ x = F.linear(patches.to(self.device, self.dtype), self.conv)
+ emb = self._pos_emb(gh, gw).to(self.device)
+ row = (emb.cos(), emb.sin())
+ idx = torch.arange((gh // MERGE) * (gw // MERGE)).reshape(gh // MERGE, gw // MERGE).t().reshape(-1).to(self.device)
+ rev = torch.argsort(idx)
+ ce = self._apply_index(emb, idx)
+ col = (ce.cos(), ce.sin())
+ for i in range(self.depth):
+ ty = self.types[i]
+ if ty == 1 and (i == 0 or self.types[i - 1] != 1):
+ x = self._apply_index(x, idx)
+ if i > 0 and ty != 1 and self.types[i - 1] == 1:
+ x = self._apply_index(x, rev)
+ cos, sin = col if ty == 1 else row
+ p = f"visual.blocks.{i}."
+ x = x + self._attn(self._ln(x, W[p + "norm1.weight"]), i, cos, sin, i in self.full)
+ h = self._ln(x, W[p + "norm2.weight"])
+ h = F.silu(F.linear(h, W[p + "mlp.gate_proj.weight"], W[p + "mlp.gate_proj.bias"])) * \
+ F.linear(h, W[p + "mlp.up_proj.weight"], W[p + "mlp.up_proj.bias"])
+ x = x + F.linear(h, W[p + "mlp.down_proj.weight"], W[p + "mlp.down_proj.bias"])
+ # the last block (27) is a full-attention block in row order; the layout is already original here
+ x = F.layer_norm(x, (self.dim,), W["visual.merger.ln_q.weight"], W.get("visual.merger.ln_q.bias"), 1e-6)
+ x = x.reshape(-1, self.dim * MERGE * MERGE)
+ x = F.gelu(F.linear(x, W["visual.merger.mlp.0.weight"], W.get("visual.merger.mlp.0.bias")))
+ return F.linear(x, W["visual.merger.mlp.2.weight"], W.get("visual.merger.mlp.2.bias"))
+
+ def get_image_embeddings(self, image, text_alias: str | None = None):
+ """PIL image -> MMEmbedding whose token string is only the N placeholder rows (the chat template already
+ writes <|vision_start|> and <|vision_end|> around the single <|image_pad|>)."""
+ from exllamav3.tokenizer import MMEmbedding
+ patches, grid = preprocess(image, self.min_pixels)
+ emb = self.forward(patches, grid).to(torch.float16).cpu()
+ n = emb.shape[0]
+ mme = MMEmbedding(embeddings=emb, text_alias=text_alias,
+ token_string=torch.full((1, n), -1, dtype=torch.long))
+ mme.metadata.update({"original_size": image.size, "preprocessed_size": (grid[2] * PATCH, grid[1] * PATCH),
+ "model_architecture": "MiMoV2ForCausalLM"})
+ return mme
+
+
+def load_tower(model_dir: str, cfg: dict, device: str = "cuda"):
+ path = os.path.join(model_dir, VISION_FILE)
+ if not os.path.isfile(path):
+ raise FileNotFoundError(f"no vision weights at {path}")
+ return VisionTower(path, cfg, device=device)