Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 .
146 changes: 90 additions & 56 deletions README.md
Original file line number Diff line number Diff line change
@@ -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).
66 changes: 46 additions & 20 deletions docs/ag_news_ablation_report.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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.
Loading
Loading