Download scripts/r5_onemodel/om_probe.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 7.76 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_onemodel/om_probe.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/scripts/r5_onemodel/om_probe.py
-
curl -L -o om_probe.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_onemodel/om_probe.py
7.76 kB
| """ONEMODEL pilot (design ONEMODEL-pilot-1), CPU smoke part 1: check the spotting facts against the leader's own tokenizer and | |
| processor, and time one full-size page sample against one crop sample (forward + backward) for the GPU-hour estimate. | |
| Checks: location tokens <|LOC_0|>..<|LOC_1000|> are single ids 100297..101297 and are not special; '\\n' is one id; a real | |
| target tokenizes and decodes back exactly; the rendered page prompt is the leader's chat template with 'Spotting:'; a | |
| pre-resized page reaches the model unresized through the page processor kwargs (image_grid_thw), while the default processor | |
| call would shrink it to <= 1,003,520 pixels; a crop gets the same grid through the crop path as the leader's | |
| vlm_common.prompt_batch; transformers.image_utils.load_image source (EXIF handling) is recorded. | |
| Timing: bf16 on CPU with gradient checkpointing; each sample timed twice, the second time is kept. | |
| usage: om_probe.py --out JSON [--threads 32] | |
| """ | |
| import argparse | |
| import inspect | |
| import json | |
| import os | |
| import sys | |
| import time | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, HERE) | |
| import om_common as C # noqa: E402 | |
| import om_text as T # noqa: E402 | |
| import torch # noqa: E402 | |
| import transformers # noqa: E402 | |
| from PIL import Image # noqa: E402 | |
| vc = C.vc | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--out", required=True) | |
| ap.add_argument("--threads", type=int, default=32) | |
| ap.add_argument("--data-root", default=C.DATA + "/data/processed/r6_onemodel") | |
| ap.add_argument("--no-timing", action="store_true") | |
| a = ap.parse_args() | |
| torch.set_num_threads(a.threads) | |
| rep = {"design": T.DESIGN_ID, "transformers": transformers.__version__, "torch": torch.__version__} | |
| proc, tok, model = C.load(C.LEADER) | |
| tmpl_kw = vc.template_kwargs(proc, tok) | |
| rep["processor_class"] = type(proc).__name__ | |
| rep["image_processor_class"] = type(proc.image_processor).__name__ | |
| rep["image_processor_size_default"] = dict(proc.image_processor.size) if hasattr(proc.image_processor.size, "keys") else str(proc.image_processor.size) | |
| # tokenizer facts | |
| ids = tok.convert_tokens_to_ids(["<|LOC_0|>", "<|LOC_500|>", "<|LOC_1000|>"]) | |
| rep["loc_ids"] = ids | |
| rep["loc_single_ids"] = [tok("<|LOC_%d|>" % n, add_special_tokens=False).input_ids for n in (0, 500, 1000)] | |
| rep["loc_special"] = [bool(getattr(tok.added_tokens_decoder.get(i), "special", None)) for i in ids] | |
| rep["newline_ids"] = tok("\n", add_special_tokens=False).input_ids | |
| rec = json.loads(open(os.path.join(a.data_root, "records", "gen_val.jsonl"), encoding="utf-8").readline()) | |
| tid = tok(rec["target"], add_special_tokens=False).input_ids | |
| rep["target_roundtrip"] = {"id": rec["id"], "ids_equal_record": tid + [2] == rec["target_ids"], | |
| "decode_equal": tok.decode(tid, skip_special_tokens=False, clean_up_tokenization_spaces=False) == rec["target"], | |
| "decode_skip_special_keeps_loc": "<|LOC_" in tok.decode(tid, skip_special_tokens=True), | |
| "first_ids": tid[:20], "first_tokens": tok.convert_ids_to_tokens(tid[:20])} | |
| rep["rendered_page_prompt"] = proc.apply_chat_template([{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": T.SPOT_PROMPT}]}], | |
| add_generation_prompt=True, tokenize=False, **tmpl_kw) | |
| rep["rendered_crop_prompt"] = vc.rendered_prompt(C.SHORT, proc, tmpl_kw) | |
| suffix = vc.answer_suffix(C.SHORT, proc, tok, model.generation_config, tmpl_kw) | |
| rep["answer_suffix"] = {"ids": suffix[0], "how": suffix[1], "text": suffix[2]} | |
| # processor: page and crop grids | |
| page = Image.open(rec["image"]).convert("RGB") | |
| enc_p = C.page_prompt_batch(proc, [page], tmpl_kw) | |
| C.check_page_grids(enc_p, [page]) | |
| enc_def = proc.apply_chat_template([[{"role": "user", "content": [{"type": "image", "image": page}, {"type": "text", "text": T.SPOT_PROMPT}]}]], | |
| add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", padding=True) | |
| n_img = int((enc_p["input_ids"][0] == model.config.image_token_id).sum()) | |
| rep["page_grid"] = {"image": list(page.size), "grid_with_page_kwargs": enc_p["image_grid_thw"][0].tolist(), | |
| "visual_tokens_with_page_kwargs": n_img, "grid_default_call": enc_def["image_grid_thw"][0].tolist(), | |
| "page_unresized": enc_p["image_grid_thw"][0].tolist() == [1, page.size[1] // 14, page.size[0] // 14]} | |
| crop_rows = [] | |
| with open(os.path.join(a.data_root, "seq", "crop_seq.tsv"), encoding="utf-8") as f: | |
| hdr = f.readline().rstrip("\n").split("\t") | |
| ix = {h: i for i, h in enumerate(hdr)} | |
| for line in f: | |
| p_ = line.rstrip("\n").split("\t") | |
| crop_rows.append({"id": p_[ix["id"]], "image": p_[ix["image"]], "text": p_[ix["text"]]}) | |
| if len(crop_rows) >= 16: | |
| break | |
| crop_row = [r for r in crop_rows if r["text"]][0] | |
| crop = Image.open(crop_row["image"]).convert("RGB") | |
| crops16 = [Image.open(r["image"]).convert("RGB") for r in crop_rows] | |
| enc_c_leader = vc.prompt_batch(C.SHORT, proc, [crop], tmpl_kw) | |
| rep["crop_grid"] = {"id": crop_row["id"], "image": list(crop.size), "grid_leader_path": enc_c_leader["image_grid_thw"][0].tolist()} | |
| try: | |
| from transformers import image_utils | |
| src = inspect.getsource(image_utils.load_image) | |
| rep["load_image_mentions_exif_transpose"] = "exif_transpose" in src | |
| except Exception as e: # noqa: BLE001 | |
| rep["load_image_source"] = repr(e)[:200] | |
| # timing: one full page sample vs one crop sample, forward + backward, bf16, gradient checkpointing | |
| if not a.no_timing: | |
| model.config.use_cache = False | |
| model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False}) | |
| model.train() | |
| for p_ in model.parameters(): | |
| p_.requires_grad_(True) | |
| trp = {} | |
| for s in ("gen_train", "school_train"): | |
| r_ = json.loads(open(os.path.join(a.data_root, "records", s + ".jsonl"), encoding="utf-8").readline()) | |
| trp[s] = (Image.open(r_["image"]).convert("RGB"), r_["target_ids"], r_["id"]) | |
| def one(kind): | |
| if kind in trp: | |
| im_, tg_, _ = trp[kind] | |
| inp, lab = C.page_train_batch(proc, tok, [im_], [tg_], tmpl_kw) | |
| else: | |
| inp, lab, _ = vc.build_train_batch(C.SHORT, proc, tok, crops16, [r["text"] for r in crop_rows], suffix[0], tmpl_kw) | |
| t0 = time.time() | |
| out = model(**C.to_dev(inp, "cpu"), use_cache=False) | |
| ls, nt = vc.target_loss_sum(out.logits, lab) | |
| (ls / max(nt, 1)).backward() | |
| dt = time.time() - t0 | |
| model.zero_grad(set_to_none=True) | |
| return dt, list(inp["input_ids"].shape), nt, int((inp["input_ids"] == model.config.image_token_id).sum()) | |
| tm = {} | |
| one("crop") # warm-up | |
| for kind in ("crop", "gen_train", "school_train"): | |
| tm[kind] = one(kind) | |
| per_crop = tm["crop"][0] / len(crop_rows) | |
| tt = {"crop_microbatch16_seconds": round(tm["crop"][0], 3), "crop_input_shape": tm["crop"][1], "crop_target_tokens": tm["crop"][2], | |
| "crop_visual_tokens_total": tm["crop"][3], "threads": a.threads, | |
| "note": "forward + backward with gradient checkpointing, bf16 on CPU, after one warm-up crop micro-batch; the first record of " | |
| "gen_train and of school_train at full size (u = 1) vs the first 16 crops of crop_seq"} | |
| for s in ("gen_train", "school_train"): | |
| tt[s] = {"id": trp[s][2], "seconds": round(tm[s][0], 2), "input_shape": tm[s][1], "target_tokens": tm[s][2], | |
| "visual_tokens": tm[s][3], "ratio_one_page_over_one_crop": round(tm[s][0] / per_crop, 2)} | |
| rep["timing_cpu_bf16"] = tt | |
| json.dump(rep, open(a.out, "w"), indent=1, ensure_ascii=False) | |
| print(json.dumps(rep, ensure_ascii=False, indent=1)[:4000]) | |