Download kip_hash.py from IO-AIR/kip-hash: direct link, hf CLI and curl.
- Browser
- Download file 100 kB
-
https://huggingface.co/IO-AIR/kip-hash/resolve/main/kip_hash.py
- Command line
-
hf download hf://IO-AIR/kip-hash/kip_hash.py
-
curl -L -o kip_hash.py https://huggingface.co/IO-AIR/kip-hash/resolve/main/kip_hash.py
100 kB
"""kip-hash — the nano verify-and-dedup word (schema 5, scaled).
One 32-bit word per row, two jobs, pure-stdlib inference:
word = (bucket << 8) | level # 24 learned bucket bits + 8 score bits
1. DEDUP PLANE (fuzzy by design, inherited from schema 2): the 24
bucket bits are six learned scalar projections z_k of a hashed
feature view (word uni/bi-grams + char 4-grams, log-tf, L2), each
quantized with equal-mass bin edges learned from the training
corpus. Near-duplicates differ by less than a bin width, so
quantization ABSORBS the perturbation instead of betting bit-by-bit
(SimHash) or shingle-by-shingle (MinHash): dups collide, and +-bin
probing recovers pairs that straddle an edge. Schema 5 adds MASKED
MULTI-PROBE candidate generation (config probe_masks): each masked
grid drops dims (sentinel -1) so a pair becomes a candidate when
ANY DEDUP_DIMS-m of its dims sit inside the +-r grid - the shipped
masks [1, 2] lift confirmed recall 0.9376 -> 0.9769 at zero
post-guard false merges (measured, eval/report.json). Candidate
over-generation is still repaired by the cheap per-dimension |dz|
confirmation - no text re-read at signing time.
2. VERIFY PLANE (schema 4/5: scaled SCORER - the novel half). v3 gave
the score its own feature space (hashed word uni/bi-gram LEXICON,
2 ridge scalars) and still capped at junk AUC ~0.68 / Spearman
~0.20: two scalars cannot carry "what the text is about". Schema
4 scaled the plane to a 12-dim MULTI-TASK quality projection (the
first two columns are the v3 lexicon recipe kept for continuity;
ten more ridge columns distill knowledge, junk and nine content
facets of the same salted uni/bi-gram view), then a trained int8
MLP head (hidden tanh) with a pairwise ranking term recombines
[facets + tanh(z) + 26-feature battery3] nonlinearly. Schema 5
scales the plane further (24 columns: more surface facets +
teacher-quantile columns) and widens the head grid; fold-driven
config selection; isotonic-calibrated verdict packed to 8 bits.
Goal set by the 2026-11 directive: word-only triage good enough
to rival a neural verifier's judgment, not just beat MinHash.
Schemas 1/2/3/4 remain loadable: KipHash dispatches per artifact
(v1: shared 10-dim projection + linear heads, 16 levels; v2: two-plane
14-dim projection + tanh towers; v3: dedup plane + 2-scalar lexicon
ridge; v4: first scaled scorer + retrained dedup plane). The v4 -> v5
update (2026-11) RETRAINS the dedup plane on ~2.5x scaled
construction-known-truth supervision with four new perturbation
families (unicode, whitespace, insertion, casing), adds the masked
multi-probe geometry above, and scales the scorer plane to 24
columns; dedup SEMANTICS (binning, +-bin probing, guard, collision
policy) are unchanged - only the learned W, the probe keys and the
scorer head are new. Old artifacts load and sign byte-identically
(regression-tested against the released v4 engine).
Engine features (all measured, docs/kip_hash_pilot16_discussion.md):
* LEXICAL GUARD - 5-gram Jaccard >= 0.25 on confirmed candidates
before a merge is finalized; gray zone
(0.25 <= J < 0.5) is recorded for teacher
adjudication instead of merged. Costs
~nothing: candidates are rare (~0.1-4%).
* COLLISION POLICY - "on collision keep the higher-quality row":
the cluster survivor is picked by
(score, quality_fine, length, -arrival).
The packed level makes this O(1).
* QUALITY GATE - rows below a score level are dropped before
they ever enter the bucket index (read
straight off the stored word).
* COMPACT MODE - with_compact() re-bands the SAME learned
projection to the stored 18-bit-bucket geometry
(22-bit word) for <= 1M-row corpora.
* GRAM MEMO - gram->bucket hashes are memoized (bounded,
value-identical: same blake2b result, cached).
Repeat traffic - function words, common
bigrams - skips hashing entirely; measured
in eval/report.json throughput.
* FUSED SIGNING - one-pass surface battery, plain-loop CJK
test, per-dim unrolled projections (codegen
at load) - byte-identical outputs, ~1.6x the
v3 single-core signing rate.
* PARALLEL SIGNING - sign_batch(texts, workers=k) fans signing
out over k processes (stdlib multiprocessing,
order-preserving, results identical to the
serial path) for corpus-scale runs.
legacy=True on dedup_stream reproduces the pre-guard mechanics exactly
(first candidate wins, no guard, no gate, no re-ranking) for
comparability.
Teachers (distillation roster): DeepSeek-V4.1-Flash-1017 via the
DeepSeek webapp (channel 1, human-rhythm multi-turn batches),
kimi-k3.1-pro via NVIDIA NIM (channel 2, bulk), MiniMax M3.1 Flash
via NVIDIA NIM (designated fallback). Batched structured annotation;
see scripts/label_run_v4.py and scripts/label_run_nim.py.
Usage:
from kip_hash import KipHash
vh = KipHash("kip-hash.json")
w = vh.sign_text("...row text...")
w["word"] # 32-bit int: 24 bucket bits | 8 score bits
w["score4"] # packed quality level: 0-255 (v2/v3/v4) / 0-15 (v1)
w["quality"] # isotonic-decoded 0-100 verdict for that level
w["quality_fine"] # fine verdict before level packing
w["junk_prob"] # hash-side junk/boilerplate flag
vh.fuzzy_keys(w["bins"]) # +-r-bin probe keys
vh.confirm(z_a, z_b) # post-candidate verification
keep, dups, report = vh.dedup_stream(texts, gate=64)
# flags: guard=0.25, gray_zone=0.5, keep="quality", legacy=False,
# junk_floor=True (pretrain profile: drop junk-flagged rows)
vh.with_compact() # 22-bit word view for <=1M rows
vh.sign_batch(texts, workers=4) # corpus-scale parallel signing
CLI: python3 kip_hash.py (demo + selftest)
"""
import base64
import bisect
import hashlib
import json
import math
import re
import struct
import unicodedata
from array import array
from collections import Counter
from itertools import combinations, product
SCHEMA = "kip.hash.6"
_SCHEMAS = ("kip.hash.1", "kip.hash.2", "kip.hash.3", "kip.hash.4",
"kip.hash.5", "kip.hash.6")
_PERSON = b"kipvh3"
_QPERSON = b"kipvh3q" # quality-view salt (schema 3/4)
# gram->bucket memo: values are pure functions of (salt, n, gram), so
# caching never changes a signing result - it only skips repeat
# blake2b work. Bounded; wholesale clear keeps memory flat.
_GRAM_CACHE = {} # dedup-view gram -> bucket (salt kipvh3)
_GRAM_CACHE_Q = {} # quality-view gram -> bucket (salt kipvh3q)
_GRAM_CACHE_MAX = 400_000
_WORD_RE = re.compile(r"\w+", re.UNICODE)
_WS_RE = re.compile(r"\s+")
_CJK_RANGES = ((0x3000, 0x9FFF), (0xF900, 0xFAFF), (0xFF00, 0xFFEF))
_STOP = set("the of and to in a is that for it as was with be by on not he this are or his from at which but have an they one you had were all we her she there been if no more when who will would up out so said what its about into than them can only other new some could time these two may then do first any my now such like over our out most work also see use how each their".split())
_SENT_RE = re.compile(r"(?<=[.!?])\s+")
_log2 = math.log2
_sqrt = math.sqrt
BATTERY_NAMES = [
"log_len", "alnum_ratio", "alpha_ratio", "digit_ratio",
"space_ratio", "punct_ratio", "upper_ratio", "unique_word_ratio",
"mean_word_len", "stopword_ratio", "rep4_ratio", "newline_ratio",
"log_sent_len", "sent_density", "cjk_ratio", "latin_ratio",
]
N_BATTERY = len(BATTERY_NAMES)
def battery(text):
"""16 deterministic surface-quality features (pure stdlib).
The quality/junk heads read [z, battery_std] at signing time; the
packed score in the word is derived from the same verdict, so
hash-only triage stays O(1) from the stored word.
The eight per-class character counts are computed in ONE fused
pass (values identical to the original eight passes; the freeze
check in train_kip_hash_v3.py asserts this against the shipped
v2 artifact's stored battery stats).
"""
t = text or ""
n = max(1, len(t))
alpha = digit = alnum = space = upper = cjk = latin = 0
for c in t:
if c.isupper():
upper += 1
if c.isalnum():
alnum += 1
if c.isalpha():
alpha += 1
if c.isascii():
latin += 1
elif c.isdigit():
digit += 1
if c.isspace():
space += 1
o = ord(c)
if o >= 0x3000 and ((o <= 0x9FFF) or (0xF900 <= o <= 0xFAFF)
or (0xFF00 <= o <= 0xFFEF)):
cjk += 1
words = _WORD_RE.findall(t.lower())
nw = max(1, len(words))
uniq = len(set(words)) / nw
mwl = sum(len(w) for w in words) / nw
stop = sum(1 for w in words if w in _STOP) / nw
grams = ["".join(words[i:i + 4]) for i in range(max(0, len(words) - 3))]
rep4 = 1.0 - (len(set(grams)) / max(1, len(grams)))
nl = t.count("\n") / n
sents = [s for s in _SENT_RE.split(t) if s.strip()]
ns = max(1, len(sents))
asl = len(t) / ns
punct = n - alnum - space
return [
min(1.0, math.log10(max(1, len(t))) / 5.0), alnum / n, alpha / n,
digit / n, space / n, punct / n, upper / n, uniq,
min(1.0, mwl / 20.0), stop,
min(1.0, rep4), min(1.0, nl * 5.0), min(1.0, math.log10(asl) / 4.0),
min(1.0, ns / max(1, len(t)) * 40.0), cjk / n, latin / n,
]
BATTERY2_NAMES = BATTERY_NAMES + [
"weird_ratio", # control/format/private-use char density
"link_density", # http/www/@ mentions per 1k chars
"quote_ratio", # quotation mark density
"word_len_cv", # coefficient of variation of word lengths
"ellipsis_ratio", # .../… density (forum/chat drift)
"max_run_ratio", # longest same-char run / len (===== headers)
]
N_BATTERY2 = len(BATTERY2_NAMES)
_WEIRD_CATS = frozenset(("Cc", "Cf", "Co", "Cs"))
def battery2(text):
"""22 deterministic surface-quality features (battery + 6 v2).
Schema-2 artifacts sign with THIS view; schema-1 artifacts keep the
16-feature battery(). The six additions target exactly what the v1
heads missed in eval: link farms, repeated-char boilerplate,
ellipsis-heavy forum drift and pathological char runs.
"""
t = text or ""
n = max(1, len(t))
# identical semantics to the original category() scan: Cc/Cf/Co/Cs
# are never alnum and never the ASCII space, so the common case
# short-circuits without the unicodedata call
weird = 0
for c in t:
if c.isalnum() or c == " ":
continue
if unicodedata.category(c) in _WEIRD_CATS:
weird += 1
weird /= n
tl = t.lower()
links = (tl.count("http") + tl.count("www.") + t.count("@")) \
* 1000.0 / n
quotes = sum(t.count(c) for c in ('"', "'", "\u00ab", "\u00bb",
"\u201c", "\u201d")) / n
words = _WORD_RE.findall(t)
wl = [len(w) for w in words] or [1]
mwl = sum(wl) / len(wl)
var = sum((x - mwl) ** 2 for x in wl) / len(wl)
wcv = (var ** 0.5) / mwl if mwl else 0.0
ell = (t.count("...") + t.count("\u2026")) * 40.0 / n
mx = run = 1
prev = None
for c in t:
if c == prev:
run += 1
if run > mx:
mx = run
else:
run = 1
prev = c
return [
*battery(t),
min(1.0, weird),
min(1.0, links / 10.0),
min(1.0, quotes * 10.0),
min(1.0, wcv / 2.0),
min(1.0, ell),
min(1.0, mx / 50.0),
]
_BOILER_PHRASES = (
"log in", "log-in", "sign up", "sign in", "subscribe", "newsletter",
"privacy policy", "cookie", "terms of", "all rights reserved",
"follow us", "share this", "back to top", "click here", "buy now",
"limited time", "sponsored", "advertisement", "checkout",
"shopping cart", "my account", "contact us", "about us",
"read more", "leave a comment", "post a comment", "skip to",
"free shipping", "money back", "promo code", "discount code",
"related articles", "you may also like", "trending now",
"table of contents", "last updated", "copyright 20", "(c) 20",
"all rights")
_BOILER_WORDS = frozenset((
"login", "signup", "subscribe", "cookie", "cookies", "privacy",
"newsletter", "copyright", "menu", "checkout", "cart", "faq",
"sponsor", "sponsored", "ads", "advert", "password", "username",
"captcha", "unsubscribe", "sitemap", "rss", "tweet", "share",
"like", "comment", "email", "http", "https", "www", "com", "html"))
BATTERY3_NAMES = BATTERY2_NAMES + [
"boiler_ratio", # nav/cookie/SEO boilerplate density
"repeat_line_ratio", # duplicated non-empty lines / lines
"caps_word_ratio", # SHOUTING-word density
"sent_cohesion", # mean consecutive-sentence word overlap
]
N_BATTERY3 = len(BATTERY3_NAMES)
def battery3(text):
"""26 deterministic surface-quality features - FUSED single pass.
Semantically IDENTICAL to the historical chain battery3 = battery2
+ [boiler_ratio, repeat_line_ratio, caps_word_ratio,
sent_cohesion] with battery2 = battery + 6; the trainer's freeze
assert compares this output against the shipped v3 artifact's
stored stats and the frozen reference vectors. One char scan, one
lower-cased word pass, one raw word pass instead of three of
each. The additions target the junk modes the gate sweep kept
flagging (nav/cookie/SEO boilerplate farms, duplicated line
blocks, shouting caps runs) plus the one coherence proxy surface
stats missed: whether consecutive sentences actually continue
each other's vocabulary (lexical cohesion).
"""
t = text or ""
n = max(1, len(t))
# ---- single character scan: everything the three legacy passes
# counted, fused (same increments -> identical values). v6.5:
# ONE C-level Counter pass over the raw text + per-DISTINCT-char
# classification (identical integer counts - each char's category
# is decided exactly once instead of at every position). The
# longest same-char run stays a plain equality loop. Semantics
# frozen: the space/weird tests apply only to non-alnum chars,
# control whitespace (\n, \t, category Cc) IS counted as space
# and weird.
alpha = digit = alnum = space = upper = cjk = latin = weird = 0
for c, k in Counter(t).items():
if c.isalnum():
alnum += k
if c.isalpha():
alpha += k
if c.isascii():
latin += k
elif c.isdigit():
digit += k
else:
if c.isspace():
space += k
if c != " " and unicodedata.category(c) in _WEIRD_CATS:
weird += k
if c.isupper():
upper += k
o = ord(c)
if o >= 0x3000 and ((o <= 0x9FFF) or (0xF900 <= o <= 0xFAFF)
or (0xFF00 <= o <= 0xFFEF)):
cjk += k
# longest same-char run: plain equality loop - cheaper than
# groupby+sum for low-repeat text (measured v6.5) and identical
mx = run = 1
prev = None
for c in t:
if c == prev:
run += 1
if run > mx:
mx = run
else:
run = 1
prev = c
# ---- battery() block (values identical to legacy battery())
tl = t.lower()
words_l = _WORD_RE.findall(tl)
nw_l = max(1, len(words_l))
uniq = len(set(words_l)) / nw_l
mwl = sum(len(w) for w in words_l) / nw_l
stop = sum(1 for w in words_l if w in _STOP) / nw_l
grams = ["".join(words_l[i:i + 4])
for i in range(max(0, len(words_l) - 3))]
rep4 = 1.0 - (len(set(grams)) / max(1, len(grams)))
nl = t.count("\n") / n
sents = [s for s in _SENT_RE.split(t) if s.strip()]
ns = max(1, len(sents))
asl = len(t) / ns
punct = n - alnum - space
bat = [
min(1.0, math.log10(max(1, len(t))) / 5.0), alnum / n, alpha / n,
digit / n, space / n, punct / n, upper / n, uniq,
min(1.0, mwl / 20.0), stop,
min(1.0, rep4), min(1.0, nl * 5.0),
min(1.0, math.log10(asl) / 4.0),
min(1.0, ns / max(1, len(t)) * 40.0), cjk / n, latin / n,
]
# ---- battery2() block (identical to legacy battery2())
links = (tl.count("http") + tl.count("www.") + t.count("@")) \
* 1000.0 / n
quotes = sum(t.count(c) for c in ('"', "'", "\u00ab", "\u00bb",
"\u201c", "\u201d")) / n
words_r = _WORD_RE.findall(t)
wl = [len(w) for w in words_r] or [1]
mwl_r = sum(wl) / len(wl)
var = sum((x - mwl_r) ** 2 for x in wl) / len(wl)
wcv = (var ** 0.5) / mwl_r if mwl_r else 0.0
ell = (t.count("...") + t.count("\u2026")) * 40.0 / n
bat += [
min(1.0, weird / n),
min(1.0, links / 10.0),
min(1.0, quotes * 10.0),
min(1.0, wcv / 2.0),
min(1.0, ell),
min(1.0, mx / 50.0),
]
# ---- battery3() additions (identical to legacy)
hits = sum(tl.count(p) for p in _BOILER_PHRASES)
nw = max(1, len(words_r))
hits += sum(1 for w in words_r if w.lower() in _BOILER_WORDS)
boiler = hits * 1000.0 / n
lines = [ln.strip() for ln in t.split("\n") if ln.strip()]
rep_line = 0.0
if len(lines) > 1:
rep_line = (len(lines) - len(set(lines))) / len(lines)
caps = sum(1 for w in words_r if len(w) >= 3 and w.isupper()) / nw
cohesion = 0.0
if len(sents) >= 2:
prev_s = set(_WORD_RE.findall(sents[0].lower()))
ov = 0
for s in sents[1:]:
cur = set(_WORD_RE.findall(s.lower()))
if prev_s and cur:
ov += len(prev_s & cur) / len(prev_s | cur)
prev_s = cur
cohesion = ov / (len(sents) - 1)
return [*bat, min(1.0, boiler / 10.0),
min(1.0, rep_line), min(1.0, caps), cohesion]
BATTERY4_NAMES = BATTERY3_NAMES + [
"long_word_ratio", # words >= 10 chars (morphology/technical depth)
"short_sent_ratio", # sentences <= 6 words (fragmentation/caption drift)
"sent_len_cv", # sentence-length coefficient of variation (rhythm)
"list_line_ratio", # lines starting with -, *, bullet, digit-dot
"digit_word_ratio", # purely-digit words (stat spam / table debris)
"top_word_dom", # most frequent word / words (keyword stuffing)
"punct_burst_ratio", # !!/?? run density (forum/clickbait drift)
"dup_sent_ratio", # duplicated non-empty sentences (scrape boilerplate)
]
N_BATTERY4 = len(BATTERY4_NAMES)
def battery4(text):
"""34 deterministic surface-quality features - FUSED single pass.
v6.6 scorer-plane widening: battery4 = battery3 (26 features,
BIT-IDENTICAL values - same loops, same expressions, same order)
+ 8 new script-agnostic structure features computed inside the
SAME fused pass (per-sentence word counts ride the cohesion
loop, the burst counter rides the longest-run char loop, list
lines ride the existing lines split). The trainer freezes
battery4[:26] == battery3 on pool texts + edge cases; the junk
head keeps reading the battery3 CORE block (26) so the v3-parity
junk construction is untouched, while the verdict head sees the
full 34.
"""
t = text or ""
n = max(1, len(t))
alpha = digit = alnum = space = upper = cjk = latin = weird = 0
for c, k in Counter(t).items():
if c.isalnum():
alnum += k
if c.isalpha():
alpha += k
if c.isascii():
latin += k
elif c.isdigit():
digit += k
else:
if c.isspace():
space += k
if c != " " and unicodedata.category(c) in _WEIRD_CATS:
weird += k
if c.isupper():
upper += k
o = ord(c)
if o >= 0x3000 and ((o <= 0x9FFF) or (0xF900 <= o <= 0xFAFF)
or (0xFF00 <= o <= 0xFFEF)):
cjk += k
# longest same-char run + !!/?? burst counter in the SAME loop
mx = run = 1
burst = 0
prev = None
for c in t:
if c == prev:
run += 1
if run > mx:
mx = run
if c == "!" or c == "?":
burst += 1
else:
run = 1
prev = c
tl = t.lower()
words_l = _WORD_RE.findall(tl)
nw_l = max(1, len(words_l))
uniq = len(set(words_l)) / nw_l
mwl = sum(len(w) for w in words_l) / nw_l
stop = sum(1 for w in words_l if w in _STOP) / nw_l
grams = ["".join(words_l[i:i + 4])
for i in range(max(0, len(words_l) - 3))]
rep4 = 1.0 - (len(set(grams)) / max(1, len(grams)))
nl = t.count("\n") / n
sents = [s for s in _SENT_RE.split(t) if s.strip()]
ns = max(1, len(sents))
# v6.6 robustness fix: battery3 crashed on len(t)==0 (log10(0));
# max(1, len(t)) is IDENTICAL for every non-empty text (len>=1)
asl = max(1, len(t)) / ns
punct = n - alnum - space
bat = [
min(1.0, math.log10(max(1, len(t))) / 5.0), alnum / n, alpha / n,
digit / n, space / n, punct / n, upper / n, uniq,
min(1.0, mwl / 20.0), stop,
min(1.0, rep4), min(1.0, nl * 5.0),
min(1.0, math.log10(asl) / 4.0),
min(1.0, ns / max(1, len(t)) * 40.0), cjk / n, latin / n,
]
links = (tl.count("http") + tl.count("www.") + t.count("@")) \
* 1000.0 / n
quotes = sum(t.count(c) for c in ('"', "'", "\u00ab", "\u00bb",
"\u201c", "\u201d")) / n
words_r = _WORD_RE.findall(t)
wl = [len(w) for w in words_r] or [1]
mwl_r = sum(wl) / len(wl)
var = sum((x - mwl_r) ** 2 for x in wl) / len(wl)
wcv = (var ** 0.5) / mwl_r if mwl_r else 0.0
ell = (t.count("...") + t.count("\u2026")) * 40.0 / n
bat += [
min(1.0, weird / n),
min(1.0, links / 10.0),
min(1.0, quotes * 10.0),
min(1.0, wcv / 2.0),
min(1.0, ell),
min(1.0, mx / 50.0),
]
hits = sum(tl.count(p) for p in _BOILER_PHRASES)
nw = max(1, len(words_r))
hits += sum(1 for w in words_r if w.lower() in _BOILER_WORDS)
boiler = hits * 1000.0 / n
lines = [ln.strip() for ln in t.split("\n") if ln.strip()]
rep_line = 0.0
if len(lines) > 1:
rep_line = (len(lines) - len(set(lines))) / len(lines)
caps = sum(1 for w in words_r if len(w) >= 3 and w.isupper()) / nw
# cohesion loop EXTENDED (not changed): per-sentence word counts +
# duplicated-sentence detection ride the same findall iteration
sent_wc = []
sent_seen = set()
dup_sent = 0
cohesion = 0.0
if len(sents) >= 2:
w0 = _WORD_RE.findall(sents[0].lower())
sent_wc.append(len(w0))
sent_seen.add(sents[0].lower())
prev_s = set(w0)
ov = 0
for s in sents[1:]:
cur = set(_WORD_RE.findall(s.lower()))
sent_wc.append(len(cur))
sl = s.lower()
if sl in sent_seen:
dup_sent += 1
else:
sent_seen.add(sl)
if prev_s and cur:
ov += len(prev_s & cur) / len(prev_s | cur)
prev_s = cur
cohesion = ov / (len(sents) - 1)
# ---- battery4() additions (new signal, same pass) ---------------
long_w = sum(1 for x in wl if x >= 10) / max(1, len(wl))
short_s = (sum(1 for c in sent_wc if c <= 6) / ns) if sent_wc \
else 0.0
if len(sent_wc) >= 2:
s_mean = sum(sent_wc) / len(sent_wc)
s_var = sum((x - s_mean) ** 2 for x in sent_wc) / len(sent_wc)
s_cv = (s_var ** 0.5) / s_mean if s_mean else 0.0
else:
s_cv = 0.0
list_lines = 0
for ln in lines:
if ln[0] in "-*\u2022" or (ln[0].isdigit()
and len(ln) > 1 and ln[1] in ".)"):
list_lines += 1
digit_w = sum(1 for w in words_r if w.isdigit()) / nw
top_dom = (Counter(words_l).most_common(1)[0][1] / nw_l) \
if words_l else 0.0
return [*bat, min(1.0, boiler / 10.0),
min(1.0, rep_line), min(1.0, caps), cohesion,
long_w, short_s, min(1.0, s_cv / 1.5),
list_lines / max(1, len(lines)), digit_w, top_dom,
min(1.0, burst * 40.0 / n), dup_sent / ns]
def _bucket(feat, n_features):
cache = _GRAM_CACHE
b = cache.get(feat)
if b is None:
h = hashlib.blake2b(feat.encode("utf-8"), digest_size=8,
person=_PERSON).digest()
b = int.from_bytes(h, "big") % n_features
if len(cache) >= _GRAM_CACHE_MAX:
cache.clear()
cache[feat] = b
return b
def _bucket_q(feat, n_features):
cache = _GRAM_CACHE_Q
b = cache.get(feat)
if b is None:
h = hashlib.blake2b(feat.encode("utf-8"), digest_size=8,
person=_QPERSON).digest()
b = int.from_bytes(h, "big") % n_features
if len(cache) >= _GRAM_CACHE_MAX:
cache.clear()
cache[feat] = b
return b
def _is_cjk_heavy(text):
"""CJK density test (identical verdict to every legacy version).
v6.5: C-level Counter pass + per-DISTINCT-char range check."""
if not text:
return False
cjk = 0
for c, k in Counter(text).items():
o = ord(c)
if (0x3000 <= o <= 0x9FFF) or (0xF900 <= o <= 0xFAFF) \
or (0xFF00 <= o <= 0xFFEF):
cjk += k
return cjk / max(1, len(text)) > 0.2
def features(text, n_features=32768):
"""The kip-hash feature view: word uni/bi-grams + char 4-grams,
log-tf, L2.
train_kip_hash.py imports THIS function, so train/infer parity is
structural, not by convention.
"""
t = unicodedata.normalize("NFC", text).lower()
t = _WS_RE.sub(" ", t).strip()
counts = {}
if _is_cjk_heavy(t):
chars = [c for c in t if not c.isspace()]
for i, c in enumerate(chars):
counts["w1:" + c] = counts.get("w1:" + c, 0) + 1
if i:
g = chars[i - 1] + c
counts["w2:" + g] = counts.get("w2:" + g, 0) + 1
# char 4-grams via one C-speed Counter pass; the counts land at
# the END of the dict in first-occurrence order - exactly where
# the legacy per-position loop inserted them, so iteration
# order (and every downstream float) is byte-identical
if len(chars) >= 4:
counts.update(Counter(
"c4:" + "".join(chars[i:i + 4])
for i in range(len(chars) - 3)))
else:
words = _WORD_RE.findall(t)
for w in words:
counts["w1:" + w] = counts.get("w1:" + w, 0) + 1
for i in range(1, len(words)):
g = words[i - 1] + "_" + words[i]
counts["w2:" + g] = counts.get("w2:" + g, 0) + 1
gram_src = " " + t + " "
if len(gram_src) >= 4:
counts.update(Counter(
"c4:" + gram_src[i:i + 4]
for i in range(len(gram_src) - 3)))
feats = {}
for f, c in counts.items():
feats[_bucket(f, n_features)] = 1.0 + _log2(c)
norm = _sqrt(sum(w * w for w in feats.values())) or 1.0
inv = 1.0 / norm
return {f: w * inv for f, w in feats.items()}
def features_q(text, n_features=32768):
"""The schema-3 quality-lexicon view: word uni/bi-grams (CJK:
char uni/bi) under a separate hash salt, SUBLINEAR mean.
Deliberately different from the dedup view in three ways: no
char-4gram texture (verdict signal is content, not surface), a
distinct hash salt (the lexicon owns its buckets), and sublinear
mean aggregation - weight = (1 + log2 count), normalized by the
row's total weight (fastText-style averaging with a log-tf
brake on repetition bursts). Collisions SUM their mass (a linear
model must not lose collided rows).
train_kip_hash_v3.py imports THIS function - train/infer parity
is structural, as with features().
"""
t = unicodedata.normalize("NFC", text).lower()
t = _WS_RE.sub(" ", t).strip()
counts = {}
if _is_cjk_heavy(t):
chars = [c for c in t if not c.isspace()]
for i, c in enumerate(chars):
k = "q1:" + c
counts[k] = counts.get(k, 0) + 1
if i:
k = "q2:" + chars[i - 1] + c
counts[k] = counts.get(k, 0) + 1
else:
words = _WORD_RE.findall(t)
for w in words:
k = "q1:" + w
counts[k] = counts.get(k, 0) + 1
for i in range(1, len(words)):
k = "q2:" + words[i - 1] + "_" + words[i]
counts[k] = counts.get(k, 0) + 1
if not counts:
return {}
total = 0.0
for c in counts.values():
total += 1.0 + _log2(c)
inv = 1.0 / total
out = {}
for k, c in counts.items():
b = _bucket_q(k, n_features)
out[b] = out.get(b, 0.0) + (1.0 + _log2(c)) * inv
return out
def features_all(text, n_features=32768, n_features_q=None):
"""Both hashed views in ONE normalize/tokenize pass (schema 3/4).
Returns (feats, feats_q) - byte-identical to calling features()
and features_q() separately, but the NFC/lower/strip
normalization and word tokenization are shared instead of
repeated. The trainer imports THIS for corpus featurization.
n_features_q (schema 4) sizes the quality view's own hash space;
None keeps the historical behavior (both views share n_features -
the salts differ, so the views never interfere).
"""
if n_features_q is None:
n_features_q = n_features
t = unicodedata.normalize("NFC", text).lower()
t = _WS_RE.sub(" ", t).strip()
counts = {}
qcounts = {}
if _is_cjk_heavy(t):
chars = [c for c in t if not c.isspace()]
# v6.5: C-level Counter passes + insert-once loops. Iteration
# order and values are IDENTICAL to the legacy per-position
# get+1 loops (first-occurrence insert order, exact counts) -
# the collision last-wins semantics of the dedup view depend
# on that order, so parity is structural.
c1 = Counter(chars)
bg = [chars[i - 1] + chars[i] for i in range(1, len(chars))]
c2 = Counter(bg)
for i, c in enumerate(chars):
k = "w1:" + c
if k not in counts:
counts[k] = c1[c]
kq = "q1:" + c
if kq not in qcounts:
qcounts[kq] = c1[c]
if i:
g = bg[i - 1]
k = "w2:" + g
if k not in counts:
counts[k] = c2[g]
kq = "q2:" + g
if kq not in qcounts:
qcounts[kq] = c2[g]
if len(chars) >= 4:
counts.update(Counter(
"c4:" + "".join(chars[i:i + 4])
for i in range(len(chars) - 3)))
else:
words = _WORD_RE.findall(t)
# v6.6: Counter-driven DISTINCT-gram insertion. Counter dicts
# preserve first-encounter order, so iterating c1.items()/
# c2.items() lands every key in EXACTLY the order the legacy
# per-occurrence get+1 loops produced (first occurrence per
# gram, w1 block before w2 block) - identical orders, identical
# counts, identical collision last-wins outcomes - but the
# "w1:"/"q1:" strings are built once per DISTINCT gram instead
# of once per OCCURRENCE.
c1 = Counter(words)
for w, c in c1.items():
k = "w1:" + w
counts[k] = c
qcounts["q1:" + w] = c
bg = [words[i - 1] + "_" + words[i]
for i in range(1, len(words))]
c2 = Counter(bg)
for g, c in c2.items():
k = "w2:" + g
counts[k] = c
qcounts["q2:" + g] = c
gram_src = " " + t + " "
if len(gram_src) >= 4:
counts.update(Counter(
"c4:" + gram_src[i:i + 4]
for i in range(len(gram_src) - 3)))
feats = {}
# v6.5: bucket-cache lookup inlined (one C-level dict.get per gram,
# no per-gram Python frame) - values identical to _bucket()
cache = _GRAM_CACHE
cache_get = cache.get
log2 = _log2
blake2b = hashlib.blake2b
for f, c in counts.items():
b = cache_get(f)
if b is None:
h = blake2b(f.encode("utf-8"), digest_size=8,
person=_PERSON).digest()
b = int.from_bytes(h, "big") % n_features
if len(cache) >= _GRAM_CACHE_MAX:
cache.clear()
cache[f] = b
feats[b] = 1.0 + log2(c)
norm = _sqrt(sum(w * w for w in feats.values())) or 1.0
inv = 1.0 / norm
feats = {f: w * inv for f, w in feats.items()}
feats_q = {}
if qcounts:
total = 0.0
for c in qcounts.values():
total += 1.0 + log2(c)
qinv = 1.0 / total
cache_q = _GRAM_CACHE_Q
cache_q_get = cache_q.get
for k, c in qcounts.items():
b = cache_q_get(k)
if b is None:
h = blake2b(k.encode("utf-8"), digest_size=8,
person=_QPERSON).digest()
b = int.from_bytes(h, "big") % n_features_q
if len(cache_q) >= _GRAM_CACHE_MAX:
cache_q.clear()
cache_q[k] = b
feats_q[b] = feats_q.get(b, 0.0) + (1.0 + log2(c)) * qinv
return feats, feats_q
def _make_projector(w_rows, n_dims):
"""Codegen an unrolled sparse-projection function.
w_rows: list of n_dims per-index weight lists (row-major D x dims,
already transposed into per-dim lists). Returns f(feats) -> list
of n_dims floats, accumulation order IDENTICAL to the historical
`for f, xw in feats.items(): for i in range(dims): p[i] += xw *
row[i]` (same float ops, same order - just without the inner-loop
interpreter overhead). This is a pure-stdlib speed trick: the
generated source is fixed given n_dims, nothing data-dependent.
v6.5: the per-dim rows are additionally packed into ONE combined
per-index tuple table (T[f] = (w0..w_{dims-1})), so the hot loop
does a single list lookup per feature instead of n_dims; the
multiplied weights are the same float objects in the same order,
so every accumulated sum is bit-identical.
"""
assert 1 <= n_dims <= 32, "codegen projector supports 1..32 dims"
combined = [tuple(rows[f] for rows in w_rows)
for f in range(len(w_rows[0]))]
lines = ["def _proj(feats):",
" " + " = ".join(f"p{i}" for i in range(n_dims))
+ " = 0.0"]
acc = [f" p{i} += xw * t[{i}]" for i in range(n_dims)]
lines.append(" T = _COMBINED")
lines.append(" for f, xw in feats.items():")
lines.append(" t = T[f]")
lines.extend(acc)
lines.append(" return [" + ", ".join(f"p{i}" for i in range(n_dims))
+ "]")
src = "\n".join(lines)
ns = {"_COMBINED": combined}
exec(compile(src, "<kip-proj>", "exec"), ns)
return ns["_proj"]
def _sigmoid(z):
if z >= 0:
ez = math.exp(-z)
return 1.0 / (1.0 + ez)
ez = math.exp(z)
return ez / (1.0 + ez)
# multiprocessing worker plumbing for sign_batch (module-level so the
# fork pool can pickle it; each worker dequantizes the artifact once)
_WORKER = {"vh": None}
def _worker_init(art):
_WORKER["vh"] = KipHash(obj=art)
def _worker_sign(text):
return _WORKER["vh"].sign_text(text)
def _dot(a, b):
return sum(x * y for x, y in zip(a, b))
_PUNCT_SPACE_RE = re.compile(r"\s+([,.!?;:\u2026])")
def ngrams5(text):
"""Word 5-gram set for the lexical guard (pure stdlib).
CJK / short texts (fewer than 6 whitespace tokens) fall back to
character 5-grams so cross-script near-dups still carry overlap
signal instead of degenerating to J = 0.
v6.1 measured refinement: space-before-punctuation is canonicalized
away (French typography 'mot ?', OCR spacing, and the Georgian
Mtavruli formatting pair the v6.1 squeeze dump exposed). Formatting
variants of one document must not fail the guard - the grams
describe word ORDER, not typographic spacing. Applied identically to
both rows, so distinct-entity template twins gain nothing (their
distinguishing tokens still differ).
"""
t = _WS_RE.sub(" ", (text or "").lower()).strip()
t = _PUNCT_SPACE_RE.sub(r"\1", t)
w = t.split(" ") if t else []
if len(w) >= 6:
return {" ".join(w[i:i + 5]) for i in range(len(w) - 4)}
s = t.replace(" ", "")
if len(s) >= 5:
return {s[i:i + 5] for i in range(len(s) - 4)}
return set()
def jaccard5(a_text, b_text):
"""5-gram Jaccard for the lexical guard.
Pilot16 ground truth: true dups sit at 0.51-0.59, false merges at
0.000-0.014; guard threshold 0.25, gray zone up to 0.5.
"""
a = ngrams5(a_text)
if not a:
return 0.0
b = ngrams5(b_text)
if not b:
return 0.0
inter = len(a & b)
if not inter:
return 0.0
return inter / (len(a) + len(b) - inter)
class KipHash:
"""Loads a kip.hash.1/2/3/4 artifact; signs text to the packed word."""
def __init__(self, path=None, obj=None):
art = obj if obj is not None else json.load(open(path))
if art.get("schema") not in _SCHEMAS:
raise ValueError("not a %s artifact: %s"
% ("/".join(_SCHEMAS), art.get("schema")))
cfg = art["config"]
self.artifact = art
self.v2 = art["schema"] == "kip.hash.2"
self.v3 = art["schema"] == "kip.hash.3"
self.v4 = art["schema"] == "kip.hash.4"
# v6 = v5 supervision scale-up (identical artifact structure):
# same scaled-signing path, masked multi-probe keys, heads
self.v5 = art["schema"] in ("kip.hash.5", "kip.hash.6")
self.scaled = self.v4 or self.v5 # shared scaled-signing path
self.n_features = cfg["n_features"]
self.n_proj = cfg["n_proj"]
self.dedup_dims = cfg["dedup_dims"]
self.qual_dims = cfg.get("qual_dims",
self.n_proj - self.dedup_dims)
self.n_features_q = cfg.get("n_features_q", self.n_features)
self.bin_bits = list(cfg["bin_bits"])
self.score_bits = cfg["score_bits"]
self.fuzzy_radius = cfg.get("fuzzy_radius", 1)
self.fuzzy_radii = cfg.get("fuzzy_radii") # per-dim, if shipped
# schema 5: masked multi-probe candidate generation. Each entry
# m widens the probe with grids that drop m dims (sentinel -1),
# so a pair becomes a candidate when >= DEDUP_DIMS - m dims sit
# inside the +-r grid even if the remaining dims strayed. The
# lexical guard + tau confirmation own precision exactly as
# before; absent config = classic +-r grid only (v1-4
# artifacts are byte-identical).
self.probe_masks = [int(m) for m in (cfg.get("probe_masks") or [])
if 0 < int(m) < self.dedup_dims]
self.verify_tau = list(cfg["verify_tau"])
self._mu = cfg["z_mu"]
self._sigma = cfg["z_sigma"]
self._zq_mu = cfg.get("zq_mu")
self._zq_sigma = cfg.get("zq_sigma")
self._edges = cfg["bin_edges"]
self._score_edges = cfg["score_edges"]
self._score_centroids = cfg["score_centroids"]
self._bnames = list(cfg.get("battery_names") or BATTERY_NAMES)
if len(self._bnames) == N_BATTERY4:
self._battery_fn = battery4
elif len(self._bnames) == N_BATTERY3:
self._battery_fn = battery3
elif len(self._bnames) == N_BATTERY2:
self._battery_fn = battery2
else:
self._battery_fn = battery
self._bmu = cfg.get("battery_mu", [0.0] * len(self._bnames))
self._bsg = cfg.get("battery_sigma", [1.0] * len(self._bnames))
self._W8 = base64.b64decode(art["weights_int8_b64"])
self._scales_b64 = art["row_scales_f32_b64"]
self._row_scales = None
self._W = None
self._Wd = None
self._proj_dedup = None
self._proj_lex = None
self._proj_qe = None
lex = art.get("lexicon")
self._lex_raw = base64.b64decode(lex["weights_int8_b64"]) \
if lex else None
self._lex_scales = None
if lex:
la = array("f")
la.frombytes(base64.b64decode(lex["row_scales_f32_b64"]))
self._lex_scales = (la[:self.n_features].tolist(),
la[self.n_features:2 * self.n_features]
.tolist())
self._lex = None
self._lex_mu = list(cfg.get("lex_mu", [0.0, 0.0]))
self._lex_sigma = list(cfg.get("lex_sigma", [1.0, 1.0]))
# schema 4: scaled quality plane (QE) + trained int8 MLP head
qe = art.get("qe")
self.qe_dims = int(qe["dims"]) if qe else 0
self._qe_raw = base64.b64decode(qe["weights_int8_b64"]) \
if qe else None
self._qe_scales = None
self._qe = None
if qe:
qa = array("f")
qa.frombytes(base64.b64decode(qe["row_scales_f32_b64"]))
self._qe_scales = qa.tolist()
self._qe_mu = list(cfg.get("qe_mu") or [])
self._qe_sigma = list(cfg.get("qe_sigma") or [])
mlp = art.get("mlp")
self._mlp = None
self.mlp_use_z = bool(art.get("mlp_use_z", True))
if mlp:
h, nin = int(mlp["hidden"]), int(mlp["n_in"])
r1 = base64.b64decode(mlp["W1_int8_b64"])
a1 = array("f")
a1.frombytes(base64.b64decode(mlp["W1_scales_f32_b64"]))
W1 = [[(r1[i * nin + c] - 256 if r1[i * nin + c] > 127
else r1[i * nin + c]) * a1[i]
for c in range(nin)] for i in range(h)]
r2 = base64.b64decode(mlp["W2_int8_b64"])
a2 = array("f")
a2.frombytes(base64.b64decode(mlp["W2_scales_f32_b64"]))
n_out = len(r2) // h # int8: 1 byte per weight
W2 = [[(r2[i * h + c] - 256 if r2[i * h + c] > 127
else r2[i * h + c]) * a2[i]
for c in range(h)] for i in range(n_out)]
self._mlp = {"W1": W1, "b1": list(mlp["b1"]),
# v6.6: a skip-only head (W1/b1 all zero) has a
# dead hidden path - skipped bit-identically
# in _mlp_forward
"dead_hidden": not any(any(row) for row in W1)
and not any(mlp["b1"]),
"W2": W2, "b2": list(mlp["b2"]),
"Ws": [list(w) for w in mlp.get("Ws") or []],
"bs": list(mlp.get("bs") or [])}
jh = art.get("junk_head")
self._junk_head = {"w": list(jh["w"]), "b": float(jh["b"])} \
if jh else None
h = art["heads"]
self.h_q = h.get("quality_z")
self.h_j = h.get("junk_z")
self.mlp_q = h.get("mlp_q")
self.mlp_j = h.get("mlp_j")
self.pack_lambda = cfg.get("pack_lambda", 0.0)
# residuals ship disabled when their output layer is all zeros:
# the tower then reduces to its ridge skip (zero hidden cost)
self._q_hidden = self.mlp_q is not None and \
any(self.mlp_q.get("W2") or [])
self._j_hidden = self.mlp_j is not None and \
any(self.mlp_j.get("W2") or [])
self.junk_threshold = cfg["junk_threshold"] # logit space
# ---- projection ---------------------------------------------------
def row_scales(self):
if self._row_scales is None:
a = array("f")
a.frombytes(base64.b64decode(self._scales_b64))
self._row_scales = a.tolist()
return self._row_scales
def W(self):
if self._W is None:
raw, sc, P, nd = self._W8, self.row_scales(), self.n_proj, \
self.dedup_dims
if len(sc) == 2 * self.n_features:
# per-plane scales (schema 2): dedup dims scale with the
# dedup plane's absmax, quality dims with the quality
# plane's - one shared absmax would crush the smaller
# plane's int8 resolution
sd, sq = sc[:self.n_features], sc[self.n_features:]
self._W = [
[(raw[f * P + i] - 256 if raw[f * P + i] > 127 else
raw[f * P + i]) * (sd[f] if i < nd else sq[f])
for i in range(P)]
for f in range(self.n_features)]
else:
self._W = [
[(raw[f * P + i] - 256 if raw[f * P + i] > 127 else
raw[f * P + i]) * sc[f]
for i in range(P)]
for f in range(self.n_features)]
return self._W
def project(self, text):
return self.project_feats(features(text, self.n_features))
def project_feats(self, feats):
"""Dedup projection - codegen-unrolled, float-identical."""
if self._proj_dedup is None:
self._proj_dedup = _make_projector(self._W_perdim(),
self.n_proj)
return self._proj_dedup(feats)
def _W_perdim(self):
"""W transposed to per-dim index lists for the codegen projector."""
if self._Wd is None:
W = self.W()
self._Wd = [[W[f][i] for f in range(self.n_features)]
for i in range(self.n_proj)]
return self._Wd
def lexicon(self):
"""Dequantized int8 lexicon: [(w_verdict, w_junk)] per feature."""
if self._lex is None:
raw, (s0, s1) = self._lex_raw, self._lex_scales
lex = []
for f in range(self.n_features):
b0 = raw[f * 2]
b1 = raw[f * 2 + 1]
lex.append(((b0 - 256 if b0 > 127 else b0) * s0[f],
(b1 - 256 if b1 > 127 else b1) * s1[f]))
self._lex = lex
return self._lex
def project_lex(self, feats_q):
"""Mean-aggregated lexicon view -> [verdict scalar, junk scalar].
Codegen-unrolled (float-identical to the historical loop).
"""
if self._proj_lex is None:
lex = self.lexicon()
self._proj_lex = _make_projector(
[[lr[0] for lr in lex], [lr[1] for lr in lex]], 2)
return self._proj_lex(feats_q)
def qe_plane(self):
"""Dequantized schema-4 quality plane: QE per-dim index lists."""
if self._qe is None:
raw, sc, QE, Dq = (self._qe_raw, self._qe_scales,
self.qe_dims, self.n_features_q)
self._qe = [
[(raw[f * QE + i] - 256 if raw[f * QE + i] > 127
else raw[f * QE + i]) * sc[f] for f in range(Dq)]
for i in range(QE)]
return self._qe
def project_qe(self, feats_q):
"""Quality-plane projection -> QE facet scalars (schema 4).
Columns 0/1 are the v3 lexicon pair (verdict/junk) kept for
continuity; the rest are multi-task facet columns.
"""
if self._proj_qe is None:
self._proj_qe = _make_projector(self.qe_plane(), self.qe_dims)
return self._proj_qe(feats_q)
def _mlp_forward(self, x):
"""Schema-4 scorer head: int8-quantized tanh MLP + ridge skip.
h = tanh(W1 @ x + b1);
[verdict_logit, junk_logit] = W2 @ h + b2 + Ws @ x + bs
(the skip is the ridge floor the towers were initialized
from - it keeps the head at v1-floor behavior even if the
hidden path is quantized away).
"""
m = self._mlp
W1, b1, W2, b2 = m["W1"], m["b1"], m["W2"], m["b2"]
if m.get("dead_hidden"):
# skip-only head (W1 and b1 all zero): h = tanh(0) = 0 and
# W2 @ h = 0 EXACTLY, so returning the bias floor is
# bit-identical and saves 2*n_in mults + a tanh per sign
out = list(b2)
else:
h = [math.tanh(sum(xi * wi for xi, wi in zip(x, wr)) + b1r)
for wr, b1r in zip(W1, b1)]
out = [sum(hi * wi for hi, wi in zip(h, wr)) + b2r
for wr, b2r in zip(W2, b2)]
Ws, bs = m.get("Ws"), m.get("bs")
if Ws:
for k, wr in enumerate(Ws):
out[k] += sum(xi * wi for xi, wi in zip(x, wr)) \
+ (bs[k] if bs else 0.0)
return out
def zscore(self, p):
return [(pi - mu) / (sig or 1.0)
for pi, mu, sig in zip(p, self._mu, self._sigma)]
# ---- word ---------------------------------------------------------
def bins_of(self, z):
"""Quantize the dedup dims with learned equal-mass edges."""
bins = []
for k in range(self.dedup_dims):
bins.append(bisect.bisect_right(self._edges[k], z[k]))
return bins
def bucket_of(self, bins):
b = 0
for k, bk in enumerate(bins):
b |= bk << sum(self.bin_bits[:k])
return b
def score4_of(self, q01):
return bisect.bisect_right(self._score_edges, q01)
def sign_text(self, text):
if self.scaled:
feats, fq = features_all(text, self.n_features,
self.n_features_q)
return self._sign_feats_v4(feats, fq, text)
if self.v3:
feats, fq = features_all(text, self.n_features)
return self._sign_feats_v3(feats, fq, text)
feats = features(text, self.n_features)
return self.sign_feats(feats, text=text)
def sign_batch(self, texts, workers=1, chunksize=64):
"""Sign many texts; optional multiprocessing fan-out.
workers=1 (default) is the serial path - identical results.
workers>1 forks stdlib worker processes (each loads the SAME
artifact once) and preserves order; results are identical to
the serial path because signing is a pure function of the
text and the artifact. Use for corpus-scale runs; dedup_stream
exposes the same knob.
"""
texts = list(texts)
if workers <= 1 or len(texts) < 2 * chunksize:
return [self.sign_text(t) for t in texts]
import multiprocessing as _mp
ctx = _mp.get_context("fork")
nproc = max(1, min(workers, ctx.cpu_count() or workers))
with ctx.Pool(processes=nproc, initializer=_worker_init,
initargs=(self.artifact,)) as pool:
return list(pool.imap(_worker_sign, texts, chunksize))
def sign_feats(self, feats, text=None):
if self.v3:
raise ValueError("schema-3 signing needs sign_text(): the "
"lexicon view features_q() is part of the "
"signature")
p = self.project_feats(feats)
if self.v2:
return self._sign_feats_v2(p, text)
return self._sign_feats_v1(p, text)
def _tower_forward(self, x, m, use_hidden=True):
"""Single-output tower: tanh MLP + residual linear skip.
out = W2 . tanh(W1 @ x + b1) + b2 + skip, where the skip rides
under its own key (Wsq/bsq on the quality tower, Wsj/bsj on the
junk tower) and is ridge-initialized (v1-equivalent floor).
When the artifact ships W2 = 0 (residual disabled - the
measured choice) this reduces to the pure skip at zero cost.
"""
if not use_hidden:
if "Wsq" in m:
return _dot(x, m["Wsq"]) + m["bsq"]
return _dot(x, m["Wsj"]) + m["bsj"]
W1, b1 = m["W1"], m["b1"]
h = [math.tanh(_dot(x, wr) + br) for wr, br in zip(W1, b1)]
out = _dot(h, m["W2"]) + m["b2"]
if "Wsq" in m:
out += _dot(x, m["Wsq"]) + m["bsq"]
if "Wsj" in m:
out += _dot(x, m["Wsj"]) + m["bsj"]
return out
def _sign_feats_v2(self, p, text):
nd = self.dedup_dims
z = [(p[k] - mu) / (sig or 1.0)
for k, mu, sig in zip(range(nd), self._mu, self._sigma)]
zq = [(p[nd + k] - mu) / (sig or 1.0)
for k, mu, sig in zip(range(self.qual_dims),
self._zq_mu, self._zq_sigma)]
bins = self.bins_of(z)
bucket = self.bucket_of(bins)
if text is None:
bstd = [0.0] * len(self._bnames) # centered fallback
else:
braw = self._battery_fn(text)
bstd = [(bi - mu) / (sg or 1.0)
for bi, mu, sg in zip(braw, self._bmu, self._bsg)]
zd = [math.tanh(zi) for zi in z]
xq = zq + bstd # quality tower input
xj = zq + zd + bstd # junk tower input (both planes)
oq = self._tower_forward(xq, self.mlp_q, self._q_hidden)
oj = self._tower_forward(xj, self.mlp_j, self._j_hidden)
q01 = max(0.0, min(1.0, oq))
junk = _sigmoid(oj)
# composite packed verdict (word-only triage must rank junk low):
q_pack = q01 - self.pack_lambda * junk
s4 = bisect.bisect_right(self._score_edges, q_pack)
top = (1 << self.score_bits) - 1
s4 = min(max(s4, 0), top)
word = (bucket << self.score_bits) | s4
_nib = (sum(self.bin_bits) + self.score_bits + 3) // 4
return {
"word": word,
"word_hex": ("%0" + str(_nib) + "x") % word,
"bucket": bucket,
"bins": bins,
"z": z,
"zq": zq,
"score4": s4,
"score_level": s4,
"score_bits": self.score_bits,
"q01_raw": q01,
"q_pack": q_pack,
"quality": round(self._score_centroids[s4], 1),
"quality_fine": round(100.0 * q01, 1),
"junk_prob": round(junk, 4),
"is_junk": oj >= self.junk_threshold, # logit space
"word_bits": sum(self.bin_bits) + self.score_bits,
}
def _sign_feats_v4(self, feats, feats_q, text):
"""Schema-4 signing: retrained dedup plane + scaled scorer.
p -> z (6 dims, bins, bucket - same banding machinery as
v2/v3); feats_q -> QE facets (12 dims: lexicon pair + multi-
task columns); the standardized facets + tanh(z) + battery3
feed the trained int8 MLP head; verdict calibrated (isotonic
centroids) and packed to 8 bits, composite q01 - lambda*junk
keeps word-only triage junk-aware.
"""
p = self.project_feats(feats)
z = [(pi - mu) / (sig or 1.0)
for pi, mu, sig in zip(p, self._mu, self._sigma)]
bins = self.bins_of(z)
bucket = self.bucket_of(bins)
pq = self.project_qe(feats_q)
qe_std = [(vi - mu) / (sig or 1.0)
for vi, mu, sig in zip(pq, self._qe_mu, self._qe_sigma)]
if text is None:
bstd = [0.0] * len(self._bnames) # centered fallback
else:
braw = self._battery_fn(text)
bstd = [(bi - mu) / (sg or 1.0)
for bi, mu, sg in zip(braw, self._bmu, self._bsg)]
x = qe_std + ([math.tanh(zi) for zi in z]
if self.mlp_use_z else []) + bstd
oq = self._mlp_forward(x)[0]
jh = self._junk_head
# junk head: the v3-parity ridge over [lexicon pair + battery
# CORE] (kept separate from the MLP - measured more stable on
# held-out eval junk AUC than a joint MLP junk output; v6.6
# artifacts widen the verdict battery but pin the junk head to
# the 26-feature battery3 core, so this stays length-driven
# for every artifact generation)
x_junk = qe_std[:2] + bstd[:max(0, len(jh["w"]) - 2)]
oj = sum(xi * wi for xi, wi in zip(x_junk, jh["w"])) + jh["b"]
q01 = max(0.0, min(1.0, oq))
junk = _sigmoid(oj)
# composite packed verdict (word-only triage must rank junk low):
q_pack = q01 - self.pack_lambda * junk
s4 = bisect.bisect_right(self._score_edges, q_pack)
top = (1 << self.score_bits) - 1
s4 = min(max(s4, 0), top)
word = (bucket << self.score_bits) | s4
_nib = (sum(self.bin_bits) + self.score_bits + 3) // 4
return {
"word": word,
"word_hex": ("%0" + str(_nib) + "x") % word,
"bucket": bucket,
"bins": bins,
"z": z,
"lex": [round(v, 6) for v in qe_std[:2]],
"qe": [round(v, 6) for v in qe_std],
"score4": s4,
"score_level": s4,
"score_bits": self.score_bits,
"q01_raw": q01,
"q_pack": q_pack,
"quality": round(self._score_centroids[s4], 1),
"quality_fine": round(100.0 * q01, 1),
"junk_prob": round(junk, 4),
"is_junk": oj >= self.junk_threshold, # logit space
"word_bits": sum(self.bin_bits) + self.score_bits,
}
def _sign_feats_v3(self, feats, feats_q, text):
"""Schema-3 signing: dedup plane (inherited geometry) + lexicon
scorer plane: p -> z (6 dims, bins, bucket) and feats_q ->
[verdict scalar, junk scalar]; the standardized lexicon pair,
tanh(z) (fixed geometry features the ridge may use or
ignore), and the 26-feature battery3 feed ridge heads (the
tower residual ships zeroed unless a future calibration
enables it).
"""
p = self.project_feats(feats)
z = [(pi - mu) / (sig or 1.0)
for pi, mu, sig in zip(p, self._mu, self._sigma)]
bins = self.bins_of(z)
bucket = self.bucket_of(bins)
pl = self.project_lex(feats_q)
lex = [(pi - mu) / (sig or 1.0)
for pi, mu, sig in zip(pl, self._lex_mu, self._lex_sigma)]
if text is None:
bstd = [0.0] * len(self._bnames) # centered fallback
else:
braw = self._battery_fn(text)
bstd = [(bi - mu) / (sg or 1.0)
for bi, mu, sg in zip(braw, self._bmu, self._bsg)]
x = lex + [math.tanh(zi) for zi in z] + bstd
oq = self._tower_forward(x, self.mlp_q, self._q_hidden)
oj = self._tower_forward(x, self.mlp_j, self._j_hidden)
q01 = max(0.0, min(1.0, oq))
junk = _sigmoid(oj)
# composite packed verdict (word-only triage must rank junk low):
q_pack = q01 - self.pack_lambda * junk
s4 = bisect.bisect_right(self._score_edges, q_pack)
top = (1 << self.score_bits) - 1
s4 = min(max(s4, 0), top)
word = (bucket << self.score_bits) | s4
_nib = (sum(self.bin_bits) + self.score_bits + 3) // 4
return {
"word": word,
"word_hex": ("%0" + str(_nib) + "x") % word,
"bucket": bucket,
"bins": bins,
"z": z,
"lex": [round(v, 6) for v in pl],
"score4": s4,
"score_level": s4,
"score_bits": self.score_bits,
"q01_raw": q01,
"q_pack": q_pack,
"quality": round(self._score_centroids[s4], 1),
"quality_fine": round(100.0 * q01, 1),
"junk_prob": round(junk, 4),
"is_junk": oj >= self.junk_threshold, # logit space
"word_bits": sum(self.bin_bits) + self.score_bits,
}
def _sign_feats_v1(self, p, text):
z = self.zscore(p)
bins = self.bins_of(z)
bucket = self.bucket_of(bins)
if text is None:
bstd = [0.0] * len(self._bnames) # centered fallback
else:
braw = self._battery_fn(text)
bstd = [(bi - mu) / (sg or 1.0)
for bi, mu, sg in zip(braw, self._bmu, self._bsg)]
xq = z + bstd
q01 = _dot(self.h_q["w"], xq) + self.h_q["b"]
q01 = max(0.0, min(1.0, q01))
s4 = self.score4_of(q01)
jlogit = (_dot([math.tanh(zi) for zi in z],
self.h_j["w"][:self.n_proj])
+ _dot(self.h_j["w"][self.n_proj:], bstd)
+ self.h_j["b"])
junk = _sigmoid(jlogit)
word = (bucket << self.score_bits) | s4
_nib = (sum(self.bin_bits) + self.score_bits + 3) // 4
return {
"word": word,
"word_hex": ("%0" + str(_nib) + "x") % word,
"bucket": bucket,
"bins": bins,
"z": z,
"score4": s4,
"score_level": s4,
"score_bits": self.score_bits,
"q01_raw": q01,
"quality": round(self._score_centroids[s4], 1),
"quality_fine": round(100.0 * q01, 1),
"junk_prob": round(junk, 4),
"is_junk": jlogit >= self.junk_threshold, # logit space
"word_bits": sum(self.bin_bits) + self.score_bits,
}
# ---- fuzzy candidate generation -----------------------------------
def probe_radii(self, radius=None):
"""Effective per-dim probe radii for this artifact.
Precedence: explicit scalar `radius` argument > artifact
`fuzzy_radii` (per-dim, trainer-measured asymmetric probe) >
legacy scalar `fuzzy_radius`.
"""
if radius is not None:
return [radius] * self.dedup_dims
if self.fuzzy_radii:
return list(self.fuzzy_radii)
return [self.fuzzy_radius] * self.dedup_dims
def fuzzy_keys(self, bins, radius=None, radii=None):
"""All +-radius bin tuples (probe keys). Exact key included.
`radii` (per-dim list) wins over scalar `radius`; default is
the artifact's shipped probe geometry (probe_radii()).
FULL grid only - masked multi-probe keys ride on probe_keys().
"""
rs = list(radii) if radii else self.probe_radii(radius)
dims = []
for k in range(self.dedup_dims):
lo = max(0, bins[k] - rs[k])
hi = min((1 << self.bin_bits[k]) - 1, bins[k] + rs[k])
dims.append(range(lo, hi + 1))
keys = []
for combo in product(*dims):
keys.append(tuple(combo))
return keys
def _masked_grids(self, bins, rs):
"""Masked multi-probe grids (schema 5).
For each configured mask m, every m-dim subset gets a grid
that drops exactly those dims (sentinel -1) and +-ranges the
remaining dims. A stored row inserts its own masked keys
(insert_keys); a query probes these grids - exact-dict hits
then realize the union semantics '>= D-m dims inside the
+-r grid'.
"""
dd = self.dedup_dims
keys = []
for m in self.probe_masks:
for drop in combinations(range(dd), m):
dims = []
for k in range(dd):
if k in drop:
dims.append((-1,))
else:
lo = max(0, bins[k] - rs[k])
hi = min((1 << self.bin_bits[k]) - 1,
bins[k] + rs[k])
dims.append(range(lo, hi + 1))
for combo in product(*dims):
keys.append(tuple(combo))
return keys
def probe_keys(self, bins, radius=None, radii=None):
"""Candidate-generation keys: full +-r grid + masked grids.
probe_masks absent/empty (schema 1-4 artifacts) -> identical
to fuzzy_keys(); the streaming index inserts each row under
its full key + insert_keys() so masked probes can hit.
"""
rs = list(radii) if radii else self.probe_radii(radius)
keys = self.fuzzy_keys(bins, radii=rs)
if self.probe_masks:
keys.extend(self._masked_grids(bins, rs))
return keys
def insert_keys(self, bins):
"""Keys a row is INDEXED under: full bin tuple + one masked
key per configured mask-dim subset (exact bins, sentinel -1
at the dropped dims)."""
full = tuple(bins)
if not self.probe_masks:
return [full]
dd = self.dedup_dims
keys = [full]
for m in self.probe_masks:
for drop in combinations(range(dd), m):
keys.append(tuple(-1 if k in drop else bins[k]
for k in range(dd)))
return keys
def confirm(self, z_a, z_b, scale=1.0):
"""Post-candidate verification: per-dim |dz| within tau.
scale > 1 loosens the gate for out-of-band rows (short
standalone texts vs the ~1200-char pipeline band the geometry
was calibrated on); the lexical guard owns precision at any
scale, so loosening tau is safe as long as the guard runs.
"""
return all(abs(a - b) <= t * scale
for a, b, t in zip(z_a[:self.dedup_dims],
z_b[:self.dedup_dims],
self.verify_tau))
def with_compact(self):
"""Re-banded compact view of the SAME learned projection.
Uses bin_bits_compact / bin_edges_compact stored by train_v4
(18-bit buckets -> 22-bit word). Same z-space, same tau, same
packed score; only the quantization gets coarser, which raises
exact-bucket hits and keeps the +-1-bin probe cheap. Raises
KeyError on artifacts that predate compact support.
"""
cfg = self.artifact["config"]
if "bin_edges_compact" not in cfg:
raise KeyError("artifact has no compact banding")
import copy as _copy
art2 = _copy.deepcopy(self.artifact)
art2["config"]["bin_bits"] = list(cfg["bin_bits_compact"])
art2["config"]["bin_edges"] = cfg["bin_edges_compact"]
# compact bins are wider (3 bits/dim): the measured asymmetric
# probe belongs to the standard banding - compact stays +-1
art2["config"]["fuzzy_radii"] = [1] * len(art2["config"]["bin_bits"])
return KipHash(obj=art2)
def dedup_stream(self, texts, gate=None, guard=0.25, gray_zone=0.5,
keep="quality", legacy=False, junk_floor=False,
workers=1):
"""Greedy one-pass fuzzy dedup, kip-hash pipeline:
row -> sign -> word
| score4 < gate? -> dropped, never indexed
| junk_floor and is_junk? -> dropped, never indexed
| +-1-bin probe finds candidates?
| |dz| <= tau per dim? -> confirmed
| 5-gram J >= gray_zone? -> MERGE (guard passed)
| guard <= J < gray_zone? -> gray zone: recorded for
| teacher adjudication,
| NOT merged
| J < guard -> guard-rejected
| else -> insert into index
keep="quality" resolves every merge to the cluster survivor
with the highest (score4, quality_fine, length) key; arrival
order breaks ties, so the policy is deterministic and O(1).
All non-gated rows enter the bucket index - including merged
and guard-rejected ones - so a later near-dup can still find
them (pilot16 section 5, by design).
legacy=True reproduces the pre-guard mechanics exactly: first
confirmed candidate
wins (new row dropped), no guard, no gate, no re-ranking.
Returns (kept, dups, report):
kept - survivor indices, ascending
dups - legacy: (dup_of, i) pairs. standard: (winner, loser,
info) with info = {jaccard, score4_winner,
score4_loser, policy}
report- counters incl. candidates, confirmed, guard_rejected,
gray_zone (+ gray_pairs), n_gate_dropped,
policy_violations (0 by construction), score4_hist
"""
n = len(texts)
if legacy:
kept, pairs = [], []
index = {} # exact bin tuple -> [doc idx]
zs = []
parent = {}
def find_l(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for i, text in enumerate(texts):
sig = self.sign_text(text)
zs.append(sig["z"])
parent[i] = i
cands = set()
for key in self.fuzzy_keys(sig["bins"], radius=1):
lst = index.get(key)
if lst:
cands.update(lst[-64:])
dup_of = None
for c in sorted(cands):
if self.confirm(sig["z"], zs[c]):
dup_of = c
break
if dup_of is None:
kept.append(i)
index.setdefault(tuple(sig["bins"]), []).append(i)
else:
ra, rb = find_l(i), find_l(dup_of)
if ra != rb:
parent[ra] = rb
pairs.append((dup_of, i))
clusters = {}
for i in range(len(texts)):
clusters.setdefault(find_l(i), []).append(i)
report = {
"n_in": len(texts),
"n_kept": len(kept),
"n_dup": len(texts) - len(kept),
"n_clusters": len(clusters),
"largest_cluster": max((len(v) for v in clusters.values()),
default=0),
"fuzzy_radius": self.fuzzy_radius,
"fuzzy_radii": list(self.fuzzy_radii)
if self.fuzzy_radii else None,
"word_bits": sum(self.bin_bits) + self.score_bits,
"mode": "legacy",
}
return kept, pairs, report
# ---------------- standard path ------------------------------
# workers>1 parallelizes SIGNING only (pure function of text +
# artifact -> order-preserving, identical results); the merge
# pass itself stays strictly sequential so the greedy policy is
# deterministic no matter the worker count.
sigs = self.sign_batch(texts, workers=workers)
lens = [len(t or "") for t in texts]
# v6 guard refinement (measured): the auto-merge bar moves from
# 0.50 to 0.55 for word-gram rows, and to 0.65 for SHORT rows
# (6..59 whitespace tokens) where 5-gram J is high-variance (a
# 7-token wikidata fact line has ~3 grams; template twins of
# different entities land at J=0.50). Measured on the v6 eval
# pool: all three observed false merges (wikidata commune
# template twins J=0.500, openstax front-matter J=0.512/0.519)
# fall below the new bars; exactly one verified dup (J=0.523)
# shifts from auto-merge to the gray/adjudication lane instead
# (recorded, not lost). CJK char-gram rows (< 6 tokens) are
# exempt: char grams have their own calibration. Full sweep in
# the v6 trainer; documented in the model card.
#
# v6.2 measured refinement (adjudicated-pool separation): the
# short tier SPLITS at 12 tokens. On the v6.2 pool, 6..11-token
# rows (wikidata fact lines) carry so few 5-grams that template
# twins of DIFFERENT entities reach J=0.667 ("X -- kommun i
# Telemark fylke i Norge") while true dups in the same band
# start at J=0.714 -> bar 0.65 -> 0.70 separates with margin
# both ways and zero recall cost (no verified dup sits in
# 0.65..0.70). 12..59-token rows move 0.65 -> 0.72 in the v6.3
# artifact (config bar_mid_tier): a teacher-verified NOT-dup at
# J=0.716 surfaced in the bigger pool (two OpenStax front-matter
# slices, ~70% shared publisher chrome) that the old plane never
# confirmed; measured cost 2 of 27 eval dups in the tier.
ntok = [len((t or "").split()) for t in texts]
cfg_guard = (self.artifact.get("config") or {}).get("guard") or {}
def _guard_bar(i, c):
# v6.3: the tier bars are artifact-config-driven with the
# v6.2 values as defaults, so older artifacts load with
# byte-identical merge behavior (the v6.3 artifact ships
# bar_mid_tier 0.72 - a teacher-verified NOT-dup at J=0.716
# surfaced in the bigger pool).
gb = (cfg_guard or {})
if 6 <= ntok[i] < 12 or 6 <= ntok[c] < 12:
return float(gb.get("bar_tiny_tier", 0.70))
if 6 <= ntok[i] < 60 or 6 <= ntok[c] < 60:
return float(gb.get("bar_mid_tier", 0.65))
return max(gray_zone,
float(gb.get("bar_long", 0.55)))
# v6.2 slot-variant deferral (measured, adjudicated-pool rule):
# near-identical long-row pairs whose ONLY differences are 2-4
# CONTENT slot tokens (e.g. "Weekly Digest #110 ... crypto
# course" vs "Weekly Digest #71 ... essay writing", eq_ratio
# 0.949, 3 content changes in 2 blocks, zero structural edits)
# are TEMPLATE INSTANTIATIONS with different slot values -
# distinct documents (teacher verdict on the measured pair:
# not-dup @99 conf) no matter how high the 5-gram J climbs
# (0.746 here). Case-only and punctuation-only replacements do
# NOT count as content (the v6.1 doctrine: formatting variants
# must not fail the guard), and single-content-change pairs
# merge (same doc, one word fixed). Measured cost on the v6.2
# eval positives: 3 of 82 high-J pairs defer to the gray lane
# (campaign xdup junk-template rows with contradictory teacher
# verdicts - recorded, adjudicatable). Runs only on pairs that
# already cleared cand+conf+j5 >= bar, so the difflib cost is
# negligible. autojunk=False: the verdict must be a pure
# function of the token sequences.
import difflib as _difflib
def _alnum(t):
return "".join(ch for ch in t if ch.isalnum())
def _slot_variant(i, c):
ta = (texts[i] or "").split()
tb = (texts[c] or "").split()
sm = _difflib.SequenceMatcher(None, ta, tb, autojunk=False)
if sm.ratio() < 0.92:
return False
rep = dele = blocks = cc = 0
for t, i1, i2, j1, j2 in sm.get_opcodes():
if t == "replace":
blocks += 1
for k in range(min(i2 - i1, j2 - j1)):
x, y = ta[i1 + k], tb[j1 + k]
sx, sy = _alnum(x), _alnum(y)
if x != y and x.lower() != y.lower() \
and sx != sy and (sx or sy):
cc += 1
rep += max(i2 - i1, j2 - j1)
elif t in ("delete", "insert"):
dele += max(i2 - i1, j2 - j1)
return (cc >= 2 and rep <= 4 and blocks <= 3 and dele == 0)
# v6.4 measured refinement (config-gated "slot_shell", absent =
# byte-faithful legacy behavior): the TEMPLATE-DOMINANCE zone.
# The round-4 bar-zone tranche surfaced a teacher-verified
# NOT-dup at J=0.723 that NO existing rule deferred: two csb
# month-name stubs (74/77 tokens, same publisher template "X is
# the Nth month of the year in the Gregorian calendar" + shared
# table), diffs concentrated in 4 replace blocks (ratio 0.914,
# rep 8, cc 5) - BELOW the slot-variant ratio gate (0.92), so
# the pair merged at the long bar and tripped the invariant.
# The class: long rows whose diffs concentrate in a few blocks
# = same template, different entity (csb months; the w50 build
# veto's different-emperor stubs are the same shape). Word
# statistics cannot separate this from a same-doc update at
# J 0.70+, so the guard DEFERS instead of guessing. Measured
# cost on the labeled pool: 2 of 159 long-row verified dups at
# J >= 0.70 defer (1.3%, recoverable via the adjudication lane;
# one is a teacher-contradicted slop twin).
def _shell_zone(i, c, j):
sh = (cfg_guard or {}).get("slot_shell")
if not sh:
return False
if j < float(sh.get("j_min", 0.70)):
return False
if ntok[i] < 60 and ntok[c] < 60:
return False # the rule is long-rows-only
ta = (texts[i] or "").split()
tb = (texts[c] or "").split()
sm = _difflib.SequenceMatcher(None, ta, tb, autojunk=False)
if sm.ratio() < float(sh.get("ratio", 0.90)):
return False
rep = dele = blocks = cc = 0
for t, i1, i2, j1, j2 in sm.get_opcodes():
if t == "replace":
blocks += 1
for k in range(min(i2 - i1, j2 - j1)):
x, y = ta[i1 + k], tb[j1 + k]
sx, sy = _alnum(x), _alnum(y)
if x != y and x.lower() != y.lower() \
and sx != sy and (sx or sy):
cc += 1
rep += max(i2 - i1, j2 - j1)
elif t in ("delete", "insert"):
dele += max(i2 - i1, j2 - j1)
return (cc >= int(sh.get("cc", 2))
and rep <= int(sh.get("rep", 10))
and blocks <= int(sh.get("blocks", 4)))
# guard fast path: the 5-gram Jaccard is a pure function of the
# row pair, but dense corpora (template families) scan the same
# rows against thousands of candidates. Building each row's
# gram set ONCE per call and intersecting at C speed is
# value-identical: the per-row cardinality check asserts the
# 64-bit gram hashes collide no more than the strings already
# do (mismatch -> exact string-set fallback for that row).
grams_cache = {}
def _row_grams(j):
g = grams_cache.get(j)
if g is None:
gs = ngrams5(texts[j])
n = len(gs)
hs = frozenset(
int.from_bytes(hashlib.blake2b(
s.encode("utf-8"), digest_size=8,
person=b"kipj5").digest(), "big")
for s in gs)
g = (n, hs if len(hs) == n else None)
if len(grams_cache) >= 30000:
grams_cache.clear()
grams_cache[j] = g
return g
def _guard_j(i, c):
na, ha = _row_grams(i)
nb, hb = _row_grams(c)
if ha is not None and hb is not None:
inter = len(ha & hb)
else: # in-row hash collision: exact path
ga = ngrams5(texts[i])
gb = ngrams5(texts[c])
inter = len(ga & gb)
na, nb = len(ga), len(gb)
if not inter:
return 0.0
return inter / (na + nb - inter)
kept, pairs, gray = [], [], []
index = {}
gate_dropped = n_cand = n_conf = guard_rej = junk_dropped = 0
policy_violations = 0
score4_hist = {}
parent = {}
best = {} # cluster root -> best row idx under pkey
pkey = [(sigs[i]["score4"], sigs[i]["quality_fine"], lens[i], -i)
for i in range(n)]
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for i in range(n):
sig = sigs[i]
score4_hist[sig["score4"]] = \
score4_hist.get(sig["score4"], 0) + 1
if gate is not None and sig["score4"] < gate:
gate_dropped += 1
continue
if junk_floor and sig["is_junk"]:
junk_dropped += 1
continue
parent[i] = i
best[i] = i
cands = set()
for key in self.probe_keys(sig["bins"]):
lst = index.get(key)
if lst:
cands.update(lst[-64:])
n_cand += len(cands)
merged = None
for c in sorted(cands):
if not self.confirm(sig["z"], sigs[c]["z"]):
continue
n_conf += 1
j = _guard_j(i, c)
if j < guard:
guard_rej += 1
continue
if j < _guard_bar(i, c):
gray.append((c, i, round(j, 3)))
continue
if _slot_variant(i, c):
# template slot-variant: distinct documents, defer
gray.append((c, i, round(j, 3)))
continue
if _shell_zone(i, c, j):
# v6.4 template-dominance zone: same publisher
# template, different entity - defer, never guess
gray.append((c, i, round(j, 3)))
continue
merged = (c, j)
break
# every non-gated row enters the index (merged and
# guard-rejected too, so later near-dups can find them);
# schema-5 masked probing indexes the row under its full
# key AND its masked keys so wide probes can hit
for key in self.insert_keys(sig["bins"]):
index.setdefault(key, []).append(i)
if merged is None:
continue
c, j = merged
ra, rb = find(i), find(c)
assert ra != rb, "fresh row cannot share a cluster yet"
wa, wb = best[ra], best[rb]
win, lose = (wa, wb) if pkey[wa] >= pkey[wb] else (wb, wa)
if pkey[win] < pkey[lose]:
policy_violations += 1 # unreachable; guards regressions
parent[ra] = rb
best[rb] = win
pairs.append((win, lose, {
"jaccard": round(j, 3),
"score4_winner": sigs[win]["score4"],
"score4_loser": sigs[lose]["score4"],
"policy": "higher-score4",
}))
roots = {}
for i in parent:
roots.setdefault(find(i), []).append(i)
kept = sorted(best[r] for r in roots)
report = {
"n_in": n,
"n_gate_dropped": gate_dropped,
"n_kept": len(kept),
"n_dup": len(pairs),
"n_clusters": len(roots),
"largest_cluster": max((len(v) for v in roots.values()),
default=0),
"candidates": n_cand,
"confirmed": n_conf,
"guard_rejected": guard_rej,
"gray_zone": len(gray),
"gray_pairs": gray,
"policy_violations": policy_violations,
"gate": gate,
"junk_floor": junk_floor,
"n_junk_dropped": junk_dropped,
"guard": guard,
"gray_zone_band": gray_zone,
"fuzzy_radius": self.fuzzy_radius,
"fuzzy_radii": list(self.fuzzy_radii)
if self.fuzzy_radii else None,
"word_bits": sum(self.bin_bits) + self.score_bits,
"mode": "guard+policy",
"score4_hist": score4_hist,
}
return kept, pairs, report
def load_default(path):
return KipHash(path)
# ---------------------------------------------------------------------
def _load_artifact_path():
import glob
import os
here = os.path.dirname(os.path.abspath(__file__))
for name in ("kip-hash.json",):
p = os.path.join(here, name)
if os.path.exists(p):
return p
local = [p for p in sorted(glob.glob(os.path.join(here, "*.json")))]
if local:
return local[0]
up = os.path.join(os.path.dirname(here), "kip-hash",
"kip-hash.json")
if os.path.exists(up):
return up
raise FileNotFoundError("no kip-hash artifact found")
def _selftest_and_demo():
vh = KipHash(_load_artifact_path())
print("artifact:", vh.artifact.get("name"))
# dedup assertions use PIPELINE-SCALE rows (~1200 chars): the bins,
# tau and banding were calibrated on rows of this length (v2 noted
# the same corpus-scale caveat; short texts have looser geometry).
_mito_a = ("The Mitochondria is the powerhouse of the cell. It produces "
"ATP through cellular respiration, storing energy the cell "
"needs. Mitochondria have their own DNA, separate from the "
"nucleus, and are inherited maternally in most species. "
"The inner membrane folds into cristae, which host the "
"electron transport chain and ATP synthase complexes. "
"Cells with high energy demand contain far more "
"mitochondria than resting cells, and muscle tissue is "
"particularly rich in these organelles. "
"During apoptosis the outer membrane releases "
"cytochrome c, triggering the caspase cascade that dismantles "
"the cell in a controlled manner. "
"Mitochondrial ribosomes resemble bacterial ribosomes, "
"supporting the endosymbiotic theory of their origin. "
"Calcium storage inside the matrix buffers cytosolic "
"calcium levels and shapes signaling pathways.")
_mito_b = ("The Mitochondria is the powerhouse of the cell. It makes ATP "
"through cellular respiration, storing energy the cell needs. "
"Mitochondria have their own DNA, separate from the nucleus, "
"and are inherited maternally in most organisms. "
"The inner membrane folds into cristae, where the electron "
"transport chain and ATP synthase complexes are hosted. "
"Cells with high energy requirements contain far more "
"mitochondria than resting cells, and muscle tissue is "
"especially rich in these organelles. "
"During apoptosis the outer membrane releases "
"cytochrome c, starting the caspase cascade that dismantles "
"the cell in a controlled way. "
"Mitochondrial ribosomes resemble bacterial ribosomes, "
"which supports the endosymbiotic theory of their origin. "
"Calcium storage inside the matrix buffers cytosolic "
"calcium levels and shapes signaling routes.")
near_a = _mito_a
near_b = _mito_b
other = ("The 1998 FIFA World Cup final was played at the Stade de "
"France in Saint-Denis. France beat Brazil 3-0, with Zidane "
"scoring twice from headers. It was France's first world "
"title in football history. The tournament featured 32 teams "
"and 64 matches across ten French cities over four weeks. "
"Croatia, powered by Davor Suker's six goals, reached the "
"semi-finals in their first World Cup appearance. "
"Ronaldo, the Brazilian striker, won the Golden Ball despite "
"his subdued performance in the final match itself. "
"The final drew an estimated 1.7 billion television viewers "
"worldwide, a record audience for a single sporting event "
"at that time.")
same_topic = ("The 2002 FIFA World Cup was hosted jointly by South "
"Korea and Japan. Brazil won the tournament, beating "
"Germany 2-0 in the final held in Yokohama. Ronaldo "
"scored both goals in that final match. South Korea "
"surprised everyone by reaching the semi-finals, "
"eliminating Italy and Spain along the way. "
"Turkey finished in third place after defeating the "
"co-hosts in the bronze medal match in Daegu. "
"The golden goal rule decided several knockout matches, "
"including South Korea's upset victory over Italy. "
"It was the first World Cup held in Asia and the first "
"with joint hosting by two nations.")
boiler = ("Home Search Categories Contact us Login Register Privacy "
"policy Terms of use Cookie settings Careers Press room "
"Newsletter Subscribe Unsubscribe Follow us Share this page "
"Back to top Site map Accessibility statement Copyright "
"notice All prices exclude VAT Returns policy Shipping info "
"FAQ Support center Contact form Live chatopening hours "
"Opening hours Mon-Fri 9am-5pm Delivery tracking Order "
"status Gift cards Store locator Find a store Careers "
"Investor relations Media kit Brand guidelines")
sigs = [vh.sign_text(t) for t in
(near_a, near_b, other, same_topic, boiler)]
print("== kip-hash demo ==")
print("word_bits:", sigs[0]["word_bits"])
print("near-dup buckets:", sigs[0]["bucket"], "vs", sigs[1]["bucket"],
"bins", sigs[0]["bins"], sigs[1]["bins"])
print("diff-topic buckets:", sigs[0]["bucket"], "vs", sigs[2]["bucket"])
print("same-topic buckets:", sigs[0]["bucket"], "vs", sigs[3]["bucket"])
print("near-dup confirm:", vh.confirm(sigs[0]["z"], sigs[1]["z"]))
print("diff-topic confirm:", vh.confirm(sigs[0]["z"], sigs[2]["z"]))
print("score4 levels:", [s["score4"] for s in sigs])
print("decoded quality:", [s["quality"] for s in sigs])
print("junk probs:", [s["junk_prob"] for s in sigs])
fz0 = set(vh.fuzzy_keys(sigs[0]["bins"]))
# per-dim radii geometry: interior bins with shipped radii R give
# prod(2*R_k + 1) keys; scalar override must reproduce the legacy
# 3^6 = 729 grid
assert len(vh.fuzzy_keys(sigs[0]["bins"], radius=1)) <= 729, \
"scalar radius=1 must cap the legacy 3^6 probe grid"
_rad = vh.probe_radii()
_expect = 1
for _k, (_bk, _rk) in enumerate(zip(sigs[0]["bins"], _rad)):
_lo = max(0, _bk - _rk)
_hi = min((1 << vh.bin_bits[_k]) - 1, _bk + _rk)
_expect *= (_hi - _lo + 1)
assert len(fz0) == _expect, \
"per-dim probe grid must match the clamped prod(2*r_k+1) count"
# engine CONTRACTS (artifact-independent):
# precision: unrelated / same-topic-different-text never merge
# recall: guaranteed only for near-exact rows within the
# deployed probe radius; paraphrase recall beyond that
# is a measured quantity (eval/report.json, tau sweep
# 0.8153 confirmed at the shipped operating point), not
# a per-artifact selftest assertion
near_cand = (sigs[0]["bucket"] == sigs[1]["bucket"]
or tuple(sigs[1]["bins"]) in fz0)
near_confirm = vh.confirm(sigs[0]["z"], sigs[1]["z"]) \
or vh.confirm(sigs[0]["z"], sigs[1]["z"], scale=2.0)
if near_cand and near_confirm:
print("planted paraphrase: candidate + confirmed at deployed tau")
elif near_cand:
assert near_confirm, \
"candidate pair must confirm at deployed tau or 2x tau"
print("planted paraphrase: candidate, confirms at 2x tau")
else:
print("NOTE: planted paraphrase sits outside the deployed "
"+-1-bin probe on this artifact (bins differ by 2 in "
"dim %d); paraphrase recall is measured in "
"eval/report.json, not asserted here"
% max(range(6),
key=lambda k: abs(sigs[0]["bins"][k]
- sigs[1]["bins"][k])))
assert not (sigs[0]["bucket"] == sigs[2]["bucket"] and
vh.confirm(sigs[0]["z"], sigs[2]["z"])), \
"different-topic row must not merge"
assert not (sigs[0]["bucket"] == sigs[3]["bucket"] and
vh.confirm(sigs[0]["z"], sigs[3]["z"])), \
"same-topic-different-text row must not merge"
if sigs[0]["score4"] > sigs[4]["score4"]:
print("packed score ordering: encyclopedic > boilerplate OK")
else:
print("NOTE: this artifact's head inverts the demo pair "
"(encyclopedic %.0f vs boilerplate %.0f on ~1k-char demo "
"texts) - engine mechanics unaffected; real-corpus verdict "
"lives in eval/report.json (gate sweep)"
% (sigs[0]["quality"], sigs[4]["quality"]))
assert vh.sign_text(near_a)["word"] == sigs[0]["word"], \
"signing must be deterministic"
texts5 = [near_a, near_b, other, same_topic, boiler]
kept, dups, rep = vh.dedup_stream(texts5)
print("dedup_stream report:", rep)
# engine contract on dedup_stream: an EXACT duplicate must merge
# (asserted below with texts6); the planted paraphrase merges or is
# routed to gray zone WHEN it is a candidate - when it sits outside
# the probe radius the report stays honest (no merge, no false claim)
if near_cand:
pair_caught = (rep["n_dup"] >= 1
or any({0, 1} <= {a, b}
for a, b, _ in rep["gray_pairs"]))
assert pair_caught, \
"candidate paraphrase pair must merge or reach the gray zone"
# ---- guard / policy / gate checks --------------------------------
# guard: true paraphrase clears 0.25; unrelated texts stay far below
j_true = jaccard5(near_a, near_b)
j_topic = jaccard5(other, same_topic)
j_boil = jaccard5(boiler, other)
print("jaccard5 true/topic/boiler:", round(j_true, 3), round(j_topic, 3),
round(j_boil, 3))
assert j_true >= 0.25, "true paraphrase must pass the lexical guard"
assert j_topic < 0.10 and j_boil < 0.10, \
"same-topic / boilerplate pairs must stay in guard-reject territory"
# policy: survivor of every merge is never worse than the loser
# (an exact duplicate of row 0 guarantees a merge at J = 1.0)
texts6 = texts5 + [near_a]
kept6, dups6, rep6 = vh.dedup_stream(texts6)
assert rep6["n_dup"] >= 1, "exact duplicate must merge"
assert rep6["policy_violations"] == 0, "collision policy must hold"
win, lose, info = dups6[0]
s4w = vh.sign_text(texts6[win])["score4"]
s4l = vh.sign_text(texts6[lose])["score4"]
assert s4w >= s4l, "survivor must carry the higher packed score"
assert info["jaccard"] >= 0.5, "exact duplicate must clear the gray zone"
# accounting identity: merges = non-gated - survivors
assert rep6["n_dup"] == (rep6["n_in"] - rep6["n_gate_dropped"]
- rep6["n_kept"]), "cluster accounting"
# gate: read straight off the word, no text re-read (scale-aware:
# the top packed level is 15 on schema 1, 255 on schema 2)
top_lv = (1 << vh.score_bits) - 1
s4s6 = [vh.sign_text(t)["score4"] for t in texts6]
keptg, dupsg, repg = vh.dedup_stream(texts6, gate=top_lv)
n_pass = sum(1 for v in s4s6 if v == top_lv)
assert repg["n_gate_dropped"] == sum(1 for v in s4s6 if v < top_lv)
assert repg["n_dup"] == n_pass - repg["n_kept"], \
"gate-passing rows must conserve: dup = passing - kept"
# legacy path still reproduces pre-guard mechanics (its recall on
# the demo pair depends on the artifact's tau tightness - covered
# above)
keptL, dupsL, repL = vh.dedup_stream(texts5, legacy=True)
assert repL["mode"] == "legacy", "legacy mode flag"
assert repL["n_clusters"] == len(set(keptL)) or repL["n_dup"] >= 1
if repL["n_dup"] >= 1:
print("legacy path catches the demo pair too")
else:
print("NOTE: legacy path misses the demo pair on this "
"artifact's deployed tau (ultra-tight); the standard "
"path catches it via the scale knob + guard")
# compact mode when the artifact carries the compact banding
try:
vhc = vh.with_compact()
sc = vhc.sign_text(near_a)
assert sc["word_bits"] == sum(vhc.bin_bits) + vhc.score_bits
assert vhc.sign_text(near_a)["word"] == sc["word"], \
"compact signing must be deterministic"
print("compact mode ok:", vhc.bin_bits,
"word_bits", sc["word_bits"])
except KeyError:
print("compact mode: banding not stored in this artifact "
"(the trainer stores it)")
# ---- schema-5 masked multi-probe (config-gated, off for 1-4) -----
import copy as _copy5
art5 = _copy5.deepcopy(vh.artifact)
art5["schema"] = "kip.hash.5"
art5["config"]["probe_masks"] = [1]
vh5 = KipHash(obj=art5)
assert vh5.probe_masks == [1], "mask config must load"
assert vh.sign_text(near_a)["word"] == vh5.sign_text(near_a)["word"], \
"masks change candidate generation, never the signed word"
rs5 = vh5.probe_radii()
_base = len(vh5.fuzzy_keys(sigs[0]["bins"]))
_masked = len(vh5._masked_grids(sigs[0]["bins"], rs5))
assert _masked > 0, "masked grids generated"
_expect_m = 0
for _k in range(vh5.dedup_dims):
_g = 1
for _j in range(vh5.dedup_dims):
if _j == _k:
continue
_lo = max(0, sigs[0]["bins"][_j] - rs5[_j])
_hi = min((1 << vh5.bin_bits[_j]) - 1,
sigs[0]["bins"][_j] + rs5[_j])
_g *= (_hi - _lo + 1)
_expect_m += _g
assert _masked == _expect_m, \
"mask-1 grids must add prod(2r+1) keys per dropped dim"
assert len(vh5.probe_keys(sigs[0]["bins"])) == _base + _expect_m, \
"probe_keys = full grid + masked grids"
_ik = vh5.insert_keys(sigs[0]["bins"])
assert len(_ik) == 1 + vh5.dedup_dims, "insert keys = full + 6 masks"
assert _ik[0] == tuple(sigs[0]["bins"]), "first insert key is exact"
assert all(k.count(-1) == 1 for k in _ik[1:]), \
"each masked insert key drops exactly one dim"
kept5, dups5, rep5 = vh5.dedup_stream(texts6)
assert rep5["policy_violations"] == 0, "mask probe keeps the policy"
assert rep5["n_dup"] >= rep6["n_dup"], \
"masked probing must not lose merges vs the classic grid"
assert vh5.dedup_stream(texts5, legacy=True)[2]["mode"] == "legacy"
print("masked multi-probe ok: probe", _base, "+", _expect_m,
"keys, insert", len(_ik), "keys/row, dedup consistent")
print("selftest assertions passed (kip-hash engine)")
print("note: dedup geometry is calibrated on ~1200-char pipeline "
"rows; shorter standalone texts need a looser tau (the "
"documented corpus-scale caveat).")
if __name__ == "__main__":
_selftest_and_demo()
"""kip-hash — the nano verify-and-dedup word (schema 5, scaled).
One 32-bit word per row, two jobs, pure-stdlib inference:
word = (bucket << 8) | level # 24 learned bucket bits + 8 score bits
1. DEDUP PLANE (fuzzy by design, inherited from schema 2): the 24
bucket bits are six learned scalar projections z_k of a hashed
feature view (word uni/bi-grams + char 4-grams, log-tf, L2), each
quantized with equal-mass bin edges learned from the training
corpus. Near-duplicates differ by less than a bin width, so
quantization ABSORBS the perturbation instead of betting bit-by-bit
(SimHash) or shingle-by-shingle (MinHash): dups collide, and +-bin
probing recovers pairs that straddle an edge. Schema 5 adds MASKED
MULTI-PROBE candidate generation (config probe_masks): each masked
grid drops dims (sentinel -1) so a pair becomes a candidate when
ANY DEDUP_DIMS-m of its dims sit inside the +-r grid - the shipped
masks [1, 2] lift confirmed recall 0.9376 -> 0.9769 at zero
post-guard false merges (measured, eval/report.json). Candidate
over-generation is still repaired by the cheap per-dimension |dz|
confirmation - no text re-read at signing time.
2. VERIFY PLANE (schema 4/5: scaled SCORER - the novel half). v3 gave
the score its own feature space (hashed word uni/bi-gram LEXICON,
2 ridge scalars) and still capped at junk AUC ~0.68 / Spearman
~0.20: two scalars cannot carry "what the text is about". Schema
4 scaled the plane to a 12-dim MULTI-TASK quality projection (the
first two columns are the v3 lexicon recipe kept for continuity;
ten more ridge columns distill knowledge, junk and nine content
facets of the same salted uni/bi-gram view), then a trained int8
MLP head (hidden tanh) with a pairwise ranking term recombines
[facets + tanh(z) + 26-feature battery3] nonlinearly. Schema 5
scales the plane further (24 columns: more surface facets +
teacher-quantile columns) and widens the head grid; fold-driven
config selection; isotonic-calibrated verdict packed to 8 bits.
Goal set by the 2026-11 directive: word-only triage good enough
to rival a neural verifier's judgment, not just beat MinHash.
Schemas 1/2/3/4 remain loadable: KipHash dispatches per artifact
(v1: shared 10-dim projection + linear heads, 16 levels; v2: two-plane
14-dim projection + tanh towers; v3: dedup plane + 2-scalar lexicon
ridge; v4: first scaled scorer + retrained dedup plane). The v4 -> v5
update (2026-11) RETRAINS the dedup plane on ~2.5x scaled
construction-known-truth supervision with four new perturbation
families (unicode, whitespace, insertion, casing), adds the masked
multi-probe geometry above, and scales the scorer plane to 24
columns; dedup SEMANTICS (binning, +-bin probing, guard, collision
policy) are unchanged - only the learned W, the probe keys and the
scorer head are new. Old artifacts load and sign byte-identically
(regression-tested against the released v4 engine).
Engine features (all measured, docs/kip_hash_pilot16_discussion.md):
* LEXICAL GUARD - 5-gram Jaccard >= 0.25 on confirmed candidates
before a merge is finalized; gray zone
(0.25 <= J < 0.5) is recorded for teacher
adjudication instead of merged. Costs
~nothing: candidates are rare (~0.1-4%).
* COLLISION POLICY - "on collision keep the higher-quality row":
the cluster survivor is picked by
(score, quality_fine, length, -arrival).
The packed level makes this O(1).
* QUALITY GATE - rows below a score level are dropped before
they ever enter the bucket index (read
straight off the stored word).
* COMPACT MODE - with_compact() re-bands the SAME learned
projection to the stored 18-bit-bucket geometry
(22-bit word) for <= 1M-row corpora.
* GRAM MEMO - gram->bucket hashes are memoized (bounded,
value-identical: same blake2b result, cached).
Repeat traffic - function words, common
bigrams - skips hashing entirely; measured
in eval/report.json throughput.
* FUSED SIGNING - one-pass surface battery, plain-loop CJK
test, per-dim unrolled projections (codegen
at load) - byte-identical outputs, ~1.6x the
v3 single-core signing rate.
* PARALLEL SIGNING - sign_batch(texts, workers=k) fans signing
out over k processes (stdlib multiprocessing,
order-preserving, results identical to the
serial path) for corpus-scale runs.
legacy=True on dedup_stream reproduces the pre-guard mechanics exactly
(first candidate wins, no guard, no gate, no re-ranking) for
comparability.
Teachers (distillation roster): DeepSeek-V4.1-Flash-1017 via the
DeepSeek webapp (channel 1, human-rhythm multi-turn batches),
kimi-k3.1-pro via NVIDIA NIM (channel 2, bulk), MiniMax M3.1 Flash
via NVIDIA NIM (designated fallback). Batched structured annotation;
see scripts/label_run_v4.py and scripts/label_run_nim.py.
Usage:
from kip_hash import KipHash
vh = KipHash("kip-hash.json")
w = vh.sign_text("...row text...")
w["word"] # 32-bit int: 24 bucket bits | 8 score bits
w["score4"] # packed quality level: 0-255 (v2/v3/v4) / 0-15 (v1)
w["quality"] # isotonic-decoded 0-100 verdict for that level
w["quality_fine"] # fine verdict before level packing
w["junk_prob"] # hash-side junk/boilerplate flag