Generating an instruction-tuning dataset is only the first step.
A JSONL file can look correct in a text editor and still contain problems that affect training:
- Missing fields
- Empty instructions
- Duplicate examples
- Invalid JSON
- Extremely long outputs
- Inconsistent response formats
- Data leakage between training and validation sets
A small validation script can catch many of these problems before the dataset reaches a training job.
A practical record format
A simple instruction-tuning record may look like this:
{"instruction":"Summarize the document.","input":"The document contains three sections.","output":"The document has three main sections."} Each line should contain one valid JSON object.
For this example, the required fields are:
instructioninputoutput
The exact schema can vary between projects, but it should be defined before validation begins.
What should be checked?
A useful validator should check at least five areas:
- JSON syntax
- Required fields
- Empty or very short text
- Duplicate records
- Approximate length limits
It is also useful to produce a report instead of stopping at the first error.
That way, the dataset owner can fix several problems in one iteration.
A simple validation script
The following script reads a JSONL file, validates each record, detects duplicates, and writes a JSON report.
import argparse import hashlib import json from collections import Counter from pathlib import Path REQUIRED_FIELDS = ("instruction", "input", "output") def normalize_text(value): if not isinstance(value, str): return "" return " ".join(value.split()) def record_hash(record): normalized = { field: normalize_text(record.get(field, "")) for field in REQUIRED_FIELDS } payload = json.dumps( normalized, ensure_ascii=False, sort_keys=True, ) return hashlib.sha256(payload.encode("utf-8")).hexdigest() def validate_file(path, min_chars=10, max_chars=12000): errors = [] valid_records = [] hashes = [] line_count = 0 with path.open("r", encoding="utf-8") as file: for line_number, raw_line in enumerate(file, start=1): line_count += 1 raw_line = raw_line.strip() if not raw_line: errors.append({ "line": line_number, "type": "empty_line", }) continue try: record = json.loads(raw_line) except json.JSONDecodeError as exc: errors.append({ "line": line_number, "type": "invalid_json", "message": str(exc), }) continue if not isinstance(record, dict): errors.append({ "line": line_number, "type": "record_is_not_object", }) continue missing_fields = [ field for field in REQUIRED_FIELDS if field not in record ] if missing_fields: errors.append({ "line": line_number, "type": "missing_fields", "fields": missing_fields, }) continue normalized = { field: normalize_text(record[field]) for field in REQUIRED_FIELDS } empty_fields = [ field for field, value in normalized.items() if not value ] if empty_fields: errors.append({ "line": line_number, "type": "empty_fields", "fields": empty_fields, }) continue short_fields = [ field for field, value in normalized.items() if len(value) < min_chars ] if short_fields: errors.append({ "line": line_number, "type": "text_too_short", "fields": short_fields, }) long_fields = [ field for field, value in normalized.items() if len(value) > max_chars ] if long_fields: errors.append({ "line": line_number, "type": "text_too_long", "fields": long_fields, }) current_hash = record_hash(record) hashes.append(current_hash) valid_records.append(record) counts = Counter(hashes) duplicate_groups = { value: count for value, count in counts.items() if count > 1 } return { "file": str(path), "total_lines": line_count, "valid_records": len(valid_records), "error_count": len(errors), "duplicate_groups": len(duplicate_groups), "duplicate_records": sum( count - 1 for count in duplicate_groups.values() ), "errors": errors, } def main(): parser = argparse.ArgumentParser() parser.add_argument("input_file", type=Path) parser.add_argument( "--report", type=Path, default=Path("validation_report.json"), ) parser.add_argument("--min-chars", type=int, default=10) parser.add_argument("--max-chars", type=int, default=12000) args = parser.parse_args() report = validate_file( args.input_file, min_chars=args.min_chars, max_chars=args.max_chars, ) args.report.write_text( json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8", ) print(json.dumps(report, indent=2, ensure_ascii=False)) if __name__ == "__main__": main() Run it with:
python validate_jsonl.py training.jsonl --report report.json The script does not automatically delete bad records. It creates a report so that the cleaning decision remains visible and reviewable.
Why duplicate detection matters
Duplicate examples can make a dataset appear larger without adding new information.
They can also distort training when one pattern is repeated many times.
The script creates a normalized hash from the three required fields:
instructioninputoutput
Whitespace differences are ignored before hashing.
For example, these two records are treated as equivalent:
{"instruction":"Summarize this.","input":"Text here.","output":"A summary."} {"instruction":" Summarize this. ","input":"Text here.","output":"A summary."} For more complex datasets, the hash can also include:
- Source document ID
- Task category
- Language
- Difficulty
- Annotation version
The fields included in the hash should match the project definition of a duplicate.
Character length is only an approximation
Character count is a simple first check, but training systems usually operate on tokens.
A long string may use fewer tokens than expected in one language and more tokens in another.
For production validation, add the tokenizer used by the training model.
The validator can then report:
- Token count per field
- Total token count
- Percentage above the model limit
- Truncated records
- Average tokens per example
- Token distribution by category
A record should not be silently truncated during training. Truncation can remove the instruction, the important context, or the expected answer.
Validate train and validation leakage
A dataset can pass structural validation and still produce unreliable evaluation results.
If nearly identical examples appear in both training and validation sets, the validation score may be too optimistic.
Leakage can happen when:
- The same source document is split into multiple records
- Paragraphs from one document enter different splits
- Near-duplicate instructions are generated
- Multiple versions of the same answer are retained
- A source record is processed more than once
A practical solution is to store a stable source ID and split at the source level.
For example:
source_document_id -> train source_document_id -> train source_document_id -> validation All records derived from the same document should normally remain in the same split unless there is a specific reason to do otherwise.
Keep validation reports with the dataset
The validation report should be stored next to the dataset revision.
A useful directory structure is:
dataset/ v1/ train.jsonl validation.jsonl schema.json validation_report.json README.md The report should include:
- Dataset revision
- Validation script version
- Schema version
- Input file hash
- Total line count
- Valid record count
- Error count
- Duplicate count
- Length statistics
- Validation timestamp
This makes the dataset easier to audit and reproduce.
Do not hide quality decisions
It is tempting to delete invalid records and keep only the cleaned file.
That may be convenient, but it hides useful information.
A better workflow is:
- Preserve the original file
- Run validation
- Write a quality report
- Create a cleaned revision
- Record the filtering rules
- Re-run validation
- Freeze the final revision
The cleaned dataset should be derived from the original through a documented process.
Final checklist
Before using an instruction-tuning JSONL file, check:
- Is every line valid JSON?
- Does every record contain the required fields?
- Are empty fields rejected?
- Are duplicate records measured?
- Are very short and very long examples reviewed?
- Is token length checked with the training tokenizer?
- Are source documents split consistently?
- Is the validation report stored with the dataset?
- Is the cleaning process reproducible?
- Is the final dataset revision immutable?
A small validation step can prevent much more expensive training failures.
The same principles also apply to structured text, image, audio, video, and multimodal datasets. For larger AI-ready data workflows, schema, provenance, validation, and versioning should be designed together.


