Download code/multi-hop/export_online_dataset.py from fhyfhy/Implicit-Reasoning-checkpoints: direct link, hf CLI and curl.
- Browser
- Download file 5.94 kB
-
https://huggingface.co/fhyfhy/Implicit-Reasoning-checkpoints/resolve/main/code/multi-hop/export_online_dataset.py
- Command line
-
hf download hf://fhyfhy/Implicit-Reasoning-checkpoints/code/multi-hop/export_online_dataset.py
-
curl -L -o export_online_dataset.py https://huggingface.co/fhyfhy/Implicit-Reasoning-checkpoints/resolve/main/code/multi-hop/export_online_dataset.py
5.94 kB
| #!/usr/bin/env python3 | |
| """ | |
| Export a finite static dataset by sampling from OnlineDataset. | |
| Examples: | |
| python export_online_dataset.py \ | |
| --output data/custom/online_train.json \ | |
| --num-samples 50000 \ | |
| --num-entities 50 --num-relations 50 --edges-per-entity 10 \ | |
| --num-hops 2 --train-qa-ratio 0.5 --seed 42 \ | |
| --format text | |
| python export_online_dataset.py \ | |
| --output data/custom/online_train_jsontext.json \ | |
| --num-samples 20000 \ | |
| --format jsontext | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| from typing import Any, Dict, List | |
| from generate_data import DataGenerator | |
| from online_data import OnlineDataset | |
| def to_plain_python(value: Any) -> Any: | |
| if isinstance(value, dict): | |
| return {k: to_plain_python(v) for k, v in value.items()} | |
| if isinstance(value, list): | |
| return [to_plain_python(v) for v in value] | |
| if hasattr(value, "tolist"): | |
| return value.tolist() | |
| return value | |
| def build_tokenizer(tokenizer_name: str | None, trust_remote_code: bool): | |
| if not tokenizer_name: | |
| return None | |
| from transformers import AutoTokenizer | |
| tokenizer = AutoTokenizer.from_pretrained(tokenizer_name, trust_remote_code=trust_remote_code) | |
| if tokenizer.pad_token is None and tokenizer.eos_token is not None: | |
| tokenizer.pad_token = tokenizer.eos_token | |
| return tokenizer | |
| def to_output_record(example: Dict[str, Any], out_format: str) -> Dict[str, Any]: | |
| if out_format == "text": | |
| return {"text": example["text"], "kind": example.get("kind")} | |
| if out_format == "jsontext": | |
| return {"input_text": "", "target_text": example["text"], "kind": example.get("kind")} | |
| if out_format == "tokenized": | |
| return to_plain_python(example) | |
| raise ValueError(f"Unknown format: {out_format}") | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description="Export static JSON by sampling OnlineDataset.") | |
| parser.add_argument("--output", type=Path, required=True, help="Output JSON path.") | |
| parser.add_argument("--num-samples", type=int, required=True, help="Number of samples to export.") | |
| parser.add_argument("--num-entities", type=int, default=50) | |
| parser.add_argument("--num-relations", type=int, default=50) | |
| parser.add_argument("--edges-per-entity", type=int, default=10) | |
| parser.add_argument("--num-hops", type=int, default=2) | |
| parser.add_argument("--train-qa-ratio", type=float, default=0.5) | |
| parser.add_argument("--seed", type=int, default=42) | |
| parser.add_argument("--sampling-alpha", type=float, default=None, help="Zipf alpha for QA path sampling.") | |
| parser.add_argument("--split-profile-facts", action="store_true", help="Emit one atom fact per training sample.") | |
| parser.add_argument("--multi-hop-format", choices=["reverse", "direct"], default="reverse") | |
| parser.add_argument("--leading-space", action="store_true", help="Prefix each sequence with a whitespace.") | |
| parser.add_argument("--format", choices=["text", "jsontext", "tokenized"], default="text") | |
| parser.add_argument("--tokenizer", type=str, default=None, help="Tokenizer name/path. Required for tokenized format.") | |
| parser.add_argument("--trust-remote-code", action="store_true") | |
| parser.add_argument("--max-length", type=int, default=100) | |
| parser.add_argument("--padding", action="store_true") | |
| parser.add_argument("--save-graph", action="store_true", help="Also save graph edges next to output JSON.") | |
| return parser.parse_args() | |
| def main() -> None: | |
| args = parse_args() | |
| if args.num_samples <= 0: | |
| raise ValueError("--num-samples must be > 0.") | |
| if not (0.0 <= args.train_qa_ratio <= 1.0): | |
| raise ValueError("--train-qa-ratio must be in [0, 1].") | |
| if args.format == "tokenized" and not args.tokenizer: | |
| raise ValueError("--tokenizer is required when --format tokenized.") | |
| tokenizer = build_tokenizer(args.tokenizer, args.trust_remote_code) | |
| generator = DataGenerator( | |
| num_entities=args.num_entities, | |
| num_relations=args.num_relations, | |
| seed=args.seed, | |
| sampling_alpha=args.sampling_alpha, | |
| ) | |
| generator.generate_graph(edges_per_entity=args.edges_per_entity) | |
| dataset = OnlineDataset( | |
| generator=generator, | |
| num_hops=args.num_hops, | |
| train_qa_ratio=args.train_qa_ratio, | |
| tokenizer=tokenizer if args.format == "tokenized" else None, | |
| max_length=args.max_length, | |
| padding=args.padding, | |
| split_profile_facts=args.split_profile_facts, | |
| multi_hop_format=args.multi_hop_format, | |
| leading_space=args.leading_space, | |
| ) | |
| records: List[Dict[str, Any]] = [] | |
| text_mode_qa = 0 | |
| text_mode_profile = 0 | |
| it = iter(dataset) | |
| for _ in range(args.num_samples): | |
| ex = next(it) | |
| rec = to_output_record(ex, args.format) | |
| records.append(rec) | |
| if args.format in ("text", "jsontext"): | |
| if rec.get("kind") == "qa": | |
| text_mode_qa += 1 | |
| else: | |
| text_mode_profile += 1 | |
| args.output.parent.mkdir(parents=True, exist_ok=True) | |
| args.output.write_text(json.dumps(records, indent=2)) | |
| print(f"Saved {len(records)} samples to {args.output}") | |
| if args.format in ("text", "jsontext"): | |
| print( | |
| f"Mix summary (from online sample kind): " | |
| f"qa={text_mode_qa}, profile={text_mode_profile}, qa_ratio={text_mode_qa / len(records):.4f}" | |
| ) | |
| if args.save_graph: | |
| graph_path = args.output.with_suffix(".graph.json") | |
| graph_records = [ | |
| {"source": src, "relation": rel, "target": tgt} | |
| for (src, rel), tgt in generator.knowledge_graph.items() | |
| ] | |
| graph_path.write_text(json.dumps(graph_records, indent=2)) | |
| print(f"Saved graph with {len(graph_records)} edges to {graph_path}") | |
| if __name__ == "__main__": | |
| main() | |