# Multimodal LLM: image kaise token banti hai

> Vision-language model image ko patch, visual encoder, merge aur projection se visual tokens banata hai, text ke saath LM mein bhejta hai। CLIP contrastive learning, LLaVA ke do-phase training, dynamic resolution ke tokens aur KV Cache, aur resolution chhote akshar padhne par kya asar - naapi kar।

- URL: https://dmxsf.com/hi/wiki/multimodal/multimodal-llms/
- [DMXSF](https://dmxsf.com/hi/about/)
- मध्यम
- अपडेट किया गया: 2026-11-18
- Tags: Multimodal, CLIP, Embeddings

## यह पृष्ठ पूरा करने पर आप

- Multimodal LLM ka data flow banao: image, patch, visual encoder, merge aur projection, visual tokens, language model — har step ke tensor shapes likhein।
- CLIP ka symmetric contrastive loss likhein; temperature aur batch size ka kaam samjhaayein; zero-shot classification se jaanchein।
- `smart_resize` ke niyam se dynamic resolution model mein ek image ke visual tokens ginna seekhein, aur use context, KV Cache aur prefill delay mein badlein।
- LLaVA ke do phases mein kaun se parameters train hote hain, kaun sa data use hota hai — spasht karein।
- Task ke anusaar resolution aur approach chunein (OCR pipeline, VLM ya combination), aur "dekhा ya nahi, sahi joda ya nahi, sahi use kiya ya nahi" ke kram se debugging karein।

Multimodal LLM (ya vision-language model, VLM) ka tareeka ek line mein: **image ko vectors ki shreni mein badalkar \"visual tokens\" ke roop mein language model ke input sequence mein daalna**। Language model khud lagbhag nahi badalta — wo token ki shreni padhta hai, agla token predict karta hai; bas un tokens mein se kuch images se aate hain। Isliye multimodal ke saare sawaal teen cheezon par: image vectors kaise banti hai (visual encoder); vectors language-model-readable tokens kaise (merge aur projection); ek image kitne tokens leti hai (resolution aur cost)। Ye page pehle data flow saaf karta hai, phir CLIP aur LLaVA se do training thoughts batata hai, aakhir mein naape numbers se: ek image kitne tokens, kitni memory, chhote akshar padhe jaate hain ya nahi।

> [!NOTE] Experiment environment
> Is page ke numbers MacBook Pro (Apple M2 Max, 64 GB unified memory) se hain। CLIP experiment PyTorch + `openai/clip-vit-base-patch32`; VLM MLX par `mlx-community/Qwen3-VL-4B-Instruct-4bit` (Qwen3-VL-4B-Instruct ka 4-bit quantized version)। Token count, KV Cache aur parameters model config files aur code se gine gaye; delay aur accuracy measured। Alag hardware/model par absolute numbers alag — le jaane wali baat niyam aur tareeka hai।

## Poora picture: image language model mein kaise ghusati hai

*Figure: Udaharan ke numbers Qwen3-VL-4B se: patch 16 px, ViT chaudai 1024, LM chaudai 2560; n = text prompt ke tokens। Tasveer simboodik hai; DeepStack aur position encoding chhode gaye।*

Text ka entry tokenizer + embedding layer hai: har token table se ek vector। Image ki vocabulary nahi — usi shape ke vectors banane ke liye doosra raasta:

1. **Katna**: image ko $P\times P$ pixels ke chhote blocks (patch) mein; $H\times W$ image se $N=\frac{H}{P}\cdot\frac{W}{P}$ blocks; har block flatten karke ek vector — ek shabd ko ek token banana।
2. **Visual encoder**: ViT pehle har block ko linearly hidden dimension mein, phir kai layers ka self-attention — har block ka vector paas ka context le leta hai; output phir bhi $N$ vectors।
3. **Merge aur projection**: paas ke $2\times2$ vectors jodkar ek, phir MLP se language model ke hidden dimension mein; $N$ se $N/4$ — yahi **visual tokens**।
4. **Jodna**: prompt mein pehle image ke liye placeholder tokens; embedding table ke baad in positions ke vectors visual tokens se replace; poori sequence language model ko।

Neeche wala seedha chalane yogya code, step 3 aur 4 ko random numbers se PyTorch mein likhta hai:

```python
import torch
import torch.nn as nn

torch.manual_seed(0)
grid_h, grid_w, merge = 8, 12, 2          # ek image 8 x 12 patches mein
d_vit, d_llm = 1024, 2560                 # Qwen3-VL-4B: ViT chaudai, LLM chaudai

vit_out = torch.randn(grid_h * grid_w, d_vit)      # har patch ka ek vector

# 1. Merge: paas ke 2 x 2 patches jodkar ek vector
x = vit_out.view(grid_h // merge, merge, grid_w // merge, merge, d_vit)
x = x.permute(0, 2, 1, 3, 4).reshape(-1, merge * merge * d_vit)

# 2. Projection: do-layer MLP, vector ko LLM ke embedding space mein
merger = nn.Sequential(nn.Linear(merge * merge * d_vit, merge * merge * d_vit),
                       nn.GELU(), nn.Linear(merge * merge * d_vit, d_llm))
visual = merger(x)
print("patches", tuple(vit_out.shape), "-> blocks", tuple(x.shape),
      "-> visual tokens", tuple(visual.shape))
print("merger parameters:", sum(p.numel() for p in merger.parameters()))

# 3. Jodna: prompt mein har visual token ka placeholder id; lookup ke baad replace
IMAGE = -1
ids = torch.tensor([5, 9] + [IMAGE] * len(visual) + [7, 3, 4])
embed = nn.Embedding(100, d_llm)
inputs_embeds = embed(ids.clamp(min=0))            # placeholder par pehle koi bhi vector
inputs_embeds = inputs_embeds.masked_scatter((ids == IMAGE)[:, None], visual)
print("LLM input:", tuple(inputs_embeds.shape),
      "= 2 text + 24 visual + 3 text tokens")
```

```text
patches (96, 1024) -> blocks (24, 4096) -> visual tokens (24, 2560)
merger parameters: 27269632
LLM input: (29, 2560) = 2 text + 24 visual + 3 text tokens
```

Dhyan dene wali baatein:

- Merge sirf `view`, `permute`, `reshape`: $8\times12=96$ patch vectors -> 24 vectors of 4096-dim ($4\times1024$); har visual token $2\times2$ ke paas ke area ko \"dekhta\" hai।
- Merge + projection do-layer MLP, kul 27,269,632 parameters — 4B language model ke 1% se kam। Asli Qwen3-VL mein DeepStack ke liye teen aur merge layers — aage।
- `masked_scatter` ke baad language model ko $[29, 2560]$ matrix dikhta hai; use pata nahi kaun si rows image se, kaun si table se। Positional relations position encoding se (aage M-RoPE)।
- Asli prompt mein image ka likha: `<|vision_start|>`, phir visual token count jitne `<|image_pad|>`, phir `<|vision_end|>` (Qwen family ka style; neeche ke token counts in dono markers ko shamil nahi — har ek ek position leta hai)।

Is page ke models ka output sirf text: visual hissa image ko LM-readable vectors mein \"translate\" karta hai; generation LM hi karta hai। Image ya audio seedha banane wale \"omni\" models doosra raasta — is page se bahar।

## Katna aur visual encoder: resolution cost kyun hai

ViT paper (Dosovitskiy et al., 2020) ka title — An Image is Worth 16x16 Words — isi kadam ka saar: image ko $P\times P$ pixel \"shabdon\" ke vaakya jaisa samjho। $P$ chhota — zyada blocks, zyada detail, zyada cost। Kuch aam configurations (block counts config files se code se gine gaye):

| Model (input) | Patch side | Blocks | LLM mein jaane wale visual tokens |
| --- | --- | --- | --- |
| CLIP ViT-B/32 (224x224) | 32 | 49 (+1 class token) | LLM se judta nahi; poora image 1 vector |
| LLaVA-1.5-7B (ViT-L/14, 336x336) | 14 | 576 | 576 (merge nahi) |
| Qwen2-VL-7B (1024x768 -> 1036x756) | 14 | 3,996 | 999 ($2\times2$ merge) |
| Qwen3-VL-4B (1024x768) | 16 | 3,072 | 768 ($2\times2$ merge) |

Resolution ke do hisaab:

- **Visual encoder**: ViT ka self-attention $N$ patches ke beech pairwise; cost $N^2$ par। Side duguni — $N$ chaar guna; attention cost solah guna।
- **Language model**: har visual token context ka ek position; attention mein hissa; KV Cache mein jagah। Side duguni — visual tokens chaar guna; prefill time aur KV Cache badhte hain।

Aage \"visual tokens ka bill\" khnd dono hisaab numbers mein ginta hai।

## CLIP: contrastive learning se image-text ek space mein

CLIP (Radford et al., OpenAI, 2021) ek image encoder aur ek text encoder saath train karta hai; maqsad saral: image aur uska description — vectors paas; galat jodi — door। Training data 40 crore web image-text pairs; batch 32,768।

Ek batch mein $N$ images aur $N$ texts; saare vectors normalize karke pairwise cosine similarity — $N\times N$ matrix $s_{ij}$: diagonal matched pairs; baaki $N^2-N$ negative। Har row (image->text) aur har column (text->image) par softmax cross entropy, average — symmetric InfoNCE loss:

$$
\mathcal{L}=\frac{1}{2N}\sum_{i=1}^{N}\left[-\log\frac{e^{s_{ii}/\tau}}{\sum_{j}e^{s_{ij}/\tau}}-\log\frac{e^{s_{ii}/\tau}}{\sum_{j}e^{s_{ji}/\tau}}\right]
$$

$\tau$ temperature hai। Paper ise learnable parameter maanta hai, initial 0.07, aur $1/\tau$ ko 100 par cap karta hai, warna training asathir। Trained weights mein $1/\tau$ theek cap par — neeche ka code 100 print karta hai।

Zero-shot classification ko classifier nahi chahiye: har class name ko vaakya mein likho (jaise \"a photo of a cat.\"), text vector encode karo; image vector ke sabse paas wala class = prediction। Neeche CIFAR-10 ke 10,000 test images (32x32, 224x224 mein upscale) par, alag sentence templates se:

```python
import torch
import torch.nn.functional as F
from datasets import load_dataset
from transformers import CLIPModel, CLIPProcessor

NAME, DEV = "openai/clip-vit-base-patch32", "mps"     # ya "cuda" / "cpu"
model = CLIPModel.from_pretrained(NAME).to(DEV).eval()
proc = CLIPProcessor.from_pretrained(NAME)
data = load_dataset("uoft-cs/cifar10", split="test")      # 10000 images
classes = data.features["label"].names
print("temperature scale:", round(model.logit_scale.exp().item()))

def tensor_of(out):              # transformers 5 output object deta hai
    return out if isinstance(out, torch.Tensor) else out.pooler_output

@torch.no_grad()
def embed_images(images):
    px = proc(images=images, return_tensors="pt")["pixel_values"].to(DEV)
    e = tensor_of(model.get_image_features(pixel_values=px))
    return F.normalize(e, dim=-1).cpu()

@torch.no_grad()
def embed_classes(templates):
    """Har class ka ek vector: pehle templates ka mean, phir normalize।"""
    rows = []
    for c in classes:
        tok = proc(text=[t.format(c) for t in templates],
                   return_tensors="pt", padding=True).to(DEV)
        e = F.normalize(tensor_of(model.get_text_features(**tok)), dim=-1)
        rows.append(F.normalize(e.mean(0), dim=-1).cpu())
    return torch.stack(rows)

images = [r["img"].convert("RGB") for r in data]
labels = torch.tensor(data["label"])
img = torch.cat([embed_images(images[i:i + 250])
                 for i in range(0, len(images), 250)])

TEMPLATES = {
    "bare class name": ["{}"],
    "a photo of a {}.": ["a photo of a {}."],
    "a drawing of a {}.": ["a drawing of a {}."],
    "a low resolution photo of a {}.": ["a low resolution photo of a {}."],
    "unrelated sentence": ["the weather is nice today, {}"],
    "mean of 7 templates": [
        "a photo of a {}.", "a blurry photo of a {}.",
        "a low resolution photo of a {}.", "a bad photo of a {}.",
        "a good photo of a {}.", "a photo of the {}.",
        "a close-up photo of a {}."],
}
for name, templates in TEMPLATES.items():
    pred = (img @ embed_classes(templates).T).argmax(-1)
    print(f"{name:32s} accuracy {(pred == labels).float().mean():.4f}")
```

```text
temperature scale: 100
bare class name                  accuracy 0.8735
a photo of a {}.                 accuracy 0.8830
a drawing of a {}.               accuracy 0.8967
a low resolution photo of a {}.  accuracy 0.8903
unrelated sentence               accuracy 0.8733
mean of 7 templates              accuracy 0.8917
```

(अंग्रेज़ी आउटपुट चीनी page की उसी मूल run से।)

Result table padhte waqt chaar baatein:

- Koi classifier train nahi kiya, phir bhi 87%–90%। Sirf class name 87.35%; \"a photo of a {}.\" par 88.30% — CLIP paper ki baat se milta hai: vaakya single shabd se captions ke zyada paas।
- Template ek hyperparameter hai। \"a drawing of a {}.\" \"a photo of a {}.\" se 1.4 bindu ooncha — ho sakta hai 32x32 chhoti image upscale hone par illustration jaisi lage; humne aage jaancha nahi। 7 templates ke text vectors ka mean (paper: embedding-space ensemble) — 89.17%।
- Image se unrelated vaakya \"the weather is nice today, {}\" (87.33%) sirf class name (87.35%) jaisa hi — text encoder yahan mukhya roop se class name padh raha hai।
- Yahan test set se template chuna gaya — sirf sensitivity dikhane ke liye; asli mein validation set। 10,000 images par 0.88 ke aaspaas accuracy ka SE lagbhag 0.3 bindu। Paper ki appendix table ViT-B/32 ka CIFAR-10 zero-shot 91.3% batati hai; paper zyadatar datasets ke liye custom prompts + ensembles use karta tha — 7 generic templates se seedha compare nahi।

Ab loss khud dekho। 8 classes, har ek ki ek image; 8 class texts:

```python
def clip_loss(a, b, scale):
    """Image-text similarity matrix par symmetric cross entropy।"""
    logits = scale * a @ b.T                  # row i: image i vs saare texts
    target = torch.arange(len(logits))        # matched text diagonal par
    return (F.cross_entropy(logits, target)
            + F.cross_entropy(logits.T, target)) / 2

scale = model.logit_scale.exp().item()
one_each = [(labels == c).nonzero()[0].item() for c in range(8)]
a, b = img[one_each], embed_classes(["a photo of a {}."])[:8]
print("cosine similarities, rows = 8 images, columns = 8 class texts:")
print((a @ b.T).numpy().round(2))
print("loss, correct pairs   :", round(clip_loss(a, b, scale).item(), 3))
print("loss, shifted pairs   :",
      round(clip_loss(a, b.roll(1, dims=0), scale).item(), 3))
print("loss, scale 1 (no temperature):", round(clip_loss(a, b, 1.0).item(), 3))
print("chance level, ln(8)   :", round(torch.tensor(8.0).log().item(), 3))
```

```text
cosine similarities, rows = 8 images, columns = 8 class texts:
[[0.24 0.21 0.23 0.18 0.17 0.18 0.18 0.2 ]
 [0.18 0.26 0.19 0.18 0.17 0.19 0.17 0.18]
 [0.2  0.21 0.27 0.22 0.22 0.23 0.2  0.23]
 [0.17 0.18 0.2  0.21 0.18 0.2  0.18 0.19]
 [0.2  0.19 0.22 0.2  0.28 0.22 0.19 0.22]
 [0.17 0.19 0.19 0.23 0.19 0.25 0.19 0.2 ]
 [0.17 0.21 0.23 0.22 0.2  0.22 0.29 0.19]
 [0.18 0.2  0.2  0.21 0.2  0.21 0.16 0.27]]
loss, correct pairs   : 0.307
loss, shifted pairs   : 6.587
loss, scale 1 (no temperature): 2.027
chance level, ln(8)   : 2.079
```

(अंग्रेज़ी आउटपुट चीनी page की उसी मूल run से।)

- Matrix ki diagonal (matched) 0.21–0.29; usi row ke baaki 0.16–0.23। Antar chhota, par 8 rows mein har ek ka max diagonal par।
- $1/\tau=100$ ke baad correct pairs ka loss 0.307; har image ko \"agli class\" ka text (shifted) — loss 6.587।
- Temperature hatao ($1/\tau=1$): loss 2.027 — yadcchik anuman $\ln 8=2.079$ ke lagbhag: cosine similarities ke antar itne chhote ki softmax lagbhag uniform, gradient signal nahi। Temperature yahi chhote antaron ko badata hai।
- Batch bada — negative zyada: batch 32,768 par har positive 32,767 negatives se compare hota hai।

CLIP ki seema bhi saaf: har image ka ek vector — retrieval aur classification ke liye, par \"teesri row ka doosra number kya hai\" ka jawab nahi, text bhi nahi banata। Image ke aaspaas baat karne ke liye image representation ko language model se jodna hoga।

## Alignment se conversation tak: LLaVA ke do phase

LLaVA (Liu et al., 2023) ki sanrachna saral: CLIP ka visual encoder (ViT-L/14), ek linear projection layer, language model Vicuna। Training do phase:

| | Phase 1: feature alignment | Phase 2: visual instruction fine-tuning |
| --- | --- | --- |
| Train hue parameters | Sirf projection matrix; visual encoder aur LM freeze | Projection layer aur LM; visual encoder phir bhi freeze |
| Data | Filtered CC3M, 5.95 lakh image-text pairs (image + ek description) | 1.58 lakh instruction data: conversation 58k, detailed description 23k, complex reasoning 77k |
| Maqsad | Visual tokens frozen LM ke word embeddings se mil jaayein | Instructions ke mutabik image ke sawaal ka jawab |
| Hyperparams | 1 epoch, lr 2e-3, batch 128 | 3 epochs, lr 2e-5, batch 32 |

Teen poorniyan:

- **Phase 1 \"ek tokenizer train karna\" hai**: paper use \"frozen LM ke liye compatible visual tokenizer\" kehta hai। Aam vyakhya: random init projection pehle noise deta hai; use akela train karke noise ka LM weights par prahar roka jaata hai।
- **Phase 2 ka data \"banaya\" gaya tha**: tab image-instruction data ready nahi tha; lekhakon ne image descriptions + bounding boxes sirf-text wale GPT-4 ko diye; use conversations, descriptions aur reasoning sawaal likhwaye। Phase 2 mool roop se image input wala [instruction fine-tuning](https://dmxsf.com/hi/wiki/post-training/sft-data/) hai।
- **LLaVA-1.5** (Liu et al., 2023) do saral badlav: projection linear se do-layer MLP; visual encoder 336x336 input wala CLIP ViT-L/14 ($24\times24=576$ tokens); academic VQA data aur unified answer format prompt; data 5.58 lakh + 6.65 lakh।

Projection layer chhoti hai: Vicuna-7B (hidden 4096) aur 1024-dim ViT output ke liye linear layer $1024\times4096+4096=4{,}198{,}400$ parameters; do-layer MLP mein aur $4096\times4096+4096$ — kul 20,979,712; 6.74-arb parameters ke LM ka kramse 0.06% aur 0.31%। Ek bahut chhota module — isi se tay hota hai image ki jaankari LM tak pahunchi ya nahi।

## Dynamic resolution: ek image wakai kitne tokens

LLaVA-1.5 har image ko 336x336 karta hai — hamesha 576 tokens: 12-megapixel photo aur kuch lines ke chhote akshar wala screenshot — barabar tokens; chhote akshar zoom mein kho gaye।

Qwen2-VL (2024) \"naive dynamic resolution\": visual encoder se absolute position encoding hati, 2D RoPE aayi — koi bhi size chalta hai; output mein MLP paas ke $2\times2$ tokens ko 1 mein jodta hai। Image pehle scale hoti hai — dono sides $f=p\cdot m$ ke multiple ($p$ patch side, $m$ merge side; Qwen2-VL $f=14\times2=28$; Qwen3-VL $f=16\times2=32$); ek visual token $f\times f$ pixels ke liye; token count:

$$
n_{\text{tok}}=\frac{H'}{f}\cdot\frac{W'}{f}
$$

$H'$, $W'$ scaled height/width। Total pixels `min_pixels` aur `max_pixels` ke beech: bada — proportional neeche; chhota — proportional upar। Dono models ka default limit har image max 16,384 visual tokens (Qwen2-VL `max_pixels` $28^2\times16384$; Qwen3-VL $32^2\times16384$)। Neeche ye niyam code mein, saath KV Cache ka size:

```python
import math

def smart_resize(h, w, factor, min_pixels, max_pixels):
    """Dono sides ko factor ke multiple mein round; total pixels budget ke andar।"""
    hb, wb = round(h / factor) * factor, round(w / factor) * factor
    if hb * wb > max_pixels:                       # bada: proportional chhota
        beta = math.sqrt(h * w / max_pixels)
        hb = max(factor, math.floor(h / beta / factor) * factor)
        wb = max(factor, math.floor(w / beta / factor) * factor)
    elif hb * wb < min_pixels:                     # chhota: proportional bada
        beta = math.sqrt(min_pixels / (h * w))
        hb = math.ceil(h * beta / factor) * factor
        wb = math.ceil(w * beta / factor) * factor
    return hb, wb

# (patch, merge, min_pixels, max_pixels, layers, KV heads, head_dim)
MODELS = {
    "Qwen2-VL-7B": (14, 2, 3136, 12845056, 28, 4, 128),
    "Qwen3-VL-4B": (16, 2, 65536, 16777216, 36, 8, 128),
}
for name, (patch, merge, lo, hi, layers, kv, hd) in MODELS.items():
    per_token = 2 * layers * kv * hd * 2          # K aur V; FP16 mein har sankhya 2 bytes
    print(f"{name}: KV cache {per_token / 1024:.0f} KiB per token")
    for h, w in [(224, 224), (768, 1024), (1080, 1920), (3024, 4032)]:
        hb, wb = smart_resize(h, w, patch * merge, lo, hi)
        n = (hb // patch // merge) * (wb // patch // merge)
        print(f"  {w}x{h} -> {wb}x{hb}: {n:5d} tokens, "
              f"{n * per_token / 2**20:6.0f} MiB of KV cache")
```

```text
Qwen2-VL-7B: KV cache 56 KiB per token
  224x224 -> 224x224:    64 tokens,      4 MiB of KV cache
  1024x768 -> 1036x756:   999 tokens,     55 MiB of KV cache
  1920x1080 -> 1932x1092:  2691 tokens,    147 MiB of KV cache
  4032x3024 -> 4032x3024: 15552 tokens,    850 MiB of KV cache
Qwen3-VL-4B: KV cache 144 KiB per token
  224x224 -> 256x256:    64 tokens,      9 MiB of KV cache
  1024x768 -> 1024x768:   768 tokens,    108 MiB of KV cache
  1920x1080 -> 1920x1088:  2040 tokens,    287 MiB of KV cache
  4032x3024 -> 4032x3008: 11844 tokens,   1666 MiB of KV cache
```

(अंग्रेज़ी आउटपुट चीनी page की उसी मूल run से।)

- 224x224 thumbnail sirf 64 tokens (Qwen3-VL ka pixel min $256^2$ — pehle 256x256 mein bada); 1024x768: 999 aur 768; 1920x1080 screenshot: 2,691 aur 2,040।
- 4032x3024 ki 12-megapixel photo: dono models mein 15,552 aur 11,844 tokens — 32K context window ka 47% aur 36%। Limit na ho to ek image aadhi se zyada window kha jaati — `max_pixels` isi se hai।
- Dono models ki KV Cache per token 56 KiB aur 144 KiB; agli khnd batati hai ye number kahan se aaya।

Neeche ka calculator usi niyam se — image size badal sakte, model badal sakte, per-image token cap laga sakte:

Dynamic resolution ek naya sawaal laata hai: visual tokens 2D image mein rows/columns rakhte hain; LM ka 1D position encoding use express nahi kar sakta। Qwen2-VL ka upaay M-RoPE (multimodal RoPE): position ko time, height, width ke teen components mein; text tokens ke teeno same (normal RoPE jaisa); image tokens ke height/width components rows/columns ke saath। Qwen3-VL in teeno ko alag frequencies par interleave karta hai, aur DeepStack jodta hai: visual encoder ke teen intermediate layers (4B config mein 0 se ginte 5, 11, 17) ko extra merge layers se guzaar kar LM ke pehli teen layers ke visual positions par kram se jodta hai — LM ko neechi layers ki detail aur oonchi layers ka meaning saath। Position encoding ke baare mein [positional encoding](https://dmxsf.com/hi/wiki/architecture/positional-encoding/) page।

## Visual tokens ka bill: context, KV Cache aur delay

Visual tokens text jaise hi context ginte hain, aur key/value bhi cache karna padta hai। Har token ka poore model mein KV Cache:

$$
\text{bytes per token}=2\times L\times n_{\text{kv}}\times d_{\text{head}}\times b
$$

$L$ layers; $n_{\text{kv}}$ KV heads; $d_{\text{head}}$ har head ka dimension; $b$ har number ke bytes (FP16 = 2); shuru ka 2 = K aur V। GQA $n_{\text{kv}}$ ghatata hai — hisaab seedha neeche:

| Model | Layers | KV heads | KV Cache per token | Visual tokens per image | KV Cache per image |
| --- | --- | --- | --- | --- | --- |
| LLaVA-1.5-7B (Vicuna-7B) | 32 | 32 | 512 KiB | 576 (fixed) | 288 MiB |
| Qwen2-VL-7B | 28 | 4 | 56 KiB | 999 (1024x768) | 55 MiB |
| Qwen3-VL-4B | 36 | 8 | 144 KiB | 768 (1024x768) | 108 MiB |

LLaVA-1.5 mein GQA-rehit multi-head attention: per token 512 KiB; ek image ke 576 tokens = 288 MiB; Qwen2-VL-7B ke visual tokens 1.7 guna, KV Cache sirf panchvaan hissa। Multi-image: hisaab images ke saath linear; concurrent requests: concurrency se guna; capacity planning ke liye LLM serving ki baat — Hindi mein us adhyay ka page abhi available nahi।

Delay wala hisaab naapna padta hai। MLX par Qwen3-VL-4B-Instruct ka 4-bit version; `max_tokens=1` — naapa gaya TTFT (first-token delay): image preprocessing + visual encoder + LM prefill। Visual hissa alag dikhane ke liye wahi setting par \"sirf text, same prompt length\" wali requests bhi — comparison।

*Figure: Qwen3-VL-4B-Instruct (4-bit, MLX) ka M2 Max par 1 token generate karne ka samay; har level 3 runs ka median (sabse bada level 2 runs), pehle ek warmup। Image white background + 60 random color blocks; sirf-text comparison same-length prompt; dono ka antar visual hissa hai — image preprocessing sahit।*

| Side (tokens) | Image ke saath (sec) | Sirf text (sec) | Visual hissa (measured) | Visual hissa (estimated) |
| --- | --- | --- | --- | --- |
| 256x256 (64) | 0.19 | 0.14 | 26% | 26% |
| 512x512 (256) | 0.47 | 0.35 | 25% | 28% |
| 768x768 (576) | 1.2 | 0.82 | 30% | 31% |
| 1024x1024 (1,024) | 2.1 | 1.4 | 33% | 35% |
| 1536x1536 (2,304) | 5.4 | 3.2 | 39% | 43% |
| 2048x2048 (4,096) | 11 | 5.9 | 48% | 51% |
| 3072x3072 (9,216) | 39 | 15 | 60% | 63% |
| 4096x4096 (16,384) | 108 | 32 | 70% | 70% |

Table ke aakhri do columns visual hissa total mein: pichhli — measured (image wali - sirf text, image wali se divide); aakhri — neeche wale code se estimated compute share (sirf matmul FLOPs; normalization aur activations chhode):

```python
# Qwen3-VL-4B ke structural params (model ke config.json se)
VIT = dict(depth=24, d=1024, ff=4096)                       # visual encoder
LLM = dict(depth=36, d=2560, heads=32, kv=8, hd=128, ff=9728)  # language model

def vit_flops(n_tok, merge=2):
    """Visual encoder: merge ke pehle merge^2 guna patches, bidirectional attention।"""
    m = merge * merge * n_tok
    weights = 4 * VIT["d"]** 2 + 2 * VIT["d"] * VIT["ff"]  # har layer ke projections + MLP
    linear = 2 * m * VIT["depth"] * weights
    attn = 4 * m * m * VIT["d"] * VIT["depth"]    # QK^T aur AV, har ek 2*m^2*d
    return linear + attn

def llm_flops(n_tok):
    """LM prefill n_tok tokens; causal attention sirf lower triangle।"""
    q, kv = LLM["heads"] * LLM["hd"], LLM["kv"] * LLM["hd"]
    d = LLM["d"]
    weights = d * (q + 2 * kv) + q * d + 3 * d * LLM["ff"]
    linear = 2 * n_tok * LLM["depth"] * weights
    attn = 2 * n_tok * n_tok * q * LLM["depth"]
    return linear + attn

print(f"{'visual tokens':>13} {'ViT TFLOPs':>11} {'LLM TFLOPs':>11} "
      f"{'ViT share':>10}")
for side in (256, 512, 768, 1024, 1536, 2048, 3072, 4096):
    n = (side // 32)** 2          # ek visual token = 32x32 pixels
    v, l = vit_flops(n), llm_flops(n)
    print(f"{n:>13,} {v / 1e12:>11.2f} {l / 1e12:>11.2f} "
          f"{v / (v + l):>10.0%}")
```

```text
visual tokens  ViT TFLOPs  LLM TFLOPs  ViT share
           64        0.16        0.47        26%
          256        0.72        1.88        28%
          576        1.91        4.28        31%
        1,024        4.12        7.75        35%
        2,304       13.92       18.31        43%
        4,096       36.28       34.71        51%
        9,216      155.86       92.02        63%
       16,384      461.79      198.22        70%
```

(अंग्रेज़ी आउटपुट चीनी page की उसी मूल run से।)

- **Delay tokens se tezi se chadhta hai**: side x2, tokens x4 par image-wali requests 1,024 se 4,096 tokens mein 5.4 guna (2.1 -> 11 sec), 4,096 se 16,384 mein 9.4 guna (11 -> 108)। Same-length text requests dheeme (4.2x aur 5.5x) par phir bhi tez: attention compute lambai ke square par; jitna lamba, utna hissa।
- **Badi images par visual encoder LM se bhi dheema**: visual encoder ko merge se pehle ki $2\times2$ guna patches par bidirectional attention; attention term ka coefficient LM ke causal attention ka lagbhag 5.3 guna (code ke dono functions ki `attn` line compare karo, apni widths/layers daalkar)। Total mein hissa 26% se 70%; side 3072 (9,216 tokens) par visual 23 sec, LM prefill sirf 15।
- **Formula trend samjhata hai**: estimated shares measured se 4 bindu se zyada nahi, sab thoda oonche। Ye ek reconciliation hai, prediction formula nahi: hardware, implementation, quantization badle — share badlega; \"bottleneck visual ya language\" ka faisla ke liye kaafi।
- **Ye sirf ek machine, ek request ka prefill**: M2 Max, batch 1, concurrency nahi। Server GPU par absolute bahut chhota; visual share ka resolution ke saath chadhne wala aakar milta-julta hoga — ye is page ne jaancha nahi।

Is hisaab ke teen seedhe engineering upyog:

1. **Resolution ko delay/cost ka knob banao**: 1,024 tokens mein hal hone wala task ko 9,216 na bhejo; pichhle khnd ne \"kaafi minimum resolution\" kaise dhundein bataya।
2. **Ek image par kai sawaal: dobara calculate nahi, reuse karo**: inference engine image-prefix caching support kare to visual encode + prefill ka fixed cost ek baar; image prompt ke aage, sawaal peeche — hit ka mauka; mechanism prefix caching mein (Hindi page abhi nahi)।
3. **Badi image: pehle low-res mein global, phir local crop**: key area akela bhejo — chhote aksharon ki effective size bachi, poore high-res ka square cost bhi bacha।

## Experiment: resolution chhote akshar padhne ka faisla karti hai

OCR multimodal applications ki sabse aam aur sabse accident-prone zaroorat hai। \"Resolution padhne par kya asar\" quantize karne ke liye synthetic experiment:

- 512x512 white background par 5 random 6-digit numbers (Arial; font size 8, 12, 16, 24 px); kul 20 images; fixed seed।
- Har image bicubic se x0.5, x1, x2, x3 scale, phir Qwen3-VL-4B-Instruct (4-bit, MLX)। Prompt: \"Read all the numbers in the image from top to bottom. Answer with the numbers only, separated by commas.\"; greedy decoding।
- Do accuracy: **strict match** — output ke number groups asli se ek-ek milen; **ignore extra punctuation** — \"61.6517\" ko \"616517\" gino; sirf digits ka padhna। Har cell 100 numbers, isliye ~0.7 ke nateeje ka 95% range lagbhag +/-9 bindu।

*Figure: Qwen3-VL-4B-Instruct (4-bit) 512x512 white-background images ke 6-digit numbers padhta hai; har bindu 100 numbers। Image pehle x0.5, x1, x2, x3 scale hoti hai, isliye ek hi effective size alag size+scale se aa sakta hai; ek hi kshaitij-bindu par bindu horizontally thode khisakaye gaye।*

Neeche table har cell mein \"strict / ignore-extra-punctuation\" digit accuracy:

| Font size (px) | x0.5 (64 tokens) | x1 (256) | x2 (1,024) | x3 (2,304) |
| --- | --- | --- | --- | --- |
| 8 | 0.01 / 0.04 | 0.69 / 0.90 | 0.94 / 0.99 | 0.97 / 0.97 |
| 12 | 0.75 / 0.75 | 1.00 / 1.00 | 1.00 / 1.00 | 1.00 / 1.00 |
| 16 | 0.92 / 0.92 | 1.00 / 1.00 | 1.00 / 1.00 | 1.00 / 1.00 |
| 24 | 1.00 / 1.00 | 1.00 / 1.00 | 1.00 / 1.00 | 1.00 / 1.00 |

- **Accuracy character ki effective size tay karti hai, token count nahi**: font size x scale = character ki model input mein asli size (effective font size)। Sab cells lagbhag ek curve par: 4 px par sirf 4%; 6 px 75%; 8 px lagbhag 91%; 12 px+ sab sahi। 8-px image x1 (256 tokens) aur 16-px image x0.5 (64 tokens) — dono ka effective 8 px; accuracy 90% aur 92%; tokens 4 guna ke antar। Ek visual token ka side 32 px: ~12 px (0.4 token) pakka padhta; 8 px (0.25 token) galtiyan shuru; 4 px (0.125 token) lagbhag sab galat।
- **Bahut chhote akshar — model banata hai**: 8-px x0.5 (effective 4 px; 64 tokens): 100 mein sirf 4 sahi; 8 ek digit galat; baaki 88 digits ki sankhya hi galat; output mein \"027982,027982,...\" jaise repeats aur \"03 08 17\" jaise non-numbers।
- **Border zone ki galtiyan \"ek digit ka antar\"**: effective 6 px (12-px x0.5): 25 galat, unme 22 sirf ek digit; effective 8 px (16-px x0.5): 8 galat, sab sirf ek digit — jaise \"031862\" ko \"031882\" padhna। Ye galtiyan \"sahi dikhti hain\" — aankh se spot-check mushkil।
- **Format errors doosri category**: 8-px, 256 tokens: strict 0.69, ignore-punctuation 0.90। Bech ka 21: digits sab sahi, par model numbers ke beech decimal point laga diya — \"61.6517\", \"76.86.94\" — do-teen numbers ban gaye। Ye output-format constraints + checks se roke ja sakte hain (jaise har line par sirf 6-digit + regex)।
- **Zoom madad karta hai, par khoi hui jaankari wapas nahi laata**: 8-px x2 par 0.90 se 0.99; x3 par 0.97 — aur nahi badha: zoom ne jaankari nahi badhai, sirf har character ko zyada tokens diye; original mein blur strokes blur hi hain। 12-px+ images 256 tokens (512x512) par hi sab sahi — aur zoom sirf cost।

Ye experiment synthetic data par hai: sirf Arial digits, ek 4-bit 4B model, ek prompt। Le jaane wali baat tareeka hai, threshold nahi: **apne asli samples lo, kai resolutions par chalao, accuracy-token curve banao, phir knee chuno**।

Chhote akshar padhe na jaayein to pehle saste upay: PDF zyada DPI par render karo, screenshot zoom karo, sirf key region crop karke bhejo। Poore image ka resolution badhana tokens ko side ke square par badhata hai।

## Task selection: OCR, VLM ya combination

Neeche November 2026 ki aam salah; asli chunav apne samples ke evaluation se:

| Task | Behtar tareeka | Wajah |
| --- | --- | --- |
| Image-search, image-text retrieval, zero-shot classification | CLIP, SigLIP jaise embedding models + vector retrieval | Har image ek baar encode; baad mein vector comparison — sasta; retrieval ka tareeka RAG mein (Hindi page abhi nahi) |
| Bill/form se fixed fields | OCR ya layout parsing + rule checks; VLM se nikalna ho to checks zaroori | Auditable, dohraaya ja sakta; VLM ke number-galti \"sahi dikhte hain\" |
| Screenshot, chart, UI dekhkar jawab | VLM; input resolution kaafi oonchi | Layout aur semantics chahiye, sirf text nahi |
| Multi-page PDF, contracts, strict compliance Q&A | Layout parsing + retrieval; sirf key pages VLM ko | Tokens/cost pages ke saath linear; jawab ke paas traceable source honi chahiye |
| UI chalane wale Agents | VLM screen dekhe + tool calls | (Hindi page abhi nahi) |

## Debugging: dekha ya nahi, joda ya nahi, use kiya ya nahi

Multimodal system galat jawab de to sirf final answer se karan milte-julte। Neeche ke kram se jaancha zyada mazboot:

| Layer | Sawaal | Lakshan | Jaanch aur upay |
| --- | --- | --- | --- |
| Dekha ya nahi | Target jaankari visual tokens mein aayi? | Chhote akshar, patli lines, dense tables mein galti; prompt badalne se farak nahi | Effective font size aur tokens anuman; zoom, local crop, `max_pixels` badhao (upar ka experiment) |
| Joda ya nahi | Visual tokens instruction se sahi bände? | Beka sawaal ka jawab; multi-image mein galat image se | Chat template aur placeholders jaacho: har image ke start/end markers, placeholder count = visual tokens, image-sawaal ka kram |
| Use kiya ya nahi | Model sachmuch image par aadharit? | Image mein jo nahi wo gadh diya; bina image dekhe common sense se jawab | Comparison karo: doosri image, key region chhupao, khaali image — jawab same hai to image use nahi hui; image ke andar ka evidence maango |

## Evaluation: sirf \"jawab milta-julta\" dekhkar nahi

Sabse chhota usable multimodal evaluation — galtiyon ke type ke hisab se record, ek total score se zyada kaam ka:

1. 20–50 asli samples; apne asli input types cover karein (screenshots, scans, photos)।
2. Har image ka standard answer likho; failure types label karo: **perception errors** (object, color, count), **OCR errors** (khaas numbers aur proper nouns), **spatial relation errors**, **instruction/format errors**, **hallucinations** (image mein jo nahi)।
3. Kai resolutions aur prompts par ek-ek baar chalao; har type ki ginnati, delay aur per-run cost record।
4. Comparison samples (doosri image, khaali image) — confirm karo model sachmuch image use karta hai।

Evaluation ka aam tareeka LLM evaluation methodology mein — Hindi page abhi available nahi।

## Image-text QA se native multimodal tak

[Stanford CS25 ki native multimodal class](https://drive.google.com/file/d/10Doblrt3Le_FpbVQoMP0DbuCIO3rtWPW/view) representation, sequence modeling aur modality-specific compute se architecture chedti hai। Ek model family padhte waqt teen chunav alag rakho: kaun se modalities ek trunk share karte hain; kaun se saath train hote hain; kaun se seedha output de sakte hain। LM ko visual encoder jodna image-text QA deta hai। Realtime audio/video interaction ke liye alag sampling rates, time alignment, streaming output bhi।

Failure analysis mein ek hi video ka sirf frame-order badla version banakar poocho \"kaunsi cheez pehle hui\"। Do inputs ka jawab hamesha same ho to jaacho: sampled frames mein event hai ya nahi, time info model tak pahunchi ya nahi, sawaal order hint karta hai ya nahi। Ye comparison static image classification se video tasks ke zyada paas hai।

## Video models image predict kar sakte, representation bhi

Stanford CS25 ki Joint Embedding Predictive World Models class [V-JEPA 2](https://arxiv.org/abs/2506.09985) se doosra training objective batati hai। Encoder video ko features banata hai; kuch features chhupe hote hain; predictor visible context se target features ka anuman lagata hai। Feature prediction representation learning ke kaam aata hai। Action-conditioned version V-JEPA 2-AC action ko input lekar us action ke baad ki state representation predict karta hai।

Robot planning mein ek hi start observation se candidate actions evaluate karke har ek ki predicted representation ko target se compare kar sakte hain। Acceptance mein representation-prediction error aur actual task success alag dekho। Model object position sahi bhi likhe, par grip ke contact, occlusion, chhote shape ke antar chhod sakta hai — wahi action ka natija badalte hain। Action aur occlusion severity ke hisaab se slice karne se VQA tests jo cover nahi karte wo failures dikhte hain।

## Saransh aur abhyas

**Is page ke bindu:**

1. Multimodal LLM image ko patch mein kaatta hai; visual encoder, merge, projection se visual tokens; prompt ke placeholders replace; LM text ki tarah padhta; output text hi।
2. CLIP symmetric InfoNCE se image-text align karta hai; temperature cosine ke chhote antaron ko badata hai; har image ek vector — retrieval aur zero-shot ke liye, conversation ke liye nahi।
3. LLaVA do kadam: pehle sirf projection align; phir image-instruction data se projection + LM।
4. Dynamic resolution mein visual tokens $\frac{H'}{f}\cdot\frac{W'}{f}$ ($f$ = patch x merge, 28 ya 32 px); tokens context, KV Cache aur prefill delay tay karte; GQA KV Cache neeche।
5. Delay tokens se tez chadhta hai: Qwen3-VL-4B ka M2 Max TTFT — 1,024 visual tokens ~2 sec; 16,384 ~108 sec; visual encoder ka hissa 26% se 70%; side 3072 par LM se bhi dheema।
6. Chhote akshar ka padhna character ki effective size se: is page mein ~12 px+ sab sahi (visual token ka side 32 px), 8 px galtiyan, 4 px lagbhag sab galat; galtiyan aksar \"ek digit\", ya decimal format। Pehle zoom ya crop; phir model badalne ka sawaal; format output constraints se।

### Tvarit self-check

**1. LLaVA ke Phase 1 (feature alignment) mein kaun se parameters train hote hain?**

- [ ] Visual encoder, projection layer aur LM ke saare
- [x] Sirf projection layer
- [ ] Sirf language model
- [ ] Visual encoder aur LM; projection freeze

> Phase 1 mein visual encoder aur LM freeze; sirf projection matrix; Phase 2 mein projection + LM dono।

**2. Qwen2-VL (patch 14, merge $2\times2$) 448x448 image — visual tokens kitne (markers chhode)?**

- [ ] 1024
- [ ] 64
- [x] 256
- [ ] 1568

> $f=14\times2=28$; $448/28=16$; to $16\times16=256$ tokens।

**3. CLIP ka batch itna bada (32,768) kyun?**

- [ ] Memory bharne ke liye
- [x] Batch mein har positive baaki $N-1$ samples se compare hota hai; batch bada — negatives zyada
- [ ] Text encoder ko bahut images chahiye
- [ ] Temperature parameter bachane ke liye

> Diagonal positive; baaki $N^2-N$ pairs negative; batch bada — comparison poori।

**4. Is page ke experiment mein temperature nahi ($1/\tau=1$) to CLIP loss 2.027 — yadcchik $\ln 8=2.079$ ke paas. Karan?**

- [ ] Model kharab
- [ ] Cosine similarity sirf 0 ya 1 le sakta
- [x] Cosine similarities ke antar sirf dasvein-hissey ke darje; bina amplify softmax lagbhag uniform
- [ ] 8 classes kam hain

> Temperature 0.01–0.10 darje ke antaron ko 100 guna badata hai; tab softmax mein farak, gradient mein signal।

**5. Lagbhag barabar visual tokens (~1000) par Qwen2-VL-7B ka KV Cache LLaVA-1.5-7B ke 576 tokens se bahut chhota kyun?**

- [ ] Qwen2-VL ke tokens chhote hain
- [ ] Qwen2-VL KV Cache ko 8-bit mein simatata hai
- [x] Qwen2-VL GQA use karta hai: sirf 4 KV heads; per-token KV Cache 56 KiB vs LLaVA-1.5 ke 512 KiB
- [ ] Visual tokens ko KV Cache nahi chahiye

> Per-token KV Cache KV heads ke samanupati: $2\times28\times4\times128\times2=57344$ bytes।

**6. Model screenshot ke chhote akshar nahi padh pa raha — sabse sasta pehla kadam?**

- [ ] Bada model lo
- [x] Input zoom karo ya sirf key region crop karo — character ko zyada visual tokens milne do
- [ ] Temperature 0 karo
- [ ] Prompt mein examples badhao

> Character bahut chhota ho to jaankari katne/merge mein hi kho gayi; model ya prompt se wapas nahi aati।

**अभ्यास:**

1. `smart_resize` haath se: Qwen2-VL 1920x1080 screenshot — scaled size, visual tokens, aur FP16 KV Cache?
2. $N=8$ batch, yadcchik anuman par CLIP loss ki expectation? Is page ke no-temperature 2.027 se compare karke kya samajh aata?
3. LLaVA-1.5 ka ViT output 1024-dim; Vicuna-7B hidden 4096। Linear projection aur do-layer MLP projection ke parameters gino, code se verify।
4. Apne ek screenshot par \"resolution aur padhna\" experiment dohrao: x1, x2, x3 zoom; har baar padhwao; galtiyon ke types record।
5. Customer-support system user ke uploaded invoice se amount bharta hai — design likho: kahan OCR, kahan VLM, \"sahi dikha par galat\" errors kaise rokein?
6. Is page ke `vit_flops` aur `llm_flops` se 2048x2048 vs 1024x1024 compare: visual encoder aur LLM prefill compute kitne guna badha? Dono multiples kyun alag?

<details>
<summary>संदर्भ उत्तर</summary>

1. $f=28$: $1080/28=38.57$ -> round 39; $39\times28=1092$; $1920/28=68.57$ -> 69; $69\times28=1932$। Scaled 1932x1092; dono pixel limit ke andar — aur adjust nahi। Visual tokens $39\times69=2691$। Per-token KV Cache $2\times28\times4\times128\times2=57344$ bytes (56 KiB); kul $2691\times56\text{ KiB}\approx147\text{ MiB}$।
2. Yadcchik anuman par softmax lagbhag uniform; cross entropy $\ln 8\approx2.079$; dono dishaon ka ausat bhi 2.079। No-temperature ka 2.027 lagbhag barabar — cosine ke antar itne chhote ki model ke paas abhi discrimination nahi; isi se CLIP $1/\tau$ ~100 rakhta hai।
3. Linear projection: $1024\times4096+4096=4{,}198{,}400$; do-layer MLP: + $4096\times4096+4096=16{,}781{,}312$; kul $20{,}979{,}712$। `nn.Linear(1024, 4096)` aur `nn.Linear(4096, 4096)` banakar `numel()` se jaanch।
4. Fixed jawab nahi। Typical: x1 par \"ek digit ka antar\" wali galtiyan, zoom par gayab — matlab jaankari thi, tokens kam the; zoom ke baad bhi galat — original ki jaankari kho gayi (compression, blur); zyada saaf source chahiye।
5. Sondar plan: pehle OCR ya layout parsing se \"amount\" region locate + text; phir VLM usi region parhe; dono mein antar -> manual review; amount vs line-items ka sum, invoice number format, date range — rule checks; original image + recognition results rakhkar audit ke liye। Kunji: ek hi reading par bharosa na karo; \"sahi dikha\" wali galti doosri raasta ya rule roke।
6. Visual encoder 4.12 se 36.28 TFLOPs — 8.8 guna; LM 7.75 se 34.71 — 4.5 guna। Tokens 4 guna; dono ke linear parts (projections, MLP) 4 guna; attention parts 16 guna; kul 4 se 16 ke beech — jis mein attention ka hissa zyada, utna 16 ke paas। Visual encoder ka attention coefficient bahut bada — isliye uska multiple ooncha; aur badi image par uska share aur badhega।

</details>

## Aage ki padhai

- Radford et al., [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/2103.00020) (CLIP)।
- Dosovitskiy et al., [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929) (ViT)।
- Liu et al., [Visual Instruction Tuning](https://arxiv.org/abs/2304.08485) (LLaVA) aur [Improved Baselines with Visual Instruction Tuning](https://arxiv.org/abs/2310.03744) (LLaVA-1.5)।
- Zhai et al., [Sigmoid Loss for Language Image Pre-Training](https://arxiv.org/abs/2303.15343) (SigLIP; softmax ki jagah sigmoid loss)।
- Wang et al., [Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution](https://arxiv.org/abs/2409.12191); Qwen team, [Qwen3-VL Technical Report](https://arxiv.org/abs/2511.21631)।
- Sambandhit pages: [Diffusion aur flow matching](https://dmxsf.com/hi/wiki/multimodal/diffusion-and-flow-matching/) (\"image banana\" ka doosra raasta; pi0 aur GR00T N1 ke action heads usi ke flow-matching versions hain), [Attention](https://dmxsf.com/hi/wiki/architecture/attention-basics/), [Positional encoding](https://dmxsf.com/hi/wiki/architecture/positional-encoding/), [Instruction fine-tuning data](https://dmxsf.com/hi/wiki/post-training/sft-data/), [World models aur planning](https://dmxsf.com/hi/wiki/multimodal/world-models/)।
- Brohan et al., [RT-2: Vision-Language-Action Models Transfer Web Knowledge to Robotic Control](https://arxiv.org/abs/2307.15818): robot actions tokens bana kar web data ke saath VLM fine-tune।
- Kim et al., [OpenVLA: An Open-Source Vision-Language-Action Model](https://arxiv.org/abs/2406.09246): Llama 2 7B + DINOv2 + SigLIP fused visual encoder ka open VLA।
- Black et al., [pi0: A Vision-Language-Action Flow Model for General Robot Control](https://arxiv.org/abs/2410.24164): PaliGemma ke paas lagbhag 300M ka flow-matching action expert; ek baar mein 50-step continuous action chunk।
- NVIDIA, [GR00T N1: An Open Foundation Model for Generalist Humanoid Robots](https://arxiv.org/abs/2503.14734): Eagle-2 VLM + flow-matching DiT action head; cross-attention se jude; \"data pyramid\" se real, sim, neural video aur insani video ek saath।

- [World models aur planning](https://dmxsf.com/hi/wiki/multimodal/world-models/)

## सहायक कोड

[Multimodal LLMs: images as tokens](https://github.com/dmxsf/dmxsf/tree/main/labs/multimodal/multimodal-llms): Patches to visual tokens, what the tokens cost in KV cache and FLOPs, LLaVA's projector and two training stages, CLIP's contrastive loss and a small CLIP trained from scratch on rendered shapes. With --hf, CLIP ViT-B/32 on CIFAR-10.

- सहायक रिपॉज़िटरी में चलाएँ (--quick से तेज़ जाँच): `uv run dmxsf run multimodal/multimodal-llms`
- [प्रयोग स्क्रिप्ट देखें](https://github.com/dmxsf/dmxsf/blob/main/labs/multimodal/multimodal-llms/run.py)
- [प्रयोग विवरण](https://github.com/dmxsf/dmxsf/blob/main/labs/multimodal/multimodal-llms/README.en.md)
- [`vision.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/multimodal/vision.py)
- [`clip.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/multimodal/clip.py)
- [सूची में देखें](https://dmxsf.com/hi/code/#multimodal-llms)

## अक्सर पूछे जाने वाले सवाल

### Multimodal bade model ki bunyadi sanrachna kya hai?

Teen hisse aur ek convention। Visual encoder (aam taur ViT) image ko patch mein kaatkar vectors mein encode karta hai; merge aur projection layer paas ke patch vectors jodkar linear layer ya MLP se language model ke hidden dimension mein le jaati hai — visual tokens; language model in visual aur text tokens ko text jaise padhta hai aur text banata hai। Convention: prompt mein har visual token ke liye ek placeholder reserved hota hai; embedding lookup ke baad un positions ke vectors visual tokens se badal diye jaate hain।

### CLIP aur LLaVA mein kya antar?

CLIP contrastive learning se image encoder aur text encoder train karta hai — matching image-text ek hi vector space mein paas; har image ka sirf ek vector; retrieval aur zero-shot classification mein achha, par text nahi banata। LLaVA CLIP ke visual encoder ko projection layer se language model se jodta hai: pehle sirf projection layer align karne ko, phir image-instruction data se projection + LM dono — ab image ke aaspaas baat ho sakti hai।

### Ek image multimodal model mein kitne tokens leti hai?

Model par nirbhar। LLaVA-1.5 sab images ko 336x336 kar deta hai — hamesha 576 tokens। Qwen2-VL aur Qwen3-VL dynamic resolution: dono sides ko patch x merge (28 ya 32 pixel) ke multiple mein round; har token 784 ya 1024 pixels ke liye। 1920x1080 screenshot lagbhag 2,040-2,691 tokens; 4032x3024 phone photo lagbhag 12,000-16,000; default pixel limit = har image max 16,384 tokens।

### Resolution badhane se multimodal results behtar hote hain?

Hamesha nahi। Resolution duguni — tokens chaar guna; prefill delay aur KV Cache saath chadhte; fayda sirf tab jab task detail maange। Is page ke experiment mein Qwen3-VL-4B 12-pixel+ font-size ke numbers 512x512 input (256 tokens) par hi sab sahi; 8-pixel numbers 256x256 (64 tokens) par lagbhag sab galat, 512x512 par lagbhag 90%, 1024x1024 (1,024 tokens) par 99%। Resolution ko task ki minimum zaroori detail se chunein; zaroorat par local crop + zoom, poora image nahi।

### Kab OCR, kab seedha VLM?

Fixed fields (amount, date, number) nikaal kar auditable record chhodna ho to pehle OCR ya layout parsing + rule checks — VLM numbers mein galti kare to wo "sahi dikhta hai"। Layout, charts, image ke meaning ke saath jawab chahiye to VLM behtar। Multi-page PDF aur strict compliance aam taur combination: pehle parse aur retrieve, sirf key pages VLM ko।
