File size: 4,576 Bytes
f764cdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02ebb32
 
f764cdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
"""Audit dependency samples against real local The Stack v2 repositories."""

from __future__ import annotations

import argparse
from collections import Counter
import json
import os
from pathlib import Path
import time

import tiktoken

from audit_repoinfo_stack_v2 import load_bodies, make_repo, sample_repositories
from stackbuild import BuildConfig, build_samples


ROOT = Path(__file__).resolve().parents[1]
DATA_ROOT = Path(os.environ.get(
    "STACKGO_DATA_ROOT", "/home/ldj/tgai/data/pretrain-data"
))
DEFAULT_DATA = DATA_ROOT / "the-stack-v2-contents-star-gt10"
DEFAULT_REPORT = ROOT / "reports/stackbuild-audit.json"


def audit_repo(repo, samples, max_tokens: int) -> tuple[list[str], dict]:
    errors: list[str] = []
    source_paths = {file.path.lstrip("/") for file in repo.files}
    covered = {file.path for sample in samples for file in sample.files}
    if covered != source_paths:
        errors.append(
            f"coverage mismatch missing={len(source_paths - covered)} "
            f"extra={len(covered - source_paths)}"
        )
    if any(sample.kind != "dependency" for sample in samples):
        errors.append("non-dependency sample emitted")
    ids = [sample.sample_id for sample in samples]
    if len(ids) != len(set(ids)):
        errors.append("duplicate sample ids")
    oversized = [sample.sample_id for sample in samples if sample.token_count > max_tokens]
    if oversized:
        errors.append(f"{len(oversized)} samples exceed token budget")
    malformed = [
        sample.sample_id for sample in samples
        if not sample.text.startswith(f"<|begin▁of▁repo▁name|>{repo.repo_id}<|end▁of▁repo▁name|>\n")
        or sample.text.count("<|begin▁of▁file▁name|>") != len(sample.files)
        or "<|endoftext|>" in sample.text
        or "<|fim_" in sample.text
    ]
    if malformed:
        errors.append(f"{len(malformed)} samples have malformed boundary tokens")
    return errors, {
        "files": len(source_paths),
        "samples": len(samples),
        "covered_files": len(covered),
        "max_sample_tokens": max((sample.token_count for sample in samples), default=0),
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data-root", type=Path, default=DEFAULT_DATA)
    parser.add_argument("--repositories", type=int, default=10)
    parser.add_argument("--seed", type=int, default=20261030)
    parser.add_argument("--max-tokens", type=int, default=8192)
    parser.add_argument("--report", type=Path, default=DEFAULT_REPORT)
    args = parser.parse_args()

    sampled = sample_repositories(args.data_root, 1, args.repositories, args.seed)
    encoding = tiktoken.get_encoding("cl100k_base")
    config = BuildConfig(max_tokens=args.max_tokens)
    report = {"seed": args.seed, "max_tokens": args.max_tokens, "repositories": []}
    totals = Counter()
    maximum_sample_tokens = 0
    started = time.perf_counter()
    for shard, rows in sampled:
        bodies = load_bodies(shard, rows)
        for row in rows:
            repo, source_errors = make_repo(row, bodies)
            before = time.perf_counter()
            samples = build_samples(repo, config=config, tokenizer=encoding)
            errors, stats = audit_repo(repo, samples, args.max_tokens)
            errors[:0] = source_errors
            record = {
                "repo_id": repo.repo_id,
                "revision_id": repo.revision_id,
                "elapsed_seconds": round(time.perf_counter() - before, 4),
                "stats": stats,
                "errors": errors,
            }
            report["repositories"].append(record)
            maximum_sample_tokens = max(maximum_sample_tokens, stats["max_sample_tokens"])
            additive = {key: value for key, value in stats.items() if key != "max_sample_tokens"}
            totals.update(repositories=1, errors=len(errors), **additive)
            print(repo.repo_id, stats, f"errors={len(errors)}", flush=True)
    totals["elapsed_seconds"] = round(time.perf_counter() - started, 3)
    totals["max_sample_tokens"] = maximum_sample_tokens
    report["totals"] = dict(totals)
    args.report.parent.mkdir(parents=True, exist_ok=True)
    temporary = args.report.with_suffix(args.report.suffix + ".part")
    temporary.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
    temporary.replace(args.report)
    print(json.dumps(report["totals"], indent=2), flush=True)
    if totals["errors"]:
        raise SystemExit(1)


if __name__ == "__main__":
    main()