File size: 3,877 Bytes
b312080
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Transformers integration for DocSEAM on the Qwen3.5 backbone."""

from contextvars import ContextVar

import torch.nn.functional as F
from torch import nn
from transformers.models.qwen3_5.modeling_qwen3_5 import (
    Qwen3_5ForConditionalGeneration,
    Qwen3_5Model,
    Qwen3_5PreTrainedModel,
)

from .docseam import DocSEAM


_page_counts = ContextVar("docseam_page_counts", default=None)


class DocSEAMModel(Qwen3_5Model):
    def __init__(self, config):
        super().__init__(config)
        self.docseam = DocSEAM(
            hidden_size=config.text_config.hidden_size,
            num_heads=config.text_config.num_attention_heads,
            intermediate_size=4096,
            num_layers=config.docseam_num_layers,
            cap_frac=config.docseam_cap_frac,
        )
        self.docseam.pos_feature_mode = config.docseam_pos_feature_mode
        self.docseam.use_checkpoint = False

    def forward(self, input_ids=None, position_ids=None, pixel_values=None, **kwargs):
        pages = None
        if pixel_values is not None and input_ids is not None:
            image_starts = (
                (input_ids[:, :-1] == self.config.vision_start_token_id)
                & (input_ids[:, 1:] == self.config.image_token_id)
            )
            pages = [count for count in image_starts.sum(dim=1).tolist() if count]
        token = _page_counts.set(pages)
        try:
            return super().forward(
                input_ids=input_ids, position_ids=position_ids, pixel_values=pixel_values, **kwargs
            )
        finally:
            _page_counts.reset(token)

    def get_video_features(self, pixel_values_videos, video_grid_thw=None, **kwargs):
        return super().get_image_features(pixel_values_videos, video_grid_thw, **kwargs)

    def get_image_features(self, pixel_values, image_grid_thw=None, **kwargs):
        return_dict = kwargs.pop("return_dict", getattr(self.config, "return_dict", True))
        output = super().get_image_features(pixel_values, image_grid_thw, return_dict=True, **kwargs)
        pages = _page_counts.get()
        if pages is not None:
            if sum(pages) != len(output.pooler_output):
                raise ValueError("DocSEAM page counts do not match the encoded images.")
            grids = image_grid_thw.tolist()
            merge = self.visual.spatial_merge_size
            output.pooler_output = tuple(self.docseam(
                list(output.pooler_output),
                page_grid_dims=[(h // merge, w // merge) for _, h, w in grids],
                pages_per_document=pages,
                page_ink_masks=_ink_masks(pixel_values, grids, merge),
            ))
        return output if return_dict else output.to_tuple()


def _ink_masks(pixel_values, grids, merge):
    """Reproduce the Stage B runtime ink estimates used by the frontier gates."""
    masks = []
    start = 0
    for t, h, w in grids:
        stop = start + t * h * w
        patches = pixel_values[start:stop].detach().float()
        start = stop
        rows, cols = h // merge, w // merge
        darkness = ((1.0 - patches).clamp(0.0, 2.0) * 0.5).mean(dim=-1)
        darkness = darkness.view(t, h, w).mean(dim=0)
        darkness = darkness[: rows * merge, : cols * merge]
        darkness = darkness.reshape(rows, merge, cols, merge).mean(dim=(1, 3))
        darkness = F.avg_pool2d(darkness[None, None], kernel_size=3, stride=1, padding=1)[0, 0]
        masks.append(((darkness - 0.01) / 0.12).clamp(0.0, 1.0).reshape(-1).to(pixel_values.dtype))
    return masks


class DocSEAMForConditionalGeneration(Qwen3_5ForConditionalGeneration):
    def __init__(self, config):
        Qwen3_5PreTrainedModel.__init__(self, config)
        self.model = DocSEAMModel(config)
        self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
        self.post_init()