File size: 4,546 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 | 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
|