Module contents
Lesson 26 of 33Advanced 115 min

VLMs in depth: resolution, grounding, hallucination and early fusion

Handle high-resolution images and visual-token compression, produce grounded points, evaluate object hallucination, and compare connector VLMs with early-fusion models.

After this lesson you can

  • Compare dynamic tiling and native resolution with 2D positions for cost and detail.
  • Implement visual-token grouping or pruning and measure the effect.
  • Train a VLM to output box or point coordinates as text and evaluate it.
  • Measure object hallucination with a POPE-like protocol and explain causes.
  • Contrast connector VLMs with early fusion using discrete image tokens.

Before you start

Seeing detail without losing context

Reading a receipt, counting objects, and pointing to a grasp location require different details from a general description. Dynamic resolution adapts patch count to the image. One strategy divides it into a tile grid and adds a global view: tiles preserve detail but multiply tokens and may split objects at boundaries. The global view helps recover context, though by itself it may reduce small letters to a few pixels.

InteractiveTo tile or not to tile
RECEIPT · SIMULATED DOCUMENTSMALL TEXT · SCHEMATIC ONLY

1344 × 896 pixel document. Tiles: grid 3 × 2 plus a global view, each padded if partial and resized to 448 × 448; native: patches over the full image, padded if needed. Estimated height assumes original 12 px text; exceeding 8 px is a fictional rule, not an OCR test or readability guarantee. Enlarging a tile cannot restore lost detail.

Method
448
448
28
Visual patches1792
Estimated text height12.0 px
Illustrative thresholdmet
Schematic document and geometric budget. The text threshold is illustrative, not an OCR test.

Another strategy preserves aspect ratio and resolution through patch sequences of different lengths, with two-dimensional positions and masks preventing packed images from attending to one another. NaViT studies packing with variable aspect ratios; Qwen2-VL uses dynamic resolution and multimodal positions. Higher resolution costs more and does not guarantee text recognition if data, encoder, or focus are unsuitable.

Fewer tokens, less information

Visual-token compression can group neighbors, select by score, or summarize with queries. Averaging four patches preserves broad signals but may dilute a small object; pruning by norm discards information if the score does not match the task. Positions and image identity must accompany retained tokens. Compare reading and counting as well as general accuracy, and measure actual time and memory rather than extrapolating from token count alone.

Pointing and evaluating

Visual grounding links an expression to a point, box, or mask. Some models emit coordinates as text or discrete tokens. Before interpreting them, declare origin, axis order, bounds, quantization, and crop-to-original-image transformation. A point inside a mask is a different metric from box IoU; neither ensures a grasp is physically feasible. If an answer is invalid, excluding it from mean error among valid points hides failures: also report how many answers have valid format and calculate the percentage within a radius over the total. Mean error depends on image scale and discretization, so it is not directly comparable across resolutions. Molmo and PixMo study open pointing and visual-answer data.

In the local run with 800 training and 64 held-out scenes, the initial model produced no valid coordinates out of 128; after 400 steps it produced 128/128 valid, with mean error 19.16 pixels and 18/128 within eight pixels. These are synthetic 64×64 scenes, not a grasp evaluation.

InteractivePointing with text

The aqua circle is the color-mask center and magenta cross the generated point. Origin is top left; each number from 0 to 7 represents the center of an 8-pixel cell. Invalid format counts as failure, not zero error.

Model state
Block
Held-out scene
Generated output4,3
Error for this point10.4 px
Within 8 px18/128
Valid format128/128
Points generated on four held-out scenes; indicators summarize all 128 test queries.

Object hallucination means claiming something appears when it is absent. Language patterns and co-occurrences can induce affirmative answers even without visual evidence. POPE asks presence questions with random, popular, or adversarial negatives. Measure accuracy, yes precision and recall, yes rate, and false positives; prevalence and the rule for interpreting ambiguous answers change results. Preference tuning can change bias, but both false positives and false negatives must be measured without promising their elimination. Yes precision is VP/(VP+FP), recall is VP/(VP+FN), and yes rate is (VP+FP)/N. If there are no yes answers, precision is undefined; high accuracy from always answering no can hide zero recall. Results depend on negative construction and class proportions.

In the balanced probe, before preference tuning the VLM answers “yes” to all 64 positives and 64 negatives of each type. After 200 steps it retains all 64 positive yeses and answers “no” to all 64 pairs without red, but still answers “yes” to all 64 random negatives. The zero-visual control also receives “yes” in 64 repetitions of the same question. Tuning improves the taught distinction without resolving bias for other absent colors. OpenCLIP, using a different rule, answers “no” to every positive and negative in this probe; its balanced 50% accuracy hides zero recall.

InteractiveProbing presence

Percentage of yes answers

0 %20 %40 %60 %80 %100 %Object present100 %Object absent100 %

Original scenes contain red and blue blocks. The correlated negative removes red pixels and retains blue; the random negative asks about an absent color chosen with a fixed seed. The VLM forces a choice between yes and no logits; OpenCLIP compares similarity to positive and negative phrases. These are different mechanisms, not a general ranking. The zero control repeats the same zeroed visual input; these are not independent samples.

Model
Negatives
Accuracy50.0 %
Yes rate100.0 %
Yes precision50.0 %
Yes recall100.0 %
Yes with zero vector64/64
64 positive and 64 negative scenes per category; synthetic scenes and two states of the same VLM, compared with an OpenCLIP contrastive probe.

VLM evaluation should use held-out images, contrastive question pairs, no-image or swapped-image controls, and a declared output format. An answer inferable from text does not prove the system looks at the image. Reviewing dataset origin and possible contamination helps limit conclusions, though it cannot always be ruled out.

In multimodal early fusion, a discrete visual tokenizer can integrate image and text tokens into one sequence and allow a joint model to generate both. Chameleon is an example; a connector VLM does not automatically acquire image generation. Understanding and generation quality, sequence cost, and detail depend on tokenizer and training; no architecture dominates all tasks by definition.

Lab: tiles and tokens

The grid minimizes logarithmic aspect-ratio error with a maximum tile count and breaks ties by lower count. Packing retains position and image index; grouping averages 2×2 regions including partial boundaries. Norm pruning is an example, not a learned importance measure. A point signal becomes one quarter when four cells are averaged.

[ ]Tiles, positions and compressionBrowser
import numpy as np

def choose_tiling(width,height,max_tiles):
 if width<=0 or height<=0 or max_tiles<1:raise ValueError('dimensiones y máximo positivos')
 candidates=[(abs(np.log((cols/rows)/(width/height))),cols*rows,cols,rows) for rows in range(1,max_tiles+1) for cols in range(1,max_tiles+1) if cols*rows<=max_tiles]
 _,_,cols,rows=min(candidates);return cols,rows
def pack_patches(grids):
 tokens=[];positions=[];image_ids=[]
 for i,grid in enumerate(grids):
  h,w,d=grid.shape;tokens.append(grid.reshape(-1,d));positions.extend((row,col) for row in range(h) for col in range(w));image_ids.extend([i]*(h*w))
 return np.concatenate(tokens),np.array(positions),np.array(image_ids)
def pool2(grid):
 h,w,_=grid.shape
 return np.array([[grid[y:min(y+2,h),x:min(x+2,w)].mean((0,1)) for x in range(0,w,2)] for y in range(0,h,2)])
def prune(grid,k):
 flat=grid.reshape(-1,grid.shape[-1]);score=np.linalg.norm(flat,axis=1);idx=np.argsort(-score,kind='stable')[:k]
 return flat[idx],idx
for w,h in [(1344,896),(1600,400),(400,1600),(900,900)]:
 cols,rows=choose_tiling(w,h,6);print(f'{w}x{h}: rejilla {cols}x{rows}, teselas+global {cols*rows+1}, tokens {(cols*rows+1)*256}')
rng=np.random.default_rng(26);grids=[rng.normal(size=(7,11,4)),rng.normal(size=(4,8,4))];packed,pos,ids=pack_patches(grids)
print('empaquetados:',len(packed),'posiciones:',pos.shape,'identidades:',np.bincount(ids))
for grid in grids:
 pooled=pool2(grid);kept,indices=prune(grid,grid.shape[0]*grid.shape[1]//2)
 print('original/agrupado/podado:',grid.shape[0]*grid.shape[1],pooled.shape[0]*pooled.shape[1],len(kept),'primera posición elegida:',np.unravel_index(indices[0],grid.shape[:2]))
# Señal puntual: una media 2x2 divide su intensidad por cuatro.
signal=np.zeros((4,4,1));signal[0,0,0]=1;print('pico original/agrupado:',signal.max(),pool2(signal).max())

Local lab: pointing and probing

These two programs run the full experiment outside the browser. First they generate 1000 64×64 MuJoCo scenes and extract OpenCLIP representations; then they reuse the adapter and projector trained in lesson 25. Install MuJoCo 4.0.1, PyTorch with CUDA, torchvision, open_clip_torch, transformers, peft, bitsandbytes, huggingface_hub and Pillow in a compatible environment. MuJoCo rendering needs an OpenGL context; the second program needs a GPU. To share files between processes set GROUND_ROOT to an absolute path and VLM_LAB_DIR to the absolute lesson 25 output directory, which must contain adapters and projector.pt. Optional VLM_CLIP_DIR and VLM_QWEN_DIR point to local downloads of pinned models; without them the specified revisions are downloaded. Keep the generated JSON and adapters to audit the run.

The first program builds color masks and their visible centroids. Correlated negatives are created by removing red pixels while retaining blue. The OpenCLIP probe compares cosine similarity of two phrases; this is not the same response rule used by the VLM.

[ ]Prepare scenes and CLIP probeLocal GPU
import os, hashlib
from pathlib import Path
import numpy as np, torch, open_clip, mujoco
from PIL import Image
from huggingface_hub import snapshot_download

torch.set_num_threads(2)
root=Path(os.environ.get('GROUND_ROOT','vlm-grounding-data'));root.mkdir(parents=True,exist_ok=True)
XML='''<mujoco model="reach"><option timestep="0.01" gravity="0 0 -9.81"/><visual><global offwidth="64" offheight="64"/></visual>
<worldbody><light pos="0 0 2" dir="0 0 -1" diffuse=".8 .8 .8" ambient=".5 .5 .5"/><camera name="top" pos="0 0 2" fovy="48"/>
<geom type="plane" size="1 1 .05" rgba=".35 .35 .35 1" contype="0" conaffinity="0"/>
<geom name="red" type="box" pos="-.3 .2 .05" size=".07 .07 .05" rgba=".9 .05 .05 1" contype="0" conaffinity="0"/>
<geom name="blue" type="box" pos=".3 -.2 .05" size=".07 .07 .05" rgba=".05 .1 .9 1" contype="0" conaffinity="0"/>
<body name="cursor" pos="0 0 .11"><joint name="x" type="slide" axis="1 0 0" damping="3"/><joint name="y" type="slide" axis="0 1 0" damping="3"/><geom type="sphere" size=".035" mass=".2" rgba="1 1 1 1" contype="0" conaffinity="0"/></body></worldbody>
<actuator><position joint="x" kp="35"/><position joint="y" kp="35"/></actuator></mujoco>'''
rng=np.random.default_rng(24);sim=mujoco.MjModel.from_xml_string(XML);state=mujoco.MjData(sim);renderer=mujoco.Renderer(sim,64,64)
redid=mujoco.mj_name2id(sim,mujoco.mjtObj.mjOBJ_GEOM,'red');blueid=mujoco.mj_name2id(sim,mujoco.mjtObj.mjOBJ_GEOM,'blue');images=[]
for _ in range(1000):
 while True:
  pts=rng.uniform(-.55,.55,(3,2))
  if min(np.linalg.norm(pts[0]-pts[1]),np.linalg.norm(pts[0]-pts[2]),np.linalg.norm(pts[1]-pts[2]))>.22:break
 sim.geom_pos[redid,:2]=pts[0];sim.geom_pos[blueid,:2]=pts[1];mujoco.mj_resetData(sim,state);state.qpos[:2]=pts[2];state.ctrl[:]=pts[2];mujoco.mj_forward(sim,state)
 renderer.update_scene(state,camera='top');images.append(renderer.render().copy())
renderer.close();images=np.asarray(images);a=images.astype(float);points=[]
for c in (0,2):
 mask=(a[:,:,:,c]>1.5*a[:,:,:,(c+1)%3])&(a[:,:,:,c]>1.5*a[:,:,:,(c+2)%3])&(a[:,:,:,c]>40)
 if not np.all(mask.sum((1,2))>0):raise ValueError('algún bloque no tiene máscara visible')
 y,x=np.indices(mask.shape[1:]);points.append(np.stack([(mask*x).sum((1,2))/mask.sum((1,2)),(mask*y).sum((1,2))/mask.sum((1,2))],1))
points=np.stack(points,1)
ids=list(range(128))+list(range(800,864));removed=[]
for i in ids:
 im=images[i].copy();v=im.astype(float);mask=(v[:,:,0]>1.5*v[:,:,1])&(v[:,:,0]>1.5*v[:,:,2])&(v[:,:,0]>40)
 bg=np.median(np.concatenate([im[0],im[-1],im[:,0],im[:,-1]],axis=0),axis=0).astype(np.uint8);im[mask]=bg;removed.append(im)
clipdir=Path(os.environ.get('VLM_CLIP_DIR') or snapshot_download('laion/CLIP-ViT-B-32-laion2B-s34B-b79K',revision='1a25a446712ba5ee05982a381eed697ef9b435cf',allow_patterns=['open_clip_model.safetensors']))
weights=clipdir/'open_clip_model.safetensors'
with weights.open('rb') as f:assert hashlib.file_digest(f,'sha256').hexdigest()=='ac4f8c4b88af6d963118cbf40ad93176d092abbedfcb752601ae1866352656e6'
model,_,pre=open_clip.create_model_and_transforms('ViT-B-32',pretrained=str(weights),device='cpu');model.eval()
def encode(ims):
 result=[]
 with torch.no_grad():
  for start in range(0,len(ims),16):result.append(model.encode_image(torch.stack([pre(Image.fromarray(x)) for x in ims[start:start+16]]),normalize=True).numpy())
 return np.concatenate(result)
features=encode(images);removed_features=encode(removed)
np.savez(root/'blocks_features.npz',features=features,points=points,images=images)
np.savez(root/'red_removed.npz',features=removed_features,images=np.stack(removed),ids=np.array(ids))
np.save(root/'blank_feature.npy',encode([np.zeros((64,64,3),dtype=np.uint8)])[0])
print('1000 escenas, 800 train y 64 test; 192 pares con píxeles rojos eliminados',flush=True)
import json
tokenizer=open_clip.get_tokenizer('ViT-B-32');colors=('red','green','yellow','white')
texts=[s for color in colors for s in (f'a photo of a {color} block',f'a photo without a {color} block')]
with torch.no_grad(): emb=model.encode_text(tokenizer(texts),normalize=True)
test=torch.tensor(features[800:864]);test_removed=torch.tensor(removed_features[128:]);choices=np.random.default_rng(260).integers(0,3,64)
def score(x,c):
 [email protected];return logits[:,2*c]>logits[:,2*c+1]
yes=score(test,0);neg=score(test_removed,0);random=[bool(score(test[i:i+1],int(c)+1)[0]) for i,c in enumerate(choices)]
probe={'presente':{'n':64,'yes':int(yes.sum()),'correct':int(yes.sum())},'ausente correlacionado':{'n':64,'yes':int(neg.sum()),'correct':64-int(neg.sum())},'ausente aleatorio':{'n':64,'yes':sum(random),'correct':64-sum(random)}}
(root/'clip_probe.json').write_text(json.dumps(probe,ensure_ascii=False,indent=2),encoding='utf8');print('sondeo CLIP:',probe,flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The second program tunes coordinates on 800 scenes, evaluates 64 held-out scenes for both colors, and applies synthetic preferences on 128 pairs. Presence answers compare only first-token yes and no logits; they are neither human judgments nor the official POPE dataset. The zero visual vector is a control repeated for the same question. Each preference says “yes” in the original scene and “no” in the paired scene without red. DPO compares the margin between both tokens with the margin of the frozen pre-tuning copy, with β=0.1. The signal teaches that particular distinction: improvement on these pairs does not guarantee less hallucination for other objects or contexts.

[ ]Train and evaluate grounding and preferencesLocal GPU
import os, re, json, math, copy
from pathlib import Path
import numpy as np
import torch
from torch import nn
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from peft import PeftModel
from huggingface_hub import snapshot_download

torch.set_num_threads(2);torch.manual_seed(26);np.random.seed(26)
assert torch.cuda.is_available()
device='cuda';root=Path(os.environ.get('GROUND_ROOT','vlm-grounding-data'))
data=np.load(root/'blocks_features.npz');features=torch.tensor(data['features']);points=data['points'];images=data['images']
ground_steps=int(os.environ.get('GROUND_STEPS','400'));dpo_steps=int(os.environ.get('DPO_STEPS','200'))
test_n=int(os.environ.get('GROUND_TEST','64'));train_n=int(os.environ.get('GROUND_TRAIN','800'));pref_n=int(os.environ.get('PREF_TRAIN','128'))
assert 1<=test_n<=64 and 1<=train_n<=800 and 1<=pref_n<=128
qwen=os.environ.get('VLM_QWEN_DIR') or snapshot_download('Qwen/Qwen2.5-0.5B-Instruct',revision='7ae557604adf67be50417f59c2c2f167def9a775',allow_patterns=['*.json','*.safetensors','*.txt'])
base=Path(os.environ.get('VLM_LAB_DIR','vlm-lab-data'))
tok=AutoTokenizer.from_pretrained(qwen);tok.pad_token=tok.eos_token
quant=BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type='nf4',bnb_4bit_use_double_quant=True,bnb_4bit_compute_dtype=torch.float16)
llm=AutoModelForCausalLM.from_pretrained(qwen,quantization_config=quant,device_map={'':0},dtype=torch.float16);llm.config.use_cache=False
llm=PeftModel.from_pretrained(llm,str(base/'adapters'),is_trainable=True)
projector=nn.Sequential(nn.Linear(512,512),nn.GELU(),nn.Linear(512,llm.config.hidden_size)).to(device)
projector.load_state_dict(torch.load(base/'projector.pt',map_location=device,weights_only=True))
colors=('red','blue')
def prefix(prompt):return tok.encode('User: '+prompt+'\nAssistant:',add_special_tokens=False)
def inputs(feat,prompt,answer):
 pre=prefix(prompt);suffix=tok.encode(' '+answer,add_special_tokens=False)+[tok.eos_token_id];ids=torch.tensor(pre+suffix,device=device)
 vis=projector(feat[None].to(device)).to(llm.get_input_embeddings().weight.dtype)
 em=torch.cat([vis,llm.get_input_embeddings()(ids).detach()],0)
 labels=torch.tensor([-100]*(1+len(pre))+suffix,device=device)
 return em,labels
def loss_batch(rows):
 seq=[inputs(*r) for r in rows];size=max(len(y) for x,y in seq)
 emb=torch.stack([nn.functional.pad(x,(0,0,0,size-len(y))) for x,y in seq]);labels=torch.stack([nn.functional.pad(y,(0,size-len(y)),value=-100) for x,y in seq])
 mask=torch.stack([torch.arange(size,device=device)<len(y) for _,y in seq]);return llm(inputs_embeds=emb,attention_mask=mask,labels=labels).loss
def generate_batch(feat,prompt):
 pre=prefix(prompt);ids=torch.tensor([pre]*len(feat),device=device)
 with torch.no_grad():
  v=projector(feat.to(device)).to(llm.get_input_embeddings().weight.dtype)[:,None];em=torch.cat([v,llm.get_input_embeddings()(ids)],1)
  done=torch.zeros(len(feat),dtype=torch.bool,device=device);out=[]
  for _ in range(7):
   n=llm(inputs_embeds=em,attention_mask=torch.ones(em.shape[:2],device=device,dtype=torch.long)).logits[:,-1].argmax(-1)
   n=torch.where(done,torch.full_like(n,tok.eos_token_id),n);out.append(n);done|=n.eq(tok.eos_token_id)
   if bool(done.all()):break
   em=torch.cat([em,llm.get_input_embeddings()(n[:,None])],1)
  seq=torch.stack(out,1).cpu().tolist()
 return [tok.decode(row[:row.index(tok.eos_token_id)] if tok.eos_token_id in row else row,skip_special_tokens=True).strip() for row in seq]
def grid(p):return np.clip(np.floor(p/8),0,7).astype(int)
def ground_eval():
 llm.eval();projector.eval();records=[]
 for color in range(2):
  prompt=f'Where is the {colors[color]} block? Answer x,y as integers from 0 to 7.'
  for start in range(800,800+test_n,8):
   answers=generate_batch(features[start:min(start+8,800+test_n)],prompt)
   for i,answer in enumerate(answers,start):
    match=re.fullmatch(r'\s*([0-7])\s*[, ]\s*([0-7])\s*',answer);pred=None if not match else [int(match[1])*8+4,int(match[2])*8+4]
    target=points[i,color].tolist();error=None if pred is None else float(np.linalg.norm(np.asarray(pred)-target))
    records.append({'index':i,'color':colors[color],'answer':answer,'target':target,'prediction':pred,'error_px':error})
 ok=[r['error_px'] for r in records if r['error_px'] is not None]
 return {'n':len(records),'valid':len(ok),'mean_error_valid_px':float(np.mean(ok)) if ok else None,'within_8px':sum(e<=8 for e in ok),'records':records}
print('grounding initial',flush=True);before=ground_eval();print('initial valid',before['valid'],'/',before['n'],flush=True)
optim=torch.optim.AdamW(list(projector.parameters())+[p for p in llm.parameters() if p.requires_grad],lr=1e-4)
llm.train();projector.train();rng=np.random.default_rng(26)
for step in range(ground_steps):
 rows=[]
 for _ in range(4):
  i=int(rng.integers(0,train_n));c=int(rng.integers(2));x,y=grid(points[i,c]);rows.append((features[i],f'Where is the {colors[c]} block? Answer x,y as integers from 0 to 7.',f'{x},{y}'))
 loss=loss_batch(rows);optim.zero_grad();loss.backward();optim.step()
 if step%100==0 or step==ground_steps-1:print('ground step',step+1,'loss',float(loss.detach()),flush=True)
print('grounding final',flush=True);after=ground_eval();print('final valid',after['valid'],'/',after['n'],'mean error',after['mean_error_valid_px'],'within 8px',after['within_8px'],flush=True)
if os.environ.get('GROUND_SAVE','1')=='1':
 llm.save_pretrained(root/'ground-adapters');torch.save(projector.state_dict(),root/'ground-projector.pt')

# Binary POPE-style probe: all original scenes have red and blue, but no green.
# Red pixels are removed in matched images, retaining blue as a co-occurrence cue.
# A no-image control exposes answers attributable to text priors.
blank=torch.tensor(np.load(root/'blank_feature.npy'))
removed=torch.tensor(np.load(root/'red_removed.npz')['features'])
yes_ids=tok.encode(' yes',add_special_tokens=False);no_ids=tok.encode(' no',add_special_tokens=False)
assert len(yes_ids)==len(no_ids)==1,(yes_ids,no_ids)
def yes_no_logits(feat,prompt):
 ids=torch.tensor([prefix(prompt)]*len(feat),device=device);v=projector(feat.to(device)).to(llm.get_input_embeddings().weight.dtype)[:,None]
 emb=torch.cat([v,llm.get_input_embeddings()(ids).detach()],1);out=llm(inputs_embeds=emb,attention_mask=torch.ones(emb.shape[:2],device=device,dtype=torch.long)).logits[:,-1]
 return out[:,yes_ids[0]]-out[:,no_ids[0]]
def probe():
 llm.eval();projector.eval();res={}
 with torch.no_grad():
  for name,prompt,feat,labels in [
   ('presente','Is there a red block? Answer yes or no.',features[800:800+test_n],torch.ones(test_n)),
   ('ausente correlacionado','Is there a red block? Answer yes or no.',removed[128:128+test_n],torch.zeros(test_n)),
   ('prior texto','Is there a red block? Answer yes or no.',torch.zeros_like(features[800:800+test_n]),torch.ones(test_n))]:
   pred=torch.cat([yes_no_logits(x,prompt).cpu() for x in feat.split(8)])>0
   res[name]={'n':len(pred),'yes':int(pred.sum()),'correct':int((pred==labels.bool()).sum())}
  choices=np.random.default_rng(260).integers(0,3,test_n);yes_count=0
  for c,color in enumerate(('green','yellow','white')):
   selected=np.flatnonzero(choices==c);feat=features[800:800+test_n][selected]
   if len(feat)==0:continue
   for x in feat.split(8):yes_count+=int((yes_no_logits(x,f'Is there a {color} block? Answer yes or no.')>0).sum())
  res['ausente aleatorio']={'n':test_n,'yes':yes_count,'correct':test_n-yes_count}
 return res
before_pref=probe();print('probe antes',before_pref,flush=True)
prompt='Is there a red block? Answer yes or no.'
pref_features=torch.cat([features[:pref_n],removed[:pref_n]]);sign=torch.cat([torch.ones(pref_n),-torch.ones(pref_n)]).to(device)
llm.eval();projector.eval()
with torch.no_grad():ref=torch.cat([yes_no_logits(x,prompt).detach() for x in pref_features.split(8)])
optim=torch.optim.AdamW(list(projector.parameters())+[p for p in llm.parameters() if p.requires_grad],lr=5e-5);llm.train();projector.train()
for step in range(dpo_steps):
 idx=torch.randint(len(sign),(4,));delta=sign[idx]*(yes_no_logits(pref_features[idx],prompt)-ref[idx]);loss=-nn.functional.logsigmoid(.1*delta).mean()
 optim.zero_grad();loss.backward();optim.step()
 if step%50==0 or step==dpo_steps-1:print('DPO step',step+1,'loss',float(loss.detach()),flush=True)
after_pref=probe();print('probe después',after_pref,flush=True)
out={'ground_before':before,'ground_after':after,'pope_before':before_pref,'pope_after':after_pref,'ground_steps':ground_steps,'dpo_steps':dpo_steps,'train_scene_count':train_n,'test_scene_count':test_n,'preference_train_count':pref_n,'peak_allocated_mib':torch.cuda.max_memory_allocated()/2**20,'peak_reserved_mib':torch.cuda.max_memory_reserved()/2**20,'source':'rendered MuJoCo scenes; pixel masks, synthetic preference labels; not human annotations'}
Path(os.environ.get('GROUND_OUTPUT',str(root/'ground-results.json'))).write_text(json.dumps(out,ensure_ascii=False,indent=2),encoding='utf8')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Numeric
A 1344×896 image is divided into 448×448 tiles and a global view. Each produces 256 tokens. How many tokens are there before compression?
CodeChoose a grid
Implement choose_tiling(width, height, max_tiles). Return positive (columns, rows) with product ≤ max_tiles minimizing abs(log((columns/rows)/(width/height))). Break ties by smaller product, then smaller columns and rows. Reject nonpositive dimensions or maximum.
def choose_tiling(width, height, max_tiles):
  pass
Shift+Enter to run
Quiz
What test detects a tendency to answer yes due to co-occurrence?
Quiz
What does a joint architecture with discrete image and text tokens allow?
CodeRead a quantized point
Implement point_hit(texto, mascara): accept only 'x,y' with integers from 0 to 1000 and optional whitespace. Convert to pixels as round(x(width-1)/1000), round(y(height-1)/1000) and return bool(mascara[y][x]); reject format, bounds, or empty mask with ValueError.
def point_hit(texto, mascara):
  pass
Shift+Enter to run
Key idea
Resolution, compression, and evaluation should be chosen according to the detail required by the task.