zandervdm commited on
Commit
cb3fb46
·
verified ·
1 Parent(s): 77f9eec

Bundle the qevi inference engine in-repo

Browse files
Files changed (1) hide show
  1. qevi/core.py +179 -0
qevi/core.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The validated Qevi readout, in one place.
2
+
3
+ Consolidates the routine that had been copy-pasted into eleven experiment scripts. Every design
4
+ decision here is one this project measured rather than assumed:
5
+
6
+ packed layout + block-diagonal mask plan/02 section 3; exact order invariance, research/19
7
+ widened shared V-prefix research/31: the image is wrapped once in
8
+ <|im_start|>user\\n<|vision_start|> ... <|vision_end|> so
9
+ every question's causal view reconstructs a real chat turn
10
+ corrected M-RoPE text offset research/18 section 6: text resumes at
11
+ max(grid_h, grid_w) // spatial_merge_size, NOT at the raw
12
+ image token count
13
+ native LM-head readout research/31/32: reading the trunk's own logits at each
14
+ sentinel beats a trained typed head by 15-34 points on
15
+ every task tested. Do NOT delete the LM head and train
16
+ typed heads, which is what plan/02 section 4.4 originally
17
+ specified.
18
+
19
+ One forward pass answers N questions. No text is generated. `forward_logits` returns, per question,
20
+ the raw logits over that question's own candidate answer tokens, so callers softmax over 2 logits
21
+ for noul, K for choice, L for score.
22
+
23
+ This module is import-safe without torch for the pure-python helpers at the bottom, which the
24
+ corpus builder and analysis scripts use.
25
+ """
26
+
27
+ from dataclasses import dataclass
28
+ from typing import Sequence
29
+
30
+ PREFIX_PRE = "<|im_start|>user\n<|vision_start|>"
31
+ PREFIX_POST = "<|vision_end|>"
32
+
33
+ NOUL_TEMPLATE = "Statement: {s}\nIs this statement true of the image? Answer Yes or No."
34
+ LETTERS = ["A", "B", "C", "D", "E", "F", "G", "H"]
35
+
36
+
37
+ def wrap_turn(body: str) -> str:
38
+ """Close the user turn and open the assistant turn, so the sentinel sits exactly where the
39
+ model would begin generating its answer."""
40
+ return f"{body}<|im_end|>\n<|im_start|>assistant\n"
41
+
42
+
43
+ def noul_question(statement: str) -> str:
44
+ return wrap_turn(NOUL_TEMPLATE.format(s=statement))
45
+
46
+
47
+ def choice_question(options: Sequence[str]) -> str:
48
+ opts = " ".join(f"{LETTERS[i]}) {o}" for i, o in enumerate(options))
49
+ return wrap_turn(f"Which of these is in the image? {opts}\nAnswer with the letter.")
50
+
51
+
52
+ def score_question(levels: Sequence[str], subject: str = "people") -> str:
53
+ lv = " / ".join(l.capitalize() for l in levels)
54
+ return wrap_turn(f"How many {subject} are in this image? Answer with one word: {lv}.")
55
+
56
+
57
+ def choice_question_generic(text: str, options: Sequence[str]) -> str:
58
+ """Like choice_question, but the caller's own question text is the prompt, not a hardcoded
59
+ "which of these is in the image". Needed for the API (server.py), where a caller's choice
60
+ question is arbitrary ("What product category does this belong to?"), not always about
61
+ object presence the way every choice_question call site in the research scripts was."""
62
+ opts = " ".join(f"{LETTERS[i]}) {o}" for i, o in enumerate(options))
63
+ return wrap_turn(f"{text} {opts}\nAnswer with the letter.")
64
+
65
+
66
+ def score_question_generic(text: str, levels: Sequence[str]) -> str:
67
+ """Like score_question, but the caller's own question text is the prompt, not the hardcoded
68
+ "how many {subject}" counting template. Needed for the API, where a score question is
69
+ arbitrary ("Rate the condition"), not always a count."""
70
+ lv = " / ".join(l.capitalize() for l in levels)
71
+ return wrap_turn(f"{text} Answer with one word: {lv}.")
72
+
73
+
74
+ @dataclass
75
+ class Readout:
76
+ """Where to read, and which vocabulary entries constitute the answer alphabet."""
77
+ question_text: str
78
+ candidate_token_ids: list
79
+
80
+
81
+ def softmax(logits, T=1.0):
82
+ import math
83
+ m = max(l / T for l in logits)
84
+ ex = [math.exp(l / T - m) for l in logits]
85
+ s = sum(ex)
86
+ return [e / s for e in ex]
87
+
88
+
89
+ def build_readouts(tokenizer, specs):
90
+ """specs: list of (question_text, [answer strings]) -> list[Readout]."""
91
+ out = []
92
+ for qtext, answers in specs:
93
+ ids = [tokenizer.encode(a, add_special_tokens=False)[0] for a in answers]
94
+ out.append(Readout(question_text=qtext, candidate_token_ids=ids))
95
+ return out
96
+
97
+
98
+ def unwrap(model):
99
+ """Reach the underlying Qwen3VL model whether or not `model` is PEFT/LoRA-wrapped.
100
+
101
+ Needed because PEFT replaces `model.model` with a LoraModel and `model.get_rope_index` then
102
+ does not exist. PEFT injects its adapter layers in place, so the base model's own forward and
103
+ lm_head still route through them and gradients still reach the LoRA parameters; the wrapper is
104
+ only needed for saving.
105
+ """
106
+ return model.get_base_model() if hasattr(model, "get_base_model") else model
107
+
108
+
109
+ def forward_logits(model, processor, image, readouts, need_grad=False):
110
+ """One packed forward pass over `image` answering every readout independently.
111
+
112
+ Returns list[list[float]] when need_grad is False, or a list of 1-D tensors when True (so a
113
+ training loop can backprop through them). The image tokens are causally isolated from all
114
+ question text, and each question is isolated from every other by the block-diagonal mask.
115
+
116
+ Works with a plain Qwen3VLForConditionalGeneration or a PEFT-wrapped one.
117
+ """
118
+ import torch
119
+ from .pack import Question, build_packed_batch
120
+
121
+ base = unwrap(model)
122
+ ctx = torch.enable_grad() if need_grad else torch.no_grad()
123
+ with ctx:
124
+ ii = processor.image_processor(images=[image], return_tensors="pt")
125
+ pixel_values = ii["pixel_values"].to(model.device, model.dtype)
126
+ grid = ii["image_grid_thw"].to(model.device)
127
+
128
+ sms = model.config.vision_config.spatial_merge_size
129
+ _, gh, gw = grid[0].tolist()
130
+ gt = grid[0].tolist()[0]
131
+ n_img = (gt * gh * gw) // (sms**2)
132
+ img_tok = model.config.image_token_id
133
+
134
+ tok = processor.tokenizer
135
+ pre = tok(PREFIX_PRE, add_special_tokens=False).input_ids
136
+ post = tok(PREFIX_POST, add_special_tokens=False).input_ids
137
+ L1, L2 = len(pre), len(post)
138
+ v_len = L1 + n_img + L2
139
+ tso = max(gh, gw) // sms # research/18 section 6
140
+
141
+ toks = [tok(r.question_text, add_special_tokens=False).input_ids for r in readouts]
142
+ qs = [Question(qtype="noul", context_len=len(t), readout_lens=[]) for t in toks]
143
+ batch = build_packed_batch(image_len=v_len, questions=qs, position_scheme="reset",
144
+ text_start_offset=L1 + tso + L2)
145
+
146
+ input_ids = torch.full((batch.seq_len,), img_tok, dtype=torch.long)
147
+ input_ids[:L1] = torch.tensor(pre)
148
+ input_ids[L1 + n_img : v_len] = torch.tensor(post)
149
+ cur, sentinels = v_len, []
150
+ for t in toks:
151
+ input_ids[cur : cur + len(t)] = torch.tensor(t)
152
+ cur += len(t)
153
+ sentinels.append(cur - 1)
154
+ input_ids = input_ids.unsqueeze(0).to(model.device)
155
+
156
+ ph = torch.full((1, n_img), img_tok, dtype=torch.long, device=model.device)
157
+ tt = torch.ones((1, n_img), dtype=torch.int, device=model.device)
158
+ ipos, _ = base.model.get_rope_index(input_ids=ph, mm_token_type_ids=tt,
159
+ image_grid_thw=grid)
160
+
161
+ pos = torch.zeros(3, 1, batch.seq_len, dtype=torch.long, device=model.device)
162
+ pos[:, :, :L1] = torch.arange(L1, device=model.device)
163
+ pos[:, :, L1 : L1 + n_img] = ipos + L1
164
+ pos[:, :, L1 + n_img : v_len] = (L1 + tso) + torch.arange(L2, device=model.device)
165
+ ts = batch.position_ids[0].to(model.device)
166
+ pos[:, :, v_len:] = ts[v_len:]
167
+
168
+ out = base.model(input_ids=input_ids,
169
+ attention_mask=batch.attn_bias.to(dtype=model.dtype,
170
+ device=model.device),
171
+ position_ids=pos, pixel_values=pixel_values, image_grid_thw=grid)
172
+ hidden = out.last_hidden_state[0]
173
+ stacked = torch.stack([hidden[p] for p in sentinels]).to(model.dtype)
174
+ logits = base.lm_head(stacked).float()
175
+
176
+ if need_grad:
177
+ return [logits[i, r.candidate_token_ids] for i, r in enumerate(readouts)]
178
+ return [[logits[i, c].item() for c in r.candidate_token_ids]
179
+ for i, r in enumerate(readouts)]