""" Data generation script for implicit multi-hop reasoning with non-layerwise graph structure. Settings: - |E| <= len(single_names) (number of entities/people) - |R| = 50/100/200 (number of relations) - Non-layerwise graph: Any entity can connect to any other entity via any relation """ import json import random import argparse import os from typing import List, Dict, Tuple, Set, Optional from utils.data.name_space import single_names class DataGenerator: def __init__( self, num_entities: int = 50, num_relations: int = 50, seed: int = 42, sampling_alpha: float = None, entities: Optional[List[str]] = None, relations: Optional[List[str]] = None, ): """ Initialize the data generator. Args: num_entities: Number of entities (people) in the graph num_relations: Number of relation types (max 200) seed: Random seed for reproducibility sampling_alpha: If set, use Zipf distribution for relation sampling in QA """ # Validate constraints assert num_entities <= len(single_names), f"Maximum {len(single_names)} entities supported, requested {num_entities}" assert num_relations <= 200, f"Maximum 200 relations supported, requested {num_relations}" self.num_entities = num_entities self.num_relations = num_relations self.seed = seed self.sampling_alpha = sampling_alpha random.seed(seed) # Select entities from the name space if entities is not None: if len(entities) != num_entities: raise ValueError(f"Expected {num_entities} explicit entities, got {len(entities)}") if len(set(entities)) != len(entities): raise ValueError("Explicit entities must be unique") self.entities = list(entities) else: self.entities = random.sample(single_names, num_entities) # Generate relation names if relations is not None: if len(relations) != num_relations: raise ValueError(f"Expected {num_relations} explicit relations, got {len(relations)}") if len(set(relations)) != len(relations): raise ValueError("Explicit relations must be unique") self.relations = list(relations) else: self.relations = self._generate_relation_names(num_relations) # Pre-calculate relation ranks for power-law sampling self.rel_to_idx = {rel: i for i, rel in enumerate(self.relations)} # Initialize the knowledge graph # Format: {(entity, relation): target_entity} self.knowledge_graph: Dict[Tuple[str, str], str] = {} @staticmethod def all_relation_names() -> List[str]: """ Generate unique relation names. Supports up to 200 unique relations. """ # Exactly 200 unique relation names all_relations = [ # Educational/Training roles (18) "instructor", "teacher", "advisor", "supervisor", "mentor", "guide", "coach", "trainer", "tutor", "counselor", "educator", "lecturer", "professor", "dean", "principal", "chancellor", "provost", "rector", # Management/Leadership roles (18) "director", "manager", "leader", "chief", "head", "boss", "captain", "commander", "ruler", "governor", "administrator", "executive", "superintendent", "overseer", "foreman", "chairperson", "president", "vice-president", # Support/Assistance roles (18) "patron", "sponsor", "supporter", "backer", "guardian", "protector", "caretaker", "helper", "assistant", "aide", "attendant", "companion", "associate", "partner", "collaborator", "ally", "advocate", "champion", # Monitoring/Evaluation roles (18) "watcher", "monitor", "inspector", "examiner", "reviewer", "evaluator", "assessor", "judge", "arbiter", "auditor", "observer", "scrutinizer", "analyst", "critic", "appraiser", "validator", "checker", "verifier", # Coordination/Facilitation roles (18) "mediator", "negotiator", "facilitator", "coordinator", "organizer", "planner", "strategist", "architect", "designer", "developer", "engineer", "arranger", "scheduler", "dispatcher", "moderator", "intermediary", "liaison", # Expertise/Consultation roles (18) "consultant", "adviser", "expert", "specialist", "authority", "master", "guru", "scholar", "sage", "maven", "professional", "technician", "practitioner", "veteran", "virtuoso", "connoisseur", "savant", "pundit", # Creative/Production roles (18) "creator", "producer", "maker", "builder", "inventor", "innovator", "artist", "craftsman", "composer", "author", "writer", "poet", "playwright", "sculptor", "painter", "illustrator", "photographer", "filmmaker", # Communication/Information roles (18) "spokesperson", "representative", "delegate", "envoy", "emissary", "ambassador", "agent", "broker", "dealer", "trader", "merchant", "vendor", "reporter", "journalist", "correspondent", "announcer", "narrator", "commentator", # Service/Care roles (18) "caregiver", "nurse", "healer", "therapist", "psychiatrist", "psychologist", "physician", "doctor", "surgeon", "dentist", "pharmacist", "paramedic", "social-worker", "case-worker", "welfare-officer", "counselor-aide", "care-coordinator", "ombudsman", # Legal/Administrative roles (18) "lawyer", "attorney", "solicitor", "barrister", "prosecutor", "defender", "notary", "clerk", "secretary", "registrar", "recorder", "archivist", "curator", "librarian", "documentalist", "bureaucrat", "official", "magistrate", # Financial/Business roles (18) "accountant", "treasurer", "banker", "financier", "investor", "stockbroker", "auditor-general", "tax-advisor", "economist", "business-analyst", "financial-planner", "actuary", "entrepreneur", "businessman", "retailer", "wholesaler", "distributor", "franchiser", # Technical/Scientific roles (22) "scientist", "researcher", "investigator", "experimenter", "explorer", "pioneer", "technician", "mechanic", "civil-engineer", "surveyor", "geologist", "chemist", "programmer", "software-developer", "data-analyst", "systems-designer", "quality-tester", "debugger", "physicist", "biologist", "mathematician", "astronomer" ] # Validate we have at least 200 relations assert len(all_relations) >= 200, f"Need at least 200 relations, but have {len(all_relations)}" return all_relations def _generate_relation_names(self, num_relations: int) -> List[str]: assert num_relations <= 200, f"Cannot generate more than 200 relations, requested {num_relations}" return self.all_relation_names()[:num_relations] def get_entity_fact_map(self) -> Dict[str, List[Tuple[str, str]]]: entity_to_facts: Dict[str, List[Tuple[str, str]]] = {entity: [] for entity in self.entities} for (entity, relation), target in self.knowledge_graph.items(): entity_to_facts.setdefault(entity, []).append((relation, target)) return entity_to_facts def format_atom_fact(self, entity: str, relation: str, target: str, leading_space: bool = False) -> str: text = f"{entity}'s {relation} is {target}" return f" {text}" if leading_space else text def format_atom_prompt(self, entity: str, relation: str, leading_space: bool = False) -> str: text = f"{entity}'s {relation} is" return f" {text}" if leading_space else text def generate_graph(self, edges_per_entity: int = 5, ensure_connectivity: bool = True): """ Generate a non-layerwise knowledge graph. Args: edges_per_entity: Average number of outgoing edges per entity ensure_connectivity: If True, ensure the graph is connected """ self.knowledge_graph.clear() # For each entity and relation, assign a target entity # This creates a flat, non-layerwise structure for entity in self.entities: # Randomly select relations for this entity num_edges = random.randint( max(1, edges_per_entity - 2), edges_per_entity + 2 ) selected_relations = random.sample( self.relations, min(num_edges, len(self.relations)) ) for relation in selected_relations: # Select a target entity (can be any entity except self) possible_targets = [e for e in self.entities if e != entity] target = random.choice(possible_targets) self.knowledge_graph[(entity, relation)] = target # Ensure connectivity if requested if ensure_connectivity: self._ensure_connectivity() def _ensure_connectivity(self): """Ensure the graph is connected by adding edges if necessary.""" # Simple approach: ensure each entity has at least one incoming and one outgoing edge entities_with_outgoing = set(entity for entity, _ in self.knowledge_graph.keys()) entities_with_incoming = set(self.knowledge_graph.values()) # Add outgoing edges for entities without them for entity in self.entities: if entity not in entities_with_outgoing: relation = random.choice(self.relations) target = random.choice([e for e in self.entities if e != entity]) self.knowledge_graph[(entity, relation)] = target # Add incoming edges for entities without them if entity not in entities_with_incoming: source = random.choice([e for e in self.entities if e != entity]) relation = random.choice(self.relations) self.knowledge_graph[(source, relation)] = entity def _find_n_hop_path(self, n: int) -> Tuple[str, List[str], str]: """ Find an n-hop path in the graph. Returns: (start_entity, [relation1, relation2, ...], end_entity) """ max_attempts = 1000 for _ in range(max_attempts): # Start from a random entity start_entity = random.choice(self.entities) path = [start_entity] relations = [] current = start_entity success = True for hop in range(n): # Find all possible next hops possible_next = [ (rel, target) for (ent, rel), target in self.knowledge_graph.items() if ent == current ] if not possible_next: success = False break if self.sampling_alpha is not None: # Power law (Zipf) sampling # w_i = (rank_i)^(-alpha) weights = [ (self.rel_to_idx[rel] + 1) ** (-self.sampling_alpha) for rel, target in possible_next ] relation, next_entity = random.choices(possible_next, weights=weights, k=1)[0] else: # Uniform sampling relation, next_entity = random.choice(possible_next) relations.append(relation) path.append(next_entity) current = next_entity if success and len(path) == n + 1: return start_entity, relations, path[-1] # If we couldn't find a path, create one by ensuring connectivity return self._create_n_hop_path(n) def _create_n_hop_path(self, n: int) -> Tuple[str, List[str], str]: """Create an n-hop path by adding edges if necessary.""" entities = random.sample(self.entities, n + 1) relations = random.sample(self.relations * ((n // len(self.relations)) + 1), n) # Add edges to graph for i in range(n): self.knowledge_graph[(entities[i], relations[i])] = entities[i + 1] return entities[0], relations, entities[-1] def _format_question(self, start_entity: str, relations: List[str]) -> str: """Format a multi-hop question from a start entity and relation chain.""" num_hops = len(relations) if num_hops == 2: return f"Who is the {relations[1]} of the {relations[0]} of {start_entity}?" if num_hops == 3: return f"Who is the {relations[2]} of the {relations[1]} of the {relations[0]} of {start_entity}?" if num_hops == 4: return f"Who is the {relations[3]} of the {relations[2]} of the {relations[1]} of the {relations[0]} of {start_entity}?" reversed_relations = list(reversed(relations)) relation_chain = " of the ".join(reversed_relations) return f"Who is the {relation_chain} of {start_entity}?" def format_multihop_prompt( self, start_entity: str, relations: List[str], multi_hop_format: str = "reverse", leading_space: bool = False, ) -> str: if multi_hop_format == "reverse": text = f"{self._format_question(start_entity, relations)}\nAnswer:" elif multi_hop_format == "direct": relation_chain = "".join([f"'s {relation}" for relation in relations]) text = f"{start_entity}{relation_chain} is" else: raise ValueError(f"Unknown multi_hop_format: {multi_hop_format}") return f" {text}" if leading_space else text def format_multihop_example( self, start_entity: str, relations: List[str], end_entity: str, multi_hop_format: str = "reverse", leading_space: bool = False, ) -> str: return f"{self.format_multihop_prompt(start_entity, relations, multi_hop_format, leading_space)} {end_entity}" def _follow_path(self, start_entity: str, relations: List[str]) -> List[str]: entities_in_path = [start_entity] current = start_entity for relation in relations: next_entity = self.knowledge_graph.get((current, relation)) if next_entity is None: break entities_in_path.append(next_entity) current = next_entity return entities_in_path def build_multihop_record( self, start_entity: str, relations: List[str], end_entity: str, multi_hop_format: str = "reverse", leading_space: bool = False, text_with_answer: bool = True, ) -> Dict: question = self._format_question(start_entity, relations) prompt = self.format_multihop_prompt( start_entity, relations, multi_hop_format=multi_hop_format, leading_space=leading_space, ) target = self.format_multihop_example( start_entity, relations, end_entity, multi_hop_format=multi_hop_format, leading_space=leading_space, ) entities_in_path = self._follow_path(start_entity, relations) return { "question": question, "answer": end_entity, "q_type": "_".join([f"{rel}_1" for rel in relations]), "q_person": start_entity, "var": entities_in_path[1:], "relations": relations, "text": target if text_with_answer else prompt, "label": target, "input_text": prompt, "target_text": target, "format": multi_hop_format, } def sample_unique_multihop_examples( self, num_examples: int, num_hops: int, multi_hop_format: str = "reverse", leading_space: bool = False, seen: Optional[Set[Tuple[str, Tuple[str, ...], str]]] = None, ) -> List[Dict]: examples: List[Dict] = [] seen_keys = seen if seen is not None else set() max_attempts = max(1000, num_examples * 200) attempts = 0 while len(examples) < num_examples and attempts < max_attempts: attempts += 1 start_entity, relations, end_entity = self._find_n_hop_path(num_hops) key = (start_entity, tuple(relations), end_entity) if key in seen_keys: continue seen_keys.add(key) examples.append( self.build_multihop_record( start_entity, relations, end_entity, multi_hop_format=multi_hop_format, leading_space=leading_space, text_with_answer=True, ) ) if len(examples) < num_examples: raise RuntimeError( f"Could only sample {len(examples)} unique {num_hops}-hop examples after {attempts} attempts" ) return examples def generate_all_atom_examples( self, split_atom_sequences: bool = False, leading_space: bool = False, ) -> List[Dict]: examples: List[Dict] = [] entity_to_facts = self.get_entity_fact_map() for entity in self.entities: facts = entity_to_facts.get(entity, [])[:] random.shuffle(facts) if not facts: continue if split_atom_sequences: for relation, target in facts: prompt = self.format_atom_prompt(entity, relation, leading_space=leading_space) target_text = self.format_atom_fact(entity, relation, target, leading_space=leading_space) examples.append( { "text": target_text, "input_text": prompt, "target_text": target_text, "entity": entity, "relation": relation, "answer": target, "kind": "atom", } ) else: fact_texts = [self.format_atom_fact(entity, relation, target) for relation, target in facts] text = ". ".join(fact_texts) + "." if leading_space: text = f" {text}" examples.append( { "text": text, "input_text": "", "target_text": text, "entity": entity, "kind": "atom_group", } ) return examples def generate_training_examples( self, num_examples: int, num_hops: int, split_atom_sequences: bool = False, leading_space: bool = False, ) -> List[Dict]: """Generate training profile examples (facts only, no questions).""" examples = [] for _ in range(num_examples): # Select a random entity entity = random.choice(self.entities) # Get all facts about this entity facts = [] for (ent, rel), target in self.knowledge_graph.items(): if ent == entity: facts.append(f"{entity}'s {rel} is {target}") # Shuffle facts random.shuffle(facts) if split_atom_sequences: relation, target = random.choice( [(rel, tgt) for (ent, rel), tgt in self.knowledge_graph.items() if ent == entity] ) prompt = self.format_atom_prompt(entity, relation, leading_space=leading_space) target_text = self.format_atom_fact(entity, relation, target, leading_space=leading_space) examples.append({ "text": target_text, "input_text": prompt, "target_text": target_text, "entity": entity, "relation": relation, "answer": target, "kind": "atom", }) else: text = ". ".join(facts) + "." if leading_space: text = f" {text}" examples.append({ "text": text, "input_text": "", "target_text": text, "entity": entity, "kind": "atom_group", }) return examples def generate_train_qa_examples( self, num_examples: int, num_hops: int, multi_hop_format: str = "reverse", leading_space: bool = False, ) -> List[Dict]: """Generate training QA examples with answer in text.""" examples = [] for _ in range(num_examples): # Find an n-hop path start_entity, relations, end_entity = self._find_n_hop_path(num_hops) examples.append( self.build_multihop_record( start_entity, relations, end_entity, multi_hop_format=multi_hop_format, leading_space=leading_space, text_with_answer=True, ) ) return examples def generate_test_examples( self, num_examples: int, num_hops: int, multi_hop_format: str = "reverse", leading_space: bool = False, ) -> List[Dict]: """Generate test examples with questions and answers.""" examples = [] for _ in range(num_examples): # Find an n-hop path start_entity, relations, end_entity = self._find_n_hop_path(num_hops) record = self.build_multihop_record( start_entity, relations, end_entity, multi_hop_format=multi_hop_format, leading_space=leading_space, text_with_answer=False, ) examples.append(record) return examples def save_to_file(self, examples: List[Dict], output_path: str): """Save examples to a JSON file.""" os.makedirs(os.path.dirname(output_path), exist_ok=True) with open(output_path, 'w') as f: json.dump(examples, f, indent=2) print(f"Saved {len(examples)} examples to {output_path}") def main(): parser = argparse.ArgumentParser(description="Generate multi-hop reasoning dataset") parser.add_argument("--num_entities", type=int, default=50, help="Number of entities") parser.add_argument("--num_relations", type=int, default=50, help="Number of relations") parser.add_argument("--num_hops", type=int, default=2, help="Number of hops (2, 3, or 4)") parser.add_argument("--num_train", type=int, default=5000, help="Number of training examples") parser.add_argument("--train_qa_ratio", type=float, default=0.5, help="Fraction of training examples that are QA") parser.add_argument("--num_test", type=int, default=1000, help="Number of test examples") parser.add_argument("--output_dir", type=str, default="data/custom", help="Output directory") parser.add_argument("--seed", type=int, default=42, help="Random seed") parser.add_argument("--edges_per_entity", type=int, default=10, help="Average edges per entity") parser.add_argument("--split-atom-sequences", action="store_true", help="Emit one atom fact per training example.") 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.") args = parser.parse_args() print(f"Generating dataset with:") print(f" - Entities: {args.num_entities}") print(f" - Relations: {args.num_relations}") print(f" - Hops: {args.num_hops}") print(f" - Training examples: {args.num_train}") print(f" - Train QA ratio: {args.train_qa_ratio}") print(f" - Test examples: {args.num_test}") print(f" - Edges per entity: {args.edges_per_entity}") # Create data generator generator = DataGenerator( num_entities=args.num_entities, num_relations=args.num_relations, seed=args.seed ) # Generate knowledge graph print("\nGenerating knowledge graph...") generator.generate_graph(edges_per_entity=args.edges_per_entity) print(f"Generated graph with {len(generator.knowledge_graph)} edges") if not 0.0 <= args.train_qa_ratio <= 1.0: raise ValueError(f"--train_qa_ratio must be between 0 and 1, got {args.train_qa_ratio}") num_train_qa = int(round(args.num_train * args.train_qa_ratio)) num_train_profiles = args.num_train - num_train_qa # Generate training examples print("\nGenerating training examples...") profile_examples = generator.generate_training_examples( num_train_profiles, args.num_hops, split_atom_sequences=args.split_atom_sequences, leading_space=args.leading_space, ) qa_examples = generator.generate_train_qa_examples( num_train_qa, args.num_hops, multi_hop_format=args.multi_hop_format, leading_space=args.leading_space, ) train_examples = profile_examples + qa_examples # Generate test examples print("\nGenerating test examples...") test_examples = generator.generate_test_examples( args.num_test, args.num_hops, multi_hop_format=args.multi_hop_format, leading_space=args.leading_space, ) # Save to files output_dir = f"{args.output_dir}/hop{args.num_hops}/E{args.num_entities}_R{args.num_relations}" train_path = f"{output_dir}/train.json" test_path = f"{output_dir}/test.json" generator.save_to_file(train_examples, train_path) generator.save_to_file(test_examples, test_path) print("\nDataset generation complete!") print(f"Training data: {train_path}") print(f"Test data: {test_path}") if __name__ == "__main__": main()