"""Request-scoped evidence and persistent image/text recall shipped with the V18 checkpoint.""" from __future__ import annotations import hashlib import io import json import math import re from collections import OrderedDict from pathlib import Path import torch from PIL import Image from safetensors import SafetensorError from safetensors.torch import load, load_file, save from .memory_v18 import absence_reader_input from .store_v18 import ( EventStore, query_references, record_links, source_reference as normalize_reference, ) def components_for(model): base = model.model text = getattr(base, "language_model", base) if getattr(text, "memory_v18", None) is None: raise ValueError("Load Inkling with text_config.v18_memory_enabled=True") return text.memory_v18 def freeze_backbone(model): model.requires_grad_(False) components = components_for(model) components.requires_grad_(True) return components def _device(module): return next(module.parameters()).device def _image(obj): if isinstance(obj, Image.Image): return obj with Image.open(io.BytesIO(obj)) as image: return image.copy() @torch.no_grad() def _source_parts(model, processor, text, images): """Canonical evidence order is source text followed by original images in occurrence order.""" embedding = model.get_input_embeddings() device = _device(embedding) parts, spans = [], [] offset = 0 if text: ids = processor.tokenizer(text, add_special_tokens=False, return_tensors="pt")[ "input_ids" ].to(device) if ids.shape[1]: parts.append(embedding(ids)[0]) offset = ids.shape[1] spans.append({"kind": "text", "start": 0, "end": offset}) for i, obj in enumerate(images): image = _image(obj) inp = processor.image_processor(images=[image], return_tensors="pt") tower = model.model.vision_tower params = next(tower.parameters()) grid = inp["image_grid_thw"] pixels = inp["pixel_values"].to(device=params.device, dtype=params.dtype) features = model.get_image_features( pixels, grid, return_dict=True ).pooler_output[0] parts.append(features.to(device=device, dtype=embedding.weight.dtype)) cell = processor.image_processor.size spans.append( dict( kind="image", image=i, start=offset, end=offset + len(features), grid=grid[0].tolist(), width=image.width, height=image.height, cell_width=cell["width"], cell_height=cell["height"], ) ) offset += len(features) if not parts: raise ValueError("An event needs at least one text or image token") return torch.cat(parts), spans def _source_geometry(processor, text, images): """Recover token coordinates for Inkling's native pad-to-grid processor without running vision.""" end = ( len(processor.tokenizer(text, add_special_tokens=False)["input_ids"]) if text else 0 ) spans = [dict(kind="text", start=0, end=end)] if end else [] cell = processor.image_processor.size for i, data in enumerate(images): with Image.open(io.BytesIO(data)) as im: width, height = im.size rows, cols = ( math.ceil(height / cell["height"]), math.ceil(width / cell["width"]), ) spans.append( dict( kind="image", image=i, start=end, end=end + rows * cols, grid=[1, rows, cols], width=width, height=height, cell_width=cell["width"], cell_height=cell["height"], ) ) end += rows * cols if not end: raise ValueError("An event needs at least one text or image token") return spans def encode_source(model, processor, text, images=()): return _source_parts(model, processor, text, images)[0] class EvidenceContext: """Create once per prompt. Anchors are absolute, causal position IDs of the last question token.""" def __init__(self, anchors, provider, *, allow_skip=False): self.anchors = tuple(int(pos) for pos in anchors) if not self.anchors or min(self.anchors) < 0: raise ValueError( "anchors must contain a nonnegative position for each example" ) self.provider = provider self.allow_skip = allow_skip self.queries = {} self._evidence = {} self.read_status = {} self.loop_num_passes = None def bind_loop_num_passes(self, count): """A prefix and its saved reads belong to the schedule which produced them.""" if self.loop_num_passes is not None and self.loop_num_passes != count: raise ValueError( "Changing loop_num_passes requires a fresh evidence context and prefix cache" ) self.loop_num_passes = count def rebase_anchor(self, anchor): """Set the absolute question boundary after joining a prepared query with a cached history.""" if ( self.loop_num_passes is not None or self._evidence or len(self.anchors) != 1 or type(anchor) is not int or anchor < 0 ): raise ValueError("Anchor may only be set on a fresh single-prompt context") self.anchors = (anchor,) def begin_forward(self, position_ids, attention_mask): return _EvidenceView(self, position_ids, attention_mask) class _EvidenceView: """Each forward gets its own position mask even if checkpoint backward runs much later.""" def __init__(self, owner, position_ids, attention_mask): self.owner = owner self.positions = position_ids self.mask = ( attention_mask if isinstance(attention_mask, torch.Tensor) and attention_mask.ndim == 2 else None ) self.layout = None self.bound = {} def _rows(self, states): if self.layout is None: batch, length = states.shape[:2] n = len(self.owner.anchors) if batch % n: raise ValueError( "Expanded batch must preserve the prompt/beam grouping" ) pos = self.positions.reshape(-1, length).expand(batch, -1) mask = ( torch.ones_like(pos, dtype=torch.bool) if self.mask is None else self.mask[:, -length:].to(pos.device).expand_as(pos).bool() ) anchors = torch.tensor( self.owner.anchors, device=pos.device ).repeat_interleave(batch // n) hit = (pos == anchors[:, None]) & mask # One small device-to-host transfer per forward for the sparse scheduling decisions. # -2 means the incoming prefix is already past its anchor. missing = torch.where(((pos > anchors[:, None]) & mask).any(-1), -2, -1) here = torch.where(hit.any(-1), hit.long().argmax(-1), missing).tolist() self.layout = [ (i // (batch // n), here[i], (pos[i] >= anchors[i]) & mask[i]) for i in range(batch) ] return self.layout def prepare(self, components, hidden, hop): # Common decoding path: each beam in a prompt group already has its immutable recall decision. if all( (row, hop) in self.owner._evidence for row in range(len(self.owner.anchors)) ): self.bound.update( { (row, hop): self.owner._evidence[row, hop] for row in range(len(self.owner.anchors)) } ) return for i, (row, local_anchor, _) in enumerate(self._rows(hidden)): key = row, hop if local_anchor == -2 and key not in self.owner._evidence: raise ValueError( "The supplied cache starts after the query anchor; restore its evidence context or replay the prefix" ) if local_anchor >= 0 and key not in self.owner._evidence: h = hidden[i, local_anchor] self.owner.queries[key] = h.clone() skip = self.owner.allow_skip and int(components.action(h).argmax()) == 0 packs = [] if skip else self.owner.provider(row, hop, h, components) prior = (row, hop - 1) if packs: self.owner.read_status[key] = "evidence" self.owner._evidence[key] = torch.cat([p["values"] for p in packs]) elif skip and self.owner.read_status.get(prior) == "evidence": self.owner.read_status[key] = "evidence" self.owner._evidence[key] = self.owner._evidence[prior] else: status = self.owner.read_status.setdefault( key, "read_declined" if skip else "no_external_support" ) self.owner._evidence[key] = absence_reader_input(components, status) self.bound[key] = self.owner._evidence.get(key) def inject(self, components, states, hop): if not any( self.bound.get((row, hop)) is not None for row in range(len(self.owner.anchors)) ): return states if states.shape[1] == 1: batch = states.shape[0] n = len(self.owner.anchors) if batch % n: raise ValueError("Invalid beam batch size") pos = self.positions.reshape(-1, 1).expand(batch, 1) mask = ( self.mask[:, -1:].expand(batch, 1).to(pos.device).bool() if self.mask is not None else None ) result = [] for i in range(batch): row = i // (batch // n) values = self.bound.get((row, hop)) if values is None: result.append(states[i]) continue active = pos[i] >= self.owner.anchors[row] if mask is not None: active = active & mask[i] # Avoid a synchronizing GPU nonzero()/tolist() for a one-token decode. update = components.read(states[i], values) result.append(states[i] + update * active[:, None].to(states.device)) return torch.stack(result) result = [] for i, (row, _, eligible) in enumerate(self._rows(states)): value = self.bound.get((row, hop)) if value is None: result.append(states[i]) continue # Select active positions before attention so earlier prompt tokens incur no reader cost. indices = eligible.nonzero().flatten().to(states.device) active = states[i].index_select(0, indices) delta = components.read(active, value.to(states.device)) result.append(torch.index_add(states[i], 0, indices, delta)) return ( torch.stack(result) if any(v is not None for v in self.bound.values()) else states ) def _encode_cache(pack): return save( { k: t.detach().to(device="cpu", dtype=torch.bfloat16).contiguous() for k, t in pack.items() } ) def _load_pack(data, device): return {k: t.to(device=device, dtype=torch.float32) for k, t in load(data).items()} def _crop_for_region(record, index, slots): """Map an ordered writer slot back to an image and the covered rectangular patch envelope.""" source = [ s for s in record["spans"] if s.get("kind") in {"image", "text"} and "start" in s and "end" in s ] if not source: return None total = max(s["end"] for s in source) q, r = divmod(total, slots) low = index * q + min(index, r) high = low + q + int(index < r) options = [ (max(0, min(s["end"], high) - max(s["start"], low)), s) for s in source if s["kind"] == "image" ] if not options: return None overlap, s = max(options, key=lambda item: item[0]) if not overlap: return None first, last = ( max(low, s["start"]) - s["start"], min(high, s["end"]) - s["start"] - 1, ) cols = s["grid"][2] y0, x0 = divmod(first, cols) y1, x1 = divmod(last, cols) if y0 != y1: x0, x1 = 0, cols - 1 return s["image"], ( x0 * s["cell_width"], y0 * s["cell_height"], min(s["width"], (x1 + 1) * s["cell_width"]), min(s["height"], (y1 + 1) * s["cell_height"]), ) class SourceEvidenceError(LookupError): """A source-bound request reached the answer boundary without the required evidence.""" def __init__(self, grounding): self.grounding = dict(grounding) self.status = self.grounding["status"] self.reason = self.grounding["reason"] self.evidence_ids = list(self.grounding.get("evidence_ids", ())) super().__init__(self.reason) def _resolve_source(store, ref, snapshot, budget): """Resolve an address through its declared redirects, on one immutable bank snapshot.""" path = [] current = ref while len(path) < budget: if type(current) is int: eid = current else: owners = store.lookup_reference(current, revision=snapshot) if len(owners) != 1: return path, "ambiguous_reference" if owners else "missing_reference" eid = owners[0] if eid in path: return path, "reference_cycle" try: meta = store.get(eid, revision=snapshot, include_images=False) except KeyError: return path, "missing_reference" path.append(eid) try: links = record_links( meta, directory=(not isinstance(current, int) and current[0] == "directory"), ) except ValueError: return path, "invalid_redirect" if len(links) > 1: return path, "ambiguous_redirect" if not links: if not isinstance(current, int) and current[0] == "directory": return path, "missing_redirect" return path, None current = links[0] return path, "reference_budget_exhausted" class _NativeImageBinding: """Request-local proof that named image vectors reached their positions in native text input.""" def __init__(self, ctx, targets): self.ctx = ctx self.targets = ( targets # (offset from question anchor, event ID, post-projector features) ) self.by_event = {} for _, eid, features in targets: self.by_event.setdefault(eid, []).append(features) self.seen = [set() for _ in targets] self.consumed = False @torch.no_grad() def observe(self, embedded, image_mask, position_ids, cache): past = int(cache.get_seq_length()) if cache is not None else 0 (anchor,) = self.ctx.anchors if self.consumed and past > anchor: return # ordinary cached decode if past == 0 and (position_ids is None or int(position_ids.min()) == 0): self.seen = [set() for _ in self.targets] self.consumed = False self.ctx.grounding["native_visual_consumed"] = False batch, length = embedded.shape[:2] pos = ( torch.arange(past, past + length, device=embedded.device) if position_ids is None else position_ids.to(embedded.device) ) pos = pos.reshape(-1, length).expand(batch, -1) for j, (delta, _, features) in enumerate(self.targets): first = anchor + delta mask = (pos >= first) & (pos < first + len(features)) cols = mask[0].nonzero().flatten() if not len(cols) and not bool(mask.any()): continue # Prepared requests are single examples, possibly expanded into identical prompt beams. if not torch.equal(mask, mask[0:1].expand_as(mask)): self._mismatch() offsets = pos[0, cols] - first if image_mask is None or not bool(image_mask[:, cols, 0].all()): self._mismatch() expected = features.to(embedded).index_select(0, offsets) if not torch.equal( pos[:, cols], pos[0:1, cols].expand(batch, -1) ) or not torch.equal( embedded[:, cols], expected.unsqueeze(0).expand(batch, -1, -1) ): self._mismatch() self.seen[j].update(offsets.tolist()) self.consumed = all( len(done) == len(features) for done, (_, _, features) in zip(self.seen, self.targets) ) self.ctx.grounding["native_visual_consumed"] = self.consumed def _mismatch(self): self.consumed = False self.ctx.grounding["native_visual_consumed"] = False raise SourceEvidenceError( dict( self.ctx.grounding, status="insufficient_evidence", reason="native_image_mismatch", ) ) class InklingMemory: """Use with a frozen deployed checkpoint. Open one context per question; retain it for decode.""" def __init__(self, model, processor, store): self.model, self.processor, self.store = model, processor, store self.backbone_id = store.keyspace_id.rsplit(":", 1)[0] self.components = components_for(model) if (store.dimension, store.region_dimension) != ( self.components.key_dim, self.components.region_dim, ): raise ValueError( "The store dimensions must match the V18 event and region heads" ) @classmethod def open(cls, model, processor, path, *, bank_id, backbone_id, adapter_path): """backbone_id identifies the exact base revision plus tokenizer/processor configuration.""" if not backbone_id: raise ValueError( "backbone_id must identify the deployed checkpoint and processor" ) p = Path(adapter_path) digest = hashlib.sha256(p.read_bytes()).hexdigest() comp = components_for(model) comp.float().load_state_dict(load_file(str(p)), strict=True) model.eval() store = EventStore( path, bank_id=bank_id, keyspace_id=f"{backbone_id}:{digest}", dimension=comp.key_dim, region_dimension=comp.region_dim, ) return cls(model, processor, store) @torch.no_grad() def remember( self, *, occurrence_id, text="", images=(), spans=(), defer_index=False, image_features=None, image_grid_thw=None, **source, ): images = tuple(images) if any(not isinstance(img, bytes) for img in images): raise TypeError("remember() accepts original encoded image bytes") if defer_index: return self.store.append( occurrence_id=occurrence_id, text=text, images=images, spans=[*_source_geometry(self.processor, text, images), *spans], **source, ) if image_features is None and image_grid_thw is None: states, geometry = _source_parts(self.model, self.processor, text, images) else: if image_features is None or image_grid_thw is None: raise ValueError( "Precomputed image evidence requires both features and image_grid_thw" ) geometry = _source_geometry(self.processor, text, images) features = list(image_features) grids = torch.as_tensor(image_grid_thw).reshape(-1, 3).tolist() expected = [span["grid"] for span in geometry if span["kind"] == "image"] if grids != expected or len(features) != len(images): raise ValueError( "Image grids and original image occurrence order must agree" ) pieces = [encode_source(self.model, self.processor, text)] if text else [] for f, g in zip(features, grids): if ( f.shape != (math.prod(g), self.components.write_in.in_features) or not f.is_floating_point() ): raise ValueError("Invalid post-projector evidence shape or dtype") pieces.append(f.detach()) states = torch.cat([x.to(self.components.write_in.weight) for x in pieces]) pack = self.components.encode_event(states.to(_device(self.components))) eid = self.store.append( occurrence_id=occurrence_id, text=text, images=images, spans=[*geometry, *spans], key=pack["key"].tolist(), region_keys=pack["regions"].tolist(), **source, ) self.store.put_cache(eid, _encode_cache(pack)) return eid @torch.no_grad() def remember_features( self, *, occurrence_id, text, image_features, image_grid_thw, backbone_id, **source, ): """Persist supplied post-projector features when the original pixels were not provided.""" if backbone_id != self.backbone_id: raise ValueError( "Projected-only evidence must match this backbone/processor identity" ) grids = ( torch.as_tensor(image_grid_thw, dtype=torch.long).reshape(-1, 3).tolist() ) image_features = list(image_features) if len(image_features) != len(grids) or not grids: raise ValueError("Need one grid for every projected image") parts, spans = ( _source_parts(self.model, self.processor, text, ()) if text else (None, []) ) states = [] if parts is None else [parts] start = 0 if parts is None else len(parts) width = self.components.write_in.in_features packed = [] for i, (features, grid) in enumerate(zip(image_features, grids)): if ( min(grid) < 1 or features.shape != (math.prod(grid), width) or not features.is_floating_point() ): raise ValueError( "Projected features must be [grid.prod(), backbone hidden size]" ) packed.append(save({"features": features.detach().cpu().contiguous()})) spans.append( dict( kind="projected_image", index=i, grid=grid, start=start, end=start + len(features), backbone_id=backbone_id, ) ) start += len(features) states.append(features) device = _device(self.components) pack = self.components.encode_event( torch.cat( [ t.to(device=device, dtype=self.components.write_in.weight.dtype) for t in states ] ) ) eid = self.store.append( occurrence_id=occurrence_id, text=text, feature_blobs=packed, key=pack["key"].tolist(), region_keys=pack["regions"].tolist(), spans=[*spans, *source.pop("spans", ())], **source, ) self.store.put_cache(eid, _encode_cache(pack)) return eid @torch.no_grad() def _reencode(self, record): features = record.get("feature_blobs", []) if not features: states = encode_source( self.model, self.processor, record["text"], record["images"] ) else: pieces = ( [encode_source(self.model, self.processor, record["text"])] if record["text"] else [] ) for i, data in enumerate(features): desc = next( s for s in record["spans"] if s.get("kind") == "projected_image" and s["index"] == i ) if desc["backbone_id"] != self.backbone_id: raise ValueError( "Projected-only evidence belongs to a different backbone/processor" ) pieces.append(load(data)["features"]) device = _device(self.components) states = torch.cat( [ t.to(device=device, dtype=self.components.write_in.weight.dtype) for t in pieces ] ) return self.components.encode_event(states.to(_device(self.components))) def index_page(self, *, revision=None, after=0, limit=128): """Build this adapter's keys for one page of existing source events.""" def encode(record): pack = self._reencode(record) self.store.put_cache(record["event_id"], _encode_cache(pack)) return dict(key=pack["key"].tolist(), region_keys=pack["regions"].tolist()) return self.store.rebuild(encode, revision=revision, after=after, limit=limit) @torch.no_grad() def prepare_generation( self, messages, *, text, reasoning_effort="none", **context_options ): """Resolve named visual sources and return (native HF inputs, context) for a single request. The raw source is routed through Inkling's vision tower. Already projected sources are consumed at their recorded precision. The caller's messages remain unchanged. """ ctx = self.context(0, text=text, **context_options) images = ctx.native_images() features = ctx.native_features() inputs_messages = list(messages) device = _device(self.model.get_input_embeddings()) def tokenize(chat): batch = self.processor.apply_chat_template( chat, tokenize=True, add_generation_prompt=True, return_tensors="pt", return_dict=True, reasoning_effort=reasoning_effort, ) return { k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in batch.items() } if not images and not features: inputs = tokenize(inputs_messages) ctx.rebase_anchor(inputs["input_ids"].shape[1] - 1) return inputs, ctx if not inputs_messages or inputs_messages[-1].get("role") != "user": raise ValueError( "Named visual evidence must be prepared with the final user query" ) user = inputs_messages[-1] content = user["content"] if isinstance(content, str): content = [{"type": "text", "text": content}] # Each archived image is prepended to the current question. Existing dialog images # stay in place, including examples of the same object at earlier times. offset = sum( part.get("type") == "image" for msg in inputs_messages[:-1] if isinstance(msg["content"], list) for part in msg["content"] ) media, targets, supplied = [], [], {} def add_source(eid, index, img): i = offset + len(targets) if len(images) + len(features) > 1 or any( x.get("type") == "image" for x in content ): media.append( { "type": "text", "text": f"Archived event {eid}, image {index + 1}:", } ) media.append({"type": "image", "image": img}) targets.append((i, eid)) return i for eid, index, data in images: add_source(eid, index, _image(data)) for eid, index, tensor, grid in features: # Tokenize a one-cell sentinel, then expand its token span. Its pixels are # never encoded or submitted to the model as the archived observation. i = add_source(eid, index, Image.new("RGB", (1, 1))) supplied[i] = (tensor, torch.as_tensor(grid).reshape(3).tolist()) inputs_messages[-1] = dict(user, content=media + list(content)) inputs = tokenize(inputs_messages) grids = inputs["image_grid_thw"].cpu().tolist() counts = [math.prod(grid) for grid in grids] token_id = self.model.config.image_token_id ids = inputs["input_ids"] positions = (ids[0] == token_id).nonzero().flatten() if len(positions) != sum(counts): raise ValueError( "Image slots in the prepared prompt do not match the processor grid" ) patches = inputs.pop("pixel_values").split(counts) repeats = torch.ones(ids.shape[1], dtype=torch.long, device=device) spans = positions.split(counts) vectors = [] proj = self.model.get_input_embeddings().weight param = next(self.model.model.vision_tower.parameters()) for i, grid in enumerate(grids): if i in supplied: value, grids[i] = supplied[i] new_count = math.prod(grids[i]) if counts[i] != 1 or value.shape != (new_count, proj.shape[1]): raise ValueError( "Projected-only image shape or placeholder differs from its source" ) repeats[spans[i][0]] = new_count else: encoded = self.model.get_image_features( patches[i].to(param), inputs["image_grid_thw"][i : i + 1], return_dict=True, ) value = encoded.pooler_output[0] vectors.append(value.to(proj)) if supplied: for key in ( "input_ids", "attention_mask", "token_type_ids", "mm_token_type_ids", ): if key in inputs: inputs[key] = inputs[key].repeat_interleave(repeats, dim=1) inputs["image_grid_thw"] = inputs["image_grid_thw"].new_tensor(grids) # Passing the actual per-image projected values also avoids another vision forward inside generate(). from transformers.modeling_outputs import BaseModelOutputWithPooling inputs["mm_encoder_outputs"] = { "image": BaseModelOutputWithPooling(pooler_output=tuple(vectors)) } ids = inputs["input_ids"] anchor = ids.shape[1] - 1 groups = ( (ids[0] == token_id).nonzero().flatten().split([len(v) for v in vectors]) ) bound = [] for i, eid in targets: slots = groups[i] if int(slots[-1] - slots[0]) + 1 != len(slots): raise ValueError( "Archived image must occupy consecutive native token positions" ) bound.append((int(slots[0]) - anchor, eid, vectors[i].detach().clone())) ctx.bind_native_images(images, anchor=anchor, features=features) ctx._native_binding = _NativeImageBinding(ctx, bound) return inputs, ctx def context( self, anchor, *, text="", mode="fast", event_ids=(), revision=None, k=8, candidate_budget=64, force_read=False, require_source=None, source_reference=None, visual_read="native", ): if visual_read not in ("native", "slots"): raise ValueError("visual_read must be 'native' or 'slots'") if require_source not in (None, "off", "event", "image"): raise ValueError("require_source must be None, 'off', 'event', or 'image'") if require_source == "off" and source_reference is not None: raise ValueError("An explicit source_reference requires source validation") refs = [] if source_reference is not None: refs = [normalize_reference(source_reference)] elif require_source != "off": refs = query_references(text) event_ids = tuple(dict.fromkeys(event_ids)) required = None if require_source == "off" else require_source if required is None and require_source != "off" and (refs or event_ids): if re.search( r"\b(?:photographs?|photos?|pictures?|images?)\b|照片|圖片|图片|圖像|图像|影像", text, re.I, ): required = "image" elif refs: required = "event" if len(event_ids) > k: raise ValueError("Increase k to include all explicitly requested event IDs") if mode not in ("fast", "exact") or k < 1 or candidate_budget < k: raise ValueError("Invalid retrieval mode, k or candidate budget") snap = self.store.snapshot() if revision is None else revision previous = OrderedDict() cache = {} trace = [] # One- and two-pass schedules get one read. Longer schedules split this same budget over two reads. def quota(total, hop): passes = ctx.loop_num_passes if ( passes is None ): # Earlier V18 runtimes use the checkpoint's fixed schedule. passes = self.model.config.text_config.loop_num_passes return ( total if passes <= 2 else (total + 1) // 2 if hop == 1 else total // 2 ) def fetch(eid): if eid not in cache: record = self.store.get(eid, revision=snap, include_images=False) data = self.store.get_cache(eid, revision=snap) if data is None: raw = self.store.get(eid, revision=snap) data = _encode_cache(self._reencode(raw)) self.store.put_cache(eid, data) pack = _load_pack(data, _device(self.components)) cache[eid] = record, pack return cache[eid] ref = refs[0] if len(refs) == 1 else None grounding = dict( required=required, status="pending" if required else "not_required", reason=None, revision=snap, bank_id=self.store.bank_id, source_reference=dict(kind=ref[0], key=ref[1]) if ref else None, path=[], target_event_id=None, evidence_ids=[], visual_event_ids=[], ) native_required = bool( required == "image" and (refs or event_ids) and visual_read == "native" ) grounding.update( visual_read=visual_read, requires_native_image=native_required, native_image_inputs=[], ) resolved = None native_sources = None native_bound = False def visual_pack(eid): if eid not in grounding["visual_event_ids"]: raw = self.store.get(eid, revision=snap) if not (raw["image_digests"] or raw["feature_digests"]): return None # A mixed summary may be dominated by text; source-bound image claims read # and encode the selected visual source, even when the event has a cached summary. pack = self._reencode(dict(raw, text="")) cache[eid] = raw, pack grounding["visual_event_ids"].append(eid) return cache[eid][1] def resolve_once(): nonlocal resolved if resolved is None: if refs: path, reason = ( ([], "multiple_references") if ref is None else _resolve_source(self.store, ref, snap, candidate_budget) ) targets = path[-1:] if reason is None else [] if targets and event_ids and targets[0] not in event_ids: reason = "source_reference_mismatch" else: path = targets = list(event_ids) reason = None if reason is None: for eid in targets: try: target = self.store.get( eid, revision=snap, include_images=False ) except KeyError: reason = "missing_reference" break if required == "image" and not ( target["image_digests"] or target["feature_digests"] ): reason = "missing_image" break resolved = path, targets, reason grounding.update( path=list(path), target_event_ids=list(targets), target_event_id=(targets[0] if len(targets) == 1 else None), reason=reason, ) return resolved def deny(reason): nonlocal native_bound native_bound = False grounding.update(status="insufficient_evidence", reason=reason) raise SourceEvidenceError(grounding) def prepare_native_sources(): nonlocal native_sources if native_sources is not None: return native_sources images, features, descriptors = [], [], [] if native_required: _, targets, reason = resolve_once() if reason: deny(reason) for eid in targets: rec = self.store.get(eid, revision=snap) if rec["images"]: for i, raw in enumerate(rec["images"]): digest = hashlib.sha256(raw).hexdigest() if digest != rec["image_digests"][i]: deny("image_digest_mismatch") try: with Image.open(io.BytesIO(raw)) as image: image.verify() except (OSError, ValueError, SyntaxError): deny("unreadable_image") images.append((eid, i, raw)) descriptors.append( dict( event_id=eid, image_index=i, encoding="raw", sha256=digest, ) ) else: for i, blob in enumerate(rec["feature_blobs"]): desc = next( ( x for x in rec["spans"] if x.get("kind") == "projected_image" and x.get("index") == i ), None, ) if not desc or desc.get("backbone_id") != self.backbone_id: deny("incompatible_projected_image") digest = hashlib.sha256(blob).hexdigest() if digest != rec["feature_digests"][i]: deny("image_digest_mismatch") try: tensor = load(blob)["features"] grid = tuple(desc["grid"]) except (KeyError, ValueError, TypeError, SafetensorError): deny("unreadable_projected_image") if ( len(grid) != 3 or any(type(n) is not int or n < 1 for n in grid) or not tensor.is_floating_point() or tensor.shape != ( math.prod(grid), self.components.write_in.in_features, ) ): deny("invalid_projected_image") features.append((eid, i, tensor, grid)) descriptors.append( dict( event_id=eid, image_index=i, encoding="projected", sha256=digest, grid=list(grid), backbone_id=self.backbone_id, ) ) native_sources = images, features, descriptors return native_sources def native_images(): images, _, _ = prepare_native_sources() return list(images) def native_features(): _, features, _ = prepare_native_sources() # Caller may move/cast these tensors. Keep independent original bytes for input binding. return [ (eid, index, tensor.clone(), list(grid)) for eid, index, tensor, grid in features ] def bind_native_images(delivered, *, anchor, features=()): nonlocal native_bound if ctx.loop_num_passes is not None or ctx.queries: raise ValueError("Bind native evidence before model prefill") if type(anchor) is not int or anchor < 0: raise ValueError("anchor must be a nonnegative token position") expected, projections, descriptors = prepare_native_sources() delivered, features = list(delivered), list(features) if len(delivered) != len(expected) or len(features) != len(projections): deny("native_image_mismatch") for (eid, index, raw), (other, offset, received) in zip( expected, delivered ): if ( eid != other or index != offset or not isinstance(received, bytes) or raw != received ): deny("native_image_mismatch") for (eid, index, tensor, grid), (other, offset, received, shape) in zip( projections, features ): if ( eid != other or index != offset or tuple(shape) != grid or not isinstance(received, torch.Tensor) or received.dtype != tensor.dtype or not torch.equal(received.detach().cpu(), tensor) ): deny("native_image_mismatch") ctx.anchors = (anchor,) native_bound = bool(descriptors) grounding.update( native_image_inputs=[dict(d) for d in descriptors], reason=None, visual_event_ids=list( dict.fromkeys(d["event_id"] for d in descriptors) ), ) return list(grounding["native_image_inputs"]) def strict_packs(row, hop): resolve_once() path, targets, reason = resolved single_read = ( ctx.loop_num_passes or self.model.config.text_config.loop_num_passes ) <= 2 terminal_due = hop == 2 or single_read or path == targets if reason is None and terminal_due and native_required and not native_bound: reason = "native_visual_input_required" grounding["reason"] = reason if reason is not None: ids = [] elif terminal_due: # Reserve slots for the actual targets, including when the shortlist has one slot. bridges = [eid for eid in path if eid not in targets] ids = bridges[: max(0, k - len(targets))] + targets else: ids = path[:-1][: quota(k, 1)] packs = [] for eid in ids: if native_required and eid in targets and terminal_due: binding = getattr(ctx, "_native_binding", None) by_event = getattr(binding, "by_event", {}) if not native_bound or eid not in by_event or not by_event[eid]: ids, packs = [], [] reason = "native_visual_input_required" grounding["reason"] = reason break # The native token stream and V18 reader share the same image encoder result. packs.append( self.components.encode_event( torch.cat(by_event[eid], 0).to(_device(self.components)) ) ) elif terminal_due and required == "image" and eid in targets: try: pack = visual_pack(eid) except (OSError, ValueError): reason = "unreadable_image" grounding["reason"] = reason ids, packs = [], [] break packs.append(pack) else: packs.append(fetch(eid)[1]) grounding["evidence_ids"] = ids if reason is not None: grounding["status"] = "insufficient_evidence" elif terminal_due: grounding["status"] = "grounded" trace.append( dict( hop=hop, action="resolve_source", revision=snap, evidence=list(ids), path=list(path), target_event_id=grounding["target_event_id"], reason=reason, ) ) if not packs: ctx.read_status[row, hop] = "searched_empty" return packs def learned_values(): if required != "image": return list(previous.values()) # This mode asks for visual evidence but supplied no exact locator. It certifies # the modality of the selected evidence, not an unobserved object's identity. for eid in list(previous): try: pack = visual_pack(eid) except (OSError, ValueError): pack = None if pack is None: del previous[eid] else: previous[eid] = pack return list(previous.values()) @torch.no_grad() def provider(row, hop, h, comp): if refs or (required and event_ids): return strict_packs(row, hop) choice = int(comp.action(h).argmax()) confidence = float(comp.support(h).sigmoid()) if not (force_read or event_ids or mode == "exact") and ( confidence < 0.5 or choice == 0 ): trace.append( dict( hop=hop, action=choice, support=confidence, revision=snap, evidence=list(previous), ) ) if not previous: ctx.read_status[row, hop] = "read_declined" return learned_values() take, budget = quota(k, hop), quota(candidate_budget, hop) if event_ids and (hop == 1 or choice != 3): ids = list(event_ids) elif hop == 2 and choice in (0, 1): ids = list(previous) elif hop == 2 and choice == 3 and previous: ids = list(previous) # Compare only slots that have image evidence. The best text slot cannot be cropped. best = None for eid in previous: record, pack = fetch(eid) if record["image_digests"] and not any( s.get("kind") == "image" for s in record["spans"] ): raw = self.store.get(eid, revision=snap) _, geometry = _source_parts( self.model, self.processor, raw["text"], raw["images"] ) record = dict(record, spans=[*geometry, *record["spans"]]) scores = (pack["regions"] @ comp.region_query(h)).tolist() for idx, score in enumerate(scores): crop = _crop_for_region(record, idx, len(scores)) if crop is not None and (best is None or score > best[0]): best = score, eid, crop if best is not None: _, eid, (image_index, box) = best part = _image( self.store.get_image(eid, image_index, revision=snap) ).crop(box) detail = comp.encode_event( encode_source(self.model, self.processor, "", [part]) ) previous[eid] = detail trace.append( dict(hop=hop, event_id=eid, image=image_index, box=box) ) elif take: links = [] probed = set() if hop == 2: for eid in previous: meta, _ = fetch(eid) for span in meta["spans"]: if span.get("kind") == "relation" and isinstance( span.get("event_id"), int ): target = span["event_id"] if target not in probed and target not in previous: probed.add(target) try: self.store.get( target, revision=snap, include_images=False ) except KeyError: pass else: links.append(target) if len(links) >= take or len(probed) >= budget: break if len(links) >= take or len(probed) >= budget: break search = None if len(links) < take and (mode == "exact" or len(probed) < budget): search = self.store.search( comp.query_key(h).tolist(), region_query=comp.region_query(h).tolist(), terms=[text], mode=mode, k=take - len(links), candidate_budget=max(1, budget - len(probed)), revision=snap, ) ids = ( list(previous) + links + ([x["event_id"] for x in search["hits"]] if search else []) ) if search: trace.append( { key: search[key] for key in ( "revision", "scanned", "complete", "missing_keys", ) } ) else: ids = list(previous) for eid in ids: if eid not in previous: previous[eid] = fetch(eid)[1] values = learned_values() trace.append( dict( hop=hop, action=choice, support=confidence, revision=snap, evidence=list(previous), ) ) if not previous: ctx.read_status[row, hop] = ( "searched_empty" if take and (hop == 1 or choice == 2) else "no_external_support" ) return values def validate(*, allow_pending=True): if not required: return dict(grounding) hops = ( 1 if ( ctx.loop_num_passes or self.model.config.text_config.loop_num_passes ) <= 2 else 2 ) if (0, hops) not in ctx._evidence: if grounding["status"] == "insufficient_evidence": raise SourceEvidenceError(grounding) if allow_pending: return dict(grounding, status="pending") raise SourceEvidenceError( dict( grounding, status="insufficient_evidence", reason="anchor_not_reached", ) ) if not refs and not event_ids: ids = list(previous) visual_ids = [ eid for eid in ids if eid in grounding["visual_event_ids"] ] reason = ( "no_evidence" if not ids else "missing_image" if required == "image" and not visual_ids else None ) grounding.update( status="insufficient_evidence" if reason else "grounded", reason=reason, evidence_ids=ids, visual_event_ids=visual_ids, ) if grounding["status"] == "grounded": actual = grounding["evidence_ids"] expected = grounding.get("target_event_ids", []) if ( ctx.read_status.get((0, hops)) != "evidence" or not actual or any(eid not in actual for eid in expected) or ( required == "image" and not set(actual).intersection(grounding["visual_event_ids"]) ) ): grounding.update( status="insufficient_evidence", reason="undelivered_evidence" ) if ( native_required and grounding["status"] == "grounded" and not getattr( getattr(ctx, "_native_binding", None), "consumed", False ) ): grounding.update( status="insufficient_evidence", reason="native_visual_input_required", ) if grounding["status"] != "grounded": raise SourceEvidenceError( dict(grounding, status="insufficient_evidence") ) return dict(grounding) ctx = EvidenceContext([anchor], provider) ctx.trace = trace ctx.revision = snap ctx.requires_source_validation = bool(required) ctx.grounding = grounding ctx.validate_source_for_answer = validate ctx.native_images = native_images ctx.native_features = native_features ctx.bind_native_images = bind_native_images return ctx def open_checkpoint_memory(model, processor, path, *, bank_id, checkpoint_dir=None): """Attach a private on-disk bank to an embedded checkpoint loaded with AutoModel. Local directories and Hub model IDs are supported. On the Hub, use the same resolved revision as the model, including when materializing FP32 evidence heads. """ from transformers.utils.hub import cached_file source = checkpoint_dir if checkpoint_dir is not None else model.config.name_or_path if not source: raise ValueError("Supply the V18 checkpoint directory or Hub model ID") revision = getattr(model.config, "_commit_hash", None) def resolve(name): return Path(cached_file(str(source), name, revision=revision)) manifest = json.loads(resolve("v18_export.json").read_bytes()) identity = manifest.get("keyspace_id") if not identity or identity != getattr(model.config, "v18_keyspace_id", None): raise ValueError( "This checkpoint and the loaded model have different V18 keyspaces" ) base = {key: manifest["backbone"][key] for key in ("resources", "weights")} base_id = hashlib.sha256(json.dumps(base, sort_keys=True).encode()).hexdigest() if ( base_id != manifest["backbone_id"] or identity != f"{base_id}:{manifest['weights_sha256']}" ): raise ValueError("Invalid V18 base or adapter identity") name = "model-v18-memory.safetensors" data = resolve(name).read_bytes() if hashlib.sha256(data).hexdigest() != manifest["files"][name]: raise ValueError("Embedded V18 memory shard hash mismatch") prefix = "model.language_model.memory_v18." stored = load(data) if any( not key.startswith(prefix) or tensor.dtype != torch.float32 for key, tensor in stored.items() ): raise ValueError("Invalid embedded V18 memory tensor") state = {key[len(prefix) :]: tensor for key, tensor in stored.items()} if hashlib.sha256(save(state)).hexdigest() != manifest["memory_tensors_sha256"]: raise ValueError("Embedded V18 memory tensor digest mismatch") components = components_for(model) # Do not reset a model that has already learned a different adapter in this process. current = components.state_dict() if current.keys() != state.keys() or any( not torch.equal(t.detach().cpu(), state[n].to(dtype=t.dtype)) for n, t in current.items() ): raise ValueError( "In-memory V18 weights differ from the checkpoint; export the trained adapter first" ) components.float().load_state_dict(state, strict=True) model.eval() store = EventStore( path, bank_id=bank_id, keyspace_id=identity, dimension=components.key_dim, region_dimension=components.region_dim, ) return InklingMemory(model, processor, store)