diff --git a/examples/data_quality_ablation/README.md b/examples/data_quality_ablation/README.md new file mode 100644 index 0000000..aead1ab --- /dev/null +++ b/examples/data_quality_ablation/README.md @@ -0,0 +1,54 @@ +# Data-quality ablation example + +This example shows how to compare preprocessing choices with the same input +corpus and record the data-side consequences reproducibly. + +## Conditions + +| Condition | Steps | +|---|---| +| `raw` | Validate JSONL schema and copy without text transformations | +| `clean` | Conservative Unicode/text cleanup | +| `clean_dedupe` | Clean, then remove exact duplicate text | +| `full_filter` | Clean, exact deduplication, then configurable length/repetition filtering | + +## Run + +From the repository root after installing the package: + +```bash +pip install -e ".[dev]" +python examples/data_quality_ablation/run_ablation.py \ + --input examples/data_quality_ablation/sample.jsonl \ + --output-dir runs/data_quality_ablation \ + --min-chars 30 \ + --max-chars 1000 \ + --min-unique-word-ratio 0.30 \ + --seed 42 +``` + +Outputs include one `corpus.jsonl` and `manifest.json` per condition, a +filter rejection report for `full_filter`, and `ablation_summary.json` with +corpus statistics and SHA-256 checksums. + +## Interpretation and limitations + +This is a **data-preparation ablation**, not evidence that a filter improves +model quality. The script does not train or evaluate a language model. The +summary explicitly marks model evaluation as not run. + +For a downstream model-quality experiment: + +1. Create a fixed, independently held-out validation/test set before training. + Do not run the ablation filters on that held-out set. +2. Keep the base model, tokenizer, training token budget, sequence length, + optimizer, learning-rate schedule, training steps, and evaluation protocol + fixed across conditions where possible. +3. Run each condition with the same held-out examples; record model and + tokenizer revisions, training config, seed, hardware, and metrics. +4. Compare both a fixed-token-budget setting and an all-retained-data setting; + they answer different questions. +5. Inspect rejected examples and report negative or inconclusive results. + +The included sample data is synthetic and only demonstrates the pipeline. It +must not be used to draw conclusions about real-world model performance. diff --git a/examples/data_quality_ablation/run_ablation.py b/examples/data_quality_ablation/run_ablation.py new file mode 100644 index 0000000..3cebb20 --- /dev/null +++ b/examples/data_quality_ablation/run_ablation.py @@ -0,0 +1,186 @@ +"""Run a reproducible data-preparation ablation without training a model. + +This script compares raw, cleaned, cleaned+deduplicated, and fully filtered +corpora. It reports corpus-level effects only; it does not claim that any +condition improves model quality. +""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any, Iterator + +from llm_data_lab.pipeline import ( + build_run_manifest, + clean_jsonl, + corpus_stats, + deduplicate_jsonl, + filter_jsonl, + read_jsonl, + sha256_file, + write_jsonl, +) + + +def _copy_validated(source: Path, destination: Path, text_field: str) -> dict[str, int]: + """Validate JSONL rows and copy them without changing text.""" + count = 0 + + def rows() -> Iterator[dict[str, Any]]: + nonlocal count + for index, row in enumerate(read_jsonl(source), 1): + if not isinstance(row.get(text_field), str): + raise TypeError(f"Record {index}: {text_field!r} must be a string") + count += 1 + yield row + + written = write_jsonl(destination, rows()) + return {"input_documents": count, "output_documents": written} + + +def run_ablation( + input_path: str | Path, + output_dir: str | Path, + *, + text_field: str = "text", + min_chars: int = 200, + max_chars: int = 100_000, + min_unique_word_ratio: float = 0.30, + seed: int = 42, +) -> dict[str, Any]: + source = Path(input_path) + out = Path(output_dir) + out.mkdir(parents=True, exist_ok=True) + source_hash = sha256_file(source) + input_documents = sum(1 for _ in read_jsonl(source)) + + conditions = { + "raw": {"description": "Schema validation only; no text transformations."}, + "clean": {"description": "Conservative Unicode/text cleanup."}, + "clean_dedupe": {"description": "Cleaning followed by exact deduplication."}, + "full_filter": { + "description": "Cleaning, exact deduplication, then configured quality filters." + }, + } + summary: dict[str, Any] = { + "experiment": "data_quality_ablation", + "input": { + "path": str(source), + "sha256": source_hash, + "documents": input_documents, + }, + "seed": seed, + "text_field": text_field, + "filter_config": { + "min_chars": min_chars, + "max_chars": max_chars, + "min_unique_word_ratio": min_unique_word_ratio, + }, + "scope_note": ( + "Corpus-level ablation only. No model was trained or evaluated by this script. " + "Use the same independently held-out validation set and matched training settings " + "for downstream model comparisons." + ), + "conditions": {}, + } + + for name, config in conditions.items(): + condition_dir = out / name + condition_dir.mkdir(parents=True, exist_ok=True) + corpus = condition_dir / "corpus.jsonl" + stages: dict[str, Any] = {} + + if name == "raw": + stages["copy"] = _copy_validated(source, corpus, text_field) + else: + cleaned = condition_dir / "cleaned.jsonl" + stages["clean"] = clean_jsonl(source, cleaned, text_field=text_field) + if name == "clean": + cleaned.replace(corpus) + else: + deduped = condition_dir / "deduplicated.jsonl" + stages["dedupe"] = deduplicate_jsonl( + cleaned, deduped, text_field=text_field + ) + if name == "clean_dedupe": + deduped.replace(corpus) + else: + stages["filter"] = filter_jsonl( + deduped, + corpus, + text_field=text_field, + min_chars=min_chars, + max_chars=max_chars, + min_unique_word_ratio=min_unique_word_ratio, + report_path=condition_dir / "filter_report.json", + ) + + stats = corpus_stats(corpus, text_field=text_field) + manifest = build_run_manifest( + corpus, + dataset_identifier=f"{source} [{name}]", + pipeline_config={ + "condition": name, + "description": config["description"], + "text_field": text_field, + "filter_config": summary["filter_config"] if name == "full_filter" else {}, + "stages": stages, + }, + seed=seed, + run_name=f"data-quality-{name}", + evaluation_config={ + "status": "not_run", + "note": "This data-preparation example does not train or evaluate a model.", + }, + ) + manifest_path = condition_dir / "manifest.json" + manifest_path.write_text( + json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", + encoding="utf-8", + ) + summary["conditions"][name] = { + "description": config["description"], + "corpus_path": str(corpus), + "corpus_sha256": sha256_file(corpus), + "documents_retained": stats["documents"], + "retention_rate_vs_input": ( + stats["documents"] / input_documents if input_documents else 0.0 + ), + "corpus_stats": stats, + "stages": stages, + "manifest_path": str(manifest_path), + } + + summary_path = out / "ablation_summary.json" + summary_path.write_text( + json.dumps(summary, indent=2, ensure_ascii=False) + "\n", + encoding="utf-8", + ) + return summary + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--input", required=True, help="Input JSONL corpus.") + parser.add_argument("--output-dir", required=True, help="Directory for conditions and reports.") + parser.add_argument("--text-field", default="text") + parser.add_argument("--min-chars", type=int, default=200) + parser.add_argument("--max-chars", type=int, default=100_000) + parser.add_argument("--min-unique-word-ratio", type=float, default=0.30) + parser.add_argument("--seed", type=int, default=42) + args = parser.parse_args() + summary = run_ablation( + args.input, + args.output_dir, + text_field=args.text_field, + min_chars=args.min_chars, + max_chars=args.max_chars, + min_unique_word_ratio=args.min_unique_word_ratio, + seed=args.seed, + ) + print(json.dumps(summary, indent=2, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/examples/data_quality_ablation/sample.jsonl b/examples/data_quality_ablation/sample.jsonl new file mode 100644 index 0000000..4d82120 --- /dev/null +++ b/examples/data_quality_ablation/sample.jsonl @@ -0,0 +1,10 @@ +{"text":"A language model learns statistical patterns from the text it sees during training. Careful dataset preparation can reduce noise and improve reproducibility.","source":"synthetic-demo","kind":"useful"} +{"text":"A language model learns statistical patterns from the text it sees during training. Careful dataset preparation can reduce noise and improve reproducibility.","source":"synthetic-duplicate","kind":"duplicate"} +{"text":"The training corpus should preserve document provenance, license details, and stable checksums. Researchers should record every transformation applied to the data.","source":"synthetic-demo","kind":"useful"} +{"text":"ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha","source":"synthetic-demo","kind":"repetitive"} +{"text":"Short note.","source":"synthetic-demo","kind":"short"} +{"text":"Validation data must remain separate from training data. Exact duplicates should be removed before splitting, and evaluation prompts should not be included in training.","source":"synthetic-demo","kind":"useful"} +{"text":"Text normalization should be conservative and should not silently change the meaning of a document. Every filter should report how many examples it rejects.","source":"synthetic-demo","kind":"useful"} +{"text":"Model perplexity depends on tokenization and evaluation protocol. Comparing different tokenizers using raw perplexity alone can be misleading.","source":"synthetic-demo","kind":"useful"} +{"text":"bad bad bad bad bad bad bad bad bad bad bad bad bad bad bad bad bad bad","source":"synthetic-demo","kind":"repetitive"} +{"text":"When preparing a corpus, researchers should inspect both retained and rejected examples. Heuristics can remove valid text, especially in multilingual or informal datasets.","source":"synthetic-demo","kind":"useful"} diff --git a/src/llm_data_lab/cli.py b/src/llm_data_lab/cli.py index 9c9194e..c170cdc 100644 --- a/src/llm_data_lab/cli.py +++ b/src/llm_data_lab/cli.py @@ -8,7 +8,11 @@ from typing import Any from llm_data_lab.pipeline import ( - clean_jsonl, corpus_stats, deduplicate_jsonl, filter_jsonl, split_jsonl, + clean_jsonl, + corpus_stats, + deduplicate_jsonl, + filter_jsonl, + split_jsonl, write_run_manifest, ) diff --git a/src/llm_data_lab/pipeline.py b/src/llm_data_lab/pipeline.py index e1673bd..d818bdc 100644 --- a/src/llm_data_lab/pipeline.py +++ b/src/llm_data_lab/pipeline.py @@ -11,9 +11,10 @@ import sys import unicodedata from collections import Counter +from collections.abc import Iterator from datetime import datetime, timezone from pathlib import Path -from typing import Any, Iterator +from typing import Any ZERO_WIDTH_RE = re.compile(r"[\u200B-\u200D\uFEFF\u00AD]") HTML_TAG_RE = re.compile(r"<[^>]+>") @@ -34,7 +35,7 @@ def read_jsonl(path: str | Path) -> Iterator[dict[str, Any]]: except json.JSONDecodeError as exc: raise ValueError(f"{path}:{line_number}: invalid JSON: {exc.msg}") from exc if not isinstance(item, dict): - raise ValueError(f"{path}:{line_number}: each JSONL row must be an object") + raise TypeError(f"{path}:{line_number}: each JSONL row must be an object") yield item @@ -79,7 +80,7 @@ def rows() -> Iterator[dict[str, Any]]: read_count += 1 value = row.get(text_field) if not isinstance(value, str): - raise ValueError( + raise TypeError( f"Record {read_count}: expected string field {text_field!r}, " f"got {type(value).__name__}" ) @@ -122,7 +123,7 @@ def deduplicate_jsonl( read_count += 1 value = row.get(text_field) if not isinstance(value, str): - raise ValueError(f"Record {read_count}: {text_field!r} must be a string") + raise TypeError(f"Record {read_count}: {text_field!r} must be a string") digest = hashlib.sha256(value.encode("utf-8")).hexdigest() cursor = connection.execute( "INSERT OR IGNORE INTO seen(digest) VALUES (?)", @@ -175,7 +176,7 @@ def rows() -> Iterator[dict[str, Any]]: read_count += 1 text = row.get(text_field) if not isinstance(text, str): - raise ValueError(f"Record {read_count}: {text_field!r} must be a string") + raise TypeError(f"Record {read_count}: {text_field!r} must be a string") length = len(text) reason = None if length < min_chars: @@ -236,8 +237,8 @@ def split_jsonl( for index, row in enumerate(read_jsonl(input_path), 1): value = row.get(text_field) if not isinstance(value, str): - raise ValueError(f"Record {index}: {text_field!r} must be a string") - digest = hashlib.sha256(f"{seed}\0{value}".encode("utf-8")).hexdigest() + raise TypeError(f"Record {index}: {text_field!r} must be a string") + digest = hashlib.sha256(f"{seed}\0{value}".encode()).hexdigest() if int(digest, 16) <= threshold: validation.write(json.dumps(row, ensure_ascii=False) + "\n") val_count += 1 @@ -255,7 +256,7 @@ def corpus_stats(input_path: str | Path, *, text_field: str = "text") -> dict[st for index, row in enumerate(read_jsonl(input_path), 1): text = row.get(text_field) if not isinstance(text, str): - raise ValueError(f"Record {index}: {text_field!r} must be a string") + raise TypeError(f"Record {index}: {text_field!r} must be a string") count += 1 total_chars += len(text) total_words += len(text.split()) diff --git a/tests/test_ablation_example.py b/tests/test_ablation_example.py new file mode 100644 index 0000000..30fe87e --- /dev/null +++ b/tests/test_ablation_example.py @@ -0,0 +1,64 @@ +import importlib.util +import json +from pathlib import Path + +import pytest + +# Load the example by path: examples/ is intentionally not an installed package. +_EXAMPLE_PATH = ( + Path(__file__).resolve().parents[1] + / "examples" + / "data_quality_ablation" + / "run_ablation.py" +) +_SPEC = importlib.util.spec_from_file_location("run_ablation_example", _EXAMPLE_PATH) +if _SPEC is None or _SPEC.loader is None: + raise ImportError(f"Could not load ablation example from {_EXAMPLE_PATH}") +_MODULE = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(_MODULE) +run_ablation = _MODULE.run_ablation + + +def write_rows(path, rows): + path.write_text( + "".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows), + encoding="utf-8", + ) + + +def test_ablation_writes_four_conditions_and_manifests(tmp_path): + source = tmp_path / "input.jsonl" + output = tmp_path / "runs" + write_rows(source, [ + {"text": "This is a useful document with enough unique words for filtering.", "source": "a"}, + {"text": "This is a useful document with enough unique words for filtering.", "source": "b"}, + {"text": "ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha", "source": "a"}, + {"text": "tiny", "source": "a"}, + ]) + + result = run_ablation( + source, + output, + min_chars=20, + min_unique_word_ratio=0.3, + seed=123, + ) + + assert set(result["conditions"]) == {"raw", "clean", "clean_dedupe", "full_filter"} + assert result["conditions"]["raw"]["documents_retained"] == 4 + assert result["conditions"]["clean_dedupe"]["documents_retained"] == 3 + assert result["conditions"]["full_filter"]["documents_retained"] < 4 + for name in result["conditions"]: + condition_dir = output / name + assert (condition_dir / "corpus.jsonl").exists() + assert (condition_dir / "manifest.json").exists() + manifest = json.loads((condition_dir / "manifest.json").read_text(encoding="utf-8")) + assert manifest["evaluation"]["status"] == "not_run" + assert (output / "ablation_summary.json").exists() + + +def test_ablation_fails_on_non_string_text_field(tmp_path): + source = tmp_path / "input.jsonl" + write_rows(source, [{"text": 123}]) + with pytest.raises(TypeError, match="must be a string"): + run_ablation(source, tmp_path / "runs") diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index a9959d1..00d5ee6 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -3,8 +3,13 @@ import pytest from llm_data_lab.pipeline import ( - build_run_manifest, clean_jsonl, clean_text, corpus_stats, deduplicate_jsonl, - filter_jsonl, split_jsonl, + build_run_manifest, + clean_jsonl, + clean_text, + corpus_stats, + deduplicate_jsonl, + filter_jsonl, + split_jsonl, ) @@ -32,7 +37,7 @@ def test_clean_jsonl_preserves_metadata_and_drops_empty(tmp_path): def test_clean_fails_for_missing_text_field(tmp_path): source, target = tmp_path / "in.jsonl", tmp_path / "out.jsonl" write_rows(source, [{"content": "hello"}]) - with pytest.raises(ValueError, match="text"): + with pytest.raises(TypeError, match="text"): clean_jsonl(source, target) @@ -63,7 +68,7 @@ def test_split_is_deterministic_and_disjoint(tmp_path): assert train.read_text() == first_train assert val.read_text() == first_val assert report1 == report2 - assert set(row["text"] for row in read_rows(train)).isdisjoint( + assert {row["text"] for row in read_rows(train)}.isdisjoint( row["text"] for row in read_rows(val) )