File size: 13,503 Bytes
2699213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d93242
2699213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81d7320
2699213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81d7320
2699213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1cd218
2699213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81d7320
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
"""DocSEAM: Bidirectional Cross-Page Encoding for Multi-Page Document Understanding.

A Gradio demo for the mossbee/DocSEAM checkpoint (Qwen3.5-9B + injectable
cross-page encoder). Upload one or more document pages in reading order, ask
a question, and DocSEAM enriches each page's visual features with context
from its immediate neighbors before answering.

Reference implementation: https://github.com/mossbee/DocSEAM (infer.py,
visualize_attention.py).
"""

import tempfile
import threading
import time
from pathlib import Path

import spaces  # must precede any torch/CUDA-touching import
import gradio as gr
import matplotlib
import numpy as np
import torch
from PIL import Image
from qwen_vl_utils import process_vision_info
from transformers import AutoModelForImageTextToText, AutoProcessor

matplotlib.use("Agg")
import matplotlib.pyplot as plt

MODEL_ID = "mossbee/DocSEAM"
HERE = Path(__file__).resolve().parent

# --- Model load (module scope, eager .to("cuda")) ----------------------------
processor = AutoProcessor.from_pretrained(MODEL_ID)
model = AutoModelForImageTextToText.from_pretrained(
    MODEL_ID, dtype=torch.bfloat16, trust_remote_code=True
)
model = model.to("cuda").eval()
processor.tokenizer.padding_side = "left"

ENCODER = model.model.docseam
SALIENCE_KEYS = ("s_send_to_next", "s_recv_from_prev", "s_send_to_prev", "s_recv_from_next")
# record_salience + _last_salience_records are encoder-global state; serialize
# them so concurrent requests don't leak records into each other's heatmaps.
_SALIENCE_LOCK = threading.Lock()


# --- Reference-path inference (ports docseam-repo/infer.py 1:1) --------------
def _build_content(image_paths, question):
    """Build chat content the way docseam-repo/infer.py::prepare_inputs does."""
    pages = [
        {
            "type": "image",
            "image": f"file://{Path(p).resolve()}",
            "min_pixels": 32768,
            "max_pixels": 524288,
        }
        for p in image_paths
    ]
    parts = question.split("<image>")
    if len(parts) == 1:
        return [*pages, {"type": "text", "text": question}]
    if len(parts) - 1 != len(pages):
        raise ValueError(
            f"The question contains {len(parts) - 1} '<image>' placeholder(s) "
            f"but {len(pages)} page image(s) were provided. Each '<image>' "
            "placeholder requires exactly one page image."
        )
    content = []
    for index, part in enumerate(parts):
        if part:
            content.append({"type": "text", "text": part})
        if index < len(pages):
            content.append(pages[index])
    return content


def _decode_answer(text):
    """Trim generation at chat markers, like docseam-repo/infer.py::decode_answer."""
    for marker in ("<|im_end|>", "<|im_start|>", "\nuser\n", "\nassistant\n", "\nUser\n", "\nAssistant\n"):
        if marker in text:
            return text.split(marker, 1)[0].rstrip("\n")
    return text.rstrip("\n")


def _center_page_index(num_pages):
    """Index of the page whose triplet is shown in the salience heatmap."""
    return min(max((num_pages - 1) // 2, 0), num_pages - 1)


def _salience_heatmap(image_paths, page_grids, records, center_idx):
    """Overlay the averaged directional salience gates on the center triplet.

    Mirrors docseam-repo/visualize_attention.py: average the center page's
    records across DocSEAM layers, reshape each gate to its page grid,
    normalize 2-98 percentile, and paint a turbo heatmap over the pages.
    """
    selected = [r for r in records if r["curr_page_index"] == center_idx]
    if not selected:
        return None
    n_prev, n_curr, n_next = selected[0]["n_prev"], selected[0]["n_curr"], selected[0]["n_next"]
    salience = {
        key: torch.stack([torch.sigmoid(r[key]).float() for r in selected]).mean(dim=0).numpy()
        for key in SALIENCE_KEYS
    }

    # Boundary pages fall back to themselves (self-fallback in DocSEAM.forward),
    # so prev/next grids equal the center grid there — same as the module does.
    h_prev, w_prev = page_grids[center_idx - 1] if center_idx > 0 else page_grids[center_idx]
    h_curr, w_curr = page_grids[center_idx]
    h_next, w_next = page_grids[center_idx + 1] if center_idx < len(page_grids) - 1 else page_grids[center_idx]

    prev_send = salience["s_send_to_next"][:n_prev].reshape(h_prev, w_prev)
    curr_recv_p = salience["s_recv_from_prev"][n_prev : n_prev + n_curr].reshape(h_curr, w_curr)
    curr_recv_n = salience["s_recv_from_next"][n_prev : n_prev + n_curr].reshape(h_curr, w_curr)
    next_send = salience["s_send_to_prev"][n_prev + n_curr : n_prev + n_curr + n_next].reshape(h_next, w_next)

    n_pages = len(image_paths)
    prev_idx = max(center_idx - 1, 0)
    next_idx = min(center_idx + 1, n_pages - 1)
    panels = [
        (prev_idx, prev_send, f"Page {prev_idx + 1} → next", "what this page sends forward"),
        (center_idx, curr_recv_p, f"Page {center_idx + 1} ← prev", "what the center reads from previous"),
        (center_idx, curr_recv_n, f"Page {center_idx + 1} ← next", "what the center reads from next"),
        (next_idx, next_send, f"Page {next_idx + 1} → prev", "what this page sends back"),
    ]
    values = np.concatenate([p[1].reshape(-1) for p in panels])
    vmin, vmax = np.percentile(values, [2, 98])
    if vmax <= vmin:
        vmin, vmax = float(values.min()), float(values.max())
    if vmax <= vmin:
        vmax = vmin + 1e-6

    fig, axes = plt.subplots(2, len(panels), figsize=(5 * len(panels), 10), constrained_layout=True)
    if len(panels) == 1:
        axes = axes.reshape(2, 1)
    overlay = None
    for col, (img_idx, heatmap, title, subtitle) in enumerate(panels):
        img = Image.open(image_paths[img_idx]).convert("RGB")
        axes[0, col].imshow(img)
        axes[0, col].set_title(title, fontsize=11)
        axes[0, col].axis("off")
        axes[1, col].imshow(img)
        rel = np.clip((heatmap - vmin) / (vmax - vmin), 0.0, 1.0)
        hm = Image.fromarray(rel.astype(np.float32)).resize(img.size, Image.BILINEAR)
        overlay = axes[1, col].imshow(np.array(hm), cmap="turbo", alpha=0.62, vmin=0.0, vmax=1.0)
        axes[1, col].set_title(subtitle, fontsize=9)
        axes[1, col].axis("off")
    fig.colorbar(
        overlay,
        ax=axes[1, :].ravel().tolist(),
        fraction=0.025,
        pad=0.02,
        label="relative salience gate strength",
    )
    out_dir = tempfile.mkdtemp(prefix="docseam_salience_")
    out_path = Path(out_dir) / "salience.png"
    fig.savefig(out_path, dpi=110)
    plt.close(fig)
    return str(out_path)


# --- GPU inference -----------------------------------------------------------
@spaces.GPU(duration=45)
def answer_question(
    pages,
    question,
    show_salience=True,
    max_new_tokens=256,
    progress=gr.Progress(track_tqdm=True),
):
    """Answer a question over an ordered list of document pages.

    Args:
        pages: one or more page images in document order (first = first page).
        question: the question; a literal "<image>" inside it places pages
            at that point in the prompt, otherwise pages come first.
        show_salience: also render the cross-page salience heatmap for the
            center page's triplet.
        max_new_tokens: generation budget for the answer.

    Returns:
        Tuple of (answer text, elapsed seconds, salience heatmap or None).
    """
    if not pages:
        raise gr.Error("Please upload at least one page image.")
    if not question or not question.strip():
        raise gr.Error("Please enter a question.")

    image_paths = [p if isinstance(p, str) else p.name for p in pages]
    messages = [{"role": "user", "content": _build_content(image_paths, question.strip())}]
    prompt = processor.apply_chat_template(
        messages, tokenize=False, add_generation_prompt=True, enable_thinking=False
    )
    images, _ = process_vision_info(messages, image_patch_size=processor.image_processor.patch_size)
    inputs = processor(text=[prompt], images=images, padding=True, return_tensors="pt").to(model.device)

    tokenizer = processor.tokenizer
    _SALIENCE_LOCK.acquire()
    try:
        ENCODER.record_salience = bool(show_salience)
        t0 = time.perf_counter()
        with torch.inference_mode():
            tokens = model.generate(
                **inputs,
                max_new_tokens=int(max_new_tokens),
                do_sample=False,
                eos_token_id=tokenizer.eos_token_id,
                pad_token_id=tokenizer.pad_token_id,
            )
        elapsed = time.perf_counter() - t0
        # Snapshot the records now; page grids/tensors are detached CPU tensors.
        records = list(ENCODER._last_salience_records) if show_salience else []
        ENCODER.record_salience = False
    finally:
        _SALIENCE_LOCK.release()

    text = _decode_answer(
        processor.decode(tokens[0, inputs.input_ids.shape[1]:], skip_special_tokens=False, clean_up_tokenization_spaces=False)
    )
    heatmap = None
    if records:
        try:
            merge = model.model.visual.spatial_merge_size
            page_grids = [
                (int(h) // merge, int(w) // merge) for _, h, w in inputs.image_grid_thw.tolist()
            ]
            heatmap = _salience_heatmap(image_paths, page_grids, records, _center_page_index(len(image_paths)))
        except Exception as exc:  # heatmap is best-effort; never fail the answer
            print(f"salience heatmap failed: {exc!r}")
    return text, round(elapsed, 2), heatmap


# --- UI ----------------------------------------------------------------------
CSS = """
#col-container { max-width: 1200px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""

with gr.Blocks(title="DocSEAM") as demo:
    with gr.Column(elem_id="col-container"):
        gr.Markdown(
            """
            # DocSEAM: Bidirectional Cross-Page Encoding for Multi-Page Document Understanding
            Ask questions across multi-page documents. DocSEAM enriches each page's visual
            features with context from its **neighboring pages** via center-anchored masked
            attention and directional salience gates — without inflating the visual token count.

            [Paper](https://arxiv.org/abs/2611.34420) · [Project page](https://mossbee.github.io/projects/DocSEAM/) · [Code](https://github.com/mossbee/DocSEAM) · [Model](https://huggingface.co/mossbee/DocSEAM)
            """
        )
        with gr.Row():
            with gr.Column(scale=1):
                pages_in = gr.Files(
                    label="Document pages (in reading order)",
                    file_count="multiple",
                    file_types=["image"],
                    type="filepath",
                )
                question_in = gr.Textbox(
                    label="Question",
                    placeholder="e.g. How many parallel attention heads are used in the model?",
                    lines=3,
                )
                show_salience_in = gr.Checkbox(
                    label="Show cross-page salience heatmap",
                    value=True,
                )
                run_btn = gr.Button("Ask", variant="primary")
                with gr.Accordion("Advanced settings", open=False):
                    max_new_tokens_in = gr.Slider(
                        minimum=16, maximum=1024, value=256, step=16,
                        label="Max new tokens",
                    )
            with gr.Column(scale=1):
                answer_out = gr.Textbox(label="Answer", lines=4)
                elapsed_out = gr.Number(label="Inference time (s)", precision=2)
                salience_out = gr.Image(
                    label="Cross-page salience gates (center triplet)",
                    type="filepath",
                )

        gr.Examples(
            examples=[
                [
                    [
                        str(HERE / "examples/1706.03762v7_page-0004.jpg"),
                        str(HERE / "examples/1706.03762v7_page-0005.jpg"),
                        str(HERE / "examples/1706.03762v7_page-0006.jpg"),
                    ],
                    "How many parallel attention heads are used in the model? Answer with only the number.",
                    True,
                    128,
                ],
                [
                    [
                        str(HERE / "examples/1706.03762v7_page-0004.jpg"),
                        str(HERE / "examples/1706.03762v7_page-0005.jpg"),
                        str(HERE / "examples/1706.03762v7_page-0006.jpg"),
                    ],
                    "Page 4:\n<image>\nPage 5:\n<image>\nPage 6:\n<image>\nRead the table continuously across the boundary from Page 4 into Page 5, then use Page 6 only as the following context page.",
                    True,
                    256,
                ],
            ],
            inputs=[pages_in, question_in, show_salience_in, max_new_tokens_in],
            outputs=[answer_out, elapsed_out, salience_out],
            fn=answer_question,
            cache_examples=True,
            cache_mode="lazy",
            examples_per_page=2,
        )

    run_btn.click(
        answer_question,
        inputs=[pages_in, question_in, show_salience_in, max_new_tokens_in],
        outputs=[answer_out, elapsed_out, salience_out],
        api_name="answer",
    )

demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)