File size: 4,640 Bytes
cf8c8d4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | """Loop guard: a decoding-time safety net against runaway repetition (the model writing the same token or chunk
until the token limit).
Two rules, applied to the generated tokens only:
1. Mark cap: after `max_marks` consecutive tokens that are pure combining marks (Arabic harakat, shadda,
sukun, superscript alef), another such token is blocked. More than two marks on one letter is not valid
Arabic, so this cannot remove a correct reading; it stops loops like a fatha repeated thousands of times.
2. Windowed n-gram blocker (as in DeepSeek-OCR's recommended decoding): a token that would complete an n-gram
already written within the last `window` tokens is blocked. Table and markup tokens (anything containing
< > | or only dashes / whitespace) are exempt, so repeated empty table cells and rules stay possible.
from common.loop_guard import LoopGuard
guard = LoopGuard(tokenizer, prompt_len=inputs["input_ids"].shape[1])
model.generate(**inputs, logits_processor=LogitsProcessorList([guard]))
guard.hits # how often each rule stepped in
Apply the same guard to every model being compared (base and fine-tuned), and report results with and
without it.
"""
import re
import torch
from transformers import LogitsProcessor
MARK_ONLY = re.compile(r"^[ً-ْٰٖ-ٟ]+$")
MARKUP = re.compile(r"[<>|]|^[\s\-:=]+$")
_CACHE = {}
def trim_repeated_tail(text, min_len=8000, max_period=400, min_repeats=5, min_chars=100):
"""Cut a repeated tail from a long output, keeping one copy of the repeated unit.
The same post-processing the OvisOCR3 authors ship for Markdown output (their README's
`_clean_truncated_repeats`: outputs of at least 8,000 characters, a unit repeated at least 5 times, at least
100 characters); the unit length here goes up to 400 characters so a cycle of several table rows is caught.
A tail is periodic with period p when text[i] == text[i - p] for every position i in it; the last, possibly
unfinished copy is handled naturally. Returns (text, characters removed)."""
n = len(text)
if n < min_len:
return text, 0
best = 0
for p in range(1, min(max_period, n // 2) + 1):
run, i = 0, n - 1
while i - p >= 0 and text[i] == text[i - p]:
run += 1
i -= 1
if run >= max(min_chars, (min_repeats - 1) * p) and run > best:
best = run
return (text[:n - best], best) if best else (text, 0)
def token_classes(tokenizer):
"""(ids of pure combining-mark tokens, ids exempt from the n-gram rule), computed once per tokenizer."""
key = (tokenizer.name_or_path, len(tokenizer))
if key not in _CACHE:
marks, exempt = [], []
for i in range(len(tokenizer)):
s = tokenizer.decode([i])
if s and MARK_ONLY.match(s):
marks.append(i)
elif s and MARKUP.search(s):
exempt.append(i)
_CACHE[key] = (marks, set(exempt))
return _CACHE[key]
class LoopGuard(LogitsProcessor):
def __init__(self, tokenizer, prompt_len, ngram=20, window=120, max_marks=2):
self.prompt_len, self.n, self.window, self.max_marks = prompt_len, ngram, window, max_marks
marks, self.exempt = token_classes(tokenizer)
self.mark_ids = torch.tensor(marks, dtype=torch.long)
self.mark_set = set(marks)
self.hits = {"mark_cap": 0, "ngram": 0}
def __call__(self, input_ids, scores):
gen = input_ids[:, self.prompt_len:]
if gen.shape[1] == 0:
return scores
for row in range(gen.shape[0]):
seq = gen[row].tolist()
# rule 1: cap consecutive pure-mark tokens
run = 0
for t in reversed(seq):
if t in self.mark_set:
run += 1
else:
break
if run >= self.max_marks and len(self.mark_ids):
scores[row, self.mark_ids.to(scores.device)] = -float("inf")
self.hits["mark_cap"] += 1
# rule 2: windowed n-gram blocker
if len(seq) >= self.n:
prefix = seq[-(self.n - 1):]
win = seq[-self.window:]
banned = set()
for i in range(len(win) - self.n + 1):
if win[i:i + self.n - 1] == prefix:
nxt = win[i + self.n - 1]
if nxt not in self.exempt:
banned.add(nxt)
if banned:
scores[row, list(banned)] = -float("inf")
self.hits["ngram"] += 1
return scores
|