Spaces:
Running on Zero
Running on Zero
Swedish HTR speed and Jev: TrOCR vs MiniCPM-OCR alone and with its DSpark draft (PyTorch on CUDA graphs), Jev per line
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +9 -0
- .ruff_cache/.gitignore +2 -0
- .ruff_cache/0.17.4/10670050264457222690 +0 -0
- .ruff_cache/0.17.4/8792248902311164429 +0 -0
- .ruff_cache/CACHEDIR.TAG +1 -0
- DejaVuSans.ttf +3 -0
- HOW_IT_WORKS.md +57 -0
- README.md +21 -6
- app.py +411 -0
- dspark_hf.py +604 -0
- examples/19a1b2195bab_right_0/line_00.jpg +0 -0
- examples/19a1b2195bab_right_0/line_01.jpg +0 -0
- examples/19a1b2195bab_right_0/line_02.jpg +0 -0
- examples/19a1b2195bab_right_0/line_03.jpg +0 -0
- examples/19a1b2195bab_right_0/line_04.jpg +0 -0
- examples/19a1b2195bab_right_0/line_05.jpg +0 -0
- examples/19a1b2195bab_right_0/line_06.jpg +0 -0
- examples/19a1b2195bab_right_0/line_07.jpg +0 -0
- examples/19a1b2195bab_right_0/region.png +3 -0
- examples/35ffe6b8b600_left_0/line_00.jpg +0 -0
- examples/35ffe6b8b600_left_0/line_01.jpg +0 -0
- examples/35ffe6b8b600_left_0/line_02.jpg +0 -0
- examples/35ffe6b8b600_left_0/line_03.jpg +0 -0
- examples/35ffe6b8b600_left_0/line_04.jpg +0 -0
- examples/35ffe6b8b600_left_0/line_05.jpg +0 -0
- examples/35ffe6b8b600_left_0/line_06.jpg +0 -0
- examples/35ffe6b8b600_left_0/line_07.jpg +0 -0
- examples/35ffe6b8b600_left_0/line_08.jpg +0 -0
- examples/35ffe6b8b600_left_0/line_09.jpg +0 -0
- examples/35ffe6b8b600_left_0/line_10.jpg +0 -0
- examples/35ffe6b8b600_left_0/line_11.jpg +0 -0
- examples/35ffe6b8b600_left_0/line_12.jpg +0 -0
- examples/35ffe6b8b600_left_0/line_13.jpg +0 -0
- examples/35ffe6b8b600_left_0/line_14.jpg +0 -0
- examples/35ffe6b8b600_left_0/line_15.jpg +0 -0
- examples/35ffe6b8b600_left_0/line_16.jpg +0 -0
- examples/35ffe6b8b600_left_0/line_17.jpg +0 -0
- examples/35ffe6b8b600_left_0/region.png +3 -0
- examples/38c4ce6331ad_left_1/line_00.jpg +0 -0
- examples/38c4ce6331ad_left_1/line_01.jpg +0 -0
- examples/38c4ce6331ad_left_1/line_02.jpg +0 -0
- examples/38c4ce6331ad_left_1/line_03.jpg +0 -0
- examples/38c4ce6331ad_left_1/line_04.jpg +0 -0
- examples/38c4ce6331ad_left_1/line_05.jpg +0 -0
- examples/38c4ce6331ad_left_1/line_06.jpg +0 -0
- examples/38c4ce6331ad_left_1/line_07.jpg +0 -0
- examples/38c4ce6331ad_left_1/line_08.jpg +0 -0
- examples/38c4ce6331ad_left_1/line_09.jpg +0 -0
- examples/38c4ce6331ad_left_1/line_10.jpg +0 -0
- examples/38c4ce6331ad_left_1/line_11.jpg +0 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,12 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
DejaVuSans.ttf filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
examples/19a1b2195bab_right_0/region.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
examples/35ffe6b8b600_left_0/region.png filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
examples/38c4ce6331ad_left_1/region.png filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
examples/8d24e7df7dea_2/region.png filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
examples/eed569a6699c_left_3/line_07.jpg filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
examples/eed569a6699c_left_3/line_08.jpg filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
examples/eed569a6699c_left_3/region.png filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
examples/f970d28ac08b_left_0/region.png filter=lfs diff=lfs merge=lfs -text
|
.ruff_cache/.gitignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Automatically created by ruff.
|
| 2 |
+
*
|
.ruff_cache/0.17.4/10670050264457222690
ADDED
|
Binary file (356 Bytes). View file
|
|
|
.ruff_cache/0.17.4/8792248902311164429
ADDED
|
Binary file (268 Bytes). View file
|
|
|
.ruff_cache/CACHEDIR.TAG
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Signature: 8a477f597d28d172789f06886806bc55
|
DejaVuSans.ttf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ae7b7855e115a5966d8b1b3f80f254ccc117ec86f9965e202ee2940453837280
|
| 3 |
+
size 759720
|
HOW_IT_WORKS.md
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
### What is timed
|
| 2 |
+
|
| 3 |
+
Each reader is timed from the images to the text, preprocessing included, on the same GPU (ZeroGPU: half an RTX PRO
|
| 4 |
+
6000 Blackwell), after a warm-up that is not timed:
|
| 5 |
+
|
| 6 |
+
- **Swedish Lion TrOCR** (Riksarkivet's Swedish Lion Libre 2026, large, character-based) reads the region's lines,
|
| 7 |
+
all in one batch, greedily, in float32 as Riksarkivet runs it.
|
| 8 |
+
- **MiniCPM-OCR reader alone** reads the whole region in one request, one token per pass, greedily.
|
| 9 |
+
- **Reader + DSpark draft**: the draft proposes 15 tokens at a time; the reader checks them in one pass and keeps the
|
| 10 |
+
ones it agrees with, plus one of its own. Greedy decoding, so the text is the reader's own.
|
| 11 |
+
|
| 12 |
+
### Why the draft makes it faster
|
| 13 |
+
|
| 14 |
+
Decoding one token at a time reads every weight of the reader for each token. A check of 16 tokens costs about the
|
| 15 |
+
same pass, and the reader keeps on average about 8 of them (the acceptance length). The draft is small (5 layers) and
|
| 16 |
+
reads the reader's own hidden states, so its guesses are cheap and usually right. It helps most when one region is
|
| 17 |
+
read at a time and its text is long; reading many requests at once keeps the GPU busy anyway.
|
| 18 |
+
|
| 19 |
+
### How it runs here
|
| 20 |
+
|
| 21 |
+
vLLM runs the draft natively, but vLLM cannot run on ZeroGPU, so this Space decodes in PyTorch. Profiled with
|
| 22 |
+
`torch.profiler`, eager decoding was launch-bound (about 1,500 small kernels a pass, the GPU busy 12 % of the time), so:
|
| 23 |
+
|
| 24 |
+
1. Each reader pass is replayed from a **CUDA graph** (transformers' StaticCache, the attention mask built on the GPU),
|
| 25 |
+
for the reader alone and with the draft alike.
|
| 26 |
+
2. The draft's whole proposal, its Markov sampling included, is **one graph**.
|
| 27 |
+
3. **One reader pass per draft block.** The reader is hybrid: its linear-attention layers keep a recurrent state that
|
| 28 |
+
cannot be cut back after rejected guesses. The checking pass keeps each such layer's inputs for the block, and the
|
| 29 |
+
state is rebuilt over the accepted tokens only (a few kernels instead of a second pass).
|
| 30 |
+
|
| 31 |
+
Measured on our server (12 dev regions, a full RTX PRO 6000 shared with a training run): the reader alone 31.5 s,
|
| 32 |
+
with DSpark 6.8 s (**4.6×**); the eager reader alone, before these changes, about 2× slower than the first.
|
| 33 |
+
|
| 34 |
+
### The same models in vLLM
|
| 35 |
+
|
| 36 |
+
On 1,000 test lines and 200 dev regions, one GPU per server (the draft's model card):
|
| 37 |
+
|
| 38 |
+
| | one at a time | 64 at a time |
|
| 39 |
+
|---|---|---|
|
| 40 |
+
| lines: reader alone → with DSpark | 13.3 → 18.2 lines/s (1.37×) | 74.6 → 82.2 lines/s (1.10×) |
|
| 41 |
+
| regions: reader alone → with DSpark | 1.95 → 4.08 regions/s (2.09×) | 12.4 → 13.2 regions/s (1.07×) |
|
| 42 |
+
|
| 43 |
+
Acceptance length 8.72; the character error rate is the same with and without the draft.
|
| 44 |
+
|
| 45 |
+
### Jev
|
| 46 |
+
|
| 47 |
+
Jev compares the line image with the candidate text drawn as an image (`@RENDERER@`) and returns a score from 0 to 1.
|
| 48 |
+
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
|
| 49 |
+
threshold). Picking, line by line, the reading Jev scores higher is one way to combine two readers.
|
| 50 |
+
|
| 51 |
+
### Limits
|
| 52 |
+
|
| 53 |
+
- The examples are from GT-Lejonet's dev volumes; other hands and periods read worse.
|
| 54 |
+
- Near-greedy decoding can repeat a phrase to the token limit on dense pages (a loop); such a reading is wrong from
|
| 55 |
+
where it starts.
|
| 56 |
+
- Timings vary with the GPU slice and the queue; the first request of a fresh worker captures its CUDA graphs first
|
| 57 |
+
(not counted in the timings shown).
|
README.md
CHANGED
|
@@ -1,13 +1,28 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
colorFrom: green
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.31.0
|
| 8 |
-
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Swedish HTR speed and Jev
|
| 3 |
+
emoji: 🪶
|
| 4 |
colorFrom: green
|
| 5 |
+
colorTo: gray
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.31.0
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
+
python_version: "3.12"
|
| 10 |
+
short_description: TrOCR vs MiniCPM-OCR with a DSpark draft, and Jev
|
| 11 |
+
license: apache-2.0
|
| 12 |
+
startup_duration_timeout: 1h
|
| 13 |
+
models:
|
| 14 |
+
- Gabriel/diffu-minicpm-ocr-htr
|
| 15 |
+
- Gabriel/diffu-minicpm-ocr-htr-dspark
|
| 16 |
+
- Gabriel/diffu-minicpm-ocr-htr-jev
|
| 17 |
+
- Gabriel/swedish-lion-trocr-large-handwritten-char
|
| 18 |
---
|
| 19 |
|
| 20 |
+
# Swedish HTR speed and Jev
|
| 21 |
+
|
| 22 |
+
Reads a handwritten text region three ways on the same GPU and times each: the Swedish Lion TrOCR line by line, the
|
| 23 |
+
[MiniCPM-OCR HTR reader](https://huggingface.co/Gabriel/diffu-minicpm-ocr-htr) on the whole region, and the same reader
|
| 24 |
+
with its [DSpark draft](https://huggingface.co/Gabriel/diffu-minicpm-ocr-htr-dspark). Then
|
| 25 |
+
[Jev](https://huggingface.co/Gabriel/diffu-minicpm-ocr-htr-jev), the reader's proof-reader, scores each line's readings.
|
| 26 |
+
|
| 27 |
+
Decoding runs in PyTorch on CUDA graphs (`dspark_hf.py`); see the app's "How it works" tab. Part of
|
| 28 |
+
[diffu](https://github.com/Borg93/diffu2).
|
app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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reading Swedish handwriting: the Swedish Lion TrOCR against our MiniCPM-OCR reader, alone and with its DSpark
|
| 2 |
+
draft, timed on the same region; and Jev, the reader's proof-reader, scoring each line's readings.
|
| 3 |
+
|
| 4 |
+
Everything runs in PyTorch on ZeroGPU (vLLM, where the draft normally runs, cannot run here): the reader's passes and
|
| 5 |
+
the draft's proposals are replayed from CUDA graphs (dspark_hf.py), for the reader alone and with the draft alike.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import io
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import threading
|
| 12 |
+
import time
|
| 13 |
+
from collections.abc import Callable
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Any, TypeVar
|
| 16 |
+
|
| 17 |
+
import gradio as gr
|
| 18 |
+
import pandas as pd
|
| 19 |
+
import spaces # before torch: ZeroGPU patches CUDA
|
| 20 |
+
import torch
|
| 21 |
+
from huggingface_hub import snapshot_download
|
| 22 |
+
from PIL import Image
|
| 23 |
+
from pydantic import BaseModel
|
| 24 |
+
from rapidfuzz.distance import Levenshtein
|
| 25 |
+
from transformers import (
|
| 26 |
+
AutoModelForImageTextToText,
|
| 27 |
+
AutoProcessor,
|
| 28 |
+
Qwen3_5ForSequenceClassification,
|
| 29 |
+
TrOCRProcessor,
|
| 30 |
+
VisionEncoderDecoderModel,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
import dspark_hf as D
|
| 34 |
+
from jev_prompt import model_prompt
|
| 35 |
+
from jev_render import render_text, renderer_version
|
| 36 |
+
|
| 37 |
+
READER = "Gabriel/diffu-minicpm-ocr-htr"
|
| 38 |
+
DRAFT = "Gabriel/diffu-minicpm-ocr-htr-dspark"
|
| 39 |
+
JEV = "Gabriel/diffu-minicpm-ocr-htr-jev"
|
| 40 |
+
TROCR = os.environ.get("TROCR_REPO", "Gabriel/swedish-lion-trocr-large-handwritten-char") # private copy
|
| 41 |
+
HERE = Path(__file__).parent
|
| 42 |
+
FONT = HERE / "DejaVuSans.ttf"
|
| 43 |
+
EXAMPLES: list[dict[str, Any]] = json.loads((HERE / "examples" / "examples.json").read_text(encoding="utf-8"))
|
| 44 |
+
MAX_LEN = 8192 # the reader's cache: the longest prompt (a region's image) and its reading
|
| 45 |
+
MINICPM_IMAGES = {"downsample_mode": "4x", "max_slice_nums": 9} # OpenBMB's settings, as the reader was trained
|
| 46 |
+
JEV_HEIGHT, JEV_JPEG = 48, 95 # Jev's line crops, as its training pairs were cut
|
| 47 |
+
T = TypeVar("T")
|
| 48 |
+
|
| 49 |
+
# On CUDA at module level, as ZeroGPU asks: the weights move to the GPU when a GPU call starts.
|
| 50 |
+
processor = AutoProcessor.from_pretrained(READER)
|
| 51 |
+
reader = AutoModelForImageTextToText.from_pretrained(READER, dtype=torch.bfloat16).to("cuda").eval()
|
| 52 |
+
draft = D.DSparkDraft.from_folder(snapshot_download(DRAFT), reader.get_input_embeddings())
|
| 53 |
+
draft = draft.to("cuda", torch.bfloat16).eval()
|
| 54 |
+
_eos = reader.generation_config.eos_token_id
|
| 55 |
+
EOS: set[int] = set(_eos) if isinstance(_eos, list) else {int(_eos)}
|
| 56 |
+
jev_processor = AutoProcessor.from_pretrained(JEV)
|
| 57 |
+
jev = Qwen3_5ForSequenceClassification.from_pretrained(JEV, num_labels=2, dtype=torch.bfloat16).to("cuda").eval()
|
| 58 |
+
trocr_processor = TrOCRProcessor.from_pretrained(TROCR)
|
| 59 |
+
trocr = VisionEncoderDecoderModel.from_pretrained(TROCR).to("cuda").eval() # float32, as Riksarkivet runs it
|
| 60 |
+
|
| 61 |
+
_engines: dict[int, D.FastDSpark] = {} # per GPU worker process: CUDA graphs belong to the process that captured them
|
| 62 |
+
_lock = threading.Lock()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class JevLine(BaseModel):
|
| 66 |
+
"""Jev's scores of one line's TrOCR reading and, when the reader's region reading splits into as many lines, of
|
| 67 |
+
the reader's."""
|
| 68 |
+
|
| 69 |
+
trocr: str
|
| 70 |
+
trocr_score: float
|
| 71 |
+
minicpm: str | None = None
|
| 72 |
+
minicpm_score: float | None = None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class Comparison(BaseModel):
|
| 76 |
+
"""One region read three ways: each reading, its seconds, and the draft's counters."""
|
| 77 |
+
|
| 78 |
+
truth: list[str] | None
|
| 79 |
+
trocr: list[str] | None = None
|
| 80 |
+
trocr_seconds: float | None = None
|
| 81 |
+
plain: str
|
| 82 |
+
plain_seconds: float
|
| 83 |
+
plain_passes: int
|
| 84 |
+
dspark: str
|
| 85 |
+
dspark_seconds: float
|
| 86 |
+
dspark_passes: int
|
| 87 |
+
tokens: int
|
| 88 |
+
acceptance: float
|
| 89 |
+
identical: bool
|
| 90 |
+
jev: list[JevLine] | None = None
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _example(example_id: str) -> dict[str, Any]:
|
| 94 |
+
return next(e for e in EXAMPLES if e["id"] == example_id)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _region_inputs(image: Image.Image) -> dict[str, Any]:
|
| 98 |
+
content = [{"type": "image", "image": image}, {"type": "text", "text": "Text Recognition:"}]
|
| 99 |
+
batch = processor.apply_chat_template(
|
| 100 |
+
[{"role": "user", "content": content}],
|
| 101 |
+
add_generation_prompt=True,
|
| 102 |
+
tokenize=True,
|
| 103 |
+
return_dict=True,
|
| 104 |
+
return_tensors="pt",
|
| 105 |
+
enable_thinking=False,
|
| 106 |
+
processor_kwargs=MINICPM_IMAGES,
|
| 107 |
+
)
|
| 108 |
+
inputs = dict(batch.to("cuda"))
|
| 109 |
+
inputs["downsample_mode"] = MINICPM_IMAGES["downsample_mode"]
|
| 110 |
+
return inputs
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _trocr_read(lines: list[Image.Image], max_new_tokens: int = 128) -> list[str]:
|
| 114 |
+
"""TrOCR's greedy readings of a batch of lines, as Riksarkivet's evaluation runs it: the Swedish Lion starts
|
| 115 |
+
decoding from its config's token (its generation_config names another, which costs about 2 points of CER), and
|
| 116 |
+
its 192 x 1024 inputs need the position encoding interpolated."""
|
| 117 |
+
pixels = trocr_processor(images=lines, return_tensors="pt").pixel_values.to("cuda")
|
| 118 |
+
ids = trocr.generate(
|
| 119 |
+
pixels,
|
| 120 |
+
decoder_start_token_id=trocr.config.decoder_start_token_id,
|
| 121 |
+
interpolate_pos_encoding=True,
|
| 122 |
+
num_beams=1,
|
| 123 |
+
max_new_tokens=max_new_tokens,
|
| 124 |
+
)
|
| 125 |
+
return [text.strip() for text in trocr_processor.batch_decode(ids, skip_special_tokens=True)]
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _jev_crop(line: Image.Image) -> Image.Image:
|
| 129 |
+
"""A line's crop as Jev was trained on it: 48 pixels high, its aspect kept, through JPEG at quality 95."""
|
| 130 |
+
image = line.convert("RGB")
|
| 131 |
+
if image.height != JEV_HEIGHT:
|
| 132 |
+
width = max(1, round(image.width * JEV_HEIGHT / image.height))
|
| 133 |
+
image = image.resize((width, JEV_HEIGHT), Image.Resampling.LANCZOS)
|
| 134 |
+
buffer = io.BytesIO()
|
| 135 |
+
image.save(buffer, format="JPEG", quality=JEV_JPEG)
|
| 136 |
+
return Image.open(io.BytesIO(buffer.getvalue())).convert("RGB")
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _jev_score(crop: Image.Image, text: str) -> float:
|
| 140 |
+
rendering = render_text(text, FONT, crop.size)
|
| 141 |
+
inputs = jev_processor(text=[model_prompt(text)], images=[crop, rendering], return_tensors="pt").to("cuda")
|
| 142 |
+
with torch.inference_mode():
|
| 143 |
+
logits = jev(**inputs).logits[0].float()
|
| 144 |
+
return float(torch.softmax(logits, -1)[1])
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _engine() -> D.FastDSpark:
|
| 148 |
+
"""This worker's reader and draft on CUDA graphs, captured and warmed on first use (no timing includes it)."""
|
| 149 |
+
engine = _engines.get(os.getpid())
|
| 150 |
+
if engine is None:
|
| 151 |
+
engine = D.FastDSpark(reader, draft, MAX_LEN)
|
| 152 |
+
warm = Image.open(HERE / "examples" / EXAMPLES[0]["id"] / "region.png").convert("RGB")
|
| 153 |
+
engine.warm(_region_inputs(warm), EOS)
|
| 154 |
+
_trocr_read([warm.crop((0, 0, 200, 40))], max_new_tokens=4)
|
| 155 |
+
_jev_score(_jev_crop(warm.crop((0, 0, 200, 40))), "warm")
|
| 156 |
+
_engines[os.getpid()] = engine
|
| 157 |
+
return engine
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _timed(fn: Callable[[], T]) -> tuple[T, float]:
|
| 161 |
+
torch.cuda.synchronize()
|
| 162 |
+
started = time.perf_counter()
|
| 163 |
+
result = fn()
|
| 164 |
+
torch.cuda.synchronize()
|
| 165 |
+
return result, time.perf_counter() - started
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _text(tokens: list[int]) -> str:
|
| 169 |
+
return processor.decode(tokens, skip_special_tokens=True).strip()
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _cer(prediction: str, truth: str) -> float:
|
| 173 |
+
prediction, truth = " ".join(prediction.split()), " ".join(truth.split())
|
| 174 |
+
return Levenshtein.distance(prediction, truth) / max(1, len(truth))
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _duration(example_id: str, upload: Image.Image | None, with_jev: bool) -> int:
|
| 178 |
+
lines = 0 if upload is not None else len(_example(example_id)["lines"])
|
| 179 |
+
return int(min(115, 45 + 2.5 * lines + (25 if with_jev else 0)))
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
@spaces.GPU(duration=_duration)
|
| 183 |
+
def compare(example_id: str, upload: Image.Image | None, with_jev: bool) -> Comparison:
|
| 184 |
+
"""Read one region three ways and time each, from the images to the text: TrOCR on its lines in one batch, the
|
| 185 |
+
MiniCPM-OCR reader alone, and the reader with its DSpark draft (the last two on the same CUDA graphs). For an
|
| 186 |
+
example region, Jev then scores each line's TrOCR and MiniCPM readings."""
|
| 187 |
+
with _lock, torch.inference_mode():
|
| 188 |
+
engine = _engine()
|
| 189 |
+
if upload is not None:
|
| 190 |
+
region, lines, truth = upload.convert("RGB"), [], None
|
| 191 |
+
else:
|
| 192 |
+
folder = HERE / "examples" / example_id
|
| 193 |
+
truth = _example(example_id)["lines"]
|
| 194 |
+
region = Image.open(folder / "region.png").convert("RGB")
|
| 195 |
+
lines = [Image.open(folder / f"line_{i:02d}.jpg").convert("RGB") for i in range(len(truth))]
|
| 196 |
+
trocr_lines, trocr_seconds = _timed(lambda: _trocr_read(lines)) if lines else (None, None)
|
| 197 |
+
plain, plain_seconds = _timed(lambda: D.greedy(engine.reader, _region_inputs(region), 4096, EOS))
|
| 198 |
+
spec, dspark_seconds = _timed(lambda: engine.decode(_region_inputs(region), 4096, EOS))
|
| 199 |
+
result = Comparison(
|
| 200 |
+
truth=truth,
|
| 201 |
+
trocr=trocr_lines,
|
| 202 |
+
trocr_seconds=trocr_seconds,
|
| 203 |
+
plain=_text(plain.tokens),
|
| 204 |
+
plain_seconds=plain_seconds,
|
| 205 |
+
plain_passes=plain.reader_passes,
|
| 206 |
+
dspark=_text(spec.tokens),
|
| 207 |
+
dspark_seconds=dspark_seconds,
|
| 208 |
+
dspark_passes=spec.reader_passes,
|
| 209 |
+
tokens=len(spec.tokens),
|
| 210 |
+
acceptance=spec.acceptance_length,
|
| 211 |
+
identical=plain.tokens == spec.tokens,
|
| 212 |
+
)
|
| 213 |
+
if with_jev and trocr_lines is not None:
|
| 214 |
+
minicpm_lines = result.dspark.split("\n")
|
| 215 |
+
aligned = len(minicpm_lines) == len(lines)
|
| 216 |
+
rows = []
|
| 217 |
+
for i, line in enumerate(lines):
|
| 218 |
+
crop = _jev_crop(line)
|
| 219 |
+
row = JevLine(trocr=trocr_lines[i], trocr_score=_jev_score(crop, trocr_lines[i]))
|
| 220 |
+
if aligned:
|
| 221 |
+
row.minicpm, row.minicpm_score = minicpm_lines[i], _jev_score(crop, minicpm_lines[i])
|
| 222 |
+
rows.append(row)
|
| 223 |
+
result.jev = rows
|
| 224 |
+
return result
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
@spaces.GPU(duration=30)
|
| 228 |
+
def score_line(line: Image.Image | None, text: str) -> tuple[dict[str, float], Image.Image]:
|
| 229 |
+
"""Jev's score (0 to 1) that a candidate text is exactly what a handwritten line says, and the rendering of the
|
| 230 |
+
candidate it compares with the line."""
|
| 231 |
+
if line is None or not text.strip():
|
| 232 |
+
raise gr.Error("Give a line image and a candidate text.")
|
| 233 |
+
with _lock, torch.inference_mode():
|
| 234 |
+
crop = _jev_crop(line)
|
| 235 |
+
score = _jev_score(crop, text.strip())
|
| 236 |
+
return {"matches": score, "does not match": 1 - score}, render_text(text.strip(), FONT, crop.size)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _bars(result: Comparison) -> str:
|
| 240 |
+
rows: list[tuple[str, float, str, str]] = []
|
| 241 |
+
if result.trocr_seconds is not None:
|
| 242 |
+
rows.append(("Swedish Lion TrOCR", result.trocr_seconds, "#8a6d3b", "its lines in one batch"))
|
| 243 |
+
rows += [
|
| 244 |
+
("MiniCPM-OCR reader alone", result.plain_seconds, "#5b6b7a", f"{result.plain_passes} reader passes"),
|
| 245 |
+
("Reader + DSpark draft", result.dspark_seconds, "#2f6f4f", f"{result.dspark_passes} reader passes"),
|
| 246 |
+
]
|
| 247 |
+
longest = max(seconds for _, seconds, _, _ in rows)
|
| 248 |
+
html = ['<div style="display:flex;flex-direction:column;gap:8px;font-variant-numeric:tabular-nums">']
|
| 249 |
+
for name, seconds, colour, note in rows:
|
| 250 |
+
width = max(2.0, 100 * seconds / longest)
|
| 251 |
+
html.append(
|
| 252 |
+
'<div><div style="display:flex;justify-content:space-between;font-size:14px">'
|
| 253 |
+
f"<span><b>{name}</b> · {note}</span><span>{seconds:.2f} s</span></div>"
|
| 254 |
+
'<div style="height:14px;background:rgba(128,128,128,.15);border-radius:3px">'
|
| 255 |
+
f'<div style="width:{width:.1f}%;height:100%;background:{colour};border-radius:3px"></div></div></div>'
|
| 256 |
+
)
|
| 257 |
+
html.append("</div>")
|
| 258 |
+
return "".join(html)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _summary(result: Comparison) -> str:
|
| 262 |
+
against_trocr = (
|
| 263 |
+
f", **{result.trocr_seconds / result.dspark_seconds:.1f}×** TrOCR" if result.trocr_seconds is not None else ""
|
| 264 |
+
)
|
| 265 |
+
same = (
|
| 266 |
+
"The draft's reading is identical to the reader's alone."
|
| 267 |
+
if result.identical
|
| 268 |
+
else "The two readings differ at a near-tied token: the reader checks 16 tokens at once, and a batch of "
|
| 269 |
+
"another size can tip a tie the other way (the reader alone does the same between batch sizes)."
|
| 270 |
+
)
|
| 271 |
+
return (
|
| 272 |
+
f"**{result.tokens} tokens.** DSpark: acceptance length **{result.acceptance:.2f}** (tokens kept per reader "
|
| 273 |
+
f"check, at most 16), {result.dspark_passes} reader passes instead of {result.plain_passes}; "
|
| 274 |
+
f"**{result.plain_seconds / result.dspark_seconds:.1f}×** the reader alone{against_trocr}. {same}"
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def _jev_table(result: Comparison) -> tuple[dict[str, Any], str]:
|
| 279 |
+
if not result.jev or result.truth is None or result.trocr is None:
|
| 280 |
+
return gr.update(visible=False, value=None), ""
|
| 281 |
+
records = []
|
| 282 |
+
for i, row in enumerate(result.jev):
|
| 283 |
+
record: dict[str, Any] = {
|
| 284 |
+
"line": i + 1,
|
| 285 |
+
"ground truth": result.truth[i],
|
| 286 |
+
"TrOCR": row.trocr,
|
| 287 |
+
"Jev(TrOCR)": round(row.trocr_score, 3),
|
| 288 |
+
}
|
| 289 |
+
if row.minicpm is not None and row.minicpm_score is not None:
|
| 290 |
+
record |= {
|
| 291 |
+
"MiniCPM": row.minicpm,
|
| 292 |
+
"Jev(MiniCPM)": round(row.minicpm_score, 3),
|
| 293 |
+
"Jev picks": "MiniCPM" if row.minicpm_score > row.trocr_score else "TrOCR",
|
| 294 |
+
}
|
| 295 |
+
records.append(record)
|
| 296 |
+
truth = " ".join(result.truth)
|
| 297 |
+
scored = [row for row in result.jev if row.minicpm is not None and row.minicpm_score is not None]
|
| 298 |
+
if len(scored) != len(result.jev):
|
| 299 |
+
note = "The reader's reading has a different number of lines than the region: Jev scored TrOCR's lines only."
|
| 300 |
+
else:
|
| 301 |
+
picked = [row.minicpm if (row.minicpm_score or 0) > row.trocr_score else row.trocr for row in scored]
|
| 302 |
+
note = (
|
| 303 |
+
f"Line CER · TrOCR {100 * _cer(' '.join(result.trocr), truth):.1f} % · MiniCPM "
|
| 304 |
+
f"{100 * _cer(' '.join(row.minicpm or '' for row in scored), truth):.1f} % · "
|
| 305 |
+
f"**Jev's pick per line {100 * _cer(' '.join(str(p) for p in picked), truth):.1f} %**"
|
| 306 |
+
)
|
| 307 |
+
return gr.update(visible=True, value=pd.DataFrame(records)), note
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def run(example_label: str, upload: Image.Image | None, with_jev: bool) -> tuple[Any, ...]:
|
| 311 |
+
"""Read the chosen example (or an uploaded region) three ways and show the timings, readings and Jev's scores."""
|
| 312 |
+
result = compare(LABELS[example_label], upload, with_jev)
|
| 313 |
+
truth = "\n".join(result.truth) if result.truth else None
|
| 314 |
+
|
| 315 |
+
def box(name: str, seconds: float | None, text: str) -> dict[str, Any]:
|
| 316 |
+
cer = f" · CER {100 * _cer(text, truth):.1f} %" if truth else ""
|
| 317 |
+
timing = f" · {seconds:.2f} s" if seconds is not None else " · reads lines, not uploads"
|
| 318 |
+
return gr.update(value=text, label=f"{name}{timing}{cer if seconds is not None else ''}")
|
| 319 |
+
|
| 320 |
+
table, note = _jev_table(result)
|
| 321 |
+
return (
|
| 322 |
+
_bars(result),
|
| 323 |
+
box("Swedish Lion TrOCR", result.trocr_seconds, "\n".join(result.trocr or [])),
|
| 324 |
+
box("MiniCPM-OCR reader alone", result.plain_seconds, result.plain),
|
| 325 |
+
box("Reader + DSpark draft", result.dspark_seconds, result.dspark),
|
| 326 |
+
_summary(result),
|
| 327 |
+
table,
|
| 328 |
+
note,
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
@spaces.GPU(duration=240)
|
| 333 |
+
def _warm_startup() -> None:
|
| 334 |
+
"""At startup, one worker captures every graph and compiles the Triton kernels, cached on disk for later ones."""
|
| 335 |
+
_engine()
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def _label(example: dict[str, Any]) -> str:
|
| 339 |
+
collection = example["collection"].removeprefix("GT-").rsplit("_", 1)[0].replace("_", " ")
|
| 340 |
+
return f"{collection} · {len(example['lines'])} lines"
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
LABELS = {_label(e): e["id"] for e in EXAMPLES}
|
| 344 |
+
|
| 345 |
+
with gr.Blocks(title="Swedish HTR: TrOCR, MiniCPM-OCR and DSpark") as demo:
|
| 346 |
+
gr.Markdown(
|
| 347 |
+
"# Reading Swedish handwriting faster\n"
|
| 348 |
+
"A text region from an archive volume, read three ways on the same GPU: Riksarkivet's **Swedish Lion TrOCR** "
|
| 349 |
+
f"line by line; our **[MiniCPM-OCR reader](https://huggingface.co/{READER})** on the whole region; and the "
|
| 350 |
+
f"same reader with its **[DSpark draft](https://huggingface.co/{DRAFT})**, which guesses 15 tokens at a time "
|
| 351 |
+
f"for the reader to check in one pass. Then **[Jev](https://huggingface.co/{JEV})**, the reader's "
|
| 352 |
+
"proof-reader, scores each line's two readings. The regions are from volumes none of the models trained on."
|
| 353 |
+
)
|
| 354 |
+
with gr.Tab("Compare"):
|
| 355 |
+
with gr.Row():
|
| 356 |
+
with gr.Column(scale=2):
|
| 357 |
+
choice = gr.Dropdown(list(LABELS), value=next(iter(LABELS)), label="Example region")
|
| 358 |
+
preview = gr.Image(
|
| 359 |
+
value=str(HERE / "examples" / EXAMPLES[0]["id"] / "region.png"),
|
| 360 |
+
label="Region",
|
| 361 |
+
interactive=False,
|
| 362 |
+
height=360,
|
| 363 |
+
)
|
| 364 |
+
upload = gr.Image(
|
| 365 |
+
type="pil", label="Or your own region (the reader only: TrOCR and Jev need its lines)"
|
| 366 |
+
)
|
| 367 |
+
with_jev = gr.Checkbox(value=True, label="Score each line with Jev")
|
| 368 |
+
go = gr.Button("Read", variant="primary")
|
| 369 |
+
with gr.Column(scale=3):
|
| 370 |
+
bars = gr.HTML()
|
| 371 |
+
summary = gr.Markdown()
|
| 372 |
+
with gr.Row():
|
| 373 |
+
t_trocr = gr.Textbox(label="Swedish Lion TrOCR", lines=10)
|
| 374 |
+
t_plain = gr.Textbox(label="MiniCPM-OCR reader alone", lines=10)
|
| 375 |
+
t_dspark = gr.Textbox(label="Reader + DSpark draft", lines=10)
|
| 376 |
+
jev_note = gr.Markdown()
|
| 377 |
+
jev_table = gr.Dataframe(visible=False, wrap=True, label="Jev per line")
|
| 378 |
+
choice.change(lambda label: str(HERE / "examples" / LABELS[label] / "region.png"), choice, preview)
|
| 379 |
+
go.click(run, [choice, upload, with_jev], [bars, t_trocr, t_plain, t_dspark, summary, jev_table, jev_note])
|
| 380 |
+
with gr.Tab("Try Jev"):
|
| 381 |
+
gr.Markdown(
|
| 382 |
+
"Jev scores whether a text is exactly what a **single handwritten line** says. Upload a line crop and type "
|
| 383 |
+
"a reading; change a letter and watch the score drop."
|
| 384 |
+
)
|
| 385 |
+
with gr.Row():
|
| 386 |
+
with gr.Column():
|
| 387 |
+
line_in = gr.Image(type="pil", label="Line image", height=120)
|
| 388 |
+
text_in = gr.Textbox(label="Candidate text")
|
| 389 |
+
score_go = gr.Button("Score", variant="primary")
|
| 390 |
+
with gr.Column():
|
| 391 |
+
score_out = gr.Label(label="Jev")
|
| 392 |
+
render_out = gr.Image(label="The candidate rendered, as Jev compares it", height=120)
|
| 393 |
+
first = EXAMPLES[0]
|
| 394 |
+
gr.Examples(
|
| 395 |
+
[[str(HERE / "examples" / first["id"] / f"line_{i:02d}.jpg"), first["lines"][i]] for i in range(3)],
|
| 396 |
+
[line_in, text_in],
|
| 397 |
+
cache_examples=False,
|
| 398 |
+
)
|
| 399 |
+
score_go.click(score_line, [line_in, text_in], [score_out, render_out])
|
| 400 |
+
with gr.Tab("How it works"):
|
| 401 |
+
gr.Markdown(
|
| 402 |
+
(HERE / "HOW_IT_WORKS.md").read_text(encoding="utf-8").replace("@RENDERER@", renderer_version(FONT))
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
if os.environ.get("SPACES_ZERO_GPU"):
|
| 406 |
+
try:
|
| 407 |
+
_warm_startup()
|
| 408 |
+
except Exception as error: # the app still works: the first request warms its own worker
|
| 409 |
+
print(f"startup warm-up skipped: {error}", flush=True)
|
| 410 |
+
|
| 411 |
+
demo.queue(default_concurrency_limit=2).launch(show_error=True)
|
dspark_hf.py
ADDED
|
@@ -0,0 +1,604 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""DSpark speculative decoding for the MiniCPM-OCR HTR reader in PyTorch and transformers, on CUDA graphs.
|
| 2 |
+
|
| 3 |
+
vLLM serves this draft natively; this module is for hosts where vLLM cannot run (ZeroGPU). It follows the speculators
|
| 4 |
+
DSpark recipe the draft was trained with (speculators 0.10, ``models/dflash`` and ``models/dspark``):
|
| 5 |
+
|
| 6 |
+
* Context: the reader's residual stream entering layers 4, 8, 12, 16 and 20 at every position before the anchor,
|
| 7 |
+
concatenated, through ``fc`` and ``hidden_norm``; each draft layer projects it to keys and values (``k_norm`` and
|
| 8 |
+
rotary on the keys). A sliding window of 2,048 positions.
|
| 9 |
+
* Query block: the anchor token and 14 mask tokens at positions p..p+14, causal inside the block; slot k predicts the
|
| 10 |
+
token at p+k+1 (``sample_from_anchor``).
|
| 11 |
+
* Sampling: the block's base logits (a 32,000-token draft vocabulary) plus the Markov bias of the previous token,
|
| 12 |
+
argmax, left to right; draft ids map to the reader's vocabulary through ``d2t``.
|
| 13 |
+
|
| 14 |
+
Profiled with torch.profiler, eager decoding was launch-bound (about 1,500 kernels a reader pass, the GPU busy 12 % of
|
| 15 |
+
the time). So the reader runs on transformers' StaticCache with each pass replayed from a CUDA graph
|
| 16 |
+
(``GraphedReader``), the draft's whole proposal is one graph (``GraphedDraft``), and a draft cycle takes one reader
|
| 17 |
+
pass (``FastDSpark``): the reader is hybrid, its linear-attention states cannot be cut back after rejected tokens, so
|
| 18 |
+
the verifying graph keeps each linear layer's block inputs and the states are rebuilt over the accepted tokens only.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import json
|
| 24 |
+
import time
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Any, cast
|
| 27 |
+
|
| 28 |
+
import torch
|
| 29 |
+
import torch.nn.functional as F
|
| 30 |
+
from pydantic import BaseModel, ConfigDict, Field
|
| 31 |
+
from safetensors.torch import load_file
|
| 32 |
+
from torch import nn
|
| 33 |
+
from transformers import PreTrainedModel, Qwen3Config, StaticCache
|
| 34 |
+
from transformers.cache_utils import LinearAttentionCacheLayerMixin, StaticLayer
|
| 35 |
+
from transformers.models.qwen3.modeling_qwen3 import Qwen3MLP, Qwen3RMSNorm, Qwen3RotaryEmbedding
|
| 36 |
+
from transformers.models.qwen3_5 import modeling_qwen3_5 as qwen3_5
|
| 37 |
+
|
| 38 |
+
AUX_LAYERS = (4, 8, 12, 16, 20)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def rotate_half(x: torch.Tensor) -> torch.Tensor:
|
| 42 |
+
x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
|
| 43 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
|
| 47 |
+
"""Rotary position embedding of x [heads, n, head_dim] with cos/sin [n, head_dim]."""
|
| 48 |
+
return x * cos[None] + rotate_half(x) * sin[None]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class DraftAttention(nn.Module):
|
| 52 |
+
def __init__(self, hidden: int, heads: int, kv_heads: int, head_dim: int, eps: float):
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.heads, self.kv_heads, self.head_dim = heads, kv_heads, head_dim
|
| 55 |
+
self.q_proj = nn.Linear(hidden, heads * head_dim, bias=False)
|
| 56 |
+
self.k_proj = nn.Linear(hidden, kv_heads * head_dim, bias=False)
|
| 57 |
+
self.v_proj = nn.Linear(hidden, kv_heads * head_dim, bias=False)
|
| 58 |
+
self.o_proj = nn.Linear(heads * head_dim, hidden, bias=False)
|
| 59 |
+
self.q_norm = Qwen3RMSNorm(head_dim, eps=eps)
|
| 60 |
+
self.k_norm = Qwen3RMSNorm(head_dim, eps=eps)
|
| 61 |
+
|
| 62 |
+
def query(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
|
| 63 |
+
n = x.shape[0]
|
| 64 |
+
return rope(self.q_norm(self.q_proj(x).view(n, self.heads, self.head_dim)).transpose(0, 1), cos, sin)
|
| 65 |
+
|
| 66 |
+
def kv(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 67 |
+
"""Keys and values of x [n, hidden], each [kv_heads, n, head_dim]."""
|
| 68 |
+
n = x.shape[0]
|
| 69 |
+
k = self.k_norm(self.k_proj(x).view(n, self.kv_heads, self.head_dim)).transpose(0, 1)
|
| 70 |
+
v = self.v_proj(x).view(n, self.kv_heads, self.head_dim).transpose(0, 1)
|
| 71 |
+
return rope(k, cos, sin), v
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class DraftLayer(nn.Module):
|
| 75 |
+
def __init__(self, cfg: Qwen3Config, heads: int, kv_heads: int, head_dim: int):
|
| 76 |
+
super().__init__()
|
| 77 |
+
eps = float(cfg.rms_norm_eps)
|
| 78 |
+
self.self_attn = DraftAttention(cfg.hidden_size, heads, kv_heads, head_dim, eps)
|
| 79 |
+
self.mlp = Qwen3MLP(cfg)
|
| 80 |
+
self.input_layernorm = Qwen3RMSNorm(cfg.hidden_size, eps=eps)
|
| 81 |
+
self.post_attention_layernorm = Qwen3RMSNorm(cfg.hidden_size, eps=eps)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class DSparkDraft(nn.Module):
|
| 85 |
+
"""The draft's weights as speculators saves them; the input embeddings are the reader's."""
|
| 86 |
+
|
| 87 |
+
def __init__(self, config: dict[str, Any], embed_tokens: nn.Embedding):
|
| 88 |
+
super().__init__()
|
| 89 |
+
layer_config = {
|
| 90 |
+
k: v for k, v in config["transformer_layer_config"].items() if k not in ("architectures", "dtype")
|
| 91 |
+
}
|
| 92 |
+
self.cfg = Qwen3Config(**layer_config)
|
| 93 |
+
hidden = self.cfg.hidden_size
|
| 94 |
+
self.heads = int(self.cfg.num_attention_heads)
|
| 95 |
+
self.kv_heads = int(self.cfg.num_key_value_heads or self.heads)
|
| 96 |
+
self.head_dim = int(self.cfg.head_dim or hidden // self.heads)
|
| 97 |
+
eps = float(self.cfg.rms_norm_eps)
|
| 98 |
+
self.block_size: int = config["block_size"]
|
| 99 |
+
self.mask_token_id: int = config["mask_token_id"]
|
| 100 |
+
self.window: int | None = self.cfg.sliding_window if self.cfg.use_sliding_window else None
|
| 101 |
+
self.embed_tokens = embed_tokens
|
| 102 |
+
self.fc = nn.Linear(len(config["aux_hidden_state_layer_ids"]) * hidden, hidden, bias=False)
|
| 103 |
+
self.hidden_norm = Qwen3RMSNorm(hidden, eps=eps)
|
| 104 |
+
blocks = [
|
| 105 |
+
DraftLayer(self.cfg, self.heads, self.kv_heads, self.head_dim) for _ in range(self.cfg.num_hidden_layers)
|
| 106 |
+
]
|
| 107 |
+
self.layers = nn.ModuleList(blocks)
|
| 108 |
+
self.blocks: tuple[DraftLayer, ...] = tuple(blocks) # the same modules, typed
|
| 109 |
+
self.norm = Qwen3RMSNorm(hidden, eps=eps)
|
| 110 |
+
self.lm_head = nn.Linear(hidden, config["draft_vocab_size"], bias=False)
|
| 111 |
+
self.markov_w1 = nn.Embedding(embed_tokens.num_embeddings, config["markov_rank"])
|
| 112 |
+
self.markov_w2 = nn.Linear(config["markov_rank"], config["draft_vocab_size"], bias=False)
|
| 113 |
+
self.register_buffer("d2t", torch.zeros(config["draft_vocab_size"], dtype=torch.long), persistent=False)
|
| 114 |
+
self.rotary = Qwen3RotaryEmbedding(self.cfg)
|
| 115 |
+
|
| 116 |
+
@classmethod
|
| 117 |
+
def from_folder(cls, folder: str | Path, embed_tokens: nn.Embedding) -> DSparkDraft:
|
| 118 |
+
"""The draft a speculators checkpoint folder holds (config.json and model.safetensors)."""
|
| 119 |
+
folder = Path(folder)
|
| 120 |
+
config = json.loads((folder / "config.json").read_text(encoding="utf-8"))
|
| 121 |
+
if config.get("markov_head_type", "vanilla") != "vanilla" or not config.get("sample_from_anchor", True):
|
| 122 |
+
raise ValueError("only drafts with the vanilla Markov head that sample from the anchor are supported")
|
| 123 |
+
draft = cls(config, embed_tokens)
|
| 124 |
+
state: dict[str, torch.Tensor] = {}
|
| 125 |
+
for name, tensor in load_file(folder / "model.safetensors").items():
|
| 126 |
+
if name == "d2t":
|
| 127 |
+
draft.d2t_map.copy_(tensor)
|
| 128 |
+
elif name != "t2d" and not name.startswith("confidence_head."): # training and adaptive verification only
|
| 129 |
+
state[name.replace("markov_head.", "")] = tensor
|
| 130 |
+
missing, unexpected = draft.load_state_dict(state, strict=False)
|
| 131 |
+
missing = [m for m in missing if not m.startswith(("embed_tokens.", "rotary."))]
|
| 132 |
+
if missing or unexpected:
|
| 133 |
+
raise ValueError(f"the draft's weights do not match: missing {missing}, unexpected {unexpected}")
|
| 134 |
+
return draft
|
| 135 |
+
|
| 136 |
+
@property
|
| 137 |
+
def d2t_map(self) -> torch.Tensor:
|
| 138 |
+
return cast(torch.Tensor, self.d2t)
|
| 139 |
+
|
| 140 |
+
def cos_sin(self, positions: torch.Tensor, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]:
|
| 141 |
+
cos, sin = self.rotary(torch.empty(0, dtype=dtype, device=positions.device), positions[None])
|
| 142 |
+
return cos[0], sin[0]
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def aux_states(hidden_states: tuple[torch.Tensor, ...]) -> torch.Tensor:
|
| 146 |
+
"""The residual stream entering each aux layer, [n, 5 * hidden]; hidden_states[0] are the embeddings."""
|
| 147 |
+
return torch.cat([hidden_states[i][0] for i in AUX_LAYERS], dim=-1)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class Decoded(BaseModel):
|
| 151 |
+
"""A reading's tokens, its seconds and reader passes; with a draft, the tokens proposed and accepted over how many
|
| 152 |
+
verifications."""
|
| 153 |
+
|
| 154 |
+
tokens: list[int] = Field(default_factory=list)
|
| 155 |
+
seconds: float = 0.0
|
| 156 |
+
reader_passes: int = 0
|
| 157 |
+
drafted: int = 0
|
| 158 |
+
accepted: int = 0
|
| 159 |
+
cycles: int = 0
|
| 160 |
+
|
| 161 |
+
@property
|
| 162 |
+
def acceptance_length(self) -> float:
|
| 163 |
+
"""vLLM's measure: 1 + accepted draft tokens per verification."""
|
| 164 |
+
return 1 + self.accepted / self.cycles if self.cycles else float("nan")
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _stop(tokens: list[int], eos: set[int], max_new: int) -> tuple[list[int], bool]:
|
| 168 |
+
for i, token in enumerate(tokens):
|
| 169 |
+
if token in eos:
|
| 170 |
+
return tokens[: i + 1], True
|
| 171 |
+
if len(tokens) >= max_new:
|
| 172 |
+
return tokens[:max_new], True
|
| 173 |
+
return tokens, False
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class _Graph(BaseModel):
|
| 177 |
+
"""A captured reader pass: its graph, the static inputs refilled before each replay, the static outputs."""
|
| 178 |
+
|
| 179 |
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
| 180 |
+
|
| 181 |
+
graph: torch.cuda.CUDAGraph
|
| 182 |
+
ids: torch.Tensor
|
| 183 |
+
pos: torch.Tensor
|
| 184 |
+
out: Any
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class _LinearState(BaseModel):
|
| 188 |
+
"""A linear-attention layer and the copy of its states `save` took."""
|
| 189 |
+
|
| 190 |
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
| 191 |
+
|
| 192 |
+
layer_idx: int
|
| 193 |
+
layer: Any
|
| 194 |
+
conv: torch.Tensor
|
| 195 |
+
recurrent: torch.Tensor
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class _AttentionState(BaseModel):
|
| 199 |
+
"""A full-attention layer and the length `save` took."""
|
| 200 |
+
|
| 201 |
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
| 202 |
+
|
| 203 |
+
layer: Any
|
| 204 |
+
length: torch.Tensor
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
class GraphedReader:
|
| 208 |
+
"""The reader on a StaticCache, each pass length replayed from a CUDA graph captured on first use.
|
| 209 |
+
|
| 210 |
+
The cache is reset in place per request (its addresses, and so the graphs, kept). Full-attention layers keep
|
| 211 |
+
preallocated keys and values and an on-device length; linear-attention layers fixed-address states; the attention
|
| 212 |
+
mask is built inside the graph from the positions."""
|
| 213 |
+
|
| 214 |
+
def __init__(self, model: PreTrainedModel, max_len: int):
|
| 215 |
+
self.model, self.max_len = model, max_len
|
| 216 |
+
self.device = model.get_output_embeddings().weight.device
|
| 217 |
+
self.cache = StaticCache(config=model.config, max_cache_len=max_len)
|
| 218 |
+
self.kv_index = torch.arange(max_len, device=self.device)
|
| 219 |
+
self.graphs: dict[tuple[int, bool], _Graph] = {}
|
| 220 |
+
self.pool = torch.cuda.graph_pool_handle()
|
| 221 |
+
self.linear: list[_LinearState] = []
|
| 222 |
+
self.attention: list[_AttentionState] = []
|
| 223 |
+
|
| 224 |
+
def prefill(self, inputs: dict[str, Any], hidden: bool) -> Any:
|
| 225 |
+
"""A new request: the cache emptied in place, then the prompt (image and text) read eagerly."""
|
| 226 |
+
if inputs["input_ids"].shape[1] + 64 > self.max_len:
|
| 227 |
+
raise ValueError(
|
| 228 |
+
f"a prompt of {inputs['input_ids'].shape[1]} tokens is too long for a cache of {self.max_len}"
|
| 229 |
+
)
|
| 230 |
+
self.cache.reset()
|
| 231 |
+
return self.model(**inputs, past_key_values=self.cache, use_cache=True, output_hidden_states=hidden)
|
| 232 |
+
|
| 233 |
+
def save(self) -> None:
|
| 234 |
+
"""Remember the cache's states and lengths, into buffers allocated on the first call."""
|
| 235 |
+
if not self.linear and not self.attention:
|
| 236 |
+
for idx, layer in enumerate(self.cache.layers):
|
| 237 |
+
if isinstance(layer, LinearAttentionCacheLayerMixin):
|
| 238 |
+
conv, recurrent = layer.conv_states[0], layer.recurrent_states[0]
|
| 239 |
+
if conv is None or recurrent is None:
|
| 240 |
+
raise RuntimeError("save() before the prompt was read")
|
| 241 |
+
self.linear.append(
|
| 242 |
+
_LinearState(layer_idx=idx, layer=layer, conv=conv.clone(), recurrent=recurrent.clone())
|
| 243 |
+
)
|
| 244 |
+
elif isinstance(layer, StaticLayer):
|
| 245 |
+
self.attention.append(_AttentionState(layer=layer, length=_length(layer).clone()))
|
| 246 |
+
return
|
| 247 |
+
for state in self.linear:
|
| 248 |
+
state.conv.copy_(state.layer.conv_states[0])
|
| 249 |
+
state.recurrent.copy_(state.layer.recurrent_states[0])
|
| 250 |
+
for state in self.attention:
|
| 251 |
+
state.length.copy_(_length(state.layer))
|
| 252 |
+
|
| 253 |
+
def restore(self) -> None:
|
| 254 |
+
"""The cache as `save` left it (keys and values written since stay behind the length, masked by position)."""
|
| 255 |
+
for state in self.linear:
|
| 256 |
+
state.layer.conv_states[0].copy_(state.conv)
|
| 257 |
+
state.layer.recurrent_states[0].copy_(state.recurrent)
|
| 258 |
+
for state in self.attention:
|
| 259 |
+
_length(state.layer).copy_(state.length)
|
| 260 |
+
|
| 261 |
+
def _forward(self, ids: torch.Tensor, pos: torch.Tensor, hidden: bool) -> Any:
|
| 262 |
+
mask = (self.kv_index[None, :] <= pos[0][:, None])[None, None]
|
| 263 |
+
return self.model(
|
| 264 |
+
input_ids=ids,
|
| 265 |
+
position_ids=pos,
|
| 266 |
+
past_key_values=self.cache,
|
| 267 |
+
use_cache=True,
|
| 268 |
+
attention_mask={"full_attention": mask, "linear_attention": None},
|
| 269 |
+
output_hidden_states=hidden,
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
def _capture(self, ids: torch.Tensor, pos: torch.Tensor, hidden: bool) -> tuple[torch.cuda.CUDAGraph, Any]:
|
| 273 |
+
self.save()
|
| 274 |
+
stream = torch.cuda.Stream()
|
| 275 |
+
stream.wait_stream(torch.cuda.current_stream())
|
| 276 |
+
with torch.cuda.stream(stream):
|
| 277 |
+
for _ in range(2): # kernels autotune and allocate outside the capture
|
| 278 |
+
self._forward(ids, pos, hidden)
|
| 279 |
+
self.restore()
|
| 280 |
+
torch.cuda.current_stream().wait_stream(stream)
|
| 281 |
+
graph = torch.cuda.CUDAGraph()
|
| 282 |
+
with torch.cuda.graph(graph, pool=self.pool):
|
| 283 |
+
out = self._forward(ids, pos, hidden)
|
| 284 |
+
self.restore() # capture records without running; the cache stays as it was
|
| 285 |
+
return graph, out
|
| 286 |
+
|
| 287 |
+
def run(self, tokens: list[int], start: int, hidden: bool) -> Any:
|
| 288 |
+
"""A pass over `tokens` at positions start.. (the cache must hold exactly the positions before start)."""
|
| 289 |
+
key = (len(tokens), hidden)
|
| 290 |
+
ids = torch.tensor([tokens], device=self.device)
|
| 291 |
+
pos = torch.arange(start, start + len(tokens), device=self.device)[None]
|
| 292 |
+
graph = self.graphs.get(key)
|
| 293 |
+
if graph is None:
|
| 294 |
+
captured, out = self._capture(ids, pos, hidden)
|
| 295 |
+
graph = self.graphs[key] = _Graph(graph=captured, ids=ids, pos=pos, out=out)
|
| 296 |
+
else:
|
| 297 |
+
graph.ids.copy_(ids)
|
| 298 |
+
graph.pos.copy_(pos)
|
| 299 |
+
graph.graph.replay()
|
| 300 |
+
return graph.out
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def _length(layer: StaticLayer) -> torch.Tensor:
|
| 304 |
+
return cast(torch.Tensor, layer.cumulative_length)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
class _Recorder:
|
| 308 |
+
"""While a verifying graph is captured: each linear layer's block inputs, by layer index."""
|
| 309 |
+
|
| 310 |
+
def __init__(self) -> None:
|
| 311 |
+
self.active = False
|
| 312 |
+
self.layer = -1
|
| 313 |
+
self.inputs: dict[int, dict[str, torch.Tensor]] = {}
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
_RECORDER = _Recorder()
|
| 317 |
+
_chunk_rule = qwen3_5.torch_chunk_gated_delta_rule
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def _recording_chunk_rule(
|
| 321 |
+
query: torch.Tensor,
|
| 322 |
+
key: torch.Tensor,
|
| 323 |
+
value: torch.Tensor,
|
| 324 |
+
g: torch.Tensor,
|
| 325 |
+
beta: torch.Tensor,
|
| 326 |
+
*args: Any,
|
| 327 |
+
**kwargs: Any,
|
| 328 |
+
) -> Any:
|
| 329 |
+
if _RECORDER.active:
|
| 330 |
+
_RECORDER.inputs[_RECORDER.layer].update(q=query, k=key, v=value, g=g, beta=beta)
|
| 331 |
+
return _chunk_rule(query, key, value, g, beta, *args, **kwargs)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
qwen3_5.torch_chunk_gated_delta_rule = _recording_chunk_rule # the layers look the rule up at call time
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class OnePassReader(GraphedReader):
|
| 338 |
+
"""A GraphedReader whose verifying graph (more than one token, hidden states out) records the linear layers' block
|
| 339 |
+
inputs, so a partly accepted block can be kept without a second pass."""
|
| 340 |
+
|
| 341 |
+
def __init__(self, model: PreTrainedModel, max_len: int):
|
| 342 |
+
super().__init__(model, max_len)
|
| 343 |
+
update = self.cache.update_conv_state
|
| 344 |
+
|
| 345 |
+
def recording_update(conv_input: torch.Tensor, layer_idx: int, *args: Any, **kwargs: Any) -> Any:
|
| 346 |
+
if _RECORDER.active:
|
| 347 |
+
_RECORDER.layer = layer_idx
|
| 348 |
+
_RECORDER.inputs[layer_idx] = {"conv": conv_input}
|
| 349 |
+
return update(conv_input, layer_idx, *args, **kwargs)
|
| 350 |
+
|
| 351 |
+
self.cache.update_conv_state = recording_update
|
| 352 |
+
self.recorded: dict[int, dict[str, torch.Tensor]] = {}
|
| 353 |
+
|
| 354 |
+
def _capture(self, ids: torch.Tensor, pos: torch.Tensor, hidden: bool) -> tuple[torch.cuda.CUDAGraph, Any]:
|
| 355 |
+
if not (hidden and ids.shape[1] > 1):
|
| 356 |
+
return super()._capture(ids, pos, hidden)
|
| 357 |
+
self.save()
|
| 358 |
+
stream = torch.cuda.Stream()
|
| 359 |
+
stream.wait_stream(torch.cuda.current_stream())
|
| 360 |
+
with torch.cuda.stream(stream):
|
| 361 |
+
for _ in range(2):
|
| 362 |
+
self._forward(ids, pos, hidden)
|
| 363 |
+
self.restore()
|
| 364 |
+
torch.cuda.current_stream().wait_stream(stream)
|
| 365 |
+
graph = torch.cuda.CUDAGraph()
|
| 366 |
+
_RECORDER.active, _RECORDER.inputs = True, {}
|
| 367 |
+
try:
|
| 368 |
+
with torch.cuda.graph(graph, pool=self.pool):
|
| 369 |
+
out = self._forward(ids, pos, hidden)
|
| 370 |
+
finally:
|
| 371 |
+
_RECORDER.active = False
|
| 372 |
+
self.recorded = dict(_RECORDER.inputs)
|
| 373 |
+
self.restore()
|
| 374 |
+
return graph, out
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
class GraphedDraft:
|
| 378 |
+
"""The draft's context in fixed buffers and its whole proposal (the parallel backbone and the Markov sampling)
|
| 379 |
+
replayed from one CUDA graph: context keys and values sit at their positions in buffers of the reader's cache
|
| 380 |
+
length, the block's own at the end; the window and causal masks come from the anchor's position on the GPU."""
|
| 381 |
+
|
| 382 |
+
def __init__(self, draft: DSparkDraft, max_len: int):
|
| 383 |
+
self.draft, self.max_len = draft, max_len
|
| 384 |
+
weight = draft.lm_head.weight
|
| 385 |
+
device, dtype = weight.device, weight.dtype
|
| 386 |
+
b = draft.block_size
|
| 387 |
+
size = (draft.kv_heads, max_len + b, draft.head_dim)
|
| 388 |
+
self.keys = [torch.zeros(size, device=device, dtype=dtype) for _ in draft.blocks]
|
| 389 |
+
self.values = [torch.zeros(size, device=device, dtype=dtype) for _ in draft.blocks]
|
| 390 |
+
self.length = 0
|
| 391 |
+
self.anchor = torch.zeros(1, dtype=torch.long, device=device)
|
| 392 |
+
self.anchor_pos = torch.zeros((), dtype=torch.long, device=device)
|
| 393 |
+
self.kv_index = torch.arange(max_len, device=device)
|
| 394 |
+
self.offsets = torch.arange(b, device=device)
|
| 395 |
+
self.mask_ids = torch.full((b,), draft.mask_token_id, dtype=torch.long, device=device)
|
| 396 |
+
self.tril = torch.ones(b, b, dtype=torch.bool, device=device).tril()
|
| 397 |
+
self.graph = torch.cuda.CUDAGraph()
|
| 398 |
+
self.captured = False
|
| 399 |
+
self.out = torch.zeros(b, dtype=torch.long, device=device)
|
| 400 |
+
|
| 401 |
+
def reset(self) -> None:
|
| 402 |
+
self.length = 0 # older entries stay behind, masked out by position
|
| 403 |
+
|
| 404 |
+
@torch.inference_mode()
|
| 405 |
+
def extend(self, aux: torch.Tensor, start: int) -> None:
|
| 406 |
+
"""The context of positions start.. (aux: the reader's states entering the aux layers)."""
|
| 407 |
+
if start != self.length or start + aux.shape[0] > self.max_len:
|
| 408 |
+
raise ValueError(f"context from {start} does not follow {self.length} or overflows {self.max_len}")
|
| 409 |
+
d, n = self.draft, aux.shape[0]
|
| 410 |
+
c = d.hidden_norm(d.fc(aux))
|
| 411 |
+
cos, sin = d.cos_sin(torch.arange(start, start + n, device=aux.device), c.dtype)
|
| 412 |
+
for i, layer in enumerate(d.blocks):
|
| 413 |
+
k, v = layer.self_attn.kv(c, cos, sin)
|
| 414 |
+
self.keys[i][:, start : start + n].copy_(k)
|
| 415 |
+
self.values[i][:, start : start + n].copy_(v)
|
| 416 |
+
self.length += n
|
| 417 |
+
|
| 418 |
+
def _propose(self) -> torch.Tensor:
|
| 419 |
+
d, b = self.draft, self.draft.block_size
|
| 420 |
+
x = d.embed_tokens(torch.where(self.offsets == 0, self.anchor, self.mask_ids)).to(d.lm_head.weight.dtype)
|
| 421 |
+
cos, sin = d.cos_sin(self.anchor_pos + self.offsets, x.dtype)
|
| 422 |
+
context = self.kv_index < self.anchor_pos
|
| 423 |
+
if d.window is not None:
|
| 424 |
+
context = context & (self.kv_index >= self.anchor_pos - d.window)
|
| 425 |
+
mask = torch.cat([context[None, :].expand(b, -1), self.tril], dim=1)[None, None]
|
| 426 |
+
for i, layer in enumerate(d.blocks):
|
| 427 |
+
attn = layer.self_attn
|
| 428 |
+
h = layer.input_layernorm(x)
|
| 429 |
+
k_block, v_block = attn.kv(h, cos, sin)
|
| 430 |
+
self.keys[i][:, self.max_len :].copy_(k_block)
|
| 431 |
+
self.values[i][:, self.max_len :].copy_(v_block)
|
| 432 |
+
out = F.scaled_dot_product_attention(
|
| 433 |
+
attn.query(h, cos, sin)[None],
|
| 434 |
+
self.keys[i][None],
|
| 435 |
+
self.values[i][None],
|
| 436 |
+
attn_mask=mask,
|
| 437 |
+
scale=attn.head_dim**-0.5,
|
| 438 |
+
enable_gqa=True,
|
| 439 |
+
)[0]
|
| 440 |
+
x = x + attn.o_proj(out.transpose(0, 1).reshape(b, -1))
|
| 441 |
+
x = x + layer.mlp(layer.post_attention_layernorm(x))
|
| 442 |
+
base = d.lm_head(d.norm(x)).float()
|
| 443 |
+
prev, tokens = self.anchor, []
|
| 444 |
+
for k in range(b):
|
| 445 |
+
# index_select, not d2t[choice]: indexing by a 0-d tensor reads it on the host, which breaks a capture
|
| 446 |
+
choice = (base[k][None] + d.markov_w2(d.markov_w1(prev)).float()).argmax(dim=-1)
|
| 447 |
+
prev = choice + d.d2t_map.index_select(0, choice)
|
| 448 |
+
tokens.append(prev)
|
| 449 |
+
return torch.cat(tokens)
|
| 450 |
+
|
| 451 |
+
@torch.inference_mode()
|
| 452 |
+
def propose(self, anchor: int, anchor_pos: int) -> torch.Tensor:
|
| 453 |
+
"""The draft's block_size tokens after the anchor (the reader's vocabulary), left on the GPU."""
|
| 454 |
+
if anchor_pos != self.length:
|
| 455 |
+
raise ValueError(f"the anchor at {anchor_pos} does not follow the context's {self.length} positions")
|
| 456 |
+
self.anchor.fill_(anchor)
|
| 457 |
+
self.anchor_pos.fill_(anchor_pos)
|
| 458 |
+
if not self.captured:
|
| 459 |
+
stream = torch.cuda.Stream()
|
| 460 |
+
stream.wait_stream(torch.cuda.current_stream())
|
| 461 |
+
with torch.cuda.stream(stream):
|
| 462 |
+
for _ in range(2):
|
| 463 |
+
self._propose()
|
| 464 |
+
torch.cuda.current_stream().wait_stream(stream)
|
| 465 |
+
with torch.cuda.graph(self.graph):
|
| 466 |
+
self.out = self._propose()
|
| 467 |
+
self.captured = True
|
| 468 |
+
self.graph.replay()
|
| 469 |
+
return self.out
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
class FastDSpark:
|
| 473 |
+
"""The reader and its draft, every step of a cycle replayed from CUDA graphs: the draft's proposal goes into the
|
| 474 |
+
verifying graph on the GPU, one sync reads the drafts and the reader's tokens together, and the work after the
|
| 475 |
+
check (the draft's context extended, the reader's states rebuilt) is one graph per number of tokens kept. That work
|
| 476 |
+
depends only on the snapshot and the recorded block inputs, so the warm-up runs before each capture need no undoing.
|
| 477 |
+
"""
|
| 478 |
+
|
| 479 |
+
def __init__(self, model: PreTrainedModel, draft: DSparkDraft, max_len: int):
|
| 480 |
+
self.reader = OnePassReader(model, max_len)
|
| 481 |
+
self.gdraft = GraphedDraft(draft, max_len)
|
| 482 |
+
self.block = draft.block_size + 1
|
| 483 |
+
self.start = torch.zeros((), dtype=torch.long, device=self.reader.device)
|
| 484 |
+
self.after: dict[int, torch.cuda.CUDAGraph] = {}
|
| 485 |
+
self.verify_out: Any = None
|
| 486 |
+
|
| 487 |
+
def _after_check(self, keep: int) -> None:
|
| 488 |
+
g, r = self.gdraft, self.reader
|
| 489 |
+
d = g.draft
|
| 490 |
+
aux = aux_states(self.verify_out.hidden_states)[:keep]
|
| 491 |
+
positions = self.start + torch.arange(keep, device=self.start.device)
|
| 492 |
+
c = d.hidden_norm(d.fc(aux))
|
| 493 |
+
cos, sin = d.cos_sin(positions, c.dtype)
|
| 494 |
+
for i, layer in enumerate(d.blocks):
|
| 495 |
+
k, v = layer.self_attn.kv(c, cos, sin)
|
| 496 |
+
g.keys[i].index_copy_(1, positions, k)
|
| 497 |
+
g.values[i].index_copy_(1, positions, v)
|
| 498 |
+
if keep == self.block:
|
| 499 |
+
return # every state is already exact
|
| 500 |
+
for state in r.linear:
|
| 501 |
+
inputs = r.recorded[state.layer_idx]
|
| 502 |
+
conv = torch.cat([state.conv, inputs["conv"][..., :keep]], dim=-1)[..., -state.conv.shape[-1] :]
|
| 503 |
+
state.layer.conv_states[0].copy_(conv)
|
| 504 |
+
_, recurrent = qwen3_5.torch_recurrent_gated_delta_rule(
|
| 505 |
+
inputs["q"][:, :keep],
|
| 506 |
+
inputs["k"][:, :keep],
|
| 507 |
+
inputs["v"][:, :keep],
|
| 508 |
+
g=inputs["g"][:, :keep],
|
| 509 |
+
beta=inputs["beta"][:, :keep],
|
| 510 |
+
initial_state=state.recurrent,
|
| 511 |
+
output_final_state=True,
|
| 512 |
+
use_qk_l2norm_in_kernel=True,
|
| 513 |
+
)
|
| 514 |
+
state.layer.recurrent_states[0].copy_(recurrent)
|
| 515 |
+
for state in r.attention:
|
| 516 |
+
_length(state.layer).copy_(self.start + keep)
|
| 517 |
+
|
| 518 |
+
def after_check(self, keep: int) -> None:
|
| 519 |
+
"""Keep the verified block's first `keep` tokens (the reader's states and the draft's context)."""
|
| 520 |
+
graph = self.after.get(keep)
|
| 521 |
+
if graph is None:
|
| 522 |
+
stream = torch.cuda.Stream()
|
| 523 |
+
stream.wait_stream(torch.cuda.current_stream())
|
| 524 |
+
with torch.cuda.stream(stream):
|
| 525 |
+
for _ in range(2):
|
| 526 |
+
self._after_check(keep)
|
| 527 |
+
torch.cuda.current_stream().wait_stream(stream)
|
| 528 |
+
graph = self.after[keep] = torch.cuda.CUDAGraph()
|
| 529 |
+
with torch.cuda.graph(graph, pool=self.reader.pool):
|
| 530 |
+
self._after_check(keep)
|
| 531 |
+
graph.replay()
|
| 532 |
+
self.gdraft.length += keep
|
| 533 |
+
|
| 534 |
+
def _verify(self, anchor: int, drafts: torch.Tensor, anchor_pos: int) -> Any:
|
| 535 |
+
r = self.reader
|
| 536 |
+
graph = r.graphs.get((self.block, True))
|
| 537 |
+
if graph is None:
|
| 538 |
+
return r.run([anchor, *drafts.tolist()], anchor_pos, hidden=True)
|
| 539 |
+
graph.ids[0, 0] = anchor
|
| 540 |
+
graph.ids[0, 1:].copy_(drafts)
|
| 541 |
+
graph.pos.copy_(torch.arange(anchor_pos, anchor_pos + self.block, device=r.device)[None])
|
| 542 |
+
graph.graph.replay()
|
| 543 |
+
return graph.out
|
| 544 |
+
|
| 545 |
+
@torch.inference_mode()
|
| 546 |
+
def decode(self, inputs: dict[str, Any], max_new: int, eos: set[int]) -> Decoded:
|
| 547 |
+
"""The reader's greedy reading of `inputs`, with the draft: the same text, fewer reader passes."""
|
| 548 |
+
torch.cuda.synchronize()
|
| 549 |
+
started = time.perf_counter()
|
| 550 |
+
r, g = self.reader, self.gdraft
|
| 551 |
+
n = inputs["input_ids"].shape[1]
|
| 552 |
+
max_new = min(max_new, r.max_len - n - 2 * self.block - 2)
|
| 553 |
+
out = r.prefill(inputs, hidden=True)
|
| 554 |
+
g.reset()
|
| 555 |
+
g.extend(aux_states(out.hidden_states), 0)
|
| 556 |
+
result = Decoded(reader_passes=1)
|
| 557 |
+
tokens, done = _stop([int(out.logits[0, -1].argmax())], eos, max_new)
|
| 558 |
+
while not done:
|
| 559 |
+
anchor_pos = n + len(tokens) - 1
|
| 560 |
+
drafts = g.propose(tokens[-1], anchor_pos)
|
| 561 |
+
r.save()
|
| 562 |
+
self.verify_out = self._verify(tokens[-1], drafts, anchor_pos)
|
| 563 |
+
both = torch.cat([drafts, self.verify_out.logits[0].argmax(-1)]).tolist() # the cycle's one sync
|
| 564 |
+
proposed, verified = both[: self.block - 1], both[self.block - 1 :]
|
| 565 |
+
accepted = 0
|
| 566 |
+
while accepted < len(proposed) and proposed[accepted] == verified[accepted]:
|
| 567 |
+
accepted += 1
|
| 568 |
+
result.reader_passes += 1
|
| 569 |
+
result.cycles += 1
|
| 570 |
+
result.drafted += len(proposed)
|
| 571 |
+
result.accepted += accepted
|
| 572 |
+
self.start.fill_(anchor_pos)
|
| 573 |
+
self.after_check(accepted + 1)
|
| 574 |
+
tokens, done = _stop(tokens + [*proposed[:accepted], verified[accepted]], eos, max_new)
|
| 575 |
+
torch.cuda.synchronize()
|
| 576 |
+
result.tokens, result.seconds = tokens, time.perf_counter() - started
|
| 577 |
+
return result
|
| 578 |
+
|
| 579 |
+
@torch.inference_mode()
|
| 580 |
+
def warm(self, inputs: dict[str, Any], eos: set[int]) -> None:
|
| 581 |
+
"""Capture every graph (one reading with and one without the draft, then each number of tokens kept)."""
|
| 582 |
+
greedy(self.reader, inputs, 32, eos)
|
| 583 |
+
self.decode(inputs, 128, eos)
|
| 584 |
+
for keep in range(1, self.block + 1): # idempotent: depends only on the snapshot and the recorded inputs
|
| 585 |
+
self.start.fill_(0)
|
| 586 |
+
self.after_check(keep)
|
| 587 |
+
self.gdraft.reset()
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
@torch.inference_mode()
|
| 591 |
+
def greedy(reader: GraphedReader, inputs: dict[str, Any], max_new: int, eos: set[int]) -> Decoded:
|
| 592 |
+
"""The reader alone on CUDA graphs: one replay per token, greedy."""
|
| 593 |
+
torch.cuda.synchronize()
|
| 594 |
+
started = time.perf_counter()
|
| 595 |
+
n = inputs["input_ids"].shape[1]
|
| 596 |
+
max_new = min(max_new, reader.max_len - n - 1)
|
| 597 |
+
out = reader.prefill(inputs, hidden=False)
|
| 598 |
+
tokens, passes = [int(out.logits[0, -1].argmax())], 1
|
| 599 |
+
while tokens[-1] not in eos and len(tokens) < max_new:
|
| 600 |
+
out = reader.run([tokens[-1]], n + len(tokens) - 1, hidden=False)
|
| 601 |
+
tokens.append(int(out.logits[0, -1].argmax()))
|
| 602 |
+
passes += 1
|
| 603 |
+
torch.cuda.synchronize()
|
| 604 |
+
return Decoded(tokens=_stop(tokens, eos, max_new)[0], seconds=time.perf_counter() - started, reader_passes=passes)
|
examples/19a1b2195bab_right_0/line_00.jpg
ADDED
|
examples/19a1b2195bab_right_0/line_01.jpg
ADDED
|
examples/19a1b2195bab_right_0/line_02.jpg
ADDED
|
examples/19a1b2195bab_right_0/line_03.jpg
ADDED
|
examples/19a1b2195bab_right_0/line_04.jpg
ADDED
|
examples/19a1b2195bab_right_0/line_05.jpg
ADDED
|
examples/19a1b2195bab_right_0/line_06.jpg
ADDED
|
examples/19a1b2195bab_right_0/line_07.jpg
ADDED
|
examples/19a1b2195bab_right_0/region.png
ADDED
|
Git LFS Details
|
examples/35ffe6b8b600_left_0/line_00.jpg
ADDED
|
examples/35ffe6b8b600_left_0/line_01.jpg
ADDED
|
examples/35ffe6b8b600_left_0/line_02.jpg
ADDED
|
examples/35ffe6b8b600_left_0/line_03.jpg
ADDED
|
examples/35ffe6b8b600_left_0/line_04.jpg
ADDED
|
examples/35ffe6b8b600_left_0/line_05.jpg
ADDED
|
examples/35ffe6b8b600_left_0/line_06.jpg
ADDED
|
examples/35ffe6b8b600_left_0/line_07.jpg
ADDED
|
examples/35ffe6b8b600_left_0/line_08.jpg
ADDED
|
examples/35ffe6b8b600_left_0/line_09.jpg
ADDED
|
examples/35ffe6b8b600_left_0/line_10.jpg
ADDED
|
examples/35ffe6b8b600_left_0/line_11.jpg
ADDED
|
examples/35ffe6b8b600_left_0/line_12.jpg
ADDED
|
examples/35ffe6b8b600_left_0/line_13.jpg
ADDED
|
examples/35ffe6b8b600_left_0/line_14.jpg
ADDED
|
examples/35ffe6b8b600_left_0/line_15.jpg
ADDED
|
examples/35ffe6b8b600_left_0/line_16.jpg
ADDED
|
examples/35ffe6b8b600_left_0/line_17.jpg
ADDED
|
examples/35ffe6b8b600_left_0/region.png
ADDED
|
Git LFS Details
|
examples/38c4ce6331ad_left_1/line_00.jpg
ADDED
|
examples/38c4ce6331ad_left_1/line_01.jpg
ADDED
|
examples/38c4ce6331ad_left_1/line_02.jpg
ADDED
|
examples/38c4ce6331ad_left_1/line_03.jpg
ADDED
|
examples/38c4ce6331ad_left_1/line_04.jpg
ADDED
|
examples/38c4ce6331ad_left_1/line_05.jpg
ADDED
|
examples/38c4ce6331ad_left_1/line_06.jpg
ADDED
|
examples/38c4ce6331ad_left_1/line_07.jpg
ADDED
|
examples/38c4ce6331ad_left_1/line_08.jpg
ADDED
|
examples/38c4ce6331ad_left_1/line_09.jpg
ADDED
|
examples/38c4ce6331ad_left_1/line_10.jpg
ADDED
|
examples/38c4ce6331ad_left_1/line_11.jpg
ADDED
|