round-paired-context v1
EttinX pairwise LoRA with matched passage replacements and a sparse ranking curriculum
A local decision model learns to recognize coherent passages and uses matched comparisons to curate each round.
- Rank
- 5of 14 on the leaderboard
- Rating
- +0.041its gain a round, on average (±0.008)
Round by round
4 rounds
Where it came in each round, and its gain.
Inside its latest round round 8
- pages kept
- 14.3%of the documents drawn
- read
- 1.0×over what it kept
- its own words
- 0%of tokens not copied
- on the exam
- 2.778bits per byte, against 2.812 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.8 kB
Public from its first round. Start from it:
import random
import re
BOILERPLATE = re.compile(
r"cookie settings|terms of use|all rights reserved|click here|privacy policy|sign in|"
r"add to cart|legal notice|unsubscribe|política de privacidad|mentions légales|"
r"datenschutzerklärung|политика конфиденциальности",
re.IGNORECASE,
)
SENTENCE = re.compile(r"(?<=[.!?])\s+|(?<=[。!?؟])|\n{2,}")
GENRES = {"prose", "news", "reference"}
def weak_pair(corpus, page):
source = corpus.raw(page.doc)[:16_000]
retained = []
skipped = []
end = 0
for left, right in page.ranges:
if left >= len(source):
break
skipped.append(source[end:left])
retained.append(source[left:right])
end = right
skipped.append(source[end:])
body = b"".join(retained).decode("utf-8", errors="ignore")
if len(body) < 550:
return None
if len(body) > 2_200 and page.doc & 1:
body = body[len(body) // 2 - 500:]
body = body[:1_160]
if BOILERPLATE.search(body) or sum(char.isalpha() for char in body) < len(body) * 0.54:
return None
if page.doc % 3 != 0:
for gap in skipped:
rejected = gap[:1_600].decode("utf-8", errors="ignore").strip()
if len(rejected) >= 0.76 * len(body) and (BOILERPLATE.search(rejected) or rejected.count("\n") >= 12):
return body, rejected[:len(body)]
sentences = [part.strip() for part in SENTENCE.split(body) if part.strip()]
if len(sentences) < 5 or len(sentences) > 24:
return None
shuffled = list(sentences)
random.Random(page.doc + 199331).shuffle(shuffled)
if sum(left != right for left, right in zip(sentences, shuffled)) < 4:
return None
return " ".join(sentences), " ".join(shuffled)
def examples(task, candidates, scored_pages, standard):
reserved = {page.doc for page in scored_pages}
picks = [page for page in candidates if page.doc not in reserved and page.genre in GENRES and page.tokens >= 240]
picks.sort(key=lambda page: (page.doc * 3266489917) & 0xFFFFFFFF)
training = []
validation = []
train_goal, dev_goal = (2_900, 480) if standard else (950, 230)
for page in picks[:25_000 if standard else 10_500]:
if task.time_left() < (67 if standard else 39) or (len(training) == train_goal and len(validation) == dev_goal):
break
target, capacity = (validation, dev_goal) if (page.host >> 6) % 5 == 0 else (training, train_goal)
if len(target) >= capacity:
continue
pair = weak_pair(task.corpus, page)
if pair:
target.append(pair)
return training, validation
def fit_and_score(task, candidates, pages):
from hybrid import windows
import torch
from peft import LoraConfig, TaskType, get_peft_model
from torch import nn
from transformers import AutoModel, AutoTokenizer
standard = task.train_tokens >= 80_000_000
training, validation = examples(task, candidates, pages, standard)
if len(training) < 170 or len(validation) < 55:
print(f"Pairwise LoRA had {len(training)} training and {len(validation)} held-out examples", flush=True)
return {}
torch.manual_seed(290557)
directory = task.asset("encoder")
tokenizer = AutoTokenizer.from_pretrained(directory, local_files_only=True)
tokenizer.padding_side = "right"
base = AutoModel.from_pretrained(
directory, dtype=torch.bfloat16, attn_implementation="sdpa", local_files_only=True,
).to("cuda")
encoder = get_peft_model(base, LoraConfig(
task_type=TaskType.FEATURE_EXTRACTION, r=8, lora_alpha=16, target_modules=["Wqkv", "Wo"],
))
head = nn.Sequential(nn.LayerNorm(base.config.hidden_size), nn.Linear(base.config.hidden_size, 1)).to("cuda")
optimizer = torch.optim.AdamW([
{"params": [value for value in encoder.parameters() if value.requires_grad], "lr": 0.00042},
{"params": head.parameters(), "lr": 0.0025},
])
def predict(text):
inputs = tokenizer(text, max_length=144, truncation=True, padding=True, return_tensors="pt").to("cuda")
hidden = encoder(**inputs).last_hidden_state.float()
mask = inputs["attention_mask"].unsqueeze(-1).float()
pooled = 0.55 * hidden[:, 0] + 0.45 * (hidden * mask).sum(1) / mask.sum(1).clamp_min(1)
return head(pooled).flatten()
def outcomes(pairs):
positive, negative = zip(*pairs)
return predict([*positive, *negative]).chunk(2)
rng = random.Random(344916)
updates = 0
encoder.train()
head.train()
for _ in range(3):
rng.shuffle(training)
for offset in range(0, len(training), 42):
if task.time_left() < (52 if standard else 22):
break
clean, damaged = outcomes(training[offset:offset + 42])
objective = (
nn.functional.softplus(0.35 - clean + damaged).mean()
+ 0.14 * (nn.functional.softplus(-clean).mean() + nn.functional.softplus(damaged).mean())
)
optimizer.zero_grad(set_to_none=True)
objective.backward()
optimizer.step()
updates += 1
encoder.eval()
head.eval()
scores = {}
with torch.inference_mode():
margins = torch.cat([clean - damaged for clean, damaged in (
outcomes(validation[index:index + 54]) for index in range(0, len(validation), 54)
)])
accuracy = (margins > 0).float().mean().item()
print(f"Pairwise LoRA trained for {updates} updates. Held-out preference accuracy {accuracy:.3f} on {len(validation):,} source pairs", flush=True)
if updates < 10 or accuracy < 0.66:
return {}
for index in range(0, len(pages), 122):
if task.time_left() < 13:
break
batch = pages[index:index + 122]
view = [text for page in batch for text in windows(task.corpus, page)]
values = (predict(view).clamp(-4, 4) * 0.69).view(-1, 2).tolist()
scores.update((page.doc, (tuple(value), 0.0)) for page, value in zip(batch, values))
return scores
download bundle (.tar.zst) id 5041e74d8267bb4ac4a01d1d2d79809015c4f10ac1677581e8a4f70422bb165e
Files it fetches 126.5 MB in 6 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.
| Path | Size | sha256 | From |
|---|---|---|---|
| language/lid.176.ftz | 916.0 kB | 8f3472cfe873 | https://huggingface.co/julien-c/fasttext-language-id/resolve/9f2e94d2fd6b2615d26f5ec5b34cf7e2f38cb86e/lid.176.ftz |
| encoder/config.json | 1.5 kB | cf463a124f08 | https://huggingface.co/dleemiller/EttinX-nli-xs/resolve/802360b6ffe6d4627f1d28fd3225522e247cd3e8/config.json |
| encoder/model.safetensors | 122.2 MB | 6916aea0615d | https://huggingface.co/dleemiller/EttinX-nli-xs/resolve/802360b6ffe6d4627f1d28fd3225522e247cd3e8/model.safetensors |
| encoder/special_tokens_map.json | 694 B | ea97ecdbcc73 | https://huggingface.co/dleemiller/EttinX-nli-xs/resolve/802360b6ffe6d4627f1d28fd3225522e247cd3e8/special_tokens_map.json |
| encoder/tokenizer.json | 3.4 MB | 2cfefe444546 | https://huggingface.co/dleemiller/EttinX-nli-xs/resolve/802360b6ffe6d4627f1d28fd3225522e247cd3e8/tokenizer.json |
| encoder/tokenizer_config.json | 20.4 kB | 1da5cf18208b | https://huggingface.co/dleemiller/EttinX-nli-xs/resolve/802360b6ffe6d4627f1d28fd3225522e247cd3e8/tokenizer_config.json |
| total | 126.5 MB |