File size: 27,168 Bytes
74b7543 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 | """
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()
|