diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index e13f715..06f83cc 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -18,4 +18,4 @@ jobs: - run: python -m pip install --upgrade pip - run: pip install -e ".[dev]" - run: pytest - - run: ruff check src tests + - run: ruff check . diff --git a/README.md b/README.md index 829a851..4dfceb5 100644 --- a/README.md +++ b/README.md @@ -1,94 +1,128 @@ # LLM Data Lab -**Reproducible data preparation and experiment utilities for language-model research.** +**Reproducible data preparation and quality checks for language-model datasets.** -LLM Data Lab turns raw text datasets into auditable training corpora. It is being developed from lessons in [KannadaSLM](https://github.com/Imkumar80/KannadaSLM), with language-specific rules kept configurable rather than hard-coded. +LLM Data Lab helps researchers inspect, clean, split, and prepare JSONL corpora for existing training tools. Reports record what was read, what was written, why records were rejected, and the configuration used. Training stays in Transformers, TRL, or another training library. -## Current scope +The project grew from data curation work in [KannadaSLM](https://github.com/Imkumar80/KannadaSLM). Language-specific rules are configurable and are not applied as universal defaults. -- Streaming JSONL validation and conservative Unicode/text cleanup -- Exact deduplication with SQLite-backed fingerprints -- Configurable document-length and repetition filters -- Deterministic train/validation splitting without loading the whole corpus into RAM -- Corpus statistics and machine-readable reports -- Dataset/run manifest generation with checksums and environment metadata -- A real-data four-condition ablation with pinned public sample provenance and a generated report -- Unit tests and CI +## Get started -Tokenizer-aware corpus profiles, experiment runners, and model evaluation are planned next. The project will keep data preparation usable on its own and add research workflows in small, optional layers; it does **not** claim to provide a complete training/evaluation framework yet. - -## Quickstart - -Requires Python 3.10+. +Requires Python 3.10 or newer. Install the core and development tools in an editable environment: ```bash python -m venv .venv -# Linux/macOS +# Linux or macOS source .venv/bin/activate -# Windows PowerShell: .venv\Scripts\Activate.ps1 +# Windows PowerShell +# .venv\Scripts\Activate.ps1 +python -m pip install -e ".[dev]" +``` + +Input and output files use UTF-8 JSONL: one JSON object per line. Most core commands use a `text` field by default, preserve other fields, and do not need extra packages. + +For example, start with `data/raw.jsonl`: -pip install -e ".[dev]" +```json +{"text":"A short example document.","source":"sample"} +{"text":"Another document.","source":"sample"} ``` -Input data is JSON Lines (one JSON object per line) with a text field, by default `text`. Extra fields are preserved. +## Prepare and inspect a corpus + +Run the core stages explicitly so each intermediate file can be inspected or reused: ```bash llm-data-lab clean --input data/raw.jsonl --output data/cleaned.jsonl llm-data-lab dedupe --input data/cleaned.jsonl --output data/deduped.jsonl -llm-data-lab filter --input data/deduped.jsonl --output data/filtered.jsonl \ - --min-chars 200 --max-chars 100000 --min-unique-word-ratio 0.30 -llm-data-lab split --input data/filtered.jsonl --train data/train.jsonl \ - --validation data/validation.jsonl --val-fraction 0.02 --seed 42 +llm-data-lab filter --input data/deduped.jsonl --output data/filtered.jsonl --min-chars 200 --max-chars 100000 --min-unique-word-ratio 0.30 +llm-data-lab split --input data/filtered.jsonl --train data/train.jsonl --validation data/validation.jsonl --val-fraction 0.02 --seed 42 llm-data-lab stats --input data/filtered.jsonl --output reports/corpus_stats.json -llm-data-lab manifest --input data/raw.jsonl --output reports/run_manifest.json \ - --run-name raw-ablation --seed 42 --pipeline-config '{"condition":"raw"}' +llm-data-lab overlap --split train=data/train.jsonl --split validation=data/validation.jsonl --normalization exact --output reports/overlap.json +llm-data-lab manifest --input data/raw.jsonl --output reports/run_manifest.json --run-name baseline --seed 42 --pipeline-config '{"steps":["clean","dedupe","filter","split"]}' ``` -All commands support `--help`. Use `--text-field` to select a different text column. Filter defaults are general-purpose length/repetition heuristics; they do not detect language. Add language-specific checks only when appropriate for the corpus. +The filter options above are examples, not recommended universal thresholds. Review the rejection report and sample rejected rows before selecting rules for a real corpus. Filtering uses general-purpose length and repetition heuristics; it does not detect language. -## Data format +Train and validation files should be split after exact deduplication, then checked for overlap. The splitter is deterministic for a given set of documents and seed. It assigns documents using a stable text hash, so assignment does not depend on input order. -Example `sample.jsonl`: +## Tokenizer-aware statistics -```json -{"text":"ನಮಸ್ಕಾರ, ಇದು ಒಂದು ಉದಾಹರಣೆ.","source":"example"} -{"text":"A second example document.","source":"example"} +Install the optional Transformers integration to count tokens with a local tokenizer or model ID: + +```bash +python -m pip install -e ".[transformers]" +llm-data-lab stats --input data/filtered.jsonl --tokenizer /path/to/tokenizer --tokenizer-revision abc123 --output reports/token_stats.json ``` -Do not commit private, licensed, or large raw datasets, model weights, credentials, or generated checkpoints. Record dataset provenance and comply with the source dataset's license and terms. +The tokenizer revision is optional; pin it when using a remote model ID for reproducibility. Token counts do not add special tokens. Empty or whitespace-only text has zero tokens. Errors identify the record number without printing its contents. The Python API also accepts a tokenizer with `encode(text, add_special_tokens=False)` or a compatible callable. -## Reproducibility notes +## Prepare training data -- Cleaning is deterministic and preserves non-text metadata. -- Deduplication uses SHA-256 of cleaned text; it is exact deduplication, not semantic deduplication. -- Splits use a stable hash of the document text and seed, so the same input documents and seed produce the same assignment independent of input order. Exact duplicate documents should be removed before splitting to avoid train/validation leakage. -- Filter reports include rejection counts. Always inspect rejected examples before using aggressive thresholds. -- Corpus statistics are descriptive, not a substitute for a held-out model evaluation. +These adapters validate and export data; they do not train a model. Install Transformers for tokenizer loading. You can also pass a tokenizer object directly to the Python API. -## Development +**Causal pretraining (CPT)** accepts raw text records and enforces per-document sequence limits plus an optional total token budget: ```bash -pytest +llm-data-lab cpt-prepare --input data/filtered.jsonl --output data/cpt.jsonl --tokenizer /path/to/tokenizer --max-sequence-length 256 --token-budget 200000 --overflow-policy truncate --report reports/cpt.json ``` -## Roadmap +**Supervised fine-tuning (SFT)** accepts records with a `messages` array and requires a tokenizer chat template that returns assistant-token masks: + +```bash +llm-data-lab sft-prepare --input data/conversations.jsonl --output data/sft.jsonl --tokenizer /path/to/chat-tokenizer --max-sequence-length 1024 --overflow-policy drop --report reports/sft.json +``` + +**Direct preference optimization (DPO)** accepts `prompt`, `chosen`, and `rejected` strings: + +```bash +llm-data-lab dpo-prepare --input data/preferences.jsonl --output data/dpo.jsonl --tokenizer /path/to/tokenizer --max-sequence-length 1024 --conflict-policy report --report reports/dpo.json +llm-data-lab dpo-overlap --split train=data/dpo_train.jsonl --split validation=data/dpo_validation.jsonl +``` -1. [x] General-purpose cleaning, exact deduplication, filtering, splitting, and statistics -2. [x] Unit tests and continuous integration -3. [x] Dataset manifests with source/version/hash and pipeline configuration -4. [ ] Tokenizer-aware corpus token counts and train/validation leakage checks -5. [ ] Config-driven CPT/SFT experiment runner -6. [ ] Standardized evaluation adapters and machine-readable reports -7. [x] Data-quality ablation example using a small public dataset +See [data schemas and report contracts](docs/data_schemas.md) for fields, overflow behavior, and Python examples. Optional [TRL handoff examples](examples/trl_integrations/README.md) show how to pass prepared data to existing SFT and DPO trainers. The pinned [CPT smoke example](examples/cpt_smoke/README.md) is an opt-in GPU integration run, not a required install or unit test. -For the planned experiment and evaluation formats, see [experiment design](docs/experiment_design.md) and [evaluation design](docs/evaluation_design.md). -The completed [AG News data-quality ablation report](docs/ag_news_ablation_report.md) documents one small, reproducible corpus-level run. -Long-lived architecture and research-workflow choices are recorded in the [decision log](docs/adr/README.md). +## Split overlap checks + +`overlap` compares exact text across two or more named splits and reports overlap counts and affected split names, never raw documents. Choose one of these explicit policies: + +- `exact` (default): compare text as-is. +- `nfc_casefold_whitespace`: apply Unicode NFC normalization, case folding, and whitespace collapsing before comparison. + +These checks detect exact text overlap under the chosen policy. They do not detect semantic similarity, paraphrases, or whether a document appeared in model pretraining. + +## Reports and reproducibility + +Where applicable, cleaning, deduplication, filtering, splitting, token statistics, overlap checks, and adapter reports record SHA-256 input/output checksums, row counts, configuration, and software or tokenizer metadata. Rejection reports summarize reasons and counts without embedding raw examples. New token-statistics, overlap, and adapter report formats declare `schema_version: 1`; existing report keys remain available as audit fields are added. + +Deduplication is exact after cleaning; it is not semantic deduplication. Keep source dataset names, revisions, licenses, and checksums with your run records. Do not commit private or licensed data, model weights, credentials, or generated checkpoints. + +Corpus statistics and data-quality reports describe the data. They do not establish that preprocessing improves model quality; that requires a controlled, held-out model evaluation. + +## Current scope and next steps + +Implemented today: + +- Streaming JSONL validation, conservative text cleanup, exact deduplication, configurable filtering, and deterministic splitting. +- Corpus statistics, optional tokenizer-aware token counts, exact split-overlap checks, checksums, and manifests. +- Preparation-only CPT, SFT, and DPO adapters with synthetic offline tests. +- A pinned public-data ablation and optional examples for handing prepared data to existing trainers. + +The next milestone is a small, reproducible CPT training integration run. It is documented in the [CPT smoke example](examples/cpt_smoke/README.md), but requires the optional training dependencies and a compatible GPU. SFT and DPO trainer integrations remain examples; there is no custom training loop, orchestration service, dashboard, distributed-training support, or RLHF implementation in the core. + +For package boundaries and adapter contracts, see [architecture](docs/architecture.md) and [data schemas](docs/data_schemas.md). The [AG News ablation report](docs/ag_news_ablation_report.md) describes the public corpus experiment. Longer-term evaluation ideas and recorded design choices are in the [evaluation design](docs/evaluation_design.md) and [decision log](docs/adr/README.md). + +## Development + +```bash +python -m pytest +ruff check . +``` -## Origin +Tests use small synthetic fixtures and do not download datasets. Use `llm-data-lab --help` or `llm-data-lab COMMAND --help` for the installed CLI's options. -The initial design is informed by data curation and evaluation work in KannadaSLM. Kannada-specific script-ratio rules remain project-specific and should be implemented as an optional plugin rather than a universal default. +## Origin and license -## License +The initial design is informed by data curation and evaluation work in [KannadaSLM](https://github.com/Imkumar80/KannadaSLM). Kannada-specific script-ratio rules remain project-specific and should be optional rather than universal defaults. -MIT. See [LICENSE](LICENSE). +This project is MIT licensed. See [LICENSE](LICENSE). diff --git a/docs/ag_news_ablation_report.md b/docs/ag_news_ablation_report.md index 6fa29a9..cc31933 100644 --- a/docs/ag_news_ablation_report.md +++ b/docs/ag_news_ablation_report.md @@ -7,9 +7,14 @@ This report compares four data-preparation conditions on a fixed public dataset - Dataset: [fancyzhx/ag_news](https://huggingface.co/datasets/fancyzhx/ag_news) - Hub revision: `eb185aade064a813bc0b7f42de02595523103ca4` - Config/split: `default` / `train` -- Sample: first 300 rows (row indices 0–299) (300 rows) -- Input JSONL SHA-256: `073b6e0b2201d3a35fbbe5c77ce38511f93c379ccf8d685c9c17853a992c8e46` +- Sampling method: Divide the training split's source-row index range into four equal strata; select one seeded contiguous 100-row block uniformly within each stratum. +- Sampling seed: `42`; requested/actual: 400/400 rows +- Sample class counts: {'World': 80, 'Sports': 79, 'Business': 109, 'Sci/Tech': 132} +- Training split rows: 120000 +- Selected source row blocks: [{'start_inclusive': 0, 'end_exclusive': 30000, 'selected_block_start': 20952, 'selected_block_end_exclusive': 21052}, {'start_inclusive': 30000, 'end_exclusive': 60000, 'selected_block_start': 33648, 'selected_block_end_exclusive': 33748}, {'start_inclusive': 60000, 'end_exclusive': 90000, 'selected_block_start': 60819, 'selected_block_end_exclusive': 60919}, {'start_inclusive': 90000, 'end_exclusive': 120000, 'selected_block_start': 114299, 'selected_block_end_exclusive': 114399}] +- Input JSONL SHA-256: `054d5a8593b706fd750cbe391613467c9195a3dd410dbbeb4aeb3f4cca930764` - Acquisition API: [https://datasets-server.huggingface.co/rows](https://datasets-server.huggingface.co/rows) +- Revision limitation: The Dataset Viewer rows endpoint does not accept an immutable Hub revision. The script checks the Hub revision before and after fetching and pins the exact serialized sample checksum to detect changed viewer results. - License note: Hugging Face lists the license as unknown. The dataset card describes the upstream AG News corpus as intended for research and other non-commercial activities; verify upstream terms before reuse. - The downloaded sample and condition corpora are written under the ignored `data/` directory; the committed report contains no article text. @@ -19,36 +24,57 @@ Recreate the sample and report from the repository root with: python examples/data_quality_ablation/run_public_dataset.py ``` -## Results +## Observed results -| Condition | Documents | Retained | Characters | Mean chars/doc | Mean words/doc | -|---|---:|---:|---:|---:|---:| -| `raw` | 300 | 100.0% | 82734 | 275.8 | 44.0 | -| `clean` | 300 | 100.0% | 82064 | 273.5 | 44.2 | -| `clean_dedupe` | 300 | 100.0% | 82064 | 273.5 | 44.2 | -| `full_filter` | 205 | 68.3% | 68130 | 332.3 | 53.3 | +Retention denominator for every condition is the same sampled input corpus. -Label counts (the source sample’s original class labels): +| Condition | Input | Output | Retained | Characters | Whitespace words | Mean chars/doc | Length chars min / p25 / median / p75 / p90 / max | +|---|---:|---:|---:|---:|---:|---:|---| +| `raw` | 400 | 400 | 100.0% | 92712 | 14867 | 231.8 | 101 / 193 / 227 / 259 / 288 / 906 | +| `clean` | 400 | 400 | 100.0% | 92150 | 14923 | 230.4 | 101 / 193 / 226 / 258 / 287 / 851 | +| `clean_dedupe` | 400 | 400 | 100.0% | 92150 | 14923 | 230.4 | 101 / 193 / 226 / 258 / 287 / 851 | +| `full_filter` | 400 | 277 | 69.2% | 71268 | 11470 | 257.3 | 200 / 225 / 245 / 273 / 304 / 851 | + +Label counts after each condition: | Condition | World | Sports | Business | Sci/Tech | |---|---:|---:|---:|---:| -| `raw` | 0 | 0 | 78 | 222 | -| `clean` | 0 | 0 | 78 | 222 | -| `clean_dedupe` | 0 | 0 | 78 | 222 | -| `full_filter` | 0 | 0 | 43 | 162 | +| `raw` | 80 | 79 | 109 | 132 | +| `clean` | 80 | 79 | 109 | 132 | +| `clean_dedupe` | 80 | 79 | 109 | 132 | +| `full_filter` | 57 | 55 | 74 | 91 | + +Sample class counts before preparation are World: 80, Sports: 79, Business: 109, Sci/Tech: 132. All source classes appear in this prefix. After full filtering, counts are World: 57, Sports: 55, Business: 74, Sci/Tech: 91. Consider both total retention and changes in class mix. + +Source document counts after each condition: + +| Condition | fancyzhx/ag_news | +|---|---:| +| `raw` | 400 | +| `clean` | 400 | +| `clean_dedupe` | 400 | +| `full_filter` | 277 | + +Per-condition corpus SHA-256: -Source-order class counts are World: 0, Sports: 0, Business: 78, Sci/Tech: 222. Absent source classes: World, Sports. After full filtering, counts are World: 0, Sports: 0, Business: 43, Sci/Tech: 162. Consider both total retention and changes in class mix. +- `raw`: `054d5a8593b706fd750cbe391613467c9195a3dd410dbbeb4aeb3f4cca930764` +- `clean`: `99535cb689f98c9223d4e66435c6349e3675bd7ce848d84a5c1460dc5ed2cd2a` +- `clean_dedupe`: `5da71d248460409d05fdca300de7d5f41263562f6a094270731ede2e6adb37b9` +- `full_filter`: `b3a658a862a85153ac14878ef71a10205dfe63b421fe39eb07e005cf5218b6f5` ### Stage effects -- `clean`: cleaned 300 documents. -- `clean_dedupe`: cleaned 300 documents; removed 0 exact duplicates. -- `full_filter`: cleaned 300 documents; removed 0 exact duplicates; filtered 95 documents (too_short: 95). +- `raw` validation/copy: 400 input → 400 output documents. +- `clean`: cleaned 400 → 400 documents; empty after cleaning: 0. +- `clean_dedupe`: cleaned 400 → 400 documents; empty after cleaning: 0; deduplicated 400 → 400 (removed 0 exact duplicates). +- `full_filter`: cleaned 400 → 400 documents; empty after cleaning: 0; deduplicated 400 → 400 (removed 0 exact duplicates); filtered 400 → 277 (too_short: 123). Filter thresholds: minimum 200 characters, maximum 100000 characters, and minimum unique-word ratio 0.30. +The minimum-character rule is the existing general-purpose default (200), kept unchanged for this demonstration; it was not tuned on a test split or model result. +Pre-filter documents shorter than 200 characters: 123; length min/median/max: 101/176/199 characters. ## Interpretation -These results describe only how this particular 300-row prefix responds to the configured preprocessing steps. The prefix is not a random sample of the full corpus. Exact deduplication uses cleaned text, so duplicates with different non-text labels retain only their first row. The filter is a heuristic; retention does not measure usefulness or model quality. For causal claims about data quality, train matched models and evaluate them on the same held-out set. +This is a source-index-stratified block sample, not a simple random sample or a representative sample of the full corpus. Contiguous blocks can cluster similar documents, and class composition is incidental rather than balanced by design; report observed class counts without generalizing them. Exact deduplication uses cleaned text, so duplicates with different non-text labels retain only their first row. The filter is a heuristic; retention does not measure usefulness or model quality. For causal claims about data quality, train matched models and evaluate them on the same held-out set. -The machine-readable run, per-condition manifests, and filter report are in `data/ag_news_ablation/` after running the command above. +The machine-readable run, per-condition manifests, and filter report are in `data/ag_news_ablation/` after running the command above. Raw article text is not included in this report. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..52f371e --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,30 @@ +# Data preparation architecture + +The maintained package is intentionally small. `pipeline.py` owns streaming JSONL validation, cleaning, exact deduplication, filtering, deterministic splitting, corpus statistics, checksums, and run manifests. `token_stats.py` adds tokenizer-aware corpus diagnostics without importing Transformers unless the caller asks to load a tokenizer by name. `leakage.py` compares exact text across named splits and does not return document contents. `adapters/cpt.py`, `adapters/sft.py`, and `adapters/dpo.py` validate and export task-specific data but do not own training. `cli.py` exposes the same operations. GPU training and TRL integrations live only in examples. + +## Optional tokenizer support + +The mandatory package has no runtime dependencies. Install `llm-data-lab[transformers]` only when using the CLI's `stats --tokenizer NAME_OR_PATH` form. Python callers may pass a tokenizer object directly and avoid Transformers entirely. Token counts omit special tokens by default. Empty or whitespace-only records count as zero and are not passed to the tokenizer. A tokenizer exception is raised as a record-numbered `RuntimeError`; malformed text fields are rejected with a `TypeError`. + +`token_stats` returns a versioned report with the input file checksum when given a path, tokenizer identifier/revision where available, document and empty-document counts, total tokens, min/max/mean, p50/p90/p95 and an exact token-length histogram. Token-length aggregation stores counts by distinct length rather than one token count per document. + +## Split overlap contract + +`check_split_overlap` accepts a mapping of split names to JSONL paths or iterables of records. It reports documents per split, affected split names, pairwise unique overlapping texts and overlapping record counts. It uses SHA-256 fingerprints internally and never includes document text or per-document hashes in reports; path inputs include file-level SHA-256 checksums for audit. + +Normalization policies are stable API values: + +- `exact` compares decoded text as supplied. +- `nfc_casefold_whitespace` applies Unicode NFC, Unicode case folding, and collapses whitespace runs before comparison. + +These checks find exact overlap under the selected normalization only. They are not semantic deduplication and cannot determine whether training data appeared in model pretraining. + +## Audit report fields + +Existing operation report keys remain available. Core processing reports add input/output SHA-256 values, row counts, operation configuration and software metadata. Filters include retained/rejected counts and a stable `rejected_by_reason` mapping. Split reports include input and both output checksums. Manifests retain their existing top-level structure and now record the input row count alongside its checksum. + +New tokenizer and overlap report objects include `schema_version: 1`. Token length histogram keys are decimal strings to remain valid JSON object keys. Tokenizer reports for iterable inputs use a null input checksum because no canonical serialized file is available. Reports contain aggregate values, file-level checksums and configuration, not raw corpus text. Overlap keeps one fixed-size fingerprint per unique document in memory, so memory use still grows with the number of unique records. + +## Validation and scope + +The unit tests are offline and use tiny synthetic records and fake tokenizers. A user must explicitly opt in to tokenizer resolution, dataset downloads, or example training. The adapter APIs do not train or evaluate a model, and data diagnostics must not be presented as model-quality evidence. See [data schemas](data_schemas.md) for the task-specific input/output contracts. diff --git a/docs/data_schemas.md b/docs/data_schemas.md new file mode 100644 index 0000000..2a915aa --- /dev/null +++ b/docs/data_schemas.md @@ -0,0 +1,37 @@ +# Prepared data schemas + +All formats are JSONL, UTF-8, one JSON object per line. Core dependencies remain optional; tokenizer commands resolve a Transformers tokenizer only when explicitly requested. The preparation API preserves row-level metadata when it can and never writes raw examples into reports. + +## CPT raw text + +Input records contain a non-empty string at `text` (or a selected `text_field`); other metadata is allowed. `prepare_cpt_dataset` writes text records with the same fields, enforcing a per-document sequence limit and optional total token budget. Overlong records use `error`, `drop`, or `truncate`. Records that do not fit the remaining budget are rejected whole. The report records input/output hashes, counts, rejected reasons, tokenizer identity and length distributions. + +```python +from transformers import AutoTokenizer +from llm_data_lab.adapters.cpt import prepare_cpt_dataset + +tokenizer = AutoTokenizer.from_pretrained("local/tokenizer") +report = prepare_cpt_dataset( + "raw.jsonl", "prepared.jsonl", tokenizer=tokenizer, + max_sequence_length=256, token_budget=200_000, + overflow_policy="truncate", report_path="prepared.report.json", +) +``` + +The exported JSONL can be read by `datasets.load_dataset("json", data_files=...)`; sequence packing and training remain with the caller. + +## SFT conversations + +Each input object contains a non-empty `messages` list. Each message has `role` in `system`, `user`, or `assistant` and string `content`; at least one assistant response must be non-empty. The tokenizer must provide a compatible chat template that returns `input_ids` and assistant-span masks when called with `return_assistant_tokens_mask=True`. + +Prepared rows preserve `messages` and add `input_ids` plus integer `assistant_mask` of the same length. The mask marks assistant target positions and is framework-neutral. It is not converted to trainer-specific `labels`. Overlength handling can error, drop, or truncate from a chosen side. Any result without at least one supervised token is rejected. + +## DPO preference pairs + +Each input object contains non-empty string fields `prompt`, `chosen`, and `rejected`. Equal answers are rejected. Prepared rows keep these fields and add `token_counts` for the prompt, each answer, and each prompt/answer sequence. Length limits apply to both prompt-plus-answer sequences. Truncation preserves the prompt and shortens answers; empty answers and pairs that become identical are rejected. + +Repeated prompts and reversed chosen/rejected preferences are counted. The default conflict policy reports and preserves contradictory rows; `error` stops before writing the output. Use `check_dpo_split_overlap` or `dpo-overlap` to check prompt overlap across pair splits. + +## Report stability and limits + +The CPT, SFT, and DPO adapter reports use `schema_version: 1`, input/output SHA-256 checksums, counts, rejection reasons, configuration, tokenizer identity and software metadata. These adapters prepare data only. They do not claim semantic leakage detection or model-quality improvement. diff --git a/examples/cpt_smoke/README.md b/examples/cpt_smoke/README.md new file mode 100644 index 0000000..33d514e --- /dev/null +++ b/examples/cpt_smoke/README.md @@ -0,0 +1,14 @@ +# CPT smoke workflow + +This example is an opt-in GPU integration run. It uses the immutable [TinyStories dataset revision](https://huggingface.co/datasets/roneneldan/TinyStories/commit/f54c09fd23315a6f9c86f9dc80f725de7d8f9c64) `f54c09fd23315a6f9c86f9dc80f725de7d8f9c64` and [SmolLM2-135M Base revision](https://huggingface.co/HuggingFaceTB/SmolLM2-135M/tree/93efa2f097d58c2a74874c7e644dbc9b0cee75a2) `93efa2f097d58c2a74874c7e644dbc9b0cee75a2`. The dataset card declares CDLA-Sharing-1.0; the model card declares Apache-2.0. Confirm that the terms fit your use before downloading or training. + +Install in a CUDA Colab runtime: + +```bash +pip install -e ".[training]" +python examples/cpt_smoke/run_training.py --train-stories 5000 +``` + +The script selects 5,000 training stories and 512 stories from TinyStories' separate validation split, prepares them under 256-token document limits and a 200k training-token budget, checks for text overlap, packs fixed-length training blocks and runs one epoch. It enables BF16 when supported, otherwise FP16, then evaluates held-out loss/perplexity, saves and reloads the checkpoint, and records optimizer steps, token counts, runtime, peak GPU memory, revisions, checksums and configuration. + +Data is written under ignored `data/cpt_smoke/`; checkpoints and the final manifest go under ignored `checkpoints/cpt-smoke/`. The script requires CUDA and was not run by unit tests. A successful smoke run validates integration and reproducibility only; it does not show that a data-preparation choice improves model quality. diff --git a/examples/cpt_smoke/run_training.py b/examples/cpt_smoke/run_training.py new file mode 100644 index 0000000..8b58a02 --- /dev/null +++ b/examples/cpt_smoke/run_training.py @@ -0,0 +1,319 @@ +"""Optional GPU smoke run using pinned TinyStories and SmolLM2 revisions. + +This is an example training script, not part of the core package. It is designed +for a CUDA Colab runtime and writes downloaded/prepared data and checkpoints only +under ignored ``data/`` and ``checkpoints/`` directories. +""" + +from __future__ import annotations + +import argparse +import importlib.metadata +import json +import math +import platform +import sys +import time +from collections.abc import Sequence +from itertools import islice +from pathlib import Path +from typing import Any + +from llm_data_lab.adapters.cpt import prepare_cpt_dataset +from llm_data_lab.leakage import check_split_overlap +from llm_data_lab.pipeline import _git_commit, sha256_file + +DATASET_ID = "roneneldan/TinyStories" +DATASET_REVISION = "f54c09fd23315a6f9c86f9dc80f725de7d8f9c64" +MODEL_ID = "HuggingFaceTB/SmolLM2-135M" +MODEL_REVISION = "93efa2f097d58c2a74874c7e644dbc9b0cee75a2" +TRAIN_STORIES = 5_000 +VALIDATION_STORIES = 512 +SEQUENCE_LENGTH = 256 +TRAIN_TOKEN_BUDGET = 200_000 +VALIDATION_TOKEN_BUDGET = 25_600 +SEED = 42 + + +def _write_jsonl(path: Path, rows: Sequence[dict[str, Any]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="utf-8", newline="\n") as handle: + for row in rows: + handle.write(json.dumps(row, ensure_ascii=False) + "\n") + + +def _tokenize_and_pack(dataset: Any, tokenizer: Any, sequence_length: int) -> Any: + def tokenize(batch: dict[str, list[str]]) -> dict[str, list[list[int]]]: + return tokenizer(batch["text"], add_special_tokens=False, truncation=False) + + tokenized = dataset.map( + tokenize, + batched=True, + remove_columns=dataset.column_names, + desc="Tokenizing prepared stories", + ) + eos_id = tokenizer.eos_token_id + if eos_id is None: + raise ValueError("The pinned tokenizer must define eos_token_id for story boundaries") + + def pack(batch: dict[str, list[list[int]]]) -> dict[str, list[list[int]]]: + stream: list[int] = [] + for ids in batch["input_ids"]: + stream.extend(ids) + stream.append(eos_id) + block_count = len(stream) // sequence_length + packed = [ + stream[index * sequence_length : (index + 1) * sequence_length] + for index in range(block_count) + ] + return {"input_ids": packed} + + packed = tokenized.map( + pack, + batched=True, + remove_columns=tokenized.column_names, + desc=f"Packing {sequence_length}-token blocks", + ) + if len(packed) == 0: + raise ValueError("Preparation produced no complete training blocks") + return packed + + +def run(output_dir: Path, *, train_stories: int = TRAIN_STORIES) -> dict[str, Any]: + try: + import torch + from datasets import load_dataset + from transformers import ( + AutoModelForCausalLM, + AutoTokenizer, + Trainer, + TrainingArguments, + ) + except ImportError as exc: + raise RuntimeError('Install the optional stack with `pip install -e ".[training]"`.') from exc + + if not torch.cuda.is_available(): + raise RuntimeError("This pilot expects a CUDA Colab runtime, such as an A100.") + if train_stories < 5_000 or train_stories > 10_000: + raise ValueError("train_stories must be between 5,000 and 10,000") + + data_dir = Path("data/cpt_smoke") + data_dir.mkdir(parents=True, exist_ok=True) + raw_train_path = data_dir / "tinystories_train_raw.jsonl" + raw_validation_path = data_dir / "tinystories_validation_raw.jsonl" + prepared_train_path = data_dir / "tinystories_train_prepared.jsonl" + prepared_validation_path = data_dir / "tinystories_validation_prepared.jsonl" + tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, revision=MODEL_REVISION) + + train_source = load_dataset( + DATASET_ID, + revision=DATASET_REVISION, + split="train", + streaming=True, + ) + validation_source = load_dataset( + DATASET_ID, + revision=DATASET_REVISION, + split="validation", + streaming=True, + ) + train_rows = list(islice(train_source, train_stories)) + validation_rows = list(islice(validation_source, VALIDATION_STORIES)) + if len(train_rows) != train_stories or len(validation_rows) != VALIDATION_STORIES: + raise ValueError("Pinned TinyStories revision returned fewer rows than requested") + _write_jsonl( + raw_train_path, + [ + {"text": row["text"], "source": DATASET_ID, "source_row": index} + for index, row in enumerate(train_rows) + ], + ) + _write_jsonl( + raw_validation_path, + [ + {"text": row["text"], "source": DATASET_ID, "source_row": index} + for index, row in enumerate(validation_source) + ], + ) + + train_report = prepare_cpt_dataset( + raw_train_path, + prepared_train_path, + tokenizer=tokenizer, + max_sequence_length=SEQUENCE_LENGTH - 1, + token_budget=TRAIN_TOKEN_BUDGET, + overflow_policy="truncate", + report_path=data_dir / "train_preparation_report.json", + ) + validation_report = prepare_cpt_dataset( + raw_validation_path, + prepared_validation_path, + tokenizer=tokenizer, + max_sequence_length=SEQUENCE_LENGTH - 1, + token_budget=VALIDATION_TOKEN_BUDGET, + overflow_policy="truncate", + report_path=data_dir / "validation_preparation_report.json", + ) + overlap = check_split_overlap( + {"train": prepared_train_path, "validation": prepared_validation_path} + ) + if overlap["has_overlap"]: + raise ValueError("Prepared train and validation splits contain overlapping stories") + + datasets = load_dataset( + "json", + data_files={"train": str(prepared_train_path), "validation": str(prepared_validation_path)}, + ) + train_dataset = _tokenize_and_pack(datasets["train"], tokenizer, SEQUENCE_LENGTH) + validation_dataset = _tokenize_and_pack(datasets["validation"], tokenizer, SEQUENCE_LENGTH) + actual_train_tokens = len(train_dataset) * SEQUENCE_LENGTH + actual_validation_tokens = len(validation_dataset) * SEQUENCE_LENGTH + if not 100_000 <= actual_train_tokens <= 250_000: + raise ValueError( + f"Packed training set has {actual_train_tokens} tokens; expected 100k–250k" + ) + + model = AutoModelForCausalLM.from_pretrained(MODEL_ID, revision=MODEL_REVISION) + bf16 = bool(torch.cuda.is_bf16_supported()) + training_args = TrainingArguments( + output_dir=str(output_dir), + num_train_epochs=1, + per_device_train_batch_size=8, + per_device_eval_batch_size=8, + learning_rate=5e-5, + weight_decay=0.01, + warmup_ratio=0.03, + lr_scheduler_type="cosine", + optim="adamw_torch", + eval_strategy="epoch", + save_strategy="epoch", + save_total_limit=1, + logging_steps=10, + seed=SEED, + data_seed=SEED, + bf16=bf16, + fp16=not bf16, + report_to="none", + dataloader_num_workers=2, + ) + def collate_fixed_blocks(features: list[dict[str, list[int]]]) -> dict[str, Any]: + input_ids = torch.tensor([feature["input_ids"] for feature in features], dtype=torch.long) + return {"input_ids": input_ids, "labels": input_ids.clone()} + + trainer = Trainer( + model=model, + args=training_args, + train_dataset=train_dataset, + eval_dataset=validation_dataset, + data_collator=collate_fixed_blocks, + ) + torch.cuda.reset_peak_memory_stats() + started = time.perf_counter() + train_result = trainer.train() + training_seconds = time.perf_counter() - started + evaluation = trainer.evaluate() + trainer.save_model(str(output_dir)) + tokenizer.save_pretrained(output_dir) + peak_memory_bytes = torch.cuda.max_memory_allocated() + + del trainer, model + torch.cuda.empty_cache() + reloaded_model = AutoModelForCausalLM.from_pretrained(output_dir).to("cuda") + reload_trainer = Trainer( + model=reloaded_model, + args=training_args, + eval_dataset=validation_dataset, + data_collator=collate_fixed_blocks, + ) + reload_evaluation = reload_trainer.evaluate() + reload_ok = math.isclose( + float(evaluation["eval_loss"]), float(reload_evaluation["eval_loss"]), rel_tol=1e-4 + ) + if not reload_ok: + raise RuntimeError("Reloaded checkpoint evaluation did not match the saved model") + + manifest = { + "schema_version": 1, + "status": "complete", + "dataset": { + "identifier": DATASET_ID, + "revision": DATASET_REVISION, + "train_rows_requested": train_stories, + "validation_rows_requested": VALIDATION_STORIES, + "selection": { + "train": f"first {train_stories} rows via streaming", + "validation": f"first {VALIDATION_STORIES} rows via streaming", + }, + "train_input_sha256": sha256_file(raw_train_path), + "validation_input_sha256": sha256_file(raw_validation_path), + "license": "cdla-sharing-1.0", + }, + "model": { + "identifier": MODEL_ID, + "revision": MODEL_REVISION, + "license": "apache-2.0", + }, + "preparation": { + "sequence_length": SEQUENCE_LENGTH, + "train_token_budget": TRAIN_TOKEN_BUDGET, + "validation_token_budget": VALIDATION_TOKEN_BUDGET, + "train": train_report, + "validation": validation_report, + "split_overlap": overlap, + }, + "training": { + "actual_train_tokens": actual_train_tokens, + "actual_validation_tokens": actual_validation_tokens, + "optimizer_steps": train_result.global_step, + "train_loss": train_result.training_loss, + "validation_loss": evaluation["eval_loss"], + "validation_perplexity": math.exp(float(evaluation["eval_loss"])), + "training_seconds": training_seconds, + "peak_gpu_memory_bytes": peak_memory_bytes, + "bf16": bf16, + "fp16": not bf16, + "checkpoint_reload_ok": reload_ok, + "reloaded_validation_loss": reload_evaluation["eval_loss"], + }, + "configuration": { + "code_commit": _git_commit(), + "seed": SEED, + "epochs": 1, + "per_device_batch_size": 8, + "gradient_accumulation_steps": 1, + "learning_rate": 5e-5, + "weight_decay": 0.01, + "warmup_ratio": 0.03, + "scheduler": "cosine", + "optimizer": "adamw_torch", + "evaluation_strategy": "epoch", + "save_strategy": "epoch", + "max_sequence_length": SEQUENCE_LENGTH, + "hardware": torch.cuda.get_device_name(0), + "python": sys.version.replace("\n", " "), + "platform": platform.platform(), + }, + "software_versions": { + "llm_data_lab": importlib.metadata.version("llm-data-lab"), + "torch": torch.__version__, + "datasets": importlib.metadata.version("datasets"), + "transformers": importlib.metadata.version("transformers"), + }, + "scope_note": "Smoke integration run only; this result does not establish a model-quality improvement.", + } + manifest_path = output_dir / "run_manifest.json" + manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") + print(json.dumps(manifest, indent=2)) + return manifest + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output-dir", type=Path, default=Path("checkpoints/cpt-smoke")) + parser.add_argument("--train-stories", type=int, default=TRAIN_STORIES) + args = parser.parse_args() + run(args.output_dir, train_stories=args.train_stories) + + +if __name__ == "__main__": + main() diff --git a/examples/data_quality_ablation/run_public_dataset.py b/examples/data_quality_ablation/run_public_dataset.py index fda876b..469870d 100644 --- a/examples/data_quality_ablation/run_public_dataset.py +++ b/examples/data_quality_ablation/run_public_dataset.py @@ -2,7 +2,11 @@ from __future__ import annotations import argparse +import hashlib import json +import math +import random +import sys from collections import Counter from pathlib import Path from typing import Any @@ -17,20 +21,26 @@ DATASET = "fancyzhx/ag_news" CONFIG = "default" SPLIT = "train" -SAMPLE_ROWS = 300 -PAGE_SIZE = 100 -VIEWER_URL = "https://datasets-server.huggingface.co/rows" +SAMPLE_ROWS = 400 +BLOCK_COUNT = 4 +BLOCK_SIZE = SAMPLE_ROWS // BLOCK_COUNT +LABELS = {0: "World", 1: "Sports", 2: "Business", 3: "Sci/Tech"} +VIEWER_ROWS_URL = "https://datasets-server.huggingface.co/rows" HUB_API_URL = "https://huggingface.co/api/datasets/" PINNED_REVISION = "eb185aade064a813bc0b7f42de02595523103ca4" -PINNED_SAMPLE_SHA256 = "073b6e0b2201d3a35fbbe5c77ce38511f93c379ccf8d685c9c17853a992c8e46" +PINNED_SAMPLE_SHA256 = "054d5a8593b706fd750cbe391613467c9195a3dd410dbbeb4aeb3f4cca930764" +DEFAULT_SEED = 42 def _get_json(url: str) -> dict[str, Any]: try: with urlopen(url, timeout=45) as response: - return json.load(response) + payload = json.load(response) except (OSError, URLError, json.JSONDecodeError) as exc: raise RuntimeError(f"Could not fetch {url}: {exc}") from exc + if not isinstance(payload, dict): + raise TypeError(f"Expected a JSON object from {url}") + return payload def _dataset_revision() -> str: @@ -46,79 +56,228 @@ def _dataset_revision() -> str: return revision -def fetch_sample(destination: Path) -> tuple[dict[str, Any], list[dict[str, Any]]]: - revision_before = _dataset_revision() +def source_index_block_offsets( + population_size: int, + *, + block_size: int = BLOCK_SIZE, + block_count: int = BLOCK_COUNT, + seed: int = DEFAULT_SEED, +) -> list[int]: + """Choose a seeded contiguous block from each equal source-row-index stratum.""" + if block_count <= 0 or block_size <= 0: + raise ValueError("block_count and block_size must be positive") + if population_size < block_size * block_count: + raise ValueError("population_size must be at least block_size * block_count") + rng = random.Random(seed) + starts: list[int] = [] + for block in range(block_count): + lower = (block * population_size) // block_count + upper = ((block + 1) * population_size) // block_count - block_size + if upper < lower: + raise ValueError("Each source-index stratum must fit one complete block") + starts.append(rng.randint(lower, upper)) + return starts + + +def _rows_url(offset: int, length: int) -> str: + query = urlencode( + { + "dataset": DATASET, + "config": CONFIG, + "split": SPLIT, + "offset": offset, + "length": length, + } + ) + return f"{VIEWER_ROWS_URL}?{query}" + + +def _validate_rows_page( + page: dict[str, Any], *, total: int | None, offset: int, expected_length: int +) -> tuple[int, list[dict[str, Any]]]: + if not isinstance(page, dict): + raise TypeError("Dataset Viewer response must be a JSON object") + if page.get("partial") is True: + raise RuntimeError("Dataset Viewer returned a partial filter result") + page_total = page.get("num_rows_total") + if not isinstance(page_total, int) or isinstance(page_total, bool): + raise TypeError("Dataset Viewer response is missing a valid num_rows_total") + if total is not None and page_total != total: + raise RuntimeError("Training split row count changed during sample acquisition") + rows = page.get("rows") + if not isinstance(rows, list): + raise TypeError("Dataset Viewer response rows must be a list") + if len(rows) != expected_length: + raise RuntimeError( + f"Dataset Viewer returned {len(rows)} rows; expected {expected_length} from offset {offset}" + ) + for position, item in enumerate(rows): + if not isinstance(item, dict): + raise TypeError("Dataset Viewer row entry must be an object") + if item.get("row_idx") != offset + position: + raise RuntimeError("Dataset Viewer returned a missing or reordered source row") + return page_total, rows + + +def _serialize_rows(rows: list[dict[str, Any]]) -> bytes: + return "".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows).encode("utf-8") + + +def verify_sample_checksum(sample: bytes, expected_sha256: str) -> str: + actual = hashlib.sha256(sample).hexdigest() + if actual != expected_sha256: + raise RuntimeError( + f"Sample SHA-256 mismatch: expected {expected_sha256}, got {actual}. " + "Review the source change and update the pin explicitly if intended." + ) + return actual + + +def fetch_sample( + destination: Path, + *, + seed: int = DEFAULT_SEED, + expected_sha256: str | None = PINNED_SAMPLE_SHA256, + get_json: Any | None = None, + revision_reader: Any | None = None, +) -> tuple[dict[str, Any], list[dict[str, Any]]]: + get_json = get_json or _get_json + revision_reader = revision_reader or _dataset_revision + revision_before = revision_reader() + population_page = get_json(_rows_url(0, 1)) + population_size, _ = _validate_rows_page( + population_page, total=None, offset=0, expected_length=1 + ) + block_offsets = source_index_block_offsets(population_size, seed=seed) rows: list[dict[str, Any]] = [] - for offset in range(0, SAMPLE_ROWS, PAGE_SIZE): - query = urlencode( - { - "dataset": DATASET, - "config": CONFIG, - "split": SPLIT, - "offset": offset, - "length": min(PAGE_SIZE, SAMPLE_ROWS - offset), - } + seen_source_rows: set[int] = set() + for offset in block_offsets: + page = get_json(_rows_url(offset, BLOCK_SIZE)) + _, selected_rows = _validate_rows_page( + page, total=population_size, offset=offset, expected_length=BLOCK_SIZE ) - page = _get_json(f"{VIEWER_URL}?{query}") - if page.get("num_rows_total", 0) < SAMPLE_ROWS: - raise RuntimeError(f"{DATASET} has fewer than {SAMPLE_ROWS} rows in {SPLIT}") - for item in page.get("rows", []): + for item in selected_rows: row_index = item.get("row_idx") - row = item.get("row", {}) - if row_index != len(rows) or not isinstance(row.get("text"), str): - raise RuntimeError("Dataset Viewer returned a missing, reordered, or invalid row") + row = item.get("row") + if not isinstance(row_index, int) or isinstance(row_index, bool): + raise TypeError("Dataset Viewer returned a row without an integer row_idx") + if row_index in seen_source_rows: + raise RuntimeError(f"Dataset Viewer returned duplicate source row {row_index}") + if not isinstance(row, dict): + raise TypeError(f"Dataset Viewer row {row_index} must be an object") + if not isinstance(row.get("text"), str): + raise TypeError(f"Dataset Viewer row {row_index} has missing or invalid text") + source_label = row.get("label") + if not isinstance(source_label, int) or isinstance(source_label, bool): + raise TypeError(f"Dataset Viewer row {row_index} has an invalid label") + if source_label not in LABELS: + raise ValueError(f"Dataset Viewer row {row_index} has unknown label {source_label}") + seen_source_rows.add(row_index) rows.append( { "text": row["text"], - "label": row.get("label"), + "label": source_label, "source": DATASET, "source_row": row_index, } ) - revision_after = _dataset_revision() - if revision_before != revision_after: - raise RuntimeError("Dataset revision changed during download; run again for a consistent slice") - destination.parent.mkdir(parents=True, exist_ok=True) - with destination.open("w", encoding="utf-8", newline="\n") as output: - for row in rows: - output.write(json.dumps(row, ensure_ascii=False) + "\n") - from llm_data_lab.pipeline import sha256_file - sample_hash = sha256_file(destination) - if sample_hash != PINNED_SAMPLE_SHA256: + revision_after = revision_reader() + if revision_before != revision_after: raise RuntimeError( - f"Fetched sample SHA-256 {sample_hash} differs from the pinned sample " - f"{PINNED_SAMPLE_SHA256}; inspect before updating the experiment." + f"Dataset revision changed during acquisition: {revision_before} -> {revision_after}" ) + rows.sort(key=lambda row: row["source_row"]) + sample_bytes = _serialize_rows(rows) + sample_hash = hashlib.sha256(sample_bytes).hexdigest() + if expected_sha256 is not None: + verify_sample_checksum(sample_bytes, expected_sha256) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(sample_bytes) + sample_class_counts = Counter(row["label"] for row in rows) metadata = { "identifier": DATASET, "revision": revision_before, "config": CONFIG, "split": SPLIT, - "selection": f"first {SAMPLE_ROWS} rows (row indices 0–{SAMPLE_ROWS - 1})", + "selection": { + "algorithm": ( + "Divide the training split's source-row index range into four equal strata; " + "select one seeded contiguous 100-row block uniformly within each stratum." + ), + "seed": seed, + "requested_rows": SAMPLE_ROWS, + "blocks": BLOCK_COUNT, + "rows_per_block": BLOCK_SIZE, + "block_start_offsets": block_offsets, + "source_index_strata": [ + { + "start_inclusive": block * population_size // BLOCK_COUNT, + "end_exclusive": (block + 1) * population_size // BLOCK_COUNT, + "selected_block_start": block_offsets[block], + "selected_block_end_exclusive": block_offsets[block] + BLOCK_SIZE, + } + for block in range(BLOCK_COUNT) + ], + "selected_source_row_indices": [row["source_row"] for row in rows], + "sample_class_counts": { + LABELS[label]: sample_class_counts.get(label, 0) for label in LABELS + }, + }, "row_count": len(rows), - "source_api": VIEWER_URL, + "training_split_rows": population_size, + "sample_sha256": sample_hash, + "source_api": VIEWER_ROWS_URL, + "viewer_revision_limitation": ( + "The Dataset Viewer rows endpoint does not accept an immutable Hub revision. " + "The script checks the Hub revision before and after fetching and pins the exact " + "serialized sample checksum to detect changed viewer results." + ), "source_card": f"https://huggingface.co/datasets/{DATASET}", "license_note": ( "Hugging Face lists the license as unknown. The dataset card describes the " "upstream AG News corpus as intended for research and other non-commercial " "activities; verify upstream terms before reuse." ), - "labels": {"0": "World", "1": "Sports", "2": "Business", "3": "Sci/Tech"}, + "labels": {str(label): name for label, name in LABELS.items()}, } return metadata, rows +def _length_distribution(lengths: list[int]) -> dict[str, int]: + if not lengths: + return {key: 0 for key in ("min", "p25", "median", "p75", "p90", "max")} + ordered = sorted(lengths) + + def nearest_rank(percentile: float) -> int: + return ordered[max(0, math.ceil(percentile * len(ordered)) - 1)] + + return { + "min": ordered[0], + "p25": nearest_rank(0.25), + "median": nearest_rank(0.50), + "p75": nearest_rank(0.75), + "p90": nearest_rank(0.90), + "max": ordered[-1], + } + + +def _corpus_lengths(corpus_path: str | Path) -> list[int]: + return [len(row["text"]) for row in read_jsonl(corpus_path)] + + def render_report(summary: dict[str, Any]) -> str: source = summary["input"]["source"] conditions = summary["conditions"] label_names = source["labels"] for result in conditions.values(): - result["label_counts"] = dict( - Counter( - str(row.get("label")) - for row in read_jsonl(result["corpus_path"]) - ) + rows = list(read_jsonl(result["corpus_path"])) + result["label_counts"] = { + str(label): count + for label, count in sorted(Counter(str(row.get("label")) for row in rows).items()) + } + result["length_distribution_chars"] = _length_distribution( + [len(row["text"]) for row in rows] ) raw_label_counts = conditions["raw"]["label_counts"] filtered_label_counts = conditions["full_filter"]["label_counts"] @@ -131,7 +290,7 @@ def render_report(summary: dict[str, Any]) -> str: else "All source classes appear in this prefix. " ) class_note = ( - "Source-order class counts are " + "Sample class counts before preparation are " + ", ".join( f"{label_names[label]}: {raw_label_counts.get(label, 0)}" for label in label_names @@ -158,9 +317,17 @@ def render_report(summary: dict[str, Any]) -> str: f"- Dataset: [{source['identifier']}]({source['source_card']})", f"- Hub revision: `{source['revision']}`", f"- Config/split: `{source['config']}` / `{source['split']}`", - f"- Sample: {source['selection']} ({summary['input']['documents']} rows)", + f"- Sampling method: {source['selection']['algorithm']}", + ( + f"- Sampling seed: `{source['selection']['seed']}`; requested/actual: " + f"{source['selection']['requested_rows']}/{source['row_count']} rows" + ), + f"- Sample class counts: {source['selection']['sample_class_counts']}", + f"- Training split rows: {source['training_split_rows']}", + f"- Selected source row blocks: {source['selection']['source_index_strata']}", f"- Input JSONL SHA-256: `{summary['input']['sha256']}`", f"- Acquisition API: [{source['source_api']}]({source['source_api']})", + f"- Revision limitation: {source['viewer_revision_limitation']}", f"- License note: {source['license_note']}", ( "- The downloaded sample and condition corpora are written under the ignored `data/` directory; " @@ -173,22 +340,30 @@ def render_report(summary: dict[str, Any]) -> str: "python examples/data_quality_ablation/run_public_dataset.py", "```", "", - "## Results", + "## Observed results", + "", + "Retention denominator for every condition is the same sampled input corpus.", "", - "| Condition | Documents | Retained | Characters | Mean chars/doc | Mean words/doc |", - "|---|---:|---:|---:|---:|---:|", + "| Condition | Input | Output | Retained | Characters | Whitespace words | Mean chars/doc | Length chars min / p25 / median / p75 / p90 / max |", + "|---|---:|---:|---:|---:|---:|---:|---|", ] + input_count = summary["input"]["documents"] for name, result in conditions.items(): stats = result["corpus_stats"] + distribution = result["length_distribution_chars"] + length_values = " / ".join( + str(distribution[key]) for key in ("min", "p25", "median", "p75", "p90", "max") + ) lines.append( - f"| `{name}` | {stats['documents']} | {result['retention_rate_vs_input']:.1%} | " - f"{stats['characters']} | {stats['mean_chars_per_document']:.1f} | " - f"{stats['mean_words_per_document']:.1f} |" + f"| `{name}` | {input_count} | {stats['documents']} | " + f"{result['retention_rate_vs_input']:.1%} | {stats['characters']} | " + f"{stats['whitespace_words']} | {stats['mean_chars_per_document']:.1f} | " + f"{length_values} |" ) lines.extend( [ "", - "Label counts (the source sample’s original class labels):", + "Label counts after each condition:", "", "| Condition | " + " | ".join(label_names.values()) + " |", "|---|" + "---:|" * len(label_names), @@ -201,20 +376,56 @@ def render_report(summary: dict[str, Any]) -> str: + " | ".join(str(counts.get(label, 0)) for label in label_names) + " |" ) - lines.extend(["", class_note, "", "### Stage effects", ""]) + lines.extend(["", class_note, "", "Source document counts after each condition:", ""]) + source_names = sorted( + { + source_name + for result in conditions.values() + for source_name in result["corpus_stats"]["source_document_counts"] + } + ) + lines.append("| Condition | " + " | ".join(source_names) + " |") + lines.append("|---|" + "---:|" * len(source_names)) + for name, result in conditions.items(): + counts = result["corpus_stats"]["source_document_counts"] + lines.append( + f"| `{name}` | " + " | ".join(str(counts.get(source_name, 0)) for source_name in source_names) + " |" + ) + lines.extend(["", "Per-condition corpus SHA-256:", ""]) + for name, result in conditions.items(): + lines.append(f"- `{name}`: `{result['corpus_sha256']}`") + lines.extend(["", "### Stage effects", ""]) + lines.append( + f"- `raw` validation/copy: {input_count} input → " + f"{conditions['raw']['corpus_stats']['documents']} output documents." + ) for name in ("clean", "clean_dedupe", "full_filter"): stages = conditions[name]["stages"] - pieces = [f"cleaned {stages['clean']['output_documents']} documents"] + clean = stages["clean"] + pieces = [ + f"cleaned {clean['input_documents']} → {clean['output_documents']} documents", + f"empty after cleaning: {clean['empty_after_cleaning']}", + ] if "dedupe" in stages: - pieces.append(f"removed {stages['dedupe']['exact_duplicates_removed']} exact duplicates") + dedupe = stages["dedupe"] + pieces.append( + f"deduplicated {dedupe['input_documents']} → {dedupe['output_documents']} " + f"(removed {dedupe['exact_duplicates_removed']} exact duplicates)" + ) if "filter" in stages: filter_report = stages["filter"] rejected = filter_report.get("rejected_by_reason", {}) pieces.append( - f"filtered {filter_report['input_documents'] - filter_report['output_documents']} " - f"documents ({', '.join(f'{key}: {value}' for key, value in rejected.items()) or 'none'})" + f"filtered {filter_report['input_documents']} → {filter_report['output_documents']} " + f"({', '.join(f'{key}: {value}' for key, value in rejected.items()) or 'no rejections'})" ) lines.append(f"- `{name}`: " + "; ".join(pieces) + ".") + deduped_path = Path(conditions["full_filter"]["corpus_path"]).with_name( + "deduplicated.jsonl" + ) + min_chars = summary["filter_config"]["min_chars"] + short_lengths = [length for length in _corpus_lengths(deduped_path) if length < min_chars] + short_distribution = _length_distribution(short_lengths) lines.extend( [ "", @@ -224,12 +435,23 @@ def render_report(summary: dict[str, Any]) -> str: f"maximum {summary['filter_config']['max_chars']} characters, and " f"minimum unique-word ratio {summary['filter_config']['min_unique_word_ratio']:.2f}." ), + ( + f"The minimum-character rule is the existing general-purpose default ({min_chars}), " + "kept unchanged for this demonstration; it was not tuned on a test split or model result." + ), + ( + f"Pre-filter documents shorter than {min_chars} characters: {len(short_lengths)}; " + f"length min/median/max: {short_distribution['min']}/" + f"{short_distribution['median']}/{short_distribution['max']} characters." + ), "", "## Interpretation", "", ( - "These results describe only how this particular 300-row prefix responds to the configured " - "preprocessing steps. The prefix is not a random sample of the full corpus. Exact deduplication " + "This is a source-index-stratified block sample, not a simple random sample or a " + "representative sample of the full corpus. Contiguous blocks can cluster similar documents, " + "and class composition is incidental rather than balanced by design; report observed class " + "counts without generalizing them. Exact deduplication " "uses cleaned text, so duplicates with different non-text labels retain only their first row. " "The filter is a heuristic; retention does not measure usefulness or model quality. For causal " "claims about data quality, train matched models and evaluate them on the same held-out set." @@ -237,7 +459,8 @@ def render_report(summary: dict[str, Any]) -> str: "", ( "The machine-readable run, per-condition manifests, and filter report are in " - "`data/ag_news_ablation/` after running the command above." + "`data/ag_news_ablation/` after running the command above. Raw article text is not included " + "in this report." ), "", ] @@ -254,11 +477,11 @@ def main() -> None: 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) + parser.add_argument("--seed", type=int, default=DEFAULT_SEED) args = parser.parse_args() args.output_dir.mkdir(parents=True, exist_ok=True) - input_path = args.output_dir / "ag_news_train_first_300.jsonl" - metadata, _ = fetch_sample(input_path) + input_path = args.output_dir / "ag_news_train_stratified_400.jsonl" + metadata, _ = fetch_sample(input_path, seed=args.seed) summary = run_ablation( input_path, args.output_dir / "conditions", @@ -275,6 +498,8 @@ def main() -> None: json.dumps(summary, indent=2, ensure_ascii=False) + "\n", encoding="utf-8", ) + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(encoding="utf-8") print(report) diff --git a/examples/trl_integrations/README.md b/examples/trl_integrations/README.md new file mode 100644 index 0000000..5f5b4d1 --- /dev/null +++ b/examples/trl_integrations/README.md @@ -0,0 +1,19 @@ +# Optional TRL integrations + +These examples show how the SFT and DPO adapter outputs can be passed to existing TRL trainers. They do not make TRL a core dependency. + +TRL's [SFT trainer](https://huggingface.co/docs/trl/en/sft_trainer) accepts conversational `messages`, while its [preference dataset format](https://huggingface.co/docs/trl/en/dataset_formats) uses `prompt`, `chosen`, and `rejected`. The examples preserve those contracts and leave trainer behavior with TRL. + +Install the optional trainer stack with `pip install -e ".[trl]"`. Prepare the input with `llm-data-lab sft-prepare` or `dpo-prepare`, then run: + +```bash +python examples/trl_integrations/sft.py \ + --prepared data/sft_prepared.jsonl --model /path/to/model \ + --revision MODEL_COMMIT --output-dir checkpoints/sft + +python examples/trl_integrations/dpo.py \ + --prepared data/dpo_prepared.jsonl --model /path/to/model \ + --revision MODEL_COMMIT --output-dir checkpoints/dpo +``` + +Use the same model/tokenizer revision used during preparation. TRL still owns training behavior and may apply its own tokenization and loss-mask logic. The scripts are integration examples, not tested training runs. diff --git a/examples/trl_integrations/dpo.py b/examples/trl_integrations/dpo.py new file mode 100644 index 0000000..c826150 --- /dev/null +++ b/examples/trl_integrations/dpo.py @@ -0,0 +1,45 @@ +"""Minimal optional TRL DPO integration for an already prepared JSONL file.""" + +from __future__ import annotations + +import argparse +from pathlib import Path + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prepared", type=Path, required=True) + parser.add_argument("--model", required=True) + parser.add_argument("--revision", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + + try: + from datasets import load_dataset + from transformers import AutoModelForCausalLM, AutoTokenizer + from trl import DPOConfig, DPOTrainer + except ImportError as exc: + raise SystemExit('Install the optional stack with `pip install -e ".[trl]"`.') from exc + + dataset = load_dataset("json", data_files=str(args.prepared), split="train") + required = {"prompt", "chosen", "rejected"} + missing = required - set(dataset.column_names) + if missing: + raise ValueError(f"Prepared DPO JSONL is missing columns: {sorted(missing)}") + dataset = dataset.remove_columns( + [column for column in dataset.column_names if column not in required] + ) + tokenizer = AutoTokenizer.from_pretrained(args.model, revision=args.revision) + model = AutoModelForCausalLM.from_pretrained(args.model, revision=args.revision) + trainer = DPOTrainer( + model=model, + args=DPOConfig(output_dir=str(args.output_dir), report_to="none"), + train_dataset=dataset, + processing_class=tokenizer, + ) + trainer.train() + trainer.save_model(str(args.output_dir)) + + +if __name__ == "__main__": + main() diff --git a/examples/trl_integrations/sft.py b/examples/trl_integrations/sft.py new file mode 100644 index 0000000..8bae9a8 --- /dev/null +++ b/examples/trl_integrations/sft.py @@ -0,0 +1,50 @@ +"""Minimal optional TRL SFT integration for an already prepared JSONL file.""" + +from __future__ import annotations + +import argparse +from pathlib import Path + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prepared", type=Path, required=True) + parser.add_argument("--model", required=True) + parser.add_argument("--revision", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + + try: + from datasets import load_dataset + from transformers import AutoModelForCausalLM, AutoTokenizer + from trl import SFTConfig, SFTTrainer + except ImportError as exc: + raise SystemExit('Install the optional stack with `pip install -e ".[trl]"`.') from exc + + dataset = load_dataset("json", data_files=str(args.prepared), split="train") + if "messages" not in dataset.column_names: + raise ValueError("Prepared SFT JSONL must include the 'messages' column") + # TRL builds its own assistant loss mask from the same chat template; the + # prepared input_ids/assistant_mask remain available in the audit artifact. + dataset = dataset.remove_columns( + [column for column in dataset.column_names if column != "messages"] + ) + tokenizer = AutoTokenizer.from_pretrained(args.model, revision=args.revision) + model = AutoModelForCausalLM.from_pretrained(args.model, revision=args.revision) + trainer = SFTTrainer( + model=model, + args=SFTConfig( + output_dir=str(args.output_dir), + max_length=1024, + assistant_only_loss=True, + report_to="none", + ), + train_dataset=dataset, + processing_class=tokenizer, + ) + trainer.train() + trainer.save_model(str(args.output_dir)) + + +if __name__ == "__main__": + main() diff --git a/pyproject.toml b/pyproject.toml index fb470f5..54a216a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,6 +14,18 @@ dependencies = [] [project.optional-dependencies] dev = ["pytest>=8.0", "ruff>=0.5"] +transformers = ["transformers>=4.44"] +training = [ + "accelerate>=1.0,<2", + "datasets>=3.0,<5", + "torch>=2.4", + "transformers>=4.50,<6", +] +trl = [ + "datasets>=3.0,<5", + "trl>=0.27,<1", + "transformers>=4.50,<6", +] [project.scripts] llm-data-lab = "llm_data_lab.cli:main" @@ -28,3 +40,7 @@ testpaths = ["tests"] [tool.ruff] line-length = 100 target-version = "py310" +include = ["src/**/*.py", "tests/**/*.py", "examples/**/*.py"] + +[tool.ruff.lint] +select = ["E4", "E7", "E9", "F", "I"] diff --git a/src/llm_data_lab/adapters/__init__.py b/src/llm_data_lab/adapters/__init__.py new file mode 100644 index 0000000..f3fd5ae --- /dev/null +++ b/src/llm_data_lab/adapters/__init__.py @@ -0,0 +1 @@ +"""Optional, preparation-only format adapters.""" diff --git a/src/llm_data_lab/adapters/cpt.py b/src/llm_data_lab/adapters/cpt.py new file mode 100644 index 0000000..227a493 --- /dev/null +++ b/src/llm_data_lab/adapters/cpt.py @@ -0,0 +1,218 @@ +"""Preparation helpers for raw-text causal pretraining corpora. + +This module validates and exports token-budgeted JSONL records. It does not +construct training examples, pack sequences, or run a model trainer. +""" + +from __future__ import annotations + +import json +import os +import tempfile +from collections import Counter +from collections.abc import Mapping +from pathlib import Path +from typing import Any, Literal + +from llm_data_lab.pipeline import ( + _ensure_distinct_paths, + _software_environment, + read_jsonl, + sha256_file, +) +from llm_data_lab.token_stats import _identity, _token_ids + +OverflowPolicy = Literal["error", "drop", "truncate"] + + +def _decode(tokenizer: Any, token_ids: list[Any]) -> str: + if not hasattr(tokenizer, "decode"): + raise TypeError("overflow_policy='truncate' requires tokenizer.decode(token_ids)") + return tokenizer.decode( + token_ids, + skip_special_tokens=True, + clean_up_tokenization_spaces=False, + ) + + +def _truncate(tokenizer: Any, text: str, ids: list[Any], max_length: int) -> tuple[str, int]: + candidate = ids[:max_length] + while candidate: + text = _decode(tokenizer, candidate) + if not isinstance(text, str): + raise TypeError("tokenizer.decode(token_ids) must return a string") + result_ids = _token_ids(tokenizer, text) + if len(result_ids) <= max_length: + return text, len(result_ids) + candidate = candidate[:-1] + return "", 0 + + +def _length_summary(lengths: Counter[int]) -> dict[str, Any]: + total = sum(lengths.values()) + tokens = sum(length * count for length, count in lengths.items()) + ordered = sorted(lengths.items()) + + def percentile(fraction: float) -> int: + if not total: + return 0 + target = max(1, int(fraction * total + 0.999999)) + seen = 0 + for length, count in ordered: + seen += count + if seen >= target: + return length + return 0 + + return { + "documents": total, + "total_tokens": tokens, + "min": ordered[0][0] if ordered else 0, + "max": ordered[-1][0] if ordered else 0, + "mean": tokens / total if total else 0.0, + "p50": percentile(0.50), + "p90": percentile(0.90), + "p95": percentile(0.95), + "histogram": {str(length): count for length, count in ordered}, + } + + +def prepare_cpt_dataset( + input_path: str | Path, + output_path: str | Path, + *, + tokenizer: Any, + tokenizer_identifier: str | None = None, + tokenizer_revision: str | None = None, + max_sequence_length: int, + token_budget: int | None = None, + overflow_policy: OverflowPolicy = "drop", + text_field: str = "text", + report_path: str | Path | None = None, +) -> dict[str, Any]: + """Validate and export raw-text JSONL under document and token limits. + + Documents over ``max_sequence_length`` are rejected, truncated through the + tokenizer's ``decode`` method, or raise an error according to + ``overflow_policy``. A document that does not fit the remaining token budget + is rejected as a whole. All source records are inspected so rejection counts + and input token statistics describe the complete input. + """ + if max_sequence_length <= 0: + raise ValueError("max_sequence_length must be positive") + if token_budget is not None and token_budget <= 0: + raise ValueError("token_budget must be positive when provided") + if overflow_policy not in {"error", "drop", "truncate"}: + raise ValueError("overflow_policy must be 'error', 'drop', or 'truncate'") + outputs = [output_path] + if report_path is not None: + outputs.append(report_path) + _ensure_distinct_paths(input_path, *outputs) + + source = Path(input_path) + destination = Path(output_path) + destination.parent.mkdir(parents=True, exist_ok=True) + input_checksum = sha256_file(source) + input_lengths: Counter[int] = Counter() + output_lengths: Counter[int] = Counter() + rejected: Counter[str] = Counter() + input_documents = output_documents = output_tokens = 0 + descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{destination.name}.", suffix=".tmp", dir=destination.parent + ) + os.close(descriptor) + temporary = Path(temporary_name) + try: + with temporary.open("w", encoding="utf-8", newline="\n") as output: + for record_number, row in enumerate(read_jsonl(source), 1): + input_documents += 1 + if not isinstance(row, Mapping): + raise TypeError(f"Record {record_number}: expected a JSON object") + text = row.get(text_field) + if not isinstance(text, str): + raise TypeError(f"Record {record_number}: {text_field!r} must be a string") + if not text.strip(): + rejected["empty_text"] += 1 + continue + try: + token_ids = _token_ids(tokenizer, text) + except Exception as exc: + raise RuntimeError( + f"Tokenizer failed for record {record_number} ({type(exc).__name__})" + ) from None + input_lengths[len(token_ids)] += 1 + if len(token_ids) > max_sequence_length: + if overflow_policy == "error": + raise ValueError( + f"Record {record_number} has {len(token_ids)} tokens; " + f"limit is {max_sequence_length}" + ) + if overflow_policy == "drop": + rejected["sequence_too_long"] += 1 + continue + try: + text, token_count = _truncate( + tokenizer, text, token_ids, max_sequence_length + ) + except Exception as exc: + raise RuntimeError( + f"Could not truncate record {record_number} " + f"({type(exc).__name__})" + ) from None + if not text.strip(): + rejected["empty_after_truncation"] += 1 + continue + row = dict(row) + row[text_field] = text + else: + token_count = len(token_ids) + if token_budget is not None and output_tokens + token_count > token_budget: + rejected["token_budget_exceeded"] += 1 + continue + output.write(json.dumps(row, ensure_ascii=False) + "\n") + output_documents += 1 + output_tokens += token_count + output_lengths[token_count] += 1 + os.replace(temporary, destination) + except BaseException: + temporary.unlink(missing_ok=True) + raise + + report = { + "schema_version": 1, + "input": { + "path": str(source), + "sha256": input_checksum, + "documents": input_documents, + "token_lengths": _length_summary(input_lengths), + }, + "output": { + "path": str(destination), + "sha256": sha256_file(destination), + "documents": output_documents, + "retained_documents": output_documents, + "rejected_documents": input_documents - output_documents, + "rejected_by_reason": dict(rejected), + "token_lengths": _length_summary(output_lengths), + }, + "tokenizer": _identity(tokenizer, tokenizer_identifier, tokenizer_revision), + "configuration": { + "text_field": text_field, + "max_sequence_length": max_sequence_length, + "token_budget": token_budget, + "overflow_policy": overflow_policy, + "add_special_tokens": False, + }, + "software": _software_environment(), + "scope_note": ( + "Preparation and validation only. This adapter does not pack sequences " + "or train/evaluate a model." + ), + } + if report_path is not None: + report_file = Path(report_path) + report_file.parent.mkdir(parents=True, exist_ok=True) + report_file.write_text( + json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" + ) + return report diff --git a/src/llm_data_lab/adapters/dpo.py b/src/llm_data_lab/adapters/dpo.py new file mode 100644 index 0000000..8fae9a2 --- /dev/null +++ b/src/llm_data_lab/adapters/dpo.py @@ -0,0 +1,282 @@ +"""Preparation and integrity checks for direct-preference optimization pairs.""" + +from __future__ import annotations + +import hashlib +import json +import os +import tempfile +from collections import Counter, defaultdict +from collections.abc import Mapping +from pathlib import Path +from typing import Any, Literal + +from llm_data_lab.leakage import _normalize, check_split_overlap +from llm_data_lab.pipeline import ( + _ensure_distinct_paths, + _software_environment, + read_jsonl, + sha256_file, +) +from llm_data_lab.token_stats import _identity, _token_ids + +from .cpt import _decode, _length_summary + +DPOOverflowPolicy = Literal["error", "drop", "truncate"] +ConflictPolicy = Literal["report", "error"] + + +def _fingerprint(text: str, normalization: str) -> str: + return hashlib.sha256(_normalize(text, normalization).encode("utf-8")).hexdigest() + + +def _truncate_answer( + tokenizer: Any, prompt: str, answer: str, max_length: int, prompt_ids: list[Any] +) -> tuple[str, int, int]: + answer_ids = _token_ids(tokenizer, answer) + candidate = answer_ids[: max(0, max_length - len(prompt_ids))] + while candidate: + truncated = _decode(tokenizer, candidate) + if not isinstance(truncated, str): + raise TypeError("tokenizer.decode(token_ids) must return a string") + sequence_length = len(_token_ids(tokenizer, prompt + truncated)) + answer_length = len(_token_ids(tokenizer, truncated)) + if truncated.strip() and sequence_length <= max_length: + return truncated, answer_length, sequence_length + candidate = candidate[:-1] + return "", 0, len(prompt_ids) + + +def _read_pair_fields(row: Any, record_number: int) -> tuple[str, str, str]: + if not isinstance(row, Mapping): + raise TypeError(f"Record {record_number}: expected a JSON object") + values = [] + for field in ("prompt", "chosen", "rejected"): + value = row.get(field) + if not isinstance(value, str): + raise TypeError(f"Record {record_number}: {field!r} must be a string") + if not value.strip(): + raise ValueError(f"Record {record_number}: {field!r} must not be empty") + values.append(value) + if values[1] == values[2]: + raise ValueError(f"Record {record_number}: chosen and rejected answers are identical") + return values[0], values[1], values[2] + + +def check_dpo_split_overlap( + splits: Mapping[str, str | Path | Any], *, normalization: str = "exact" +) -> dict[str, Any]: + """Check whether any exact prompt appears in more than one pair split.""" + report = check_split_overlap(splits, text_field="prompt", normalization=normalization) + report["integrity_scope"] = "DPO prompt-level pair leakage" + return report + + +def prepare_dpo_dataset( + input_path: str | Path, + output_path: str | Path, + *, + tokenizer: Any, + tokenizer_identifier: str | None = None, + tokenizer_revision: str | None = None, + max_sequence_length: int, + overflow_policy: DPOOverflowPolicy = "drop", + conflict_policy: ConflictPolicy = "report", + prompt_normalization: str = "exact", + report_path: str | Path | None = None, +) -> dict[str, Any]: + """Validate preference pairs and export token-counted JSONL. + + Length limits apply separately to prompt+chosen and prompt+rejected. When + truncating, the prompt is preserved and each answer is shortened to fit. + Contradictory preferences are preserved and counted by default; choose + ``conflict_policy='error'`` to stop before writing any output. + """ + if max_sequence_length <= 0: + raise ValueError("max_sequence_length must be positive") + if overflow_policy not in {"error", "drop", "truncate"}: + raise ValueError("overflow_policy must be 'error', 'drop', or 'truncate'") + if conflict_policy not in {"report", "error"}: + raise ValueError("conflict_policy must be 'report' or 'error'") + if prompt_normalization not in {"exact", "nfc_casefold_whitespace"}: + raise ValueError("prompt_normalization must be 'exact' or 'nfc_casefold_whitespace'") + outputs = [output_path] + ([report_path] if report_path is not None else []) + _ensure_distinct_paths(input_path, *outputs) + source, destination = Path(input_path), Path(output_path) + destination.parent.mkdir(parents=True, exist_ok=True) + input_checksum = sha256_file(source) + + prompt_counts: Counter[str] = Counter() + observed_pairs: dict[str, set[tuple[str, str]]] = defaultdict(set) + for record_number, row in enumerate(read_jsonl(source), 1): + try: + prompt, chosen, rejected = _read_pair_fields(row, record_number) + except (TypeError, ValueError): + continue + prompt_key = _fingerprint(prompt, prompt_normalization) + prompt_counts[prompt_key] += 1 + observed_pairs[prompt_key].add( + (_fingerprint(chosen, "exact"), _fingerprint(rejected, "exact")) + ) + conflicting_prompts = { + prompt + for prompt, pairs in observed_pairs.items() + if any((rejected, chosen) in pairs for chosen, rejected in pairs) + } + if conflicting_prompts and conflict_policy == "error": + raise ValueError( + f"Found {len(conflicting_prompts)} prompts with contradictory preferences" + ) + + lengths: dict[str, Counter[int]] = { + "prompt": Counter(), + "chosen": Counter(), + "rejected": Counter(), + } + output_lengths: dict[str, Counter[int]] = {"chosen": Counter(), "rejected": Counter()} + rejected_counts: Counter[str] = Counter() + input_documents = output_documents = 0 + descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{destination.name}.", suffix=".tmp", dir=destination.parent + ) + os.close(descriptor) + temporary = Path(temporary_name) + try: + with temporary.open("w", encoding="utf-8", newline="\n") as output: + for record_number, row in enumerate(read_jsonl(source), 1): + input_documents += 1 + try: + prompt, chosen, rejected = _read_pair_fields(row, record_number) + except TypeError as exc: + reason = "missing_or_invalid_field" + if "expected a JSON object" in str(exc): + reason = "invalid_record" + rejected_counts[reason] += 1 + continue + except ValueError as exc: + reason = ( + "identical_answers" + if "answers are identical" in str(exc) + else "empty_field" + ) + rejected_counts[reason] += 1 + continue + try: + prompt_ids = _token_ids(tokenizer, prompt) + chosen_ids = _token_ids(tokenizer, chosen) + rejected_ids = _token_ids(tokenizer, rejected) + chosen_sequence_ids = _token_ids(tokenizer, prompt + chosen) + rejected_sequence_ids = _token_ids(tokenizer, prompt + rejected) + except Exception as exc: + raise RuntimeError( + f"Tokenizer failed for record {record_number} ({type(exc).__name__})" + ) from None + lengths["prompt"][len(prompt_ids)] += 1 + lengths["chosen"][len(chosen_ids)] += 1 + lengths["rejected"][len(rejected_ids)] += 1 + if not chosen_ids or not rejected_ids: + rejected_counts["empty_tokenized_answer"] += 1 + continue + chosen_total = len(chosen_sequence_ids) + rejected_total = len(rejected_sequence_ids) + if max(chosen_total, rejected_total) > max_sequence_length: + if overflow_policy == "error": + raise ValueError( + f"Record {record_number} exceeds {max_sequence_length} tokens " + "for at least one preference sequence" + ) + if overflow_policy == "drop": + rejected_counts["sequence_too_long"] += 1 + continue + if len(prompt_ids) >= max_sequence_length: + rejected_counts["prompt_too_long"] += 1 + continue + try: + if chosen_total > max_sequence_length: + chosen, chosen_count, chosen_total = _truncate_answer( + tokenizer, prompt, chosen, max_sequence_length, prompt_ids + ) + else: + chosen_count = len(chosen_ids) + if rejected_total > max_sequence_length: + rejected, rejected_count, rejected_total = _truncate_answer( + tokenizer, prompt, rejected, max_sequence_length, prompt_ids + ) + else: + rejected_count = len(rejected_ids) + except Exception as exc: + raise RuntimeError( + f"Could not truncate record {record_number} " + f"({type(exc).__name__})" + ) from None + if not chosen.strip() or not rejected.strip(): + rejected_counts["empty_after_truncation"] += 1 + continue + if chosen == rejected: + rejected_counts["identical_after_truncation"] += 1 + continue + else: + chosen_count, rejected_count = len(chosen_ids), len(rejected_ids) + result = dict(row) + result.update( + { + "prompt": prompt, + "chosen": chosen, + "rejected": rejected, + "token_counts": { + "prompt": len(prompt_ids), + "chosen": chosen_count, + "rejected": rejected_count, + "prompt_plus_chosen": chosen_total, + "prompt_plus_rejected": rejected_total, + }, + } + ) + output.write(json.dumps(result, ensure_ascii=False) + "\n") + output_documents += 1 + output_lengths["chosen"][chosen_count] += 1 + output_lengths["rejected"][rejected_count] += 1 + os.replace(temporary, destination) + except BaseException: + temporary.unlink(missing_ok=True) + raise + + duplicate_prompt_count = sum(count > 1 for count in prompt_counts.values()) + report = { + "schema_version": 1, + "input": {"path": str(source), "sha256": input_checksum, "documents": input_documents}, + "output": { + "path": str(destination), + "sha256": sha256_file(destination), + "documents": output_documents, + "retained_documents": output_documents, + "rejected_documents": input_documents - output_documents, + "rejected_by_reason": dict(rejected_counts), + "input_token_lengths": {key: _length_summary(value) for key, value in lengths.items()}, + "token_lengths": { + key: _length_summary(value) for key, value in output_lengths.items() + }, + }, + "integrity": { + "duplicate_prompt_groups": duplicate_prompt_count, + "duplicate_prompt_records": sum(max(count - 1, 0) for count in prompt_counts.values()), + "conflicting_prompt_count": len(conflicting_prompts), + "conflict_policy": conflict_policy, + }, + "tokenizer": _identity(tokenizer, tokenizer_identifier, tokenizer_revision), + "configuration": { + "max_sequence_length": max_sequence_length, + "overflow_policy": overflow_policy, + "prompt_normalization": prompt_normalization, + "conflict_policy": conflict_policy, + }, + "software": _software_environment(), + "scope_note": "Pair preparation and integrity checks only. No preference trainer is run.", + } + if report_path is not None: + report_file = Path(report_path) + report_file.parent.mkdir(parents=True, exist_ok=True) + report_file.write_text( + json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" + ) + return report diff --git a/src/llm_data_lab/adapters/sft.py b/src/llm_data_lab/adapters/sft.py new file mode 100644 index 0000000..3f8aed5 --- /dev/null +++ b/src/llm_data_lab/adapters/sft.py @@ -0,0 +1,228 @@ +"""Preparation-only validation and export for supervised chat conversations.""" + +from __future__ import annotations + +import json +import os +import tempfile +from collections import Counter +from collections.abc import Mapping +from pathlib import Path +from typing import Any, Literal + +from llm_data_lab.pipeline import ( + _ensure_distinct_paths, + _software_environment, + read_jsonl, + sha256_file, +) +from llm_data_lab.token_stats import _identity + +from .cpt import _length_summary + +SFTOverflowPolicy = Literal["error", "drop", "truncate"] +TRUNCATION_SIDES = ("left", "right") +ALLOWED_ROLES = ("system", "user", "assistant") + + +def _as_list(value: Any, *, field: str, record_number: int) -> list[Any]: + if hasattr(value, "tolist"): + value = value.tolist() + if isinstance(value, (str, bytes)) or value is None: + raise TypeError(f"Record {record_number}: tokenizer returned invalid {field}") + try: + values = list(value) + except TypeError as exc: + raise TypeError(f"Record {record_number}: tokenizer returned invalid {field}") from exc + if values and isinstance(values[0], list): + if len(values) != 1: + raise ValueError(f"Record {record_number}: tokenizer returned multiple rows") + values = values[0] + return values + + +def _validate_messages(row: Mapping[str, Any], record_number: int) -> list[dict[str, Any]]: + messages = row.get("messages") + if not isinstance(messages, list) or not messages: + raise ValueError(f"Record {record_number}: 'messages' must be a non-empty list") + normalized: list[dict[str, Any]] = [] + assistant_count = 0 + for message_number, message in enumerate(messages, 1): + if not isinstance(message, Mapping): + raise TypeError(f"Record {record_number}, message {message_number}: expected an object") + role = message.get("role") + content = message.get("content") + if role not in ALLOWED_ROLES: + raise ValueError( + f"Record {record_number}, message {message_number}: role must be one of " + f"{', '.join(ALLOWED_ROLES)}" + ) + if not isinstance(content, str): + raise TypeError( + f"Record {record_number}, message {message_number}: content must be a string" + ) + if role == "assistant": + assistant_count += 1 + if not content.strip(): + raise ValueError( + f"Record {record_number}, message {message_number}: assistant response is empty" + ) + normalized.append(dict(message)) + if not assistant_count: + raise ValueError(f"Record {record_number}: conversation has no assistant response") + return normalized + + +def prepare_sft_dataset( + input_path: str | Path, + output_path: str | Path, + *, + tokenizer: Any, + tokenizer_identifier: str | None = None, + tokenizer_revision: str | None = None, + max_sequence_length: int, + overflow_policy: SFTOverflowPolicy = "drop", + truncation_side: Literal["left", "right"] = "right", + report_path: str | Path | None = None, +) -> dict[str, Any]: + """Validate chat records and export token IDs with an assistant loss mask. + + The tokenizer must provide a compatible chat template that supports + ``return_assistant_tokens_mask=True``. The exported ``assistant_mask`` is + framework-neutral: downstream trainers may turn it into labels as needed. + """ + if max_sequence_length <= 0: + raise ValueError("max_sequence_length must be positive") + if overflow_policy not in {"error", "drop", "truncate"}: + raise ValueError("overflow_policy must be 'error', 'drop', or 'truncate'") + if truncation_side not in TRUNCATION_SIDES: + raise ValueError(f"truncation_side must be one of {TRUNCATION_SIDES}") + outputs = [output_path] + ([report_path] if report_path is not None else []) + _ensure_distinct_paths(input_path, *outputs) + source, destination = Path(input_path), Path(output_path) + destination.parent.mkdir(parents=True, exist_ok=True) + input_checksum = sha256_file(source) + lengths: Counter[int] = Counter() + output_lengths: Counter[int] = Counter() + rejected: Counter[str] = Counter() + input_documents = output_documents = 0 + descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{destination.name}.", suffix=".tmp", dir=destination.parent + ) + os.close(descriptor) + temporary = Path(temporary_name) + try: + with temporary.open("w", encoding="utf-8", newline="\n") as output: + for record_number, row in enumerate(read_jsonl(source), 1): + input_documents += 1 + try: + messages = _validate_messages(row, record_number) + except (TypeError, ValueError) as exc: + error_text = str(exc) + if "assistant response is empty" in error_text: + reason = "empty_assistant_response" + elif "no assistant response" in error_text: + reason = "missing_assistant_response" + elif "role must be one of" in error_text: + reason = "invalid_role" + elif "content must be a string" in error_text: + reason = "invalid_content" + else: + reason = "invalid_conversation" + rejected[reason] += 1 + continue + try: + encoded = tokenizer.apply_chat_template( + messages, + tokenize=True, + add_generation_prompt=False, + return_dict=True, + return_assistant_tokens_mask=True, + ) + except Exception as exc: + raise RuntimeError( + f"Chat template failed for record {record_number} " + f"({type(exc).__name__}); it must support assistant span masks " + "and return_assistant_tokens_mask=True" + ) from None + if not isinstance(encoded, Mapping): + raise TypeError( + f"Record {record_number}: chat template must return a mapping " + "with input_ids and assistant_masks" + ) + input_ids = _as_list(encoded.get("input_ids"), field="input_ids", record_number=record_number) + mask_value = encoded.get("assistant_masks", encoded.get("assistant_mask")) + if mask_value is None: + raise ValueError( + f"Record {record_number}: chat template did not return assistant_masks; " + "the template must mark assistant generation spans" + ) + assistant_mask = _as_list(mask_value, field="assistant_masks", record_number=record_number) + if len(input_ids) != len(assistant_mask): + raise ValueError( + f"Record {record_number}: input_ids and assistant mask lengths differ" + ) + if any(value not in (0, 1, False, True) for value in assistant_mask): + raise ValueError(f"Record {record_number}: assistant mask must contain only 0 or 1") + assistant_mask = [int(value) for value in assistant_mask] + lengths[len(input_ids)] += 1 + if len(input_ids) > max_sequence_length: + if overflow_policy == "error": + raise ValueError( + f"Record {record_number} has {len(input_ids)} tokens; " + f"limit is {max_sequence_length}" + ) + if overflow_policy == "drop": + rejected["sequence_too_long"] += 1 + continue + if truncation_side == "left": + input_ids = input_ids[-max_sequence_length:] + assistant_mask = assistant_mask[-max_sequence_length:] + else: + input_ids = input_ids[:max_sequence_length] + assistant_mask = assistant_mask[:max_sequence_length] + if not any(assistant_mask): + rejected["no_supervised_tokens"] += 1 + continue + result = dict(row) + result["messages"] = messages + result["input_ids"] = input_ids + result["assistant_mask"] = assistant_mask + output.write(json.dumps(result, ensure_ascii=False) + "\n") + output_documents += 1 + output_lengths[len(input_ids)] += 1 + os.replace(temporary, destination) + except BaseException: + temporary.unlink(missing_ok=True) + raise + + report = { + "schema_version": 1, + "input": {"path": str(source), "sha256": input_checksum, "documents": input_documents}, + "output": { + "path": str(destination), + "sha256": sha256_file(destination), + "documents": output_documents, + "retained_documents": output_documents, + "rejected_documents": input_documents - output_documents, + "rejected_by_reason": dict(rejected), + "input_token_lengths": _length_summary(lengths), + "token_lengths": _length_summary(output_lengths), + }, + "tokenizer": _identity(tokenizer, tokenizer_identifier, tokenizer_revision), + "configuration": { + "max_sequence_length": max_sequence_length, + "overflow_policy": overflow_policy, + "truncation_side": truncation_side, + "assistant_mask_field": "assistant_mask", + }, + "software": _software_environment(), + "scope_note": "Preparation and schema checks only. No trainer is selected or run.", + } + if report_path is not None: + report_file = Path(report_path) + report_file.parent.mkdir(parents=True, exist_ok=True) + report_file.write_text( + json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" + ) + return report diff --git a/src/llm_data_lab/cli.py b/src/llm_data_lab/cli.py index c170cdc..0bb9b39 100644 --- a/src/llm_data_lab/cli.py +++ b/src/llm_data_lab/cli.py @@ -7,6 +7,10 @@ from pathlib import Path from typing import Any +from llm_data_lab.adapters.cpt import prepare_cpt_dataset +from llm_data_lab.adapters.dpo import check_dpo_split_overlap, prepare_dpo_dataset +from llm_data_lab.adapters.sft import prepare_sft_dataset +from llm_data_lab.leakage import NORMALIZATION_POLICIES, check_split_overlap from llm_data_lab.pipeline import ( clean_jsonl, corpus_stats, @@ -15,6 +19,7 @@ split_jsonl, write_run_manifest, ) +from llm_data_lab.token_stats import _load_tokenizer, token_stats def _print_report(report: dict[str, Any], output: str | None = None) -> None: @@ -64,6 +69,86 @@ def build_parser() -> argparse.ArgumentParser: stats.add_argument("--input", required=True) stats.add_argument("--text-field", default="text") stats.add_argument("--output", default=None) + stats.add_argument( + "--tokenizer", + help="Optional Transformers tokenizer name/path for token counts (requires [transformers]).", + ) + stats.add_argument("--tokenizer-revision", help="Optional tokenizer revision.") + + overlap = commands.add_parser( + "overlap", help="Check exact text overlap across two or more named JSONL splits." + ) + overlap.add_argument( + "--split", + action="append", + required=True, + metavar="NAME=PATH", + help="Named split input; repeat at least twice (example: train=data/train.jsonl).", + ) + overlap.add_argument("--text-field", default="text") + overlap.add_argument( + "--normalization", + choices=NORMALIZATION_POLICIES, + default="exact", + help="Text comparison policy; normalized comparison uses NFC, casefolding, and whitespace collapse.", + ) + overlap.add_argument("--output", default=None) + + cpt = commands.add_parser( + "cpt-prepare", help="Validate and export raw-text data under CPT token limits." + ) + cpt.add_argument("--input", required=True) + cpt.add_argument("--output", required=True) + cpt.add_argument("--tokenizer", required=True, help="Transformers tokenizer name or path.") + cpt.add_argument("--tokenizer-revision", default=None) + cpt.add_argument("--text-field", default="text") + cpt.add_argument("--max-sequence-length", type=int, required=True) + cpt.add_argument("--token-budget", type=int, default=None) + cpt.add_argument( + "--overflow-policy", + choices=["error", "drop", "truncate"], + default="drop", + help="How to handle documents longer than the sequence limit.", + ) + cpt.add_argument("--report", default=None, help="Optional JSON preparation report path.") + + sft = commands.add_parser( + "sft-prepare", help="Validate chat data and export token IDs with assistant masks." + ) + sft.add_argument("--input", required=True) + sft.add_argument("--output", required=True) + sft.add_argument("--tokenizer", required=True, help="Transformers tokenizer name or path.") + sft.add_argument("--tokenizer-revision", default=None) + sft.add_argument("--max-sequence-length", type=int, required=True) + sft.add_argument("--overflow-policy", choices=["error", "drop", "truncate"], default="drop") + sft.add_argument("--truncation-side", choices=["left", "right"], default="right") + sft.add_argument("--report", default=None) + + dpo = commands.add_parser( + "dpo-prepare", help="Validate and export token-counted preference pairs." + ) + dpo.add_argument("--input", required=True) + dpo.add_argument("--output", required=True) + dpo.add_argument("--tokenizer", required=True, help="Transformers tokenizer name or path.") + dpo.add_argument("--tokenizer-revision", default=None) + dpo.add_argument("--max-sequence-length", type=int, required=True) + dpo.add_argument("--overflow-policy", choices=["error", "drop", "truncate"], default="drop") + dpo.add_argument("--conflict-policy", choices=["report", "error"], default="report") + dpo.add_argument( + "--prompt-normalization", + choices=NORMALIZATION_POLICIES, + default="exact", + ) + dpo.add_argument("--report", default=None) + + dpo_overlap = commands.add_parser( + "dpo-overlap", help="Check prompt overlap across preference-pair splits." + ) + dpo_overlap.add_argument("--split", action="append", required=True, metavar="NAME=PATH") + dpo_overlap.add_argument( + "--normalization", choices=NORMALIZATION_POLICIES, default="exact" + ) + dpo_overlap.add_argument("--output", default=None) manifest = commands.add_parser( "manifest", @@ -112,7 +197,86 @@ def main() -> None: ) _print_report(report) elif args.command == "stats": - _print_report(corpus_stats(args.input, text_field=args.text_field), args.output) + report = corpus_stats(args.input, text_field=args.text_field) + if args.tokenizer: + report["token_stats"] = token_stats( + args.input, + tokenizer=args.tokenizer, + revision=args.tokenizer_revision, + text_field=args.text_field, + ) + _print_report(report, args.output) + elif args.command == "overlap": + splits: dict[str, str] = {} + for spec in args.split: + name, separator, path = spec.partition("=") + if not separator or not name or not path: + raise SystemExit(f"Invalid --split {spec!r}; expected NAME=PATH") + if name in splits: + raise SystemExit(f"Duplicate split name {name!r}") + splits[name] = path + _print_report( + check_split_overlap( + splits, + text_field=args.text_field, + normalization=args.normalization, + ), + args.output, + ) + elif args.command == "cpt-prepare": + tokenizer = _load_tokenizer(args.tokenizer, args.tokenizer_revision) + report = prepare_cpt_dataset( + args.input, + args.output, + tokenizer=tokenizer, + tokenizer_identifier=args.tokenizer, + tokenizer_revision=args.tokenizer_revision, + max_sequence_length=args.max_sequence_length, + token_budget=args.token_budget, + overflow_policy=args.overflow_policy, + text_field=args.text_field, + report_path=args.report, + ) + _print_report(report) + elif args.command == "sft-prepare": + tokenizer = _load_tokenizer(args.tokenizer, args.tokenizer_revision) + report = prepare_sft_dataset( + args.input, + args.output, + tokenizer=tokenizer, + tokenizer_identifier=args.tokenizer, + tokenizer_revision=args.tokenizer_revision, + max_sequence_length=args.max_sequence_length, + overflow_policy=args.overflow_policy, + truncation_side=args.truncation_side, + report_path=args.report, + ) + _print_report(report) + elif args.command == "dpo-prepare": + tokenizer = _load_tokenizer(args.tokenizer, args.tokenizer_revision) + report = prepare_dpo_dataset( + args.input, + args.output, + tokenizer=tokenizer, + tokenizer_identifier=args.tokenizer, + tokenizer_revision=args.tokenizer_revision, + max_sequence_length=args.max_sequence_length, + overflow_policy=args.overflow_policy, + conflict_policy=args.conflict_policy, + prompt_normalization=args.prompt_normalization, + report_path=args.report, + ) + _print_report(report) + elif args.command == "dpo-overlap": + splits: dict[str, str] = {} + for spec in args.split: + name, separator, path = spec.partition("=") + if not separator or not name or not path: + raise SystemExit(f"Invalid --split {spec!r}; expected NAME=PATH") + if name in splits: + raise SystemExit(f"Duplicate split name {name!r}") + splits[name] = path + _print_report(check_dpo_split_overlap(splits, normalization=args.normalization), args.output) elif args.command in {"manifest", "run-manifest", "experiment-manifest"}: report = write_run_manifest( args.output, diff --git a/src/llm_data_lab/leakage.py b/src/llm_data_lab/leakage.py new file mode 100644 index 0000000..e04fcd9 --- /dev/null +++ b/src/llm_data_lab/leakage.py @@ -0,0 +1,101 @@ +"""Exact text overlap checks across supplied dataset splits.""" + +from __future__ import annotations + +import hashlib +import unicodedata +from collections.abc import Iterable, Mapping +from pathlib import Path +from typing import Any + +from .pipeline import _software_environment, read_jsonl, sha256_file + +NORMALIZATION_POLICIES = ("exact", "nfc_casefold_whitespace") + + +def _normalize(text: str, policy: str) -> str: + if policy == "exact": + return text + if policy == "nfc_casefold_whitespace": + return " ".join(unicodedata.normalize("NFC", text).casefold().split()) + raise ValueError( + f"Unknown normalization policy {policy!r}; choose from {', '.join(NORMALIZATION_POLICIES)}" + ) + + +def check_split_overlap( + splits: Mapping[str, str | Path | Iterable[Mapping[str, Any]]], + *, + text_field: str = "text", + normalization: str = "exact", +) -> dict[str, Any]: + """Report exact normalized-text overlap without returning document contents. + + ``exact`` compares the text field byte-for-codepoint as decoded from JSON. + ``nfc_casefold_whitespace`` applies Unicode NFC, case folding, and collapses + all whitespace runs to one space before comparison. This detects exact text + overlap under that policy only; it does not detect semantic or pretraining leakage. + """ + if normalization not in NORMALIZATION_POLICIES: + _normalize("", normalization) + if len(splits) < 2: + raise ValueError("At least two named splits are required") + if any(not isinstance(name, str) or not name for name in splits): + raise ValueError("Split names must be non-empty strings") + contents: dict[str, dict[str, int]] = {} + row_counts: dict[str, int] = {} + checksums: dict[str, str | None] = {} + for name, source in splits.items(): + records = read_jsonl(source) if isinstance(source, (str, Path)) else source + checksums[name] = sha256_file(source) if isinstance(source, (str, Path)) else None + seen: dict[str, int] = {} + for record_number, row in enumerate(records, 1): + if not isinstance(row, Mapping): + raise TypeError(f"Split {name!r}, record {record_number}: expected an object") + text = row.get(text_field) + if not isinstance(text, str): + raise TypeError( + f"Split {name!r}, record {record_number}: {text_field!r} must be a string" + ) + normalized = _normalize(text, normalization) + key = hashlib.sha256(normalized.encode("utf-8")).hexdigest() + seen[key] = seen.get(key, 0) + 1 + contents[name] = seen + row_counts[name] = sum(seen.values()) + + pairs: list[dict[str, Any]] = [] + affected_texts = {name: set() for name in contents} + names = list(contents) + for left_index, left in enumerate(names): + for right in names[left_index + 1 :]: + common = contents[left].keys() & contents[right].keys() + left_records = sum(contents[left][text] for text in common) + right_records = sum(contents[right][text] for text in common) + pairs.append( + { + "splits": [left, right], + "unique_overlapping_texts": len(common), + "overlapping_documents": {left: left_records, right: right_records}, + } + ) + if common: + affected_texts[left].update(common) + affected_texts[right].update(common) + affected_counts = { + name: sum(contents[name][text] for text in overlapping) + for name, overlapping in affected_texts.items() + } + affected = [name for name, count in affected_counts.items() if count] + return { + "schema_version": 1, + "normalization": normalization, + "text_field": text_field, + "split_documents": row_counts, + "split_sha256": checksums, + "configuration": {"text_field": text_field, "normalization": normalization}, + "software": _software_environment(), + "affected_splits": affected, + "overlapping_documents_by_split": affected_counts, + "pairs": pairs, + "has_overlap": bool(affected), + } diff --git a/src/llm_data_lab/pipeline.py b/src/llm_data_lab/pipeline.py index d818bdc..82df590 100644 --- a/src/llm_data_lab/pipeline.py +++ b/src/llm_data_lab/pipeline.py @@ -3,6 +3,7 @@ from __future__ import annotations import hashlib +import importlib.metadata import json import platform import re @@ -51,6 +52,12 @@ def write_jsonl(path: str | Path, rows: Iterator[dict[str, Any]]) -> int: return count +def _ensure_distinct_paths(source: str | Path, *outputs: str | Path) -> None: + paths = [Path(source).resolve(), *(Path(output).resolve() for output in outputs)] + if len(set(paths)) != len(paths): + raise ValueError("Input, output, and report paths must be different") + + def clean_text(text: str, *, strip_html: bool = True, collapse_punctuation: bool = True) -> str: """Conservatively normalize text; no language-specific transformations.""" text = unicodedata.normalize("NFC", text) @@ -71,7 +78,9 @@ def clean_jsonl( *, text_field: str = "text", strip_html: bool = True, -) -> dict[str, int]: +) -> dict[str, Any]: + _ensure_distinct_paths(input_path, output_path) + input_checksum = sha256_file(input_path) read_count = written_count = empty_count = 0 def rows() -> Iterator[dict[str, Any]]: @@ -93,8 +102,18 @@ def rows() -> Iterator[dict[str, Any]]: yield row write_jsonl(output_path, rows()) - return {"input_documents": read_count, "output_documents": written_count, - "empty_after_cleaning": empty_count} + return { + "input_documents": read_count, + "output_documents": written_count, + "retained_documents": written_count, + "rejected_documents": empty_count, + "rejected_by_reason": {"empty_after_cleaning": empty_count} if empty_count else {}, + "empty_after_cleaning": empty_count, + "input_sha256": input_checksum, + "output_sha256": sha256_file(output_path), + "configuration": {"text_field": text_field, "strip_html": strip_html}, + "software": _software_environment(), + } def deduplicate_jsonl( @@ -103,13 +122,17 @@ def deduplicate_jsonl( *, text_field: str = "text", database_path: str | Path | None = None, -) -> dict[str, int]: +) -> dict[str, Any]: """Exact deduplication backed by SQLite to avoid a large in-memory hash set.""" output = Path(output_path) + _ensure_distinct_paths(input_path, output) + input_checksum = sha256_file(input_path) output.parent.mkdir(parents=True, exist_ok=True) db_path = Path(database_path) if database_path else output.with_suffix(".dedupe.sqlite3") if db_path.resolve() == output.resolve(): raise ValueError("SQLite database path must differ from output path") + if db_path.resolve() == Path(input_path).resolve(): + raise ValueError("SQLite database path must differ from input path") if db_path.exists(): db_path.unlink() db_path.parent.mkdir(parents=True, exist_ok=True) @@ -143,8 +166,18 @@ def deduplicate_jsonl( db_path.unlink(missing_ok=True) except PermissionError: pass - return {"input_documents": read_count, "output_documents": written_count, - "exact_duplicates_removed": duplicate_count} + return { + "input_documents": read_count, + "output_documents": written_count, + "retained_documents": written_count, + "rejected_documents": duplicate_count, + "rejected_by_reason": {"exact_duplicate": duplicate_count} if duplicate_count else {}, + "exact_duplicates_removed": duplicate_count, + "input_sha256": input_checksum, + "output_sha256": sha256_file(output), + "configuration": {"text_field": text_field, "deduplication": "exact_text_sha256"}, + "software": _software_environment(), + } def unique_word_ratio(text: str) -> float: @@ -166,6 +199,10 @@ def filter_jsonl( raise ValueError("Require 0 <= min_chars <= max_chars") if not 0.0 <= min_unique_word_ratio <= 1.0: raise ValueError("min_unique_word_ratio must be between 0 and 1") + _ensure_distinct_paths(input_path, output_path) + if report_path is not None: + _ensure_distinct_paths(input_path, output_path, report_path) + input_checksum = sha256_file(input_path) read_count = written_count = 0 rejected: Counter[str] = Counter() @@ -196,11 +233,22 @@ def rows() -> Iterator[dict[str, Any]]: report: dict[str, Any] = { "input_documents": read_count, "output_documents": written_count, + "retained_documents": written_count, + "rejected_documents": read_count - written_count, "retention_rate": written_count / read_count if read_count else 0.0, "rejected_by_reason": dict(rejected), "min_chars": min_chars, "max_chars": max_chars, "min_unique_word_ratio": min_unique_word_ratio, + "input_sha256": input_checksum, + "output_sha256": sha256_file(output_path), + "configuration": { + "text_field": text_field, + "min_chars": min_chars, + "max_chars": max_chars, + "min_unique_word_ratio": min_unique_word_ratio, + }, + "software": _software_environment(), } if written_count: report["kept_character_count"] = kept_characters @@ -225,6 +273,7 @@ def split_jsonl( if not 0.0 < val_fraction < 1.0: raise ValueError("val_fraction must be strictly between 0 and 1") train_file, val_file = Path(train_path), Path(validation_path) + _ensure_distinct_paths(input_path, train_file, val_file) if train_file.resolve() == val_file.resolve(): raise ValueError("train and validation paths must be different") train_file.parent.mkdir(parents=True, exist_ok=True) @@ -245,9 +294,19 @@ def split_jsonl( else: train.write(json.dumps(row, ensure_ascii=False) + "\n") train_count += 1 - return {"train_documents": train_count, "validation_documents": val_count, - "validation_fraction_requested": val_fraction, "seed": seed, - "note": "Hash-based assignment is deterministic; realized fraction varies slightly."} + return { + "input_documents": train_count + val_count, + "train_documents": train_count, + "validation_documents": val_count, + "input_sha256": sha256_file(input_path), + "train_sha256": sha256_file(train_file), + "validation_sha256": sha256_file(val_file), + "configuration": {"text_field": text_field, "val_fraction": val_fraction, "seed": seed}, + "software": _software_environment(), + "validation_fraction_requested": val_fraction, + "seed": seed, + "note": "Hash-based assignment is deterministic; realized fraction varies slightly.", + } def corpus_stats(input_path: str | Path, *, text_field: str = "text") -> dict[str, Any]: @@ -270,6 +329,9 @@ def corpus_stats(input_path: str | Path, *, text_field: str = "text") -> dict[st "mean_chars_per_document": total_chars / count if count else 0.0, "mean_words_per_document": total_words / count if count else 0.0, "source_document_counts": dict(source_counts), + "input_sha256": sha256_file(input_path), + "configuration": {"text_field": text_field}, + "software": _software_environment(), } @@ -325,7 +387,12 @@ def _load_json_blob(value: Any, *, label: str) -> dict[str, Any]: def _software_environment() -> dict[str, Any]: + try: + package_version = importlib.metadata.version("llm-data-lab") + except importlib.metadata.PackageNotFoundError: + package_version = "0.1.0" return { + "llm_data_lab": package_version, "python": sys.version.replace("\n", " "), "platform": platform.platform(), "platform_system": platform.system(), @@ -363,6 +430,7 @@ def build_dataset_manifest( "identifier": dataset_id, "path": str(input_file), "checksum_sha256": checksum_value, + "documents": sum(1 for _ in read_jsonl(input_file)), }, "pipeline_configuration": _load_json_blob(pipeline_config, label="pipeline"), "seed": seed, diff --git a/src/llm_data_lab/token_stats.py b/src/llm_data_lab/token_stats.py new file mode 100644 index 0000000..fe4907d --- /dev/null +++ b/src/llm_data_lab/token_stats.py @@ -0,0 +1,131 @@ +"""Tokenizer-aware corpus diagnostics with no mandatory tokenizer dependency.""" + +from __future__ import annotations + +import importlib +import math +from collections import Counter +from collections.abc import Iterable, Mapping +from pathlib import Path +from typing import Any + +from .pipeline import _software_environment, read_jsonl, sha256_file + + +def _load_tokenizer(identifier: str, revision: str | None) -> Any: + try: + transformers = importlib.import_module("transformers") + except ImportError as exc: + raise ImportError( + "Loading a tokenizer by name requires the optional Transformers dependency. " + 'Install it with `pip install "llm-data-lab[transformers]"`, or pass a tokenizer object.' + ) from exc + return transformers.AutoTokenizer.from_pretrained(identifier, revision=revision) + + +def _token_ids(tokenizer: Any, text: str) -> list[Any]: + if hasattr(tokenizer, "encode"): + result = tokenizer.encode(text, add_special_tokens=False) + else: + result = tokenizer(text, add_special_tokens=False) + if isinstance(result, Mapping): + result = result.get("input_ids") + if hasattr(result, "tolist"): + result = result.tolist() + if result is None: + raise TypeError("tokenizer did not return token IDs") + if isinstance(result, (str, bytes)): + raise TypeError("tokenizer output must be a sequence of token IDs") + try: + result = list(result) + except TypeError as exc: + raise TypeError("tokenizer output must be a sequence of token IDs") from exc + if result and isinstance(result[0], list): + if len(result) != 1: + raise ValueError("tokenizer returned multiple rows for one document") + result = result[0] + return result + + +def _identity(tokenizer: Any, identifier: str | None, revision: str | None) -> dict[str, Any]: + name = identifier or getattr(tokenizer, "name_or_path", None) + actual_revision = revision + init_kwargs = getattr(tokenizer, "init_kwargs", {}) + if actual_revision is None and isinstance(init_kwargs, Mapping): + actual_revision = init_kwargs.get("_commit_hash") or init_kwargs.get("revision") + return {"identifier": name or "caller_supplied", "revision": actual_revision} + + +def _quantile(length_counts: Counter[int], total: int, fraction: float) -> int: + if not total: + return 0 + target = max(1, math.ceil(fraction * total)) + seen = 0 + for length, count in sorted(length_counts.items()): + seen += count + if seen >= target: + return length + raise AssertionError("quantile target exceeded token-length count") + + +def token_stats( + corpus: str | Path | Iterable[Mapping[str, Any]], + *, + tokenizer: Any | str | None = None, + tokenizer_identifier: str | None = None, + revision: str | None = None, + text_field: str = "text", +) -> dict[str, Any]: + """Count tokens and report document-length distribution. + + Blank/whitespace-only text is defined to have zero tokens and is not passed to + the tokenizer. Other tokenizer errors include the 1-based record number. + Pass a tokenizer object or a Transformers model/tokenizer name. + """ + if tokenizer is None: + raise ValueError("Provide a tokenizer object or tokenizer identifier") + identifier = tokenizer_identifier + if isinstance(tokenizer, str): + identifier = identifier or tokenizer + tokenizer = _load_tokenizer(tokenizer, revision) + docs: Iterable[Mapping[str, Any]] + docs = read_jsonl(corpus) if isinstance(corpus, (str, Path)) else corpus + lengths: Counter[int] = Counter() + total = empty = 0 + for record_number, row in enumerate(docs, 1): + if not isinstance(row, Mapping): + raise TypeError(f"Record {record_number}: each corpus record must be an object") + text = row.get(text_field) + if not isinstance(text, str): + raise TypeError(f"Record {record_number}: {text_field!r} must be a string") + total += 1 + if not text.strip(): + empty += 1 + lengths[0] += 1 + continue + try: + lengths[len(_token_ids(tokenizer, text))] += 1 + except Exception as exc: + raise RuntimeError( + f"Tokenizer failed for record {record_number} ({type(exc).__name__})" + ) from None + total_tokens = sum(length * count for length, count in lengths.items()) + return { + "schema_version": 1, + "input_sha256": sha256_file(corpus) if isinstance(corpus, (str, Path)) else None, + "configuration": {"text_field": text_field, "add_special_tokens": False}, + "software": _software_environment(), + "tokenizer": _identity(tokenizer, identifier, revision), + "documents": total, + "empty_documents": empty, + "total_tokens": total_tokens, + "token_length": { + "min": min(lengths) if lengths else 0, + "max": max(lengths) if lengths else 0, + "mean": total_tokens / total if total else 0.0, + "p50": _quantile(lengths, total, 0.50), + "p90": _quantile(lengths, total, 0.90), + "p95": _quantile(lengths, total, 0.95), + "histogram": {str(size): count for size, count in sorted(lengths.items())}, + }, + } diff --git a/tests/test_ablation_example.py b/tests/test_ablation_example.py index 30fe87e..de19d96 100644 --- a/tests/test_ablation_example.py +++ b/tests/test_ablation_example.py @@ -46,8 +46,15 @@ def test_ablation_writes_four_conditions_and_manifests(tmp_path): assert set(result["conditions"]) == {"raw", "clean", "clean_dedupe", "full_filter"} assert result["conditions"]["raw"]["documents_retained"] == 4 + assert result["conditions"]["clean"]["documents_retained"] == 4 assert result["conditions"]["clean_dedupe"]["documents_retained"] == 3 - assert result["conditions"]["full_filter"]["documents_retained"] < 4 + assert result["conditions"]["clean_dedupe"]["stages"]["dedupe"][ + "exact_duplicates_removed" + ] == 1 + assert result["conditions"]["full_filter"]["documents_retained"] == 1 + assert result["conditions"]["full_filter"]["stages"]["filter"][ + "rejected_by_reason" + ] == {"low_unique_word_ratio": 1, "too_short": 1} for name in result["conditions"]: condition_dir = output / name assert (condition_dir / "corpus.jsonl").exists() diff --git a/tests/test_cli_adapters.py b/tests/test_cli_adapters.py new file mode 100644 index 0000000..0ffeab8 --- /dev/null +++ b/tests/test_cli_adapters.py @@ -0,0 +1,124 @@ +import json + +from llm_data_lab import cli + + +class WordTokenizer: + name_or_path = "fixture/cli-tokenizer" + init_kwargs = {"_commit_hash": "fixture-commit"} + + def encode(self, text, *, add_special_tokens=True): + return text.split() + + def decode(self, tokens, *, skip_special_tokens=True, clean_up_tokenization_spaces=False): + return " ".join(tokens) + + +class ChatTokenizer(WordTokenizer): + def apply_chat_template( + self, + messages, + *, + tokenize, + add_generation_prompt, + return_dict, + return_assistant_tokens_mask, + ): + ids, masks = [], [] + for message in messages: + for _token in message["content"].split(): + ids.append(len(ids) + 1) + masks.append(int(message["role"] == "assistant")) + return {"input_ids": ids, "assistant_masks": masks} + + +def write_jsonl(path, record): + path.write_text(json.dumps(record) + "\n", encoding="utf-8") + + +def test_cpt_prepare_cli_routes_flags_and_writes_report(tmp_path, monkeypatch, capsys): + source, output = tmp_path / "raw.jsonl", tmp_path / "prepared.jsonl" + write_jsonl(source, {"text": "one two three four"}) + monkeypatch.setattr(cli, "_load_tokenizer", lambda *_: WordTokenizer()) + monkeypatch.setattr( + "sys.argv", + [ + "llm-data-lab", + "cpt-prepare", + "--input", + str(source), + "--output", + str(output), + "--tokenizer", + "fixture", + "--max-sequence-length", + "3", + "--overflow-policy", + "truncate", + ], + ) + + cli.main() + + result = json.loads(capsys.readouterr().out) + assert json.loads(output.read_text(encoding="utf-8"))["text"] == "one two three" + assert result["output"]["documents"] == 1 + + +def test_sft_prepare_cli_routes_chat_tokens_and_mask(tmp_path, monkeypatch, capsys): + source, output = tmp_path / "raw.jsonl", tmp_path / "prepared.jsonl" + write_jsonl( + source, + {"messages": [{"role": "user", "content": "question"}, {"role": "assistant", "content": "answer"}]}, + ) + monkeypatch.setattr(cli, "_load_tokenizer", lambda *_: ChatTokenizer()) + monkeypatch.setattr( + "sys.argv", + [ + "llm-data-lab", + "sft-prepare", + "--input", + str(source), + "--output", + str(output), + "--tokenizer", + "fixture", + "--max-sequence-length", + "8", + ], + ) + + cli.main() + + result = json.loads(capsys.readouterr().out) + row = json.loads(output.read_text(encoding="utf-8")) + assert row["assistant_mask"] == [0, 1] + assert result["output"]["documents"] == 1 + + +def test_dpo_prepare_cli_routes_pair_limits_and_report(tmp_path, monkeypatch, capsys): + source, output = tmp_path / "raw.jsonl", tmp_path / "prepared.jsonl" + write_jsonl(source, {"prompt": "Question ", "chosen": "good answer", "rejected": "bad answer"}) + monkeypatch.setattr(cli, "_load_tokenizer", lambda *_: WordTokenizer()) + monkeypatch.setattr( + "sys.argv", + [ + "llm-data-lab", + "dpo-prepare", + "--input", + str(source), + "--output", + str(output), + "--tokenizer", + "fixture", + "--max-sequence-length", + "8", + ], + ) + + cli.main() + + result = json.loads(capsys.readouterr().out) + row = json.loads(output.read_text(encoding="utf-8")) + assert row["token_counts"]["prompt_plus_chosen"] <= 8 + assert result["output"]["documents"] == 1 diff --git a/tests/test_cpt.py b/tests/test_cpt.py new file mode 100644 index 0000000..b4dd123 --- /dev/null +++ b/tests/test_cpt.py @@ -0,0 +1,155 @@ +import json + +import pytest + +from llm_data_lab.adapters.cpt import prepare_cpt_dataset +from llm_data_lab.pipeline import sha256_file + + +class SpaceTokenizer: + name_or_path = "fixture/space-tokenizer" + init_kwargs = {"_commit_hash": "fixture-revision"} + + def encode(self, text, *, add_special_tokens=True): + return text.split() + + def decode(self, tokens, *, skip_special_tokens=True, clean_up_tokenization_spaces=False): + return " ".join(tokens) + + +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_cpt_prepare_truncates_enforces_budget_and_writes_audit_report(tmp_path): + source, output, report_path = ( + tmp_path / "raw.jsonl", + tmp_path / "prepared.jsonl", + tmp_path / "report.json", + ) + write_rows( + source, + [ + {"text": "one two three four", "source": "fixture"}, + {"text": " "}, + {"text": "five six"}, + {"text": "seven"}, + ], + ) + + result = prepare_cpt_dataset( + source, + output, + tokenizer=SpaceTokenizer(), + max_sequence_length=3, + token_budget=5, + overflow_policy="truncate", + report_path=report_path, + ) + + rows = [json.loads(line) for line in output.read_text(encoding="utf-8").splitlines()] + assert rows == [ + {"text": "one two three", "source": "fixture"}, + {"text": "five six"}, + ] + assert result["input"]["documents"] == 4 + assert result["input"]["token_lengths"]["total_tokens"] == 7 + assert result["output"]["documents"] == 2 + assert result["output"]["retained_documents"] == 2 + assert result["output"]["rejected_documents"] == 2 + assert result["output"]["rejected_by_reason"] == { + "empty_text": 1, + "token_budget_exceeded": 1, + } + assert result["output"]["token_lengths"]["total_tokens"] == 5 + assert result["output"]["sha256"] == sha256_file(output) + assert result["tokenizer"] == { + "identifier": "fixture/space-tokenizer", + "revision": "fixture-revision", + } + assert json.loads(report_path.read_text(encoding="utf-8")) == result + + +def test_cpt_prepare_is_deterministic_and_drops_overlong_documents(tmp_path): + source = tmp_path / "raw.jsonl" + write_rows(source, [{"text": "one two three four"}, {"text": "a b"}]) + first = prepare_cpt_dataset( + source, + tmp_path / "first.jsonl", + tokenizer=SpaceTokenizer(), + max_sequence_length=3, + overflow_policy="drop", + ) + second = prepare_cpt_dataset( + source, + tmp_path / "second.jsonl", + tokenizer=SpaceTokenizer(), + max_sequence_length=3, + overflow_policy="drop", + ) + assert (tmp_path / "first.jsonl").read_bytes() == (tmp_path / "second.jsonl").read_bytes() + assert first["output"]["sha256"] == second["output"]["sha256"] + assert first["output"]["rejected_by_reason"] == {"sequence_too_long": 1} + + +def test_cpt_prepare_rejects_invalid_config_and_sequence_overflow(tmp_path): + source = tmp_path / "raw.jsonl" + write_rows(source, [{"text": "one two three"}]) + with pytest.raises(ValueError, match="max_sequence_length"): + prepare_cpt_dataset(source, tmp_path / "out.jsonl", tokenizer=SpaceTokenizer(), max_sequence_length=0) + with pytest.raises(ValueError, match="token_budget"): + prepare_cpt_dataset( + source, + tmp_path / "out.jsonl", + tokenizer=SpaceTokenizer(), + max_sequence_length=4, + token_budget=0, + ) + with pytest.raises(ValueError, match="Record 1 has 3 tokens"): + prepare_cpt_dataset( + source, + tmp_path / "out.jsonl", + tokenizer=SpaceTokenizer(), + max_sequence_length=2, + overflow_policy="error", + ) + + +def test_cpt_prepare_reports_malformed_rows_and_tokenizer_failures(tmp_path): + source, output = tmp_path / "raw.jsonl", tmp_path / "out.jsonl" + write_rows(source, [{"text": 4}]) + with pytest.raises(TypeError, match="Record 1.*must be a string"): + prepare_cpt_dataset(source, output, tokenizer=SpaceTokenizer(), max_sequence_length=4) + assert not output.exists() + + write_rows(source, [{"text": "one two"}]) + + class BrokenTokenizer: + def encode(self, text, *, add_special_tokens=True): + raise ValueError("private text should not appear") + + with pytest.raises(RuntimeError, match="record 1.*ValueError") as error: + prepare_cpt_dataset(source, output, tokenizer=BrokenTokenizer(), max_sequence_length=4) + assert "private text" not in str(error.value) + assert not output.exists() + + +def test_cpt_truncate_requires_a_decoder(tmp_path): + source = tmp_path / "raw.jsonl" + write_rows(source, [{"text": "one two three"}]) + + class EncoderOnly: + def encode(self, text, *, add_special_tokens=True): + return text.split() + + with pytest.raises(RuntimeError, match="Could not truncate.*TypeError"): + prepare_cpt_dataset( + source, + tmp_path / "out.jsonl", + tokenizer=EncoderOnly(), + max_sequence_length=2, + overflow_policy="truncate", + ) diff --git a/tests/test_dpo.py b/tests/test_dpo.py new file mode 100644 index 0000000..896435c --- /dev/null +++ b/tests/test_dpo.py @@ -0,0 +1,130 @@ +import json + +import pytest + +from llm_data_lab.adapters.dpo import check_dpo_split_overlap, prepare_dpo_dataset + + +class SpaceTokenizer: + name_or_path = "fixture/dpo-tokenizer" + init_kwargs = {"_commit_hash": "dpo-revision"} + + def encode(self, text, *, add_special_tokens=True): + return text.split() + + def decode(self, tokens, *, skip_special_tokens=True, clean_up_tokenization_spaces=False): + return " ".join(tokens) + + +def write_rows(path, rows): + path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8") + + +def test_dpo_reports_duplicate_prompts_conflicts_and_identical_answers(tmp_path): + source, output = tmp_path / "raw.jsonl", tmp_path / "prepared.jsonl" + write_rows( + source, + [ + {"prompt": "choose a color", "chosen": "red is good", "rejected": "blue is bad"}, + {"prompt": "choose a color", "chosen": "blue is bad", "rejected": "red is good"}, + {"prompt": "same answer", "chosen": "same", "rejected": "same"}, + {"prompt": "empty answer", "chosen": "", "rejected": "not empty"}, + ], + ) + report = prepare_dpo_dataset( + source, + output, + tokenizer=SpaceTokenizer(), + max_sequence_length=10, + conflict_policy="report", + ) + assert report["output"]["documents"] == 2 + assert report["output"]["rejected_by_reason"] == { + "identical_answers": 1, + "empty_field": 1, + } + assert report["integrity"] == { + "duplicate_prompt_groups": 1, + "duplicate_prompt_records": 1, + "conflicting_prompt_count": 1, + "conflict_policy": "report", + } + row = json.loads(output.read_text(encoding="utf-8").splitlines()[0]) + assert row["token_counts"] == { + "prompt": 3, + "chosen": 3, + "rejected": 3, + "prompt_plus_chosen": 5, + "prompt_plus_rejected": 5, + } + + +def test_dpo_conflict_error_policy_stops_before_output(tmp_path): + source, output = tmp_path / "raw.jsonl", tmp_path / "prepared.jsonl" + write_rows( + source, + [ + {"prompt": "p", "chosen": "a", "rejected": "b"}, + {"prompt": "p", "chosen": "b", "rejected": "a"}, + ], + ) + with pytest.raises(ValueError, match="contradictory preferences"): + prepare_dpo_dataset( + source, + output, + tokenizer=SpaceTokenizer(), + max_sequence_length=8, + conflict_policy="error", + ) + assert not output.exists() + + +def test_dpo_truncates_answers_and_rejects_overlong_prompt(tmp_path): + source, output = tmp_path / "raw.jsonl", tmp_path / "prepared.jsonl" + write_rows( + source, + [ + {"prompt": "question ", "chosen": "one two three", "rejected": "four five six"}, + {"prompt": "one two three four", "chosen": "answer", "rejected": "other"}, + ], + ) + report = prepare_dpo_dataset( + source, + output, + tokenizer=SpaceTokenizer(), + max_sequence_length=3, + overflow_policy="truncate", + ) + rows = [json.loads(line) for line in output.read_text(encoding="utf-8").splitlines()] + assert len(rows) == 1 + assert rows[0]["token_counts"]["prompt_plus_chosen"] <= 3 + assert report["output"]["rejected_by_reason"] == {"prompt_too_long": 1} + + +def test_dpo_prompt_level_split_overlap_and_normalization(): + report = check_dpo_split_overlap( + { + "train": [{"prompt": " Help me! "}], + "validation": [{"prompt": "help me!"}], + }, + normalization="nfc_casefold_whitespace", + ) + assert report["has_overlap"] + assert report["integrity_scope"] == "DPO prompt-level pair leakage" + + +def test_dpo_rejects_pairs_that_become_identical_after_truncation(tmp_path): + source, output = tmp_path / "raw.jsonl", tmp_path / "prepared.jsonl" + write_rows( + source, + [{"prompt": "p ", "chosen": "x a", "rejected": "x b"}], + ) + report = prepare_dpo_dataset( + source, + output, + tokenizer=SpaceTokenizer(), + max_sequence_length=2, + overflow_policy="truncate", + ) + assert report["output"]["documents"] == 0 + assert report["output"]["rejected_by_reason"] == {"identical_after_truncation": 1} diff --git a/tests/test_leakage.py b/tests/test_leakage.py new file mode 100644 index 0000000..ffac9c1 --- /dev/null +++ b/tests/test_leakage.py @@ -0,0 +1,60 @@ +import json + +import pytest + +from llm_data_lab.leakage import check_split_overlap +from llm_data_lab.pipeline import sha256_file + + +def write_rows(path, texts): + path.write_text( + "".join(json.dumps({"text": text}) + "\n" for text in texts), encoding="utf-8" + ) + + +def test_overlap_reports_duplicate_and_cross_split_counts_without_text(tmp_path): + train = tmp_path / "train.jsonl" + validation = tmp_path / "validation.jsonl" + write_rows(train, ["shared secret text", "shared secret text", "train only"]) + write_rows(validation, ["shared secret text", "validation only"]) + + report = check_split_overlap({"train": train, "validation": validation}) + + assert report["has_overlap"] is True + assert report["split_sha256"] == { + "train": sha256_file(train), + "validation": sha256_file(validation), + } + assert report["affected_splits"] == ["train", "validation"] + assert report["overlapping_documents_by_split"] == {"train": 2, "validation": 1} + assert report["pairs"] == [ + { + "splits": ["train", "validation"], + "unique_overlapping_texts": 1, + "overlapping_documents": {"train": 2, "validation": 1}, + } + ] + assert "shared secret text" not in json.dumps(report) + + +def test_normalization_policy_is_explicit_and_configurable(): + splits = { + "train": [{"text": " Café\nNews "}], + "validation": [{"text": "cafe\u0301 news"}], + } + assert not check_split_overlap(splits, normalization="exact")["has_overlap"] + normalized = check_split_overlap(splits, normalization="nfc_casefold_whitespace") + assert normalized["has_overlap"] + assert normalized["normalization"] == "nfc_casefold_whitespace" + + +def test_overlap_handles_no_overlap_empty_split_and_invalid_records(): + report = check_split_overlap({"train": [], "validation": [{"text": "valid"}]}) + assert report["has_overlap"] is False + assert report["affected_splits"] == [] + with pytest.raises(TypeError, match="record 1.*string"): + check_split_overlap({"train": [{"text": None}], "validation": []}) + with pytest.raises(ValueError, match="At least two"): + check_split_overlap({"train": []}) + with pytest.raises(ValueError, match="Unknown normalization"): + check_split_overlap({"a": [], "b": []}, normalization="semantic") diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index 00d5ee6..12f0e43 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -3,12 +3,14 @@ import pytest from llm_data_lab.pipeline import ( + _software_environment, build_run_manifest, clean_jsonl, clean_text, corpus_stats, deduplicate_jsonl, filter_jsonl, + sha256_file, split_jsonl, ) @@ -30,7 +32,18 @@ def test_clean_jsonl_preserves_metadata_and_drops_empty(tmp_path): source, target = tmp_path / "in.jsonl", tmp_path / "out.jsonl" write_rows(source, [{"text": " hello world ", "source": "demo"}, {"text": " "}]) report = clean_jsonl(source, target) - assert report == {"input_documents": 2, "output_documents": 1, "empty_after_cleaning": 1} + assert report == { + "input_documents": 2, + "output_documents": 1, + "retained_documents": 1, + "rejected_documents": 1, + "rejected_by_reason": {"empty_after_cleaning": 1}, + "empty_after_cleaning": 1, + "input_sha256": sha256_file(source), + "output_sha256": sha256_file(target), + "configuration": {"text_field": "text", "strip_html": True}, + "software": _software_environment(), + } assert read_rows(target) == [{"text": "hello world", "source": "demo"}] @@ -41,6 +54,17 @@ def test_clean_fails_for_missing_text_field(tmp_path): clean_jsonl(source, target) +def test_jsonl_reader_reports_malformed_json_and_same_path_is_rejected(tmp_path): + from llm_data_lab.pipeline import read_jsonl + + source = tmp_path / "malformed.jsonl" + source.write_text("{not-json}\n", encoding="utf-8") + with pytest.raises(ValueError, match=r"malformed\.jsonl:1: invalid JSON"): + list(read_jsonl(source)) + with pytest.raises(ValueError, match="paths must be different"): + clean_jsonl(source, source) + + def test_dedupe_removes_exact_text_but_preserves_first_metadata(tmp_path): source, target = tmp_path / "in.jsonl", tmp_path / "out.jsonl" write_rows(source, [{"text": "same", "source": "first"}, @@ -52,11 +76,42 @@ def test_dedupe_removes_exact_text_but_preserves_first_metadata(tmp_path): def test_filter_reports_rejection_reasons(tmp_path): source, target = tmp_path / "in.jsonl", tmp_path / "out.jsonl" - write_rows(source, [{"text": "x"}, {"text": "hello hello hello"}, {"text": "one two three"}]) - report = filter_jsonl(source, target, min_chars=3, min_unique_word_ratio=0.5) - assert report["input_documents"] == 3 + write_rows( + source, + [ + {"text": "x"}, + {"text": "hello hello hello"}, + {"text": "one two three"}, + {"text": "a document long enough to exceed the maximum"}, + ], + ) + report = filter_jsonl( + source, + target, + min_chars=3, + max_chars=20, + min_unique_word_ratio=0.5, + ) + assert report["input_documents"] == 4 assert report["output_documents"] == 1 - assert report["rejected_by_reason"] == {"too_short": 1, "low_unique_word_ratio": 1} + assert report["retention_rate"] == 0.25 + assert report["retained_documents"] == 1 + assert report["rejected_documents"] == 3 + assert len(report["input_sha256"]) == len(report["output_sha256"]) == 64 + assert report["rejected_by_reason"] == { + "too_short": 1, + "low_unique_word_ratio": 1, + "too_long": 1, + } + + +def test_filter_rejects_invalid_thresholds(tmp_path): + source, target = tmp_path / "in.jsonl", tmp_path / "out.jsonl" + write_rows(source, [{"text": "hello world"}]) + with pytest.raises(ValueError, match="min_chars"): + filter_jsonl(source, target, min_chars=5, max_chars=4) + with pytest.raises(ValueError, match="unique_word_ratio"): + filter_jsonl(source, target, min_unique_word_ratio=1.1) def test_split_is_deterministic_and_disjoint(tmp_path): @@ -68,6 +123,10 @@ 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 report1["input_documents"] == 100 + assert len(report1["input_sha256"]) == 64 + assert len(report1["train_sha256"]) == len(report1["validation_sha256"]) == 64 + assert report1["configuration"] == {"text_field": "text", "val_fraction": 0.2, "seed": 9} assert {row["text"] for row in read_rows(train)}.isdisjoint( row["text"] for row in read_rows(val) ) @@ -80,6 +139,7 @@ def test_stats_counts_sources(tmp_path): assert report["documents"] == 2 assert report["characters"] == 12 assert report["source_document_counts"] == {"a": 1, "unknown": 1} + assert len(report["input_sha256"]) == 64 def test_invalid_split_fraction_rejected(tmp_path): @@ -110,3 +170,4 @@ def test_run_manifest_includes_dataset_and_pipeline_metadata(tmp_path): assert manifest["model"]["identifier"] == "demo-model" assert manifest["model"]["revision"] == "abc123" assert manifest["software"]["python"] + assert manifest["input_dataset"]["documents"] == 1 diff --git a/tests/test_public_ablation.py b/tests/test_public_ablation.py new file mode 100644 index 0000000..46e6fd5 --- /dev/null +++ b/tests/test_public_ablation.py @@ -0,0 +1,239 @@ +import importlib.util +import json +import sys +from collections import Counter +from pathlib import Path +from urllib.parse import parse_qs, urlsplit + +import pytest + +from llm_data_lab.pipeline import _software_environment, sha256_file + +EXAMPLE_DIR = Path(__file__).resolve().parents[1] / "examples" / "data_quality_ablation" +_SPEC = importlib.util.spec_from_file_location( + "public_ablation_example", EXAMPLE_DIR / "run_public_dataset.py" +) +if _SPEC is None or _SPEC.loader is None: + raise ImportError("Could not load the public ablation example") +_MODULE = importlib.util.module_from_spec(_SPEC) +sys.path.insert(0, str(EXAMPLE_DIR)) +try: + _SPEC.loader.exec_module(_MODULE) +finally: + sys.path.remove(str(EXAMPLE_DIR)) + + +def fake_viewer(*, population=1000, mutate=None): + def get_json(url): + query = parse_qs(urlsplit(url).query) + offset = int(query["offset"][0]) + length = int(query["length"][0]) + rows = [ + { + "row_idx": index, + "row": { + "text": f"class {index // (population // 4)} item {index} news market policy growth", + "label": min(index // (population // 4), 3), + }, + "truncated_cells": [], + } + for index in range(offset, min(offset + length, population)) + ] + page = {"num_rows_total": population, "partial": False, "rows": rows} + if mutate is not None and length == _MODULE.BLOCK_SIZE: + return mutate(page) + return page + + return get_json + + +def test_seeded_source_index_blocks_are_deterministic_and_spread(): + first = _MODULE.source_index_block_offsets(1000, seed=17) + assert first == _MODULE.source_index_block_offsets(1000, seed=17) + assert first != _MODULE.source_index_block_offsets(1000, seed=18) + assert len(first) == _MODULE.BLOCK_COUNT + for stratum, offset in enumerate(first): + low = stratum * 1000 // _MODULE.BLOCK_COUNT + high = (stratum + 1) * 1000 // _MODULE.BLOCK_COUNT + assert low <= offset + assert offset + _MODULE.BLOCK_SIZE <= high + + +def test_sample_acquisition_records_class_and_source_row_accounting(tmp_path): + source = tmp_path / "sample.jsonl" + revision_checks = iter([_MODULE.PINNED_REVISION, _MODULE.PINNED_REVISION]) + metadata, rows = _MODULE.fetch_sample( + source, + seed=17, + expected_sha256=None, + get_json=fake_viewer(), + revision_reader=lambda: next(revision_checks), + ) + + assert len(rows) == 400 + assert Counter(row["label"] for row in rows) == {label: 100 for label in range(4)} + assert len({row["source_row"] for row in rows}) == 400 + assert [row["source_row"] for row in rows] == sorted(row["source_row"] for row in rows) + assert metadata["selection"]["seed"] == 17 + assert metadata["selection"]["sample_class_counts"] == { + "World": 100, + "Sports": 100, + "Business": 100, + "Sci/Tech": 100, + } + assert metadata["selection"]["selected_source_row_indices"] == [ + row["source_row"] for row in rows + ] + assert metadata["sample_sha256"] == _MODULE.hashlib.sha256(source.read_bytes()).hexdigest() + + +def test_sample_acquisition_fails_when_revision_changes(tmp_path): + source = tmp_path / "sample.jsonl" + revisions = iter([_MODULE.PINNED_REVISION, "changed-revision"]) + with pytest.raises(RuntimeError, match="revision changed"): + _MODULE.fetch_sample( + source, + expected_sha256=None, + get_json=fake_viewer(), + revision_reader=lambda: next(revisions), + ) + assert not source.exists() + + +def test_dataset_revision_must_match_the_pinned_commit(monkeypatch): + monkeypatch.setattr(_MODULE, "_get_json", lambda _: {"sha": "unexpected-revision"}) + with pytest.raises(RuntimeError, match="moved from pinned revision"): + _MODULE._dataset_revision() + + +def test_sample_checksum_mismatch_fails_clearly(): + with pytest.raises(RuntimeError, match="Sample SHA-256 mismatch"): + _MODULE.verify_sample_checksum(b"actual", "0" * 64) + + +def test_acquisition_rejects_missing_and_malformed_rows(tmp_path): + def missing_row(page): + page["rows"].pop() + return page + + with pytest.raises(RuntimeError, match="expected 100"): + _MODULE.fetch_sample( + tmp_path / "missing.jsonl", + expected_sha256=None, + get_json=fake_viewer(mutate=missing_row), + revision_reader=lambda: _MODULE.PINNED_REVISION, + ) + + def malformed_text(page): + page["rows"][0]["row"]["text"] = None + return page + + with pytest.raises(TypeError, match="invalid text"): + _MODULE.fetch_sample( + tmp_path / "malformed.jsonl", + expected_sha256=None, + get_json=fake_viewer(mutate=malformed_text), + revision_reader=lambda: _MODULE.PINNED_REVISION, + ) + + +def _report_metadata(): + return { + "identifier": "fancyzhx/ag_news", + "revision": _MODULE.PINNED_REVISION, + "config": "default", + "split": "train", + "selection": { + "algorithm": "seeded source-index stratified fixture", + "seed": 12, + "requested_rows": 9, + "sample_class_counts": {"World": 3, "Sports": 2, "Business": 2, "Sci/Tech": 2}, + "selected_source_row_indices": list(range(9)), + "source_index_strata": [], + }, + "row_count": 9, + "sample_sha256": "fixture-hash", + "source_api": _MODULE.VIEWER_ROWS_URL, + "viewer_revision_limitation": "fixture revision checked before and after", + "training_split_rows": 1000, + "source_card": "https://huggingface.co/datasets/fancyzhx/ag_news", + "license_note": "Fixture terms", + "labels": {str(label): name for label, name in _MODULE.LABELS.items()}, + } + + +def test_ablation_counts_and_manifest_provenance(tmp_path): + source = tmp_path / "input.jsonl" + long_texts = { + label: ( + f"class {label} headline " + "market company research policy growth trading report demand results outlook" + ) + for label in range(4) + } + rows = [] + for label in range(4): + rows.extend( + [ + {"text": long_texts[label], "label": label, "source": "ag_news"}, + {"text": f"Brief {label}", "label": label, "source": "ag_news"}, + ] + ) + rows.insert(1, {"text": long_texts[0], "label": 0, "source": "ag_news"}) + source.write_text( + "".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8" + ) + summary = _MODULE.run_ablation( + source, + tmp_path / "conditions", + min_chars=50, + min_unique_word_ratio=0.3, + input_metadata=_report_metadata(), + ) + + assert summary["input"]["documents"] == 9 + clean_stage = summary["conditions"]["clean"]["stages"]["clean"] + assert clean_stage == { + "input_documents": 9, + "output_documents": 9, + "retained_documents": 9, + "rejected_documents": 0, + "rejected_by_reason": {}, + "empty_after_cleaning": 0, + "input_sha256": sha256_file(source), + "output_sha256": sha256_file(tmp_path / "conditions" / "clean" / "corpus.jsonl"), + "configuration": {"text_field": "text", "strip_html": True}, + "software": _software_environment(), + } + assert summary["conditions"]["clean_dedupe"]["stages"]["dedupe"][ + "exact_duplicates_removed" + ] == 1 + filtered = summary["conditions"]["full_filter"] + assert filtered["documents_retained"] == 4 + assert filtered["stages"]["filter"]["rejected_by_reason"] == {"too_short": 4} + manifest = json.loads( + Path(filtered["manifest_path"]).read_text(encoding="utf-8") + ) + assert manifest["pipeline_configuration"]["source_metadata"]["revision"] == ( + _MODULE.PINNED_REVISION + ) + assert manifest["pipeline_configuration"]["source_metadata"]["selection"]["seed"] == 12 + + report_one = _MODULE.render_report(summary) + report_two = _MODULE.render_report(summary) + assert report_one == report_two + assert "Input | Output | Retained" in report_one + assert "too_short: 4" in report_one + assert "World | Sports | Business | Sci/Tech" in report_one + assert "representative sample" in report_one + assert "corpus-level" in report_one.lower() or "model quality" in report_one.lower() + + +def test_empty_input_has_zero_retention_and_a_valid_report(tmp_path): + source = tmp_path / "empty.jsonl" + source.write_text("", encoding="utf-8") + summary = _MODULE.run_ablation(source, tmp_path / "empty-runs") + assert summary["input"]["documents"] == 0 + for condition in summary["conditions"].values(): + assert condition["documents_retained"] == 0 + assert condition["retention_rate_vs_input"] == 0.0 diff --git a/tests/test_sft.py b/tests/test_sft.py new file mode 100644 index 0000000..24bb1eb --- /dev/null +++ b/tests/test_sft.py @@ -0,0 +1,169 @@ +import json + +import pytest + +from llm_data_lab.adapters.sft import prepare_sft_dataset + + +class ChatTokenizer: + name_or_path = "fixture/chat-tokenizer" + init_kwargs = {"_commit_hash": "chat-revision"} + + def apply_chat_template( + self, + messages, + *, + tokenize, + add_generation_prompt, + return_dict, + return_assistant_tokens_mask, + ): + ids, mask = [], [] + for message in messages: + for token in message["content"].split(): + ids.append(len(ids) + 1) + mask.append(int(message["role"] == "assistant")) + return {"input_ids": ids, "assistant_masks": mask} + + +def write_rows(path, rows): + path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8") + + +def test_sft_prepare_validates_multiple_turns_and_exports_assistant_mask(tmp_path): + source, output = tmp_path / "raw.jsonl", tmp_path / "prepared.jsonl" + write_rows( + source, + [ + { + "messages": [ + {"role": "system", "content": "be helpful"}, + {"role": "user", "content": "first question"}, + {"role": "assistant", "content": "first answer"}, + {"role": "user", "content": "follow up"}, + {"role": "assistant", "content": "second answer"}, + ], + "id": "fixture-1", + } + ], + ) + report = prepare_sft_dataset( + source, output, tokenizer=ChatTokenizer(), max_sequence_length=20 + ) + row = json.loads(output.read_text(encoding="utf-8")) + assert row["id"] == "fixture-1" + assert len(row["input_ids"]) == 10 + assert row["assistant_mask"] == [0, 0, 0, 0, 1, 1, 0, 0, 1, 1] + assert report["output"]["documents"] == 1 + assert report["output"]["token_lengths"]["total_tokens"] == 10 + + +def test_sft_reports_missing_empty_and_invalid_assistant_messages(tmp_path): + source, output = tmp_path / "raw.jsonl", tmp_path / "prepared.jsonl" + write_rows( + source, + [ + {"messages": [{"role": "user", "content": "hello"}]}, + { + "messages": [ + {"role": "user", "content": "hello"}, + {"role": "assistant", "content": " "}, + ] + }, + { + "messages": [ + {"role": "user", "content": "hello"}, + {"role": "moderator", "content": "not allowed"}, + {"role": "assistant", "content": "response"}, + ] + }, + ], + ) + report = prepare_sft_dataset(source, output, tokenizer=ChatTokenizer(), max_sequence_length=10) + assert report["output"]["documents"] == 0 + assert report["output"]["rejected_by_reason"] == { + "missing_assistant_response": 1, + "empty_assistant_response": 1, + "invalid_role": 1, + } + + +def test_sft_truncation_keeps_mask_aligned_and_requires_supervision(tmp_path): + source, output = tmp_path / "raw.jsonl", tmp_path / "prepared.jsonl" + write_rows( + source, + [ + { + "messages": [ + {"role": "user", "content": "question"}, + {"role": "assistant", "content": "one two three"}, + ] + } + ], + ) + report = prepare_sft_dataset( + source, + output, + tokenizer=ChatTokenizer(), + max_sequence_length=2, + overflow_policy="truncate", + truncation_side="right", + ) + row = json.loads(output.read_text(encoding="utf-8")) + assert len(row["input_ids"]) == len(row["assistant_mask"]) == 2 + assert sum(row["assistant_mask"]) > 0 + assert report["output"]["documents"] == 1 + + class NoAssistantTargets(ChatTokenizer): + def apply_chat_template(self, *args, **kwargs): + return {"input_ids": [1, 2], "assistant_masks": [0, 0]} + + report = prepare_sft_dataset( + source, + tmp_path / "no-targets.jsonl", + tokenizer=NoAssistantTargets(), + max_sequence_length=4, + ) + assert report["output"]["rejected_by_reason"] == {"no_supervised_tokens": 1} + + +def test_sft_template_errors_and_mask_mismatch_are_actionable(tmp_path): + source = tmp_path / "raw.jsonl" + write_rows( + source, + [{"messages": [{"role": "assistant", "content": "answer"}]}], + ) + + class BrokenTemplate: + def apply_chat_template(self, *args, **kwargs): + raise ValueError("private conversation text") + + with pytest.raises(RuntimeError, match="Chat template failed.*ValueError") as error: + prepare_sft_dataset( + source, tmp_path / "failed.jsonl", tokenizer=BrokenTemplate(), max_sequence_length=4 + ) + assert "private conversation" not in str(error.value) + + class MismatchedMask(ChatTokenizer): + def apply_chat_template(self, *args, **kwargs): + return {"input_ids": [1, 2], "assistant_masks": [1]} + + with pytest.raises(ValueError, match="lengths differ"): + prepare_sft_dataset( + source, + tmp_path / "mismatch.jsonl", + tokenizer=MismatchedMask(), + max_sequence_length=4, + ) + + class InvalidMask(ChatTokenizer): + def apply_chat_template(self, *args, **kwargs): + return {"input_ids": [1], "assistant_masks": [2]} + + with pytest.raises(ValueError, match="only 0 or 1"): + prepare_sft_dataset( + source, + tmp_path / "invalid-mask.jsonl", + tokenizer=InvalidMask(), + max_sequence_length=4, + ) diff --git a/tests/test_token_stats.py b/tests/test_token_stats.py new file mode 100644 index 0000000..3075076 --- /dev/null +++ b/tests/test_token_stats.py @@ -0,0 +1,78 @@ +import json + +import pytest + +from llm_data_lab.pipeline import _software_environment, sha256_file +from llm_data_lab.token_stats import token_stats + + +class WordTokenizer: + name_or_path = "fixture/word-tokenizer" + init_kwargs = {"_commit_hash": "abc123"} + + def encode(self, text, *, add_special_tokens=True): + return text.split() + + +def test_token_stats_counts_tokens_and_empty_text_deterministically(tmp_path): + corpus = tmp_path / "tiny.jsonl" + corpus.write_text( + ''.join(json.dumps({"text": value}) + "\n" for value in ["one two", " ", "three"]), + encoding="utf-8", + ) + + report = token_stats(corpus, tokenizer=WordTokenizer()) + + assert report["input_sha256"] == sha256_file(corpus) + assert report["tokenizer"] == {"identifier": "fixture/word-tokenizer", "revision": "abc123"} + assert report["documents"] == 3 + assert report["empty_documents"] == 1 + assert report["total_tokens"] == 3 + assert report["token_length"]["histogram"] == {"0": 1, "1": 1, "2": 1} + assert report == token_stats(corpus, tokenizer=WordTokenizer()) + + +def test_token_stats_handles_empty_corpus(): + assert token_stats([], tokenizer=WordTokenizer()) == { + "schema_version": 1, + "input_sha256": None, + "configuration": {"text_field": "text", "add_special_tokens": False}, + "software": _software_environment(), + "tokenizer": {"identifier": "fixture/word-tokenizer", "revision": "abc123"}, + "documents": 0, + "empty_documents": 0, + "total_tokens": 0, + "token_length": { + "min": 0, + "max": 0, + "mean": 0.0, + "p50": 0, + "p90": 0, + "p95": 0, + "histogram": {}, + }, + } + + +def test_token_stats_reports_malformed_records_and_tokenizer_failures(): + with pytest.raises(TypeError, match="Record 1.*string"): + token_stats([{"text": 3}], tokenizer=WordTokenizer()) + + class BrokenTokenizer: + def encode(self, text, *, add_special_tokens=True): + raise ValueError("fixture failure") + + with pytest.raises(RuntimeError, match="record 1.*ValueError"): + token_stats([{"text": "hello"}], tokenizer=BrokenTokenizer()) + + +def test_token_stats_requires_tokenizer_and_optional_dependency(monkeypatch): + with pytest.raises(ValueError, match="Provide a tokenizer"): + token_stats([], tokenizer=None) + + def unavailable(_name): + raise ImportError("not installed") + + monkeypatch.setattr("llm_data_lab.token_stats.importlib.import_module", unavailable) + with pytest.raises(ImportError, match="pip install.*transformers"): + token_stats([], tokenizer="fixture/tokenizer")