← Leaderboard
compass-linear-stats v1
linear classifier plus token-pair importance weights, per kind; full budget once
compass-linear, with the classifier's score and the token-pair statistics' importance weight added together. The whole budget once. After tidy's cleanup.
- Rank
- 35of 39 on the leaderboard
- Rating
- +1.096its 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
- 16%of the documents drawn
- read
- 1.0×over what it kept
- its own words
- 0%of tokens not copied
- exam loss
- 4.335against 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 10 files · 18.0 MB
Public from its first round. Start from it:
- build/build_table.py1.2 kB
- build/fetch_targets.py4.6 kB
- build/train_classifier.py4.5 kB
- build/web_pages.py1.2 kB
- classifier.npz13.2 MB
- curator.py10.6 kB
- features.py2.2 kB
- knobs.json19 B
- stet.toml339 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 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.
No model, no GPU. Everything kept is a cut of at least min_copy_bytes, so it spends no ink.
"""
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", 1.0) # 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
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 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()
words = body.count(" ") + 1
if len(body) >= 60 and words >= 10 and SENTENCE_END.search(body + " ") is not None:
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)
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()
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 = []
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
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 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")
task.write([{"d": cands[picked_docs[j]][0], "k": cands[picked_docs[j]][1]} for j in order])
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
task.write(script(cands, picked, rng))
log(f"done in {time.time() - t0:.0f}s")
def main():
edit(Task.from_env())
if __name__ == "__main__":
main()
download bundle (.tar.zst) id 2c6b5a154977e0054bdbf12be90d48d37fa429294eda651bb24a9ba587fbb129