File size: 2,895 Bytes
ccbd209
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bf4115
 
ccbd209
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""Data curator: pull web data at scale, judge it against the rubric, keep only the
high-quality, COMPRESS it into compact training items, and discard the raw.

"Compressed" here = the judge distills each accepted doc into a tight
(instruction, ideal_response) pair -- far smaller than the raw page, and directly
trainable. Raw pages are never persisted (the 'weighted not stored' principle).
"""
import json
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent


def web_pull(queries, per_query=10):
    """Stream real, pre-filtered web data at scale from a HF corpus (FineWeb-Edu by
    default) and yield (source, text). This IS the 'pull internet data at insane
    quantity' step -- the judge then re-filters it for our rubric and discards the rest."""
    from datasets import load_dataset
    from config import CORPUS_DATASET, CORPUS_CONFIG
    n = max(1, per_query) * max(1, len(queries))
    ds = load_dataset(CORPUS_DATASET, name=CORPUS_CONFIG, split="train", streaming=True)
    count = 0
    for ex in ds:
        text = ex.get("text") or ex.get("content") or ""
        if len(text) < 200:
            continue
        yield (CORPUS_DATASET, text)
        count += 1
        if count >= n:
            break


def curate(docs, judge, accept_threshold, max_keep):
    """docs: iterable of (source, text). Returns compact accepted items; raw discarded."""
    kept = []
    for source, text in docs:
        if len(kept) >= max_keep:
            break
        # judge distills + rates the doc into a trainable pair
        item = _distill_doc(judge, source, text)
        if item and item["score"] >= accept_threshold:
            kept.append({"instruction": item["instruction"],
                         "response": item["response"], "score": item["score"]})
        # raw `text` goes out of scope here -> never written to disk
    return kept


def _distill_doc(judge, source, text):
    """Use the judge model to compress a raw doc into one (instruction, ideal answer)
    pair and score its quality. Compression = the compact pair, not the raw page."""
    sys = ("Extract ONE high-value instruction a user might ask, and the ideal concise "
           "answer, strictly grounded in the SOURCE. Then rate the answer 0..1. "
           "Return ONLY JSON: {\"instruction\":str,\"response\":str,\"score\":float}.")
    msg = [{"role": "system", "content": sys},
           {"role": "user", "content": f"SOURCE ({source}):\n{text[:6000]}"}]
    import re
    from core.genutil import chat_generate
    t = chat_generate(judge.model, judge.tok, msg, max_new_tokens=512, do_sample=False)
    m = re.search(r"\{.*\}", t, re.DOTALL)
    try:
        d = json.loads(m.group(0))
        return {"instruction": d["instruction"], "response": d["response"],
                "score": float(max(0.0, min(1.0, d.get("score", 0.0))))}
    except Exception:
        return None