Eroux commited on
Commit
cc59d47
·
verified ·
1 Parent(s): 8d18014

Bundle vllm_paddleocr_seqpos plugin; card: real plugin install path

Browse files
README.md CHANGED
@@ -110,9 +110,17 @@ print(processor.batch_decode(out[:, inputs["input_ids"].shape[1]:], skip_special
110
  ### vLLM (production)
111
 
112
  Serve greedy (`temperature=0`) with **vLLM ≥ 0.26**. The **only** extra requirement is
113
- the sequential image-token position regime (above): install the `vllm_paddleocr_seqpos`
114
- plugin and set `OCR_VLLM_IMAGE_TOKEN_POSITIONS=sequential`. Without it, structured
115
- pages loop and accuracy collapses.
 
 
 
 
 
 
 
 
116
 
117
  <!-- The snippets above are the intended native path; run them once on a GPU box
118
  against deploy/fast_inference/bench.py (the source-of-truth harness) before
 
110
  ### vLLM (production)
111
 
112
  Serve greedy (`temperature=0`) with **vLLM ≥ 0.26**. The **only** extra requirement is
113
+ the sequential image-token position regime (above). Stock vLLM always serves PaddleOCR-VL
114
+ in the *grid* regime and never reads `mm_token_type_ids`, so you need a tiny vLLM general
115
+ plugin **it ships in this repo** under `vllm_paddleocr_seqpos/`:
116
+
117
+ ```bash
118
+ pip install "git+https://huggingface.co/BDRC/tibetan-ocr#subdirectory=vllm_paddleocr_seqpos"
119
+ export OCR_VLLM_IMAGE_TOKEN_POSITIONS=sequential # 'grid' / unset = no-op
120
+ ```
121
+
122
+ Then serve as usual. Without this, structured (book/list) pages skip or merge lines and
123
+ CER regresses badly.
124
 
125
  <!-- The snippets above are the intended native path; run them once on a GPU box
126
  against deploy/fast_inference/bench.py (the source-of-truth harness) before
vllm_paddleocr_seqpos/README.md ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # vllm-paddleocr-seqpos
2
+
3
+ A tiny [vLLM](https://github.com/vllm-project/vllm) plugin that makes PaddleOCR-VL serve in the
4
+ **`sequential` image-token position regime** (1D positions for image tokens) instead of vLLM's
5
+ built-in **`grid`** regime (2D image-grid M-RoPE).
6
+
7
+ Use it to serve any PaddleOCR-VL checkpoint that was **trained/validated with
8
+ `image_token_positions=sequential`** (i.e. with `mm_token_type_ids` zeroed) — e.g.
9
+ `elie_v6_coarse_grow26_ep2`. Without it, vLLM silently serves such a checkpoint in the wrong
10
+ regime and the model regresses.
11
+
12
+ ## Background: the two regimes
13
+
14
+ PaddleOCR-VL uses M-RoPE. A per-token mask, `mm_token_type_ids`, decides how *image* tokens are
15
+ positioned:
16
+
17
+ - **`sequential`** — mask zeroed → image tokens get plain 1D positions, exactly like text
18
+ (M-RoPE degenerates to standard 1D RoPE). This is the regime our checkpoints are trained in.
19
+ - **`grid`** — mask marked → image tokens get native 2D image-grid M-RoPE.
20
+
21
+ The HF reference path honors both (`deploy/fast_inference/bench.py --backend hf
22
+ --image-token-positions {sequential,grid}`), and `patch_checkpoint.py` warns that serving the
23
+ `sequential` regime needs an *engine-side* override. This package is that override for vLLM.
24
+
25
+ ## Why a plugin is needed (and why there's no simpler knob)
26
+
27
+ vLLM's in-tree model `vllm/model_executor/models/paddleocr_vl.py` (checked on 0.27.1) computes
28
+ positions itself in `PaddleOCRVLForConditionalGeneration.get_mrope_input_positions`. It
29
+ **unconditionally builds the 2D grid** from `image_grid_thw`/`mm_features` and **never reads
30
+ `mm_token_type_ids`**. Consequences:
31
+
32
+ - There is **no `mm_processor_kwargs` / processor knob** to switch it to sequential — the regime
33
+ lives in vLLM's own position code, not in the processor output vLLM consumes.
34
+ - `get_mrope_input_positions` runs in a **separate `EngineCore`/worker process**, so a
35
+ monkeypatch applied in the driver process (before `LLM(...)`) does **not** reach it.
36
+
37
+ vLLM does, however, call `vllm.general_plugins` entry points in **process0, the EngineCore
38
+ process, and every worker** (`vllm/plugins/__init__.py`). So the robust, version-stable fix is a
39
+ general plugin that overrides that one method wherever it runs. That's all this package does.
40
+
41
+ ## What it does
42
+
43
+ On load, and only when the environment variable `OCR_VLLM_IMAGE_TOKEN_POSITIONS=sequential`,
44
+ it replaces `get_mrope_input_positions` with a version that returns plain 1D sequential positions
45
+ (`arange(n)` broadcast across the 3 M-RoPE sections, `mrope_position_delta=0`) for the whole
46
+ sequence, image tokens included. The image features still merge via `input_ids ==
47
+ config.image_token_id`, so zeroing positions does **not** remove the image — it only changes the
48
+ position encoding.
49
+
50
+ It is a **strict no-op** for any other value (`grid`, unset), so grid-trained checkpoints are
51
+ untouched. It is idempotent (vLLM may load plugins more than once per process).
52
+
53
+ ## Install
54
+
55
+ Install into the **same Python environment that runs vLLM** (e.g. the DLAMI `/opt/pytorch` venv
56
+ on the serving box). No dependencies are declared on purpose — the plugin only touches
57
+ `vllm`/`torch`/`numpy`, which are already present in a serving env.
58
+
59
+ ```bash
60
+ /opt/pytorch/bin/pip install /path/to/deploy/vllm_paddleocr_seqpos
61
+ ```
62
+
63
+ Verify the entry point is registered:
64
+
65
+ ```bash
66
+ python -c "from importlib.metadata import entry_points; \
67
+ print([e.value for e in entry_points(group='vllm.general_plugins') if e.name=='paddleocr_seqpos'])"
68
+ # -> ['vllm_paddleocr_seqpos:apply']
69
+ ```
70
+
71
+ ## Use
72
+
73
+ Set the env var in the process that constructs `LLM(...)` **before** the engine starts; the
74
+ EngineCore/worker children inherit it:
75
+
76
+ ```bash
77
+ export OCR_VLLM_IMAGE_TOKEN_POSITIONS=sequential # or 'grid' / unset to disable (no-op)
78
+ ```
79
+
80
+ Then serve/construct vLLM as usual. On activation you'll see a one-line WARNING:
81
+ `paddleocr-seqpos: forcing SEQUENTIAL (1D) image-token M-RoPE for PaddleOCR-VL ...`.
82
+
83
+ In the OCR web-app this is automated: `ocr_app.worker.paddle_engine` resolves the checkpoint's
84
+ regime (from `experiment_config.json` / `info.json`, defaulting to `sequential`) and sets this
85
+ env var itself before loading the engine.
86
+
87
+ ## Verification (vLLM 0.27.1, A10G)
88
+
89
+ Against the production path (chat-template prompt, pyvips long-side 2500, greedy + DRY), on the
90
+ 6-page `TSAM-CHOE.pdf`, under default multiprocessing:
91
+
92
+ | page | `grid` (stock vLLM) | `sequential` (this plugin) |
93
+ | ---- | ------------------- | -------------------------- |
94
+ | 2 | 816 gen-tokens | **479 gen-tokens** (matches the HF `--image-token-positions sequential` oracle) |
95
+ | 4 | drops a catalog entry (`༤༨` → `རི་ཁྲོད`) | correct `༤༨ ཆོས་གསུམ / ༤༩ རི་ཁྲོད / ༥༠` |
96
+
97
+ `grid` stays at 816 with the plugin installed but the flag unset/`grid` (confirmed no-op).
98
+
99
+ ## Alternative
100
+
101
+ If you'd rather not run a serving-side plugin, **train/validate the checkpoint in the `grid`
102
+ regime** (`--image-token-positions grid`) and record `image_token_positions: grid` in its
103
+ `experiment_config.json`. Grid is vLLM's native path, so serving then needs no plugin. This
104
+ package exists so you don't *have* to retrain to serve existing `sequential` checkpoints.
105
+
106
+ ## Files
107
+
108
+ - `vllm_paddleocr_seqpos/__init__.py` — the plugin (`apply()` entry point + the sequential
109
+ `get_mrope_input_positions`).
110
+ - `pyproject.toml` — declares the `vllm.general_plugins` → `paddleocr_seqpos = vllm_paddleocr_seqpos:apply`
111
+ entry point.
vllm_paddleocr_seqpos/pyproject.toml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "vllm-paddleocr-seqpos"
7
+ version = "0.1.0"
8
+ description = "vLLM general plugin: serve PaddleOCR-VL with sequential (1D) image-token M-RoPE."
9
+ requires-python = ">=3.10"
10
+ # No install deps: the plugin only touches vllm/torch/numpy, which are already present in the
11
+ # serving environment (importing them itself would wrongly pin versions).
12
+
13
+ [project.entry-points."vllm.general_plugins"]
14
+ # vLLM loads this in process0, the EngineCore process, and every worker process, and calls it
15
+ # with no args. The plugin is a no-op unless OCR_VLLM_IMAGE_TOKEN_POSITIONS=sequential.
16
+ paddleocr_seqpos = "vllm_paddleocr_seqpos:apply"
17
+
18
+ [tool.setuptools]
19
+ packages = ["vllm_paddleocr_seqpos"]
vllm_paddleocr_seqpos/vllm_paddleocr_seqpos/__init__.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """vLLM general plugin: force PaddleOCR-VL into the *sequential* image-token M-RoPE regime.
2
+
3
+ Why this exists
4
+ ---------------
5
+ PaddleOCR-VL uses M-RoPE. The ``mm_token_type_ids`` mask selects the image-token position
6
+ regime: **sequential** (mask zeroed -> image tokens get plain 1D positions, like text) vs
7
+ **grid** (mask marked -> native 2D image-grid M-RoPE). vLLM's in-tree PaddleOCR-VL model
8
+ (``vllm/model_executor/models/paddleocr_vl.py``) does not read ``mm_token_type_ids`` at all;
9
+ its ``get_mrope_input_positions`` *unconditionally* builds the 2D grid from ``image_grid_thw``.
10
+ So stock vLLM can only serve the ``grid`` regime, and there is no processor/kwarg knob to
11
+ change it.
12
+
13
+ Checkpoints trained/validated in the ``sequential`` regime (e.g. ``elie_v6_coarse_grow26_ep2``)
14
+ therefore suffer a train/serve mismatch under vLLM: line skips/merges on structured book/list
15
+ pages and a large CER regression. This plugin closes that gap by overriding the one method so
16
+ image tokens get 1D sequential positions -- verified on vLLM 0.27.1 to reproduce the HF
17
+ ``--image-token-positions sequential`` oracle exactly (TSAM-CHOE page 2: 479 generated tokens,
18
+ vs 816 under grid, with the catalog numbering restored).
19
+
20
+ How it loads
21
+ ------------
22
+ vLLM calls ``vllm.general_plugins`` entry points with no args in process0, the EngineCore
23
+ process, and every worker process (``vllm/plugins/__init__.py``), which is exactly where
24
+ ``get_mrope_input_positions`` runs. The override is a class-attribute swap, applied once
25
+ (idempotent -- plugins may be loaded multiple times per process).
26
+
27
+ Gating
28
+ ------
29
+ The plugin is a **no-op** unless the environment variable ``OCR_VLLM_IMAGE_TOKEN_POSITIONS``
30
+ equals ``sequential`` (case-insensitive). The serving process (``ocr_app.worker.paddle_engine``)
31
+ sets this from the checkpoint's resolved regime before constructing the engine; the child
32
+ processes inherit it. Anything else (``grid``/unset) leaves vLLM's native behaviour untouched.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import logging
38
+ import os
39
+ from typing import Any
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+ ENV_FLAG = "OCR_VLLM_IMAGE_TOKEN_POSITIONS"
44
+ _state = {"patched": False}
45
+
46
+
47
+ def _sequential_mrope_positions(self, input_tokens, mm_features) -> tuple[Any, int]: # noqa: ANN001, ARG001
48
+ """1D sequential positions for the whole sequence (image tokens included).
49
+
50
+ Equivalent to zeroing ``mm_token_type_ids``: every token (text and image) gets the plain
51
+ ``0..n-1`` position broadcast across the 3 M-RoPE sections, so M-RoPE degenerates to
52
+ standard 1D RoPE. ``mrope_position_delta`` is 0 so decode continues at ``n, n+1, ...``.
53
+ """
54
+ import numpy as np
55
+ import torch
56
+
57
+ n = len(input_tokens)
58
+ positions = np.broadcast_to(np.arange(n, dtype=np.int64), (3, n))
59
+ return torch.from_numpy(np.ascontiguousarray(positions)), 0
60
+
61
+
62
+ def apply() -> None:
63
+ """Entry point invoked by vLLM in every process. Idempotent; gated by env."""
64
+ if _state["patched"]:
65
+ return
66
+ regime = os.environ.get(ENV_FLAG, "").strip().lower()
67
+ if regime != "sequential":
68
+ logger.debug("paddleocr-seqpos: %s=%r != 'sequential'; not patching", ENV_FLAG, regime)
69
+ return
70
+ try:
71
+ from vllm.model_executor.models import paddleocr_vl as mod
72
+ except Exception:
73
+ logger.exception("paddleocr-seqpos: could not import PaddleOCR-VL model; not patching")
74
+ return
75
+
76
+ mod.PaddleOCRVLForConditionalGeneration.get_mrope_input_positions = _sequential_mrope_positions
77
+ _state["patched"] = True
78
+ logger.warning(
79
+ "paddleocr-seqpos: forcing SEQUENTIAL (1D) image-token M-RoPE for PaddleOCR-VL "
80
+ "(mm_token_type_ids-zeroed regime). Grid-trained checkpoints must NOT set %s=sequential.",
81
+ ENV_FLAG,
82
+ )