OPUS-5.5-DATABASE / code /opusdb /decontam.py
KeremTT's picture
Update code
c02657c verified
Raw History Blame Contribute Delete
2.62 kB
"""Benchmark decontamination by word n-gram overlap (GPT-3 / Llama style, n=13).
N-grams are represented by a deterministic 64-bit rolling hash over CRC32 word ids,
computed with numpy, so the check is fast enough for billions of pretraining words.
Benchmark items with 10-12 words are additionally matched as whole phrases, but only
for chat/preference prompts (on web text such short phrases cause false positives).
"""
import zlib
import numpy as np
from .text import normalize, words
_P = np.uint64(1_000_003)
def word_ids(toks):
return np.fromiter((zlib.crc32(t.encode()) for t in toks), dtype=np.uint64, count=len(toks))
def ngram_hashes(ids, n):
L = len(ids) - n + 1
if L <= 0:
return np.empty(0, dtype=np.uint64)
h = np.zeros(L, dtype=np.uint64)
with np.errstate(over="ignore"):
for j in range(n):
h = h * _P + ids[j:j + L]
return h
def _member(queries, sorted_arr):
"""True if any query hash is present in sorted_arr (binary search, no re-sorting)."""
if not len(sorted_arr) or not len(queries):
return False
pos = np.searchsorted(sorted_arr, queries)
pos[pos == len(sorted_arr)] = 0
return bool((sorted_arr[pos] == queries).any())
class Decontaminator:
def __init__(self, n=13, short_lengths=(10, 11, 12)):
self.n = n
self.short_lengths = short_lengths
self._long, self._short = [], {k: [] for k in short_lengths}
self.long = np.empty(0, dtype=np.uint64)
self.short = {}
def add(self, text: str):
toks = words(normalize(text))
ids = word_ids(toks)
if len(toks) >= self.n:
self._long.append(ngram_hashes(ids, self.n))
elif len(toks) in self._short:
self._short[len(toks)].append(ngram_hashes(ids, len(toks)))
def finalize(self):
self.long = np.unique(np.concatenate(self._long)) if self._long else np.empty(0, dtype=np.uint64)
self.short = {k: np.unique(np.concatenate(v)) for k, v in self._short.items() if v}
self._long, self._short = [], {}
return self
def contaminated(self, text: str, check_short=True) -> bool:
toks = words(normalize(text))
ids = word_ids(toks)
if len(ids) >= self.n and _member(ngram_hashes(ids, self.n), self.long):
return True
if check_short:
for k, arr in self.short.items():
if len(ids) >= k and _member(ngram_hashes(ids, k), arr):
return True
return False
def __len__(self):
return len(self.long) + sum(map(len, self.short.values()))