Deduplication at scale: hashing, MinHash and LSH
Study exact, substring, near-exact, and semantic deduplication, derive MinHash and banded LSH, group verified pairs, and examine the measured effects of repeated data.
After this lesson you can
- Implement document and line deduplication using hashes and Bloom filters, and calculate false-positive rates.
- Prove the MinHash collision identity and calculate estimator variance with k hash functions.
- Derive the banded LSH S-curve and choose bands and rows for an error budget.
- Implement MinHash-LSH deduplication with connected components for large document collections.
- Explain evidence on repeated data, memorization, and when repetition can be acceptable.
Before you start
When two documents count as one
Two pages may share a template but contain different articles, or be copies of one article with a slightly changed title. Comparing only identical files misses many copies. Grouping under an overly permissive similarity can remove new information. The first figure shows how estimated similarity introduces uncertainty even before deciding which documents to retain.
Exact equality, lines, and limited memory
Exact deduplication compares a fixed document representation: original bytes or text transformed under declared normalization. After transformation, compute a stable fingerprint such as SHA-256 and group equal hashes. To guarantee equality, verify bytes within each group: finite hashes can collide. Normalizing whitespace, case, or Unicode can make different strings equivalent; retain the rule, provenance, and chosen representative. Python’s built-in hash() is not a persistent fingerprint across processes.
The unit matters. Document deduplication removes complete copies, while line deduplication can remove a shared template without deleting an entire article. A license, definition, or repeated quotation may be legitimate and needed to interpret what remains. If PII is redacted before comparison, two distinct originals can become the same processed text: check their splits too. Deduplicate training against validation and test, not just within each set. The corpus documentation lesson retains versions, criteria, and decisions.
A Bloom filter stores bits and checks positions per element. A zero bit proves the element was not inserted; all ones mean “possibly present”. With approximately uniform independent positions, a common estimate after inserting elements is
This is an occupancy approximation, not a per-element guarantee or exact identity for every hash family. A Bloom positive does not authorize deleting a document: confirm equality against a fingerprint and content store. The filter does not return the matching document or remove false negatives caused by incorrect normalization.
With uniformly chosen positions, a particular bit remains zero with probability . The approximation raises the expected occupied-bit fraction to ; bit states are not exactly independent in a finite filter. Under that model and treating as continuous, the minimum is near , where about half the bits are occupied. An implementation chooses an integer, a hash family, and expected capacity. Inserting many more elements than increases occupancy and false positives.
Substrings and boundaries
Suffix-array deduplication finds repeated contiguous fragments even when the rest of a document changes. Sort token-stream suffixes and calculate common-prefix lengths between neighbors; repeated regions appear in contiguous intervals in that order. Document separators must prevent matches crossing boundaries. When removing a span, record retained occurrences and treatment of overlaps and splits.
Lee and colleagues used exact matches of at least 50 tokens in ExactSubstr. In C4 they identified 7.18% of training tokens as part of that kind of duplicate. The result depends on tokenizer, corpus, and removal policy; it does not mean every repeated 50-token span is harmful. A complete suffix array and its construction require memory and storage proportional to the stream. Test a subset first and measure resource use locally.
Shingles, sets, and Jaccard
Shingle Jaccard similarity compares sets of contiguous sequences of units. If and are the sets, with nonempty union,
Sets discard multiplicity: repeating the same shingle many times does not change . Choosing words or tokens, , normalization, and boundaries changes the definition of duplicate. Two texts shorter than may produce empty sets. The protocol must decide how to handle them instead of dividing by zero or automatically declaring them duplicates.
Why MinHash works
Let and be finite nonempty sets and let . MinHash applies a uniform permutation to the universe and keeps each set’s minimum. Minima match exactly when the first element of in the order of belongs to . Every element of is equally likely to be first, so
With independent uniform permutations, match indicators are Bernoulli with parameter . Their mean is unbiased and has variance . A practical universal hash family is not necessarily a family of uniform minwise permutations. These formulas are an ideal reference and the implementation must measure error. Collisions when mapping shingles to integers also change the represented sets.
For example, if signatures match in 40 of 100 components, the point estimate is 0.4. Under the ideal model, an approximate standard error substitutes with that proportion in . Near zero or one, an appropriate binomial interval is preferable to treating that deviation as a symmetric guarantee. A pair estimated just above threshold may really lie on either side; checking exact candidates avoids deciding solely from signature noise.
From signatures to candidates
In banded LSH, split components into bands of rows. A pair is proposed if a whole band matches. Under ideal independence, each row matches with probability ; a band matches with probability , and none of the bands matches with probability . Thus,
Approximate rule locates a transition region, not the exact probability-0.5 point . If a true duplicate is defined by , area under for represents a false-candidate rate only after weighting by a similarity distribution. Similarly, mass of pairs with not proposed by LSH depends on that distribution. Verifying exact Jaccard for each candidate removes final-decision false positives under the same representation, but cannot recover pairs LSH never proposed.
With fixed budget , increasing reduces band count and requires more simultaneous matches to propose a pair. Increasing and reducing generally makes search more sensitive to less-similar pairs. There is no single optimum without fixed costs: a false candidate consumes verification, while a false negative can leave a copy in training. Estimate both on a subset where all exact pairs can be calculated, and retain the similarity distribution used to choose parameters.
Candidates, edges, and components
After checking pairs, create an edge when similarity reaches threshold and use union-find to find connected components. The relation “” is not transitive: A can resemble B and B resemble C while A and C are below threshold. A component closes such chains transitively, so grouping it does not prove all pairs are duplicates. One representative per component can be retained if appropriate; record removals, inspect large components, and consider stricter rules when losing a variant is costly.
Semantic deduplication replaces lexical matches with embedding proximity, often after clustering vectors to limit comparisons. It can find paraphrases MinHash does not join, but may merge related documents containing different facts. It depends on the encoder and its language and domain coverage. SemDeDup studies this strategy on several datasets and models: an image-and-CLIP measurement does not automatically become a language-corpus result.
Scale changes engineering. A signature of 100 64-bit integers takes 800 bytes per document before indices and metadata; one million take 800 million bytes, excluding corpus and buckets. A very large bucket can generate a quadratic number of pairs. Write signatures and indices incrementally, bound resources explicitly, and record any bucket you cannot process: silent truncation destroys completeness. The next cell calculates this budget, while the local comparison measures a sample and promises no speed for one million documents.
Repetition, utility, and risk
Effects of repeated data depend on what is repeated, how often, the budget, and the mixture. Hernandez and colleagues observed in one experiment that an 800-million-parameter model, with 10% of tokens from a fraction repeated around 100 times, could reach test loss close to a 340-million-parameter model. This is not a law that all repetition always worsens results: regimes, epochs, and mixtures can differ.
Lee and colleagues also study the relationship between duplicates and memorized text. Reducing duplicates can reduce exposure under their protocol, but does not prove the model stopped memorizing or replace a privacy evaluation. Retain baselines, versions, and per-domain metrics: removing too many copies can shift rare languages or sources, and deduplicating a benchmark against training first requires agreement on what similarity constitutes contamination.
Lab: signatures and candidates from scratch
The following synthetic sets are defined in the cell so you can check calculations; they are not web measurements. The affine family modulo a prime is reproducible but does not guarantee exact minwise uniformity. Each text shingle can be converted into a stable integer with SHA-256; reduction modulo the prime can create collisions. The controlled test uses integers directly to separate that effect from estimation.
Search proposes pairs by band, verifies exact Jaccard, and connects only verified pairs. Printed precision and recall apply exclusively to the six sets and seed shown. The second test compares empirical frequencies with the ideal curve, without treating agreement in one sample as proof of independence.
import hashlib
import math
import re
import numpy as np
P = 2**31 - 1
def shingles(text, q=2):
if q < 1:
raise ValueError('q debe ser positivo')
words = re.findall(r'\w+', text.lower(), flags=re.UNICODE)
return {' '.join(words[i:i+q]) for i in range(len(words)-q+1)}
def stable_id(value):
return int.from_bytes(hashlib.sha256(value.encode('utf-8')).digest()[:4], 'big') % P
def coefficients(k, seed):
if k <= 0:
raise ValueError('k debe ser positivo')
rng = np.random.default_rng(seed)
return (rng.integers(1, P, size=k, dtype=np.uint64),
rng.integers(0, P, size=k, dtype=np.uint64))
def minhash_ids(ids, a, b):
values = np.asarray(sorted(ids), dtype=np.uint64)
if not len(values):
raise ValueError('MinHash requiere conjunto no vacío')
# Producto menor que 2**62: no hay desbordamiento uint64.
return ((a[:, None]*values[None, :] + b[:, None]) % np.uint64(P)).min(axis=1)
def jaccard(a, b):
if not a or not b:
raise ValueError('Usamos conjuntos no vacíos')
return len(a & b)/len(a | b)
def candidates(signatures, bands, rows):
if signatures.shape[1] != bands*rows:
raise ValueError('La firma debe tener bandas × filas componentes')
buckets, result = {}, set()
for document, signature in enumerate(signatures):
for band in range(bands):
key = (band, tuple(int(x) for x in signature[band*rows:(band+1)*rows]))
for other in buckets.get(key, []):
result.add((other, document))
buckets.setdefault(key, []).append(document)
return result
def components(n, edges):
parent = list(range(n))
def root(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for x, y in edges:
rx, ry = root(x), root(y)
if rx != ry: parent[ry] = rx
groups = {}
for i in range(n): groups.setdefault(root(i), []).append(i)
return list(groups.values())
# Documentos sintéticos definidos aquí: no son resultados de un corpus web.
sets = [set(range(20)), set(range(18)) | {20, 21}, set(range(1,21)),
set(range(100,120)), set(range(100,118)) | {120,121}, set(range(200,220))]
b, r = 20, 5
a, offset = coefficients(b*r, 2010)
sig = np.stack([minhash_ids(s, a, offset) for s in sets])
proposed = candidates(sig, b, r)
truth = {(i,j) for i in range(len(sets)) for j in range(i+1,len(sets)) if jaccard(sets[i],sets[j]) >= .8}
verified = {pair for pair in proposed if pair in truth}
print('Pares sobre umbral, candidatos, verificados:', len(truth), len(proposed), len(verified))
print('Precisión de candidatos:', len(verified)/len(proposed) if proposed else None,
'exhaustividad:', len(verified)/len(truth) if truth else None)
print('Componentes verificadas:', components(len(sets), verified))
# Ensayo controlado de dos Jaccard exactos; las familias afines no son minwise ideales.
def controlled(shared, unique):
return (set(range(shared+unique)),
set(range(shared)) | set(range(shared+unique,shared+2*unique)))
trials = 120
for shared, unique in [(20,10),(40,5)]:
left,right = controlled(shared,unique)
aa,bb = coefficients(trials*b*r, 100+shared)
equal = (minhash_ids(left,aa,bb) == minhash_ids(right,aa,bb)).reshape(trials,b,r)
observed = np.any(np.all(equal,axis=2),axis=1).mean()
s = jaccard(left,right)
print('J=',s,'candidatos observados=',float(observed),
'modelo ideal=',1-(1-s**r)**b)
print('Bloom aproximado:', (1-math.exp(-7*10**8/10**9))**7)
print('LSH s=0,5 / 0,8 y umbral aproximado:',
1-(1-.5**5)**20, 1-(1-.8**5)**20, 20**(-1/5))
print('Bytes de 100 enteros uint64 por documento:', 100*8)
print('Bytes para un millón de firmas:', 1_000_000*100*8)
print('Bytes de un millón de firmas de 64 uint32:', 1_000_000*64*4)
print('Entradas de índice para 16 bandas por documento:', 1_000_000*16)Lab: real corpus and storage
This lab reads corpus-redacted.jsonl and records.json produced by m20-l09. Set ORYON_CORPUS_DIR to that folder. Text contains only partial redaction from the previous lesson and remains private. The public report stores opaque IDs, signatures, lengths, and similarities without fragments; SQLite and token-sequence output stay local.
Install numpy and psutil. With ORYON_COMPARE_DATATROVE=1, also install datatrove and spacy. The comparator runs DataTrove MinhashDedupSignature.get_shingles and get_signature with 64 bits and SHA-1, then groups signatures into bands and checks candidates using the same custom exact Jaccard. It does not run DataTrove’s full pipeline and normalization differs; its figures do not reproduce that pipeline. Per-phase time and sampled peak RSS describe the same process, which retains earlier objects. Phases do not contain exactly the same work, and their time or memory does not fairly compare isolated systems.
The algorithm streams JSONL without loading the full corpus; SQLite indexes hashes, bands, and pairs, and offsets recover only candidate documents. Signatures use 64 pseudorandom affine functions, shingle prehashing to a 32-bit field, and a fixed seed. Prehash collisions or the function family mean these signatures are not ideal permutations; candidate pairs are checked against complete word sets. The union of verified edges is transitive even when similarity is not. Documents without shingles have no signature or defined Jaccard; in both branches they are joined only if direct comparison confirms identical text. Document and line hashes are preselections and equality is confirmed with text. In lines-deduplicated-private.jsonl the first exact line is retained, including separators, and later copies removed; blank lines remain. This output remains private.
Assignments and representative documents are written to assignments-private.jsonl and retained-private.jsonl. For each detected component, a test document is preferred, then validation, then training; within each priority the first is kept. The representative retains its original split, so evaluation text is not added to training. A candidate LSH misses is not joined: this policy cannot guarantee removal of all cross-split contamination.
The educational line output also retains field split, but is calculated on the input corpus, not document representatives. It follows input order and does not apply split priority. Do not use it to build a clean evaluation; first inspect cross-corpus contamination separately.
ORYON_DEDUP_MAX_DOCS sets the input maximum, defaulting to a one-million ceiling; ORYON_DEDUP_WORKERS allows up to 24 bounded threads. At one million documents and 64 four-byte integers, signatures use at least 256 MB before tables, indices, buckets, text, and SQLite overhead; sixteen bands imply up to 16 million index entries. Actual space and time depend on the corpus. No small test guarantees one million will fit or finish on a given machine. Oversized buckets and pairing attempts exceeding ORYON_BUCKET_LIMIT or ORYON_PAIR_LIMIT stop the process without silently discarding candidates. Reduce data, check disk, and distribute indices if expanding the work.
The suffix array processes only the first 4,000 normalized tokens from up to eight documents, compares neighboring suffixes, and removes found spans of at least 50 words within and across documents while preserving an earlier complete anchor. Neighbor comparison and that greedy policy do not guarantee finding or removing every possible match. Local file suffix-cleaned-private.jsonl contains only indexed lowercased word sequences without punctuation: it is a token-deduplication control, not reconstructed text or an implementation of Lee and colleagues’ distributed tool. Do not publish it. The report states removed token count and retains hashes.
For a test, set ORYON_QUICK=1 and a new ORYON_DEDUP_DIR folder; the lab refuses to overwrite an old database. On up to 300 documents the report includes every pair with defined Jaccard, candidates and non-candidates, to measure recall and false negatives in that sample. Exhaustive comparisons and the suffix array are not the path to million-scale processing. Small-test figures do not represent the entire web or demonstrate a change in model quality.
"""Deduplicación reproducible en disco para el JSONL redactado de m20-l09."""
import os, json, re, math, hashlib, sqlite3, struct, time, threading
from pathlib import Path
from functools import lru_cache
from concurrent.futures import ThreadPoolExecutor
from collections import deque
from itertools import islice
import numpy as np
QUICK = os.getenv('ORYON_QUICK') == '1'
SOURCE = Path(os.getenv('ORYON_CORPUS_DIR', './oryon-corpus'))
OUT = Path(os.getenv('ORYON_DEDUP_DIR', './oryon-dedup'))
MAX_DOCS = int(os.getenv('ORYON_DEDUP_MAX_DOCS', '1000000'))
WORKERS = int(os.getenv('ORYON_DEDUP_WORKERS', '2' if QUICK else '24'))
BUCKET_LIMIT = int(os.getenv('ORYON_BUCKET_LIMIT', '2000'))
PAIR_LIMIT = int(os.getenv('ORYON_PAIR_LIMIT', '10000000'))
THRESHOLD = float(os.getenv('ORYON_JACCARD_THRESHOLD', '0.8'))
SHINGLE, BANDS, ROWS, SEED = 5, 16, 4, 2010
P = 4294967291
K = BANDS*ROWS
class MemoryMeter:
"""RSS muestreada del proceso; no incluye memoria de otros procesos."""
def __init__(self):
try:
import psutil
self.process = psutil.Process()
except ImportError:
self.process = None
self.start = time.perf_counter(); self.initial = self.rss(); self.peak = self.initial
self.stop = threading.Event()
self.thread = threading.Thread(target=self._sample,daemon=True); self.thread.start()
def rss(self): return None if self.process is None else self.process.memory_info().rss
def _sample(self):
while not self.stop.wait(.05):
sample = self.rss()
if sample is not None: self.peak = max(self.peak,sample)
def finish(self):
self.stop.set(); self.thread.join()
current = self.rss()
if current is not None: self.peak = max(self.peak,current)
return {'seconds':time.perf_counter()-self.start,'rss_initial_bytes':self.initial,'rss_peak_sampled_bytes':self.peak,
'sampling_seconds':.05,'note':'RSS del mismo proceso; las fases conservan objetos previos y no son mediciones aisladas'}
def words(text): return re.findall(r'\w+', text.casefold(), flags=re.UNICODE)
def shingles(text):
tokens = words(text)
return {tuple(tokens[i:i+SHINGLE]) for i in range(len(tokens)-SHINGLE+1)}
def exact_jaccard(a,b):
if not a or not b: return None
return len(a & b)/len(a | b)
def digest(data): return hashlib.sha256(data).hexdigest()
def file_digest(path):
h = hashlib.sha256()
with path.open('rb') as stream:
for block in iter(lambda:stream.read(1024*1024),b''): h.update(block)
return h.hexdigest()
def make_coefficients():
g = np.random.default_rng(SEED)
return g.integers(1,P,size=K,dtype=np.uint64), g.integers(0,P,size=K,dtype=np.uint64)
COEFFICIENTS = make_coefficients()
def signature(items):
if not items: return None
# El prehash tiene 32 bits efectivos; el Jaccard final usa tuplas de palabras sin prehash.
values = np.fromiter((int.from_bytes(hashlib.blake2b('\0'.join(x).encode('utf-8'),digest_size=8).digest(),'big') % P for x in items),dtype=np.uint64)
a,b = COEFFICIENTS; minima = np.full(K,P,dtype=np.uint64)
for start in range(0,len(values),1024):
h = (values[start:start+1024,None]*a[None,:]+b[None,:]) % np.uint64(P)
minima = np.minimum(minima,h.min(axis=0))
return minima.astype('<u4')
class DSU:
def __init__(self,n): self.parent = list(range(n)); self.size = [1]*n
def find(self,x):
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]; x = self.parent[x]
return x
def union(self,a,b):
a,b = self.find(a),self.find(b)
if a != b:
if self.size[a] < self.size[b]: a,b = b,a
self.parent[b] = a; self.size[a] += self.size[b]
def union_exact_texts(components,texts):
representatives = {}
for i,text in enumerate(texts):
if text in representatives: components.union(representatives[text],i)
else: representatives[text] = i
def suffix_repetitions(texts, max_tokens=4000, minimum=50):
"""Array por duplicación de prefijos y LCP; no cruza fronteras de documento."""
vocabulary, sequence, owner, offset = {}, [], [], []
tokenized = [[] for _ in texts]; indexed = 0
for doc,text in enumerate(texts):
tokenized[doc] = [m.group() for m in islice(re.finditer(r'\w+',text.casefold(),flags=re.UNICODE),max_tokens-indexed)]
for pos,token in enumerate(tokenized[doc]):
value = vocabulary.setdefault(token,len(vocabulary)+1)
sequence.append(value); owner.append(doc); offset.append(pos); indexed += 1
sequence.append(-doc-1); owner.append(-1); offset.append(-1)
if indexed >= max_tokens: break
n = len(sequence)
if n < 2:
return {'tokens_indexed':0,'minimum':minimum,'matches':[],
'output_scope':'solo prefijos indexados normalizados, no documentos completos ni corpus final',
'removed_tokens_per_document':[0]*len(texts),
'cleaned_tokens_sha256':[digest(b'') for _ in texts],
'cleaned_token_sequences':[[] for _ in texts]}
ordered = sorted(range(n),key=lambda i:sequence[i]); rank = [0]*n
for j in range(1,n): rank[ordered[j]] = rank[ordered[j-1]]+(sequence[ordered[j]] != sequence[ordered[j-1]])
step = 1
while step < n:
ordered.sort(key=lambda i:(rank[i],rank[i+step] if i+step<n else -1))
new = [0]*n
for j in range(1,n):
x,y = ordered[j-1],ordered[j]
new[y] = new[x]+((rank[x],rank[x+step] if x+step<n else -1) != (rank[y],rank[y+step] if y+step<n else -1))
rank = new
if rank[ordered[-1]] == n-1: break
step *= 2
inverse = [0]*n
for i,s in enumerate(ordered): inverse[s] = i
lcp = [0]*n; h = 0
for i in range(n):
j = inverse[i]
if j == 0:
h = 0
continue
other = ordered[j-1]
while i+h<n and other+h<n and sequence[i+h]>0 and sequence[i+h]==sequence[other+h]: h += 1
lcp[j] = h; h = max(0,h-1)
matches = []
for j in range(1,n):
a,b = ordered[j-1],ordered[j]
if owner[a]>=0 and owner[b]>=0 and lcp[j]>=minimum:
matches.append({'doc_a':owner[a],'token_a':offset[a],'doc_b':owner[b],'token_b':offset[b],'length':lcp[j]})
# Agrupa sufijos vecinos y busca un ancla previa que permanezca completa.
node_ids = {}
for match in matches:
for point in ((match['doc_a'],match['token_a']),(match['doc_b'],match['token_b'])):
if point not in node_ids: node_ids[point] = len(node_ids)
nodes = DSU(len(node_ids))
for match in matches:
nodes.union(node_ids[(match['doc_a'],match['token_a'])],node_ids[(match['doc_b'],match['token_b'])])
node_groups = {}
for point,number in node_ids.items(): node_groups.setdefault(nodes.find(number),[]).append(point)
for points in node_groups.values(): points.sort()
removed = [[False]*len(row) for row in tokenized]
ordered_matches = []
for match in matches:
a,b = match['doc_a'],match['doc_b']; pa,pb = match['token_a'],match['token_b']
if (a,pa) > (b,pb): a,b,pa,pb = b,a,pb,pa
ordered_matches.append((b,pb,-match['length']))
for later,target_pos,neg_length in sorted(ordered_matches):
length = -neg_length
target = (later,target_pos)
for earlier,source_pos in node_groups[nodes.find(node_ids[target])]:
if (earlier,source_pos) >= target: break
if earlier == later and source_pos+length > target_pos: continue
if tokenized[earlier][source_pos:source_pos+length] != tokenized[later][target_pos:target_pos+length]: continue
if any(removed[earlier][source_pos:source_pos+length]): continue
removed[later][target_pos:target_pos+length] = [True]*length
break
cleaned = [[word for word,drop in zip(row,mask) if not drop] for row,mask in zip(tokenized,removed)]
return {'tokens_indexed':sum(x>=0 for x in owner),'minimum':minimum,'matches':matches,
'output_scope':'solo prefijos indexados normalizados, no documentos completos ni corpus final',
'removed_tokens_per_document':[sum(mask) for mask in removed],
'cleaned_tokens_sha256':[digest('\0'.join(row).encode('utf-8')) for row in cleaned],
'cleaned_token_sequences':cleaned}
def datatrove_signatures(texts):
from datatrove.pipeline.dedup.minhash import MinhashConfig, MinhashDedupSignature
from datatrove.utils.hashing import HashConfig
config = MinhashConfig(n_grams=SHINGLE,num_buckets=BANDS,hashes_per_bucket=ROWS,seed=SEED,hash_config=HashConfig(precision=64,hash_fc='sha1'))
tool = MinhashDedupSignature(str(OUT/'datatrove-unused-output'),config=config)
signatures = []
for text in texts:
values = tool.get_shingles(text)
signatures.append(tool.get_signature(values) if values.size else None)
return signatures
def prepare(item):
number,offset,length,text,split = item
sig = signature(shingles(text))
return number,offset,length,digest(text.encode('utf-8')),len(words(text)),sig,split
def bounded_map(executor, function, iterable, limit):
pending = deque()
for item in iterable:
pending.append(executor.submit(function,item))
if len(pending) >= limit: yield pending.popleft().result()
while pending: yield pending.popleft().result()
def main():
if not (1 <= WORKERS <= 24 and 0 <= THRESHOLD <= 1 and MAX_DOCS > 0): raise ValueError('Configuración fuera de rango')
OUT.mkdir(parents=True,exist_ok=True); database = OUT/'dedup.sqlite'
if database.exists(): raise FileExistsError('Usa una carpeta de salida nueva para no mezclar ensayos')
source_path = SOURCE/'corpus-redacted.jsonl'; metadata_path = SOURCE/'records.json'
connection = sqlite3.connect(database); connection.executescript('''
PRAGMA journal_mode=WAL;
CREATE TABLE docs (n INTEGER PRIMARY KEY, source_id TEXT, offset INTEGER, length INTEGER, digest TEXT, words INTEGER, sig BLOB, split TEXT);
CREATE INDEX document_digest ON docs(digest);
CREATE TABLE bands (band INTEGER, key BLOB, n INTEGER);
CREATE TABLE candidates (a INTEGER, b INTEGER, PRIMARY KEY(a,b)) WITHOUT ROWID;
CREATE TABLE line_hashes (digest TEXT, doc_n INTEGER, line_n INTEGER, PRIMARY KEY(digest,doc_n,line_n)) WITHOUT ROWID;
''')
ids = []; meter = MemoryMeter()
def inputs():
with source_path.open('rb') as stream:
for number in range(MAX_DOCS):
offset = stream.tell(); line = stream.readline()
if not line: break
row = json.loads(line); ids.append(row['id'])
if row['split'] not in ('train','validation','test'): raise ValueError('Partición no reconocida')
yield number,offset,len(line),row['text'],row['split']
with ThreadPoolExecutor(max_workers=WORKERS) as pool:
for number,offset,length,exact_hash,nwords,sig,split in bounded_map(pool,prepare,inputs(),max(1,2*WORKERS)):
connection.execute('INSERT INTO docs VALUES (?,?,?,?,?,?,?,?)',(number,ids[number],offset,length,exact_hash,nwords,None if sig is None else sig.tobytes(),split))
if sig is not None:
connection.executemany('INSERT INTO bands VALUES (?,?,?)',[(band,bytes(sig[band*ROWS:(band+1)*ROWS]),number) for band in range(BANDS)])
if number % 1000 == 0: connection.commit()
connection.commit(); n = len(ids)
if not n: raise ValueError('Corpus vacío')
connection.execute('CREATE INDEX band_lookup ON bands(band,key,n)'); connection.commit()
large = connection.execute('SELECT COUNT(*) FROM (SELECT band,key FROM bands GROUP BY band,key HAVING COUNT(*)>?)',(BUCKET_LIMIT,)).fetchone()[0]
if large: raise RuntimeError(f'{large} cubetas exceden el límite: no se descarta ninguna silenciosamente')
count = 0
for band,key in connection.execute('SELECT band,key FROM bands GROUP BY band,key HAVING COUNT(*)>1'):
members = [x[0] for x in connection.execute('SELECT n FROM bands WHERE band=? AND key=? ORDER BY n',(band,key))]
for i,a in enumerate(members):
for b in members[i+1:]:
connection.execute('INSERT OR IGNORE INTO candidates VALUES (?,?)',(a,b)); count += 1
if count > PAIR_LIMIT: raise RuntimeError('Excedido límite de pares de cubeta; ajusta presupuesto y vuelve a empezar')
connection.commit()
@lru_cache(maxsize=128)
def get_shingles(number):
off,length = connection.execute('SELECT offset,length FROM docs WHERE n=?',(number,)).fetchone()
with source_path.open('rb') as f: f.seek(off); row = json.loads(f.read(length))
return shingles(row['text'])
components = DSU(n); verified_count = 0
# SHA-256 selecciona candidatos exactos; el texto procesado confirma igualdad.
@lru_cache(maxsize=128)
def text_at(number):
off,length = connection.execute('SELECT offset,length FROM docs WHERE n=?',(number,)).fetchone()
with source_path.open('rb') as f: f.seek(off); return json.loads(f.read(length))['text']
exact_duplicates = 0
previous_digest, representatives = None, []
for d,item in connection.execute('SELECT digest,n FROM docs ORDER BY digest,n'):
if d != previous_digest:
previous_digest,representatives = d,[item]
continue
match = next((rep for rep in representatives if text_at(rep)==text_at(item)),None)
if match is None: representatives.append(item)
else: components.union(match,item); exact_duplicates += 1
for a,b in connection.execute('SELECT a,b FROM candidates ORDER BY a,b'):
score = exact_jaccard(get_shingles(a),get_shingles(b))
if score is not None and score >= THRESHOLD:
components.union(a,b); verified_count += 1
connection.execute('CREATE TABLE assignments (n INTEGER PRIMARY KEY, root INTEGER)')
connection.executemany('INSERT INTO assignments VALUES (?,?)',((i,components.find(i)) for i in range(n)))
connection.execute('CREATE INDEX assignment_roots ON assignments(root,n)')
connection.execute('''CREATE TABLE representatives AS SELECT root,n AS representative FROM (
SELECT a.root,a.n,ROW_NUMBER() OVER (PARTITION BY a.root ORDER BY
CASE d.split WHEN 'test' THEN 0 WHEN 'validation' THEN 1 ELSE 2 END,a.n) AS rn
FROM assignments a JOIN docs d ON d.n=a.n) WHERE rn=1''')
connection.execute('CREATE UNIQUE INDEX representative_roots ON representatives(root)')
cross_split = connection.execute('''SELECT COUNT(*) FROM (SELECT a.root FROM assignments a
JOIN docs d ON d.n=a.n GROUP BY a.root HAVING COUNT(DISTINCT d.split)>1)''').fetchone()[0]
component_count = connection.execute('SELECT COUNT(*) FROM representatives').fetchone()[0]
multi_components = connection.execute('SELECT COUNT(*) FROM (SELECT root FROM assignments GROUP BY root HAVING COUNT(*)>1)').fetchone()[0]
with source_path.open('rb') as f, (OUT/'assignments-private.jsonl').open('w',encoding='utf-8') as mapping, (OUT/'retained-private.jsonl').open('w',encoding='utf-8') as kept:
rows = connection.execute('''SELECT a.n,a.root,r.representative FROM assignments a JOIN representatives r ON a.root=r.root ORDER BY a.n''')
for number,root,representative in rows:
row = json.loads(f.readline())
mapping.write(json.dumps({'id':row['id'],'split':row['split'],'component':root,
'representative_id':ids[representative],'retained':number==representative},ensure_ascii=False)+'\n')
if number == representative: kept.write(json.dumps(row,ensure_ascii=False)+'\n')
connection.commit()
line_repeats = 0
# La base conserva offsets y números de línea; el hash solo propone candidatos.
# Los separadores de línea forman parte de la comparación exacta.
with source_path.open('rb') as f, (OUT/'lines-deduplicated-private.jsonl').open('w',encoding='utf-8') as cleaned_lines:
for doc_n in range(n):
row = json.loads(f.readline()); retained = []
for line_n,line in enumerate(row['text'].splitlines(keepends=True)):
if not line.strip():
retained.append(line); continue
d = digest(line.encode('utf-8'))
candidates = connection.execute('SELECT doc_n,line_n FROM line_hashes WHERE digest=?',(d,))
duplicate = any(text_at(other_doc).splitlines(keepends=True)[other_line] == line for other_doc,other_line in candidates)
if duplicate: line_repeats += 1
else:
connection.execute('INSERT INTO line_hashes VALUES (?,?,?)',(d,doc_n,line_n))
retained.append(line)
cleaned_lines.write(json.dumps({'id':row['id'],'split':row['split'],'text':''.join(retained)},ensure_ascii=False)+'\n')
connection.commit()
own_cost = meter.finish()
result = {'documents':n,'exact_document_duplicates':exact_duplicates,'repeated_nonempty_lines':line_repeats,
'candidate_pairs':connection.execute('SELECT COUNT(*) FROM candidates').fetchone()[0],
'verified_pairs':verified_count,'clusters_with_duplicates':multi_components,
'documents_removed_if_keep_one':n-component_count,'cross_split_components':cross_split,
'representative_policy':'test, después validation y luego train; primera posición dentro de cada prioridad; se conserva la partición original',
'config':{'shingle_words':SHINGLE,'bands':BANDS,'rows':ROWS,'seed':SEED,'hash_prime':P,
'normalization':'casefold y secuencias Unicode de palabras; shingles como conjuntos',
'threshold':THRESHOLD,'workers':WORKERS,'bucket_limit':BUCKET_LIMIT,'pair_limit':PAIR_LIMIT},
'source_sha256':file_digest(source_path),'source_records_sha256':file_digest(metadata_path),
'own_cost':own_cost,
'note':'Los tiempos dependen del equipo. El hash de shingles es aproximado; el Jaccard verificado usa palabras completas.'}
# La figura usa solo una muestra pequeña y nunca publica texto.
if n <= 300:
metadata = {}
if metadata_path.stat().st_size <= 5_000_000:
meta = json.loads(metadata_path.read_text(encoding='utf-8'))
metadata = {r['id']:r for r in meta['records']}
docs = connection.execute('SELECT n,source_id,digest,words,sig FROM docs ORDER BY n').fetchall()
sigs = [None if row[4] is None else np.frombuffer(row[4],dtype='<u4') for row in docs]
candidates = set(connection.execute('SELECT a,b FROM candidates'))
nodes = [{'id':digest(row[1].encode('utf-8'))[:16],'source':metadata.get(row[1],{}).get('source'),
'tokens':metadata.get(row[1],{}).get('redacted_tokens'),'words':row[3],
'signature':None if sigs[i] is None else [int(x) for x in sigs[i]]} for i,row in enumerate(docs)]
pairs = []
for a in range(n):
aa = get_shingles(a)
for b in range(a+1,n):
score = exact_jaccard(aa,get_shingles(b))
if score is None: continue
collisions = sum(np.array_equal(sigs[a][i*ROWS:(i+1)*ROWS],sigs[b][i*ROWS:(i+1)*ROWS]) for i in range(BANDS))
pairs.append([a,b,score,int(collisions)])
assert bool(collisions) == ((a,b) in candidates)
result['widget'] = {'nodes':nodes,'pairs':pairs,'pair_format':['node_a','node_b','jaccard_exact','coincident_bands']}
result['all_pairs_count'] = len(pairs)
if os.getenv('ORYON_COMPARE_DATATROVE') == '1':
dt_meter = MemoryMeter()
texts = []
with source_path.open('rb') as f:
for _ in range(min(n,300)): texts.append(json.loads(f.readline())['text'])
dt = datatrove_signatures(texts); dt_pairs = set()
by_band = {}
for i,sig in enumerate(dt):
if sig is None: continue
for band in range(BANDS): by_band.setdefault((band,tuple(sig[band])),[]).append(i)
for members in by_band.values():
for i,a in enumerate(members):
for b in members[i+1:]: dt_pairs.add((a,b))
# Se compara la misma muestra; Datatrove usa su propia normalización y funciones hash.
ours = set(connection.execute('SELECT a,b FROM candidates WHERE a<? AND b<?',(len(texts),len(texts))))
dt_verified = [(a,b,exact_jaccard(get_shingles(a),get_shingles(b))) for a,b in sorted(dt_pairs)]
dt_groups = DSU(len(texts))
union_exact_texts(dt_groups,texts)
for a,b,score in dt_verified:
if score is not None and score >= THRESHOLD: dt_groups.union(a,b)
result['datatrove'] = {'method':'MinhashDedupSignature.get_shingles/get_signature con SHA-1 de 64 bits, agrupación propia por bandas, verificación exacta y unión previa de textos idénticos, incluso sin shingles; no es el pipeline completo',
'sample_documents':len(texts),'candidate_pairs':len(dt_pairs),'candidate_intersection':len(ours & dt_pairs),
'verified_pairs':sum(s is not None and s>=THRESHOLD for _,_,s in dt_verified),
'removed_if_keep_one':len(texts)-len({dt_groups.find(i) for i in range(len(texts))}),
'cost':dt_meter.finish(),'cost_caveat':'sin lectura inicial ni deduplicación exacta; RSS con objetos anteriores en memoria, no comparables como procesos independientes'}
with source_path.open('rb') as f:
sample_texts = [json.loads(f.readline())['text'] for _ in range(min(n,8))]
result['suffix_array'] = suffix_repetitions(sample_texts)
cleaned = result['suffix_array'].pop('cleaned_token_sequences')
with (OUT/'suffix-cleaned-private.jsonl').open('w',encoding='utf-8') as f:
for i,tokens in enumerate(cleaned): f.write(json.dumps({'document_index':i,'scope':'prefijo indexado normalizado, no documento completo','tokens':tokens},ensure_ascii=False)+'\n')
(OUT/'dedup-report.json').write_text(json.dumps(result,ensure_ascii=False),encoding='utf-8')
print('Documentos',n,'candidatos',result['candidate_pairs'],'pares verificados',verified_count,'duplicados exactos',exact_duplicates,flush=True)
if 'datatrove' in result: print('DataTrove:',result['datatrove'],flush=True)
print('Informe:',OUT/'dedup-report.json',flush=True)
connection.close()
if __name__ == '__main__': main()npm run lab and open the connection link.Exercises
Step 1 of 3. When do the minima of A and B match?
import hashlib
import numpy as np
P = 2**31 - 1
def minhash_signature(shingles, k, seed):
pass
def estimate_jaccard(sig_a, sig_b):
pass
MinHash approximates similarity; LSH proposes candidates; verification and grouping policy decide what is removed. Each stage has different assumptions, errors, and costs.