Image-to-Text
Transformers
Safetensors
falcon_ocr
text-generation
falcon
ocr
vision-language
document-understanding
v1.5
custom_code
Eval Results
Instructions to use tiiuae/Falcon-OCR with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use tiiuae/Falcon-OCR with Transformers:
# Use a pipeline as a high-level helper # Warning: Pipeline type "image-to-text" is no longer supported in transformers v5. # You must load the model directly (see below) or downgrade to v4.x with: # pip install "transformers<5.0.0" from transformers import pipeline pipe = pipeline("image-to-text", model="tiiuae/Falcon-OCR", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("tiiuae/Falcon-OCR", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
update fused weight code
Browse files- attention.py +37 -22
- modeling_falcon_ocr.py +31 -79
attention.py
CHANGED
|
@@ -1,9 +1,12 @@
|
|
| 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 |
# ---------------------------------------------------------------------------
|
|
@@ -42,16 +45,7 @@ def get_causal_mask_mod() -> _mask_mod_signature:
|
|
| 42 |
|
| 43 |
|
| 44 |
def get_document_mask_mod(batch: T, eos_id: int) -> _mask_mod_signature:
|
| 45 |
-
"""
|
| 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)
|
|
@@ -79,20 +73,15 @@ def get_non_left_pad_mask_mod(batch: T, pad_id: int) -> _mask_mod_signature:
|
|
| 79 |
def get_image_prefix_mask_mod(
|
| 80 |
batch: T, soi_id: int, eoi_id: int
|
| 81 |
) -> _mask_mod_signature:
|
| 82 |
-
|
| 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
|
|
@@ -102,13 +91,39 @@ def get_image_prefix_mask_mod(
|
|
| 102 |
|
| 103 |
_compiled_create_block_mask = torch.compile(
|
| 104 |
create_block_mask, dynamic=True
|
| 105 |
-
)
|
| 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)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import torch
|
| 2 |
from torch import Tensor as T
|
| 3 |
from torch.nn.attention.flex_attention import (
|
| 4 |
+
BlockMask,
|
| 5 |
_mask_mod_signature,
|
| 6 |
+
and_masks,
|
| 7 |
create_block_mask,
|
| 8 |
flex_attention,
|
| 9 |
+
or_masks,
|
| 10 |
)
|
| 11 |
|
| 12 |
# ---------------------------------------------------------------------------
|
|
|
|
| 45 |
|
| 46 |
|
| 47 |
def get_document_mask_mod(batch: T, eos_id: int) -> _mask_mod_signature:
|
| 48 |
+
"""Document mask: prevents attention across document boundaries (token IDs [B, S])."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
eos_mask = batch == eos_id
|
| 50 |
eos_mask[:, -1] = True
|
| 51 |
cumulative_mask = torch.cumsum(torch.where(eos_mask, 1, 0), dim=1)
|
|
|
|
| 73 |
def get_image_prefix_mask_mod(
|
| 74 |
batch: T, soi_id: int, eoi_id: int
|
| 75 |
) -> _mask_mod_signature:
|
| 76 |
+
"""Image-prefix mask: tokens between SOI and EOI attend only within same image."""
|
| 77 |
soi_mask = batch == soi_id
|
| 78 |
eoi_mask = batch == eoi_id
|
| 79 |
acc_soi_mask = torch.cumsum(soi_mask, dim=1)
|
| 80 |
acc_eoi_mask = torch.cumsum(eoi_mask, dim=1)
|
|
|
|
| 81 |
img_mask = (acc_soi_mask - acc_eoi_mask) > 0
|
|
|
|
|
|
|
|
|
|
| 82 |
img_indices = acc_soi_mask * img_mask
|
| 83 |
|
| 84 |
def image_prefix_mask_mod(b, h, q_idx, kv_idx):
|
|
|
|
| 85 |
is_img_tokens = img_mask[b, q_idx] & img_mask[b, kv_idx]
|
| 86 |
is_same_image = img_indices[b, q_idx] == img_indices[b, kv_idx]
|
| 87 |
return is_img_tokens & is_same_image
|
|
|
|
| 91 |
|
| 92 |
_compiled_create_block_mask = torch.compile(
|
| 93 |
create_block_mask, dynamic=True
|
| 94 |
+
) # reduce-overhead mode breaks manual CUDA graph capture (private streams)
|
| 95 |
|
| 96 |
|
| 97 |
@torch.inference_mode()
|
| 98 |
+
def create_attention_mask(*args, **kwargs) -> BlockMask:
|
| 99 |
+
"""Compiled for large masks; inference_mode avoids grad_mode recompiles."""
|
|
|
|
|
|
|
|
|
|
| 100 |
return _compiled_create_block_mask(*args, **kwargs)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def create_batch_attention_mask(
|
| 104 |
+
input_batch: T,
|
| 105 |
+
*,
|
| 106 |
+
pad_token_id: int,
|
| 107 |
+
eos_token_id: int,
|
| 108 |
+
soi_token_id: int,
|
| 109 |
+
eoi_token_id: int,
|
| 110 |
+
max_len: int | None = None,
|
| 111 |
+
) -> BlockMask:
|
| 112 |
+
"""Build the combined FlexAttention mask for the batch engine.
|
| 113 |
+
|
| 114 |
+
Composes causal + document + non-left-pad + image-prefix masks.
|
| 115 |
+
"""
|
| 116 |
+
B, S = input_batch.size()
|
| 117 |
+
block_causal_mask_mod = and_masks(
|
| 118 |
+
get_causal_mask_mod(),
|
| 119 |
+
get_document_mask_mod(input_batch, eos_token_id),
|
| 120 |
+
get_non_left_pad_mask_mod(input_batch, pad_token_id),
|
| 121 |
+
)
|
| 122 |
+
image_prefix_mask_mod = get_image_prefix_mask_mod(
|
| 123 |
+
batch=input_batch,
|
| 124 |
+
soi_id=soi_token_id,
|
| 125 |
+
eoi_id=eoi_token_id,
|
| 126 |
+
)
|
| 127 |
+
mask_mod = or_masks(image_prefix_mask_mod, block_causal_mask_mod)
|
| 128 |
+
max_len = max_len or S
|
| 129 |
+
return create_attention_mask(mask_mod, B, None, max_len, max_len)
|
modeling_falcon_ocr.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
import math
|
| 2 |
from pathlib import Path
|
| 3 |
|
| 4 |
import einops as E
|
|
@@ -12,19 +11,13 @@ 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 |
-
|
| 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
|
|
@@ -120,9 +113,7 @@ def _filter_nested_detections(detections: list[dict], containment_threshold: flo
|
|
| 120 |
return keep
|
| 121 |
|
| 122 |
|
| 123 |
-
#
|
| 124 |
-
# Sub-modules: Attention
|
| 125 |
-
# ---------------------------------------------------------------------------
|
| 126 |
|
| 127 |
def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 128 |
B, S, H, D = x.shape
|
|
@@ -141,19 +132,12 @@ class Attention(nn.Module):
|
|
| 141 |
self.q_dim = config.n_heads * self.head_dim
|
| 142 |
self.kv_dim = self.n_kv_heads * self.head_dim
|
| 143 |
|
| 144 |
-
self.
|
| 145 |
-
self.wk = nn.Linear(config.dim, self.kv_dim, bias=False)
|
| 146 |
-
self.wv = nn.Linear(config.dim, self.kv_dim, bias=False)
|
| 147 |
self.wo = nn.Linear(config.n_heads * self.head_dim, config.dim, bias=False)
|
| 148 |
self.sinks = nn.Parameter(torch.empty((config.n_heads,)))
|
| 149 |
|
| 150 |
-
def _fuse_weights(self):
|
| 151 |
-
wqkv_weight = torch.cat([self.wq.weight.data, self.wk.weight.data, self.wv.weight.data], dim=0)
|
| 152 |
-
self.register_buffer("_wqkv_weight", wqkv_weight)
|
| 153 |
-
del self.wq, self.wk, self.wv
|
| 154 |
-
|
| 155 |
def _pre_attention_qkv(self, x) -> tuple[T, T, T]:
|
| 156 |
-
qkv =
|
| 157 |
xq, xk, xv = qkv.split([self.q_dim, self.kv_dim, self.kv_dim], dim=-1)
|
| 158 |
xq = E.rearrange(xq, "b s (h d) -> b s h d", d=self.head_dim)
|
| 159 |
xk = E.rearrange(xk, "b s (h d) -> b s h d", d=self.head_dim)
|
|
@@ -165,6 +149,8 @@ class Attention(nn.Module):
|
|
| 165 |
return xq, xk, xv
|
| 166 |
|
| 167 |
def _post_attention(self, output: T, lse: T) -> T:
|
|
|
|
|
|
|
| 168 |
sinks_BHS = self.sinks.view(1, -1, 1)
|
| 169 |
sink_scale = torch.sigmoid(lse - sinks_BHS)
|
| 170 |
output = (output * sink_scale.unsqueeze(-1)).to(output.dtype)
|
|
@@ -192,9 +178,7 @@ class Attention(nn.Module):
|
|
| 192 |
return self._post_attention(output, aux_output.lse)
|
| 193 |
|
| 194 |
|
| 195 |
-
#
|
| 196 |
-
# Sub-modules: FeedForward
|
| 197 |
-
# ---------------------------------------------------------------------------
|
| 198 |
|
| 199 |
@triton.jit
|
| 200 |
def _squared_relu_gate_kernel(
|
|
@@ -219,6 +203,7 @@ def _squared_relu_gate_kernel(
|
|
| 219 |
|
| 220 |
|
| 221 |
def squared_relu_gate(packed: T, hidden_dim: int) -> T:
|
|
|
|
| 222 |
packed_2d = packed.flatten(0, -2)
|
| 223 |
n_rows = packed_2d.shape[0]
|
| 224 |
n_cols = hidden_dim
|
|
@@ -237,33 +222,17 @@ def squared_relu_gate(packed: T, hidden_dim: int) -> T:
|
|
| 237 |
class FeedForward(nn.Module):
|
| 238 |
def __init__(self, dim: int, hidden_dim: int):
|
| 239 |
super().__init__()
|
| 240 |
-
self.
|
| 241 |
self.w2 = nn.Linear(hidden_dim, dim, bias=False)
|
| 242 |
-
self.w3 = nn.Linear(dim, hidden_dim, bias=False)
|
| 243 |
self.hidden_dim = hidden_dim
|
| 244 |
|
| 245 |
-
def _fuse_weights(self):
|
| 246 |
-
if hasattr(self, "_w13_weight"):
|
| 247 |
-
return
|
| 248 |
-
w1_weight_fused = self.w1.weight.data * math.sqrt(2.0)
|
| 249 |
-
w13_weight = torch.empty(
|
| 250 |
-
(2 * self.hidden_dim, self.w1.weight.shape[1]),
|
| 251 |
-
device=w1_weight_fused.device, dtype=w1_weight_fused.dtype,
|
| 252 |
-
)
|
| 253 |
-
w13_weight[0::2] = w1_weight_fused
|
| 254 |
-
w13_weight[1::2] = self.w3.weight.data
|
| 255 |
-
self.register_buffer("_w13_weight", w13_weight)
|
| 256 |
-
del self.w1, self.w3
|
| 257 |
-
|
| 258 |
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 259 |
x = F.rms_norm(x, (x.size(-1),))
|
| 260 |
-
w13_out =
|
| 261 |
return self.w2(squared_relu_gate(w13_out, self.hidden_dim))
|
| 262 |
|
| 263 |
|
| 264 |
-
#
|
| 265 |
-
# Sub-modules: TransformerBlock
|
| 266 |
-
# ---------------------------------------------------------------------------
|
| 267 |
|
| 268 |
class TransformerBlock(nn.Module):
|
| 269 |
def __init__(self, layer_id: int, config: FalconOCRConfig):
|
|
@@ -292,9 +261,7 @@ class TransformerBlock(nn.Module):
|
|
| 292 |
return out.reshape(B, S, D)
|
| 293 |
|
| 294 |
|
| 295 |
-
# ---------------------------------------------------------------------------
|
| 296 |
# KV Cache
|
| 297 |
-
# ---------------------------------------------------------------------------
|
| 298 |
|
| 299 |
class KVCache:
|
| 300 |
def __init__(self, max_batch_size, max_seq_length, n_heads, head_dim, num_layers):
|
|
@@ -334,9 +301,7 @@ class KVCache:
|
|
| 334 |
return key_view, value_view
|
| 335 |
|
| 336 |
|
| 337 |
-
# ---------------------------------------------------------------------------
|
| 338 |
# Sampling
|
| 339 |
-
# ---------------------------------------------------------------------------
|
| 340 |
|
| 341 |
@torch.inference_mode()
|
| 342 |
def sample_next_token(logits, rng, temperature=0.0, top_k=None):
|
|
@@ -355,9 +320,7 @@ def sample_next_token(logits, rng, temperature=0.0, top_k=None):
|
|
| 355 |
return torch.multinomial(probs, num_samples=1, generator=rng)
|
| 356 |
|
| 357 |
|
| 358 |
-
# ---------------------------------------------------------------------------
|
| 359 |
# Main Model
|
| 360 |
-
# ---------------------------------------------------------------------------
|
| 361 |
|
| 362 |
class FalconOCRForCausalLM(PreTrainedModel):
|
| 363 |
config_class = FalconOCRConfig
|
|
@@ -387,25 +350,19 @@ class FalconOCRForCausalLM(PreTrainedModel):
|
|
| 387 |
|
| 388 |
self.post_init()
|
| 389 |
|
| 390 |
-
#
|
| 391 |
|
| 392 |
-
def
|
|
|
|
| 393 |
if self._weights_fused:
|
| 394 |
return
|
| 395 |
-
|
| 396 |
device = self.tok_embeddings.weight.device
|
| 397 |
c = self.config
|
| 398 |
-
|
| 399 |
rope_dim = c.head_dim // 2
|
| 400 |
freqs_cis = precompute_freqs_cis(rope_dim, c.max_seq_len, c.rope_theta).to(device)
|
| 401 |
self.register_buffer("freqs_cis", freqs_cis, persistent=False)
|
| 402 |
-
|
| 403 |
if self.freqs_cis_golden.device != device:
|
| 404 |
self.freqs_cis_golden = self.freqs_cis_golden.to(device)
|
| 405 |
-
|
| 406 |
-
for layer in self.layers.values():
|
| 407 |
-
layer.attention._fuse_weights()
|
| 408 |
-
layer.feed_forward._fuse_weights()
|
| 409 |
self._weights_fused = True
|
| 410 |
|
| 411 |
def compile_model(self):
|
|
@@ -416,7 +373,7 @@ class FalconOCRForCausalLM(PreTrainedModel):
|
|
| 416 |
layer.compile(dynamic=True, mode="default")
|
| 417 |
self._is_compiled = True
|
| 418 |
|
| 419 |
-
#
|
| 420 |
|
| 421 |
def _get_tokenizer(self):
|
| 422 |
if not hasattr(self, "_tokenizer"):
|
|
@@ -433,24 +390,19 @@ class FalconOCRForCausalLM(PreTrainedModel):
|
|
| 433 |
)
|
| 434 |
return self._tokenizer
|
| 435 |
|
| 436 |
-
#
|
| 437 |
|
| 438 |
def get_attention_mask(self, input_batch: T, max_len: int | None = None):
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
image_prefix_mask_mod = get_image_prefix_mask_mod(
|
| 447 |
-
batch=input_batch, soi_id=c.image_cls_token_id, eoi_id=c.img_end_id,
|
| 448 |
)
|
| 449 |
-
mask_mod = or_masks(image_prefix_mask_mod, block_causal_mask_mod)
|
| 450 |
-
max_len = max_len or S
|
| 451 |
-
return create_attention_mask(mask_mod, B, None, max_len, max_len)
|
| 452 |
|
| 453 |
-
#
|
| 454 |
|
| 455 |
def _scatter_img_tokens_with_projector(self, h_BSD, pixel_patches_NLC, pixel_masks_NTHW, tokens_BS):
|
| 456 |
B, S, D = h_BSD.shape
|
|
@@ -469,7 +421,7 @@ class FalconOCRForCausalLM(PreTrainedModel):
|
|
| 469 |
assert valid_feats.numel() == img_mask_h_BSD.sum()
|
| 470 |
return torch.masked_scatter(h_BSD, img_mask_h_BSD, valid_feats)
|
| 471 |
|
| 472 |
-
#
|
| 473 |
|
| 474 |
def forward(
|
| 475 |
self,
|
|
@@ -528,7 +480,7 @@ class FalconOCRForCausalLM(PreTrainedModel):
|
|
| 528 |
logits_BSV = self.output(h_BSD)
|
| 529 |
return logits_BSV
|
| 530 |
|
| 531 |
-
#
|
| 532 |
|
| 533 |
def _load_layout_model(self, layout_model: str = "PaddlePaddle/PP-DocLayoutV3_safetensors"):
|
| 534 |
if hasattr(self, "_layout_model"):
|
|
@@ -618,7 +570,7 @@ class FalconOCRForCausalLM(PreTrainedModel):
|
|
| 618 |
|
| 619 |
return batch_results
|
| 620 |
|
| 621 |
-
#
|
| 622 |
|
| 623 |
def _generate_batch(
|
| 624 |
self,
|
|
@@ -698,7 +650,7 @@ class FalconOCRForCausalLM(PreTrainedModel):
|
|
| 698 |
|
| 699 |
return results
|
| 700 |
|
| 701 |
-
#
|
| 702 |
|
| 703 |
@torch.inference_mode()
|
| 704 |
def generate(
|
|
@@ -734,7 +686,7 @@ class FalconOCRForCausalLM(PreTrainedModel):
|
|
| 734 |
Returns:
|
| 735 |
List of extracted text strings, one per image.
|
| 736 |
"""
|
| 737 |
-
self.
|
| 738 |
if compile:
|
| 739 |
self.compile_model()
|
| 740 |
|
|
@@ -756,7 +708,7 @@ class FalconOCRForCausalLM(PreTrainedModel):
|
|
| 756 |
min_dimension=min_dimension, max_dimension=max_dimension, seed=seed,
|
| 757 |
)
|
| 758 |
|
| 759 |
-
#
|
| 760 |
|
| 761 |
@torch.inference_mode()
|
| 762 |
def generate_with_layout(
|
|
@@ -798,7 +750,7 @@ class FalconOCRForCausalLM(PreTrainedModel):
|
|
| 798 |
Per-image list of detections, each a dict with keys:
|
| 799 |
``category``, ``bbox`` [x1,y1,x2,y2], ``score``, ``text``.
|
| 800 |
"""
|
| 801 |
-
self.
|
| 802 |
if compile:
|
| 803 |
self.compile_model()
|
| 804 |
self._load_layout_model(layout_model)
|
|
|
|
|
|
|
| 1 |
from pathlib import Path
|
| 2 |
|
| 3 |
import einops as E
|
|
|
|
| 11 |
from torch.nn.attention.flex_attention import (
|
| 12 |
AuxRequest,
|
| 13 |
BlockMask,
|
|
|
|
|
|
|
| 14 |
)
|
| 15 |
from transformers import AutoTokenizer, PreTrainedModel
|
| 16 |
|
| 17 |
from .attention import (
|
| 18 |
compiled_flex_attn_decode,
|
| 19 |
compiled_flex_attn_prefill,
|
| 20 |
+
create_batch_attention_mask,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
offset_mask_mod,
|
| 22 |
)
|
| 23 |
from .configuration_falcon_ocr import FalconOCRConfig
|
|
|
|
| 113 |
return keep
|
| 114 |
|
| 115 |
|
| 116 |
+
# Attention
|
|
|
|
|
|
|
| 117 |
|
| 118 |
def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 119 |
B, S, H, D = x.shape
|
|
|
|
| 132 |
self.q_dim = config.n_heads * self.head_dim
|
| 133 |
self.kv_dim = self.n_kv_heads * self.head_dim
|
| 134 |
|
| 135 |
+
self.wqkv = nn.Linear(config.dim, self.q_dim + 2 * self.kv_dim, bias=False)
|
|
|
|
|
|
|
| 136 |
self.wo = nn.Linear(config.n_heads * self.head_dim, config.dim, bias=False)
|
| 137 |
self.sinks = nn.Parameter(torch.empty((config.n_heads,)))
|
| 138 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
def _pre_attention_qkv(self, x) -> tuple[T, T, T]:
|
| 140 |
+
qkv = self.wqkv(F.rms_norm(x, (x.size(-1),)))
|
| 141 |
xq, xk, xv = qkv.split([self.q_dim, self.kv_dim, self.kv_dim], dim=-1)
|
| 142 |
xq = E.rearrange(xq, "b s (h d) -> b s h d", d=self.head_dim)
|
| 143 |
xk = E.rearrange(xk, "b s (h d) -> b s h d", d=self.head_dim)
|
|
|
|
| 149 |
return xq, xk, xv
|
| 150 |
|
| 151 |
def _post_attention(self, output: T, lse: T) -> T:
|
| 152 |
+
# Sink-based scaling: sigmoid(lse - sinks) * output
|
| 153 |
+
# equivalent to prepending a sink token to the input
|
| 154 |
sinks_BHS = self.sinks.view(1, -1, 1)
|
| 155 |
sink_scale = torch.sigmoid(lse - sinks_BHS)
|
| 156 |
output = (output * sink_scale.unsqueeze(-1)).to(output.dtype)
|
|
|
|
| 178 |
return self._post_attention(output, aux_output.lse)
|
| 179 |
|
| 180 |
|
| 181 |
+
# FeedForward
|
|
|
|
|
|
|
| 182 |
|
| 183 |
@triton.jit
|
| 184 |
def _squared_relu_gate_kernel(
|
|
|
|
| 203 |
|
| 204 |
|
| 205 |
def squared_relu_gate(packed: T, hidden_dim: int) -> T:
|
| 206 |
+
"""Processes interleaved [gate, up, gate, up, ...] from w13; output = ReLU(gate)^2 * up."""
|
| 207 |
packed_2d = packed.flatten(0, -2)
|
| 208 |
n_rows = packed_2d.shape[0]
|
| 209 |
n_cols = hidden_dim
|
|
|
|
| 222 |
class FeedForward(nn.Module):
|
| 223 |
def __init__(self, dim: int, hidden_dim: int):
|
| 224 |
super().__init__()
|
| 225 |
+
self.w13 = nn.Linear(dim, 2 * hidden_dim, bias=False)
|
| 226 |
self.w2 = nn.Linear(hidden_dim, dim, bias=False)
|
|
|
|
| 227 |
self.hidden_dim = hidden_dim
|
| 228 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 230 |
x = F.rms_norm(x, (x.size(-1),))
|
| 231 |
+
w13_out = self.w13(x)
|
| 232 |
return self.w2(squared_relu_gate(w13_out, self.hidden_dim))
|
| 233 |
|
| 234 |
|
| 235 |
+
# TransformerBlock
|
|
|
|
|
|
|
| 236 |
|
| 237 |
class TransformerBlock(nn.Module):
|
| 238 |
def __init__(self, layer_id: int, config: FalconOCRConfig):
|
|
|
|
| 261 |
return out.reshape(B, S, D)
|
| 262 |
|
| 263 |
|
|
|
|
| 264 |
# KV Cache
|
|
|
|
| 265 |
|
| 266 |
class KVCache:
|
| 267 |
def __init__(self, max_batch_size, max_seq_length, n_heads, head_dim, num_layers):
|
|
|
|
| 301 |
return key_view, value_view
|
| 302 |
|
| 303 |
|
|
|
|
| 304 |
# Sampling
|
|
|
|
| 305 |
|
| 306 |
@torch.inference_mode()
|
| 307 |
def sample_next_token(logits, rng, temperature=0.0, top_k=None):
|
|
|
|
| 320 |
return torch.multinomial(probs, num_samples=1, generator=rng)
|
| 321 |
|
| 322 |
|
|
|
|
| 323 |
# Main Model
|
|
|
|
| 324 |
|
| 325 |
class FalconOCRForCausalLM(PreTrainedModel):
|
| 326 |
config_class = FalconOCRConfig
|
|
|
|
| 350 |
|
| 351 |
self.post_init()
|
| 352 |
|
| 353 |
+
# Weight management
|
| 354 |
|
| 355 |
+
def _ensure_device_buffers(self):
|
| 356 |
+
"""Recompute non-persistent buffers that HF meta-device loading may discard."""
|
| 357 |
if self._weights_fused:
|
| 358 |
return
|
|
|
|
| 359 |
device = self.tok_embeddings.weight.device
|
| 360 |
c = self.config
|
|
|
|
| 361 |
rope_dim = c.head_dim // 2
|
| 362 |
freqs_cis = precompute_freqs_cis(rope_dim, c.max_seq_len, c.rope_theta).to(device)
|
| 363 |
self.register_buffer("freqs_cis", freqs_cis, persistent=False)
|
|
|
|
| 364 |
if self.freqs_cis_golden.device != device:
|
| 365 |
self.freqs_cis_golden = self.freqs_cis_golden.to(device)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
self._weights_fused = True
|
| 367 |
|
| 368 |
def compile_model(self):
|
|
|
|
| 373 |
layer.compile(dynamic=True, mode="default")
|
| 374 |
self._is_compiled = True
|
| 375 |
|
| 376 |
+
# Tokenizer
|
| 377 |
|
| 378 |
def _get_tokenizer(self):
|
| 379 |
if not hasattr(self, "_tokenizer"):
|
|
|
|
| 390 |
)
|
| 391 |
return self._tokenizer
|
| 392 |
|
| 393 |
+
# Attention mask
|
| 394 |
|
| 395 |
def get_attention_mask(self, input_batch: T, max_len: int | None = None):
|
| 396 |
+
return create_batch_attention_mask(
|
| 397 |
+
input_batch,
|
| 398 |
+
pad_token_id=self._pad_token_id,
|
| 399 |
+
eos_token_id=self.config.eos_id,
|
| 400 |
+
soi_token_id=self.config.image_cls_token_id,
|
| 401 |
+
eoi_token_id=self.config.img_end_id,
|
| 402 |
+
max_len=max_len,
|
|
|
|
|
|
|
| 403 |
)
|
|
|
|
|
|
|
|
|
|
| 404 |
|
| 405 |
+
# Embedding helpers
|
| 406 |
|
| 407 |
def _scatter_img_tokens_with_projector(self, h_BSD, pixel_patches_NLC, pixel_masks_NTHW, tokens_BS):
|
| 408 |
B, S, D = h_BSD.shape
|
|
|
|
| 421 |
assert valid_feats.numel() == img_mask_h_BSD.sum()
|
| 422 |
return torch.masked_scatter(h_BSD, img_mask_h_BSD, valid_feats)
|
| 423 |
|
| 424 |
+
# Core forward
|
| 425 |
|
| 426 |
def forward(
|
| 427 |
self,
|
|
|
|
| 480 |
logits_BSV = self.output(h_BSD)
|
| 481 |
return logits_BSV
|
| 482 |
|
| 483 |
+
# Layout detection
|
| 484 |
|
| 485 |
def _load_layout_model(self, layout_model: str = "PaddlePaddle/PP-DocLayoutV3_safetensors"):
|
| 486 |
if hasattr(self, "_layout_model"):
|
|
|
|
| 570 |
|
| 571 |
return batch_results
|
| 572 |
|
| 573 |
+
# Core batch decode (shared by generate & generate_with_layout)
|
| 574 |
|
| 575 |
def _generate_batch(
|
| 576 |
self,
|
|
|
|
| 650 |
|
| 651 |
return results
|
| 652 |
|
| 653 |
+
# Main API: generate
|
| 654 |
|
| 655 |
@torch.inference_mode()
|
| 656 |
def generate(
|
|
|
|
| 686 |
Returns:
|
| 687 |
List of extracted text strings, one per image.
|
| 688 |
"""
|
| 689 |
+
self._ensure_device_buffers()
|
| 690 |
if compile:
|
| 691 |
self.compile_model()
|
| 692 |
|
|
|
|
| 708 |
min_dimension=min_dimension, max_dimension=max_dimension, seed=seed,
|
| 709 |
)
|
| 710 |
|
| 711 |
+
# Main API: generate_with_layout
|
| 712 |
|
| 713 |
@torch.inference_mode()
|
| 714 |
def generate_with_layout(
|
|
|
|
| 750 |
Per-image list of detections, each a dict with keys:
|
| 751 |
``category``, ``bbox`` [x1,y1,x2,y2], ``score``, ``text``.
|
| 752 |
"""
|
| 753 |
+
self._ensure_device_buffers()
|
| 754 |
if compile:
|
| 755 |
self.compile_model()
|
| 756 |
self._load_layout_model(layout_model)
|