""" Knowledge-graph generator for the synthetic natural-language two-hop datasets (Sec. 5.2). - Entities are first names from utils/data/name_space.py; relations are role nouns. - Non-layerwise graph: any entity can connect to any other entity via any relation. """ import random from typing import Dict, List, Optional, Set, Tuple from utils.data.name_space import single_names class DataGenerator: def __init__( self, num_entities: int = 50, num_relations: int = 50, seed: int = 42, 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: Seed for the global `random` module, which all sampling below uses entities: Explicit entity names (default: `num_entities` random names) relations: Explicit relation names (default: the first `num_relations` names) """ # 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 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.all_relation_names()[:num_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]: """ Relation names in a fixed order. A graph uses the first `num_relations` of them; build_graph_tokenizer.py covers the first 200 (which are unique). """ 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 (17) "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 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): """ Generate a non-layerwise knowledge graph. Args: edges_per_entity: Average number of outgoing edges per entity """ 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 self._ensure_connectivity() def _ensure_connectivity(self): """Add edges so that every 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]: """ Sample an n-hop path: a uniformly random start entity, then a uniformly random outgoing edge at every hop (every entity has at least one outgoing edge). Returns: (start_entity, [relation1, relation2, ...], end_entity) """ start_entity = random.choice(self.entities) relations = [] current = start_entity for _ in range(n): possible_next = [ (rel, target) for (ent, rel), target in self.knowledge_graph.items() if ent == current ] relation, current = random.choice(possible_next) relations.append(relation) return start_entity, relations, current def _format_question(self, start_entity: str, relations: List[str]) -> str: """Format a multi-hop question from a start entity and relation chain.""" 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, ) -> 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, "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, ) ) 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, leading_space: bool = False) -> List[Dict]: """One example per atomic fact; each entity's facts are emitted in random order.""" 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) 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", } ) return examples