import torch from torch.utils.data import IterableDataset import random from generate_data import DataGenerator from typing import Dict, List class OnlineDataset(IterableDataset): def __init__( self, generator: DataGenerator, num_hops: int, train_qa_ratio: float, tokenizer=None, max_length=100, padding=False, split_profile_facts: bool = False, multi_hop_format: str = "reverse", leading_space: bool = False, ): """ Args: generator: Initialized DataGenerator instance with a graph. num_hops: Number of hops for QA generation. train_qa_ratio: Ratio of QA examples vs Profile examples. tokenizer: Tokenizer to process the text. max_length: Max length for tokenization. padding: Whether to pad. """ self.generator = generator self.num_hops = num_hops self.train_qa_ratio = train_qa_ratio self.tokenizer = tokenizer self.max_length = max_length self.padding = padding self.split_profile_facts = split_profile_facts self.multi_hop_format = multi_hop_format self.leading_space = leading_space # Pre-process facts for efficient sampling # Index graph by entity for O(1) access during profile generation self.entity_to_facts: Dict[str, List[tuple[str, str]]] = {} for (ent, rel), target in self.generator.knowledge_graph.items(): if ent not in self.entity_to_facts: self.entity_to_facts[ent] = [] self.entity_to_facts[ent].append((rel, target)) def _generate_profile(self): # Select a random entity entity = random.choice(self.generator.entities) # Get all facts about this entity using pre-built index facts = self.entity_to_facts.get(entity, [])[:] random.shuffle(facts) if self.split_profile_facts: relation, target = random.choice(facts) text = self.generator.format_atom_fact(entity, relation, target, leading_space=self.leading_space) else: fact_texts = [self.generator.format_atom_fact(entity, relation, target) for relation, target in facts] text = ". ".join(fact_texts) + "." if self.leading_space: text = f" {text}" return {"text": text, "kind": "atom"} def _generate_qa(self): # This involves a random walk, so we use the generator's method start_entity, relations, end_entity = self.generator._find_n_hop_path(self.num_hops) text = self.generator.format_multihop_example( start_entity, relations, end_entity, multi_hop_format=self.multi_hop_format, leading_space=self.leading_space, ) return {"text": text, "kind": "qa"} def __iter__(self): worker_info = torch.utils.data.get_worker_info() # 获取分布式训练的 rank (第几张卡) rank = 0 if torch.distributed.is_initialized(): rank = torch.distributed.get_rank() seed = self.generator.seed + rank * 1000 # 确保每张卡的种子不同 if worker_info is not None: # 再根据 worker id 进行偏移,确保每个 worker 产生不同数据 random.seed(seed + worker_info.id) else: random.seed(seed) while True: if random.random() < self.train_qa_ratio: example = self._generate_qa() else: example = self._generate_profile() if self.tokenizer: tokenized = self.tokenizer( example["text"], padding="max_length" if self.padding else False, truncation=True, max_length=self.max_length, return_special_tokens_mask=True ) # Add EOS token if not padding (consistent with train.py) if not self.padding: tokenized["input_ids"].append(self.tokenizer.eos_token_id) tokenized["attention_mask"].append(1) if self.padding: tokenized["labels"] = tokenized["input_ids"].copy() yield tokenized else: yield example