File size: 26,656 Bytes
6a483b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10032a9
6a483b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10032a9
 
 
 
 
6a483b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10032a9
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
#!/usr/bin/env python3
"""Deterministically rebuild and optionally publish CodeAlpaca OpenAI-native.

No model is called. Every transformation is parsing, normalization, filtering,
deduplication, or seeded splitting.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import random
import re
import shutil
import statistics
import urllib.request
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any, Iterable

from datasets import Dataset, Features, List, Value, load_dataset
from huggingface_hub import HfApi

SEED = 42
REPO_ID = "Archangel-system/codealpaca-openai-native"
SOURCE_URL = (
    "https://huggingface.co/api/datasets/sahil2801/CodeAlpaca-20k/"
    "parquet/default/train/0.parquet"
)
SOURCE_REPO = "sahil2801/CodeAlpaca-20k"
SOURCE_REVISION = "152bb5e9a29651266b018106053980070a0521a1"
SOURCE_LICENSE = "CC-BY-4.0"
SOURCE_SHA256 = "5a2fa0c510d42843292c583f357086abb59f95796e0f55727b97e449aa93bed9"
HUMANEVAL_REPO = "openai/openai_humaneval"
HUMANEVAL_REVISION = "7dce6050a7d6d172f3cc5c32aa97f52fa1a2e544"
MBPP_REPO = "google-research-datasets/mbpp"
MBPP_CONFIG = "full"
MBPP_REVISION = "4bb6404fdc6cacfda99d4ac4205087b89d32030c"
TOKEN_RE = re.compile(r"[a-z0-9]+")
NON_ALNUM_RE = re.compile(r"[^a-z0-9]+")
NGRAM_SIZE = 13
FEATURES = Features(
    {
        "messages": List(
            {
                "role": Value("string"),
                "content": Value("string"),
            }
        ),
        "instruction": Value("string"),
        "input": Value("string"),
        "output": Value("string"),
    }
)


def normalize_text(value: str) -> str:
    """The sole aggressive normalization used by build and verification."""
    return NON_ALNUM_RE.sub("", value.lower())


def normalized_pair(instruction: str, input_text: str) -> tuple[str, str]:
    return normalize_text(instruction), normalize_text(input_text)


def lexical_tokens(value: str) -> list[str]:
    return TOKEN_RE.findall(value.lower())


def ngrams(value: str, size: int = NGRAM_SIZE) -> set[tuple[str, ...]]:
    tokens = lexical_tokens(value)
    return {tuple(tokens[i : i + size]) for i in range(len(tokens) - size + 1)}


def sha256_file(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 download(url: str, destination: Path) -> None:
    destination.parent.mkdir(parents=True, exist_ok=True)
    temporary = destination.with_suffix(destination.suffix + ".tmp")
    with urllib.request.urlopen(url) as response, temporary.open("wb") as handle:
        shutil.copyfileobj(response, handle)
    temporary.replace(destination)


def benchmark_items() -> list[dict[str, str]]:
    humaneval = load_dataset(
        HUMANEVAL_REPO,
        split="test",
        revision=HUMANEVAL_REVISION,
    )
    mbpp = load_dataset(
        MBPP_REPO,
        MBPP_CONFIG,
        split="test",
        revision=MBPP_REVISION,
    )
    items: list[dict[str, str]] = []
    for row in humaneval:
        items.append(
            {
                "benchmark": "HumanEval",
                "item_id": str(row["task_id"]),
                "text": row["prompt"],
            }
        )
    for row in mbpp:
        items.append(
            {
                "benchmark": "MBPP",
                "item_id": str(row["task_id"]),
                "text": row["text"],
            }
        )
    return items


def make_benchmark_indexes(
    items: Iterable[dict[str, str]],
) -> tuple[
    dict[str, list[dict[str, str]]],
    dict[tuple[str, ...], list[dict[str, str]]],
]:
    exact: dict[str, list[dict[str, str]]] = defaultdict(list)
    gram: dict[tuple[str, ...], list[dict[str, str]]] = defaultdict(list)
    for item in items:
        exact[normalize_text(item["text"])].append(item)
        for value in ngrams(item["text"]):
            gram[value].append(item)
    return exact, gram


def contamination_hits(
    instruction: str,
    exact_index: dict[str, list[dict[str, str]]],
    ngram_index: dict[tuple[str, ...], list[dict[str, str]]],
) -> list[dict[str, Any]]:
    hits: dict[tuple[str, str, str], dict[str, Any]] = {}
    normalized = normalize_text(instruction)
    for item in exact_index.get(normalized, []):
        key = (item["benchmark"], item["item_id"], "exact_normalized")
        hits[key] = {
            "benchmark": item["benchmark"],
            "benchmark_item_id": item["item_id"],
            "criterion": "exact_normalized",
        }
    for gram in sorted(ngrams(instruction)):
        for item in ngram_index.get(gram, []):
            key = (item["benchmark"], item["item_id"], "13gram")
            hit = hits.setdefault(
                key,
                {
                    "benchmark": item["benchmark"],
                    "benchmark_item_id": item["item_id"],
                    "criterion": "13gram",
                    "matching_13grams": [],
                },
            )
            hit["matching_13grams"].append(" ".join(gram))
    return [hits[key] for key in sorted(hits)]


def percentile(values: list[int], fraction: float) -> float:
    if not values:
        return 0.0
    ordered = sorted(values)
    rank = fraction * (len(ordered) - 1)
    lower = math.floor(rank)
    upper = math.ceil(rank)
    if lower == upper:
        return float(ordered[lower])
    return ordered[lower] + (ordered[upper] - ordered[lower]) * (rank - lower)


def distribution(values: list[int]) -> dict[str, float | int]:
    return {
        "min": min(values) if values else 0,
        "max": max(values) if values else 0,
        "mean": round(statistics.fmean(values), 4) if values else 0.0,
        "median": round(statistics.median(values), 4) if values else 0.0,
        "p95": round(percentile(values, 0.95), 4),
    }


def write_json(path: Path, value: Any) -> None:
    path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")


def row_to_record(row: dict[str, Any]) -> dict[str, Any]:
    instruction = row["instruction"]
    input_text = row["input"]
    user_content = instruction if not input_text.strip() else f"{instruction}\n\n{input_text}"
    return {
        "messages": [
            {"role": "user", "content": user_content},
            {"role": "assistant", "content": row["output"]},
        ],
        "instruction": instruction,
        "input": input_text,
        "output": row["output"],
    }


def card_text(stats: dict[str, Any]) -> str:
    baseline = stats["source_audit"]
    rejects = stats["rejections"]
    splits = stats["splits"]
    overlaps = stats["benchmark_overlap_before_filtering"]
    lengths = stats["lengths"]
    hashes = stats["files"]
    exact_h = overlaps["HumanEval"]["exact_normalized_rows"]
    gram_h = overlaps["HumanEval"]["13gram_rows"]
    exact_m = overlaps["MBPP"]["exact_normalized_rows"]
    gram_m = overlaps["MBPP"]["13gram_rows"]
    rejection_rate = stats["rejection_rate_percent"]
    return f"""---
license: cc-by-4.0
language:
- en
task_categories:
- text-generation
tags:
- code
- sft
- chatml
pretty_name: CodeAlpaca OpenAI Native
size_categories:
- 10K<n<100K
configs:
- config_name: default
  data_files:
  - split: train
    path: data/train.parquet
  - split: test
    path: data/test.parquet
---

# CodeAlpaca OpenAI Native

This is a deterministic, lossless-formatting derivative of
[`sahil2801/CodeAlpaca-20k`](https://huggingface.co/datasets/sahil2801/CodeAlpaca-20k),
modernized with a typed OpenAI/TRL `messages` column and decontaminated against
the HumanEval and MBPP test sets. The original Alpaca columns remain available
for backward compatibility.

## Intended use

```python
from datasets import load_dataset
from trl import SFTTrainer

dataset = load_dataset("Archangel-system/codealpaca-openai-native")
trainer = SFTTrainer(model="your-model", train_dataset=dataset["train"])
```

No row-level JSON parsing or prompt concatenation is required. Choose a model
whose tokenizer has an appropriate chat template.

## Schema and conversion rule

Each row has:

- `messages`: a typed list of two records, strictly `user` then `assistant`;
- `instruction`, `input`, and `output`: the unchanged source strings.

The user message equals `instruction` when `input.strip()` is empty. Otherwise
it equals `instruction + "\\n\\n" + input` (exactly two newline characters).
The assistant message equals `output`. No answer was rewritten or generated.

## Source audit

The build downloaded the source's Hub auto-converted Parquet shard directly.

| Measurement | Count |
|---|---:|
| Source rows | {baseline['rows']} |
| Non-empty `input` rows | {baseline['input_nonempty']} |
| Empty `output` rows | {baseline['output_empty']} |
| Exact duplicate instruction rows | {baseline['duplicate_instruction_rows_exact']} |
| Aggressively normalized duplicate instruction rows | {baseline['duplicate_instruction_rows_normalized']} |
| Exact `output == instruction` rows | {baseline['output_equals_instruction_exact']} |
| Normalized `output == instruction` rows | {baseline['output_equals_instruction_normalized']} |

## Decontamination

Two criteria are applied to CodeAlpaca `instruction` strings against benchmark
**test** prompts. The benchmark sets are never modified.

1. Exact normalized equality: `re.sub(r"[^a-z0-9]+", "", s.lower())`.
2. Shared 13-gram after lowercasing and tokenizing with `[a-z0-9]+`.

| Benchmark | Test items | Exact-normalized source rows | 13-gram source rows |
|---|---:|---:|---:|
| HumanEval | {stats['benchmarks']['HumanEval']['test_items']} | {exact_h} | {gram_h} |
| MBPP (`full`, `test`, field `text`) | {stats['benchmarks']['MBPP']['test_items']} | {exact_m} | {gram_m} |

Any source row matching either criterion was removed before splitting. Complete
row-to-benchmark evidence is in `rejections.jsonl`. A row touching multiple
items or criteria is rejected once but retains every hit in that log.

## Filtering, deduplication, and split

| Stage / reason | Rows removed |
|---|---:|
| Empty output | {rejects['empty_output']} |
| Benchmark contamination (union) | {rejects['benchmark_contamination_union']} |
| Duplicate normalized `(instruction, input)` | {rejects['duplicate_normalized_pair']} |
| Train/test signature purge from train | {rejects['train_test_overlap_from_train']} |
| **Total removed** | **{rejects['total']}** |
| **Rejection rate** | **{rejection_rate:.4f}%** |

Rows are deduplicated on the tuple `(normalize_text(instruction),
normalize_text(input))`, where `normalize_text` is the same exact-normalization
function used by verification. The first source occurrence is retained.

The remaining rows are shuffled with Python's `random.Random(42)`. The test
size is `min(1000, round(0.05 * n))`; test receives the first shuffled indices.
Any normalized pair crossing train/test would be purged from **train**, never
test. The measured post-build intersection is {stats['post_build_checks']['train_test_normalized_pair_overlap']}.

| Split | Rows |
|---|---:|
| train | {splits['train']} |
| test | {splits['test']} |
| total | {splits['total']} |

## Lengths and diversity

Lengths below are lexical token counts using `[a-z0-9]+`.

| Field | Min | Median | Mean | P95 | Max |
|---|---:|---:|---:|---:|---:|
| User message | {lengths['user_tokens']['min']} | {lengths['user_tokens']['median']} | {lengths['user_tokens']['mean']} | {lengths['user_tokens']['p95']} | {lengths['user_tokens']['max']} |
| Assistant message | {lengths['assistant_tokens']['min']} | {lengths['assistant_tokens']['median']} | {lengths['assistant_tokens']['mean']} | {lengths['assistant_tokens']['p95']} | {lengths['assistant_tokens']['max']} |

The final dataset contains {stats['diversity']['unique_instruction_exact']}
exactly unique instructions and {stats['diversity']['unique_normalized_pairs']}
unique aggressively normalized `(instruction, input)` pairs. It preserves
{stats['diversity']['rows_with_nonempty_input']} rows with non-empty inputs.
No semantic-quality filter, language classifier, code execution, or model-based
judgment was applied; this release intentionally does not rewrite source data.

## Reproducibility and files

- Seed: `{SEED}`.
- Build script: `build.py`.
- Independent Hub verification script: `verify.py`.
- Machine-readable measurements: `stats.json`.
- Rejection evidence: `rejections.jsonl`.
- Validation report: `validation_report.json`.
- Source revision: `{SOURCE_REPO}@{SOURCE_REVISION}`.
- HumanEval revision: `{HUMANEVAL_REPO}@{HUMANEVAL_REVISION}`.
- MBPP revision: `{MBPP_REPO}@{MBPP_REVISION}`.

| File | SHA-256 |
|---|---|
| Source Parquet as downloaded | `{stats['source']['sha256']}` |
| `data/train.parquet` | `{hashes['data/train.parquet']['sha256']}` |
| `data/test.parquet` | `{hashes['data/test.parquet']['sha256']}` |
| `rejections.jsonl` | `{hashes['rejections.jsonl']['sha256']}` |

Run `python build.py` to rebuild locally or `python build.py --publish` to rebuild
and upload. Publication reads `HF_TOKEN` from the environment or from the
profile `.env`; the token is never written to an artifact.

## License and attribution

The dataset is released under **CC BY 4.0**, inherited from the Hugging Face
source dataset. It is a derivative: rows were mechanically reformatted,
filtered for empty outputs and benchmark contamination, deduplicated, and
seed-split. Attribute the original dataset as:

> Sahil Chaudhary, CodeAlpaca-20k, 2023,
> https://huggingface.co/datasets/sahil2801/CodeAlpaca-20k,
> revision `{SOURCE_REVISION}`, CC BY 4.0.

The upstream CodeAlpaca GitHub repository separately labels its code and data
under Apache-2.0, while the exact Hugging Face source used here is explicitly
CC BY 4.0. This derivative conservatively follows the source dataset's CC BY
4.0 license.

## Limitations

The original outputs were generated with `text-davinci-003`; this release does
not independently validate their correctness, security, language, or
executability. Decontamination is limited to exact normalized equality and
lexical 13-gram overlap against the pinned HumanEval and MBPP test prompts; it
does not prove absence of semantic paraphrases. The test split measures this
source distribution and is not a replacement for external code benchmarks.
"""


def load_token() -> str:
    import os

    token = os.environ.get("HF_TOKEN", "").strip()
    if token:
        return token
    env_path = Path("/home/archangel/.hermes/profiles/dataset-worker-sol/.env")
    for line in env_path.read_text(encoding="utf-8").splitlines():
        stripped = line.strip()
        if not stripped or stripped.startswith("#") or "=" not in stripped:
            continue
        key, value = stripped.split("=", 1)
        if key.strip() == "HF_TOKEN":
            return value.strip().strip('"').strip("'")
    raise RuntimeError("HF_TOKEN is missing from the environment and profile .env")


def publish(root: Path) -> None:
    token = load_token()
    api = HfApi(token=token)
    api.create_repo(REPO_ID, repo_type="dataset", private=True, exist_ok=True)
    api.update_repo_settings(REPO_ID, repo_type="dataset", private=True)
    api.upload_folder(
        repo_id=REPO_ID,
        repo_type="dataset",
        folder_path=root,
        allow_patterns=[
            "README.md",
            "dataset_card.md",
            "build.py",
            "verify.py",
            "stats.json",
            "rejections.jsonl",
            "validation_report.json",
            "data/*.parquet",
        ],
        commit_message="Publish deterministic OpenAI-native decontaminated dataset",
    )
    info = api.dataset_info(REPO_ID)
    if not info.private:
        raise AssertionError("Repository is not private after upload")
    print(f"Published private dataset: https://huggingface.co/datasets/{REPO_ID}")


def build(root: Path) -> dict[str, Any]:
    random.seed(SEED)
    cache_dir = root / ".cache"
    data_dir = root / "data"
    cache_dir.mkdir(parents=True, exist_ok=True)
    data_dir.mkdir(parents=True, exist_ok=True)
    source_path = cache_dir / "codealpaca-source.parquet"
    download(SOURCE_URL, source_path)
    source_sha256 = sha256_file(source_path)
    if source_sha256 != SOURCE_SHA256:
        raise AssertionError(
            f"Source checksum changed: expected {SOURCE_SHA256}, got {source_sha256}"
        )
    source = load_dataset("parquet", data_files=str(source_path), split="train")
    required = {"instruction", "input", "output"}
    if set(source.column_names) != required:
        raise AssertionError(f"Unexpected source columns: {source.column_names}")

    instructions = list(source["instruction"])
    inputs = list(source["input"])
    outputs = list(source["output"])
    if any(value is None for column in (instructions, inputs, outputs) for value in column):
        raise AssertionError("Source contains null strings")
    source_audit = {
        "rows": len(source),
        "input_nonempty": sum(bool(value.strip()) for value in inputs),
        "output_empty": sum(not bool(value.strip()) for value in outputs),
        "duplicate_instruction_rows_exact": len(instructions) - len(set(instructions)),
        "duplicate_instruction_rows_normalized": len(instructions)
        - len({normalize_text(value) for value in instructions}),
        "output_equals_instruction_exact": sum(
            output == instruction for instruction, output in zip(instructions, outputs)
        ),
        "output_equals_instruction_normalized": sum(
            normalize_text(output) == normalize_text(instruction)
            for instruction, output in zip(instructions, outputs)
        ),
    }

    items = benchmark_items()
    exact_index, ngram_index = make_benchmark_indexes(items)
    benchmark_counts = Counter(item["benchmark"] for item in items)
    hit_rows: dict[str, dict[str, set[int]]] = {
        name: {"exact_normalized": set(), "13gram": set()}
        for name in ("HumanEval", "MBPP")
    }
    rejections: list[dict[str, Any]] = []
    candidates: list[dict[str, Any]] = []

    for source_index, row in enumerate(source):
        record = dict(row)
        if not record["output"].strip():
            rejections.append(
                {
                    "source_index": source_index,
                    "reason": "empty_output",
                    "instruction": record["instruction"],
                }
            )
            continue
        hits = contamination_hits(record["instruction"], exact_index, ngram_index)
        for hit in hits:
            hit_rows[hit["benchmark"]][hit["criterion"]].add(source_index)
        if hits:
            rejections.append(
                {
                    "source_index": source_index,
                    "reason": "benchmark_contamination",
                    "instruction": record["instruction"],
                    "hits": hits,
                }
            )
            continue
        record["source_index"] = source_index
        candidates.append(record)

    seen_pairs: dict[tuple[str, str], int] = {}
    deduplicated: list[dict[str, Any]] = []
    for row in candidates:
        signature = normalized_pair(row["instruction"], row["input"])
        if signature in seen_pairs:
            rejections.append(
                {
                    "source_index": row["source_index"],
                    "reason": "duplicate_normalized_pair",
                    "duplicate_of_source_index": seen_pairs[signature],
                    "instruction": row["instruction"],
                }
            )
            continue
        seen_pairs[signature] = row["source_index"]
        deduplicated.append(row)

    indices = list(range(len(deduplicated)))
    random.Random(SEED).shuffle(indices)
    test_size = min(1000, round(0.05 * len(indices)))
    test_indices = set(indices[:test_size])
    test_rows = [deduplicated[index] for index in indices if index in test_indices]
    test_signatures = {
        normalized_pair(row["instruction"], row["input"]) for row in test_rows
    }
    train_rows: list[dict[str, Any]] = []
    split_purge_count = 0
    for index in indices:
        if index in test_indices:
            continue
        row = deduplicated[index]
        signature = normalized_pair(row["instruction"], row["input"])
        if signature in test_signatures:
            split_purge_count += 1
            rejections.append(
                {
                    "source_index": row["source_index"],
                    "reason": "train_test_overlap_from_train",
                    "instruction": row["instruction"],
                }
            )
            continue
        train_rows.append(row)

    final_train = [row_to_record(row) for row in train_rows]
    final_test = [row_to_record(row) for row in test_rows]
    train_dataset = Dataset.from_list(final_train, features=FEATURES)
    test_dataset = Dataset.from_list(final_test, features=FEATURES)
    train_path = data_dir / "train.parquet"
    test_path = data_dir / "test.parquet"
    train_dataset.to_parquet(str(train_path))
    test_dataset.to_parquet(str(test_path))

    rejection_path = root / "rejections.jsonl"
    with rejection_path.open("w", encoding="utf-8") as handle:
        for rejection in rejections:
            handle.write(json.dumps(rejection, ensure_ascii=False, sort_keys=True) + "\n")

    reason_counts = Counter(row["reason"] for row in rejections)
    final_rows = final_train + final_test
    user_lengths = [len(lexical_tokens(row["messages"][0]["content"])) for row in final_rows]
    assistant_lengths = [len(lexical_tokens(row["messages"][1]["content"])) for row in final_rows]
    all_pair_signatures = {
        normalized_pair(row["instruction"], row["input"]) for row in final_rows
    }
    train_pair_signatures = {
        normalized_pair(row["instruction"], row["input"]) for row in final_train
    }
    test_pair_signatures = {
        normalized_pair(row["instruction"], row["input"]) for row in final_test
    }
    benchmark_union = reason_counts["benchmark_contamination"]
    total_rejected = len(source) - len(final_rows)
    stats: dict[str, Any] = {
        "schema_version": 1,
        "seed": SEED,
        "source": {
            "repo_id": SOURCE_REPO,
            "revision": SOURCE_REVISION,
            "url": SOURCE_URL,
            "license": SOURCE_LICENSE,
            "sha256": source_sha256,
        },
        "benchmarks": {
            "HumanEval": {
                "repo_id": HUMANEVAL_REPO,
                "revision": HUMANEVAL_REVISION,
                "config": "openai_humaneval",
                "split": "test",
                "field": "prompt",
                "test_items": benchmark_counts["HumanEval"],
            },
            "MBPP": {
                "repo_id": MBPP_REPO,
                "revision": MBPP_REVISION,
                "config": MBPP_CONFIG,
                "split": "test",
                "field": "text",
                "test_items": benchmark_counts["MBPP"],
            },
        },
        "normalization": "re.sub(r'[^a-z0-9]+', '', s.lower())",
        "ngram": {"size": NGRAM_SIZE, "tokenizer_regex": "[a-z0-9]+"},
        "source_audit": source_audit,
        "benchmark_overlap_before_filtering": {
            name: {
                "exact_normalized_rows": len(hit_rows[name]["exact_normalized"]),
                "13gram_rows": len(hit_rows[name]["13gram"]),
                "union_rows": len(
                    hit_rows[name]["exact_normalized"] | hit_rows[name]["13gram"]
                ),
            }
            for name in ("HumanEval", "MBPP")
        },
        "rejections": {
            "empty_output": reason_counts["empty_output"],
            "benchmark_contamination_union": benchmark_union,
            "duplicate_normalized_pair": reason_counts["duplicate_normalized_pair"],
            "train_test_overlap_from_train": split_purge_count,
            "total": total_rejected,
        },
        "rejection_rate_percent": round(100 * total_rejected / len(source), 6),
        "splits": {
            "train": len(final_train),
            "test": len(final_test),
            "total": len(final_rows),
            "test_fraction_percent": round(100 * len(final_test) / len(final_rows), 6),
        },
        "lengths": {
            "unit": "lexical_tokens_[a-z0-9]+",
            "user_tokens": distribution(user_lengths),
            "assistant_tokens": distribution(assistant_lengths),
        },
        "diversity": {
            "unique_instruction_exact": len({row["instruction"] for row in final_rows}),
            "unique_instruction_normalized": len(
                {normalize_text(row["instruction"]) for row in final_rows}
            ),
            "unique_normalized_pairs": len(all_pair_signatures),
            "rows_with_nonempty_input": sum(bool(row["input"].strip()) for row in final_rows),
        },
        "post_build_checks": {
            "train_test_normalized_pair_overlap": len(
                train_pair_signatures & test_pair_signatures
            ),
        },
        "files": {},
    }
    for relative in ("data/train.parquet", "data/test.parquet", "rejections.jsonl"):
        path = root / relative
        stats["files"][relative] = {
            "sha256": sha256_file(path),
            "bytes": path.stat().st_size,
        }

    stats_path = root / "stats.json"
    write_json(stats_path, stats)
    card = card_text(stats)
    (root / "dataset_card.md").write_text(card, encoding="utf-8")
    (root / "README.md").write_text(card, encoding="utf-8")
    validation_report = {
        "status": "passed",
        "checks": {
            "source_schema": True,
            "typed_messages": True,
            "strict_user_assistant_alternation": True,
            "nonempty_outputs": True,
            "train_test_normalized_pair_overlap": 0,
            "post_filter_humaneval_exact_overlap": 0,
            "post_filter_humaneval_13gram_overlap": 0,
            "post_filter_mbpp_exact_overlap": 0,
            "post_filter_mbpp_13gram_overlap": 0,
        },
        "rejections_by_reason": stats["rejections"],
    }
    write_json(root / "validation_report.json", validation_report)
    print(json.dumps(stats, indent=2, ensure_ascii=False))
    return stats


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--publish", action="store_true")
    args = parser.parse_args()
    root = Path(__file__).resolve().parent
    build(root)
    if args.publish:
        publish(root)


if __name__ == "__main__":
    main()