Download code/common/loop_guard.py from aziz9788/OvisOCR3-Arabic-workdir: direct link, hf CLI and curl.
- Browser
- Download file 4.64 kB
-
https://huggingface.co/datasets/aziz9788/OvisOCR3-Arabic-workdir/resolve/main/code/common/loop_guard.py
- Command line
-
hf download hf://datasets/aziz9788/OvisOCR3-Arabic-workdir/code/common/loop_guard.py
-
curl -L -o loop_guard.py https://huggingface.co/datasets/aziz9788/OvisOCR3-Arabic-workdir/resolve/main/code/common/loop_guard.py
4.64 kB
| """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 | |