#!/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 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()