glide-late-topic-edits v1
Two-view preferences and contextual similarity for matched prose edits, built with Fastino GLiDE
A fine-tuned decision model selects topically similar prose replacements in the final part of training.
- Rank
- 6of 14 on the leaderboard
- Rating
- +0.041its gain a round, on average (±0.008)
Round by round
9 rounds
Where it came in each round, and its gain.
- Round 14 5th of 11 one grader +0.023
- Round 13 5th of 11 one grader +0.039
- Round 12 6th of 11 one grader +0.003
- Round 11 1st of 8 one grader +0.082
- Round 10 3rd of 8 one grader −0.003
- Round 9 1st of 8 one grader +0.039
- Round 8 1st of 9 one grader +0.061
- Round 7 4th of 11 one grader +0.057
- Round 6 2nd of 11 one grader +0.053
Inside its latest round round 14
- pages kept
- 14.7%of the documents drawn
- read
- 1.0×over what it kept
- its own words
- 0%of tokens not copied
- on the exam
- 2.806bits per byte, against 2.829 unedited
Where the gain comes from
Its gain on each thing the exam tests, in bits per byte better than unedited. Each counts the same. Right is better.
The model, learning from it
Training loss on its pages. Low here is not the goal; the exam is.
Its code 4 files · 10.7 kB
Public from its first round. Start from it:
import math
import multiprocessing as mp
import random
import re
import unicodedata
from array import array
from collections import Counter, defaultdict
from dataclasses import dataclass
from pathlib import Path
import numpy as np
from stet.curator import Task
from xxhash import xxh3_64_intdigest as digest
from hybrid import edit_pages
MAX_PAGE_BYTES = 64_000
SCAN_CONTEXT = None
TEMPLATE_CONTEXT = None
DIGITS = re.compile(rb"\d+")
SPACES = re.compile(rb"\s+")
LETTERS = re.compile(r"[^\W\d_]+")
SENTENCES = re.compile(r"[.!?](?:\s|$)|[。!?؟։।]")
LINKS = re.compile(rb"https?://|\bwww\.", re.I)
FURNITURE = re.compile(
rb"\b(?:skip to (?:main )?content|all rights reserved|powered by|"
rb"cookie (?:policy|settings|preferences|consent)|accept (?:all )?cookies|"
rb"privacy policy|terms (?:of (?:use|service)|and conditions)|"
rb"javascript (?:is disabled|to view)|subscribe to our newsletter|"
rb"(?:sign|log) in (?:to|or)|add to (?:cart|basket)|"
rb"pol.{1,2}tica de privacidad|mentions l.{1,2}gales|datenschutzerkl.{1,2}rung)\b",
re.I,
)
COMMAND = re.compile(
rb"(?m)^\s{0,10}(?:(?:\$ |[\w.@-]+:[^\n $]{0,70}\$ )\S"
rb"|(?:Traceback \(most recent call last\)|(?:[A-Za-z]+Error|Exception):)"
rb"|(?:\d{4}-\d\d-\d\d[ T]\d\d:\d\d|\[?(?:DEBUG|INFO|WARN|ERROR)\]?[ :]+\S))"
)
PROGRAM = re.compile(
rb"(?m)(?:^\s{0,12}(?:def |class |function |(?:>>>|\.\.\.) |import \w"
rb"|(?:const|let|var|return|using|package) \w|public (?:static|class) )"
rb"|=>\s*[{(]|\b\w+\([^\n)]{0,50}\);|\"[\w.-]+\"\s*:\s*[\x00-\x7f])"
)
NUMERIC = re.compile(
rb"\d(?:[,.]\d+)?\s*[%=+*/<>]|[=+*/<>]\s*[-+]?\d|\d[ ]{2,}\d|\d[|,;]\s*\d"
rb"|\\(?:frac|sqrt|sum|times)\b|\b(?:equation|derivative|theorem|probability|"
rb"proportional|algebra|ecuaci.{1,2}n|teorema|gleichung|wahrscheinlichkeit)\b",
re.I,
)
CONVERSATION = re.compile(
rb"\b(?:wrote|replied|posted by|asked by|said|answers?|comments?|replies|"
rb"discussion|thread|beitrag|r.ponse|comentarios?|respostas?)\b",
re.I,
)
FORUM_PATH = re.compile(r"(?:forum|reddit|stack(?:overflow|exchange)|discuss|/thread|/comment|/issues)")
REFERENCE_PATH = re.compile(r"(?:wik(?:i|tionary)|britannica|/glossar|/encyclop|\.edu/|/handbook)")
TECH_PATH = re.compile(r"(?:github|gitlab|readthedocs|/docs/|/api/|/tutorial|/reference/)")
NEWS_PATH = re.compile(r"(?:/news/|/press/|/politics/|/noticias/|/actualites/|\.news/)")
class LineCounts:
def __init__(self, bits):
self.first = array("I", [0]) * (1 << bits)
self.second = array("I", [0]) * (1 << bits)
self.mask = (1 << bits) - 1
def add(self, key):
self.first[key & self.mask] += 1
self.second[key >> 32 & self.mask] += 1
def count(self, key):
return min(self.first[key & self.mask], self.second[key >> 32 & self.mask])
def merge(self, other):
for target, source in ((self.first, other.first), (self.second, other.second)):
counts = np.frombuffer(target, dtype=np.uint32)
counts += np.frombuffer(source, dtype=np.uint32)
@dataclass(slots=True)
class Candidate:
doc: int
host: int
language: str
genre: str
score: float
tokens: int
ranges: list
fingerprints: tuple
def host_of(url):
host = url.split("://", 1)[-1].split("/", 1)[0].split(":", 1)[0].lower()
return digest(host.removeprefix("www.").encode())
def line_key(line):
return digest(DIGITS.sub(b"0", b" ".join(line.lower().split())))
def lines_with_offsets(raw):
start = 0
for line in raw.splitlines(keepends=True):
end = start + len(line)
yield start, end, line.strip()
start = end
def template_keys(raw):
return {
line_key(line)
for start, end, line in lines_with_offsets(raw)
if 4 <= len(line) <= 256 and (len(line) < 120 or start < 700 or end > len(raw) - 900)
}
def count_templates(task, bits, start, stop):
shared = LineCounts(bits)
scanned = 0
for doc in range(start, stop):
if doc % 256 == 0 and task.time_left() < 45:
break
raw = task.corpus.raw(doc)[:MAX_PAGE_BYTES]
for key in template_keys(raw):
shared.add(key)
scanned += 1
return shared, scanned
def init_templates(task, bits):
global TEMPLATE_CONTEXT
TEMPLATE_CONTEXT = task, bits
def template_batch(bounds):
return count_templates(*TEMPLATE_CONTEXT, *bounds)
def measure_templates(task, hosts):
workers = min(6, task.cores)
bits = 23 if len(hosts) >= 100_000 else 22
if workers < 2 or len(hosts) < 20_000 or "fork" not in mp.get_all_start_methods():
shared, scanned = count_templates(task, bits, 0, len(hosts))
else:
stride = (len(hosts) + workers - 1) // workers
bounds = [(start, min(len(hosts), start + stride)) for start in range(0, len(hosts), stride)]
with mp.get_context("fork").Pool(workers, initializer=init_templates, initargs=(task, bits)) as pool:
results = pool.imap_unordered(template_batch, bounds)
shared, scanned = next(results)
for other_shared, count in results:
shared.merge(other_shared)
scanned += count
print(f"Template frequencies from {scanned:,} pages", flush=True)
return shared
def language_detector(task):
try:
import fasttext
path = Path(task.asset("language")) / "lid.176.ftz"
return fasttext.load_model(str(path))
except (ImportError, KeyError, OSError, RuntimeError, ValueError) as error:
print(f"Language model unavailable ({error})", flush=True)
return None
def language_of(text, detector):
if detector is not None:
sample = " ".join(text[:1800].split())
if sample:
labels, confidence = detector.predict(sample)
if confidence[0] >= 0.23:
return labels[0].removeprefix("__label__")
non_ascii = Counter(
unicodedata.name(char, "").split(" ", 1)[0]
for char in text[:1400] if not char.isascii() and char.isalpha()
)
if non_ascii and non_ascii.total() > 0.15 * min(1400, len(text)):
return non_ascii.most_common(1)[0][0]
return "en" if text.isascii() else "other-latin"
def find_genre(sample, url, paragraphs):
commands = len(COMMAND.findall(sample))
programs = len(PROGRAM.findall(sample))
numeric = len(NUMERIC.findall(sample))
discussion = len(CONVERSATION.findall(sample))
if commands >= 2 or (commands and programs >= 4):
return "shell", min(1.7, 0.35 * math.log1p(commands + programs))
if programs >= 4 or (programs and TECH_PATH.search(url)):
return "code", min(1.6, 0.35 * math.log1p(programs))
if numeric >= 3 and numeric * 250 >= len(sample):
return "quantitative", min(1.15, 0.31 * math.log1p(numeric))
if FORUM_PATH.search(url) or discussion >= max(4, paragraphs // 2):
return "discussion", min(0.75, 0.29 * math.log1p(discussion))
if REFERENCE_PATH.search(url):
return "reference", 0.55
if NEWS_PATH.search(url):
return "news", 0.28
if TECH_PATH.search(url):
return "technical", 0.28
return "prose", 0.0
def content_ranges(raw, shared, local):
lines = list(lines_with_offsets(raw))
features = []
for start, end, line in lines:
size = len(line)
if not size:
features.append((False, False))
continue
edge = start < 850 or end > len(raw) - 1050
if size <= 256 and (size < 120 or edge):
key = line_key(line)
long = size >= 105
if (local.get(key, 0) >= (12 if long else 4)
or shared.count(key) >= (65 if long else 24)):
features.append((False, True))
continue
if size < 270 and (FURNITURE.search(line) or line.count(b"|") >= 4):
features.append((False, True))
continue
if size < 14:
features.append((False, False))
continue
is_structure = bool(COMMAND.search(line) or PROGRAM.search(line))
if is_structure:
features.append((True, False))
continue
text = line[:640].decode("utf-8", errors="ignore")
words = LETTERS.findall(text)
letters = sum(map(len, words))
continuous = not text.isascii() and any(len(word) > 13 for word in words)
good = (
(len(text) >= 90 and letters >= 0.55 * len(text))
or (len(text) >= 34 and letters >= 0.46 * len(text) and SENTENCES.search(text))
or (continuous and letters >= 0.62 * len(text) and len(text) >= 24)
or (size >= 26 and len(NUMERIC.findall(line[:640])) >= 2)
)
features.append((bool(good), False))
seeds = [index for index, (keep, _) in enumerate(features) if keep]
keep = set(seeds)
for index in seeds:
for neighbor in (index - 1, index + 1):
if 0 <= neighbor < len(lines) and not features[neighbor][1]:
keep.add(neighbor)
ranges = []
for index in sorted(keep):
start, end, _ = lines[index]
if ranges and start == ranges[-1][1]:
ranges[-1] = (ranges[-1][0], end)
else:
ranges.append((start, end))
return [(a, b) for a, b in ranges if b - a >= 64], len(seeds)
def fingerprints(clean):
normalized = DIGITS.sub(b"0", SPACES.sub(b" ", clean.lower())).strip()
if len(normalized) < 1_000:
return (digest(normalized),)
sections = [0, len(normalized) // 2 - 180, len(normalized) - 360]
return tuple(digest(normalized[start:start + 360]) for start in sections)
def inspect_page(task, doc, host, shared, local, detector):
corpus = task.corpus
raw = corpus.raw(doc)[:MAX_PAGE_BYTES]
if len(raw) < 110:
return None
if corpus.size(doc) > MAX_PAGE_BYTES and b"\n" in raw[-1000:]:
raw = raw[:raw.rfind(b"\n") + 1]
ranges, paragraphs = content_ranges(raw, shared, local)
if not ranges:
return None
clean = b"".join(raw[a:b] for a, b in ranges)
if len(clean) < 185:
return None
sample = clean[:4000] + (clean[len(clean) // 2:][:3000] if len(clean) > 7500 else b"")
text = sample.decode("utf-8", errors="replace")
if text.count("\ufffd") > max(3, len(text) // 80):
return None
language = language_of(text, detector)
genre, form_bonus = find_genre(sample, corpus.urls[doc].lower(), paragraphs)
words = LETTERS.findall(text)
word_count = len(words)
letter_ratio = sum(map(len, words)) / max(1, len(text))
variety = len({word.lower() for word in words}) / max(1, min(word_count, 270))
sentence_rate = len(SENTENCES.findall(text)) * 135 / max(1, len(text))
size_bonus = min(1.35, math.log1p(len(clean) / 560) * 0.48)
score = (
size_bonus + 1.65 * min(letter_ratio, 0.83) + min(sentence_rate, 1.0) * 0.48
+ 0.62 * math.sqrt(len(clean) / len(raw)) + 0.68 * min(variety, 0.75)
+ form_bonus - 0.19 * min(8, len(LINKS.findall(sample)))
)
if genre == "prose" and len(clean) > 22_000:
score -= 0.30
if b"\0" in sample:
score -= 1.2
byte_rate = 3.30 if language in {"en", "es", "fr", "de", "it", "pt", "nl"} else 3.0
if genre in {"code", "shell", "quantitative"}:
byte_rate *= 0.85
tokens = max(1, int(len(clean) / byte_rate))
return Candidate(doc, host, language, genre, round(score, 4), tokens, ranges, fingerprints(clean))
def choose(candidates, target, english_floor):
by_language = defaultdict(list)
host_volume = Counter()
for page in candidates:
by_language[page.language].append(page)
host_volume[page.host] += page.tokens
language_volume = {
language: sum(page.tokens for page in pages) for language, pages in by_language.items()
}
mass = {
language: volume ** 0.95 for language, volume in language_volume.items()
}
total_mass = sum(mass.values())
native_english = mass.get("en", 0) / total_mass
english = min(0.86, max(english_floor, native_english)) if "en" in mass else 0.0
other_mass = max(1, total_mass - mass.get("en", 0))
quotas = {
language: int(target * (english if language == "en" else (1 - english) * weight / other_mass))
for language, weight in mass.items()
}
def rank(page):
dominance = math.log1p(host_volume[page.host] / max(20_000, target * 0.0004))
return (round(page.score - 0.12 * dominance, 4), -page.doc)
genre_share = {
"shell": 0.025, "code": 0.070, "quantitative": 0.070,
"discussion": 0.090, "reference": 0.075, "news": 0.040, "technical": 0.040,
}
selected = []
selected_docs = set()
seen = set()
domain_used = Counter()
language_used = Counter()
genre_used = Counter()
def take(page, host_limit):
if page.doc in selected_docs or domain_used[page.host] >= host_limit:
return False
matches = sum(fingerprint in seen for fingerprint in set(page.fingerprints))
if matches >= min(2, len(page.fingerprints)):
return False
selected.append(page)
selected_docs.add(page.doc)
seen.update(page.fingerprints)
domain_used[page.host] += page.tokens
language_used[page.language] += page.tokens
genre_used[page.genre] += page.tokens
return True
ranked = sorted(candidates, key=rank, reverse=True)
hard_limit = max(10_000, int(target * 0.019))
for page in ranked:
reserved = target * genre_share.get(page.genre, 0)
if genre_used[page.genre] < reserved and language_used[page.language] < quotas[page.language] * 0.70:
take(page, hard_limit)
for page in ranked:
if language_used[page.language] < quotas[page.language]:
take(page, hard_limit)
remaining = target - language_used.total()
for page in ranked:
if remaining <= 0:
break
if take(page, hard_limit * 2):
remaining -= page.tokens
print(f"Estimated tokens {language_used.total():,}; languages {language_used.most_common(10)}", flush=True)
print(f"Genre tokens {genre_used.most_common()}", flush=True)
return selected
def fallback(task):
order = list(range(len(task.corpus)))
random.Random(151927).shuffle(order)
chosen = []
size = 0
for doc in order:
length = task.corpus.size(doc)
if 430 <= length < 48_000:
chosen.append(doc)
size += length
if size >= task.train_tokens * 3:
break
task.write(chosen or order[:25_000])
def init_scan(task, hosts, shared, detector):
global SCAN_CONTEXT
SCAN_CONTEXT = task, hosts, shared, detector
def scan_batch(groups):
task, hosts, shared, detector = SCAN_CONTEXT
pages = []
for docs in groups:
local = Counter()
if len(docs) >= 4:
for doc in docs:
local.update(template_keys(task.corpus.raw(doc)[:MAX_PAGE_BYTES]))
for doc in docs:
page = inspect_page(task, doc, hosts[doc], shared, local, detector)
if page is not None:
pages.append(page)
return pages
def group_batches(hosts):
domains = defaultdict(list)
for doc, host in enumerate(hosts):
domains[host].append(doc)
batch = []
size = 0
for docs in domains.values():
batch.append(docs)
size += len(docs)
if size >= 128:
yield batch
batch, size = [], 0
if batch:
yield batch
def scan_candidates(task, hosts, shared, detector):
context = task, hosts, shared, detector
workers = min(6, task.cores)
candidates = []
def collect(batches):
for pages in batches:
candidates.extend(pages)
if task.time_left() < 15:
break
if workers < 2 or "fork" not in mp.get_all_start_methods():
init_scan(*context)
collect(map(scan_batch, group_batches(hosts)))
else:
with mp.get_context("fork").Pool(workers, initializer=init_scan, initargs=context) as pool:
collect(pool.imap(scan_batch, group_batches(hosts)))
return candidates
def main():
task = Task.from_env()
fallback(task)
hosts = [host_of(url) for url in task.corpus.urls]
shared = measure_templates(task, hosts)
detector = language_detector(task)
standard = task.train_tokens >= 80_000_000
target = int(task.train_tokens * (0.94 if standard else 0.77))
english_floor = 0.43 if standard else 0.63
candidates = scan_candidates(task, hosts, shared, detector)
if not candidates:
return
selected = choose(candidates, target, english_floor)
if not selected:
return
random.Random(158461).shuffle(selected)
task.write({"d": page.doc, "k": page.ranges} for page in selected)
print(f"Wrote {len(selected):,} curated pages from {len(candidates):,} candidates", flush=True)
edited = edit_pages(task, selected, candidates, target, replay=False)
if edited is not None:
task.write({"d": page.doc, "k": page.ranges} for page in edited)
if __name__ == "__main__":
main()
download bundle (.tar.zst) id ba0ebcc6ecd3828e47e004201a7a0e96de096be02e384076d8a6c5c4657acf49
Files it fetches 758.5 MB in 17 files
Too large for the bundle, so named in it by address and hash. Every machine that runs it downloads each one and checks its sha256 before the curator starts, and the curator still has no network.