#!/usr/bin/env python3 from __future__ import annotations import argparse import json import re import sys from collections import Counter from pathlib import Path from typing import Any import pandas as pd REQUIRED_V03_FIELDS = [ "id", "domain", "source_dataset", "instruction", "context", "context_chunks", "streaming_reasoning", "deep_reasoning", "answer", "response", "messages", "text", "num_chunks", "language", "split", "generation_method", "quality_flags", "version", "reasoning_policy", "chunking_method", "chunk_labels", "skip_chunks", "skip_reasons", "reasoning_token_budget", "original_num_chunks", "chunk_split_count", ] REQUIRED_V04_FIELDS = [ "quality_score", "is_high_quality", "refinement_method", "llm_augmented", "llm_augmentation_model", ] OPTIONAL_V04_FIELDS = [ "rejected_reason", "state_tracking_confidence", ] REQUIRED_FIELDS = REQUIRED_V03_FIELDS + REQUIRED_V04_FIELDS + OPTIONAL_V04_FIELDS REQUIRED_STRING_FIELDS = [ "id", "domain", "source_dataset", "instruction", "context", "streaming_reasoning", "deep_reasoning", "answer", "response", "text", "language", "split", "generation_method", "version", "reasoning_policy", "chunking_method", "refinement_method", ] FORBIDDEN_PHRASES = [ "the user is sharing everyday context", "the situation is about an everyday life situation", "the assistant should stay conversational", "the user is asking for help, clarification, or a next step", "support need centers on", "task_detail=noted", "emotion=positive; cause=", "emotion=negative; cause=", ] SEVERE_FLAGS = { "generic_reasoning", "closing_mishandled", "possible_slot_error", "excessive_chunking", "fragment_chunk", "low_specificity", } HIGH_QUALITY_EXCLUDED_FLAGS = SEVERE_FLAGS | { "copied_source_response", "awkward_answer", "keyword_stitching", "repeated_context_chunks", "weak_high_quality_candidate", } REVIEW_SAMPLE_FIELDS = [ "id", "domain", "context_chunks", "chunk_labels", "skip_reasons", "streaming_reasoning", "deep_reasoning", "answer", "quality_flags", "quality_score", "is_high_quality", "refinement_method", ] def word_count(text: Any) -> int: return len(re.findall(r"\b[\w'-]+\b", str(text))) def read_jsonl(path: Path) -> list[dict[str, Any]]: rows: list[dict[str, Any]] = [] with path.open("r", encoding="utf-8") as handle: for line_no, line in enumerate(handle, start=1): line = line.strip() if not line: continue try: rows.append(json.loads(line)) except json.JSONDecodeError as exc: raise ValueError(f"{path}:{line_no}: invalid JSON: {exc}") from exc return rows def forbidden_phrase_count(row: dict[str, Any]) -> int: text = "\n".join(str(row.get(field, "")) for field in ["streaming_reasoning", "deep_reasoning", "answer"]).lower() return sum(text.count(phrase) for phrase in FORBIDDEN_PHRASES) def normalize(text: Any) -> str: return re.sub(r"\W+", " ", str(text).lower()).strip() def is_fragment_chunk(text: Any) -> bool: stripped = str(text or "").strip() normalized = normalize(stripped) if not stripped or not normalized: return True if normalized in {"mr", "mrs", "ms", "dr", "prof", "macmillan"}: return True if re.fullmatch(r"(Mr|Mrs|Ms|Dr|Prof)\.?", stripped): return True if re.fullmatch(r"(Mr|Mrs|Ms|Dr|Prof)\s+\.", stripped): return True if word_count(stripped) <= 2 and re.fullmatch(r"[\W_]+", stripped): return True return False def validate_row(row: dict[str, Any], expected_split: str, idx: int, high_quality_file: bool = False) -> list[str]: errors: list[str] = [] row_id = row.get("id", f"row-{idx}") for field in REQUIRED_FIELDS: if field not in row: errors.append(f"{row_id}: missing field {field}") for field in REQUIRED_STRING_FIELDS: if not isinstance(row.get(field), str) or not row.get(field, "").strip(): errors.append(f"{row_id}: empty or non-string field {field}") if row.get("version") != "v0.4.1": errors.append(f"{row_id}: version must be v0.4.1") if "v0.4" not in str(row.get("generation_method", "")): errors.append(f"{row_id}: generation_method must contain v0.4") if row.get("reasoning_policy") != "selective_concise": errors.append(f"{row_id}: reasoning_policy must be selective_concise") if not str(row.get("chunking_method", "")).strip(): errors.append(f"{row_id}: chunking_method is required") chunks = row.get("context_chunks") if not isinstance(chunks, list) or not chunks or not all(isinstance(chunk, str) and chunk.strip() for chunk in chunks): errors.append(f"{row_id}: context_chunks must be a non-empty list of strings") chunks = [] context = row.get("context", "") for chunk in chunks: if chunk not in context: errors.append(f"{row_id}: context does not contain chunk text: {chunk[:80]}") if row.get("num_chunks") != len(chunks): errors.append(f"{row_id}: num_chunks does not match context_chunks length") if any(is_fragment_chunk(chunk) for chunk in chunks): errors.append(f"{row_id}: contains excessive fragment chunk") if any(re.fullmatch(r"(Mr|Mrs|Ms|Dr|Prof)\s+\.", str(chunk).strip()) for chunk in chunks): errors.append(f"{row_id}: contains isolated title fragment") chunk_labels = row.get("chunk_labels") if not isinstance(chunk_labels, list) or len(chunk_labels) != len(chunks): errors.append(f"{row_id}: chunk_labels length must equal num_chunks") chunk_labels = [] else: bad_labels = [label for label in chunk_labels if label not in {"reason", "skip"}] if bad_labels: errors.append(f"{row_id}: chunk_labels can only contain reason or skip") skip_chunks = row.get("skip_chunks") skip_reasons = row.get("skip_reasons") if not isinstance(skip_chunks, list) or not all(isinstance(item, int) for item in skip_chunks): errors.append(f"{row_id}: skip_chunks must be a list of ints") skip_chunks = [] if not isinstance(skip_reasons, dict): errors.append(f"{row_id}: skip_reasons must be a dict") skip_reasons = {} if chunk_labels: expected_skips = [i + 1 for i, label in enumerate(chunk_labels) if label == "skip"] if skip_chunks != expected_skips: errors.append(f"{row_id}: skip_chunks must correspond to skip labels") for chunk_index in expected_skips: if str(chunk_index) not in skip_reasons: errors.append(f"{row_id}: missing skip_reasons entry for chunk {chunk_index}") if not isinstance(row.get("reasoning_token_budget"), dict) or not row.get("reasoning_token_budget"): errors.append(f"{row_id}: reasoning_token_budget must be a non-empty dict") if not isinstance(row.get("original_num_chunks"), int) or row.get("original_num_chunks", 0) <= 0: errors.append(f"{row_id}: original_num_chunks must be a positive int") if not isinstance(row.get("chunk_split_count"), int) or row.get("chunk_split_count", -1) < 0: errors.append(f"{row_id}: chunk_split_count must be a non-negative int") messages = row.get("messages") if not isinstance(messages, list) or len(messages) != 2: errors.append(f"{row_id}: messages must contain exactly one user and one assistant message") else: if messages[0].get("role") != "user" or messages[1].get("role") != "assistant": errors.append(f"{row_id}: messages roles must be user then assistant") if not messages[0].get("content") or not messages[1].get("content"): errors.append(f"{row_id}: message content cannot be empty") response = row.get("response", "") for marker in ["Streaming reasoning:", "Deep reasoning:", "Answer:"]: if marker not in response: errors.append(f"{row_id}: response missing marker {marker}") if row.get("split") != expected_split: errors.append(f"{row_id}: split is {row.get('split')!r}, expected {expected_split!r}") if row.get("split") not in {"train", "eval"}: errors.append(f"{row_id}: split must be train or eval") if not isinstance(row.get("quality_flags"), list): errors.append(f"{row_id}: quality_flags must be a list") elif not all(isinstance(flag, str) and flag.strip() for flag in row.get("quality_flags", [])): errors.append(f"{row_id}: quality_flags must contain only non-empty strings") score = row.get("quality_score") if not isinstance(score, (int, float)) or not 0 <= float(score) <= 1: errors.append(f"{row_id}: quality_score must be a number in [0, 1]") if not isinstance(row.get("is_high_quality"), bool): errors.append(f"{row_id}: is_high_quality must be boolean") if not isinstance(row.get("llm_augmented"), bool): errors.append(f"{row_id}: llm_augmented must be boolean") if row.get("llm_augmentation_model") is not None and not isinstance(row.get("llm_augmentation_model"), str): errors.append(f"{row_id}: llm_augmentation_model must be string or null") if row.get("state_tracking_confidence") is not None and not isinstance(row.get("state_tracking_confidence"), (int, float)): errors.append(f"{row_id}: state_tracking_confidence must be numeric or null") if forbidden_phrase_count(row): errors.append(f"{row_id}: forbidden phrase appears in generated fields") flags = set(row.get("quality_flags", [])) if isinstance(row.get("quality_flags"), list) else set() if high_quality_file: if row.get("is_high_quality") is not True: errors.append(f"{row_id}: high-quality file contains non-high-quality row") if float(row.get("quality_score", 0)) < 0.85: errors.append(f"{row_id}: high-quality row has quality_score < 0.85") if flags & SEVERE_FLAGS: errors.append(f"{row_id}: high-quality row has severe flags {sorted(flags & SEVERE_FLAGS)}") if flags & HIGH_QUALITY_EXCLUDED_FLAGS: errors.append(f"{row_id}: high-quality row has excluded flags {sorted(flags & HIGH_QUALITY_EXCLUDED_FLAGS)}") if word_count(row.get("streaming_reasoning", "")) > 120: errors.append(f"{row_id}: high-quality row has long streaming_reasoning") if word_count(row.get("deep_reasoning", "")) > 45: errors.append(f"{row_id}: high-quality row has long deep_reasoning") return errors def validate_review_samples(sample_rows: list[dict[str, Any]], dataset_ids: set[str]) -> list[str]: errors: list[str] = [] if len(sample_rows) < 120: errors.append(f"samples_for_review.jsonl must contain at least 120 rows, found {len(sample_rows)}") domain_counts = Counter(row.get("domain") for row in sample_rows) for domain in ["task_oriented_assistant", "emotional_support", "daily_dialogue", "how_to_guidance"]: if domain_counts.get(domain, 0) < 30: errors.append(f"samples_for_review.jsonl should include at least 30 {domain} rows, found {domain_counts.get(domain, 0)}") for idx, row in enumerate(sample_rows, start=1): for field in REVIEW_SAMPLE_FIELDS: if field not in row: errors.append(f"sample row {idx}: missing field {field}") if row.get("id") not in dataset_ids: errors.append(f"sample row {idx}: id not present in train/eval: {row.get('id')}") if forbidden_phrase_count(row): errors.append(f"sample row {idx}: forbidden phrase appears") return errors def parquet_count(path: Path) -> int: return len(pd.read_parquet(path)) def validate(data_dir: Path) -> int: errors: list[str] = [] paths = { "train_jsonl": data_dir / "data" / "train.jsonl", "eval_jsonl": data_dir / "data" / "eval.jsonl", "train_parquet": data_dir / "data" / "train.parquet", "eval_parquet": data_dir / "data" / "eval.parquet", "hq_train_jsonl": data_dir / "data" / "train_high_quality.jsonl", "hq_eval_jsonl": data_dir / "data" / "eval_high_quality.jsonl", "hq_train_parquet": data_dir / "data" / "train_high_quality.parquet", "hq_eval_parquet": data_dir / "data" / "eval_high_quality.parquet", "readme": data_dir / "README.md", "info": data_dir / "dataset_info.json", "samples": data_dir / "samples_for_review.jsonl", } for name, path in paths.items(): if not path.exists(): errors.append(f"missing required file {name}: {path}") if errors: for error in errors: print(f"ERROR: {error}") return 1 train_rows = read_jsonl(paths["train_jsonl"]) eval_rows = read_jsonl(paths["eval_jsonl"]) hq_train_rows = read_jsonl(paths["hq_train_jsonl"]) hq_eval_rows = read_jsonl(paths["hq_eval_jsonl"]) sample_rows = read_jsonl(paths["samples"]) if not train_rows: errors.append("train.jsonl is empty") if not eval_rows: errors.append("eval.jsonl is empty") if not hq_train_rows: errors.append("train_high_quality.jsonl is empty") if not hq_eval_rows: errors.append("eval_high_quality.jsonl is empty") for idx, row in enumerate(train_rows, start=1): errors.extend(validate_row(row, "train", idx)) for idx, row in enumerate(eval_rows, start=1): errors.extend(validate_row(row, "eval", idx)) for idx, row in enumerate(hq_train_rows, start=1): errors.extend(validate_row(row, "train", idx, high_quality_file=True)) for idx, row in enumerate(hq_eval_rows, start=1): errors.extend(validate_row(row, "eval", idx, high_quality_file=True)) all_rows = train_rows + eval_rows ids = [row.get("id") for row in all_rows] texts = [row.get("text") for row in all_rows] duplicate_ids = [item for item, count in Counter(ids).items() if count > 1] duplicate_texts = [item for item, count in Counter(texts).items() if count > 1] if duplicate_ids: errors.append(f"duplicate ids found: {duplicate_ids[:5]}") if duplicate_texts: errors.append(f"duplicate text fields found: {len(duplicate_texts)} duplicates") errors.extend(validate_review_samples(sample_rows, set(ids))) row_count_pairs = [ (paths["train_jsonl"], paths["train_parquet"], len(train_rows)), (paths["eval_jsonl"], paths["eval_parquet"], len(eval_rows)), (paths["hq_train_jsonl"], paths["hq_train_parquet"], len(hq_train_rows)), (paths["hq_eval_jsonl"], paths["hq_eval_parquet"], len(hq_eval_rows)), ] for jsonl_path, parquet_path, expected_count in row_count_pairs: actual_count = parquet_count(parquet_path) if actual_count != expected_count: errors.append(f"{parquet_path.name} row count {actual_count} does not match {jsonl_path.name} {expected_count}") for parquet_path in [paths["train_parquet"], paths["eval_parquet"], paths["hq_train_parquet"], paths["hq_eval_parquet"]]: columns = set(pd.read_parquet(parquet_path).columns) for field in REQUIRED_FIELDS: if field not in columns: errors.append(f"{parquet_path.name} missing column {field}") try: info = json.loads(paths["info"].read_text(encoding="utf-8")) except json.JSONDecodeError as exc: errors.append(f"dataset_info.json invalid JSON: {exc}") info = {} if info.get("version") != "v0.4.1": errors.append("dataset_info.json version must be v0.4.1") if info.get("repo_id") != "skyzhou06/LifeStreamingCoT": errors.append("dataset_info.json repo_id must be skyzhou06/LifeStreamingCoT") if info.get("generation_method") != "source_grounded_rule_based_v0.4.1_quality_patch": errors.append("dataset_info.json generation_method is incorrect") if info.get("reasoning_policy") != "selective_concise": errors.append("dataset_info.json reasoning_policy is incorrect") if info.get("chunking_method") != "semantic_sentence_split_v0.4_refined": errors.append("dataset_info.json chunking_method is incorrect") total_chunks = sum(row.get("num_chunks", 0) for row in all_rows) skip_chunks = sum(len(row.get("skip_chunks", [])) for row in all_rows) chunk_word_counts = [word_count(chunk) for row in all_rows for chunk in row.get("context_chunks", [])] forbidden_count = sum(forbidden_phrase_count(row) for row in all_rows) fragment_count = sum(1 for row in all_rows for chunk in row.get("context_chunks", []) if is_fragment_chunk(chunk)) if forbidden_count: errors.append(f"forbidden phrase count must be 0, found {forbidden_count}") if fragment_count: errors.append(f"fragment chunk count must be 0, found {fragment_count}") domains = Counter(row.get("domain") for row in all_rows) source_datasets = Counter(row.get("source_dataset") for row in all_rows) avg_chunks = sum(row.get("num_chunks", 0) for row in all_rows) / len(all_rows) if all_rows else 0 avg_chunk_length = sum(chunk_word_counts) / len(chunk_word_counts) if chunk_word_counts else 0 avg_stream = sum(word_count(row.get("streaming_reasoning", "")) for row in all_rows) / len(all_rows) if all_rows else 0 avg_deep = sum(word_count(row.get("deep_reasoning", "")) for row in all_rows) / len(all_rows) if all_rows else 0 avg_score = sum(float(row.get("quality_score", 0)) for row in all_rows) / len(all_rows) if all_rows else 0 hq_total = len(hq_train_rows) + len(hq_eval_rows) quality_flags = Counter(flag for row in all_rows for flag in row.get("quality_flags", [])) llm_augmented_count = sum(1 for row in all_rows if row.get("llm_augmented")) print("Validation summary") print(f"total rows: {len(all_rows)}") print(f"train rows: {len(train_rows)}") print(f"eval rows: {len(eval_rows)}") print(f"high-quality train rows: {len(hq_train_rows)}") print(f"high-quality eval rows: {len(hq_eval_rows)}") print(f"domains: {dict(sorted(domains.items()))}") print(f"source datasets: {dict(sorted(source_datasets.items()))}") print(f"average num_chunks: {avg_chunks:.2f}") print(f"average chunk length: {avg_chunk_length:.2f}") print(f"average streaming_reasoning words: {avg_stream:.2f}") print(f"average deep_reasoning words: {avg_deep:.2f}") print(f"skip ratio: {skip_chunks / total_chunks if total_chunks else 0:.4f}") print(f"quality_flags distribution: {dict(sorted(quality_flags.items()))}") print(f"average quality_score: {avg_score:.3f}") print(f"high-quality percentage: {hq_total / len(all_rows) if all_rows else 0:.2%}") print(f"forbidden phrase count: {forbidden_count}") print(f"fragment chunk count: {fragment_count}") print(f"llm_augmented count: {llm_augmented_count}") print(f"review sample rows: {len(sample_rows)}") print(f"errors: {len(errors)}") if errors: for error in errors[:160]: print(f"ERROR: {error}") if len(errors) > 160: print(f"ERROR: ... {len(errors) - 160} more") return 1 print("validation passed") return 0 def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--data-dir", default="life_streaming_cot_dataset") args = parser.parse_args() sys.exit(validate(Path(args.data_dir))) if __name__ == "__main__": main()