File size: 15,813 Bytes
e3cb0cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
"""In-process teacher wrappers that produce the same tensors as offline precompute.

`OnlineTeacherStage2` mirrors `src/precompute_teacher_reps.py` (no-text branch):
  forward base model → pool aux-image hidden states → [L+1, N*latent_size, D] per sample.

`OnlineTeacherStage3` mirrors `src/precompute_teacher_latents.py`:
  forward Stage-2 ckpt with latent_mode=True → [L+1, N*latent_size, D] per sample.

Both write each computed tensor to disk under the same filename layout used by the
offline scripts, so subsequent runs (or pure-offline Stage-2/3 runs) can reuse them
via `load_offline_tensor`. The training loss path is unchanged: the trainer hands the
returned list[CPU Tensor] straight to `inputs['teacher_hidden_states_for_alignment']`.
"""

import hashlib
import logging
import os

import torch
import torch.nn.functional as F
from transformers import Qwen3VLConfig

from monet_qwen3_model.modeling_qwen3_vl_monet import Qwen3VLMonetForConditionalGeneration


def _compute_teacher_fingerprint(model_path: str) -> str:
    """Cheap stable fingerprint of a teacher checkpoint.

    Used to namespace cache files so that re-training Stage 2 (and pointing the
    Stage 3 online teacher at the new ckpt) cannot silently consume stale latents
    from a previous Stage 2 run. Captures:
      - absolute path (catches different ckpt directories)
      - mtime + size of the key weight/config files (catches in-place re-saves)
    Does not require reading any weights — runs in O(stat).
    """
    abs_path = os.path.abspath(model_path)
    parts = [abs_path]
    for name in (
        "config.json",
        "model.safetensors.index.json",
        "model.safetensors",
        "pytorch_model.bin.index.json",
        "pytorch_model.bin",
    ):
        p = os.path.join(abs_path, name)
        if os.path.isfile(p):
            try:
                st = os.stat(p)
                parts.append(f"{name}:{int(st.st_mtime)}:{st.st_size}")
            except Exception:
                pass
    raw = "|".join(parts).encode("utf-8")
    return hashlib.sha1(raw).hexdigest()[:12]


def _per_sample_hidden_states(hidden_states, b, batch_size):
    """Robust per-sample extraction matching `_get_sample_hidden_states` in precompute."""
    if not hidden_states:
        raise RuntimeError("hidden_states is empty; model must be called with output_hidden_states=True")
    first = hidden_states[0]
    if torch.is_tensor(first) and first.dim() == 3 and len(hidden_states) == batch_size:
        return hidden_states[b]
    if torch.is_tensor(first) and first.dim() == 3 and first.size(0) == batch_size:
        return torch.stack([layer[b] for layer in hidden_states], dim=0)
    raise RuntimeError(f"Unsupported hidden_states layout: type={type(first)}")


class _OnlineTeacherBase:
    rep_prefix = "rep"

    def __init__(
        self,
        model_path,
        tokenizer_len,
        special_token_ids,
        device,
        dtype=torch.bfloat16,
        cache_dir=None,
        answer_start_pattern=None,
        alignment_layer="all_layers",
    ):
        if alignment_layer not in ("all_layers", "last_layer"):
            raise ValueError(
                f"alignment_layer must be 'all_layers' or 'last_layer', got {alignment_layer!r}"
            )
        self.alignment_layer = alignment_layer
        config = Qwen3VLConfig.from_pretrained(model_path)
        try:
            setattr(config, "use_cache", False)
        except Exception:
            pass
        model = Qwen3VLMonetForConditionalGeneration.from_pretrained(
            model_path, config=config, dtype=dtype, attn_implementation="sdpa",
        )

        try:
            model.resize_token_embeddings(tokenizer_len)
            model.config.vocab_size = tokenizer_len
        except Exception as e:
            logging.warning(f"[online_teacher] resize_token_embeddings failed: {e}")

        model.config.latent_token_id = int(special_token_ids["abs_pad"])
        model.config.latent_start_id = int(special_token_ids["abs_start"])
        model.config.latent_end_id = int(special_token_ids["abs_end"])
        if answer_start_pattern is not None:
            try:
                model.config.answer_start_pattern = (
                    answer_start_pattern.tolist()
                    if hasattr(answer_start_pattern, "tolist")
                    else list(answer_start_pattern)
                )
            except Exception:
                pass

        for p in model.parameters():
            p.requires_grad = False
        try:
            model.gradient_checkpointing_disable()
        except Exception:
            pass
        model.eval()
        model.to(device)

        self.model = model
        self.device = device
        self.special_token_ids = special_token_ids

        # Per-teacher fingerprint: namespaces the cache so different ckpts can't
        # silently share files even when the user passes the same --teacher_*_dir.
        self.teacher_fingerprint = _compute_teacher_fingerprint(model_path)
        self.cache_root = cache_dir
        if cache_dir:
            self.cache_dir = os.path.join(cache_dir, self.teacher_fingerprint)
            os.makedirs(self.cache_dir, exist_ok=True)
            # Drop a sidecar so the subdir is self-describing (which teacher made these files).
            try:
                manifest = os.path.join(self.cache_dir, "TEACHER_INFO.txt")
                if not os.path.isfile(manifest):
                    with open(manifest, "w") as f:
                        f.write(
                            f"fingerprint: {self.teacher_fingerprint}\n"
                            f"model_path:  {os.path.abspath(model_path)}\n"
                            f"class:       {self.__class__.__name__}\n"
                        )
            except Exception as e:
                logging.warning(f"[online_teacher] failed to write TEACHER_INFO.txt: {e}")
        else:
            self.cache_dir = None
        logging.info(
            f"[online_teacher] loaded {self.__class__.__name__} from {model_path} "
            f"on {device}; fingerprint={self.teacher_fingerprint}; "
            f"cache_dir={self.cache_dir or 'none'}"
        )

    def _cache_path(self, metadata):
        # Filename matches load_offline_tensor's expectation:
        #   f"{rep_type}_{alignment_layer}_{dataset_name}_{sample_id}.pt"
        info = f"{self.alignment_layer}_{metadata['dataset_name']}_{metadata['sample_id']}"
        if not self.cache_dir:
            return None, info
        return os.path.join(self.cache_dir, f"{self.rep_prefix}_{info}.pt"), info

    def _is_valid_teacher_tensor(self, tensor, metadata, source):
        if not torch.is_tensor(tensor):
            logging.warning(
                f"[online_teacher] invalid {source} teacher tensor for "
                f"{metadata.get('dataset_name')}/{metadata.get('sample_id')}: type={type(tensor)}"
            )
            return False
        if not torch.isfinite(tensor).all().item():
            logging.warning(
                f"[online_teacher] non-finite {source} teacher tensor for "
                f"{metadata.get('dataset_name')}/{metadata.get('sample_id')}; recomputing or failing fast"
            )
            return False
        return True

    def _try_load_cache(self, metadata):
        path, _ = self._cache_path(metadata)
        if not path or not os.path.isfile(path):
            return None
        try:
            data = torch.load(path, map_location="cpu")
        except Exception as e:
            logging.warning(f"[online_teacher] cache load failed for {path}: {e}")
            return None
        # Defense in depth: even with the fingerprinted subdir, refuse to use a file
        # whose embedded fingerprint disagrees (e.g., manually copied across teachers).
        cached_fp = data.get("teacher_fingerprint") if isinstance(data, dict) else None
        if cached_fp is not None and cached_fp != self.teacher_fingerprint:
            logging.warning(
                f"[online_teacher] cache fingerprint mismatch at {path} "
                f"(cached={cached_fp}, current={self.teacher_fingerprint}); recomputing"
            )
            return None
        if not isinstance(data, dict) or "latent" not in data:
            logging.warning(f"[online_teacher] malformed cache at {path}; recomputing")
            return None
        latent = data["latent"]
        if not self._is_valid_teacher_tensor(latent, metadata, f"cached file {path}"):
            return None
        return latent

    def _write_cache(self, metadata, tensor):
        path, info = self._cache_path(metadata)
        if not path:
            return
        if not self._is_valid_teacher_tensor(tensor, metadata, "generated"):
            logging.warning(f"[online_teacher] skip writing invalid cache for {info}")
            return
        tmp = f"{path}.tmp.{os.getpid()}"
        try:
            torch.save(
                {
                    "metadata_info": info,
                    "latent": tensor.detach().cpu(),
                    "teacher_fingerprint": self.teacher_fingerprint,
                },
                tmp,
            )
            os.replace(tmp, path)
        except Exception as e:
            logging.warning(f"[online_teacher] cache write failed for {path}: {e}")
            try:
                if os.path.isfile(tmp):
                    os.remove(tmp)
            except Exception:
                pass


class OnlineTeacherStage2(_OnlineTeacherBase):
    """Replaces offline Step 1: pool aux-image hidden states from a frozen base model."""

    rep_prefix = "rep"

    def __init__(self, *args, latent_size=8, **kwargs):
        super().__init__(*args, **kwargs)
        self.latent_size = int(latent_size)

    @torch.inference_mode()
    def __call__(self, inputs):
        """Returns list[CPU Tensor [L+1, N*latent_size, D]], matching load_offline_tensor."""
        B = inputs["teacher_input_ids"].size(0)
        results = [None] * B
        misses = []
        for b in range(B):
            cached = self._try_load_cache(inputs["metadata"][b])
            if cached is not None:
                results[b] = cached
            else:
                misses.append(b)

        if not misses:
            return results

        aux_blocks = inputs["teacher_aux_image_blocks"]

        fwd_inputs = {
            "input_ids": inputs["teacher_input_ids"].to(self.device, non_blocking=True),
            "attention_mask": inputs["teacher_attention_mask"].to(self.device, non_blocking=True),
            "pixel_values": inputs["teacher_pixel_values"].to(self.device, non_blocking=True),
            "image_grid_thw": inputs["teacher_image_grid_thw"].to(self.device, non_blocking=True),
            "output_hidden_states": True,
            "return_dict": True,
            "latent_mode": False,
            "labels": None,
            "loss_type": [],
            "alignment_poss": [[] for _ in range(B)],
        }
        outputs = self.model(**fwd_inputs)
        hidden_states = outputs.hidden_states

        for b in misses:
            blocks = aux_blocks[b]
            hs_sample = _per_sample_hidden_states(hidden_states, b, B)  # [L+1, T, D]
            # last_layer: pool only the last hidden state → output is 2D [N*latent_size, D].
            # all_layers: pool every layer → 3D [L+1, N*latent_size, D].
            if self.alignment_layer == "last_layer":
                hs_for_pool = hs_sample[-1:, :, :]  # [1, T, D]
            else:
                hs_for_pool = hs_sample  # [L+1, T, D]
            pooled_per_aux = []
            for idx in blocks or []:
                if idx.numel() == 0:
                    continue
                idx_dev = idx.to(hs_for_pool.device)
                h_aux = hs_for_pool[:, idx_dev, :].permute(0, 2, 1)  # [layers, D, T_aux]
                h_aux = F.adaptive_avg_pool1d(h_aux, self.latent_size)
                pooled_per_aux.append(h_aux.permute(0, 2, 1))        # [layers, latent_size, D]
            if pooled_per_aux:
                pooled = torch.cat(pooled_per_aux, dim=1)            # [layers, N*latent_size, D]
            else:
                pooled = torch.zeros(hs_for_pool.size(0), 0, hs_for_pool.size(-1),
                                     device=hs_for_pool.device)
            if self.alignment_layer == "last_layer":
                pooled = pooled.squeeze(0)                            # [N*latent_size, D]
            pooled_cpu = pooled.detach().cpu()
            if not self._is_valid_teacher_tensor(pooled_cpu, inputs["metadata"][b], "generated"):
                raise RuntimeError(f"[online_teacher] generated non-finite teacher reps for sample {b}")
            results[b] = pooled_cpu
            self._write_cache(inputs["metadata"][b], pooled_cpu)

        return results


class OnlineTeacherStage3(_OnlineTeacherBase):
    """Replaces offline Step 3: dump latent_mode-generated reps from a frozen Stage-2 ckpt."""

    rep_prefix = "latent"

    @torch.inference_mode()
    def __call__(self, inputs):
        """Returns list[CPU Tensor [L+1, N*latent_size, D]], matching load_offline_tensor."""
        B = inputs["teacher_input_ids"].size(0)
        results = [None] * B
        misses = []
        for b in range(B):
            cached = self._try_load_cache(inputs["metadata"][b])
            if cached is not None:
                results[b] = cached
            else:
                misses.append(b)

        if not misses:
            return results

        fwd_inputs = {
            "input_ids": inputs["teacher_input_ids"].to(self.device, non_blocking=True),
            "attention_mask": inputs["teacher_attention_mask"].to(self.device, non_blocking=True),
            "pixel_values": inputs["teacher_pixel_values"].to(self.device, non_blocking=True),
            "image_grid_thw": inputs["teacher_image_grid_thw"].to(self.device, non_blocking=True),
            "return_dict": True,
            "latent_mode": True,
            "labels": None,
            "loss_type": [],
        }
        if "teacher_attention_mask_4d" in inputs and inputs["teacher_attention_mask_4d"] is not None:
            fwd_inputs["attention_mask_4d"] = inputs["teacher_attention_mask_4d"]

        if self.alignment_layer == "last_layer":
            # Mirror precompute_teacher_latents.py with --output_latent_embeds:
            # the model returns outputs.latent_embeds[b] of shape [N*latent_size, D] (2D).
            # It needs alignment_poss = latent-pad positions in each teacher sample.
            abs_pad_id = int(self.special_token_ids["abs_pad"])
            teacher_input_ids_cpu = inputs["teacher_input_ids"]
            teacher_alignment_poss = [
                (teacher_input_ids_cpu[b] == abs_pad_id)
                .nonzero(as_tuple=False)
                .flatten()
                .tolist()
                for b in range(B)
            ]
            fwd_inputs["alignment_poss"] = teacher_alignment_poss
            fwd_inputs["output_latent_embeds"] = True
        else:
            fwd_inputs["output_hidden_states"] = True

        outputs = self.model(**fwd_inputs)
        if self.alignment_layer == "last_layer":
            teacher_reps = outputs.latent_embeds      # list[Tensor [N*latent_size, D]]
        else:
            teacher_reps = outputs.hidden_states      # list[Tensor [L+1, N*latent_size, D]]

        for b in misses:
            latent_b = teacher_reps[b].detach().cpu()
            if not self._is_valid_teacher_tensor(latent_b, inputs["metadata"][b], "generated"):
                raise RuntimeError(f"[online_teacher] generated non-finite teacher latents for sample {b}")
            results[b] = latent_b
            self._write_cache(inputs["metadata"][b], latent_b)

        return results