diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..7b443eb52aead321c45020b7a3760cc808f9fb9d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,12 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +DejaVuSans.ttf filter=lfs diff=lfs merge=lfs -text +examples/19a1b2195bab_right_0/region.png filter=lfs diff=lfs merge=lfs -text +examples/35ffe6b8b600_left_0/region.png filter=lfs diff=lfs merge=lfs -text +examples/38c4ce6331ad_left_1/region.png filter=lfs diff=lfs merge=lfs -text +examples/8d24e7df7dea_2/region.png filter=lfs diff=lfs merge=lfs -text +examples/eed569a6699c_left_3/line_07.jpg filter=lfs diff=lfs merge=lfs -text +examples/eed569a6699c_left_3/line_08.jpg filter=lfs diff=lfs merge=lfs -text +examples/eed569a6699c_left_3/region.png filter=lfs diff=lfs merge=lfs -text +examples/f970d28ac08b_left_0/region.png filter=lfs diff=lfs merge=lfs -text diff --git a/.ruff_cache/.gitignore b/.ruff_cache/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b100327770759f0efb7859fe78aca4801d69ed61 --- /dev/null +++ b/.ruff_cache/.gitignore @@ -0,0 +1,2 @@ +# Automatically created by ruff. +* diff --git a/.ruff_cache/0.17.4/10670050264457222690 b/.ruff_cache/0.17.4/10670050264457222690 new file mode 100644 index 0000000000000000000000000000000000000000..a90c429b5bf1bbca629e760913cdbe2ea91cd8fa Binary files /dev/null and b/.ruff_cache/0.17.4/10670050264457222690 differ diff --git a/.ruff_cache/0.17.4/8792248902311164429 b/.ruff_cache/0.17.4/8792248902311164429 new file mode 100644 index 0000000000000000000000000000000000000000..e359084563379b0dafe85492b9337f2b23e5d6ec Binary files /dev/null and b/.ruff_cache/0.17.4/8792248902311164429 differ diff --git a/.ruff_cache/CACHEDIR.TAG b/.ruff_cache/CACHEDIR.TAG new file mode 100644 index 0000000000000000000000000000000000000000..bc1ecb967a482524e7736038de0df6e08f9ee452 --- /dev/null +++ b/.ruff_cache/CACHEDIR.TAG @@ -0,0 +1 @@ +Signature: 8a477f597d28d172789f06886806bc55 \ No newline at end of file diff --git a/DejaVuSans.ttf b/DejaVuSans.ttf new file mode 100644 index 0000000000000000000000000000000000000000..c6e19bb61692c7347365b0d3e60c17f6c8980fa8 --- /dev/null +++ b/DejaVuSans.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ae7b7855e115a5966d8b1b3f80f254ccc117ec86f9965e202ee2940453837280 +size 759720 diff --git a/HOW_IT_WORKS.md b/HOW_IT_WORKS.md new file mode 100644 index 0000000000000000000000000000000000000000..85ebe711e9b36489367122791ea3ec6b31c91409 --- /dev/null +++ b/HOW_IT_WORKS.md @@ -0,0 +1,57 @@ +### What is timed + +Each reader is timed from the images to the text, preprocessing included, on the same GPU (ZeroGPU: half an RTX PRO +6000 Blackwell), after a warm-up that is not timed: + +- **Swedish Lion TrOCR** (Riksarkivet's Swedish Lion Libre 2026, large, character-based) reads the region's lines, + all in one batch, greedily, in float32 as Riksarkivet runs it. +- **MiniCPM-OCR reader alone** reads the whole region in one request, one token per pass, greedily. +- **Reader + DSpark draft**: the draft proposes 15 tokens at a time; the reader checks them in one pass and keeps the + ones it agrees with, plus one of its own. Greedy decoding, so the text is the reader's own. + +### Why the draft makes it faster + +Decoding one token at a time reads every weight of the reader for each token. A check of 16 tokens costs about the +same pass, and the reader keeps on average about 8 of them (the acceptance length). The draft is small (5 layers) and +reads the reader's own hidden states, so its guesses are cheap and usually right. It helps most when one region is +read at a time and its text is long; reading many requests at once keeps the GPU busy anyway. + +### How it runs here + +vLLM runs the draft natively, but vLLM cannot run on ZeroGPU, so this Space decodes in PyTorch. Profiled with +`torch.profiler`, eager decoding was launch-bound (about 1,500 small kernels a pass, the GPU busy 12 % of the time), so: + +1. Each reader pass is replayed from a **CUDA graph** (transformers' StaticCache, the attention mask built on the GPU), + for the reader alone and with the draft alike. +2. The draft's whole proposal, its Markov sampling included, is **one graph**. +3. **One reader pass per draft block.** The reader is hybrid: its linear-attention layers keep a recurrent state that + cannot be cut back after rejected guesses. The checking pass keeps each such layer's inputs for the block, and the + state is rebuilt over the accepted tokens only (a few kernels instead of a second pass). + +Measured on our server (12 dev regions, a full RTX PRO 6000 shared with a training run): the reader alone 31.5 s, +with DSpark 6.8 s (**4.6×**); the eager reader alone, before these changes, about 2× slower than the first. + +### The same models in vLLM + +On 1,000 test lines and 200 dev regions, one GPU per server (the draft's model card): + +| | one at a time | 64 at a time | +|---|---|---| +| lines: reader alone → with DSpark | 13.3 → 18.2 lines/s (1.37×) | 74.6 → 82.2 lines/s (1.10×) | +| regions: reader alone → with DSpark | 1.95 → 4.08 regions/s (2.09×) | 12.4 → 13.2 regions/s (1.07×) | + +Acceptance length 8.72; the character error rate is the same with and without the draft. + +### Jev + +Jev compares the line image with the candidate text drawn as an image (`@RENDERER@`) and returns a score from 0 to 1. +On 2,000 test pairs, the original MiniCPM-OCR-Jev scores an AUROC of 0.594 and ours 0.870 (accuracy 78.6 % at its best +threshold). Picking, line by line, the reading Jev scores higher is one way to combine two readers. + +### Limits + +- The examples are from GT-Lejonet's dev volumes; other hands and periods read worse. +- Near-greedy decoding can repeat a phrase to the token limit on dense pages (a loop); such a reading is wrong from + where it starts. +- Timings vary with the GPU slice and the queue; the first request of a fresh worker captures its CUDA graphs first + (not counted in the timings shown). diff --git a/README.md b/README.md index dcc0feb8258afe9b7d8f406db1c25fc47eace346..cade02bbd50290c258c3c7b55777f954d0dbbf7e 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,28 @@ --- -title: Diffu Htr Speed -emoji: 📊 +title: Swedish HTR speed and Jev +emoji: 🪶 colorFrom: green -colorTo: green +colorTo: gray sdk: gradio sdk_version: 6.31.0 -python_version: '3.12' app_file: app.py -pinned: false +python_version: "3.12" +short_description: TrOCR vs MiniCPM-OCR with a DSpark draft, and Jev +license: apache-2.0 +startup_duration_timeout: 1h +models: + - Gabriel/diffu-minicpm-ocr-htr + - Gabriel/diffu-minicpm-ocr-htr-dspark + - Gabriel/diffu-minicpm-ocr-htr-jev + - Gabriel/swedish-lion-trocr-large-handwritten-char --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +# Swedish HTR speed and Jev + +Reads a handwritten text region three ways on the same GPU and times each: the Swedish Lion TrOCR line by line, the +[MiniCPM-OCR HTR reader](https://huggingface.co/Gabriel/diffu-minicpm-ocr-htr) on the whole region, and the same reader +with its [DSpark draft](https://huggingface.co/Gabriel/diffu-minicpm-ocr-htr-dspark). Then +[Jev](https://huggingface.co/Gabriel/diffu-minicpm-ocr-htr-jev), the reader's proof-reader, scores each line's readings. + +Decoding runs in PyTorch on CUDA graphs (`dspark_hf.py`); see the app's "How it works" tab. Part of +[diffu](https://github.com/Borg93/diffu2). diff --git a/app.py b/app.py new file mode 100644 index 0000000000000000000000000000000000000000..56c21eaff832672bd9de2f64282d7ec9fbbf9401 --- /dev/null +++ b/app.py @@ -0,0 +1,411 @@ +"""Reading Swedish handwriting: the Swedish Lion TrOCR against our MiniCPM-OCR reader, alone and with its DSpark +draft, timed on the same region; and Jev, the reader's proof-reader, scoring each line's readings. + +Everything runs in PyTorch on ZeroGPU (vLLM, where the draft normally runs, cannot run here): the reader's passes and +the draft's proposals are replayed from CUDA graphs (dspark_hf.py), for the reader alone and with the draft alike. +""" + +import io +import json +import os +import threading +import time +from collections.abc import Callable +from pathlib import Path +from typing import Any, TypeVar + +import gradio as gr +import pandas as pd +import spaces # before torch: ZeroGPU patches CUDA +import torch +from huggingface_hub import snapshot_download +from PIL import Image +from pydantic import BaseModel +from rapidfuzz.distance import Levenshtein +from transformers import ( + AutoModelForImageTextToText, + AutoProcessor, + Qwen3_5ForSequenceClassification, + TrOCRProcessor, + VisionEncoderDecoderModel, +) + +import dspark_hf as D +from jev_prompt import model_prompt +from jev_render import render_text, renderer_version + +READER = "Gabriel/diffu-minicpm-ocr-htr" +DRAFT = "Gabriel/diffu-minicpm-ocr-htr-dspark" +JEV = "Gabriel/diffu-minicpm-ocr-htr-jev" +TROCR = os.environ.get("TROCR_REPO", "Gabriel/swedish-lion-trocr-large-handwritten-char") # private copy +HERE = Path(__file__).parent +FONT = HERE / "DejaVuSans.ttf" +EXAMPLES: list[dict[str, Any]] = json.loads((HERE / "examples" / "examples.json").read_text(encoding="utf-8")) +MAX_LEN = 8192 # the reader's cache: the longest prompt (a region's image) and its reading +MINICPM_IMAGES = {"downsample_mode": "4x", "max_slice_nums": 9} # OpenBMB's settings, as the reader was trained +JEV_HEIGHT, JEV_JPEG = 48, 95 # Jev's line crops, as its training pairs were cut +T = TypeVar("T") + +# On CUDA at module level, as ZeroGPU asks: the weights move to the GPU when a GPU call starts. +processor = AutoProcessor.from_pretrained(READER) +reader = AutoModelForImageTextToText.from_pretrained(READER, dtype=torch.bfloat16).to("cuda").eval() +draft = D.DSparkDraft.from_folder(snapshot_download(DRAFT), reader.get_input_embeddings()) +draft = draft.to("cuda", torch.bfloat16).eval() +_eos = reader.generation_config.eos_token_id +EOS: set[int] = set(_eos) if isinstance(_eos, list) else {int(_eos)} +jev_processor = AutoProcessor.from_pretrained(JEV) +jev = Qwen3_5ForSequenceClassification.from_pretrained(JEV, num_labels=2, dtype=torch.bfloat16).to("cuda").eval() +trocr_processor = TrOCRProcessor.from_pretrained(TROCR) +trocr = VisionEncoderDecoderModel.from_pretrained(TROCR).to("cuda").eval() # float32, as Riksarkivet runs it + +_engines: dict[int, D.FastDSpark] = {} # per GPU worker process: CUDA graphs belong to the process that captured them +_lock = threading.Lock() + + +class JevLine(BaseModel): + """Jev's scores of one line's TrOCR reading and, when the reader's region reading splits into as many lines, of + the reader's.""" + + trocr: str + trocr_score: float + minicpm: str | None = None + minicpm_score: float | None = None + + +class Comparison(BaseModel): + """One region read three ways: each reading, its seconds, and the draft's counters.""" + + truth: list[str] | None + trocr: list[str] | None = None + trocr_seconds: float | None = None + plain: str + plain_seconds: float + plain_passes: int + dspark: str + dspark_seconds: float + dspark_passes: int + tokens: int + acceptance: float + identical: bool + jev: list[JevLine] | None = None + + +def _example(example_id: str) -> dict[str, Any]: + return next(e for e in EXAMPLES if e["id"] == example_id) + + +def _region_inputs(image: Image.Image) -> dict[str, Any]: + content = [{"type": "image", "image": image}, {"type": "text", "text": "Text Recognition:"}] + batch = processor.apply_chat_template( + [{"role": "user", "content": content}], + add_generation_prompt=True, + tokenize=True, + return_dict=True, + return_tensors="pt", + enable_thinking=False, + processor_kwargs=MINICPM_IMAGES, + ) + inputs = dict(batch.to("cuda")) + inputs["downsample_mode"] = MINICPM_IMAGES["downsample_mode"] + return inputs + + +def _trocr_read(lines: list[Image.Image], max_new_tokens: int = 128) -> list[str]: + """TrOCR's greedy readings of a batch of lines, as Riksarkivet's evaluation runs it: the Swedish Lion starts + decoding from its config's token (its generation_config names another, which costs about 2 points of CER), and + its 192 x 1024 inputs need the position encoding interpolated.""" + pixels = trocr_processor(images=lines, return_tensors="pt").pixel_values.to("cuda") + ids = trocr.generate( + pixels, + decoder_start_token_id=trocr.config.decoder_start_token_id, + interpolate_pos_encoding=True, + num_beams=1, + max_new_tokens=max_new_tokens, + ) + return [text.strip() for text in trocr_processor.batch_decode(ids, skip_special_tokens=True)] + + +def _jev_crop(line: Image.Image) -> Image.Image: + """A line's crop as Jev was trained on it: 48 pixels high, its aspect kept, through JPEG at quality 95.""" + image = line.convert("RGB") + if image.height != JEV_HEIGHT: + width = max(1, round(image.width * JEV_HEIGHT / image.height)) + image = image.resize((width, JEV_HEIGHT), Image.Resampling.LANCZOS) + buffer = io.BytesIO() + image.save(buffer, format="JPEG", quality=JEV_JPEG) + return Image.open(io.BytesIO(buffer.getvalue())).convert("RGB") + + +def _jev_score(crop: Image.Image, text: str) -> float: + rendering = render_text(text, FONT, crop.size) + inputs = jev_processor(text=[model_prompt(text)], images=[crop, rendering], return_tensors="pt").to("cuda") + with torch.inference_mode(): + logits = jev(**inputs).logits[0].float() + return float(torch.softmax(logits, -1)[1]) + + +def _engine() -> D.FastDSpark: + """This worker's reader and draft on CUDA graphs, captured and warmed on first use (no timing includes it).""" + engine = _engines.get(os.getpid()) + if engine is None: + engine = D.FastDSpark(reader, draft, MAX_LEN) + warm = Image.open(HERE / "examples" / EXAMPLES[0]["id"] / "region.png").convert("RGB") + engine.warm(_region_inputs(warm), EOS) + _trocr_read([warm.crop((0, 0, 200, 40))], max_new_tokens=4) + _jev_score(_jev_crop(warm.crop((0, 0, 200, 40))), "warm") + _engines[os.getpid()] = engine + return engine + + +def _timed(fn: Callable[[], T]) -> tuple[T, float]: + torch.cuda.synchronize() + started = time.perf_counter() + result = fn() + torch.cuda.synchronize() + return result, time.perf_counter() - started + + +def _text(tokens: list[int]) -> str: + return processor.decode(tokens, skip_special_tokens=True).strip() + + +def _cer(prediction: str, truth: str) -> float: + prediction, truth = " ".join(prediction.split()), " ".join(truth.split()) + return Levenshtein.distance(prediction, truth) / max(1, len(truth)) + + +def _duration(example_id: str, upload: Image.Image | None, with_jev: bool) -> int: + lines = 0 if upload is not None else len(_example(example_id)["lines"]) + return int(min(115, 45 + 2.5 * lines + (25 if with_jev else 0))) + + +@spaces.GPU(duration=_duration) +def compare(example_id: str, upload: Image.Image | None, with_jev: bool) -> Comparison: + """Read one region three ways and time each, from the images to the text: TrOCR on its lines in one batch, the + MiniCPM-OCR reader alone, and the reader with its DSpark draft (the last two on the same CUDA graphs). For an + example region, Jev then scores each line's TrOCR and MiniCPM readings.""" + with _lock, torch.inference_mode(): + engine = _engine() + if upload is not None: + region, lines, truth = upload.convert("RGB"), [], None + else: + folder = HERE / "examples" / example_id + truth = _example(example_id)["lines"] + region = Image.open(folder / "region.png").convert("RGB") + lines = [Image.open(folder / f"line_{i:02d}.jpg").convert("RGB") for i in range(len(truth))] + trocr_lines, trocr_seconds = _timed(lambda: _trocr_read(lines)) if lines else (None, None) + plain, plain_seconds = _timed(lambda: D.greedy(engine.reader, _region_inputs(region), 4096, EOS)) + spec, dspark_seconds = _timed(lambda: engine.decode(_region_inputs(region), 4096, EOS)) + result = Comparison( + truth=truth, + trocr=trocr_lines, + trocr_seconds=trocr_seconds, + plain=_text(plain.tokens), + plain_seconds=plain_seconds, + plain_passes=plain.reader_passes, + dspark=_text(spec.tokens), + dspark_seconds=dspark_seconds, + dspark_passes=spec.reader_passes, + tokens=len(spec.tokens), + acceptance=spec.acceptance_length, + identical=plain.tokens == spec.tokens, + ) + if with_jev and trocr_lines is not None: + minicpm_lines = result.dspark.split("\n") + aligned = len(minicpm_lines) == len(lines) + rows = [] + for i, line in enumerate(lines): + crop = _jev_crop(line) + row = JevLine(trocr=trocr_lines[i], trocr_score=_jev_score(crop, trocr_lines[i])) + if aligned: + row.minicpm, row.minicpm_score = minicpm_lines[i], _jev_score(crop, minicpm_lines[i]) + rows.append(row) + result.jev = rows + return result + + +@spaces.GPU(duration=30) +def score_line(line: Image.Image | None, text: str) -> tuple[dict[str, float], Image.Image]: + """Jev's score (0 to 1) that a candidate text is exactly what a handwritten line says, and the rendering of the + candidate it compares with the line.""" + if line is None or not text.strip(): + raise gr.Error("Give a line image and a candidate text.") + with _lock, torch.inference_mode(): + crop = _jev_crop(line) + score = _jev_score(crop, text.strip()) + return {"matches": score, "does not match": 1 - score}, render_text(text.strip(), FONT, crop.size) + + +def _bars(result: Comparison) -> str: + rows: list[tuple[str, float, str, str]] = [] + if result.trocr_seconds is not None: + rows.append(("Swedish Lion TrOCR", result.trocr_seconds, "#8a6d3b", "its lines in one batch")) + rows += [ + ("MiniCPM-OCR reader alone", result.plain_seconds, "#5b6b7a", f"{result.plain_passes} reader passes"), + ("Reader + DSpark draft", result.dspark_seconds, "#2f6f4f", f"{result.dspark_passes} reader passes"), + ] + longest = max(seconds for _, seconds, _, _ in rows) + html = ['
'] + for name, seconds, colour, note in rows: + width = max(2.0, 100 * seconds / longest) + html.append( + '
' + f"{name} · {note}{seconds:.2f} s
" + '
' + f'
' + ) + html.append("
") + return "".join(html) + + +def _summary(result: Comparison) -> str: + against_trocr = ( + f", **{result.trocr_seconds / result.dspark_seconds:.1f}×** TrOCR" if result.trocr_seconds is not None else "" + ) + same = ( + "The draft's reading is identical to the reader's alone." + if result.identical + else "The two readings differ at a near-tied token: the reader checks 16 tokens at once, and a batch of " + "another size can tip a tie the other way (the reader alone does the same between batch sizes)." + ) + return ( + f"**{result.tokens} tokens.** DSpark: acceptance length **{result.acceptance:.2f}** (tokens kept per reader " + f"check, at most 16), {result.dspark_passes} reader passes instead of {result.plain_passes}; " + f"**{result.plain_seconds / result.dspark_seconds:.1f}×** the reader alone{against_trocr}. {same}" + ) + + +def _jev_table(result: Comparison) -> tuple[dict[str, Any], str]: + if not result.jev or result.truth is None or result.trocr is None: + return gr.update(visible=False, value=None), "" + records = [] + for i, row in enumerate(result.jev): + record: dict[str, Any] = { + "line": i + 1, + "ground truth": result.truth[i], + "TrOCR": row.trocr, + "Jev(TrOCR)": round(row.trocr_score, 3), + } + if row.minicpm is not None and row.minicpm_score is not None: + record |= { + "MiniCPM": row.minicpm, + "Jev(MiniCPM)": round(row.minicpm_score, 3), + "Jev picks": "MiniCPM" if row.minicpm_score > row.trocr_score else "TrOCR", + } + records.append(record) + truth = " ".join(result.truth) + scored = [row for row in result.jev if row.minicpm is not None and row.minicpm_score is not None] + if len(scored) != len(result.jev): + note = "The reader's reading has a different number of lines than the region: Jev scored TrOCR's lines only." + else: + picked = [row.minicpm if (row.minicpm_score or 0) > row.trocr_score else row.trocr for row in scored] + note = ( + f"Line CER · TrOCR {100 * _cer(' '.join(result.trocr), truth):.1f} % · MiniCPM " + f"{100 * _cer(' '.join(row.minicpm or '' for row in scored), truth):.1f} % · " + f"**Jev's pick per line {100 * _cer(' '.join(str(p) for p in picked), truth):.1f} %**" + ) + return gr.update(visible=True, value=pd.DataFrame(records)), note + + +def run(example_label: str, upload: Image.Image | None, with_jev: bool) -> tuple[Any, ...]: + """Read the chosen example (or an uploaded region) three ways and show the timings, readings and Jev's scores.""" + result = compare(LABELS[example_label], upload, with_jev) + truth = "\n".join(result.truth) if result.truth else None + + def box(name: str, seconds: float | None, text: str) -> dict[str, Any]: + cer = f" · CER {100 * _cer(text, truth):.1f} %" if truth else "" + timing = f" · {seconds:.2f} s" if seconds is not None else " · reads lines, not uploads" + return gr.update(value=text, label=f"{name}{timing}{cer if seconds is not None else ''}") + + table, note = _jev_table(result) + return ( + _bars(result), + box("Swedish Lion TrOCR", result.trocr_seconds, "\n".join(result.trocr or [])), + box("MiniCPM-OCR reader alone", result.plain_seconds, result.plain), + box("Reader + DSpark draft", result.dspark_seconds, result.dspark), + _summary(result), + table, + note, + ) + + +@spaces.GPU(duration=240) +def _warm_startup() -> None: + """At startup, one worker captures every graph and compiles the Triton kernels, cached on disk for later ones.""" + _engine() + + +def _label(example: dict[str, Any]) -> str: + collection = example["collection"].removeprefix("GT-").rsplit("_", 1)[0].replace("_", " ") + return f"{collection} · {len(example['lines'])} lines" + + +LABELS = {_label(e): e["id"] for e in EXAMPLES} + +with gr.Blocks(title="Swedish HTR: TrOCR, MiniCPM-OCR and DSpark") as demo: + gr.Markdown( + "# Reading Swedish handwriting faster\n" + "A text region from an archive volume, read three ways on the same GPU: Riksarkivet's **Swedish Lion TrOCR** " + f"line by line; our **[MiniCPM-OCR reader](https://huggingface.co/{READER})** on the whole region; and the " + f"same reader with its **[DSpark draft](https://huggingface.co/{DRAFT})**, which guesses 15 tokens at a time " + f"for the reader to check in one pass. Then **[Jev](https://huggingface.co/{JEV})**, the reader's " + "proof-reader, scores each line's two readings. The regions are from volumes none of the models trained on." + ) + with gr.Tab("Compare"): + with gr.Row(): + with gr.Column(scale=2): + choice = gr.Dropdown(list(LABELS), value=next(iter(LABELS)), label="Example region") + preview = gr.Image( + value=str(HERE / "examples" / EXAMPLES[0]["id"] / "region.png"), + label="Region", + interactive=False, + height=360, + ) + upload = gr.Image( + type="pil", label="Or your own region (the reader only: TrOCR and Jev need its lines)" + ) + with_jev = gr.Checkbox(value=True, label="Score each line with Jev") + go = gr.Button("Read", variant="primary") + with gr.Column(scale=3): + bars = gr.HTML() + summary = gr.Markdown() + with gr.Row(): + t_trocr = gr.Textbox(label="Swedish Lion TrOCR", lines=10) + t_plain = gr.Textbox(label="MiniCPM-OCR reader alone", lines=10) + t_dspark = gr.Textbox(label="Reader + DSpark draft", lines=10) + jev_note = gr.Markdown() + jev_table = gr.Dataframe(visible=False, wrap=True, label="Jev per line") + choice.change(lambda label: str(HERE / "examples" / LABELS[label] / "region.png"), choice, preview) + go.click(run, [choice, upload, with_jev], [bars, t_trocr, t_plain, t_dspark, summary, jev_table, jev_note]) + with gr.Tab("Try Jev"): + gr.Markdown( + "Jev scores whether a text is exactly what a **single handwritten line** says. Upload a line crop and type " + "a reading; change a letter and watch the score drop." + ) + with gr.Row(): + with gr.Column(): + line_in = gr.Image(type="pil", label="Line image", height=120) + text_in = gr.Textbox(label="Candidate text") + score_go = gr.Button("Score", variant="primary") + with gr.Column(): + score_out = gr.Label(label="Jev") + render_out = gr.Image(label="The candidate rendered, as Jev compares it", height=120) + first = EXAMPLES[0] + gr.Examples( + [[str(HERE / "examples" / first["id"] / f"line_{i:02d}.jpg"), first["lines"][i]] for i in range(3)], + [line_in, text_in], + cache_examples=False, + ) + score_go.click(score_line, [line_in, text_in], [score_out, render_out]) + with gr.Tab("How it works"): + gr.Markdown( + (HERE / "HOW_IT_WORKS.md").read_text(encoding="utf-8").replace("@RENDERER@", renderer_version(FONT)) + ) + +if os.environ.get("SPACES_ZERO_GPU"): + try: + _warm_startup() + except Exception as error: # the app still works: the first request warms its own worker + print(f"startup warm-up skipped: {error}", flush=True) + +demo.queue(default_concurrency_limit=2).launch(show_error=True) diff --git a/dspark_hf.py b/dspark_hf.py new file mode 100644 index 0000000000000000000000000000000000000000..6a6bf0f7afd2c24fff34974b583281055ab8ff4a --- /dev/null +++ b/dspark_hf.py @@ -0,0 +1,604 @@ +"""DSpark speculative decoding for the MiniCPM-OCR HTR reader in PyTorch and transformers, on CUDA graphs. + +vLLM serves this draft natively; this module is for hosts where vLLM cannot run (ZeroGPU). It follows the speculators +DSpark recipe the draft was trained with (speculators 0.10, ``models/dflash`` and ``models/dspark``): + +* Context: the reader's residual stream entering layers 4, 8, 12, 16 and 20 at every position before the anchor, + concatenated, through ``fc`` and ``hidden_norm``; each draft layer projects it to keys and values (``k_norm`` and + rotary on the keys). A sliding window of 2,048 positions. +* Query block: the anchor token and 14 mask tokens at positions p..p+14, causal inside the block; slot k predicts the + token at p+k+1 (``sample_from_anchor``). +* Sampling: the block's base logits (a 32,000-token draft vocabulary) plus the Markov bias of the previous token, + argmax, left to right; draft ids map to the reader's vocabulary through ``d2t``. + +Profiled with torch.profiler, eager decoding was launch-bound (about 1,500 kernels a reader pass, the GPU busy 12 % of +the time). So the reader runs on transformers' StaticCache with each pass replayed from a CUDA graph +(``GraphedReader``), the draft's whole proposal is one graph (``GraphedDraft``), and a draft cycle takes one reader +pass (``FastDSpark``): the reader is hybrid, its linear-attention states cannot be cut back after rejected tokens, so +the verifying graph keeps each linear layer's block inputs and the states are rebuilt over the accepted tokens only. +""" + +from __future__ import annotations + +import json +import time +from pathlib import Path +from typing import Any, cast + +import torch +import torch.nn.functional as F +from pydantic import BaseModel, ConfigDict, Field +from safetensors.torch import load_file +from torch import nn +from transformers import PreTrainedModel, Qwen3Config, StaticCache +from transformers.cache_utils import LinearAttentionCacheLayerMixin, StaticLayer +from transformers.models.qwen3.modeling_qwen3 import Qwen3MLP, Qwen3RMSNorm, Qwen3RotaryEmbedding +from transformers.models.qwen3_5 import modeling_qwen3_5 as qwen3_5 + +AUX_LAYERS = (4, 8, 12, 16, 20) + + +def rotate_half(x: torch.Tensor) -> torch.Tensor: + x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :] + return torch.cat((-x2, x1), dim=-1) + + +def rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: + """Rotary position embedding of x [heads, n, head_dim] with cos/sin [n, head_dim].""" + return x * cos[None] + rotate_half(x) * sin[None] + + +class DraftAttention(nn.Module): + def __init__(self, hidden: int, heads: int, kv_heads: int, head_dim: int, eps: float): + super().__init__() + self.heads, self.kv_heads, self.head_dim = heads, kv_heads, head_dim + self.q_proj = nn.Linear(hidden, heads * head_dim, bias=False) + self.k_proj = nn.Linear(hidden, kv_heads * head_dim, bias=False) + self.v_proj = nn.Linear(hidden, kv_heads * head_dim, bias=False) + self.o_proj = nn.Linear(heads * head_dim, hidden, bias=False) + self.q_norm = Qwen3RMSNorm(head_dim, eps=eps) + self.k_norm = Qwen3RMSNorm(head_dim, eps=eps) + + def query(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: + n = x.shape[0] + return rope(self.q_norm(self.q_proj(x).view(n, self.heads, self.head_dim)).transpose(0, 1), cos, sin) + + def kv(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """Keys and values of x [n, hidden], each [kv_heads, n, head_dim].""" + n = x.shape[0] + k = self.k_norm(self.k_proj(x).view(n, self.kv_heads, self.head_dim)).transpose(0, 1) + v = self.v_proj(x).view(n, self.kv_heads, self.head_dim).transpose(0, 1) + return rope(k, cos, sin), v + + +class DraftLayer(nn.Module): + def __init__(self, cfg: Qwen3Config, heads: int, kv_heads: int, head_dim: int): + super().__init__() + eps = float(cfg.rms_norm_eps) + self.self_attn = DraftAttention(cfg.hidden_size, heads, kv_heads, head_dim, eps) + self.mlp = Qwen3MLP(cfg) + self.input_layernorm = Qwen3RMSNorm(cfg.hidden_size, eps=eps) + self.post_attention_layernorm = Qwen3RMSNorm(cfg.hidden_size, eps=eps) + + +class DSparkDraft(nn.Module): + """The draft's weights as speculators saves them; the input embeddings are the reader's.""" + + def __init__(self, config: dict[str, Any], embed_tokens: nn.Embedding): + super().__init__() + layer_config = { + k: v for k, v in config["transformer_layer_config"].items() if k not in ("architectures", "dtype") + } + self.cfg = Qwen3Config(**layer_config) + hidden = self.cfg.hidden_size + self.heads = int(self.cfg.num_attention_heads) + self.kv_heads = int(self.cfg.num_key_value_heads or self.heads) + self.head_dim = int(self.cfg.head_dim or hidden // self.heads) + eps = float(self.cfg.rms_norm_eps) + self.block_size: int = config["block_size"] + self.mask_token_id: int = config["mask_token_id"] + self.window: int | None = self.cfg.sliding_window if self.cfg.use_sliding_window else None + self.embed_tokens = embed_tokens + self.fc = nn.Linear(len(config["aux_hidden_state_layer_ids"]) * hidden, hidden, bias=False) + self.hidden_norm = Qwen3RMSNorm(hidden, eps=eps) + blocks = [ + DraftLayer(self.cfg, self.heads, self.kv_heads, self.head_dim) for _ in range(self.cfg.num_hidden_layers) + ] + self.layers = nn.ModuleList(blocks) + self.blocks: tuple[DraftLayer, ...] = tuple(blocks) # the same modules, typed + self.norm = Qwen3RMSNorm(hidden, eps=eps) + self.lm_head = nn.Linear(hidden, config["draft_vocab_size"], bias=False) + self.markov_w1 = nn.Embedding(embed_tokens.num_embeddings, config["markov_rank"]) + self.markov_w2 = nn.Linear(config["markov_rank"], config["draft_vocab_size"], bias=False) + self.register_buffer("d2t", torch.zeros(config["draft_vocab_size"], dtype=torch.long), persistent=False) + self.rotary = Qwen3RotaryEmbedding(self.cfg) + + @classmethod + def from_folder(cls, folder: str | Path, embed_tokens: nn.Embedding) -> DSparkDraft: + """The draft a speculators checkpoint folder holds (config.json and model.safetensors).""" + folder = Path(folder) + config = json.loads((folder / "config.json").read_text(encoding="utf-8")) + if config.get("markov_head_type", "vanilla") != "vanilla" or not config.get("sample_from_anchor", True): + raise ValueError("only drafts with the vanilla Markov head that sample from the anchor are supported") + draft = cls(config, embed_tokens) + state: dict[str, torch.Tensor] = {} + for name, tensor in load_file(folder / "model.safetensors").items(): + if name == "d2t": + draft.d2t_map.copy_(tensor) + elif name != "t2d" and not name.startswith("confidence_head."): # training and adaptive verification only + state[name.replace("markov_head.", "")] = tensor + missing, unexpected = draft.load_state_dict(state, strict=False) + missing = [m for m in missing if not m.startswith(("embed_tokens.", "rotary."))] + if missing or unexpected: + raise ValueError(f"the draft's weights do not match: missing {missing}, unexpected {unexpected}") + return draft + + @property + def d2t_map(self) -> torch.Tensor: + return cast(torch.Tensor, self.d2t) + + def cos_sin(self, positions: torch.Tensor, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]: + cos, sin = self.rotary(torch.empty(0, dtype=dtype, device=positions.device), positions[None]) + return cos[0], sin[0] + + +def aux_states(hidden_states: tuple[torch.Tensor, ...]) -> torch.Tensor: + """The residual stream entering each aux layer, [n, 5 * hidden]; hidden_states[0] are the embeddings.""" + return torch.cat([hidden_states[i][0] for i in AUX_LAYERS], dim=-1) + + +class Decoded(BaseModel): + """A reading's tokens, its seconds and reader passes; with a draft, the tokens proposed and accepted over how many + verifications.""" + + tokens: list[int] = Field(default_factory=list) + seconds: float = 0.0 + reader_passes: int = 0 + drafted: int = 0 + accepted: int = 0 + cycles: int = 0 + + @property + def acceptance_length(self) -> float: + """vLLM's measure: 1 + accepted draft tokens per verification.""" + return 1 + self.accepted / self.cycles if self.cycles else float("nan") + + +def _stop(tokens: list[int], eos: set[int], max_new: int) -> tuple[list[int], bool]: + for i, token in enumerate(tokens): + if token in eos: + return tokens[: i + 1], True + if len(tokens) >= max_new: + return tokens[:max_new], True + return tokens, False + + +class _Graph(BaseModel): + """A captured reader pass: its graph, the static inputs refilled before each replay, the static outputs.""" + + model_config = ConfigDict(arbitrary_types_allowed=True) + + graph: torch.cuda.CUDAGraph + ids: torch.Tensor + pos: torch.Tensor + out: Any + + +class _LinearState(BaseModel): + """A linear-attention layer and the copy of its states `save` took.""" + + model_config = ConfigDict(arbitrary_types_allowed=True) + + layer_idx: int + layer: Any + conv: torch.Tensor + recurrent: torch.Tensor + + +class _AttentionState(BaseModel): + """A full-attention layer and the length `save` took.""" + + model_config = ConfigDict(arbitrary_types_allowed=True) + + layer: Any + length: torch.Tensor + + +class GraphedReader: + """The reader on a StaticCache, each pass length replayed from a CUDA graph captured on first use. + + The cache is reset in place per request (its addresses, and so the graphs, kept). Full-attention layers keep + preallocated keys and values and an on-device length; linear-attention layers fixed-address states; the attention + mask is built inside the graph from the positions.""" + + def __init__(self, model: PreTrainedModel, max_len: int): + self.model, self.max_len = model, max_len + self.device = model.get_output_embeddings().weight.device + self.cache = StaticCache(config=model.config, max_cache_len=max_len) + self.kv_index = torch.arange(max_len, device=self.device) + self.graphs: dict[tuple[int, bool], _Graph] = {} + self.pool = torch.cuda.graph_pool_handle() + self.linear: list[_LinearState] = [] + self.attention: list[_AttentionState] = [] + + def prefill(self, inputs: dict[str, Any], hidden: bool) -> Any: + """A new request: the cache emptied in place, then the prompt (image and text) read eagerly.""" + if inputs["input_ids"].shape[1] + 64 > self.max_len: + raise ValueError( + f"a prompt of {inputs['input_ids'].shape[1]} tokens is too long for a cache of {self.max_len}" + ) + self.cache.reset() + return self.model(**inputs, past_key_values=self.cache, use_cache=True, output_hidden_states=hidden) + + def save(self) -> None: + """Remember the cache's states and lengths, into buffers allocated on the first call.""" + if not self.linear and not self.attention: + for idx, layer in enumerate(self.cache.layers): + if isinstance(layer, LinearAttentionCacheLayerMixin): + conv, recurrent = layer.conv_states[0], layer.recurrent_states[0] + if conv is None or recurrent is None: + raise RuntimeError("save() before the prompt was read") + self.linear.append( + _LinearState(layer_idx=idx, layer=layer, conv=conv.clone(), recurrent=recurrent.clone()) + ) + elif isinstance(layer, StaticLayer): + self.attention.append(_AttentionState(layer=layer, length=_length(layer).clone())) + return + for state in self.linear: + state.conv.copy_(state.layer.conv_states[0]) + state.recurrent.copy_(state.layer.recurrent_states[0]) + for state in self.attention: + state.length.copy_(_length(state.layer)) + + def restore(self) -> None: + """The cache as `save` left it (keys and values written since stay behind the length, masked by position).""" + for state in self.linear: + state.layer.conv_states[0].copy_(state.conv) + state.layer.recurrent_states[0].copy_(state.recurrent) + for state in self.attention: + _length(state.layer).copy_(state.length) + + def _forward(self, ids: torch.Tensor, pos: torch.Tensor, hidden: bool) -> Any: + mask = (self.kv_index[None, :] <= pos[0][:, None])[None, None] + return self.model( + input_ids=ids, + position_ids=pos, + past_key_values=self.cache, + use_cache=True, + attention_mask={"full_attention": mask, "linear_attention": None}, + output_hidden_states=hidden, + ) + + def _capture(self, ids: torch.Tensor, pos: torch.Tensor, hidden: bool) -> tuple[torch.cuda.CUDAGraph, Any]: + self.save() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(2): # kernels autotune and allocate outside the capture + self._forward(ids, pos, hidden) + self.restore() + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, pool=self.pool): + out = self._forward(ids, pos, hidden) + self.restore() # capture records without running; the cache stays as it was + return graph, out + + def run(self, tokens: list[int], start: int, hidden: bool) -> Any: + """A pass over `tokens` at positions start.. (the cache must hold exactly the positions before start).""" + key = (len(tokens), hidden) + ids = torch.tensor([tokens], device=self.device) + pos = torch.arange(start, start + len(tokens), device=self.device)[None] + graph = self.graphs.get(key) + if graph is None: + captured, out = self._capture(ids, pos, hidden) + graph = self.graphs[key] = _Graph(graph=captured, ids=ids, pos=pos, out=out) + else: + graph.ids.copy_(ids) + graph.pos.copy_(pos) + graph.graph.replay() + return graph.out + + +def _length(layer: StaticLayer) -> torch.Tensor: + return cast(torch.Tensor, layer.cumulative_length) + + +class _Recorder: + """While a verifying graph is captured: each linear layer's block inputs, by layer index.""" + + def __init__(self) -> None: + self.active = False + self.layer = -1 + self.inputs: dict[int, dict[str, torch.Tensor]] = {} + + +_RECORDER = _Recorder() +_chunk_rule = qwen3_5.torch_chunk_gated_delta_rule + + +def _recording_chunk_rule( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + g: torch.Tensor, + beta: torch.Tensor, + *args: Any, + **kwargs: Any, +) -> Any: + if _RECORDER.active: + _RECORDER.inputs[_RECORDER.layer].update(q=query, k=key, v=value, g=g, beta=beta) + return _chunk_rule(query, key, value, g, beta, *args, **kwargs) + + +qwen3_5.torch_chunk_gated_delta_rule = _recording_chunk_rule # the layers look the rule up at call time + + +class OnePassReader(GraphedReader): + """A GraphedReader whose verifying graph (more than one token, hidden states out) records the linear layers' block + inputs, so a partly accepted block can be kept without a second pass.""" + + def __init__(self, model: PreTrainedModel, max_len: int): + super().__init__(model, max_len) + update = self.cache.update_conv_state + + def recording_update(conv_input: torch.Tensor, layer_idx: int, *args: Any, **kwargs: Any) -> Any: + if _RECORDER.active: + _RECORDER.layer = layer_idx + _RECORDER.inputs[layer_idx] = {"conv": conv_input} + return update(conv_input, layer_idx, *args, **kwargs) + + self.cache.update_conv_state = recording_update + self.recorded: dict[int, dict[str, torch.Tensor]] = {} + + def _capture(self, ids: torch.Tensor, pos: torch.Tensor, hidden: bool) -> tuple[torch.cuda.CUDAGraph, Any]: + if not (hidden and ids.shape[1] > 1): + return super()._capture(ids, pos, hidden) + self.save() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(2): + self._forward(ids, pos, hidden) + self.restore() + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + _RECORDER.active, _RECORDER.inputs = True, {} + try: + with torch.cuda.graph(graph, pool=self.pool): + out = self._forward(ids, pos, hidden) + finally: + _RECORDER.active = False + self.recorded = dict(_RECORDER.inputs) + self.restore() + return graph, out + + +class GraphedDraft: + """The draft's context in fixed buffers and its whole proposal (the parallel backbone and the Markov sampling) + replayed from one CUDA graph: context keys and values sit at their positions in buffers of the reader's cache + length, the block's own at the end; the window and causal masks come from the anchor's position on the GPU.""" + + def __init__(self, draft: DSparkDraft, max_len: int): + self.draft, self.max_len = draft, max_len + weight = draft.lm_head.weight + device, dtype = weight.device, weight.dtype + b = draft.block_size + size = (draft.kv_heads, max_len + b, draft.head_dim) + self.keys = [torch.zeros(size, device=device, dtype=dtype) for _ in draft.blocks] + self.values = [torch.zeros(size, device=device, dtype=dtype) for _ in draft.blocks] + self.length = 0 + self.anchor = torch.zeros(1, dtype=torch.long, device=device) + self.anchor_pos = torch.zeros((), dtype=torch.long, device=device) + self.kv_index = torch.arange(max_len, device=device) + self.offsets = torch.arange(b, device=device) + self.mask_ids = torch.full((b,), draft.mask_token_id, dtype=torch.long, device=device) + self.tril = torch.ones(b, b, dtype=torch.bool, device=device).tril() + self.graph = torch.cuda.CUDAGraph() + self.captured = False + self.out = torch.zeros(b, dtype=torch.long, device=device) + + def reset(self) -> None: + self.length = 0 # older entries stay behind, masked out by position + + @torch.inference_mode() + def extend(self, aux: torch.Tensor, start: int) -> None: + """The context of positions start.. (aux: the reader's states entering the aux layers).""" + if start != self.length or start + aux.shape[0] > self.max_len: + raise ValueError(f"context from {start} does not follow {self.length} or overflows {self.max_len}") + d, n = self.draft, aux.shape[0] + c = d.hidden_norm(d.fc(aux)) + cos, sin = d.cos_sin(torch.arange(start, start + n, device=aux.device), c.dtype) + for i, layer in enumerate(d.blocks): + k, v = layer.self_attn.kv(c, cos, sin) + self.keys[i][:, start : start + n].copy_(k) + self.values[i][:, start : start + n].copy_(v) + self.length += n + + def _propose(self) -> torch.Tensor: + d, b = self.draft, self.draft.block_size + x = d.embed_tokens(torch.where(self.offsets == 0, self.anchor, self.mask_ids)).to(d.lm_head.weight.dtype) + cos, sin = d.cos_sin(self.anchor_pos + self.offsets, x.dtype) + context = self.kv_index < self.anchor_pos + if d.window is not None: + context = context & (self.kv_index >= self.anchor_pos - d.window) + mask = torch.cat([context[None, :].expand(b, -1), self.tril], dim=1)[None, None] + for i, layer in enumerate(d.blocks): + attn = layer.self_attn + h = layer.input_layernorm(x) + k_block, v_block = attn.kv(h, cos, sin) + self.keys[i][:, self.max_len :].copy_(k_block) + self.values[i][:, self.max_len :].copy_(v_block) + out = F.scaled_dot_product_attention( + attn.query(h, cos, sin)[None], + self.keys[i][None], + self.values[i][None], + attn_mask=mask, + scale=attn.head_dim**-0.5, + enable_gqa=True, + )[0] + x = x + attn.o_proj(out.transpose(0, 1).reshape(b, -1)) + x = x + layer.mlp(layer.post_attention_layernorm(x)) + base = d.lm_head(d.norm(x)).float() + prev, tokens = self.anchor, [] + for k in range(b): + # index_select, not d2t[choice]: indexing by a 0-d tensor reads it on the host, which breaks a capture + choice = (base[k][None] + d.markov_w2(d.markov_w1(prev)).float()).argmax(dim=-1) + prev = choice + d.d2t_map.index_select(0, choice) + tokens.append(prev) + return torch.cat(tokens) + + @torch.inference_mode() + def propose(self, anchor: int, anchor_pos: int) -> torch.Tensor: + """The draft's block_size tokens after the anchor (the reader's vocabulary), left on the GPU.""" + if anchor_pos != self.length: + raise ValueError(f"the anchor at {anchor_pos} does not follow the context's {self.length} positions") + self.anchor.fill_(anchor) + self.anchor_pos.fill_(anchor_pos) + if not self.captured: + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(2): + self._propose() + torch.cuda.current_stream().wait_stream(stream) + with torch.cuda.graph(self.graph): + self.out = self._propose() + self.captured = True + self.graph.replay() + return self.out + + +class FastDSpark: + """The reader and its draft, every step of a cycle replayed from CUDA graphs: the draft's proposal goes into the + verifying graph on the GPU, one sync reads the drafts and the reader's tokens together, and the work after the + check (the draft's context extended, the reader's states rebuilt) is one graph per number of tokens kept. That work + depends only on the snapshot and the recorded block inputs, so the warm-up runs before each capture need no undoing. + """ + + def __init__(self, model: PreTrainedModel, draft: DSparkDraft, max_len: int): + self.reader = OnePassReader(model, max_len) + self.gdraft = GraphedDraft(draft, max_len) + self.block = draft.block_size + 1 + self.start = torch.zeros((), dtype=torch.long, device=self.reader.device) + self.after: dict[int, torch.cuda.CUDAGraph] = {} + self.verify_out: Any = None + + def _after_check(self, keep: int) -> None: + g, r = self.gdraft, self.reader + d = g.draft + aux = aux_states(self.verify_out.hidden_states)[:keep] + positions = self.start + torch.arange(keep, device=self.start.device) + c = d.hidden_norm(d.fc(aux)) + cos, sin = d.cos_sin(positions, c.dtype) + for i, layer in enumerate(d.blocks): + k, v = layer.self_attn.kv(c, cos, sin) + g.keys[i].index_copy_(1, positions, k) + g.values[i].index_copy_(1, positions, v) + if keep == self.block: + return # every state is already exact + for state in r.linear: + inputs = r.recorded[state.layer_idx] + conv = torch.cat([state.conv, inputs["conv"][..., :keep]], dim=-1)[..., -state.conv.shape[-1] :] + state.layer.conv_states[0].copy_(conv) + _, recurrent = qwen3_5.torch_recurrent_gated_delta_rule( + inputs["q"][:, :keep], + inputs["k"][:, :keep], + inputs["v"][:, :keep], + g=inputs["g"][:, :keep], + beta=inputs["beta"][:, :keep], + initial_state=state.recurrent, + output_final_state=True, + use_qk_l2norm_in_kernel=True, + ) + state.layer.recurrent_states[0].copy_(recurrent) + for state in r.attention: + _length(state.layer).copy_(self.start + keep) + + def after_check(self, keep: int) -> None: + """Keep the verified block's first `keep` tokens (the reader's states and the draft's context).""" + graph = self.after.get(keep) + if graph is None: + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(2): + self._after_check(keep) + torch.cuda.current_stream().wait_stream(stream) + graph = self.after[keep] = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, pool=self.reader.pool): + self._after_check(keep) + graph.replay() + self.gdraft.length += keep + + def _verify(self, anchor: int, drafts: torch.Tensor, anchor_pos: int) -> Any: + r = self.reader + graph = r.graphs.get((self.block, True)) + if graph is None: + return r.run([anchor, *drafts.tolist()], anchor_pos, hidden=True) + graph.ids[0, 0] = anchor + graph.ids[0, 1:].copy_(drafts) + graph.pos.copy_(torch.arange(anchor_pos, anchor_pos + self.block, device=r.device)[None]) + graph.graph.replay() + return graph.out + + @torch.inference_mode() + def decode(self, inputs: dict[str, Any], max_new: int, eos: set[int]) -> Decoded: + """The reader's greedy reading of `inputs`, with the draft: the same text, fewer reader passes.""" + torch.cuda.synchronize() + started = time.perf_counter() + r, g = self.reader, self.gdraft + n = inputs["input_ids"].shape[1] + max_new = min(max_new, r.max_len - n - 2 * self.block - 2) + out = r.prefill(inputs, hidden=True) + g.reset() + g.extend(aux_states(out.hidden_states), 0) + result = Decoded(reader_passes=1) + tokens, done = _stop([int(out.logits[0, -1].argmax())], eos, max_new) + while not done: + anchor_pos = n + len(tokens) - 1 + drafts = g.propose(tokens[-1], anchor_pos) + r.save() + self.verify_out = self._verify(tokens[-1], drafts, anchor_pos) + both = torch.cat([drafts, self.verify_out.logits[0].argmax(-1)]).tolist() # the cycle's one sync + proposed, verified = both[: self.block - 1], both[self.block - 1 :] + accepted = 0 + while accepted < len(proposed) and proposed[accepted] == verified[accepted]: + accepted += 1 + result.reader_passes += 1 + result.cycles += 1 + result.drafted += len(proposed) + result.accepted += accepted + self.start.fill_(anchor_pos) + self.after_check(accepted + 1) + tokens, done = _stop(tokens + [*proposed[:accepted], verified[accepted]], eos, max_new) + torch.cuda.synchronize() + result.tokens, result.seconds = tokens, time.perf_counter() - started + return result + + @torch.inference_mode() + def warm(self, inputs: dict[str, Any], eos: set[int]) -> None: + """Capture every graph (one reading with and one without the draft, then each number of tokens kept).""" + greedy(self.reader, inputs, 32, eos) + self.decode(inputs, 128, eos) + for keep in range(1, self.block + 1): # idempotent: depends only on the snapshot and the recorded inputs + self.start.fill_(0) + self.after_check(keep) + self.gdraft.reset() + + +@torch.inference_mode() +def greedy(reader: GraphedReader, inputs: dict[str, Any], max_new: int, eos: set[int]) -> Decoded: + """The reader alone on CUDA graphs: one replay per token, greedy.""" + torch.cuda.synchronize() + started = time.perf_counter() + n = inputs["input_ids"].shape[1] + max_new = min(max_new, reader.max_len - n - 1) + out = reader.prefill(inputs, hidden=False) + tokens, passes = [int(out.logits[0, -1].argmax())], 1 + while tokens[-1] not in eos and len(tokens) < max_new: + out = reader.run([tokens[-1]], n + len(tokens) - 1, hidden=False) + tokens.append(int(out.logits[0, -1].argmax())) + passes += 1 + torch.cuda.synchronize() + return Decoded(tokens=_stop(tokens, eos, max_new)[0], seconds=time.perf_counter() - started, reader_passes=passes) diff --git a/examples/19a1b2195bab_right_0/line_00.jpg b/examples/19a1b2195bab_right_0/line_00.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f972980ccabbcb7aae5396b183727934516247dc Binary files /dev/null and b/examples/19a1b2195bab_right_0/line_00.jpg differ diff --git a/examples/19a1b2195bab_right_0/line_01.jpg b/examples/19a1b2195bab_right_0/line_01.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b0e2429eb2cd01e401ccb1696fe5e5c6651cb552 Binary files /dev/null and b/examples/19a1b2195bab_right_0/line_01.jpg differ diff --git a/examples/19a1b2195bab_right_0/line_02.jpg b/examples/19a1b2195bab_right_0/line_02.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6e4529c6a54438f933c12f381c102c2de15db4c1 Binary files /dev/null and b/examples/19a1b2195bab_right_0/line_02.jpg differ diff --git a/examples/19a1b2195bab_right_0/line_03.jpg b/examples/19a1b2195bab_right_0/line_03.jpg new file mode 100644 index 0000000000000000000000000000000000000000..aae98bf8cd200ea9cbfe86a9a83ca90fc4193747 Binary files /dev/null and b/examples/19a1b2195bab_right_0/line_03.jpg differ diff --git a/examples/19a1b2195bab_right_0/line_04.jpg b/examples/19a1b2195bab_right_0/line_04.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5363f793aacc1306d133f798c492d734b3739065 Binary files /dev/null and b/examples/19a1b2195bab_right_0/line_04.jpg differ diff --git a/examples/19a1b2195bab_right_0/line_05.jpg b/examples/19a1b2195bab_right_0/line_05.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f55519a4ed1ad7a54140c6bec2804f102019d608 Binary files /dev/null and b/examples/19a1b2195bab_right_0/line_05.jpg differ diff --git a/examples/19a1b2195bab_right_0/line_06.jpg b/examples/19a1b2195bab_right_0/line_06.jpg new file mode 100644 index 0000000000000000000000000000000000000000..8ca5e16b23177c367e9d5f5a6ee3790f7ebead0d Binary files /dev/null and b/examples/19a1b2195bab_right_0/line_06.jpg differ diff --git a/examples/19a1b2195bab_right_0/line_07.jpg b/examples/19a1b2195bab_right_0/line_07.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d1859a923f14cfce854e983d492f9e6253b3d145 Binary files /dev/null and b/examples/19a1b2195bab_right_0/line_07.jpg differ diff --git a/examples/19a1b2195bab_right_0/region.png b/examples/19a1b2195bab_right_0/region.png new file mode 100644 index 0000000000000000000000000000000000000000..2a86c1bed32da1ba94ee341639aeca918167538e --- /dev/null +++ b/examples/19a1b2195bab_right_0/region.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:926f78e45b6a2e229092b9b609494bf1503aa724095cdaac813d0c3df0e7c385 +size 1055219 diff --git a/examples/35ffe6b8b600_left_0/line_00.jpg b/examples/35ffe6b8b600_left_0/line_00.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7e664316748c01cb5e8f56f1c3039064fc93e828 Binary files /dev/null and b/examples/35ffe6b8b600_left_0/line_00.jpg differ diff --git a/examples/35ffe6b8b600_left_0/line_01.jpg b/examples/35ffe6b8b600_left_0/line_01.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6a1cc30a0ac35983a36fe4a8ddd55d5991f79b88 Binary files /dev/null and b/examples/35ffe6b8b600_left_0/line_01.jpg differ diff --git a/examples/35ffe6b8b600_left_0/line_02.jpg b/examples/35ffe6b8b600_left_0/line_02.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7069a438594742bad02aabb9f0cf9488f8255bdd Binary files /dev/null and b/examples/35ffe6b8b600_left_0/line_02.jpg differ diff --git a/examples/35ffe6b8b600_left_0/line_03.jpg b/examples/35ffe6b8b600_left_0/line_03.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3c6bd44de78e63104b5c11060118348ee54f929d Binary files /dev/null and b/examples/35ffe6b8b600_left_0/line_03.jpg differ diff --git a/examples/35ffe6b8b600_left_0/line_04.jpg b/examples/35ffe6b8b600_left_0/line_04.jpg new file mode 100644 index 0000000000000000000000000000000000000000..8ad98e57409ec4baf35237fcdf0e3df942e6bb48 Binary files /dev/null and b/examples/35ffe6b8b600_left_0/line_04.jpg differ diff --git a/examples/35ffe6b8b600_left_0/line_05.jpg b/examples/35ffe6b8b600_left_0/line_05.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d2a6b3fd6f943b0f8f0f993cdc270e4ccfcda91a Binary files /dev/null and b/examples/35ffe6b8b600_left_0/line_05.jpg differ diff --git a/examples/35ffe6b8b600_left_0/line_06.jpg b/examples/35ffe6b8b600_left_0/line_06.jpg new file mode 100644 index 0000000000000000000000000000000000000000..2149586420a53cd8b147e260f959b49460f7bc8e Binary files /dev/null and b/examples/35ffe6b8b600_left_0/line_06.jpg differ diff --git a/examples/35ffe6b8b600_left_0/line_07.jpg b/examples/35ffe6b8b600_left_0/line_07.jpg new file mode 100644 index 0000000000000000000000000000000000000000..01b649712580410d127d963bbe446e01d0e1f06c Binary files /dev/null and b/examples/35ffe6b8b600_left_0/line_07.jpg differ diff --git a/examples/35ffe6b8b600_left_0/line_08.jpg b/examples/35ffe6b8b600_left_0/line_08.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6b646ec51a8a18c9480d66ffcc6bc996421911dd Binary files /dev/null and b/examples/35ffe6b8b600_left_0/line_08.jpg differ diff --git a/examples/35ffe6b8b600_left_0/line_09.jpg b/examples/35ffe6b8b600_left_0/line_09.jpg new file mode 100644 index 0000000000000000000000000000000000000000..97127f87d87d4108aa28e89bac8b1b6878ff70ee Binary files /dev/null and b/examples/35ffe6b8b600_left_0/line_09.jpg differ diff --git a/examples/35ffe6b8b600_left_0/line_10.jpg b/examples/35ffe6b8b600_left_0/line_10.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c0d7cd78f0d3c52e9af019d3dff9e5ad1adaea5f Binary files /dev/null and b/examples/35ffe6b8b600_left_0/line_10.jpg differ diff --git a/examples/35ffe6b8b600_left_0/line_11.jpg b/examples/35ffe6b8b600_left_0/line_11.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0aa15447f4c52edbb77d9f2fdf60dae5581b0afb Binary files /dev/null and b/examples/35ffe6b8b600_left_0/line_11.jpg differ diff --git a/examples/35ffe6b8b600_left_0/line_12.jpg b/examples/35ffe6b8b600_left_0/line_12.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e868f41d65b85bc020d1133a705072b512bef837 Binary files /dev/null and b/examples/35ffe6b8b600_left_0/line_12.jpg differ diff --git a/examples/35ffe6b8b600_left_0/line_13.jpg b/examples/35ffe6b8b600_left_0/line_13.jpg new file mode 100644 index 0000000000000000000000000000000000000000..49bb667d453ccf5c2071b60cf91a6f5dd25d3e02 Binary files /dev/null and b/examples/35ffe6b8b600_left_0/line_13.jpg differ diff --git a/examples/35ffe6b8b600_left_0/line_14.jpg b/examples/35ffe6b8b600_left_0/line_14.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b1fce566724f6cb5a67a8cd7e0a40cc939298b3d Binary files /dev/null and b/examples/35ffe6b8b600_left_0/line_14.jpg differ diff --git a/examples/35ffe6b8b600_left_0/line_15.jpg b/examples/35ffe6b8b600_left_0/line_15.jpg new file mode 100644 index 0000000000000000000000000000000000000000..aeda145f83645b0b27c38dbe80db8eaca48e7bf4 Binary files /dev/null and b/examples/35ffe6b8b600_left_0/line_15.jpg differ diff --git a/examples/35ffe6b8b600_left_0/line_16.jpg b/examples/35ffe6b8b600_left_0/line_16.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0ecbd8d21e9d7524af7ebb0fa88c9ffddbf37352 Binary files /dev/null and b/examples/35ffe6b8b600_left_0/line_16.jpg differ diff --git a/examples/35ffe6b8b600_left_0/line_17.jpg b/examples/35ffe6b8b600_left_0/line_17.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ca60164ddbff1a4b1e4375a1bc4aec9c58540120 Binary files /dev/null and b/examples/35ffe6b8b600_left_0/line_17.jpg differ diff --git a/examples/35ffe6b8b600_left_0/region.png b/examples/35ffe6b8b600_left_0/region.png new file mode 100644 index 0000000000000000000000000000000000000000..92aa1a3e44d009469fe9e48de646c237fb33df75 --- /dev/null +++ b/examples/35ffe6b8b600_left_0/region.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f22d252d73e9e17a449a701c67f586eb851ad29ee61c57131df5cabf6b2a446 +size 3632407 diff --git a/examples/38c4ce6331ad_left_1/line_00.jpg b/examples/38c4ce6331ad_left_1/line_00.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9f5fdb4271b7769dfa570c43c8834d48c0008c2c Binary files /dev/null and b/examples/38c4ce6331ad_left_1/line_00.jpg differ diff --git a/examples/38c4ce6331ad_left_1/line_01.jpg b/examples/38c4ce6331ad_left_1/line_01.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ffed85a7f993320daf2ba9024f438d8843ab0634 Binary files /dev/null and b/examples/38c4ce6331ad_left_1/line_01.jpg differ diff --git a/examples/38c4ce6331ad_left_1/line_02.jpg b/examples/38c4ce6331ad_left_1/line_02.jpg new file mode 100644 index 0000000000000000000000000000000000000000..37ff6c47370413045fe47305114a31cc586aeb9f Binary files /dev/null and b/examples/38c4ce6331ad_left_1/line_02.jpg differ diff --git a/examples/38c4ce6331ad_left_1/line_03.jpg b/examples/38c4ce6331ad_left_1/line_03.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ae9dc5ca13d2df3bceb7ee933d06820647a8a187 Binary files /dev/null and b/examples/38c4ce6331ad_left_1/line_03.jpg differ diff --git a/examples/38c4ce6331ad_left_1/line_04.jpg b/examples/38c4ce6331ad_left_1/line_04.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1a3a3bcab59f92f014058d69aac5520a2ae21c50 Binary files /dev/null and b/examples/38c4ce6331ad_left_1/line_04.jpg differ diff --git a/examples/38c4ce6331ad_left_1/line_05.jpg b/examples/38c4ce6331ad_left_1/line_05.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4a591a583d7ae744366dc4dbcec9b7cec3f7b10a Binary files /dev/null and b/examples/38c4ce6331ad_left_1/line_05.jpg differ diff --git a/examples/38c4ce6331ad_left_1/line_06.jpg b/examples/38c4ce6331ad_left_1/line_06.jpg new file mode 100644 index 0000000000000000000000000000000000000000..18d8928fb875792735fa2a20fa5e4dcaabead3f1 Binary files /dev/null and b/examples/38c4ce6331ad_left_1/line_06.jpg differ diff --git a/examples/38c4ce6331ad_left_1/line_07.jpg b/examples/38c4ce6331ad_left_1/line_07.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1cbcbb7dfe28b75d0f093df8d18d1f20d28645ae Binary files /dev/null and b/examples/38c4ce6331ad_left_1/line_07.jpg differ diff --git a/examples/38c4ce6331ad_left_1/line_08.jpg b/examples/38c4ce6331ad_left_1/line_08.jpg new file mode 100644 index 0000000000000000000000000000000000000000..18fa4dbb654c890c02f12682a85fd76785df5b6a Binary files /dev/null and b/examples/38c4ce6331ad_left_1/line_08.jpg differ diff --git a/examples/38c4ce6331ad_left_1/line_09.jpg b/examples/38c4ce6331ad_left_1/line_09.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c9a1ebfc63c8fdbfb791b93c4930eef127c959f0 Binary files /dev/null and b/examples/38c4ce6331ad_left_1/line_09.jpg differ diff --git a/examples/38c4ce6331ad_left_1/line_10.jpg b/examples/38c4ce6331ad_left_1/line_10.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5e5f84ba93ee3c0121aba440522b390c068fe8f2 Binary files /dev/null and b/examples/38c4ce6331ad_left_1/line_10.jpg differ diff --git a/examples/38c4ce6331ad_left_1/line_11.jpg b/examples/38c4ce6331ad_left_1/line_11.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5fbadd054fa813b37b1676e3a896369b7ed68cda Binary files /dev/null and b/examples/38c4ce6331ad_left_1/line_11.jpg differ diff --git a/examples/38c4ce6331ad_left_1/line_12.jpg b/examples/38c4ce6331ad_left_1/line_12.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0388dbfe03d708857d299cbd6f6a75eacdc83a23 Binary files /dev/null and b/examples/38c4ce6331ad_left_1/line_12.jpg differ diff --git a/examples/38c4ce6331ad_left_1/line_13.jpg b/examples/38c4ce6331ad_left_1/line_13.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f2677a0277040568abf09301745c22c2ad1d6172 Binary files /dev/null and b/examples/38c4ce6331ad_left_1/line_13.jpg differ diff --git a/examples/38c4ce6331ad_left_1/line_14.jpg b/examples/38c4ce6331ad_left_1/line_14.jpg new file mode 100644 index 0000000000000000000000000000000000000000..8ae8e5826d5be757c72c5e7a6d05a3ad82e1e7fa Binary files /dev/null and b/examples/38c4ce6331ad_left_1/line_14.jpg differ diff --git a/examples/38c4ce6331ad_left_1/line_15.jpg b/examples/38c4ce6331ad_left_1/line_15.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c17593ebf72b63953c4260b54200bfbb8a6b84c2 Binary files /dev/null and b/examples/38c4ce6331ad_left_1/line_15.jpg differ diff --git a/examples/38c4ce6331ad_left_1/line_16.jpg b/examples/38c4ce6331ad_left_1/line_16.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e2ed04764ab63d6a0c1f4c5b0284b4cddd98c4ee Binary files /dev/null and b/examples/38c4ce6331ad_left_1/line_16.jpg differ diff --git a/examples/38c4ce6331ad_left_1/region.png b/examples/38c4ce6331ad_left_1/region.png new file mode 100644 index 0000000000000000000000000000000000000000..cdf65aecbff6eb39ea4566d7888fe8ff678868a0 --- /dev/null +++ b/examples/38c4ce6331ad_left_1/region.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4488216653ec83a95f692987628b362d95e94c954aacf5d6ccd25f4f63a72e8e +size 1320084 diff --git a/examples/8d24e7df7dea_2/line_00.jpg b/examples/8d24e7df7dea_2/line_00.jpg new file mode 100644 index 0000000000000000000000000000000000000000..135f8735ada8becae3fec0170005d8aa2bb9a82d Binary files /dev/null and b/examples/8d24e7df7dea_2/line_00.jpg differ diff --git a/examples/8d24e7df7dea_2/line_01.jpg b/examples/8d24e7df7dea_2/line_01.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6b3931fe49fa07bcf48fd4096af14f3662820040 Binary files /dev/null and b/examples/8d24e7df7dea_2/line_01.jpg differ diff --git a/examples/8d24e7df7dea_2/line_02.jpg b/examples/8d24e7df7dea_2/line_02.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1c84fcbf82ccc7b6e3b92d8cca4641cc6c28dc2e Binary files /dev/null and b/examples/8d24e7df7dea_2/line_02.jpg differ diff --git a/examples/8d24e7df7dea_2/line_03.jpg b/examples/8d24e7df7dea_2/line_03.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3fc806c747e263404afc6fa983a608ec4278a70f Binary files /dev/null and b/examples/8d24e7df7dea_2/line_03.jpg differ diff --git a/examples/8d24e7df7dea_2/line_04.jpg b/examples/8d24e7df7dea_2/line_04.jpg new file mode 100644 index 0000000000000000000000000000000000000000..eade8f9fc83c458ffd56e421cadb7431750077b3 Binary files /dev/null and b/examples/8d24e7df7dea_2/line_04.jpg differ diff --git a/examples/8d24e7df7dea_2/line_05.jpg b/examples/8d24e7df7dea_2/line_05.jpg new file mode 100644 index 0000000000000000000000000000000000000000..538c935a0b08d29e2495237babacfe47f450d368 Binary files /dev/null and b/examples/8d24e7df7dea_2/line_05.jpg differ diff --git a/examples/8d24e7df7dea_2/line_06.jpg b/examples/8d24e7df7dea_2/line_06.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f2c8d97b4a6bfc84a14b883849ddd4a0171e1c2f Binary files /dev/null and b/examples/8d24e7df7dea_2/line_06.jpg differ diff --git a/examples/8d24e7df7dea_2/line_07.jpg b/examples/8d24e7df7dea_2/line_07.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3d293e715c03eff2d3266dfc678b1c2295f91881 Binary files /dev/null and b/examples/8d24e7df7dea_2/line_07.jpg differ diff --git a/examples/8d24e7df7dea_2/line_08.jpg b/examples/8d24e7df7dea_2/line_08.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e6b7240bc372cf23ce51b8f9f78cb2503aa080e7 Binary files /dev/null and b/examples/8d24e7df7dea_2/line_08.jpg differ diff --git a/examples/8d24e7df7dea_2/line_09.jpg b/examples/8d24e7df7dea_2/line_09.jpg new file mode 100644 index 0000000000000000000000000000000000000000..421972dbae82671a190c35630cde349ce6a2d75b Binary files /dev/null and b/examples/8d24e7df7dea_2/line_09.jpg differ diff --git a/examples/8d24e7df7dea_2/region.png b/examples/8d24e7df7dea_2/region.png new file mode 100644 index 0000000000000000000000000000000000000000..01879589ec485ddb4d7424612e658a48f2ec1560 --- /dev/null +++ b/examples/8d24e7df7dea_2/region.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cbf6eb9398a88a7c4bac9b39c45f2e95f394ca97dce4c8f4174cde047907ec4c +size 2134539 diff --git a/examples/eed569a6699c_left_3/line_00.jpg b/examples/eed569a6699c_left_3/line_00.jpg new file mode 100644 index 0000000000000000000000000000000000000000..09f48a81d8035c40ade76a10821e1f3dbb3a1739 Binary files /dev/null and b/examples/eed569a6699c_left_3/line_00.jpg differ diff --git a/examples/eed569a6699c_left_3/line_01.jpg b/examples/eed569a6699c_left_3/line_01.jpg new file mode 100644 index 0000000000000000000000000000000000000000..efbd51f6503ce2f5741cbf4849a25801c9846855 Binary files /dev/null and b/examples/eed569a6699c_left_3/line_01.jpg differ diff --git a/examples/eed569a6699c_left_3/line_02.jpg b/examples/eed569a6699c_left_3/line_02.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3e36761e3fefa1da309eac1ab95da729203db505 Binary files /dev/null and b/examples/eed569a6699c_left_3/line_02.jpg differ diff --git a/examples/eed569a6699c_left_3/line_03.jpg b/examples/eed569a6699c_left_3/line_03.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3e6944886698329ff4132e9b32003cd8bb89e167 Binary files /dev/null and b/examples/eed569a6699c_left_3/line_03.jpg differ diff --git a/examples/eed569a6699c_left_3/line_04.jpg b/examples/eed569a6699c_left_3/line_04.jpg new file mode 100644 index 0000000000000000000000000000000000000000..05d1ad5ea9dc00495527286cdb4ac4060c040b37 Binary files /dev/null and b/examples/eed569a6699c_left_3/line_04.jpg differ diff --git a/examples/eed569a6699c_left_3/line_05.jpg b/examples/eed569a6699c_left_3/line_05.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c2b6f3e46e630522633d378f41efc67a8b300acb Binary files /dev/null and b/examples/eed569a6699c_left_3/line_05.jpg differ diff --git a/examples/eed569a6699c_left_3/line_06.jpg b/examples/eed569a6699c_left_3/line_06.jpg new file mode 100644 index 0000000000000000000000000000000000000000..31536bb299762894d26fc0860edec002992c2c68 Binary files /dev/null and b/examples/eed569a6699c_left_3/line_06.jpg differ diff --git a/examples/eed569a6699c_left_3/line_07.jpg b/examples/eed569a6699c_left_3/line_07.jpg new file mode 100644 index 0000000000000000000000000000000000000000..87f119bf75867716f888c202c8a9f909b6ade749 --- /dev/null +++ b/examples/eed569a6699c_left_3/line_07.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ebf62f2af0c3ea49c5181645f1556f2117246815e94510e68095667cd725816 +size 106037 diff --git a/examples/eed569a6699c_left_3/line_08.jpg b/examples/eed569a6699c_left_3/line_08.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6dee9e04d510b2501e0296752c69e8d248ffd63c --- /dev/null +++ b/examples/eed569a6699c_left_3/line_08.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c09a51e8967047270142a85a5e4fa855a03b38025adf3a35f9b000c6de33a62d +size 104501 diff --git a/examples/eed569a6699c_left_3/region.png b/examples/eed569a6699c_left_3/region.png new file mode 100644 index 0000000000000000000000000000000000000000..c2a6e944481324160b6a7c2f1bd00f0322e52142 --- /dev/null +++ b/examples/eed569a6699c_left_3/region.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d97f04ee67a3903feea2af175f824041aabb64ecfb1a4cc951b99ef70194da0f +size 3904704 diff --git a/examples/examples.json b/examples/examples.json new file mode 100644 index 0000000000000000000000000000000000000000..e1e3b9e0dba0cbf0ef1814857012b908c5d506c5 --- /dev/null +++ b/examples/examples.json @@ -0,0 +1,147 @@ +[ + { + "id": "8d24e7df7dea_2", + "collection": "GT-RA_alvsborgs_losen_20260211", + "volume": "Norrland_20", + "scan": "B0001019_00042.jpeg", + "lines": [ + "Ålebo", + "Anders perss", + "Silff — 2 1/2 lod — 1 quntn", + "koppar — 2 lb p 5 mk — 13 1/2 öre", + "koor — 6 st — 6 mk", + "3 ars stutar — 2 st — 1 mk", + "2 ars stut — 2 st — 4 öre", + "fåår — 5 st — 5 öre", + "suin — 3 st — 3 öre", + "loper pngr 10 mk 1 1/2 öre" + ], + "region_size": [ + 1587, + 1137 + ] + }, + { + "id": "19a1b2195bab_right_0", + "collection": "GT-RA_svea_hovratt_renskrivna_protokoll_20260218", + "volume": "Svea_hovrätt,_Renskrivna_protokoll,_1713_(jan-juni)", + "scan": "A0068632_00056.jpg", + "lines": [ + "den 27 Januarii", + "med mehra, Communicerad, med", + "Ståthållaren Wälb: Gustaf A¬", + "dolf Strömfelt, at innan otta", + "dagar inkomma med hwad", + "härwid kan wara till påminna,", + "wid tije dal.r S:mts", + "wijte." + ], + "region_size": [ + 1559, + 1158 + ] + }, + { + "id": "eed569a6699c_left_3", + "collection": "GT-SSA_politikollegiet_20260218", + "volume": "SSA_Politikollegiet_8-15", + "scan": "2104_aaaaaaaaaa1763 (17).jpg", + "lines": [ + "S: D: Uti närwaro af Dire¬", + "cteuren Ädel och Högachtad", + "Herr Gerhard Meijer uplästes", + "Höglofl: Kongl: Politie och Brand¬", + "Commissionens utdrag af Pro¬", + "tocollet d: 8 i denne månad,", + "af innehåll, at som Herr", + "Directeuren, efter Commissio¬", + "nens fastställande, förfär" + ], + "region_size": [ + 1479, + 1220 + ] + }, + { + "id": "f970d28ac08b_left_0", + "collection": "GT-SSA_stadens_kamnarsratt_20260218", + "volume": "SSA_Stadens_kämnärsrätt_5-8", + "scan": "2390_dod (88).jpg", + "lines": [ + "O.", + "Olofs dotter Greta, 236.", + "P.", + "Pipping, Agneta. 120. 140,", + "Phannenstill, Carl. 346.", + "Pers dotter Stina. 371.", + "Prech, Christian, 513.", + "Pohhieth Greta, 710. 724.", + "Person Erik. 765.", + "Putzar, Anna, Beata, 772.", + "Palm Olof 964." + ], + "region_size": [ + 931, + 1939 + ] + }, + { + "id": "38c4ce6331ad_left_1", + "collection": "GT-RA_svea_hovratt_renskrivna_protokoll_20260218", + "volume": "Svea_hovrätt,_Renskrivna_protokoll,_1713_(jan-juni)", + "scan": "A0068632_00053.jpg", + "lines": [ + "den 23 Januarii", + "Låtit utfärda constutorium för Vice", + "Notarien Wälb: Thomas Wadenstierna,", + "hwarigenom han effter Kong. Maijttz till", + "Justitiens administrerande förordnande", + "och befullmächtigade Hh.r Rådz tillstån", + "blifwit förordnad, uti häradhöfdin¬", + "gens Wälb:de Johan Engelbrecht Grewes¬", + "möhlens ställe, och under des frånwaro", + "ifrån den honom i nåder anförtrodde", + "jurisdictionen, emedlertid de därwid för¬", + "fallande så ordinarie som extraordinar", + "syßlor effter aflagd dommare ed", + "at förrätta: Altßå blef bem:te", + "Wadenstierna nu inkallad, och med", + "hand å book aflade den wahnliga", + "tro¬ och huldhets, samt dommare eden" + ], + "region_size": [ + 1118, + 1614 + ] + }, + { + "id": "35ffe6b8b600_left_0", + "collection": "GT-SSA_stadens_kamnarsratt_20260218", + "volume": "SSA_Stadens_kämnärsrätt_5-8", + "scan": "2561_alpha (166).jpg", + "lines": [ + "hus, tå han förut bodt ett halfft", + "åhr här inne uti Staden hos", + "Sockerbagaren Halling; Så hade", + "Rätten till i dag giordt an¬", + "stalt till thetta måhlets före¬", + "tagande, och låtit upkalla nå¬", + "gra af Fiscalen Stadz vice Fi¬", + "scalen wälbde Carl Johan Eke¬", + "Roth, såsom å Embetes wägr", + "häruti åklagare, nemde och", + "åberopade wittne, hwarom", + "Siöberg äfwen blifwit till¬", + "sagd, och han nu till then än¬", + "dan, i närwaro af Fiscalen", + "Nieroth utur häktet förekal¬", + "lades, och ingaf Siöberg", + "en skrifft lydande then sam¬", + "ma ord ifrån ord som följer:" + ], + "region_size": [ + 1225, + 1473 + ] + } +] \ No newline at end of file diff --git a/examples/f970d28ac08b_left_0/line_00.jpg b/examples/f970d28ac08b_left_0/line_00.jpg new file mode 100644 index 0000000000000000000000000000000000000000..12889c20821f01a8c7beb0cc23458fecf6544f80 Binary files /dev/null and b/examples/f970d28ac08b_left_0/line_00.jpg differ diff --git a/examples/f970d28ac08b_left_0/line_01.jpg b/examples/f970d28ac08b_left_0/line_01.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c6cfaa6793a9a3a38c559a466a4ffadcd14cfb83 Binary files /dev/null and b/examples/f970d28ac08b_left_0/line_01.jpg differ diff --git a/examples/f970d28ac08b_left_0/line_02.jpg b/examples/f970d28ac08b_left_0/line_02.jpg new file mode 100644 index 0000000000000000000000000000000000000000..080294d222f7e5306f75e21e916dbe0142356a86 Binary files /dev/null and b/examples/f970d28ac08b_left_0/line_02.jpg differ diff --git a/examples/f970d28ac08b_left_0/line_03.jpg b/examples/f970d28ac08b_left_0/line_03.jpg new file mode 100644 index 0000000000000000000000000000000000000000..90aa3d98f829551c869d0e59c4784a4a95761f8e Binary files /dev/null and b/examples/f970d28ac08b_left_0/line_03.jpg differ diff --git a/examples/f970d28ac08b_left_0/line_04.jpg b/examples/f970d28ac08b_left_0/line_04.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a76b60076ae23d0ebc23ec6a6d34da8f8c2e6014 Binary files /dev/null and b/examples/f970d28ac08b_left_0/line_04.jpg differ diff --git a/examples/f970d28ac08b_left_0/line_05.jpg b/examples/f970d28ac08b_left_0/line_05.jpg new file mode 100644 index 0000000000000000000000000000000000000000..877e20baa5bb5dcbcadfa872f8a8f5dd00d4b696 Binary files /dev/null and b/examples/f970d28ac08b_left_0/line_05.jpg differ diff --git a/examples/f970d28ac08b_left_0/line_06.jpg b/examples/f970d28ac08b_left_0/line_06.jpg new file mode 100644 index 0000000000000000000000000000000000000000..59c0654afd871dc2a3394a476c78c73afc866697 Binary files /dev/null and b/examples/f970d28ac08b_left_0/line_06.jpg differ diff --git a/examples/f970d28ac08b_left_0/line_07.jpg b/examples/f970d28ac08b_left_0/line_07.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a51188a6efdff729d500c971c09f056d52f88afc Binary files /dev/null and b/examples/f970d28ac08b_left_0/line_07.jpg differ diff --git a/examples/f970d28ac08b_left_0/line_08.jpg b/examples/f970d28ac08b_left_0/line_08.jpg new file mode 100644 index 0000000000000000000000000000000000000000..2b96f4cc7406949bb5238c800b6c32de082c93bf Binary files /dev/null and b/examples/f970d28ac08b_left_0/line_08.jpg differ diff --git a/examples/f970d28ac08b_left_0/line_09.jpg b/examples/f970d28ac08b_left_0/line_09.jpg new file mode 100644 index 0000000000000000000000000000000000000000..bacb2236ed70d857a5a36b8d0b28236e46bc793e Binary files /dev/null and b/examples/f970d28ac08b_left_0/line_09.jpg differ diff --git a/examples/f970d28ac08b_left_0/line_10.jpg b/examples/f970d28ac08b_left_0/line_10.jpg new file mode 100644 index 0000000000000000000000000000000000000000..89cb37081150f019aad761f79194b0389eb86b49 Binary files /dev/null and b/examples/f970d28ac08b_left_0/line_10.jpg differ diff --git a/examples/f970d28ac08b_left_0/region.png b/examples/f970d28ac08b_left_0/region.png new file mode 100644 index 0000000000000000000000000000000000000000..bb1dc5465eb8921200c37498ab22ff30e6698c9c --- /dev/null +++ b/examples/f970d28ac08b_left_0/region.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d1466c9a07749f64e4d73864cf10b68ee917b744251456d491407c135a7f21be +size 3081348 diff --git a/jev_prompt.py b/jev_prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..c68a592fed78570112c30021dee59bab8d6ba5dc --- /dev/null +++ b/jev_prompt.py @@ -0,0 +1,43 @@ +"""MiniCPM-OCR-Jev's prompt, ours in English: the crop, the candidate text, its rendering, then the instruction to +judge whether they match. Jev is fine-tuned on pairs in this prompt; its fingerprint (:func:`prompt_digest`) is in +every pair's meta, and a Jev run refuses pairs built in another wording, which would change what the scores mean. + +In a training sample (:func:`sample_prompt`) the two images are ms-swift's ```` placeholders, each followed by a +line break; the model reads the turn as :func:`model_prompt` gives it (original image, the candidate text, its +rendering, the instruction, then the empty assistant turn whose last token is pooled).""" + +from __future__ import annotations + +import hashlib + +IMAGE = "" # ms-swift's placeholder; the qwen3_5 template shows it as QWEN_IMAGE +QWEN_IMAGE = "<|vision_start|><|image_pad|><|vision_end|>" +ASSISTANT_TURN = "<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" +TEXT_LABEL = "OCR text:" +INSTRUCTION = ( + "The first image is the original; the second image is the OCR text above rendered as an image.\n" + "Judge whether the OCR text and its rendering match the content of the original exactly.\n" + "This is a binary classification: label 1 if they match, 0 if they do not." +) + + +def _turn(text: str, image: str) -> str: + return f"{image}\n{TEXT_LABEL}\n{text}\n{image}\n{INSTRUCTION}" + + +def sample_prompt(text: str) -> str: + """The user turn of a Jev training sample for the candidate ``text``, as given: its crop's placeholder, the text, + its rendering's placeholder and the instruction.""" + return _turn(text, IMAGE) + + +def model_prompt(text: str) -> str: + """The whole prompt Jev reads for the candidate ``text``: the user turn with Qwen3.5's image tokens and the empty + assistant turn.""" + return f"<|im_start|>user\n{_turn(text, QWEN_IMAGE)}{ASSISTANT_TURN}" + + +def prompt_digest() -> str: + """The prompt's fingerprint: the first 12 hex digits of the md5 of :func:`model_prompt` with ``{text}`` for the + text.""" + return hashlib.md5(model_prompt("{text}").encode("utf-8")).hexdigest()[:12] diff --git a/jev_render.py b/jev_render.py new file mode 100644 index 0000000000000000000000000000000000000000..925b188f21f8cd5849037422d500a6f34953ec03 --- /dev/null +++ b/jev_render.py @@ -0,0 +1,48 @@ +"""Our renderer of Jev's candidate texts, frozen once pairs are built with it (a new renderer is a new input +distribution): a candidate drawn black on white on one line, as tall and as wide as its crop, in one font at the +largest size that fits both (no smaller than :data:`MIN_SIZE`), laid out by FreeType's basic layout (not Raqm's, which +may or may not be installed). Its version (:func:`renderer_version`) names the rule, the font's digest and the Pillow +and FreeType that draw it; every pair's meta records it, and a Jev run refuses pairs of another.""" + +from __future__ import annotations + +import hashlib +from importlib.metadata import version +from pathlib import Path + +from PIL import Image, ImageDraw, ImageFont, features + +RULE = "htr-train-jev-render-1" # the rule below; change it with the rule +MARGIN = 4 # px left of the text +MIN_SIZE = 8 # pt: a long candidate is drawn this small, and runs over the right edge + + +def renderer_version(font: Path) -> str: + """The renderer's version: its rule, the first 12 hex digits of the font file's sha256, and the Pillow and + FreeType versions (``htr-train-jev-render-1++pillow-+freetype-``).""" + digest = hashlib.sha256(font.read_bytes()).hexdigest()[:12] + return f"{RULE}+{digest}+pillow-{version('pillow')}+freetype-{features.version('freetype2')}" + + +def _face(font: Path, points: int) -> ImageFont.FreeTypeFont: + return ImageFont.truetype(str(font), points, layout_engine=ImageFont.Layout.BASIC) + + +def _fitting_font(text: str, font: Path, size: tuple[int, int]) -> ImageFont.FreeTypeFont: + """The font at the largest size, from 70 % of the height down, whose ``text`` fits the width less the margins.""" + width, height = size + points = max(MIN_SIZE, round(height * 0.7)) + face = _face(font, points) + while points > MIN_SIZE and face.getlength(text) > width - 2 * MARGIN: + points -= 1 + face = _face(font, points) + return face + + +def render_text(text: str, font: Path, size: tuple[int, int]) -> Image.Image: + """``text`` drawn black on white in an RGB image of ``size`` (width, height), on one line, left at + :data:`MARGIN` and centred on the height.""" + image = Image.new("RGB", size, "white") + face = _fitting_font(text, font, size) + ImageDraw.Draw(image).text((MARGIN, size[1] / 2), text, fill="black", font=face, anchor="lm") + return image diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..48dc713d94ff4c5070060f4118f18703d4ae31b3 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,7 @@ +torch==2.13.0 +torchvision==0.28.0 +transformers==5.22.1 +pillow==12.2.0 +flash-linear-attention==0.6.0 +safetensors +rapidfuzz