File size: 14,989 Bytes
6a483b5
 
 
 
 
 
 
 
 
 
10032a9
 
6a483b5
 
 
 
 
 
 
 
 
 
 
 
 
 
10032a9
 
6a483b5
10032a9
 
6a483b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10032a9
 
 
 
 
 
 
 
 
 
 
 
6a483b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10032a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a483b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10032a9
 
 
 
 
 
 
6a483b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10032a9
 
 
 
 
 
 
6a483b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10032a9
 
 
6a483b5
 
 
 
 
 
 
 
10032a9
 
6a483b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cbc21b8
 
 
 
 
 
6a483b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
#!/usr/bin/env python3
"""Verify the private published dataset from fresh Hub downloads."""

from __future__ import annotations

import argparse
import hashlib
import json
import re
import shutil
import tempfile
import urllib.request
from collections import Counter
from pathlib import Path
from typing import Any

from datasets import DownloadMode, load_dataset
from huggingface_hub import HfApi, hf_hub_download

from build import (
    HUMANEVAL_REPO,
    HUMANEVAL_REVISION,
    MBPP_CONFIG,
    MBPP_REPO,
    MBPP_REVISION,
    REPO_ID,
    SOURCE_SHA256,
    SOURCE_URL,
    contamination_hits,
    distribution,
    lexical_tokens,
    load_token,
    make_benchmark_indexes,
    normalize_text,
    normalized_pair,
    sha256_file,
)

DATASETS_CACHE = Path.home() / ".cache" / "huggingface" / "datasets"


def assert_messages(row: dict[str, Any]) -> None:
    messages = row["messages"]
    assert isinstance(messages, list), "messages must be a list, not serialized JSON"
    assert len(messages) == 2, "each row must have exactly two messages"
    assert [message["role"] for message in messages] == ["user", "assistant"]
    assert all(isinstance(message, dict) for message in messages)
    assert all(isinstance(message["content"], str) for message in messages)
    assert row["output"].strip(), "output must not be empty or whitespace-only"
    assert messages[1]["content"] == row["output"]
    expected_user = (
        row["instruction"]
        if not row["input"].strip()
        else f"{row['instruction']}\n\n{row['input']}"
    )
    assert messages[0]["content"] == expected_user


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def assert_card_counts(card: str, stats: dict[str, Any]) -> None:
    audit = stats["source_audit"]
    rejects = stats["rejections"]
    splits = stats["splits"]
    overlap = stats["benchmark_overlap_before_filtering"]
    expected_lines = [
        f"| Source rows | {audit['rows']} |",
        f"| Non-empty `input` rows | {audit['input_nonempty']} |",
        f"| Empty `output` rows | {audit['output_empty']} |",
        f"| Exact duplicate instruction rows | {audit['duplicate_instruction_rows_exact']} |",
        f"| Aggressively normalized duplicate instruction rows | {audit['duplicate_instruction_rows_normalized']} |",
        f"| Exact `output == instruction` rows | {audit['output_equals_instruction_exact']} |",
        f"| Normalized `output == instruction` rows | {audit['output_equals_instruction_normalized']} |",
        f"| HumanEval | {stats['benchmarks']['HumanEval']['test_items']} | {overlap['HumanEval']['exact_normalized_rows']} | {overlap['HumanEval']['13gram_rows']} |",
        f"| MBPP (`full`, `test`, field `text`) | {stats['benchmarks']['MBPP']['test_items']} | {overlap['MBPP']['exact_normalized_rows']} | {overlap['MBPP']['13gram_rows']} |",
        f"| Empty output | {rejects['empty_output']} |",
        f"| Benchmark contamination (union) | {rejects['benchmark_contamination_union']} |",
        f"| Duplicate normalized `(instruction, input)` | {rejects['duplicate_normalized_pair']} |",
        f"| Train/test signature purge from train | {rejects['train_test_overlap_from_train']} |",
        f"| **Total removed** | **{rejects['total']}** |",
        f"| train | {splits['train']} |",
        f"| test | {splits['test']} |",
        f"| total | {splits['total']} |",
    ]
    for line in expected_lines:
        assert line in card, f"dataset card is missing measured line: {line}"


def verify(repo_id: str) -> dict[str, Any]:
    token = load_token()
    api = HfApi(token=token)
    info = api.dataset_info(repo_id)
    assert info.private, "Hub repository must be private"
    revision = info.sha

    if DATASETS_CACHE.exists():
        shutil.rmtree(DATASETS_CACHE)
    published = load_dataset(
        repo_id,
        token=token,
        revision=revision,
        download_mode=DownloadMode.FORCE_REDOWNLOAD,
    )
    assert set(published.keys()) == {"train", "test"}
    assert set(published["train"].column_names) == {
        "messages",
        "instruction",
        "input",
        "output",
    }

    remote_paths: dict[str, Path] = {}
    for filename in (
        "data/train.parquet",
        "data/test.parquet",
        "stats.json",
        "README.md",
        "dataset_card.md",
        "rejections.jsonl",
        "validation_report.json",
        "build.py",
        "verify.py",
    ):
        remote_paths[filename] = Path(
            hf_hub_download(
                repo_id,
                filename,
                repo_type="dataset",
                token=token,
                revision=revision,
                force_download=True,
            )
        )

    stats = json.loads(remote_paths["stats.json"].read_text(encoding="utf-8"))
    card = remote_paths["README.md"].read_text(encoding="utf-8")
    assert card == remote_paths["dataset_card.md"].read_text(encoding="utf-8")

    train = published["train"]
    test = published["test"]
    assert len(train) == stats["splits"]["train"]
    assert len(test) == stats["splits"]["test"]
    assert len(train) + len(test) == stats["splits"]["total"]

    for split in (train, test):
        for row in split:
            assert_messages(row)

    train_signatures = {
        normalized_pair(row["instruction"], row["input"]) for row in train
    }
    test_signatures = {
        normalized_pair(row["instruction"], row["input"]) for row in test
    }
    train_test_overlap = train_signatures & test_signatures
    assert not train_test_overlap, "aggressive train/test overlap is not zero"
    train_instruction_signatures = {
        normalize_text(row["instruction"]) for row in train
    }
    test_instruction_signatures = {
        normalize_text(row["instruction"]) for row in test
    }
    train_test_instruction_overlap = (
        train_instruction_signatures & test_instruction_signatures
    )
    assert not train_test_instruction_overlap, (
        "aggressively normalized instruction overlap across train/test is not zero"
    )
    all_rows = list(train) + list(test)
    assert len(train_signatures) == len(train)
    assert len(test_signatures) == len(test)

    humaneval = load_dataset(
        HUMANEVAL_REPO,
        split="test",
        revision=HUMANEVAL_REVISION,
        download_mode=DownloadMode.FORCE_REDOWNLOAD,
    )
    mbpp = load_dataset(
        MBPP_REPO,
        MBPP_CONFIG,
        split="test",
        revision=MBPP_REVISION,
        download_mode=DownloadMode.FORCE_REDOWNLOAD,
    )
    benchmark_items = [
        {"benchmark": "HumanEval", "item_id": str(row["task_id"]), "text": row["prompt"]}
        for row in humaneval
    ] + [
        {"benchmark": "MBPP", "item_id": str(row["task_id"]), "text": row["text"]}
        for row in mbpp
    ]
    exact_index, ngram_index = make_benchmark_indexes(benchmark_items)
    post_filter_counts: Counter[tuple[str, str]] = Counter()
    residual_hits: list[dict[str, Any]] = []
    for row in all_rows:
        hits = contamination_hits(row["instruction"], exact_index, ngram_index)
        for hit in hits:
            post_filter_counts[(hit["benchmark"], hit["criterion"])] += 1
            residual_hits.append(
                {
                    "instruction": row["instruction"],
                    "hit": hit,
                }
            )
    assert not residual_hits, f"benchmark contamination remains: {residual_hits[:3]}"

    with tempfile.TemporaryDirectory(prefix="codealpaca-verify-source-") as temporary:
        source_path = Path(temporary) / "source.parquet"
        with urllib.request.urlopen(SOURCE_URL) as response, source_path.open("wb") as handle:
            shutil.copyfileobj(response, handle)
        source = load_dataset(
            "parquet",
            data_files=str(source_path),
            split="train",
            download_mode=DownloadMode.FORCE_REDOWNLOAD,
        )
        assert sha256(source_path) == SOURCE_SHA256 == stats["source"]["sha256"]
    source_instructions = list(source["instruction"])
    source_inputs = list(source["input"])
    source_outputs = list(source["output"])
    measured_source_audit = {
        "rows": len(source),
        "input_nonempty": sum(bool(value.strip()) for value in source_inputs),
        "output_empty": sum(not bool(value.strip()) for value in source_outputs),
        "duplicate_instruction_rows_exact": len(source_instructions)
        - len(set(source_instructions)),
        "duplicate_instruction_rows_normalized": len(source_instructions)
        - len({normalize_text(value) for value in source_instructions}),
        "output_equals_instruction_exact": sum(
            output == instruction
            for instruction, output in zip(source_instructions, source_outputs)
        ),
        "output_equals_instruction_normalized": sum(
            normalize_text(output) == normalize_text(instruction)
            for instruction, output in zip(source_instructions, source_outputs)
        ),
    }
    assert measured_source_audit == stats["source_audit"]
    assert len(humaneval) == stats["benchmarks"]["HumanEval"]["test_items"]
    assert len(mbpp) == stats["benchmarks"]["MBPP"]["test_items"]

    measured_before_filtering: dict[str, dict[str, set[int]]] = {
        benchmark: {"exact_normalized": set(), "13gram": set()}
        for benchmark in ("HumanEval", "MBPP")
    }
    for source_index, instruction in enumerate(source_instructions):
        for hit in contamination_hits(instruction, exact_index, ngram_index):
            measured_before_filtering[hit["benchmark"]][hit["criterion"]].add(
                source_index
            )
    for benchmark in ("HumanEval", "MBPP"):
        exact_rows = measured_before_filtering[benchmark]["exact_normalized"]
        gram_rows = measured_before_filtering[benchmark]["13gram"]
        assert stats["benchmark_overlap_before_filtering"][benchmark] == {
            "exact_normalized_rows": len(exact_rows),
            "13gram_rows": len(gram_rows),
            "union_rows": len(exact_rows | gram_rows),
        }

    rejection_lines = [
        json.loads(line)
        for line in remote_paths["rejections.jsonl"].read_text(encoding="utf-8").splitlines()
        if line
    ]
    rejection_counts = Counter(row["reason"] for row in rejection_lines)
    assert rejection_counts["empty_output"] == stats["rejections"]["empty_output"]
    assert (
        rejection_counts["benchmark_contamination"]
        == stats["rejections"]["benchmark_contamination_union"]
    )
    assert (
        rejection_counts["duplicate_normalized_pair"]
        == stats["rejections"]["duplicate_normalized_pair"]
    )
    assert (
        rejection_counts["train_test_overlap_from_train"]
        == stats["rejections"]["train_test_overlap_from_train"]
    )
    assert len(rejection_lines) == stats["rejections"]["total"]
    assert len(source) - len(all_rows) == stats["rejections"]["total"]
    measured_rejection_rate = round(
        100 * stats["rejections"]["total"] / len(source), 6
    )
    assert measured_rejection_rate == stats["rejection_rate_percent"]
    measured_test_fraction = round(100 * len(test) / len(all_rows), 6)
    assert measured_test_fraction == stats["splits"]["test_fraction_percent"]

    assert stats["diversity"]["rows_with_nonempty_input"] == sum(
        bool(row["input"].strip()) for row in all_rows
    )
    assert stats["diversity"]["unique_instruction_exact"] == len(
        {row["instruction"] for row in all_rows}
    )
    assert stats["diversity"]["unique_instruction_normalized"] == len(
        {normalize_text(row["instruction"]) for row in all_rows}
    )
    assert stats["diversity"]["unique_normalized_pairs"] == len(
        {
            normalized_pair(row["instruction"], row["input"])
            for row in all_rows
        }
    )
    assert stats["lengths"]["user_tokens"] == distribution(
        [len(lexical_tokens(row["messages"][0]["content"])) for row in all_rows]
    )
    assert stats["lengths"]["assistant_tokens"] == distribution(
        [len(lexical_tokens(row["messages"][1]["content"])) for row in all_rows]
    )
    assert stats["post_build_checks"]["train_test_normalized_pair_overlap"] == 0

    for filename in ("data/train.parquet", "data/test.parquet", "rejections.jsonl"):
        assert sha256(remote_paths[filename]) == stats["files"][filename]["sha256"]
        assert remote_paths[filename].stat().st_size == stats["files"][filename]["bytes"]

    assert_card_counts(card, stats)
    validation_report = json.loads(
        remote_paths["validation_report.json"].read_text(encoding="utf-8")
    )
    assert validation_report["status"] == "passed"
    assert validation_report["rejections_by_reason"] == stats["rejections"]

    result = {
        "status": "passed",
        "repo_id": repo_id,
        "revision": revision,
        "private": info.private,
        "fresh_dataset_cache_removed": True,
        "splits": {"train": len(train), "test": len(test)},
        "train_test_aggressive_overlap": len(train_test_overlap),
        "train_test_normalized_instruction_overlap": len(
            train_test_instruction_overlap
        ),
        "benchmark_overlap_after_filtering": {
            "HumanEval": {"exact_normalized_rows": 0, "13gram_rows": 0},
            "MBPP": {"exact_normalized_rows": 0, "13gram_rows": 0},
        },
        "typed_messages": True,
        "strict_user_assistant_alternation": True,
        "nonempty_outputs": True,
        "card_counts_match_remote_data": True,
        "source_audit_matches_fresh_source": True,
        "prefilter_overlap_counts_match_fresh_source": True,
        "remote_hashes_match_stats": True,
    }
    print(json.dumps(result, indent=2))
    return result


def instantiate_sft_trainer(repo_id: str) -> None:
    """Optional smoke test requiring TRL, Torch, and a model checkpoint."""
    from trl import SFTConfig, SFTTrainer

    token = load_token()
    dataset = load_dataset(repo_id, token=token, split="train[:2]")
    output_dir = Path(__file__).resolve().parent / ".sft-smoke-output"
    trainer = SFTTrainer(
        model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
        train_dataset=dataset,
        args=SFTConfig(
            output_dir=str(output_dir),
            max_length=256,
            use_cpu=True,
            report_to="none",
        ),
    )
    assert trainer.train_dataset is not None
    print("SFTTrainer construction: passed")


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--repo-id", default=REPO_ID)
    parser.add_argument("--sft-smoke", action="store_true")
    args = parser.parse_args()
    verify(args.repo_id)
    if args.sft_smoke:
        instantiate_sft_trainer(args.repo_id)


if __name__ == "__main__":
    main()