yasserDahou commited on
Commit
f22f735
·
verified ·
1 Parent(s): 8b95c5a

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ pipeline_tag: image-to-text
4
+ library_name: transformers
5
+ tags:
6
+ - falcon
7
+ - ocr
8
+ - vision-language
9
+ - document-understanding
10
+ ---
11
+
12
+ # Falcon OCR
13
+
14
+ Dense early-fusion vision-language model for **document OCR**. Given a document image, it extracts text, tables, formulas, and other elements as plain text.
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ pip install transformers torch einops
20
+ ```
21
+
22
+ Requires **PyTorch 2.5+** (FlexAttention).
23
+
24
+ ## Quick Start
25
+
26
+ ```python
27
+ import torch
28
+ from transformers import AutoModelForCausalLM
29
+ from PIL import Image
30
+
31
+ model = AutoModelForCausalLM.from_pretrained(
32
+ "tiiuae/Falcon-OCR",
33
+ trust_remote_code=True,
34
+ dtype=torch.bfloat16,
35
+ device_map="cuda",
36
+ )
37
+
38
+ image = Image.open("document.png")
39
+ texts = model.generate(image)
40
+ print(texts[0])
41
+ ```
42
+
43
+ > The first `generate()` call is slower (~10-15 s) because `torch.compile` builds optimized kernels. Subsequent calls are much faster.
44
+
45
+ ## Categories
46
+
47
+ By default, category is `"plain"` (general text extraction). You can specify a category to use a task-specific prompt:
48
+
49
+ ```python
50
+ texts = model.generate(image, category="table")
51
+ texts = model.generate(image, category="formula")
52
+ ```
53
+
54
+ Available categories: `plain`, `text`, `table`, `formula`, `caption`, `footnote`, `list-item`, `page-footer`, `page-header`, `section-header`, `title`.
55
+
56
+
57
+ ## API Reference
58
+
59
+ ### `model.generate(images, *, category="plain", **kwargs)`
60
+
61
+ | Parameter | Type | Default | Description |
62
+ |---|---|---|---|
63
+ | `images` | `PIL.Image` or `list` | required | Single image or list of images (PIL, path, or URL) |
64
+ | `category` | `str` or `list[str]` | `"plain"` | OCR category (one per image or broadcast) |
65
+ | `max_new_tokens` | `int` | `4096` | Maximum generation steps |
66
+ | `min_dimension` | `int` | `64` | Minimum image side after resize |
67
+ | `max_dimension` | `int` | `1024` | Maximum image side after resize |
68
+
69
+ **Returns:** `list[str]` — one extracted text string per image.
70
+
71
+ ## Citation
72
+
73
+
attention.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import Tensor as T
3
+ from torch.nn.attention.flex_attention import (
4
+ _mask_mod_signature,
5
+ create_block_mask,
6
+ flex_attention,
7
+ )
8
+
9
+ # ---------------------------------------------------------------------------
10
+ # Two compiled variants of flex_attention
11
+ # ---------------------------------------------------------------------------
12
+ # _decode: fullgraph=True, static shapes.
13
+ # Used for decode steps (S_q == 1) where shapes are fixed and
14
+ # the call will be captured inside a CUDA graph. fullgraph=True
15
+ # avoids graph breaks that would corrupt the capture.
16
+ #
17
+ # _prefill: dynamic=True, symbolic shapes.
18
+ # Used for prefill steps (S_q > 1) where the sequence length
19
+ # varies per image. dynamic=True lets one compiled graph handle
20
+ # all lengths without recompilation. Prefill is never inside a
21
+ # CUDA graph, so symbolic shape guards are fine.
22
+ compiled_flex_attn_decode = torch.compile(flex_attention, fullgraph=True)
23
+ compiled_flex_attn_prefill = torch.compile(flex_attention, dynamic=True)
24
+
25
+
26
+ def offset_mask_mod(mask_mod: _mask_mod_signature, offset: int):
27
+ """Get a mask mod function with an offset applied to the query positions."""
28
+
29
+ def _mask_mod(b, h, q, kv):
30
+ return mask_mod(b, h, q + offset, kv)
31
+
32
+ return _mask_mod
33
+
34
+
35
+ def get_causal_mask_mod() -> _mask_mod_signature:
36
+ """Causal mask that prevents attention to future tokens."""
37
+
38
+ def _causal_mask(b: T, h: T, q_idx: T, kv_idx: T) -> T:
39
+ return q_idx >= kv_idx
40
+
41
+ return _causal_mask
42
+
43
+
44
+ def get_document_mask_mod(batch: T, eos_id: int) -> _mask_mod_signature:
45
+ """Creates a document mask that prevents attention across document boundaries.
46
+
47
+ Args:
48
+ batch: Input batch tensor with shape [b, s, h, d]
49
+ eos_id: End-of-sequence token ID that marks document boundaries
50
+
51
+ Returns:
52
+ A mask modifier function that implements document-level masking.
53
+ """
54
+ # batch is [b, s, h, d] shape
55
+ eos_mask = batch == eos_id
56
+ eos_mask[:, -1] = True
57
+ cumulative_mask = torch.cumsum(torch.where(eos_mask, 1, 0), dim=1)
58
+ sequence_indices = torch.zeros_like(cumulative_mask, dtype=torch.int32)
59
+ sequence_indices[:, 1:] = cumulative_mask[:, :-1]
60
+
61
+ def document_mask(b: T, h: T, q_idx: T, kv_idx: T) -> T:
62
+ return sequence_indices[b, q_idx] == sequence_indices[b, kv_idx]
63
+
64
+ return document_mask
65
+
66
+
67
+ def get_non_left_pad_mask_mod(batch: T, pad_id: int) -> _mask_mod_signature:
68
+ """Prevent model from attending to the left-padded token required for correct batch inference."""
69
+
70
+ non_pad_mask_id = torch.cumsum(batch != pad_id, dim=1)
71
+
72
+ # Left-most pad tokens have cumulative id == 0.
73
+ def mask_mod(b, h, q_idx, kv_idx):
74
+ return non_pad_mask_id[b, kv_idx] > 0
75
+
76
+ return mask_mod
77
+
78
+
79
+ def get_image_prefix_mask_mod(
80
+ batch: T, soi_id: int, eoi_id: int
81
+ ) -> _mask_mod_signature:
82
+ # batch is [b, s, h, d] shape
83
+ soi_mask = batch == soi_id
84
+ eoi_mask = batch == eoi_id
85
+ acc_soi_mask = torch.cumsum(soi_mask, dim=1)
86
+ acc_eoi_mask = torch.cumsum(eoi_mask, dim=1)
87
+ # Get every tokens between two soi_id and eoi_id exclusive of eoi_id
88
+ img_mask = (acc_soi_mask - acc_eoi_mask) > 0
89
+
90
+ # Create a tensor that assigns each token to its image number
91
+ # Each image starts with SOI token, so we can use acc_soi_mask to track image numbers
92
+ img_indices = acc_soi_mask * img_mask
93
+
94
+ def image_prefix_mask_mod(b, h, q_idx, kv_idx):
95
+ # Check if both tokens are image tokens and belong to the same image
96
+ is_img_tokens = img_mask[b, q_idx] & img_mask[b, kv_idx]
97
+ is_same_image = img_indices[b, q_idx] == img_indices[b, kv_idx]
98
+ return is_img_tokens & is_same_image
99
+
100
+ return image_prefix_mask_mod
101
+
102
+
103
+ _compiled_create_block_mask = torch.compile(
104
+ create_block_mask, dynamic=True
105
+ ) # Note: can't use mode = 'reduce-overhead' here because it uses internal CUDA graph trees on private streams, causing manual capture to record empty graphs
106
+
107
+
108
+ @torch.inference_mode()
109
+ def create_attention_mask(*args, **kwargs):
110
+ """
111
+ NOTE: We compile this for performance/memory reasons in large masks. To reduce
112
+ recompiles due to grad_mode flips, we always run mask creation under inference_mode.
113
+ """
114
+ return _compiled_create_block_mask(*args, **kwargs)
config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "FalconOCRForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_falcon_ocr.FalconOCRConfig",
7
+ "AutoModelForCausalLM": "modeling_falcon_ocr.FalconOCRForCausalLM"
8
+ },
9
+ "model_type": "falcon_ocr",
10
+ "torch_dtype": "bfloat16",
11
+
12
+ "dim": 768,
13
+ "n_layers": 22,
14
+ "n_heads": 16,
15
+ "head_dim": 64,
16
+ "n_kv_heads": 8,
17
+ "vocab_size": 65536,
18
+ "ffn_dim": 2304,
19
+ "norm_eps": 1e-05,
20
+ "max_seq_len": 8192,
21
+ "rope_theta": 10000,
22
+
23
+ "channel_size": 3,
24
+ "spatial_patch_size": 16,
25
+ "temporal_patch_size": 1,
26
+
27
+ "img_id": 227,
28
+ "eos_id": 11,
29
+ "image_cls_token_id": 244,
30
+ "image_mask_token_id": 243,
31
+ "image_reg_1_token_id": 245,
32
+ "image_reg_2_token_id": 246,
33
+ "image_reg_3_token_id": 247,
34
+ "image_reg_4_token_id": 248,
35
+ "img_start_id": 229,
36
+ "img_end_id": 230,
37
+ "img_row_sep_id": 228,
38
+ "vid_start_id": 231,
39
+ "vid_end_id": 232,
40
+ "frame_sep_id": 233
41
+ }
configuration_falcon_ocr.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class FalconOCRConfig(PretrainedConfig):
5
+ model_type = "falcon_ocr"
6
+
7
+ def __init__(
8
+ self,
9
+ dim: int = 768,
10
+ n_layers: int = 22,
11
+ n_heads: int = 16,
12
+ head_dim: int = 64,
13
+ n_kv_heads: int = 8,
14
+ vocab_size: int = 65536,
15
+ ffn_dim: int = 2304,
16
+ norm_eps: float = 1e-5,
17
+ max_seq_len: int = 8192,
18
+ rope_theta: int = 10000,
19
+ channel_size: int = 3,
20
+ spatial_patch_size: int = 16,
21
+ temporal_patch_size: int = 1,
22
+ img_id: int = 227,
23
+ eos_id: int = 11,
24
+ image_cls_token_id: int = 244,
25
+ image_mask_token_id: int = 243,
26
+ image_reg_1_token_id: int = 245,
27
+ image_reg_2_token_id: int = 246,
28
+ image_reg_3_token_id: int = 247,
29
+ image_reg_4_token_id: int = 248,
30
+ img_start_id: int = 229,
31
+ img_end_id: int = 230,
32
+ img_row_sep_id: int = 228,
33
+ vid_start_id: int = 231,
34
+ vid_end_id: int = 232,
35
+ frame_sep_id: int = 233,
36
+ **kwargs,
37
+ ):
38
+ self.dim = dim
39
+ self.n_layers = n_layers
40
+ self.n_heads = n_heads
41
+ self.head_dim = head_dim
42
+ self.n_kv_heads = n_kv_heads
43
+ self.vocab_size = vocab_size
44
+ self.ffn_dim = ffn_dim
45
+ self.norm_eps = norm_eps
46
+ self.max_seq_len = max_seq_len
47
+ self.rope_theta = rope_theta
48
+ self.channel_size = channel_size
49
+ self.spatial_patch_size = spatial_patch_size
50
+ self.temporal_patch_size = temporal_patch_size
51
+ self.img_id = img_id
52
+ self.eos_id = eos_id
53
+ self.image_cls_token_id = image_cls_token_id
54
+ self.image_mask_token_id = image_mask_token_id
55
+ self.image_reg_1_token_id = image_reg_1_token_id
56
+ self.image_reg_2_token_id = image_reg_2_token_id
57
+ self.image_reg_3_token_id = image_reg_3_token_id
58
+ self.image_reg_4_token_id = image_reg_4_token_id
59
+ self.img_start_id = img_start_id
60
+ self.img_end_id = img_end_id
61
+ self.img_row_sep_id = img_row_sep_id
62
+ self.vid_start_id = vid_start_id
63
+ self.vid_end_id = vid_end_id
64
+ self.frame_sep_id = frame_sep_id
65
+ super().__init__(**kwargs)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aa99dfc0a738bb1499d40e24d90ced8311515c2f09516a9dad23662f91a2e63e
3
+ size 1079796208
model_args.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "channel_size": 3,
3
+ "coord_dec_dim": 8192,
4
+ "coord_enc_dim": 512,
5
+ "coord_out_dim": 2048,
6
+ "coord_token_id": 240,
7
+ "dim": 768,
8
+ "do_segmentation": false,
9
+ "eos_id": 11,
10
+ "ffn_dim": 2304,
11
+ "frame_sep_id": 233,
12
+ "head_dim": 64,
13
+ "image_cls_token_id": 244,
14
+ "image_mask_token_id": 243,
15
+ "image_reg_1_token_id": 245,
16
+ "image_reg_2_token_id": 246,
17
+ "image_reg_3_token_id": 247,
18
+ "image_reg_4_token_id": 248,
19
+ "img_end_id": 230,
20
+ "img_id": 227,
21
+ "img_row_sep_id": 228,
22
+ "img_start_id": 229,
23
+ "max_seq_len": 8192,
24
+ "n_heads": 16,
25
+ "n_kv_heads": 8,
26
+ "n_layers": 22,
27
+ "norm_eps": 1e-05,
28
+ "num_segm_layers": 3,
29
+ "rope_theta": 10000,
30
+ "seg_token_id": 262,
31
+ "segm_out_dim": 256,
32
+ "size_dec_dim": 8192,
33
+ "size_enc_dim": 512,
34
+ "size_out_dim": 2048,
35
+ "size_token_id": 241,
36
+ "spatial_patch_size": 16,
37
+ "temporal_patch_size": 1,
38
+ "vid_end_id": 232,
39
+ "vid_start_id": 231,
40
+ "vocab_size": 65536
41
+ }
modeling_falcon_ocr.py ADDED
@@ -0,0 +1,586 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from pathlib import Path
3
+
4
+ import einops as E
5
+ import torch
6
+ import torch.nn.functional as F
7
+ import triton
8
+ import triton.language as tl
9
+ from PIL import Image
10
+ from torch import Tensor as T
11
+ from torch import nn
12
+ from torch.nn.attention.flex_attention import (
13
+ AuxRequest,
14
+ BlockMask,
15
+ and_masks,
16
+ or_masks,
17
+ )
18
+ from transformers import AutoTokenizer, PreTrainedModel
19
+
20
+ from .attention import (
21
+ compiled_flex_attn_decode,
22
+ compiled_flex_attn_prefill,
23
+ create_attention_mask,
24
+ get_causal_mask_mod,
25
+ get_document_mask_mod,
26
+ get_image_prefix_mask_mod,
27
+ get_non_left_pad_mask_mod,
28
+ offset_mask_mod,
29
+ )
30
+ from .configuration_falcon_ocr import FalconOCRConfig
31
+ from .processing_falcon_ocr import load_image, process_batch
32
+ from .rope import (
33
+ apply_3d_rotary_emb,
34
+ apply_golden_freqs_cis_to_visual_pos,
35
+ precompute_freqs_cis,
36
+ )
37
+
38
+
39
+ CATEGORY_PROMPTS = {
40
+ "plain": "Extract the text content from this image.",
41
+ "formula": "Extract the formula content from this image.",
42
+ "table": "Extract the table content from this image.",
43
+ "text": "Extract the text content from this image.",
44
+ "caption": "Extract the caption content from this image.",
45
+ "footnote": "Extract the footnote content from this image.",
46
+ "list-item": "Extract the list-item content from this image.",
47
+ "page-footer": "Extract the page-footer content from this image.",
48
+ "page-header": "Extract the page-header content from this image.",
49
+ "section-header": "Extract the section-header content from this image.",
50
+ "title": "Extract the title content from this image.",
51
+ }
52
+
53
+
54
+ # ---------------------------------------------------------------------------
55
+ # Sub-modules: Attention
56
+ # ---------------------------------------------------------------------------
57
+
58
+ def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
59
+ B, S, H, D = x.shape
60
+ if n_rep == 1:
61
+ return x
62
+ return torch.unsqueeze(x, dim=3).expand(B, S, H, n_rep, D).reshape(B, S, H * n_rep, D)
63
+
64
+
65
+ class Attention(nn.Module):
66
+ def __init__(self, config: FalconOCRConfig, layer_id: int):
67
+ super().__init__()
68
+ self.layer_id = layer_id
69
+ self.n_kv_heads = config.n_kv_heads or config.n_heads
70
+ self.n_rep = config.n_heads // self.n_kv_heads
71
+ self.head_dim = config.head_dim or config.dim // config.n_heads
72
+ self.q_dim = config.n_heads * self.head_dim
73
+ self.kv_dim = self.n_kv_heads * self.head_dim
74
+
75
+ self.wq = nn.Linear(config.dim, self.q_dim, bias=False)
76
+ self.wk = nn.Linear(config.dim, self.kv_dim, bias=False)
77
+ self.wv = nn.Linear(config.dim, self.kv_dim, bias=False)
78
+ self.wo = nn.Linear(config.n_heads * self.head_dim, config.dim, bias=False)
79
+ self.sinks = nn.Parameter(torch.empty((config.n_heads,)))
80
+
81
+ def _fuse_weights(self):
82
+ wqkv_weight = torch.cat([self.wq.weight.data, self.wk.weight.data, self.wv.weight.data], dim=0)
83
+ self.register_buffer("_wqkv_weight", wqkv_weight)
84
+ del self.wq, self.wk, self.wv
85
+
86
+ def _pre_attention_qkv(self, x) -> tuple[T, T, T]:
87
+ qkv = F.linear(F.rms_norm(x, (x.size(-1),)), self._wqkv_weight)
88
+ xq, xk, xv = qkv.split([self.q_dim, self.kv_dim, self.kv_dim], dim=-1)
89
+ xq = E.rearrange(xq, "b s (h d) -> b s h d", d=self.head_dim)
90
+ xk = E.rearrange(xk, "b s (h d) -> b s h d", d=self.head_dim)
91
+ xv = E.rearrange(xv, "b s (h d) -> b s h d", d=self.head_dim)
92
+ xq = F.rms_norm(xq, (xq.size(-1),))
93
+ xk = F.rms_norm(xk, (xk.size(-1),))
94
+ xk = repeat_kv(xk, n_rep=self.n_rep)
95
+ xv = repeat_kv(xv, n_rep=self.n_rep)
96
+ return xq, xk, xv
97
+
98
+ def _post_attention(self, output: T, lse: T) -> T:
99
+ sinks_BHS = self.sinks.view(1, -1, 1)
100
+ sink_scale = torch.sigmoid(lse - sinks_BHS)
101
+ output = (output * sink_scale.unsqueeze(-1)).to(output.dtype)
102
+ output = output.permute(0, 2, 1, 3).contiguous().flatten(2)
103
+ return self.wo(output)
104
+
105
+ def compile_attention(self, *, dynamic: bool = True, mode: str = "default"):
106
+ self._pre_attention_qkv = torch.compile(self._pre_attention_qkv, dynamic=dynamic, mode=mode)
107
+ self._post_attention = torch.compile(self._post_attention, dynamic=dynamic, mode=mode)
108
+
109
+ def forward(
110
+ self, x: T, attention_masks: BlockMask, freqs_cis: T,
111
+ freqs_cis_2d: T | None = None, pos_hw: T | None = None,
112
+ kv_cache=None, input_pos=None, batch_idx=None,
113
+ flex_attn_kernel_options=None,
114
+ ):
115
+ xq, xk, xv = self._pre_attention_qkv(x)
116
+ xq, xk = apply_3d_rotary_emb(xq, xk, freqs_cis, freqs_cis_2d, pos_hw)
117
+ xq = E.rearrange(xq, "b s h d -> b h s d")
118
+ xk = E.rearrange(xk, "b s h d -> b h s d")
119
+ xv = E.rearrange(xv, "b s h d -> b h s d")
120
+ xk, xv = kv_cache.insert_kv(self.layer_id, xk, xv, input_pos=input_pos, batch_idx=batch_idx)
121
+ flex_fn = compiled_flex_attn_decode if xq.shape[2] == 1 else compiled_flex_attn_prefill
122
+ output, aux_output = flex_fn(xq, xk, xv, block_mask=attention_masks, return_aux=AuxRequest(lse=True))
123
+ return self._post_attention(output, aux_output.lse)
124
+
125
+
126
+ # ---------------------------------------------------------------------------
127
+ # Sub-modules: FeedForward
128
+ # ---------------------------------------------------------------------------
129
+
130
+ @triton.jit
131
+ def _squared_relu_gate_kernel(
132
+ packed_ptr, out_ptr, n_rows, n_cols,
133
+ in_row_stride, in_col_stride, out_row_stride, out_col_stride,
134
+ BLOCK_SIZE: tl.constexpr,
135
+ ):
136
+ pid = tl.program_id(0)
137
+ n_elements = n_rows * n_cols
138
+ offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
139
+ mask = offsets < n_elements
140
+ rows = offsets // n_cols
141
+ cols = offsets % n_cols
142
+ gate_idx = rows * in_row_stride + (2 * cols) * in_col_stride
143
+ up_idx = rows * in_row_stride + (2 * cols + 1) * in_col_stride
144
+ out_idx = rows * out_row_stride + cols * out_col_stride
145
+ gate = tl.load(packed_ptr + gate_idx, mask=mask)
146
+ up = tl.load(packed_ptr + up_idx, mask=mask)
147
+ gate = tl.where(gate > 0, gate, 0.0)
148
+ out = gate * gate * up
149
+ tl.store(out_ptr + out_idx, out, mask=mask)
150
+
151
+
152
+ def squared_relu_gate(packed: T, hidden_dim: int) -> T:
153
+ packed_2d = packed.flatten(0, -2)
154
+ n_rows = packed_2d.shape[0]
155
+ n_cols = hidden_dim
156
+ out_2d = torch.empty((n_rows, n_cols), device=packed.device, dtype=packed.dtype)
157
+ n = n_rows * n_cols
158
+ grid = lambda meta: (triton.cdiv(n, meta["BLOCK_SIZE"]),)
159
+ _squared_relu_gate_kernel[grid](
160
+ packed_2d, out_2d, n_rows, n_cols,
161
+ packed_2d.stride(0), packed_2d.stride(1),
162
+ out_2d.stride(0), out_2d.stride(1),
163
+ BLOCK_SIZE=1024,
164
+ )
165
+ return out_2d.view(*packed.shape[:-1], hidden_dim)
166
+
167
+
168
+ class FeedForward(nn.Module):
169
+ def __init__(self, dim: int, hidden_dim: int):
170
+ super().__init__()
171
+ self.w1 = nn.Linear(dim, hidden_dim, bias=False)
172
+ self.w2 = nn.Linear(hidden_dim, dim, bias=False)
173
+ self.w3 = nn.Linear(dim, hidden_dim, bias=False)
174
+ self.hidden_dim = hidden_dim
175
+
176
+ def _fuse_weights(self):
177
+ if hasattr(self, "_w13_weight"):
178
+ return
179
+ w1_weight_fused = self.w1.weight.data * math.sqrt(2.0)
180
+ w13_weight = torch.empty(
181
+ (2 * self.hidden_dim, self.w1.weight.shape[1]),
182
+ device=w1_weight_fused.device, dtype=w1_weight_fused.dtype,
183
+ )
184
+ w13_weight[0::2] = w1_weight_fused
185
+ w13_weight[1::2] = self.w3.weight.data
186
+ self.register_buffer("_w13_weight", w13_weight)
187
+ del self.w1, self.w3
188
+
189
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
190
+ x = F.rms_norm(x, (x.size(-1),))
191
+ w13_out = F.linear(x, self._w13_weight)
192
+ return self.w2(squared_relu_gate(w13_out, self.hidden_dim))
193
+
194
+
195
+ # ---------------------------------------------------------------------------
196
+ # Sub-modules: TransformerBlock
197
+ # ---------------------------------------------------------------------------
198
+
199
+ class TransformerBlock(nn.Module):
200
+ def __init__(self, layer_id: int, config: FalconOCRConfig):
201
+ super().__init__()
202
+ self.attention = Attention(config, layer_id)
203
+ self.feed_forward = FeedForward(config.dim, config.ffn_dim)
204
+
205
+ def compile(self, *, dynamic: bool = True, mode: str = "default"):
206
+ self.feed_forward = torch.compile(self.feed_forward, dynamic=dynamic, mode=mode)
207
+ self.attention.compile_attention(dynamic=dynamic, mode=mode)
208
+ return self
209
+
210
+ def forward(
211
+ self, x: T, freqs_cis: T, freqs_cis_2d: T | None = None,
212
+ pos_hw: T | None = None, attention_masks=None, kv_cache=None,
213
+ input_pos=None, batch_idx=None, flex_attn_kernel_options=None,
214
+ ):
215
+ B, S, D = x.shape
216
+ x = x + self.attention(
217
+ x, freqs_cis=freqs_cis, freqs_cis_2d=freqs_cis_2d, pos_hw=pos_hw,
218
+ attention_masks=attention_masks, kv_cache=kv_cache,
219
+ input_pos=input_pos, batch_idx=batch_idx,
220
+ flex_attn_kernel_options=flex_attn_kernel_options,
221
+ )
222
+ out = x + self.feed_forward(x)
223
+ return out.reshape(B, S, D)
224
+
225
+
226
+ # ---------------------------------------------------------------------------
227
+ # KV Cache
228
+ # ---------------------------------------------------------------------------
229
+
230
+ class KVCache:
231
+ def __init__(self, max_batch_size, max_seq_length, n_heads, head_dim, num_layers):
232
+ self.kv_shape = (num_layers, 2, max_batch_size, n_heads, max_seq_length, head_dim)
233
+ self.kv_cache = None
234
+ self.pos = 0
235
+ self.pos_t: T | None = None
236
+
237
+ def reset(self):
238
+ self.pos = 0
239
+ self.pos_t = None
240
+
241
+ def get_pos(self):
242
+ return self.pos
243
+
244
+ def set_pos_t(self, pos_t):
245
+ self.pos_t = pos_t
246
+
247
+ def increment_and_get_pos_t(self):
248
+ assert self.pos_t is not None
249
+ self.pos_t += 1
250
+ return self.pos_t
251
+
252
+ def insert_kv(self, layer_id: int, k: T, v: T, **kwargs):
253
+ del kwargs
254
+ assert self.pos_t is not None
255
+ if self.kv_cache is None:
256
+ self.kv_cache = torch.empty(self.kv_shape, dtype=k.dtype, device=k.device)
257
+ B, H, T_add, D = k.size()
258
+ t0, t1 = self.pos, self.pos + T_add
259
+ self.kv_cache[layer_id, 0, :, :, t0:t1] = k
260
+ self.kv_cache[layer_id, 1, :, :, t0:t1] = v
261
+ key_view = self.kv_cache[layer_id, 0, :, :, :t1]
262
+ value_view = self.kv_cache[layer_id, 1, :, :, :t1]
263
+ if layer_id == self.kv_cache.size(0) - 1:
264
+ self.pos = t1
265
+ return key_view, value_view
266
+
267
+
268
+ # ---------------------------------------------------------------------------
269
+ # Sampling
270
+ # ---------------------------------------------------------------------------
271
+
272
+ @torch.inference_mode()
273
+ def sample_next_token(logits, rng, temperature=0.0, top_k=None):
274
+ assert temperature >= 0.0
275
+ if temperature == 0.0:
276
+ return torch.argmax(logits, dim=-1, keepdim=True)
277
+ if top_k is not None:
278
+ k = min(top_k, logits.size(-1))
279
+ vals, idx = torch.topk(logits, k, dim=-1)
280
+ vals = vals / temperature
281
+ probs = F.softmax(vals, dim=-1)
282
+ choice = torch.multinomial(probs, num_samples=1, generator=rng)
283
+ return idx.gather(1, choice)
284
+ logits = logits / temperature
285
+ probs = F.softmax(logits, dim=-1)
286
+ return torch.multinomial(probs, num_samples=1, generator=rng)
287
+
288
+
289
+ # ---------------------------------------------------------------------------
290
+ # Main Model
291
+ # ---------------------------------------------------------------------------
292
+
293
+ class FalconOCRForCausalLM(PreTrainedModel):
294
+ config_class = FalconOCRConfig
295
+ _no_split_modules = ["TransformerBlock"]
296
+
297
+ def __init__(self, config: FalconOCRConfig):
298
+ super().__init__(config)
299
+ img_in_dim = config.temporal_patch_size * config.spatial_patch_size ** 2 * config.channel_size
300
+ self.img_projector = nn.Linear(img_in_dim, config.dim, bias=False)
301
+ self.tok_embeddings = nn.Embedding(config.vocab_size, config.dim)
302
+
303
+ self.layers = nn.ModuleDict()
304
+ for layer_id in range(config.n_layers):
305
+ self.layers[str(layer_id)] = TransformerBlock(layer_id, config)
306
+
307
+ self.norm = nn.RMSNorm(config.dim, eps=config.norm_eps)
308
+ self.output = nn.Linear(config.dim, config.vocab_size, bias=False)
309
+
310
+ rope_dim = config.head_dim // 2
311
+ freqs_cis = precompute_freqs_cis(rope_dim, config.max_seq_len, config.rope_theta)
312
+ freqs_cis_golden = torch.empty((config.n_heads, rope_dim // 2, 2), dtype=torch.float)
313
+ self.register_buffer("freqs_cis", freqs_cis, persistent=False)
314
+ self.register_buffer("freqs_cis_golden", freqs_cis_golden, persistent=True)
315
+
316
+ self._weights_fused = False
317
+ self._is_compiled = False
318
+
319
+ self.post_init()
320
+
321
+ # -- Weight management ---------------------------------------------------
322
+
323
+ def _fuse_weights(self):
324
+ if self._weights_fused:
325
+ return
326
+
327
+ device = self.tok_embeddings.weight.device
328
+ c = self.config
329
+
330
+ rope_dim = c.head_dim // 2
331
+ freqs_cis = precompute_freqs_cis(rope_dim, c.max_seq_len, c.rope_theta).to(device)
332
+ self.register_buffer("freqs_cis", freqs_cis, persistent=False)
333
+
334
+ if self.freqs_cis_golden.device != device:
335
+ self.freqs_cis_golden = self.freqs_cis_golden.to(device)
336
+
337
+ for layer in self.layers.values():
338
+ layer.attention._fuse_weights()
339
+ layer.feed_forward._fuse_weights()
340
+ self._weights_fused = True
341
+
342
+ def compile_model(self):
343
+ if self._is_compiled:
344
+ return
345
+ torch._inductor.config.triton.cudagraphs = False
346
+ for layer in self.layers.values():
347
+ layer.compile(dynamic=True, mode="default")
348
+ self._is_compiled = True
349
+
350
+ # -- Tokenizer -----------------------------------------------------------
351
+
352
+ def _get_tokenizer(self):
353
+ if not hasattr(self, "_tokenizer"):
354
+ import os
355
+ path = self.config._name_or_path
356
+ is_local = os.path.exists(path)
357
+ self._tokenizer = AutoTokenizer.from_pretrained(path, local_files_only=is_local, trust_remote_code=True)
358
+ for token_name, token in self._tokenizer.special_tokens_map.items():
359
+ if isinstance(token, str):
360
+ setattr(self._tokenizer, token_name, token)
361
+ setattr(
362
+ self._tokenizer, token_name + "_id",
363
+ self._tokenizer.convert_tokens_to_ids(token),
364
+ )
365
+ return self._tokenizer
366
+
367
+ # -- Attention mask ------------------------------------------------------
368
+
369
+ def get_attention_mask(self, input_batch: T, max_len: int | None = None):
370
+ B, S = input_batch.size()
371
+ c = self.config
372
+ block_causal_mask_mod = and_masks(
373
+ get_causal_mask_mod(),
374
+ get_document_mask_mod(input_batch, c.eos_id),
375
+ get_non_left_pad_mask_mod(input_batch, self._pad_token_id),
376
+ )
377
+ image_prefix_mask_mod = get_image_prefix_mask_mod(
378
+ batch=input_batch, soi_id=c.image_cls_token_id, eoi_id=c.img_end_id,
379
+ )
380
+ mask_mod = or_masks(image_prefix_mask_mod, block_causal_mask_mod)
381
+ max_len = max_len or S
382
+ return create_attention_mask(mask_mod, B, None, max_len, max_len)
383
+
384
+ # -- Embedding helpers ---------------------------------------------------
385
+
386
+ def _scatter_img_tokens_with_projector(self, h_BSD, pixel_patches_NLC, pixel_masks_NTHW, tokens_BS):
387
+ B, S, D = h_BSD.shape
388
+ pixel_patch_mask = E.reduce(
389
+ pixel_masks_NTHW,
390
+ "n (t pt) (h ph) (w pw) -> (n t h w)",
391
+ reduction="any",
392
+ pt=self.config.temporal_patch_size,
393
+ ph=self.config.spatial_patch_size,
394
+ pw=self.config.spatial_patch_size,
395
+ )
396
+ pixel_patches_flat = E.rearrange(pixel_patches_NLC, "n p c -> (n p) c")
397
+ valid_patches = pixel_patches_flat[pixel_patch_mask]
398
+ valid_feats = self.img_projector(valid_patches)
399
+ img_mask_h_BSD = E.repeat(tokens_BS == self.config.img_id, "b s -> b s d", d=D)
400
+ assert valid_feats.numel() == img_mask_h_BSD.sum()
401
+ return torch.masked_scatter(h_BSD, img_mask_h_BSD, valid_feats)
402
+
403
+ # -- Core forward --------------------------------------------------------
404
+
405
+ def forward(
406
+ self,
407
+ tokens: T,
408
+ attention_mask: BlockMask,
409
+ kv_cache,
410
+ rope_pos_t: T | None = None,
411
+ rope_pos_hw: T | None = None,
412
+ pixel_values: T | None = None,
413
+ pixel_mask: T | None = None,
414
+ ):
415
+ B, S = tokens.size()
416
+ c = self.config
417
+ block_mask = attention_mask
418
+
419
+ T_pos = kv_cache.get_pos()
420
+ is_prefill = S != 1
421
+
422
+ if is_prefill:
423
+ assert rope_pos_t is not None and rope_pos_hw is not None
424
+ pos_t = rope_pos_t[:, T_pos:T_pos + S].long()
425
+ kv_cache.pos_t = pos_t[:, -1:]
426
+ freqs_cis = self.freqs_cis[pos_t]
427
+ rope_pos_hw = rope_pos_hw[:, T_pos:T_pos + S]
428
+ freqs_cis_golden = apply_golden_freqs_cis_to_visual_pos(self.freqs_cis_golden, rope_pos_hw)
429
+ block_mask.seq_lengths = (S, S)
430
+ else:
431
+ pos_t = kv_cache.increment_and_get_pos_t()
432
+ freqs_cis = self.freqs_cis[pos_t]
433
+ freqs_cis_golden = None
434
+ block_idx = T_pos // block_mask.BLOCK_SIZE[0]
435
+ block_mask = block_mask[:, :, block_idx]
436
+ block_mask.seq_lengths = (S, T_pos + S)
437
+ block_mask.mask_mod = offset_mask_mod(attention_mask.mask_mod, offset=T_pos)
438
+
439
+ h_BSD = self.tok_embeddings(tokens)
440
+
441
+ if pixel_values is not None:
442
+ assert pixel_mask is not None
443
+ pixel_values = pixel_values.to(self.dtype)
444
+ pixel_mask = pixel_mask.to(self.dtype)
445
+ pixel_patches_NLC = E.rearrange(
446
+ pixel_values,
447
+ "n (t pt) (h ph) (w pw) c -> n (t h w) (pt ph pw c)",
448
+ pt=c.temporal_patch_size, ph=c.spatial_patch_size, pw=c.spatial_patch_size,
449
+ )
450
+ h_BSD = self._scatter_img_tokens_with_projector(h_BSD, pixel_patches_NLC, pixel_mask, tokens)
451
+
452
+ for layer in self.layers.values():
453
+ h_BSD = layer(
454
+ h_BSD, freqs_cis=freqs_cis, freqs_cis_2d=freqs_cis_golden,
455
+ pos_hw=rope_pos_hw, attention_masks=block_mask, kv_cache=kv_cache,
456
+ )
457
+
458
+ h_BSD = self.norm(h_BSD)
459
+ logits_BSV = self.output(h_BSD)
460
+ return logits_BSV
461
+
462
+ # -- Main API: generate --------------------------------------------------
463
+
464
+ @torch.inference_mode()
465
+ def generate(
466
+ self,
467
+ images,
468
+ *,
469
+ category: str | list[str] = "plain",
470
+ max_new_tokens: int = 4096,
471
+ temperature: float = 0.0,
472
+ top_k: int | None = None,
473
+ min_dimension: int = 64,
474
+ max_dimension: int = 1024,
475
+ compile: bool = True,
476
+ seed: int | None = 42,
477
+ ) -> list[str]:
478
+ """
479
+ Extract text from document images.
480
+
481
+ Args:
482
+ images: Single PIL Image (or path/URL) or list of them.
483
+ category: OCR category — one of "plain", "text", "table", "formula",
484
+ "caption", "footnote", "list-item", "page-footer", "page-header",
485
+ "section-header", "title". Can be a single string (applied to all
486
+ images) or a list (one per image).
487
+ max_new_tokens: Maximum generation steps.
488
+ temperature: Sampling temperature (0.0 = greedy).
489
+ top_k: Top-k sampling (None = disabled).
490
+ min_dimension: Min image side after resize.
491
+ max_dimension: Max image side after resize.
492
+ compile: Whether to torch.compile on first call.
493
+ seed: Random seed for reproducibility (None = non-deterministic).
494
+
495
+ Returns:
496
+ List of extracted text strings, one per image.
497
+ """
498
+ self._fuse_weights()
499
+ if compile:
500
+ self.compile_model()
501
+
502
+ if isinstance(images, (str, Path, Image.Image)):
503
+ images = [images]
504
+ if isinstance(category, str):
505
+ category = [category] * len(images)
506
+ assert len(images) == len(category), "Must provide one category per image"
507
+
508
+ device = self.device
509
+ tokenizer = self._get_tokenizer()
510
+ self._pad_token_id = tokenizer.convert_tokens_to_ids("<|pad|>")
511
+ stop_token_ids = [self.config.eos_id, tokenizer.convert_tokens_to_ids("<|end_of_query|>")]
512
+
513
+ image_prompt_pairs = []
514
+ for img, cat in zip(images, category):
515
+ instruction = CATEGORY_PROMPTS.get(cat.strip().lower(), CATEGORY_PROMPTS["plain"])
516
+ prompt = f"<|image|>{instruction}\n<|OCR_PLAIN|>"
517
+ image_prompt_pairs.append((img, prompt))
518
+
519
+ batch_inputs = process_batch(
520
+ tokenizer, self.config, image_prompt_pairs,
521
+ max_length=4096, min_dimension=min_dimension, max_dimension=max_dimension,
522
+ )
523
+ batch_inputs = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in batch_inputs.items()}
524
+
525
+ tokens = batch_inputs["tokens"]
526
+ B, L = tokens.size()
527
+ block_size = 128
528
+ S = (L + max_new_tokens + block_size - 1) // block_size * block_size
529
+ assert S <= self.config.max_seq_len
530
+
531
+ rng = torch.Generator(device).manual_seed(seed) if seed is not None else None
532
+
533
+ kv_cache = KVCache(
534
+ max_batch_size=B, max_seq_length=S, n_heads=self.config.n_heads,
535
+ head_dim=self.config.head_dim, num_layers=self.config.n_layers,
536
+ )
537
+
538
+ padded_tokens = torch.full((B, S), self._pad_token_id, dtype=tokens.dtype, device=device)
539
+ padded_tokens[:, :L] = tokens
540
+
541
+ attention_mask = self.get_attention_mask(padded_tokens, max_len=S)
542
+
543
+ # Prefill
544
+ logits_BSV = self.forward(
545
+ tokens=tokens, rope_pos_t=batch_inputs["pos_t"], rope_pos_hw=batch_inputs["pos_hw"],
546
+ attention_mask=attention_mask, kv_cache=kv_cache,
547
+ pixel_values=batch_inputs["pixel_values"], pixel_mask=batch_inputs["pixel_mask"],
548
+ )
549
+
550
+ stop_ids = torch.tensor(stop_token_ids).to(device)
551
+ should_stop_B = torch.full((B,), False, dtype=torch.bool, device=device)
552
+ generated_ids: list[list[int]] = [[] for _ in range(B)]
553
+
554
+ # Decode loop
555
+ while not torch.all(should_stop_B) and (pos := kv_cache.get_pos()) < S:
556
+ tokens_B1 = sample_next_token(logits_BSV[:, -1], rng, temperature, top_k)
557
+
558
+ if torch.any(should_stop_B):
559
+ tokens_B1 = tokens_B1.clone()
560
+ tokens_B1[should_stop_B, :] = self._pad_token_id
561
+ padded_tokens[:, pos] = tokens_B1[:, -1]
562
+
563
+ for b in range(B):
564
+ if not should_stop_B[b]:
565
+ generated_ids[b].append(tokens_B1[b, 0].item())
566
+
567
+ logits_BSV = self.forward(
568
+ tokens=tokens_B1, attention_mask=attention_mask, kv_cache=kv_cache,
569
+ )
570
+
571
+ hit_stop_B = torch.isin(tokens_B1, stop_ids).any(dim=-1)
572
+ should_stop_B = should_stop_B.logical_or(hit_stop_B)
573
+
574
+ # Decode tokens to text
575
+ results = []
576
+ for b in range(B):
577
+ text = tokenizer.decode(generated_ids[b], skip_special_tokens=False)
578
+ text = (
579
+ text
580
+ .replace("<|end_of_query|>", "")
581
+ .replace("<|end_of_text|>", "")
582
+ .strip()
583
+ )
584
+ results.append(text)
585
+
586
+ return results
processing_falcon_ocr.py ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import math
3
+
4
+ import einops as E
5
+ import numpy as np
6
+ import requests
7
+ import torch
8
+ from PIL import Image
9
+ from transformers.image_processing_utils import BaseImageProcessor
10
+ from transformers.image_transforms import convert_to_rgb, resize
11
+ from transformers.image_utils import (
12
+ ImageInput,
13
+ get_image_size,
14
+ infer_channel_dimension_format,
15
+ to_numpy_array,
16
+ valid_images,
17
+ validate_preprocess_arguments,
18
+ )
19
+
20
+ IMAGE_MEAN = [0.5, 0.5, 0.5]
21
+ IMAGE_STD = [0.5, 0.5, 0.5]
22
+
23
+
24
+ def load_image(image):
25
+ if image is None:
26
+ return None
27
+ if isinstance(image, Image.Image):
28
+ return image
29
+ if isinstance(image, str):
30
+ if image.startswith(("http://", "https://")):
31
+ response = requests.get(image, timeout=10)
32
+ response.raise_for_status()
33
+ return Image.open(io.BytesIO(response.content))
34
+ if image.endswith(".npy"):
35
+ img_array = io.BytesIO(np.load(image))
36
+ return Image.open(img_array)
37
+ return Image.open(image)
38
+ if isinstance(image, np.bytes_):
39
+ return Image.open(io.BytesIO(image))
40
+ if isinstance(image, np.ndarray):
41
+ return Image.fromarray(image)
42
+ raise TypeError(f"Unknown image format {image}")
43
+
44
+
45
+ def load_images(images_input, min_dimension: int, max_dimension: int):
46
+ images = []
47
+ if images_input is not None:
48
+ for inp in images_input:
49
+ img = load_image(inp)
50
+ img = resize_image_if_necessary(img, min_dimension, max_dimension)
51
+ images.append(img)
52
+ return images
53
+
54
+
55
+ def resize_image_if_necessary(
56
+ image,
57
+ shortest_dimension=224,
58
+ longest_dimension=896,
59
+ ):
60
+ original_width, original_height = image.size
61
+ aspect_ratio = original_width / original_height
62
+
63
+ if (
64
+ shortest_dimension <= original_width <= longest_dimension
65
+ and shortest_dimension <= original_height <= longest_dimension
66
+ ):
67
+ return image
68
+
69
+ is_vertical_image = original_width < original_height
70
+ if original_width < shortest_dimension or original_height < shortest_dimension:
71
+ if is_vertical_image:
72
+ new_width = shortest_dimension
73
+ new_height = int(new_width / aspect_ratio)
74
+ else:
75
+ new_height = shortest_dimension
76
+ new_width = int(new_height * aspect_ratio)
77
+ else:
78
+ if is_vertical_image:
79
+ new_width = longest_dimension
80
+ new_height = int(new_width / aspect_ratio)
81
+ else:
82
+ new_height = longest_dimension
83
+ new_width = int(new_height * aspect_ratio)
84
+
85
+ if new_width > longest_dimension:
86
+ new_width = longest_dimension
87
+ new_height = int(new_width / aspect_ratio)
88
+ if new_height > longest_dimension:
89
+ new_height = longest_dimension
90
+ new_width = int(new_height * aspect_ratio)
91
+
92
+ resized_image = image.resize((new_width, new_height))
93
+ return resized_image
94
+
95
+
96
+ def smart_resize(
97
+ image,
98
+ factor: int,
99
+ resample,
100
+ input_data_format,
101
+ min_pixels: int = 56 * 56,
102
+ max_pixels: int = 14 * 14 * 4 * 1280,
103
+ ):
104
+ height, width = get_image_size(image, channel_dim=input_data_format)
105
+ if height < factor or width < factor:
106
+ raise ValueError(f"{height=} or {width=} must be larger than {factor=}")
107
+ if max(height, width) / min(height, width) > 200:
108
+ raise ValueError(
109
+ f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"
110
+ )
111
+ h_bar = round(height / factor) * factor
112
+ w_bar = round(width / factor) * factor
113
+ if h_bar * w_bar > max_pixels:
114
+ beta = np.sqrt((height * width) / max_pixels)
115
+ h_bar = math.floor(height / beta / factor) * factor
116
+ w_bar = math.floor(width / beta / factor) * factor
117
+ elif h_bar * w_bar < min_pixels:
118
+ beta = np.sqrt(min_pixels / (height * width))
119
+ h_bar = math.ceil(height * beta / factor) * factor
120
+ w_bar = math.ceil(width * beta / factor) * factor
121
+ image = resize(
122
+ image,
123
+ size=(h_bar, w_bar),
124
+ resample=resample,
125
+ input_data_format=input_data_format,
126
+ )
127
+ return image
128
+
129
+
130
+ class ImageProcessor(BaseImageProcessor):
131
+ def __init__(
132
+ self,
133
+ patch_size,
134
+ merge_size,
135
+ do_resize: bool = True,
136
+ resample: Image.Resampling = Image.Resampling.BICUBIC,
137
+ do_rescale: bool = True,
138
+ rescale_factor: float = 1 / 255,
139
+ do_normalize: bool = True,
140
+ image_mean: float | list[float] | None = None,
141
+ image_std: float | list[float] | None = None,
142
+ do_convert_rgb: bool = True,
143
+ min_pixels: int = 56 * 56,
144
+ max_pixels: int = 28 * 28 * 1280,
145
+ **kwargs,
146
+ ) -> None:
147
+ super().__init__(**kwargs)
148
+ self.do_resize = do_resize
149
+ self.resample = resample
150
+ self.do_rescale = do_rescale
151
+ self.rescale_factor = rescale_factor
152
+ self.do_normalize = do_normalize
153
+ self.image_mean = image_mean or IMAGE_MEAN
154
+ self.image_std = image_std or IMAGE_STD
155
+ self.min_pixels = min_pixels
156
+ self.max_pixels = max_pixels
157
+ self.patch_size = patch_size
158
+ self.merge_size = merge_size
159
+ self.size = {"min_pixels": min_pixels, "max_pixels": max_pixels}
160
+ self.do_convert_rgb = do_convert_rgb
161
+ validate_preprocess_arguments(
162
+ rescale_factor=self.rescale_factor,
163
+ do_normalize=self.do_normalize,
164
+ image_mean=self.image_mean,
165
+ image_std=self.image_std,
166
+ do_resize=self.do_resize,
167
+ size=self.size,
168
+ resample=self.resample,
169
+ )
170
+
171
+ def _preprocess(self, image: ImageInput, do_rescale=None, do_normalize=None):
172
+ if self.do_convert_rgb:
173
+ image = convert_to_rgb(image)
174
+ image = to_numpy_array(image)
175
+ input_data_format = infer_channel_dimension_format(image)
176
+ if self.do_resize:
177
+ image = smart_resize(
178
+ image,
179
+ factor=self.patch_size * self.merge_size,
180
+ resample=self.resample,
181
+ input_data_format=input_data_format,
182
+ min_pixels=self.min_pixels,
183
+ max_pixels=self.max_pixels,
184
+ )
185
+ if do_rescale or self.do_rescale:
186
+ image = self.rescale(image, scale=self.rescale_factor, input_data_format=input_data_format)
187
+ if do_normalize or self.do_normalize:
188
+ image = self.normalize(
189
+ image=image, mean=self.image_mean, std=self.image_std,
190
+ input_data_format=input_data_format,
191
+ )
192
+ return image
193
+
194
+ def preprocess(self, images: list[ImageInput] | None, do_rescale=None, do_normalize=None, **kwargs):
195
+ del kwargs
196
+ if images is None:
197
+ return []
198
+ images = [item for item in images if item is not None]
199
+ if not valid_images(images):
200
+ raise ValueError(
201
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
202
+ "torch.Tensor, tf.Tensor or jax.ndarray."
203
+ )
204
+ pixel_values = []
205
+ for image in images:
206
+ processed_image = self._preprocess(image, do_rescale, do_normalize)
207
+ processed_image = processed_image[None, ...]
208
+ pixel_values.append(processed_image)
209
+ return pixel_values
210
+
211
+ def batch_images_with_mask(self, pixel_values, max_image_height, max_image_width):
212
+ if pixel_values is None:
213
+ return None
214
+ pixel_values = [item for item in pixel_values if item is not None and len(item) != 0]
215
+ if len(pixel_values) == 0:
216
+ return None
217
+ pixel_values = [torch.from_numpy(img) for img in pixel_values]
218
+ max_temporal = max(img.shape[0] for img in pixel_values)
219
+
220
+ def pad_image_and_mask(img):
221
+ time_steps, height, width, channels = img.shape
222
+ if channels != 3:
223
+ raise ValueError(f"Expected 3-channel RGB images, got {channels} channels.")
224
+ padding = (0, 0, 0, max_image_width - width, 0, max_image_height - height, 0, max_temporal - time_steps)
225
+ padded_image = torch.nn.functional.pad(img, padding)
226
+ mask = torch.zeros((max_temporal, max_image_height, max_image_width), dtype=torch.long)
227
+ mask[:time_steps, :height, :width] = 1
228
+ return padded_image, mask
229
+
230
+ padded_pixel_values, padding_masks = zip(*[pad_image_and_mask(img) for img in pixel_values])
231
+ padded_pixel_values = torch.stack(list(padded_pixel_values))
232
+ padding_masks = torch.stack(list(padding_masks))
233
+ return {"pixel_values": padded_pixel_values, "padding_mask": padding_masks}
234
+
235
+
236
+ # ---------------------------------------------------------------------------
237
+ # Positional encoding helpers
238
+ # ---------------------------------------------------------------------------
239
+
240
+ def _compute_image_spatial_positions(
241
+ pixel_mask_THW: torch.Tensor,
242
+ spatial_patch_size: int,
243
+ temporal_patch_size: int = 1,
244
+ ) -> tuple[torch.Tensor, torch.Tensor]:
245
+ mask_thw = E.reduce(
246
+ pixel_mask_THW,
247
+ "(t tp) (h hp) (w wp) -> t h w",
248
+ reduction="any",
249
+ tp=temporal_patch_size,
250
+ hp=spatial_patch_size,
251
+ wp=spatial_patch_size,
252
+ )
253
+ width = E.reduce(mask_thw.sum(dim=-1).int(), "t h -> ", reduction="max")
254
+ height = E.reduce(mask_thw.sum(dim=-2).int(), "t w -> ", reduction="max")
255
+ xlim = torch.sqrt(width / height)
256
+ ylim = torch.sqrt(height / width)
257
+ xpos = torch.linspace(-xlim, xlim, int(width))
258
+ ypos = torch.linspace(-ylim, ylim, int(height))
259
+ wpos, hpos = torch.meshgrid(xpos, ypos, indexing="xy")
260
+ return hpos.flatten(), wpos.flatten()
261
+
262
+
263
+ def _get_image_token_masks(tokens, config):
264
+ spatial_mask = tokens == config.img_id
265
+ no_increase_mask = (
266
+ spatial_mask
267
+ | (tokens == config.image_reg_1_token_id)
268
+ | (tokens == config.image_reg_2_token_id)
269
+ | (tokens == config.image_reg_3_token_id)
270
+ | (tokens == config.image_reg_4_token_id)
271
+ | (tokens == config.img_end_id)
272
+ )
273
+ return spatial_mask, no_increase_mask
274
+
275
+
276
+ def get_pos_thw(
277
+ tokens: torch.Tensor,
278
+ pixel_masks_NTHW: torch.Tensor,
279
+ config,
280
+ spatial_patch_size: int,
281
+ temporal_patch_size: int = 1,
282
+ pad_token_id: int = None,
283
+ ):
284
+ assert pad_token_id is not None
285
+ assert tokens.ndim == 2
286
+ assert pixel_masks_NTHW.ndim == 4
287
+
288
+ spatial_img_token_mask_BS, no_increase_idx_img_token_mask_BS = _get_image_token_masks(tokens, config)
289
+
290
+ hpos_parts, wpos_parts = [], []
291
+ for i in range(pixel_masks_NTHW.shape[0]):
292
+ h, w = _compute_image_spatial_positions(pixel_masks_NTHW[i], spatial_patch_size, temporal_patch_size)
293
+ hpos_parts.append(h)
294
+ wpos_parts.append(w)
295
+
296
+ hpos_N = torch.cat(hpos_parts) if hpos_parts else torch.empty(0)
297
+ wpos_N = torch.cat(wpos_parts) if wpos_parts else torch.empty(0)
298
+
299
+ expected_tokens = spatial_img_token_mask_BS.sum().item()
300
+ actual_tokens = hpos_N.numel()
301
+ assert actual_tokens == expected_tokens, (
302
+ f"Mismatch between spatial image tokens ({expected_tokens}) and generated positions ({actual_tokens})."
303
+ )
304
+
305
+ hpos_BS = torch.full_like(tokens, fill_value=torch.nan, dtype=torch.float, device=tokens.device)
306
+ wpos_BS = torch.full_like(tokens, fill_value=torch.nan, dtype=torch.float, device=tokens.device)
307
+ hpos_BS = hpos_BS.masked_scatter_(spatial_img_token_mask_BS, hpos_N)
308
+ wpos_BS = wpos_BS.masked_scatter_(spatial_img_token_mask_BS, wpos_N)
309
+
310
+ tpos_BS = torch.ones_like(tokens, dtype=torch.float, device=tokens.device)
311
+ tpos_BS[no_increase_idx_img_token_mask_BS] = 0
312
+ tpos_BS = torch.cumsum(tpos_BS, dim=1) - 1
313
+ tpos_BS[tokens == pad_token_id] = 0
314
+
315
+ hw_pos_BS2 = torch.stack([hpos_BS, wpos_BS], dim=-1)
316
+ return tpos_BS.long(), hw_pos_BS2
317
+
318
+
319
+ def calculate_image_tokens(image, patch_size, merge_size):
320
+ height, width = get_image_size(image)
321
+ return int((height * width) / (patch_size * patch_size * merge_size * merge_size))
322
+
323
+
324
+ def tokenize_inputs(prompt, images, tokenizer, config, patch_size, merge_size, max_length):
325
+ img_reg_ids = [
326
+ config.image_reg_1_token_id,
327
+ config.image_reg_2_token_id,
328
+ config.image_reg_3_token_id,
329
+ config.image_reg_4_token_id,
330
+ ]
331
+
332
+ if images is not None and len(images) > 0:
333
+ image_token_counts = [calculate_image_tokens(image, patch_size, merge_size) for image in images]
334
+ else:
335
+ image_token_counts = []
336
+
337
+ image_token = tokenizer.convert_ids_to_tokens(config.img_id)
338
+ prompt_chunks = [tokenizer.encode(chunk) for chunk in prompt.split(image_token)]
339
+
340
+ def insert_separator(X, sep):
341
+ return [ele for sublist in zip(X, sep) for ele in sublist][:-1]
342
+
343
+ input_ids = []
344
+ offset = 0
345
+ bos_id = getattr(tokenizer, "bos_token_id", None)
346
+ if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and bos_id is not None and prompt_chunks[0][0] == bos_id:
347
+ offset = 1
348
+ input_ids.append(prompt_chunks[0][0])
349
+
350
+ separators = []
351
+ for count in image_token_counts:
352
+ tokens = [config.img_id] * count
353
+ image_block = [config.image_cls_token_id, *img_reg_ids, *tokens, config.img_end_id]
354
+ separators.append(image_block)
355
+
356
+ if len(separators) != 0 and len(separators) != len(prompt_chunks):
357
+ separators.append(separators[-1])
358
+
359
+ selected_images = []
360
+ if len(separators) == 0:
361
+ input_ids = prompt_chunks[0]
362
+ else:
363
+ for index, x in enumerate(insert_separator(prompt_chunks, separators)):
364
+ if index % 2 != 0:
365
+ if (len(input_ids) + len(x)) < max_length:
366
+ input_ids.extend(x)
367
+ selected_images.append(images[index // 2])
368
+ elif index % 2 == 0:
369
+ input_ids.extend(x[offset:])
370
+
371
+ input_ids = torch.LongTensor(input_ids)
372
+ return input_ids, selected_images
373
+
374
+
375
+ def process_batch(
376
+ tokenizer,
377
+ config,
378
+ image_prompt_pairs,
379
+ max_length,
380
+ min_dimension,
381
+ max_dimension,
382
+ patch_size=16,
383
+ merge_size=1,
384
+ ):
385
+ """
386
+ Process a batch of images with text prompts.
387
+ Uses LEFT PADDING for proper batch generation with causal models.
388
+ """
389
+ all_input_ids = []
390
+ all_selected_images = []
391
+ processor_local = ImageProcessor(patch_size, merge_size)
392
+
393
+ for img_input, prompt in image_prompt_pairs:
394
+ img = load_image(img_input)
395
+ if img is not None:
396
+ img = resize_image_if_necessary(img, min_dimension, max_dimension)
397
+ images = processor_local.preprocess(images=[img] if img else [])
398
+ input_ids, selected_images = tokenize_inputs(
399
+ prompt, images, tokenizer, config, patch_size, merge_size, max_length,
400
+ )
401
+ all_input_ids.append(input_ids)
402
+ all_selected_images.extend(selected_images)
403
+
404
+ pad_token_id = tokenizer.convert_tokens_to_ids("<|pad|>")
405
+ padded_input_ids = torch.nn.utils.rnn.pad_sequence(
406
+ all_input_ids, batch_first=True, padding_value=pad_token_id, padding_side="left",
407
+ )
408
+
409
+ processed = processor_local.batch_images_with_mask(all_selected_images, max_dimension, max_dimension)
410
+ assert processed is not None
411
+
412
+ pos_t, pos_hw = get_pos_thw(
413
+ padded_input_ids, processed["padding_mask"], config, patch_size, pad_token_id=pad_token_id,
414
+ )
415
+
416
+ return {
417
+ "tokens": padded_input_ids,
418
+ "pixel_values": processed["pixel_values"],
419
+ "pixel_mask": processed["padding_mask"],
420
+ "pos_t": pos_t,
421
+ "pos_hw": pos_hw,
422
+ "pad_token_id": pad_token_id,
423
+ }
rope.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import einops as E
2
+ import torch
3
+
4
+
5
+ def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0) -> torch.Tensor:
6
+ """
7
+ Precompute the frequency tensor for complex exponentials (cis) with given dimensions.
8
+
9
+ This function calculates a frequency tensor with complex exponentials using the given dimension 'dim'
10
+ and the end index 'end'. The 'theta' parameter scales the frequencies.
11
+ The returned tensor contains complex values in complex64 data type.
12
+
13
+ Args:
14
+ dim (int): Dimension of the frequency tensor.
15
+ end (int): End index for precomputing frequencies.
16
+ theta (float, optional): Scaling factor for frequency computation. Defaults to 10000.0.
17
+
18
+ Returns:
19
+ torch.Tensor: Precomputed frequency tensor with complex exponentials.
20
+ """
21
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
22
+ t = torch.arange(end, device=freqs.device)
23
+ freqs = torch.outer(t, freqs).float()
24
+ freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
25
+ return freqs_cis # [S, D//2]
26
+
27
+
28
+ def apply_rotary_emb(
29
+ xq: torch.Tensor,
30
+ xk: torch.Tensor,
31
+ freqs_cis: torch.Tensor,
32
+ ) -> tuple[torch.Tensor, torch.Tensor]:
33
+ """1D rotary embedding"""
34
+ xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
35
+ xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
36
+ assert freqs_cis.ndim == 3, (
37
+ "Freqs_cis must be indexed by position ids already and has shape (B,S,D)"
38
+ )
39
+ freqs_cis = E.rearrange(freqs_cis, "b s d -> b s 1 d")
40
+ xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
41
+ xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
42
+ return xq_out.type_as(xq), xk_out.type_as(xk)
43
+
44
+
45
+ ###### 2D golden rope
46
+ """
47
+ Dimension key:
48
+ B: batch size
49
+ S: number of tokens per sample, Seqlen
50
+ T: Number of selected Tokens
51
+ P: pos_dim
52
+ h: n_heads
53
+ d: head_dim
54
+ F: num_freqs == head_dim // 2
55
+ """
56
+
57
+
58
+ def apply_golden_freqs_cis_to_visual_pos(freqs_hFP, pos_BSP) -> torch.Tensor:
59
+ """
60
+ This function is applied once per input batch, and the cached
61
+ freqs_cis is passed through to all layers.
62
+ Safe for Torch‑Inductor because it never uses boolean indexing on a symbolic tensor.
63
+ """
64
+ # 1. Boolean mask → integer indices (no unbacked shapes)
65
+ img_mask_BS = E.reduce(~torch.isnan(pos_BSP), 'b s p -> b s', reduction='all')
66
+ idx_b, idx_s = torch.nonzero(img_mask_BS, as_tuple=True) # each shape: (N,)
67
+
68
+ # 2. Gather the positional tensor for those tokens
69
+ pos_tP = pos_BSP[idx_b, idx_s].float() # (N, p)
70
+
71
+ # 3. Project positions onto the frequency table → angles θ
72
+ theta_thF = torch.einsum("tp,hfp->thf", pos_tP, freqs_hFP.float()) # (t, h, f)
73
+
74
+ # 4. Convert to complex numbers on the unit circle
75
+ freqs_cis_thF = torch.polar(torch.ones_like(theta_thF), theta_thF)
76
+ return freqs_cis_thF
77
+
78
+
79
+ def apply_golden_rotary_emb(input_BShd, freqs_cis_thF, pos_BSP) -> torch.Tensor:
80
+ """
81
+ Rotates *only* the image tokens in `input_BShd`. No boolean indexing,
82
+ so it is safe for Torch‑Inductor.
83
+ """
84
+ img_mask_BS = E.reduce(~torch.isnan(pos_BSP), 'b s p -> b s', reduction='all')
85
+ idx_b, idx_s = torch.nonzero(img_mask_BS, as_tuple=True) # (N,)
86
+
87
+ input_thd = input_BShd[idx_b, idx_s].float() # (N, h, d)
88
+ x_even = input_thd[..., 0::2] # (N, h, F)
89
+ x_odd = input_thd[..., 1::2] # (N, h, F)
90
+
91
+ cos_thF = freqs_cis_thF.real
92
+ sin_thF = freqs_cis_thF.imag
93
+
94
+ # (a + ib) * (c + id) = (ac - bd) + i(ad + bc)
95
+ rot_even = x_even * cos_thF - x_odd * sin_thF
96
+ rot_odd = x_even * sin_thF + x_odd * cos_thF
97
+
98
+ output_real = torch.empty_like(input_thd)
99
+ output_real[..., 0::2] = rot_even
100
+ output_real[..., 1::2] = rot_odd
101
+ output_real = output_real.type_as(input_BShd)
102
+
103
+ output_BShd = input_BShd.clone()
104
+ output_BShd[idx_b, idx_s] = output_real
105
+
106
+ return output_BShd
107
+
108
+
109
+ def apply_3d_rotary_emb(
110
+ xq: torch.Tensor, # (B, S, H, D)
111
+ xk: torch.Tensor, # (B, S, H, D)
112
+ freqs_cis: torch.Tensor,
113
+ freqs_cis_2d: torch.Tensor | None,
114
+ pos_hw: torch.Tensor | None, # (B,S,3)
115
+ ) -> tuple[torch.Tensor, torch.Tensor]:
116
+ xq_t, xq_hw = xq.chunk(chunks=2, dim=-1)
117
+ xk_t, xk_hw = xk.chunk(chunks=2, dim=-1)
118
+ B, S, H, D = xq.shape
119
+
120
+ xq_t, xk_t = apply_rotary_emb(xq_t, xk_t, freqs_cis)
121
+ if freqs_cis_2d is not None and pos_hw is not None:
122
+ xq_hw = apply_golden_rotary_emb(xq_hw, freqs_cis_2d, pos_hw)
123
+ xk_hw = apply_golden_rotary_emb(xk_hw, freqs_cis_2d, pos_hw)
124
+
125
+ xq_out = torch.concat([xq_t, xq_hw], dim=-1).type_as(xq)
126
+ xk_out = torch.concat([xk_t, xk_hw], dim=-1).type_as(xk)
127
+ return xq_out, xk_out
special_tokens_map.json ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|pad|>",
4
+ ">>ABSTRACT<<",
5
+ ">>INTRODUCTION<<",
6
+ ">>SUMMARY<<",
7
+ ">>COMMENT<<",
8
+ ">>ANSWER<<",
9
+ ">>QUESTION<<",
10
+ ">>DOMAIN<<",
11
+ ">>PREFIX<<",
12
+ ">>SUFFIX<<",
13
+ ">>MIDDLE<<",
14
+ "<|finetune_right_pad_id|>",
15
+ "<|start_header_id|>",
16
+ "<|end_header_id|>",
17
+ "<|eom_id|>",
18
+ "<|eot_id|>",
19
+ "<|begin_of_text|>",
20
+ ">>TITLE<<",
21
+ "<tool_response>",
22
+ "</tool_response>",
23
+ "<tool_call>",
24
+ "</tool_call>",
25
+ "<schema>",
26
+ "</schema>",
27
+ "<scratch_pad>",
28
+ "</scratch_pad>",
29
+ "<thinking>",
30
+ "</thinking>",
31
+ "<explanation>",
32
+ "</explanation>",
33
+ "<file_sep>",
34
+ "<repo_name>",
35
+ "<tr>",
36
+ "</tr>",
37
+ "<|image|>",
38
+ "<|image_row_sep|>",
39
+ "<|start_of_image|>",
40
+ "<|end_of_image|>",
41
+ "<|start_of_video|>",
42
+ "<|end_of_video|>",
43
+ "<|frame_sep|>",
44
+ "<|start_of_turn|>",
45
+ "<|end_of_turn|>",
46
+ "<|start_of_diffusion_query|>",
47
+ "<|end_of_diffusion_query|>",
48
+ "<|diffusion_query|>",
49
+ "<|object|>",
50
+ "<|coord|>",
51
+ "<|size|>",
52
+ "<|perceive|>",
53
+ "<|image_mask_token|>",
54
+ "<|image_cls|>",
55
+ "<|image_reg_1|>",
56
+ "<|image_reg_2|>",
57
+ "<|image_reg_3|>",
58
+ "<|image_reg_4|>",
59
+ "<|image_reg_5|>",
60
+ "<|image_reg_6|>",
61
+ "<|image_reg_7|>",
62
+ "<|image_reg_8|>",
63
+ "<|DET|>",
64
+ "<|POINTING|>",
65
+ "<|OCR_GROUNDING|>",
66
+ "<|OCR_DOC_PARSER|>",
67
+ "<|OCR_PLAIN|>",
68
+ "<|REF_SEG|>",
69
+ "<|POINT_REF_SEG|>",
70
+ "<|CAPTION|>",
71
+ "<|DETAILED_CAPTION|>",
72
+ "<|seg|>",
73
+ "<|end_of_query|>",
74
+ "<|start_of_query|>",
75
+ "<|task_sep|>",
76
+ "<|QA|>",
77
+ "<|LAYOUT_DETECTION|>",
78
+ "<|category_sep|>",
79
+ "<td>",
80
+ "</td>",
81
+ "<th>",
82
+ "</th>",
83
+ ">>UNUSED_261<<",
84
+ ">>UNUSED_262<<",
85
+ ">>UNUSED_263<<",
86
+ ">>UNUSED_264<<",
87
+ ">>UNUSED_265<<",
88
+ ">>UNUSED_266<<",
89
+ ">>UNUSED_267<<",
90
+ ">>UNUSED_268<<",
91
+ ">>UNUSED_269<<",
92
+ ">>UNUSED_270<<",
93
+ ">>UNUSED_271<<",
94
+ ">>UNUSED_272<<",
95
+ ">>UNUSED_273<<",
96
+ ">>UNUSED_274<<",
97
+ ">>UNUSED_275<<",
98
+ ">>UNUSED_276<<",
99
+ ">>UNUSED_277<<",
100
+ ">>UNUSED_278<<",
101
+ ">>UNUSED_279<<",
102
+ ">>UNUSED_280<<",
103
+ ">>UNUSED_281<<",
104
+ ">>UNUSED_282<<",
105
+ ">>UNUSED_283<<",
106
+ ">>UNUSED_284<<",
107
+ ">>UNUSED_285<<",
108
+ ">>UNUSED_286<<",
109
+ ">>UNUSED_287<<",
110
+ ">>UNUSED_288<<",
111
+ ">>UNUSED_289<<",
112
+ ">>UNUSED_290<<",
113
+ ">>UNUSED_291<<",
114
+ ">>UNUSED_292<<",
115
+ ">>UNUSED_293<<",
116
+ ">>UNUSED_294<<",
117
+ ">>UNUSED_295<<",
118
+ ">>UNUSED_296<<",
119
+ ">>UNUSED_297<<",
120
+ ">>UNUSED_298<<",
121
+ ">>UNUSED_299<<",
122
+ ">>UNUSED_300<<",
123
+ ">>UNUSED_301<<",
124
+ ">>UNUSED_302<<",
125
+ ">>UNUSED_303<<",
126
+ ">>UNUSED_304<<",
127
+ ">>UNUSED_305<<",
128
+ ">>UNUSED_306<<",
129
+ ">>UNUSED_307<<",
130
+ ">>UNUSED_308<<",
131
+ ">>UNUSED_309<<",
132
+ ">>UNUSED_310<<",
133
+ ">>UNUSED_311<<",
134
+ ">>UNUSED_312<<",
135
+ ">>UNUSED_313<<",
136
+ ">>UNUSED_314<<",
137
+ ">>UNUSED_315<<",
138
+ ">>UNUSED_316<<",
139
+ ">>UNUSED_317<<",
140
+ ">>UNUSED_318<<",
141
+ ">>UNUSED_319<<",
142
+ ">>UNUSED_320<<",
143
+ ">>UNUSED_321<<",
144
+ ">>UNUSED_322<<",
145
+ ">>UNUSED_323<<",
146
+ ">>UNUSED_324<<",
147
+ ">>UNUSED_325<<",
148
+ ">>UNUSED_326<<",
149
+ ">>UNUSED_327<<",
150
+ ">>UNUSED_328<<",
151
+ ">>UNUSED_329<<",
152
+ ">>UNUSED_330<<",
153
+ ">>UNUSED_331<<",
154
+ ">>UNUSED_332<<",
155
+ ">>UNUSED_333<<",
156
+ ">>UNUSED_334<<",
157
+ ">>UNUSED_335<<",
158
+ ">>UNUSED_336<<",
159
+ ">>UNUSED_337<<",
160
+ ">>UNUSED_338<<",
161
+ ">>UNUSED_339<<",
162
+ ">>UNUSED_340<<",
163
+ ">>UNUSED_341<<",
164
+ ">>UNUSED_342<<",
165
+ ">>UNUSED_343<<",
166
+ ">>UNUSED_344<<",
167
+ ">>UNUSED_345<<",
168
+ ">>UNUSED_346<<",
169
+ ">>UNUSED_347<<",
170
+ ">>UNUSED_348<<",
171
+ ">>UNUSED_349<<",
172
+ ">>UNUSED_350<<",
173
+ ">>UNUSED_351<<",
174
+ ">>UNUSED_352<<",
175
+ ">>UNUSED_353<<",
176
+ ">>UNUSED_354<<",
177
+ ">>UNUSED_355<<",
178
+ ">>UNUSED_356<<",
179
+ ">>UNUSED_357<<",
180
+ ">>UNUSED_358<<",
181
+ ">>UNUSED_359<<",
182
+ ">>UNUSED_360<<",
183
+ ">>UNUSED_361<<",
184
+ ">>UNUSED_362<<",
185
+ ">>UNUSED_363<<",
186
+ ">>UNUSED_364<<",
187
+ ">>UNUSED_365<<",
188
+ ">>UNUSED_366<<",
189
+ ">>UNUSED_367<<",
190
+ ">>UNUSED_368<<",
191
+ ">>UNUSED_369<<",
192
+ ">>UNUSED_370<<",
193
+ ">>UNUSED_371<<",
194
+ ">>UNUSED_372<<",
195
+ ">>UNUSED_373<<",
196
+ ">>UNUSED_374<<",
197
+ ">>UNUSED_375<<",
198
+ ">>UNUSED_376<<",
199
+ ">>UNUSED_377<<",
200
+ ">>UNUSED_378<<",
201
+ ">>UNUSED_379<<",
202
+ ">>UNUSED_380<<",
203
+ ">>UNUSED_381<<",
204
+ ">>UNUSED_382<<",
205
+ ">>UNUSED_383<<",
206
+ ">>UNUSED_384<<",
207
+ ">>UNUSED_385<<",
208
+ ">>UNUSED_386<<",
209
+ ">>UNUSED_387<<",
210
+ ">>UNUSED_388<<",
211
+ ">>UNUSED_389<<",
212
+ ">>UNUSED_390<<",
213
+ ">>UNUSED_391<<",
214
+ ">>UNUSED_392<<",
215
+ ">>UNUSED_393<<",
216
+ ">>UNUSED_394<<",
217
+ ">>UNUSED_395<<",
218
+ ">>UNUSED_396<<",
219
+ ">>UNUSED_397<<",
220
+ ">>UNUSED_398<<",
221
+ ">>UNUSED_399<<",
222
+ ">>UNUSED_400<<",
223
+ ">>UNUSED_401<<",
224
+ ">>UNUSED_402<<",
225
+ ">>UNUSED_403<<",
226
+ ">>UNUSED_404<<",
227
+ ">>UNUSED_405<<",
228
+ ">>UNUSED_406<<",
229
+ ">>UNUSED_407<<",
230
+ ">>UNUSED_408<<",
231
+ ">>UNUSED_409<<",
232
+ ">>UNUSED_410<<",
233
+ ">>UNUSED_411<<",
234
+ ">>UNUSED_412<<",
235
+ ">>UNUSED_413<<",
236
+ ">>UNUSED_414<<",
237
+ ">>UNUSED_415<<",
238
+ ">>UNUSED_416<<",
239
+ ">>UNUSED_417<<",
240
+ ">>UNUSED_418<<",
241
+ ">>UNUSED_419<<",
242
+ ">>UNUSED_420<<",
243
+ ">>UNUSED_421<<",
244
+ ">>UNUSED_422<<",
245
+ ">>UNUSED_423<<",
246
+ ">>UNUSED_424<<",
247
+ ">>UNUSED_425<<",
248
+ ">>UNUSED_426<<",
249
+ ">>UNUSED_427<<",
250
+ ">>UNUSED_428<<",
251
+ ">>UNUSED_429<<",
252
+ ">>UNUSED_430<<",
253
+ ">>UNUSED_431<<",
254
+ ">>UNUSED_432<<",
255
+ ">>UNUSED_433<<",
256
+ ">>UNUSED_434<<",
257
+ ">>UNUSED_435<<",
258
+ ">>UNUSED_436<<",
259
+ ">>UNUSED_437<<",
260
+ ">>UNUSED_438<<",
261
+ ">>UNUSED_439<<",
262
+ ">>UNUSED_440<<",
263
+ ">>UNUSED_441<<",
264
+ ">>UNUSED_442<<",
265
+ ">>UNUSED_443<<",
266
+ ">>UNUSED_444<<",
267
+ ">>UNUSED_445<<",
268
+ ">>UNUSED_446<<",
269
+ ">>UNUSED_447<<",
270
+ ">>UNUSED_448<<",
271
+ ">>UNUSED_449<<",
272
+ ">>UNUSED_450<<",
273
+ ">>UNUSED_451<<",
274
+ ">>UNUSED_452<<",
275
+ ">>UNUSED_453<<",
276
+ ">>UNUSED_454<<",
277
+ ">>UNUSED_455<<",
278
+ ">>UNUSED_456<<",
279
+ ">>UNUSED_457<<",
280
+ ">>UNUSED_458<<",
281
+ ">>UNUSED_459<<",
282
+ ">>UNUSED_460<<",
283
+ ">>UNUSED_461<<",
284
+ ">>UNUSED_462<<",
285
+ ">>UNUSED_463<<",
286
+ ">>UNUSED_464<<",
287
+ ">>UNUSED_465<<",
288
+ ">>UNUSED_466<<",
289
+ ">>UNUSED_467<<",
290
+ ">>UNUSED_468<<",
291
+ ">>UNUSED_469<<",
292
+ ">>UNUSED_470<<",
293
+ ">>UNUSED_471<<",
294
+ ">>UNUSED_472<<",
295
+ ">>UNUSED_473<<",
296
+ ">>UNUSED_474<<",
297
+ ">>UNUSED_475<<",
298
+ ">>UNUSED_476<<",
299
+ ">>UNUSED_477<<",
300
+ ">>UNUSED_478<<",
301
+ ">>UNUSED_479<<",
302
+ ">>UNUSED_480<<",
303
+ ">>UNUSED_481<<",
304
+ ">>UNUSED_482<<",
305
+ ">>UNUSED_483<<",
306
+ ">>UNUSED_484<<",
307
+ ">>UNUSED_485<<",
308
+ ">>UNUSED_486<<",
309
+ ">>UNUSED_487<<",
310
+ ">>UNUSED_488<<",
311
+ ">>UNUSED_489<<",
312
+ ">>UNUSED_490<<",
313
+ ">>UNUSED_491<<",
314
+ ">>UNUSED_492<<",
315
+ ">>UNUSED_493<<",
316
+ ">>UNUSED_494<<",
317
+ ">>UNUSED_495<<",
318
+ ">>UNUSED_496<<",
319
+ ">>UNUSED_497<<",
320
+ ">>UNUSED_498<<",
321
+ ">>UNUSED_499<<",
322
+ ">>UNUSED_500<<",
323
+ ">>UNUSED_501<<",
324
+ ">>UNUSED_502<<",
325
+ ">>UNUSED_503<<",
326
+ ">>UNUSED_504<<",
327
+ ">>UNUSED_505<<",
328
+ ">>UNUSED_506<<",
329
+ ">>UNUSED_507<<",
330
+ ">>UNUSED_508<<",
331
+ ">>UNUSED_509<<",
332
+ ">>UNUSED_510<<",
333
+ ">>UNUSED_511<<"
334
+ ],
335
+ "eos_token": {
336
+ "content": "<|end_of_text|>",
337
+ "lstrip": false,
338
+ "normalized": false,
339
+ "rstrip": false,
340
+ "single_word": false
341
+ },
342
+ "image_token": "<|image|>",
343
+ "image_cls_token": "<|image_cls|>",
344
+ "image_reg_1_token": "<|image_reg_1|>",
345
+ "image_reg_2_token": "<|image_reg_2|>",
346
+ "image_reg_3_token": "<|image_reg_3|>",
347
+ "image_reg_4_token": "<|image_reg_4|>",
348
+ "image_reg_5_token": "<|image_reg_5|>",
349
+ "image_reg_6_token": "<|image_reg_6|>",
350
+ "image_reg_7_token": "<|image_reg_7|>",
351
+ "image_reg_8_token": "<|image_reg_8|>",
352
+ "image_row_sep_token": "<|image_row_sep|>",
353
+ "start_of_image_token": "<|start_of_image|>",
354
+ "end_of_image_token": "<|end_of_image|>",
355
+ "start_of_video_token": "<|start_of_video|>",
356
+ "end_of_video_token": "<|end_of_video|>",
357
+ "frame_sep_token": "<|frame_sep|>",
358
+ "start_of_turn_token": "<|start_of_turn|>",
359
+ "end_of_turn_token": "<|end_of_turn|>",
360
+ "start_of_diffusion_query_token": "<|start_of_diffusion_query|>",
361
+ "end_of_diffusion_query_token": "<|end_of_diffusion_query|>",
362
+ "diffusion_query_token": "<|diffusion_query|>",
363
+ "object_token": "<|object|>",
364
+ "coord_token": "<|coord|>",
365
+ "size_token": "<|size|>",
366
+ "perceive_token": "<|perceive|>",
367
+ "image_mask_token": "<|image_mask_token|>",
368
+ "det_token": "<|DET|>",
369
+ "pointing_token": "<|POINTING|>",
370
+ "ocr_grounding_token": "<|OCR_GROUNDING|>",
371
+ "ocr_doc_parser_token": "<|OCR_DOC_PARSER|>",
372
+ "ocr_plain_token": "<|OCR_PLAIN|>",
373
+ "ref_seg_token": "<|REF_SEG|>",
374
+ "point_ref_seg_token": "<|POINT_REF_SEG|>",
375
+ "caption_token": "<|CAPTION|>",
376
+ "detailed_caption_token": "<|DETAILED_CAPTION|>",
377
+ "seg_token": "<|seg|>",
378
+ "start_of_query_token": "<|start_of_query|>",
379
+ "end_of_query_token": "<|end_of_query|>",
380
+ "task_sep_token": "<|task_sep|>",
381
+ "qa_token": "<|QA|>",
382
+ "layout_detection_token": "<|LAYOUT_DETECTION|>",
383
+ "category_sep_token": "<|category_sep|>",
384
+ "table_row_start_token": "<tr>",
385
+ "table_row_end_token": "</tr>",
386
+ "table_data_start_token": "<td>",
387
+ "table_data_end_token": "</td>",
388
+ "table_header_start_token": "<th>",
389
+ "table_header_end_token": "</th>"
390
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
The diff for this file is too large to render. See raw diff