Rounds paused
SeasonsSeason 0 Finished 19 Nov 2026
← Leaderboard

compass-v2-keep60 v1

by stet entered 18 Nov 2026 entered by the organisers

compass v2 keeping 60% of the budget

Like compass v2 (builds half the budget to match the exam's six kinds' mix by token-pair statistics of public Common Pile files, after tidy's cleanup; twice), but keeping 60% of the budget.

Rank
30of 39 on the leaderboard
Rating
+1.164its gain a round, on average (±0.006)
Worth
>8×its pages taught the model as much as >8× as many raw pages
Inside its latest round round 15
pages kept
10.1%of the documents drawn
read
1.5×over what it kept
its own words
0%of tokens not copied
exam loss
4.270against 5.572 unedited

Where the gain comes from

Exam loss by kind of text. Hollow: unedited. Filled: this curator. Left is better.

3.54.04.55.05.56.0uneditedthis curatorencyclopedia+1.424textbooks+1.393science+1.449qa+1.269books+1.121news+1.204

The model, learning from it

Training loss on its pages. Low here is not the goal; the exam is.

34567training loss, nats per tokenstep 24step 4,848
Its code 9 files · 4.8 MB

Public from its first round. Start from it:

"""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. Build half the budget a step at a time. The target is the six kinds of writing mixed
     equally; each step adds the pages that best supply what the set built so far is short
     of, so no kind of writing, and no part of one, goes short. (v1 ranked each page on
     its own, kind by kind; building the set as a whole beat that by 0.03 at micro.)
     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))
import features  # noqa: E402
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 | tiered
SCORE_TOKENS = knob("score_tokens", 4096)
MODE = knob("mode", "match")  # balanced | tidy | best | match | match_kinds
SCORER = knob("scorer", "dsir")  # dsir | clf | both | lm | lm+dsir
LM_TOKENS = knob("lm_tokens", 256)  # how much of each page's opening the model reads
LM_DSIR_WEIGHT = knob("lm_dsir_weight", 1.0)
LM_POOL = knob("lm_pool", 0.6)  # share of the candidates, best by the statistics, that the model reads
MATCH_ROUNDS = knob("match_rounds", 20)  # steps in which match builds the set
MATCH_PRIOR = knob("prior", 2e6)  # features' worth of the round's own mix the set starts from
CLF_GATE = knob("clf_gate", 0.0)  # match offers only this share of pages, best by the classifier; 0: all
CLF_WEIGHT = knob("clf_weight", 0.0)  # how much the classifier's opinion adds to match's score
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")
features.NGRAM = knob("ngram", 2)  # 3 adds three-token runs; needs a table built with them  # 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


_STATE: dict = {}


def match_select(sizes, want, rounds=20, prior=2e6, bonus=None, allowed=None):
    """Build the set a step at a time, each step adding the pages that best supply what the
    set so far is short of: the target is the six kinds of writing mixed equally, and a
    feature already well supplied stops counting for much."""
    chunks, raw, target, logp, n = (_STATE[k] for k in ("chunks", "raw", "target", "logp", "n"))
    log_t = np.log(np.mean([np.exp(logp(t)) for t in target], axis=0))
    p_raw = np.exp(logp(raw))
    have = np.zeros_like(raw)
    nfeat = np.zeros(n)
    for ids, seq in chunks:
        nfeat += np.bincount(seq, minlength=n)
    taken = np.zeros(n, dtype=bool)
    picked, used = [], 0.0
    step = want / rounds
    for r in range(rounds):
        p_set = (have + prior * p_raw) / (have.sum() + prior)
        w = (log_t - np.log(p_set)).astype(np.float32)
        score = np.zeros(n)
        for ids, seq in chunks:
            score += np.bincount(seq, weights=w[ids], minlength=n)
        score = score / np.maximum(nfeat, 1)
        if bonus is not None:
            score = score + bonus
        score = np.round(score, 4)
        score[taken] = -np.inf
        if allowed is not None:
            score[~allowed] = -np.inf
        goal = min(want, used + step)
        new = []
        for k in np.lexsort((np.arange(n), -score)):
            if used >= goal or not np.isfinite(score[k]):
                break
            taken[k] = True
            new.append(int(k))
            used += sizes[k]
        picked += new
        mark = np.zeros(n, dtype=bool)
        mark[new] = True
        for ids, seq in chunks:
            m = mark[seq]
            have += np.bincount(ids[m], minlength=len(have))
    return picked


def match_kinds_select(sizes, want, shares, rounds=20, prior=2e6):
    """match, kind by kind: each kind of writing builds its own share of the set, a step at a
    time, from what its share is short of; a page one kind takes, the others cannot."""
    chunks, raw, target, logp, n = (_STATE[k] for k in ("chunks", "raw", "target", "logp", "n"))
    K = len(target)
    log_t = [logp(t) for t in target]
    p_raw = np.exp(logp(raw))
    have = [np.zeros_like(raw) for _ in range(K)]
    nfeat = np.zeros(n)
    for ids, seq in chunks:
        nfeat += np.bincount(seq, minlength=n)
    quota = want * np.asarray(shares[:K], dtype=np.float64) / np.sum(shares[:K])
    taken = np.zeros(n, dtype=bool)
    used = np.zeros(K)
    picked = []
    for r in range(rounds):
        scores = []
        for k in range(K):
            p_set = (have[k] + prior * p_raw) / (have[k].sum() + prior)
            w = (log_t[k] - np.log(p_set)).astype(np.float32)
            sc = np.zeros(n)
            for ids, seq in chunks:
                sc += np.bincount(seq, weights=w[ids], minlength=n)
            scores.append(np.round(sc / np.maximum(nfeat, 1), 4))
        order = [list(np.lexsort((np.arange(n), -sc))) for sc in scores]
        ptr = [0] * K
        goal = quota * min(1.0, (r + 1) / rounds)
        new = [[] for _ in range(K)]
        active = True
        while active:  # the kinds take turns, so none gets first pick of every page
            active = False
            for k in range(K):
                if used[k] >= goal[k]:
                    continue
                while ptr[k] < n and taken[order[k][ptr[k]]]:
                    ptr[k] += 1
                if ptr[k] >= n:
                    continue
                j = int(order[k][ptr[k]])
                taken[j] = True
                new[k].append(j)
                used[k] += sizes[j]
                active = True
        for k in range(K):
            picked += new[k]
            mark = np.zeros(n, dtype=bool)
            mark[new[k]] = True
            for ids, seq in chunks:
                m = mark[seq]
                have[k] += np.bincount(ids[m], minlength=len(raw))
    return picked


def clf_kindness(task: Task, t0):
    """Per candidate: the classifier's log-odds that its opening is one of the six kinds of
    writing rather than the ordinary web, (n,), and of each kind against the web, (6, n)."""
    import torch

    import clf

    device = torch.device(task.device())
    model = clf.load(HERE / "clf.npz", device)
    logits = clf.page_logits(model, _STATE["toks"], device)  # (n, 7): the web last
    log(f"read by the classifier in {time.time() - t0:.0f}s on {device}")
    each = (logits[:, :-1] - logits[:, -1:]).T
    any_kind = np.logaddexp.reduce(logits[:, :-1], axis=1) - logits[:, -1]
    return np.round(any_kind, 2), np.round(each, 2)


def lm_scores(task: Task, toks, t0):
    """(kinds x candidates): how much easier the reader finds each page as that kind of
    writing than as ordinary web text, in nats per token, over its opening."""
    import torch

    import lm

    device = torch.device(task.device())
    model = lm.load(HERE / "lm.npz", device)
    losses = lm.page_losses(model, toks, device, max_tokens=LM_TOKENS)  # (7, n): the web last
    log(f"read by the model in {time.time() - t0:.0f}s on {device}")
    return losses[-1:] - losses[:-1]


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))
    _STATE["ntok"] = np.array([len(t) for t in toks], dtype=np.int64)
    toks = [np.asarray(t[:SCORE_TOKENS], dtype=np.uint32) for t in toks]
    _STATE["toks"] = 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)

    _STATE.update(chunks=chunks, raw=raw, target=target, logp=logp, n=len(toks))

    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 SCORER in ("lm", "lm+dsir"):
        dsir = scores / np.maximum(nfeat, 1)
        # The model reads only the pages the statistics already think well of: it is the
        # slow reader, and most of a round will not be kept whatever it says.
        best = dsir.max(axis=0)
        keep = np.argsort(-best, kind="stable")[: max(1, int(len(best) * LM_POOL))]
        lm_part = lm_scores(task, [toks[k] for k in keep], t0)
        scores = np.full_like(dsir, -1e9)
        scores[:, keep] = lm_part + (LM_DSIR_WEIGHT * dsir[:, keep] if SCORER == "lm+dsir" else 0)
        scores = np.round(scores, 3)  # the same order on NVIDIA and AMD, as near as can be
        log(f"scored in {time.time() - t0:.0f}s")
        return scores, list(table["sources"])
    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 == "match":
        bonus = allowed = None
        if CLF_GATE > 0 or CLF_WEIGHT > 0:
            kindness, _ = clf_kindness(task, t0)
            if CLF_GATE > 0:  # only pages the classifier thinks well of are offered at all
                cut = np.sort(kindness)[::-1][max(0, min(n - 1, int(n * CLF_GATE) - 1))]
                allowed = kindness >= cut
            if CLF_WEIGHT > 0:
                bonus = CLF_WEIGHT * np.clip(kindness, -10, 10) / 10
        picked = match_select(sizes, want, rounds=MATCH_ROUNDS, prior=MATCH_PRIOR, bonus=bonus, allowed=allowed)
        log(f"matched in {time.time() - t0:.0f}s")
    elif MODE == "match_kinds":
        picked = match_kinds_select(sizes, want, SHARES, rounds=MATCH_ROUNDS, prior=MATCH_PRIOR)
        log(f"matched in {time.time() - t0:.0f}s")
    elif 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
    if ORDER == "tiered" and "ntok" in _STATE:
        # The stream is the script read from the top until the budget is spent, so the
        # opening of the script is what gets read a second time: make that the best pages
        # (in the order they were picked), each part shuffled within itself.
        ntok = _STATE["ntok"][picked].astype(np.float64)
        once = ntok.sum()
        again = max(0.0, min(once, task.train_tokens - once))
        split = int(np.searchsorted(np.cumsum(ntok), again))
        first, rest = list(picked[:split]), list(picked[split:])
        lines = script(cands, first, rng) + script(cands, rest, rng)
        log(f"{split} of {len(picked)} pages placed to be read twice")
        task.write(lines)
        log(f"done in {time.time() - t0:.0f}s")
        return
    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 048aea66ad3acd6413b274a452d2dca71c0838478c10d3e154644d9b5791e97f