from __future__ import annotations from collections import defaultdict from dataclasses import asdict from pathlib import Path import json import sys from typing import Any from datasets import Dataset, load_dataset from huggingface_hub import HfApi PROJECT_ROOT = Path(__file__).resolve().parents[3] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) from nano_ir_eval.bm25_subset import ( # noqa: E402 DEFAULT_TRANSFORMER_TOKENIZER, compute_ndcg_at_k, compute_qrels_coverage, detect_primary_language, generate_bm25_rows, plan_tokenization, ) SOURCE_DATASET_ID = "dwzhu/LongEmbed" OUTPUT_DIR = Path(__file__).resolve().parent QUERY_LIMIT = 50 CORPUS_LIMIT = 10_000 TOP_K = 100 LANGUAGE_SEED = 13 LANGUAGE_SAMPLE_SIZE = 50 TASKS = [ ("narrativeqa", "NanoNarrativeQA", "first_valid_queries"), ("summ_screen_fd", "NanoSummScreenFD", "first_valid_queries"), ("qmsum", "NanoQMSum", "first_valid_queries"), ("2wikimqa", "Nano2WikiMultihopQA", "first_valid_queries"), ("passkey", "NanoPasskey", "balanced_context_length"), ("needle", "NanoNeedle", "balanced_context_length"), ] def _clean_text(value: Any) -> str: return str(value).strip() def _source_revision() -> str | None: try: return str(HfApi().dataset_info(SOURCE_DATASET_ID).sha) except Exception: return None def _load_source_task(config_name: str) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]: corpus = list(load_dataset(SOURCE_DATASET_ID, config_name, split="corpus")) queries = list(load_dataset(SOURCE_DATASET_ID, config_name, split="queries")) qrels = list(load_dataset(SOURCE_DATASET_ID, config_name, split="qrels")) return corpus, queries, qrels def _qrels_by_query(qrels: list[dict[str, Any]]) -> dict[str, list[str]]: result: dict[str, list[str]] = defaultdict(list) for row in qrels: query_id = str(row["qid"]) corpus_id = str(row["doc_id"]) if query_id and corpus_id: result[query_id].append(corpus_id) return dict(result) def _select_first_valid_queries( queries: list[dict[str, Any]], qrels_for_query: dict[str, list[str]], corpus_ids: set[str], ) -> list[dict[str, Any]]: selected: list[dict[str, Any]] = [] for row in queries: query_id = str(row["qid"]) if not query_id or not _clean_text(row["text"]): continue positives = qrels_for_query.get(query_id, []) if not positives or not all(corpus_id in corpus_ids for corpus_id in positives): continue selected.append(row) if len(selected) >= QUERY_LIMIT: break return selected def _select_balanced_context_queries( queries: list[dict[str, Any]], qrels_for_query: dict[str, list[str]], corpus_ids: set[str], ) -> list[dict[str, Any]]: groups: dict[int, list[dict[str, Any]]] = defaultdict(list) for row in queries: query_id = str(row["qid"]) if not query_id or not _clean_text(row["text"]): continue positives = qrels_for_query.get(query_id, []) if not positives or not all(corpus_id in corpus_ids for corpus_id in positives): continue groups[int(row["context_length"])].append(row) selected: list[dict[str, Any]] = [] context_lengths = sorted(groups) index = 0 while len(selected) < QUERY_LIMIT: added = False for context_length in context_lengths: bucket = groups[context_length] if index < len(bucket): selected.append(bucket[index]) added = True if len(selected) >= QUERY_LIMIT: break if not added: break index += 1 return selected def _build_nano_split(config_name: str, split_name: str, selection_policy: str) -> dict[str, Any]: source_corpus, source_queries, source_qrels = _load_source_task(config_name) corpus_ids = {str(row["doc_id"]) for row in source_corpus} qrels_for_query = _qrels_by_query(source_qrels) if selection_policy == "balanced_context_length": selected_queries = _select_balanced_context_queries(source_queries, qrels_for_query, corpus_ids) else: selected_queries = _select_first_valid_queries(source_queries, qrels_for_query, corpus_ids) if len(selected_queries) != QUERY_LIMIT: raise RuntimeError(f"{split_name}: selected {len(selected_queries)} queries, expected {QUERY_LIMIT}.") selected_query_ids = [str(row["qid"]) for row in selected_queries] selected_query_id_set = set(selected_query_ids) selected_qrels = [ {"query-id": query_id, "corpus-id": corpus_id} for query_id in selected_query_ids for corpus_id in qrels_for_query[query_id] ] positive_corpus_ids = {row["corpus-id"] for row in selected_qrels} selected_corpus: list[dict[str, str]] = [] seen_corpus_ids: set[str] = set() seen_texts: set[str] = set() duplicate_text_skipped = 0 for row in source_corpus: corpus_id = str(row["doc_id"]) text = _clean_text(row["text"]) if not corpus_id or not text: continue if corpus_id in seen_corpus_ids: continue if text in seen_texts: duplicate_text_skipped += 1 if corpus_id not in positive_corpus_ids: continue selected_corpus.append({"_id": corpus_id, "text": text}) seen_corpus_ids.add(corpus_id) seen_texts.add(text) if len(selected_corpus) >= CORPUS_LIMIT: break selected_corpus_ids = {row["_id"] for row in selected_corpus} missing_positive_ids = positive_corpus_ids - selected_corpus_ids if missing_positive_ids: raise RuntimeError(f"{split_name}: qrels positives missing from selected corpus: {sorted(missing_positive_ids)[:5]}") nano_queries = [{"_id": str(row["qid"]), "text": _clean_text(row["text"])} for row in selected_queries] if len({row["_id"] for row in nano_queries}) != len(nano_queries): raise RuntimeError(f"{split_name}: duplicate query IDs.") if len({row["_id"] for row in selected_corpus}) != len(selected_corpus): raise RuntimeError(f"{split_name}: duplicate corpus IDs.") if any(row["query-id"] not in selected_query_id_set for row in selected_qrels): raise RuntimeError(f"{split_name}: qrels reference an unselected query.") if any(row["corpus-id"] not in selected_corpus_ids for row in selected_qrels): raise RuntimeError(f"{split_name}: qrels reference an unselected document.") output_paths = { "corpus": OUTPUT_DIR / "corpus" / f"{split_name}.parquet", "queries": OUTPUT_DIR / "queries" / f"{split_name}.parquet", "qrels": OUTPUT_DIR / "qrels" / f"{split_name}.parquet", } for path in output_paths.values(): path.parent.mkdir(parents=True, exist_ok=True) Dataset.from_list(selected_corpus).to_parquet(str(output_paths["corpus"])) Dataset.from_list(nano_queries).to_parquet(str(output_paths["queries"])) Dataset.from_list(selected_qrels).to_parquet(str(output_paths["qrels"])) context_counts: dict[str, int] | None = None if selected_queries and "context_length" in selected_queries[0]: counts: dict[str, int] = defaultdict(int) for row in selected_queries: counts[str(row["context_length"])] += 1 context_counts = dict(sorted(counts.items(), key=lambda item: int(item[0]))) return { "source_config": config_name, "split_name": split_name, "selection_policy": selection_policy, "source_query_count": len(source_queries), "source_corpus_count": len(source_corpus), "source_qrels_count": len(source_qrels), "selected_query_count": len(nano_queries), "selected_corpus_count": len(selected_corpus), "qrels_count": len(selected_qrels), "duplicate_text_skipped": duplicate_text_skipped, "qrels_rewrite_count": 0, "context_length_query_counts": context_counts, } def _force_qrels_positive_candidates( rows: list[dict[str, Any]], qrels: list[dict[str, Any]], *, top_k: int, corpus_size: int, ) -> tuple[list[dict[str, Any]], int]: positives_by_query: dict[str, list[str]] = defaultdict(list) for row in qrels: positives_by_query[str(row["query-id"])].append(str(row["corpus-id"])) effective_top_k = min(top_k, corpus_size) forced_count = 0 forced_rows: list[dict[str, Any]] = [] for row in rows: query_id = str(row["query-id"]) positives = positives_by_query.get(query_id, []) positive_set = set(positives) candidates = [] seen: set[str] = set() for corpus_id in row["corpus-ids"]: corpus_id = str(corpus_id) if corpus_id not in seen: candidates.append(corpus_id) seen.add(corpus_id) for positive_id in positives: if positive_id in seen: continue forced_count += 1 if len(candidates) < effective_top_k: candidates.append(positive_id) seen.add(positive_id) continue for index in range(len(candidates) - 1, -1, -1): if candidates[index] not in positive_set: seen.remove(candidates[index]) candidates[index] = positive_id seen.add(positive_id) break else: raise RuntimeError(f"{query_id}: cannot force all positives within top-{effective_top_k}.") forced_rows.append({"query-id": query_id, "corpus-ids": candidates[:effective_top_k]}) return forced_rows, forced_count def _build_bm25_for_split(split_name: str) -> dict[str, Any]: corpus = list(Dataset.from_parquet(str(OUTPUT_DIR / "corpus" / f"{split_name}.parquet"))) queries = list(Dataset.from_parquet(str(OUTPUT_DIR / "queries" / f"{split_name}.parquet"))) qrels = list(Dataset.from_parquet(str(OUTPUT_DIR / "qrels" / f"{split_name}.parquet"))) detection = detect_primary_language( [str(row["text"]) for row in corpus], sample_size=LANGUAGE_SAMPLE_SIZE, seed=LANGUAGE_SEED, ) plan = plan_tokenization( detection=detection, splitter_mode="auto", tokenizer_name=DEFAULT_TRANSFORMER_TOKENIZER, language_hint="en", ) raw_rows = generate_bm25_rows( corpus=corpus, queries=queries, plan=plan, top_k=TOP_K, show_progress=False, ) rows, forced_count = _force_qrels_positive_candidates( raw_rows, qrels, top_k=TOP_K, corpus_size=len(corpus), ) coverage = compute_qrels_coverage(bm25_rows=rows, qrels=qrels, top_k=TOP_K) if coverage.recall != 1.0: raise RuntimeError(f"{split_name}: BM25 qrels coverage is {coverage.recall}, expected 1.0.") bm25_path = OUTPUT_DIR / "bm25" / f"{split_name}.parquet" bm25_path.parent.mkdir(parents=True, exist_ok=True) Dataset.from_list(rows).to_parquet(str(bm25_path)) ndcg_at_10 = compute_ndcg_at_k(bm25_rows=rows, qrels=qrels, k=min(10, TOP_K)) ndcg_at_100 = compute_ndcg_at_k(bm25_rows=rows, qrels=qrels, k=min(100, TOP_K)) return { "split_name": split_name, "language_detection": asdict(detection), "tokenization_plan": asdict(plan), "top_k": TOP_K, "qrels_coverage": asdict(coverage), "forced_positive_count": forced_count, "ndcg_at_10": ndcg_at_10, "ndcg_at_100": ndcg_at_100, } def _write_readme(split_names: list[str]) -> None: config_order = ["bm25", "corpus", "qrels", "queries"] lines = ["---", "configs:"] for config_name in config_order: lines.append(f"- config_name: {config_name}") lines.append(" data_files:") for split_name in split_names: lines.append(f" - split: {split_name}") lines.append(f" path: {config_name}/{split_name}.parquet") if config_name == "queries": lines.append(" default: true") lines.extend( [ "language:", "- en", "tags:", "- Long Context", "- retrieval", "- nano", "---", "", "# NanoLongEmbed", "", "NanoLongEmbed is a Nano-style retrieval subset derived from `dwzhu/LongEmbed`.", "It keeps the NanoBEIR-compatible config layout: `corpus`, `queries`, `qrels`, and `bm25`.", "", "## Source", "", "- Source dataset: `dwzhu/LongEmbed`", "- Source tasks: NarrativeQA, SummScreenFD, QMSum, 2WikiMultihopQA, Passkey, Needle", "- Upstream card: https://huggingface.co/datasets/dwzhu/LongEmbed", "", "## Extraction Policy", "", "- 50 queries are selected per task.", "- Real-world tasks use the first valid source queries in source order.", "- Passkey and Needle use deterministic round-robin selection across context lengths.", "- The full source corpus is retained for each task because every corpus has fewer than 10,000 documents.", "- Exact duplicate corpus text is skipped when present; no duplicate corpus text was found in this build.", "- Qrels are limited to the selected queries and retain only `query-id` and `corpus-id`.", "", "## BM25", "", "- BM25 candidates are top-100 per query.", "- Tokenization uses the repository BM25 auto plan with English as a language hint.", "- Any missing qrels-positive document is forced into the candidate list by replacing tail non-positive candidates.", "- Per-split metadata and reproducibility settings are in `metadata/*.json` and `nano_bm25_subset_config.json`.", "", "## Schemas", "", "- `corpus`: `_id: string`, `text: string`", "- `queries`: `_id: string`, `text: string`", "- `qrels`: `query-id: string`, `corpus-id: string`", "- `bm25`: `query-id: string`, `corpus-ids: list[string]`", "", "## License", "", "This derived local dataset does not assign a new license. Users must comply with the upstream LongEmbed dataset and source-data terms.", "", ] ) (OUTPUT_DIR / "README.md").write_text("\n".join(lines), encoding="utf-8") def main() -> None: OUTPUT_DIR.mkdir(parents=True, exist_ok=True) source_revision = _source_revision() split_metadata = [] bm25_metadata = [] split_names = [split_name for _, split_name, _ in TASKS] for source_config, split_name, selection_policy in TASKS: print(f"Building nano split {split_name} from {source_config}", flush=True) split_metadata.append(_build_nano_split(source_config, split_name, selection_policy)) for split_name in split_names: print(f"Building BM25 split {split_name}", flush=True) bm25_metadata.append(_build_bm25_for_split(split_name)) metadata_by_split = {item["split_name"]: item for item in split_metadata} for item in bm25_metadata: split_name = item["split_name"] metadata_by_split[split_name]["bm25"] = item metadata_dir = OUTPUT_DIR / "metadata" metadata_dir.mkdir(parents=True, exist_ok=True) for split_name, metadata in metadata_by_split.items(): metadata["source_dataset_id"] = SOURCE_DATASET_ID metadata["source_revision"] = source_revision (metadata_dir / f"{split_name}.json").write_text( json.dumps(metadata, ensure_ascii=False, indent=2), encoding="utf-8", ) manifest = { "dataset_name": "NanoLongEmbed", "source_dataset_id": SOURCE_DATASET_ID, "source_revision": source_revision, "output_dir": str(OUTPUT_DIR), "query_limit_per_split": QUERY_LIMIT, "corpus_limit_per_split": CORPUS_LIMIT, "bm25_top_k": TOP_K, "language_seed": LANGUAGE_SEED, "language_sample_size": LANGUAGE_SAMPLE_SIZE, "split_mapping": [ {"source_config": source_config, "split_name": split_name, "selection_policy": selection_policy} for source_config, split_name, selection_policy in TASKS ], "counts": [ { "split_name": item["split_name"], "queries": item["selected_query_count"], "corpus": item["selected_corpus_count"], "qrels": item["qrels_count"], } for item in split_metadata ], } (OUTPUT_DIR / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8") bm25_summary = { "dataset_id": str(OUTPUT_DIR), "source_dataset_id": SOURCE_DATASET_ID, "source_revision": source_revision, "output_dir": str(OUTPUT_DIR), "corpus_subset_name": "corpus", "queries_subset_name": "queries", "qrels_subset_name": "qrels", "top_k": TOP_K, "sample_size": LANGUAGE_SAMPLE_SIZE, "language_seed": LANGUAGE_SEED, "auto_select_best_splitter": False, "selection_ndcg_k": None, "default_tokenization_config": { "splitter_mode": "auto", "tokenizer_name": DEFAULT_TRANSFORMER_TOKENIZER, "stemmer_algorithm": None, "enable_stemming": True, }, "positive_forcing": "replace tail non-positive candidates with missing qrels positives", "splits": [ { "split_name": item["split_name"], "tokenization_plan": item["tokenization_plan"], "main_score_name": None, "main_score": None, "selected_evaluation": None, "candidate_evaluations": None, "qrels_coverage": item["qrels_coverage"], "forced_positive_count": item["forced_positive_count"], "ndcg_at_10": item["ndcg_at_10"], "ndcg_at_100": item["ndcg_at_100"], } for item in bm25_metadata ], } (OUTPUT_DIR / "nano_bm25_subset_config.json").write_text( json.dumps(bm25_summary, ensure_ascii=False, indent=2), encoding="utf-8", ) _write_readme(split_names) print(f"Wrote NanoLongEmbed to {OUTPUT_DIR}", flush=True) if __name__ == "__main__": main()