| '''Training scripts''' |
|
|
| from data import load_mumin_graph |
| from model import HeteroGraphSAGE |
|
|
| from pathlib import Path |
| import torch |
| import torch.nn.functional as F |
| import torch.optim as optim |
| import torch.utils.data as D |
| from torch.optim.lr_scheduler import LinearLR |
| import torchmetrics as tm |
| from dgl.dataloading.neighbor import MultiLayerNeighborSampler |
| from dgl.dataloading.pytorch import NodeDataLoader |
| import dgl |
| import logging |
| import datetime as dt |
| from tqdm.auto import tqdm |
| from mumin import load_dgl_graph, save_dgl_graph |
| from typing import Dict |
|
|
|
|
| logger = logging.getLogger(__name__) |
|
|
|
|
| def train_graph_model(task: str, |
| size: str, |
| num_epochs: int = 300, |
| random_split: bool = False, |
| **_) -> Dict[str, Dict[str, float]]: |
| '''Train a heterogeneous GraphConv model on the MuMiN dataset. |
| |
| Args: |
| task (str): |
| The task to consider, which can be either 'tweet' or 'claim', |
| corresponding to doing thread-level or claim-level node |
| classification. |
| size (str): |
| The size of the dataset to use. |
| num_epochs (int, optional): |
| The number of epochs to train for. Defaults to 300. |
| random_split (bool, optional): |
| Whether a random train/val/test split of the data should be |
| performed (with a fixed random seed). If not then the claim cluster |
| splits will be used. Defaults to False. |
| |
| dict: |
| The results of the training, with keys 'train', 'val' and 'split', |
| with dictionaries with the split scores as values. |
| ''' |
| |
| torch.manual_seed(4242) |
| dgl.seed(4242) |
|
|
| |
| config = dict(hidden_dim=1024, |
| input_dropout=0.2, |
| dropout=0.2, |
| size=size, |
| task=task, |
| lr=3e-4, |
| betas=(0.9, 0.999), |
| pos_weight=20.) |
|
|
| |
| device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') |
|
|
| |
| graph_path = Path(f'dgl-graph-{size}.bin') |
|
|
| |
| if graph_path.exists(): |
| graph = load_dgl_graph(graph_path) |
|
|
| |
| else: |
| |
| graph = load_mumin_graph(size=size) |
|
|
| |
| save_dgl_graph(graph, graph_path) |
|
|
| |
| train_mask = graph.nodes[task].data['train_mask'].bool() |
| val_mask = graph.nodes[task].data['val_mask'].bool() |
| test_mask = graph.nodes[task].data['test_mask'].bool() |
|
|
| |
| dims = {ntype: graph.nodes[ntype].data['feat'].shape[-1] |
| for ntype in graph.ntypes} |
| feat_dict = {rel: (dims[rel[0]], dims[rel[2]]) |
| for rel in graph.canonical_etypes} |
|
|
| |
| model = HeteroGraphSAGE(input_dropout=0.2, |
| dropout=0.2, |
| hidden_dim=1024, |
| feat_dict=feat_dict, |
| task=task) |
| model.to(device) |
| model.train() |
|
|
| |
| node_enum = torch.arange(graph.num_nodes(task)) |
|
|
| |
| |
| if random_split: |
|
|
| |
| torch_gen = torch.Generator().manual_seed(4242) |
|
|
| |
| num_train = int(0.8 * graph.num_nodes(task)) |
| num_val = int(0.1 * graph.num_nodes(task)) |
| num_test = graph.num_nodes(task) - (num_train + num_val) |
| nums = [num_train, num_val, num_test] |
|
|
| |
| train_nids, val_nids, test_nids = D.random_split(dataset=node_enum, |
| lengths=nums, |
| generator=torch_gen) |
|
|
| |
| train_nids = {task: train_nids} |
| val_nids = {task: val_nids} |
| test_nids = {task: test_nids} |
|
|
| |
| |
| |
| else: |
| train_nids = {task: node_enum[train_mask].int()} |
| val_nids = {task: node_enum[val_mask].int()} |
| test_nids = {task: node_enum[test_mask].int()} |
|
|
| |
| sampler = MultiLayerNeighborSampler([100, 100], replace=False) |
|
|
| |
| train_dataloader = NodeDataLoader(g=graph, |
| nids=train_nids, |
| block_sampler=sampler, |
| batch_size=32, |
| shuffle=True, |
| drop_last=False, |
| num_workers=1) |
| val_dataloader = NodeDataLoader(g=graph, |
| nids=val_nids, |
| block_sampler=sampler, |
| batch_size=1000000, |
| shuffle=False, |
| drop_last=False, |
| num_workers=1) |
| test_dataloader = NodeDataLoader(g=graph, |
| nids=test_nids, |
| block_sampler=sampler, |
| batch_size=1000000, |
| shuffle=False, |
| drop_last=False, |
| num_workers=1) |
|
|
| |
| pos_weight_tensor = torch.tensor(20.).to(device) |
|
|
| |
| datetime = dt.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') |
| Path('models').mkdir(exist_ok=True) |
| model_dir = Path('models') / f'{datetime}-{task}-model-{size}' |
| model_dir.mkdir(exist_ok=True) |
|
|
| |
| opt = optim.AdamW(model.parameters(), lr=3e-4, betas=(0.9, 0.999)) |
|
|
| |
| scheduler = LinearLR(optimizer=opt, |
| start_factor=1., |
| end_factor=1e-7 / 3e-4, |
| total_iters=100) |
|
|
| |
| scorer = tm.F1Score(num_classes=2, average='none').to(device) |
|
|
| |
| epoch_pbar = tqdm(range(num_epochs), desc='Training') |
|
|
| for epoch in epoch_pbar: |
|
|
| |
| train_loss = 0.0 |
| train_misinformation_f1 = 0.0 |
| train_factual_f1 = 0.0 |
| val_loss = 0.0 |
| val_misinformation_f1 = 0.0 |
| val_factual_f1 = 0.0 |
|
|
| |
| scorer.reset() |
|
|
| |
| model.train() |
| for _, _, blocks in train_dataloader: |
|
|
| |
| opt.zero_grad() |
|
|
| |
| blocks = [block.to(device) for block in blocks] |
|
|
| |
| input_feats = {n: feat.float() |
| for n, feat in blocks[0].srcdata['feat'].items()} |
| output_labels = blocks[-1].dstdata['label'][task].to(device) |
|
|
| |
| logits = model(blocks, input_feats).squeeze() |
|
|
| |
| loss = F.binary_cross_entropy_with_logits( |
| input=logits, |
| target=output_labels.float(), |
| pos_weight=pos_weight_tensor |
| ) |
|
|
| |
| scorer(logits.ge(0), output_labels) |
|
|
| |
| loss.backward() |
|
|
| |
| opt.step() |
|
|
| |
| train_loss += float(loss) |
|
|
| |
| train_loss /= len(train_dataloader) |
|
|
| |
| train_f1s = scorer.compute() |
| train_misinformation_f1 = train_f1s[0].item() |
| train_factual_f1 = train_f1s[1].item() |
|
|
| |
| scorer.reset() |
|
|
| |
| model.eval() |
| for _, _, blocks in val_dataloader: |
| with torch.no_grad(): |
|
|
| |
| blocks = [block.to(device) for block in blocks] |
|
|
| |
| input_feats = {n: f.float() |
| for n, f in blocks[0].srcdata['feat'].items()} |
| output_labels = blocks[-1].dstdata['label'][task].to(device) |
|
|
| |
| logits = model(blocks, input_feats).squeeze() |
|
|
| |
| loss = F.binary_cross_entropy_with_logits( |
| input=logits, |
| target=output_labels.float(), |
| pos_weight=pos_weight_tensor |
| ) |
|
|
| |
| scorer(logits.ge(0), output_labels) |
|
|
| |
| val_loss += float(loss) |
|
|
| |
| val_loss /= len(val_dataloader) |
|
|
| |
| val_f1s = scorer.compute() |
| val_misinformation_f1 = val_f1s[0].item() |
| val_factual_f1 = val_f1s[1].item() |
|
|
| |
| stats = [ |
| ('train_loss', train_loss), |
| ('train_misinformation_f1', train_misinformation_f1), |
| ('train_factual_f1', train_factual_f1), |
| ('val_loss', val_loss), |
| ('val_misinformation_f1', val_misinformation_f1), |
| ('val_factual_f1', val_factual_f1), |
| ('learning_rate', opt.param_groups[0]['lr']) |
| ] |
|
|
| |
| config['epoch'] = epoch |
| for statistic, value in stats: |
| config[statistic] = value |
|
|
| |
| desc = (f'Training - ' |
| f'loss {train_loss:.3f} - ' |
| f'factual_f1 {train_factual_f1:.3f} - ' |
| f'misinfo_f1 {train_misinformation_f1:.3f} - ' |
| f'val_loss {val_loss:.3f} - ' |
| f'val_factual_f1 {val_factual_f1:.3f} - ' |
| f'val_misinfo_f1 {val_misinformation_f1:.3f}') |
| epoch_pbar.set_description(desc) |
|
|
| |
| scheduler.step() |
|
|
| |
| epoch_pbar.close() |
|
|
| |
| val_loss = 0.0 |
| test_loss = 0.0 |
|
|
| |
| scorer.reset() |
|
|
| |
| model.eval() |
| for _, _, blocks in tqdm(val_dataloader, desc='Evaluating'): |
| with torch.no_grad(): |
|
|
| |
| blocks = [block.to(device) for block in blocks] |
|
|
| |
| input_feats = {n: f.float() |
| for n, f in blocks[0].srcdata['feat'].items()} |
| output_labels = blocks[-1].dstdata['label'][task].to(device) |
|
|
| |
| logits = model(blocks, input_feats).squeeze() |
|
|
| |
| loss = F.binary_cross_entropy_with_logits( |
| input=logits, |
| target=output_labels.float(), |
| pos_weight=pos_weight_tensor |
| ) |
|
|
| |
| scorer(logits.ge(0), output_labels) |
|
|
| |
| val_loss += float(loss) |
|
|
| |
| val_loss /= len(val_dataloader) |
|
|
| |
| val_f1s = scorer.compute() |
| val_misinformation_f1 = val_f1s[0].item() |
| val_factual_f1 = val_f1s[1].item() |
|
|
| |
| scorer.reset() |
|
|
| |
| model.eval() |
| for _, _, blocks in tqdm(test_dataloader, desc='Evaluating'): |
| with torch.no_grad(): |
|
|
| |
| blocks = [block.to(device) for block in blocks] |
|
|
| |
| input_feats = {n: f.float() |
| for n, f in blocks[0].srcdata['feat'].items()} |
| output_labels = blocks[-1].dstdata['label'][task].to(device) |
|
|
| |
| logits = model(blocks, input_feats).squeeze() |
|
|
| |
| loss = F.binary_cross_entropy_with_logits( |
| input=logits, |
| target=output_labels.float(), |
| pos_weight=pos_weight_tensor |
| ) |
|
|
| |
| scorer(logits.ge(0), output_labels) |
|
|
| |
| test_loss += float(loss) |
|
|
| |
| test_loss /= len(test_dataloader) |
|
|
| |
| test_f1s = scorer.compute() |
| test_misinformation_f1 = test_f1s[0].item() |
| test_factual_f1 = test_f1s[1].item() |
|
|
| |
| results = { |
| 'train': { |
| 'loss': train_loss, |
| 'factual_f1': train_factual_f1, |
| 'misinformation_f1': train_misinformation_f1 |
| }, |
| 'val': { |
| 'loss': val_loss, |
| 'factual_f1': val_factual_f1, |
| 'misinformation_f1': val_misinformation_f1 |
| }, |
| 'test': { |
| 'loss': test_loss, |
| 'factual_f1': test_factual_f1, |
| 'misinformation_f1': test_misinformation_f1 |
| } |
| } |
|
|
| return results |
|
|