← Leaderboard
compass-v1-shrink v1
compass v1, short pages' scores trusted less
Like compass v1 (keeps pages most like each of the exam's six kinds by token-pair statistics of public Common Pile files, after tidy's cleanup; half the budget, twice), but a short page's score is pulled toward zero.
- Rank
- 17of 39 on the leaderboard
- Rating
- +1.182its gain a round, on average (±0.007)
- Worth
- >8×its pages taught the model as much as >8× as many raw pages
Round by round
3 rounds
Where it came in each round, and its gain.
Inside its latest round round 15
- pages kept
- 7%of the documents drawn
- read
- 1.8×over what it kept
- its own words
- 0%of tokens not copied
- exam loss
- 4.253against 5.572 unedited
Where the gain comes from
Exam loss by kind of text. Hollow: unedited. Filled: this curator. Left is better.
The model, learning from it
Training loss on its pages. Low here is not the goal; the exam is.
Its code 7 files · 4.8 MB
Public from its first round. Start from it:
- build/build_table.py1.2 kB
- build/fetch_targets.py4.6 kB
- curator.py13.6 kB
- features.py2.2 kB
- knobs.json16 B
- stet.toml363 B
- table.npz4.8 MB
"""compass: pick the web pages that read like the six kinds of writing the exam covers.
1. Clean up as tidy does: English prose only, exact duplicates dropped, navigation and
boilerplate lines cut out of each page. That script is written at once, so a run
that is cut short still has it.
2. Read every page that is left with the student's own tokenizer, and compare its token
pairs with those of each kind of writing (table.npz: counts from public Common Pile
collections, none of them a file either exam is cut from) and with this round's own
pages. A page scores high for a kind of writing when it is made of what that kind is
made of and the rest of the round is not.
3. Fill half the budget from the six kinds in turn, each taking the pages that score
highest for it, so that no kind of writing goes short. The student reads that half
twice: the best pages seen twice teach it more than twice as many pages seen once.
No model, no GPU, about a minute at micro. Everything kept is a cut of at least
min_copy_bytes, so it spends no ink. How table.npz was made, from which files, is in
build/: rebuild it with build/fetch_targets.py and build/build_table.py.
"""
from __future__ import annotations
import hashlib
import json
import os
import random
import re
import sys
import time
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from features import BUCKETS, encoder, features_many, normalize # noqa: E402
from stet.curator import Task # noqa: E402
SENTENCE_END = re.compile(r"[.!?][\"')\]]?\s")
STOPWORDS = (" the ", " of ", " and ", " to ", " in ", " is ", " that ", " for ")
BYTES_PER_TOKEN = 3.7
# Knobs. knobs.json beside this file sets them for an experiment (a curator is not handed
# its starter's environment); otherwise these defaults.
_KNOBS = json.loads((HERE / "knobs.json").read_text()) if (HERE / "knobs.json").exists() else {}
def knob(name, default):
return type(default)(_KNOBS.get(name, os.environ.get("COMPASS_" + name.upper(), default)))
SHARES = [float(x) for x in str(knob("shares", "1,1,1,1,1,1")).split(",")]
FILL = knob("fill", 0.5) # budgets' worth of distinct text to keep
ALPHA = knob("alpha", 1.0) # smoothing of feature counts
CLIP = knob("clip", 0.0) # 0: no clipping of feature weights
ORDER = knob("order", "shuffle") # shuffle | anneal | anneal2
SCORE_TOKENS = knob("score_tokens", 4096)
MODE = knob("mode", "balanced") # balanced | tidy | best
SCORER = knob("scorer", "dsir") # dsir | clf | both
RESHUFFLE = knob("reshuffle", False) # repeats in fresh orders
REPEATS = [float(x) for x in str(knob("repeats", "")).split(",") if x] # per kind; overrides fill
SHRINK = knob("shrink", 0.0) # features' worth of prior on each page's score
HOST_CAP = knob("host_cap", 0) # most pages kept from one website; 0 for no limit
LINES = knob("lines", "tidy") # tidy | loose: which lines of a page count as prose
def log(*a):
print(f"[{time.strftime('%H:%M:%S')}]", *a, file=sys.stderr, flush=True)
def looks_english(text: str) -> bool:
sample = text[:3000]
if len(sample) < 200:
return False
letters = sum(c.isascii() and (c.isalpha() or c == " ") for c in sample)
if letters / len(sample) < 0.75:
return False
low = sample.lower()
return sum(low.count(w) for w in STOPWORDS) >= max(4, len(sample) // 300)
def is_prose(body: str) -> bool:
words = body.count(" ") + 1
if LINES == "loose": # shorter sentences too (dialogue, answers), and long unpunctuated paragraphs
return (len(body) >= 25 and words >= 5 and SENTENCE_END.search(body + " ") is not None) or (len(body) >= 200 and words >= 30)
return len(body) >= 60 and words >= 10 and SENTENCE_END.search(body + " ") is not None
def prose_ranges(text: str, min_copy: int = 64) -> tuple[list[list[int]], int]:
"""Byte ranges of the lines worth keeping, and how many bytes they hold."""
ranges: list[list[int]] = []
pos = 0
for line in text.split("\n"):
n = len(line.encode("utf-8")) + 1
body = line.strip()
if is_prose(body):
if ranges and ranges[-1][1] == pos:
ranges[-1][1] = pos + n
else:
ranges.append([pos, pos + n])
pos += n
ranges = [r for r in ranges if r[1] - r[0] >= min_copy + 4]
return ranges, sum(b - a for a, b in ranges)
def tidy_score(text: str, kept: int) -> float:
total = max(1, len(text.encode("utf-8")))
density = kept / total
length = min(1.0, kept / 3000)
low = text[:4000].lower()
explains = sum(low.count(w) for w in (" because ", " therefore ", " however ", " for example ", " which ", " whereas "))
sells = sum(low.count(w) for w in (" buy ", " price", " shipping", " cart", " sale", " click ", " subscribe", " cookies"))
return density * 1.0 + length * 1.0 + min(explains, 8) * 0.08 - min(sells, 8) * 0.1
def candidates(task: Task):
"""tidy's cleanup: (doc, ranges, kept bytes, kept text, tidy score) for every page worth a look."""
corpus = task.corpus
min_copy = int(task.info.get("min_copy_bytes", 64))
seen: set[bytes] = set()
out = []
for i, text in corpus:
if not looks_english(text):
continue
ranges, kept = prose_ranges(text, min_copy)
if kept < 400:
continue
key = hashlib.blake2b(text[:2000].encode("utf-8", "replace"), digest_size=8).digest()
if key in seen:
continue
seen.add(key)
size = corpus.size(i)
ranges = [[a, min(b, size)] for a, b in ranges if a < size and min(b, size) - a >= min_copy]
if not ranges:
continue
raw = corpus.raw(i)
kept_text = b"".join(raw[a:b] for a, b in ranges).decode("utf-8", "replace")
out.append((i, ranges, sum(b - a for a, b in ranges), kept_text, tidy_score(text, kept)))
return out
def fill(order_of_docs, sizes, budget_bytes):
chosen, used = [], 0
for k in order_of_docs:
if used >= budget_bytes:
break
chosen.append(k)
used += sizes[k]
return chosen
def script(cands, picked, rng):
lines = [{"d": cands[k][0], "k": cands[k][1]} for k in picked]
rng.shuffle(lines)
return lines
def score_candidates(task: Task, cands, t0=None):
"""(kinds x candidates) mean log importance of each candidate for each kind of writing."""
t0 = t0 or time.time()
# Every candidate, read with the student's tokenizer.
enc = encoder()
texts = [normalize(c[3]) for c in cands]
toks = enc.encode_ordinary_batch(texts, num_threads=max(1, task.cores))
toks = [np.asarray(t[:SCORE_TOKENS], dtype=np.uint32) for t in toks]
log(f"tokenized in {time.time() - t0:.0f}s")
# Feature counts of this round's pages, and of each kind of writing.
table = np.load(HERE / "table.npz")
target = table["counts"].astype(np.float64) # (6, BUCKETS)
raw = np.zeros(BUCKETS, dtype=np.float64)
chunks = []
step = 4000
for a in range(0, len(toks), step):
ids, seq = features_many(toks[a : a + step])
ids, seq = ids.astype(np.int32), (seq + a).astype(np.int32)
raw += np.bincount(ids, minlength=BUCKETS)
chunks.append((ids, seq))
log(f"features in {time.time() - t0:.0f}s")
def logp(c):
return np.log(c + ALPHA) - np.log(c.sum() + ALPHA * BUCKETS)
weights = np.stack([logp(t) - logp(raw) for t in target]).astype(np.float32) # (6, BUCKETS)
if CLIP > 0:
np.clip(weights, -CLIP, CLIP, out=weights)
offset = np.zeros(len(target))
if SCORER in ("clf", "both"):
# The classifier's log-odds of each kind against the web, from the same features.
clf = np.load(HERE / "classifier.npz")
w = clf["weights"].astype(np.float32) # (BUCKETS, kinds + 1), the web last
lo = (w[:, :-1] - w[:, -1:]).T # (kinds, BUCKETS)
offset = clf["bias"][:-1] - clf["bias"][-1]
weights = lo if SCORER == "clf" else weights + lo
n = len(cands)
scores = np.zeros((len(target), n), dtype=np.float64)
nfeat = np.zeros(n, dtype=np.float64)
for ids, seq in chunks:
nfeat += np.bincount(seq, minlength=n)
for s in range(len(target)):
scores[s] += np.bincount(seq, weights=weights[s][ids], minlength=n)
if SHRINK > 0: # a short page's mean is noisy: pull it towards what is usual for the kind
mean = scores / np.maximum(nfeat, 1)
usual = np.median(mean, axis=1, keepdims=True)
scores = (scores + SHRINK * usual) / (nfeat + SHRINK)
else:
scores /= np.maximum(nfeat, 1)
scores += offset[:, None]
scores = np.round(scores, 4) # the same order on every machine
log(f"scored in {time.time() - t0:.0f}s")
return scores, list(table["sources"])
def edit(task: Task):
t0 = time.time()
rng = random.Random(0)
cands = candidates(task)
sizes = np.array([c[2] for c in cands], dtype=np.int64)
budget = task.train_tokens * BYTES_PER_TOKEN
log(f"{len(cands)} candidate pages, {sizes.sum() / 1e6:.0f} MB of prose, in {time.time() - t0:.0f}s")
# The tidy script first: a run cut short keeps it.
by_tidy = sorted(range(len(cands)), key=lambda k: -cands[k][4])
task.write(script(cands, fill(by_tidy, sizes, budget), rng))
if MODE == "tidy":
return
scores, names = score_candidates(task, cands, t0)
n = len(cands)
target = names
want = budget * FILL
if MODE == "best": # each page's best kind, one ranking
best = scores.max(axis=0)
picked = fill(sorted(range(n), key=lambda k: (-best[k], k)), sizes, want)
else: # each kind takes its share, best first, in turn
shares = np.array(SHARES[: len(target)], dtype=np.float64)
quota = want * shares / shares.sum()
if REPEATS: # each kind its own number of readings: its distinct pages are its share over that
reps = np.array(REPEATS[: len(target)], dtype=np.float64)
quota = budget * shares / shares.sum() / reps
ranked = [sorted(range(n), key=lambda k, s=s: (-scores[s][k], k)) for s in range(len(target))]
ptr = [0] * len(target)
got = np.zeros(len(target))
taken = np.zeros(n, dtype=bool)
picked = []
from urllib.parse import urlsplit
hosts = [urlsplit(task.corpus.urls[c[0]]).netloc.lower() for c in cands] if HOST_CAP else None
per_host: dict[str, int] = {}
while True:
open_ = [s for s in range(len(target)) if got[s] < quota[s] and ptr[s] < n]
if not open_:
break
for s in open_:
while ptr[s] < n and taken[ranked[s][ptr[s]]]:
ptr[s] += 1
if ptr[s] >= n:
continue
k = ranked[s][ptr[s]]
taken[k] = True
if HOST_CAP: # one website's template does not get to fill a kind's share
if per_host.get(hosts[k], 0) >= HOST_CAP:
continue
per_host[hosts[k]] = per_host.get(hosts[k], 0) + 1
picked.append((s, k))
got[s] += sizes[k]
log("bytes per kind:", {names[s]: f"{got[s] / 1e6:.1f}MB" for s in range(len(target))})
picked_docs = [k for _, k in picked]
if REPEATS:
lines = []
for s_, k in picked:
r = REPEATS[s_]
times = int(r) + (1 if random.Random(k).random() < r - int(r) else 0)
lines += [{"d": cands[k][0], "k": cands[k][1]}] * times
rng.shuffle(lines)
task.write(lines)
log(f"done in {time.time() - t0:.0f}s")
return
if ORDER == "anneal2": # each kind's best last, every kind spread evenly through training
pos = np.zeros(len(picked))
for s in range(len(target)):
mine = [j for j, (ss, _) in enumerate(picked) if ss == s]
# picked in rank order within a kind: the first is its best
for r, j in enumerate(mine):
pos[j] = 1.0 - r / max(1, len(mine))
jitter = np.array([random.Random(k).random() * 1e-6 for _, k in picked])
order = np.argsort(pos + jitter, kind="stable")
last = [{"d": cands[picked_docs[j]][0], "k": cands[picked_docs[j]][1]} for j in order]
if FILL < 1: # repeats: the earlier passes shuffled, the last one with the best at its end
import math
earlier = []
for _ in range(math.ceil(1 / FILL) - 1):
again = list(last)
rng.shuffle(again)
earlier += again
last = earlier + last
task.write(last)
log(f"done in {time.time() - t0:.0f}s")
return
if ORDER == "anneal": # the most exam-like last, where the learning rate is low
strength = np.array([scores[s][k] for s, k in picked])
order = np.argsort(strength, kind="stable")
lines = [{"d": cands[picked_docs[j]][0], "k": cands[picked_docs[j]][1]} for j in order]
task.write(lines)
log(f"done in {time.time() - t0:.0f}s")
return
picked = picked_docs
lines = script(cands, picked, rng)
if RESHUFFLE and FILL < 1: # each repeat in an order of its own, not the same order again
import math
copies = [lines]
for _ in range(math.ceil(1 / FILL) - 1):
again = list(lines)
rng.shuffle(again)
copies.append(again)
lines = [x for c in copies for x in c]
task.write(lines)
log(f"done in {time.time() - t0:.0f}s")
def main():
edit(Task.from_env())
if __name__ == "__main__":
main()
download bundle (.tar.zst) id e55ae01435ac4122763d1ef77f14185028b5881a9c02bce1dbc97cb12fe5af40