"""Adapter: deepseek-ai/DeepSeek-OCR-2 (maker code, pinned revision aaa02f3811945a91062062994c5c4a3f4c0af2b0). Runs in its own venv with transformers 4.46.3 and torch 2.6.0, the versions the model card names. INPUTS: the same steps as the maker's infer() with the card's settings (base_size 1024, image_size 768, crop_mode True): prompt "\\n" + our instruction in the "plain" template, BOS id 0, 256+1 image tokens for the global view (ImageOps.pad to 1024x1024 with grey 127), plus 144 per 768x768 tile when a side exceeds 768 (the maker's dynamic_preprocess, 2 to 6 tiles). Target = label tokens + <|end▁of▁sentence|> (tokenizer eos, id 1). LOSS WRAPPER (own code): the maker's DeepseekOCR2Model.forward runs the whole image branch under torch.no_grad() (and calls .cuda() and print()), so the maker's forward cannot train the vision encoder. The adapter repeats the same image branch WITH gradients: SAM ViT-B -> Qwen2 decoder-as-encoder -> linear projector, features ordered [tiles, global view, view separator] exactly as the maker, scattered into the token embeddings at the image positions; then the maker's DeepseekV2Model.forward on inputs_embeds and the maker's lm_head; loss = token-mean cross-entropy over target tokens. Global views of the micro-batch go through the encoder as one batch (the encoders treat images independently, so this equals one-by-one). The MoE layers add the maker's auxiliary load-balancing gradient (alpha 0.001, AddAuxiliaryLoss) as in the maker's training branch. AMP CAST: under bf16 autocast with fp32 master weights, the maker's MoE training branch writes bf16 expert outputs into an fp32 buffer and fails; the MoE input is cast to bf16 under autocast (the experts run in bf16 under autocast anyway, so the arithmetic is the same). ATTENTION: "eager" (the maker's ATTENTION_CLASSES has no sdpa entry; flash-attn not installed). DECODING: the maker's generate() path (its forward injects the image features on the first step), greedy, no no_repeat_ngram constraint (infer() uses 20 or 35; our protocol is plain greedy for every arm). """ import math import sys import torch from PIL import ImageOps from transformers import AutoModel, AutoTokenizer from .common import INSTRUCTION, assert_no_token_env, autocast, target_loss_sum, master_dtype, remote_files_check IMAGE_TOKEN_ID = 128815 # hard-coded in the maker's infer() class Adapter: NOTES = __doc__ BASE, TILE, PATCH, DOWN = 1024, 768, 16, 4 def __init__(self, model_dir, device, precision): assert_no_token_env() remote_files_check(model_dir) self.device = device self.model = AutoModel.from_pretrained(model_dir, trust_remote_code=True, use_safetensors=True, torch_dtype=master_dtype(precision), attn_implementation="eager") self.model.to(device) self.tok = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True) self.mm = sys.modules[type(self.model).__module__] pkg = type(self.model).__module__.rsplit(".", 1)[0] self.mv2 = sys.modules[pkg + ".modeling_deepseekv2"] self._patch_moe() self.eos = self.tok.eos_token_id assert self.eos == 1, self.eos self.pad = self.tok.pad_token_id if self.tok.pad_token_id is not None else self.eos conv = [{"role": "<|User|>", "content": "\n" + INSTRUCTION}, {"role": "<|Assistant|>", "content": ""}] self.prompt = self.mm.format_messages(conversations=conv, sft_format="plain", system_prompt="") self.tf = self.mm.BasicImageTransform(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), normalize=True) def _patch_moe(self): moe = self.mv2.DeepseekV2MoE if getattr(moe, "_vlmb_patched", False): return orig = moe.forward def fwd(self_, hidden_states): if torch.is_autocast_enabled() and hidden_states.dtype == torch.float32: return orig(self_, hidden_states.to(torch.bfloat16)) return orig(self_, hidden_states) moe.forward = fwd moe._vlmb_patched = True def enable_gradient_checkpointing(self): """LLM and the Qwen2 decoder-as-encoder through transformers; the SAM blocks (not a transformers module) through a wrapper here: each block's forward is recomputed in backward (same arithmetic, less memory).""" self.model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False}) from torch.utils.checkpoint import checkpoint for blk in self.model.model.sam_model.blocks: if getattr(blk, "_vlmb_ckpt", False): continue orig = blk.forward def fwd(x, _orig=orig, _blk=blk): if _blk.training and torch.is_grad_enabled(): return checkpoint(_orig, x, use_reentrant=False) return _orig(x) blk.forward = fwd blk._vlmb_ckpt = True # ---- the maker's infer() preprocessing, one image ------------------------------------------------------------ def _prep(self, image): mm, tok = self.mm, self.tok splits = self.prompt.split("") ids, mask = [], [] sep = mm.text_encode(tok, splits[0], bos=False, eos=False) ids += sep mask += [False] * len(sep) crops = [] if image.size[0] <= self.TILE and image.size[1] <= self.TILE: ratio = [1, 1] else: raw, ratio = mm.dynamic_preprocess(image) crops = [self.tf(c).to(torch.bfloat16) for c in raw] gv = ImageOps.pad(image, (self.BASE, self.BASE), color=tuple(int(x * 255) for x in self.tf.mean)) ori = self.tf(gv).to(torch.bfloat16) w, h = ratio nq = math.ceil((self.TILE // self.PATCH) / self.DOWN) nqb = math.ceil((self.BASE // self.PATCH) / self.DOWN) timg = [IMAGE_TOKEN_ID] * (nqb * nqb) + [IMAGE_TOKEN_ID] if w > 1 or h > 1: timg += [IMAGE_TOKEN_ID] * ((nq * w) * (nq * h)) ids += timg mask += [True] * len(timg) sep = mm.text_encode(tok, splits[-1], bos=False, eos=False) ids += sep mask += [False] * len(sep) ids = [0] + ids mask = [False] + mask crop_t = torch.stack(crops) if crops else torch.zeros((1, 3, self.BASE, self.BASE)) return ids, mask, crop_t, ori[None], [w, h], len(crops) # ---- training forward ------------------------------------------------------------------------------------------ def _image_features(self, oris, crop_list): m = self.model.model d = self.device g = m.projector(m.qwen2_model(m.sam_model(torch.cat(oris).to(d)))) # (B, 256, 1280) loc = None ncs = [c.shape[0] if n else 0 for c, n in crop_list] if sum(ncs): allc = torch.cat([c for c, n in crop_list if n]).to(d) loc = m.projector(m.qwen2_model(m.sam_model(allc))) # (sum n, 144, 1280) feats, k = [], 0 for b, n in enumerate(ncs): parts = [] if n: parts.append(loc[k:k + n].reshape(-1, loc.shape[-1])) k += n parts.append(g[b].reshape(-1, g.shape[-1])) parts.append(m.view_seperator[None, :].to(g.dtype)) feats.append(torch.cat(parts, dim=0)) return feats def _batch(self, images, texts=None): P = [self._prep(im) for im in images] seqs, masks, labs = [], [], [] for i, (ids, mask, _, _, _, _) in enumerate(P): if texts is not None: tgt = self.target_ids(texts[i]) seqs.append(ids + tgt) masks.append(mask + [False] * len(tgt)) labs.append([-100] * len(ids) + tgt) else: seqs.append(ids) masks.append(mask) return P, seqs, masks, labs def logits(self, images, texts): P, seqs, masks, labs = self._batch(images, texts) B, L = len(seqs), max(len(s) for s in seqs) inp = torch.full((B, L), self.pad, dtype=torch.long) msk = torch.zeros((B, L), dtype=torch.bool) lab = torch.full((B, L), -100, dtype=torch.long) am = torch.zeros((B, L), dtype=torch.long) for i in range(B): n = len(seqs[i]) inp[i, :n] = torch.tensor(seqs[i]) msk[i, :n] = torch.tensor(masks[i]) lab[i, :n] = torch.tensor(labs[i]) am[i, :n] = 1 d = self.device m = self.model.model emb = m.get_input_embeddings()(inp.to(d)) feats = self._image_features([p[3] for p in P], [(p[2], p[5]) for p in P]) rows = [] for i in range(B): mi = msk[i].to(d) assert int(mi.sum()) == feats[i].shape[0], (int(mi.sum()), feats[i].shape) rows.append(emb[i].masked_scatter(mi[:, None], feats[i].to(emb.dtype))) emb = torch.stack(rows) out = self.mm.DeepseekV2Model.forward(m, input_ids=None, attention_mask=am.to(d), inputs_embeds=emb, use_cache=False, return_dict=True) return self.model.lm_head(out.last_hidden_state), lab, (inp, msk, am, P) def target_ids(self, text): return (self.tok.encode(text, add_special_tokens=False) if text else []) + [self.eos] def loss(self, images, texts): with autocast(self.device): lg, lab, _ = self.logits(images, texts) return target_loss_sum(lg, lab) @torch.no_grad() def check_equivalence(self, images, texts): """Logits of the adapter's forward vs the maker's DeepseekOCR2ForCausalLM.forward (GPU only: .cuda()).""" if self.device.type != "cuda": return "skipped on CPU: the maker's forward calls .cuda(); runs at the start of the GPU task" was = self.model.training self.model.eval() with autocast(self.device): mine, lab, (inp, msk, am, P) = self.logits(images, texts) imgs = [(p[2].to(self.device), p[3].to(self.device)) for p in P] sc = torch.tensor([p[4] for p in P], dtype=torch.long) ref = self.model(input_ids=inp.to(self.device), attention_mask=am.to(self.device), images=imgs, images_seq_mask=msk.to(self.device), images_spatial_crop=sc, use_cache=False).logits sel = lab.to(self.device) != -100 mine, ref = mine.float(), ref.float() self.model.train(was) return {"max_abs_logit_diff_on_targets": float((mine - ref).abs()[sel].max()), "argmax_agreement_on_targets": float((mine.argmax(-1) == ref.argmax(-1))[sel].float().mean())} # ---- decoding ---------------------------------------------------------------------------------------------------- def prepare_eval(self): self.model.eval() self.model.to(torch.bfloat16) @torch.inference_mode() def generate(self, images, max_new_tokens, temperature=None): """temperature=None: greedy, unchanged. Else the cap-retry sampling path (VLMC, 21 Nov; common.retry_sampling).""" from .common import retry_sampling, stop_records P, seqs, masks, _ = self._batch(images) B, L = len(seqs), max(len(s) for s in seqs) inp = torch.full((B, L), self.pad, dtype=torch.long) msk = torch.zeros((B, L), dtype=torch.bool) am = torch.zeros((B, L), dtype=torch.long) for i in range(B): n = len(seqs[i]) inp[i, L - n:] = torch.tensor(seqs[i]) msk[i, L - n:] = torch.tensor(masks[i]) am[i, L - n:] = 1 d = self.device imgs = [(p[2].to(d), p[3].to(d)) for p in P] sc = torch.tensor([p[4] for p in P], dtype=torch.long) gk = dict(max_new_tokens=max_new_tokens, do_sample=False, num_beams=1, eos_token_id=self.eos, pad_token_id=self.pad, use_cache=True, repetition_penalty=1.0, no_repeat_ngram_size=0) if temperature is not None: gk.update(retry_sampling(temperature)) with autocast(d): out = self.model.generate(inp.to(d), attention_mask=am.to(d), images=imgs, images_seq_mask=msk.to(d), images_spatial_crop=sc, **gk) if temperature is not None: return stop_records(self.tok, out[:, L:], self.eos) return self.tok.batch_decode(out[:, L:], skip_special_tokens=True, clean_up_tokenization_spaces=False)