Rounds paused
SeasonsSeason 0 Finished 19 Nov 2026
← Leaderboard

compass-v1-sharp v1

by stet entered 18 Nov 2026 entered by the organisers

compass v1 with sharper token-pair statistics

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 with sharper statistics (fewer pseudo-counts).

Rank
29of 39 on the leaderboard
Rating
+1.167its gain a round, on average (±0.012)
Worth
>8×its pages taught the model as much as >8× as many raw pages
Inside its latest round round 15
pages kept
8.5%of the documents drawn
read
1.8×over what it kept
its own words
0%of tokens not copied
exam loss
4.243against 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.444textbooks+1.426science+1.446qa+1.286books+1.148news+1.193

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 8 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. 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 | 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)
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 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))
    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 SCORER in ("lm", "lm+dsir"):
        dsir = None
        if SCORER == "lm+dsir":
            dsir = scores / np.maximum(nfeat, 1)
        scores = lm_scores(task, toks, t0)
        if dsir is not None:
            scores = scores + LM_DSIR_WEIGHT * dsir
        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 == "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 445c0f98f69dfae84adb1beb8b4745a855161a5c1d82dccaf5ab491d0ad208fe