Download scripts/r5_vlmb/adapters/ad_youtu_parsing.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 14.7 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_vlmb/adapters/ad_youtu_parsing.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/scripts/r5_vlmb/adapters/ad_youtu_parsing.py
-
curl -L -o ad_youtu_parsing.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_vlmb/adapters/ad_youtu_parsing.py
14.7 kB
| """Adapter: tencent/Youtu-Parsing (maker code, pinned revision b82ee76cca8aa94ffd6451de38cd72aa8362f3c2). | |
| Written by stage VLMC (R5) in VLMB's adapter style. Own venv: torch 2.8.0+cu128, transformers 4.56.0 (the version in | |
| the repo's config.json), huggingface-hub < 1.0. The README's git-installed parser package and flash-attn wheels are | |
| not installed (flash-attn absent -> the maker code uses its eager paths). | |
| MODEL: SigLIP2-NaFlex vision transformer (27 layers, packed patches of all images with window attention and a global | |
| layer every 8th, 2D vision RoPE) -> 2x2 patch merger (RMSNorm + MLP) -> 32-layer decoder with multi-latent attention | |
| (DeepSeek-V2 style MLA) and dense MLPs; lm_head tied to the token embedding. Attention "eager" for both towers | |
| (the vision tower has only eager and flash-attention classes). | |
| INPUTS: the maker's YoutuVLProcessor + Siglip2ImageProcessorFast (its default call: max_image_patches 36864, no | |
| up-scaling, sides rounded up to 32 px, 16-px patches in 2x2 merge order). PROMPT: the repo chat template with one | |
| image + our instruction, generation prompt on ("<|begin_of_text|>system\\nYou are a helpful | |
| assistant.<|end_of_text|>\\n<|begin_of_text|>user\\n<|vision_start|><|image_pad|>...<|vision_end|>" + instruction + | |
| "<|end_of_text|>\\n<|begin_of_text|>assistant\\n"). Target = label tokens + <|end_of_text|> (id 128001, eos). | |
| FORWARD (own batching, maker modules): the maker's YoutuVLForConditionalGeneration.forward raises for batch size > 1 | |
| when images are given. The adapter runs the maker's own pieces on a batch: get_visiual_features (SigLIP2 + merger) | |
| once per image (exactly the maker's batch-1 vision call), outputs concatenated in image order, the image features | |
| scattered into the token embeddings at the | |
| image-pad positions in order (the maker's masked_scatter, generalised to several rows), then the maker's YoutuModel | |
| (decoder) with the padding mask, and lm_head on the target positions only. Loss = summed cross-entropy over target | |
| tokens (equal to common.target_loss_sum). check_equivalence compares these logits with the maker's own forward run | |
| one sample at a time (runs on CPU and GPU). | |
| GRADIENT CHECKPOINTING: the maker's decoder loop ignores its gradient_checkpointing flag, so the adapter wraps each | |
| decoder layer and each vision encoder layer in torch.utils.checkpoint (non-reentrant; same arithmetic). | |
| DECODING (own loop, same steps as the maker's decoder use): prefill with the image-merged embeddings on a | |
| DynamicCache, then one token per step through the maker's forward without pixel values, greedy argmax, stop at EOS | |
| or the token cap. DECODING IS BATCH 1 (21 Nov): generate() decodes one image at a time, so its output | |
| does not depend on the batch size. The left-padded batched loop (_generate_rows) gave a different word on 1 of 4 | |
| rows at batch 2 vs batch 1 in the CPU smoke ("жүрлен" vs "жүрген"); it is kept only as a helper. Images/s reported | |
| for this arm is therefore a batch-1 speed (the eval script still calls generate with up to 16 images). | |
| """ | |
| import sys | |
| import torch | |
| import torch.nn.functional as F | |
| from transformers import AutoModelForCausalLM, AutoProcessor | |
| from .common import INSTRUCTION, assert_no_token_env, autocast, master_dtype, remote_files_check | |
| EOS = 128001 | |
| class Adapter: | |
| NOTES = __doc__ | |
| def __init__(self, model_dir, device, precision): | |
| assert_no_token_env() | |
| remote_files_check(model_dir) | |
| self.device = device | |
| model, info = AutoModelForCausalLM.from_pretrained(model_dir, trust_remote_code=True, use_safetensors=True, | |
| torch_dtype=master_dtype(precision), | |
| attn_implementation="eager", output_loading_info=True) | |
| self.model = model | |
| bufs = {n for n, _ in model.named_buffers()} | |
| missing = list(info.get("missing_keys", [])) | |
| bad = [k for k in missing if k not in bufs and k != "lm_head.weight"] | |
| assert not bad, ("missing weights after load", bad[:10]) | |
| assert not info.get("mismatched_keys"), ("mismatched", info.get("mismatched_keys")[:5]) | |
| assert model.lm_head.weight is model.model.embed_tokens.weight, "lm_head not tied" | |
| self.mm = sys.modules[type(model).__module__] | |
| fixed = self._check_rope_buffers() | |
| self.load_info = {"missing_keys": missing, "unexpected_keys": list(info.get("unexpected_keys", []))[:20], | |
| "n_unexpected": len(info.get("unexpected_keys", [])), "rope_buffers_rebuilt": fixed, | |
| "vision_attn": type(model.siglip2.vision_model.encoder.layers[0].self_attn).__name__} | |
| print("[ad_youtu] load info", self.load_info, flush=True) | |
| self.NOTES = __doc__ + "\nload info: " + repr(self.load_info) | |
| self.model.to(device) | |
| self.proc = AutoProcessor.from_pretrained(model_dir, trust_remote_code=True) | |
| self.tok = self.proc.tokenizer | |
| assert self.tok.eos_token_id == EOS, self.tok.eos_token_id | |
| self.pad = self.tok.pad_token_id if self.tok.pad_token_id is not None else EOS | |
| self.image_token_id = model.config.image_token_id | |
| conv = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": INSTRUCTION}]}] | |
| self.prompt = self.proc.apply_chat_template(conv, add_generation_prompt=True, tokenize=False) | |
| assert self.prompt.count("<|image_pad|>") == 1, self.prompt | |
| def _check_rope_buffers(self): | |
| """Non-persistent rotary inv_freq buffers are recomputed with the maker's own formulas and replaced if the | |
| loaded values differ (guards against meta-device loading).""" | |
| fixed = [] | |
| rot = self.model.model.rotary_emb | |
| inv, _ = rot.rope_init_fn(rot.config, torch.device("cpu")) | |
| if not torch.equal(rot.inv_freq.detach().cpu().float(), inv.float()): | |
| rot.inv_freq = inv.to(rot.inv_freq.device) | |
| rot.original_inv_freq = rot.inv_freq | |
| fixed.append("model.rotary_emb.inv_freq") | |
| vr = self.model.siglip2.vision_model.encoder.rotary_pos_emb | |
| dim = vr.inv_freq.numel() * 2 | |
| inv2 = 1.0 / (10000.0 ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) | |
| if not torch.equal(vr.inv_freq.detach().cpu().float(), inv2): | |
| vr.inv_freq = inv2.to(vr.inv_freq.device) | |
| fixed.append("siglip2.vision_model.encoder.rotary_pos_emb.inv_freq") | |
| return fixed | |
| def enable_gradient_checkpointing(self): | |
| from torch.utils.checkpoint import checkpoint | |
| layers = list(self.model.model.layers) + list(self.model.siglip2.vision_model.encoder.layers) | |
| for blk in layers: | |
| if getattr(blk, "_vlmc_ckpt", False): | |
| continue | |
| orig = blk.forward | |
| def fwd(*a, _orig=orig, _blk=blk, **kw): | |
| if _blk.training and torch.is_grad_enabled(): | |
| return checkpoint(_orig, *a, use_reentrant=False, **kw) | |
| return _orig(*a, **kw) | |
| blk.forward = fwd | |
| blk._vlmc_ckpt = True | |
| def target_ids(self, text): | |
| return (self.tok.encode(text, add_special_tokens=False) if text else []) + [EOS] | |
| def _one(self, image): | |
| enc = self.proc(text=[self.prompt], images=[image], return_tensors="pt") | |
| return (torch.as_tensor(enc["input_ids"])[0].tolist(), torch.as_tensor(enc["pixel_values"])[0], | |
| torch.as_tensor(enc["spatial_shapes"])) | |
| def _vision(self, E): | |
| """The maker's get_visiual_features once per image (its eager vision attention materialises a full mask over | |
| the packed sequence, so packing many images would cost memory quadratic in the total), outputs concatenated | |
| in image order.""" | |
| d = self.device | |
| dt = self.model.siglip2.dtype | |
| feats = [] | |
| for e in E: | |
| pv = e[1][None].to(d, dt) | |
| pm = torch.ones(pv.shape[:2], dtype=torch.int32, device=d) | |
| feats.append(self.model.get_visiual_features(pv, pm, e[2].to(d))) | |
| return torch.cat(feats, dim=0) | |
| def _batch(self, images, texts): | |
| E = [self._one(im) for im in images] | |
| seqs, labs = [], [] | |
| for e, tx in zip(E, texts): | |
| tgt = self.target_ids(tx) | |
| seqs.append(e[0] + tgt) | |
| labs.append([-100] * len(e[0]) + tgt) | |
| B, L = len(seqs), max(len(s) for s in seqs) | |
| inp = torch.full((B, L), self.pad, dtype=torch.long) | |
| 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]) | |
| lab[i, :n] = torch.tensor(labs[i]) | |
| am[i, :n] = 1 | |
| return E, inp.to(self.device), am.to(self.device), lab | |
| def _hidden(self, images, texts): | |
| E, inp, am, lab = self._batch(images, texts) | |
| emb = self.model.get_input_idx_embeddings(inp) | |
| feats = self._vision(E) | |
| mask = (inp == self.image_token_id) | |
| assert int(mask.sum()) == feats.shape[0], (int(mask.sum()), feats.shape) | |
| emb = emb.masked_scatter(mask[..., None].expand_as(emb), feats.to(emb.dtype)) | |
| out = self.model.model(input_ids=None, inputs_embeds=emb, attention_mask=am, use_cache=False) | |
| return out.last_hidden_state, lab, (E, inp, am) | |
| def loss(self, images, texts): | |
| with autocast(self.device): | |
| h, lab, _ = self._hidden(images, texts) | |
| lb = lab[:, 1:].to(h.device) | |
| sel = lb != -100 | |
| lg = self.model.lm_head(h[:, :-1][sel]) | |
| return F.cross_entropy(lg.float(), lb[sel], reduction="sum"), int(sel.sum()) | |
| def check_equivalence(self, images, texts): | |
| """Target-position logits of the adapter's batched forward vs the maker's own forward, one sample at a time.""" | |
| was = self.model.training | |
| self.model.eval() | |
| d = self.device | |
| with autocast(d): | |
| h, lab, (E, inp, am) = self._hidden(images, texts) | |
| lb = lab[:, 1:] | |
| mine, ref = [], [] | |
| for i, e in enumerate(E): | |
| n = int(am[i].sum()) | |
| sel = (lb[i, :n - 1] != -100).to(d) | |
| mine.append(self.model.lm_head(h[i, :n - 1][sel]).float()) | |
| pv = e[1][None].to(d, self.model.siglip2.dtype) | |
| out = self.model(input_ids=inp[i:i + 1, :n], attention_mask=am[i:i + 1, :n], pixel_values=pv, | |
| pixel_attention_mask=torch.ones(pv.shape[:2], dtype=torch.int32, device=d), | |
| spatial_shapes=e[2].to(d), use_cache=False) | |
| ref.append(out.logits[0, :n - 1][sel].float()) | |
| mine, ref = torch.cat(mine), torch.cat(ref) | |
| self.model.train(was) | |
| return {"max_abs_logit_diff_on_targets": float((mine - ref).abs().max()), | |
| "argmax_agreement_on_targets": float((mine.argmax(-1) == ref.argmax(-1)).float().mean())} | |
| def prepare_eval(self): | |
| self.model.eval() | |
| self.model.to(torch.bfloat16) | |
| def generate(self, images, max_new_tokens, temperature=None): | |
| """Batch-1 greedy decoding: one image per decoder call, so the output is the same at any eval batch size. | |
| With a temperature (cap-retry rule, VLMC 21 Nov): the same loop samples from softmax(logits / T) (no top-k or | |
| top-p cut; torch seeded per set by the eval script) and returns records saying whether EOS was emitted.""" | |
| outs = [] | |
| for im in images: | |
| outs += self._generate_rows([im], max_new_tokens, temperature) | |
| return outs | |
| def _generate_rows(self, images, max_new_tokens, temperature=None): | |
| """Batched greedy decoding with left padding: prefill on the image-merged embeddings with the padding mask | |
| and position ids counted over real tokens only, then one token per step for every row through the maker's | |
| forward (no pixel values), finished rows fed EOS and ignored. Not used for results (see the module note).""" | |
| from transformers.cache_utils import DynamicCache | |
| d = self.device | |
| E = [self._one(im) for im in images] | |
| B, L = len(E), max(len(e[0]) for e in E) | |
| inp = torch.full((B, L), self.pad, dtype=torch.long) | |
| am = torch.zeros((B, L), dtype=torch.long) | |
| for i, e in enumerate(E): | |
| n = len(e[0]) | |
| inp[i, L - n:] = torch.tensor(e[0]) | |
| am[i, L - n:] = 1 | |
| inp, am = inp.to(d), am.to(d) | |
| with autocast(d): | |
| emb = self.model.get_input_idx_embeddings(inp) | |
| feats = self._vision(E) | |
| mask = (inp == self.image_token_id)[..., None].expand_as(emb) | |
| emb = emb.masked_scatter(mask, feats.to(emb.dtype)) | |
| pos = (am.cumsum(-1) - 1).clamp(min=0) | |
| out = self.model(input_ids=None, inputs_embeds=emb, attention_mask=am, position_ids=pos, | |
| past_key_values=DynamicCache(), use_cache=True) | |
| last = pos[:, -1] | |
| done = torch.zeros(B, dtype=torch.bool, device=d) | |
| gen = [] | |
| for _ in range(max_new_tokens): | |
| if temperature is None: | |
| nxt = out.logits[:, -1].float().argmax(-1) | |
| else: | |
| nxt = torch.multinomial(torch.softmax(out.logits[:, -1].float() / float(temperature), dim=-1), 1)[:, 0] | |
| nxt = torch.where(done, torch.full_like(nxt, EOS), nxt) | |
| gen.append(nxt) | |
| done = done | (nxt == EOS) | |
| if bool(done.all()): | |
| break | |
| am = torch.cat([am, torch.ones((B, 1), dtype=am.dtype, device=d)], dim=1) | |
| last = last + 1 | |
| out = self.model(input_ids=nxt[:, None], attention_mask=am, position_ids=last[:, None], | |
| past_key_values=out.past_key_values, use_cache=True) | |
| self.model.first_logits = None | |
| rows = torch.stack(gen, dim=1).tolist() if gen else [[] for _ in range(B)] | |
| outs = [] | |
| for row in rows: | |
| toks = [] | |
| for t in row: | |
| if t == EOS: | |
| break | |
| toks.append(t) | |
| text = self.tok.decode(toks, skip_special_tokens=True, clean_up_tokenization_spaces=False) | |
| if temperature is None: | |
| outs.append(text) | |
| else: | |
| eos = EOS in row | |
| outs.append({"raw": text, "n_new": len(toks), "hit_cap": not eos, "eos": eos, "conf": None, | |
| "conf_min": None, "stop_source": "adapter: own decode loop"}) | |
| return outs | |