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
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
'''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.
    '''
    # Set random seeds
    torch.manual_seed(4242)
    dgl.seed(4242)

    # Set config
    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.)

    # Set up PyTorch device
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    # Set up graph path
    graph_path = Path(f'dgl-graph-{size}.bin')

    # Load the graph if it exists
    if graph_path.exists():
        graph = load_dgl_graph(graph_path)

    # Otherwise, build the graph and save it
    else:
        # Build the graph
        graph = load_mumin_graph(size=size)

        # Save the graph
        save_dgl_graph(graph, graph_path)

    # Store labels and masks
    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()

    # Initialise dictionary with feature dimensions
    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}

    # Initialise model
    model = HeteroGraphSAGE(input_dropout=0.2,
                            dropout=0.2,
                            hidden_dim=1024,
                            feat_dict=feat_dict,
                            task=task)
    model.to(device)
    model.train()

    # Enumerate the nodes with the labels, for performing train/val/test splits
    node_enum = torch.arange(graph.num_nodes(task))

    # If we are performing a random split then split the dataset into a
    # 80/10/10 train/val/test split, with a fixed random seed
    if random_split:

        # Set a random seed through a PyTorch Generator
        torch_gen = torch.Generator().manual_seed(4242)

        # Compute the number of train/val/test samples
        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]

        # Split the data, using the PyTorch generator for reproducibility
        train_nids, val_nids, test_nids = D.random_split(dataset=node_enum,
                                                         lengths=nums,
                                                         generator=torch_gen)

        # Store the resulting node IDs
        train_nids = {task: train_nids}
        val_nids = {task: val_nids}
        test_nids = {task: test_nids}

    # If we are not performing a random split we're performing a split based on
    # the claim clusters of the data. This means that the different splits will
    # belong to different events, thus making the task harder.
    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()}

    # Set up the sampler
    sampler = MultiLayerNeighborSampler([100, 100], replace=False)

    # Set up the dataloaders
    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)

    # Set up pos_weight
    pos_weight_tensor = torch.tensor(20.).to(device)

    # Set up path to state dict
    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)

    # Initialise optimiser
    opt = optim.AdamW(model.parameters(), lr=3e-4, betas=(0.9, 0.999))

    # Initialise learning rate scheduler
    scheduler = LinearLR(optimizer=opt,
                         start_factor=1.,
                         end_factor=1e-7 / 3e-4,
                         total_iters=100)

    # Initialise scorer
    scorer = tm.F1Score(num_classes=2, average='none').to(device)

    # Initialise progress bar
    epoch_pbar = tqdm(range(num_epochs), desc='Training')

    for epoch in epoch_pbar:

        # Reset metrics
        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

        # Reset metrics
        scorer.reset()

        # Train model
        model.train()
        for _, _, blocks in train_dataloader:

            # Reset the gradients
            opt.zero_grad()

            # Ensure that `blocks` are on the correct device
            blocks = [block.to(device) for block in blocks]

            # Get the input features and the output labels
            input_feats = {n: feat.float()
                           for n, feat in blocks[0].srcdata['feat'].items()}
            output_labels = blocks[-1].dstdata['label'][task].to(device)

            # Forward propagation
            logits = model(blocks, input_feats).squeeze()

            # Compute loss
            loss = F.binary_cross_entropy_with_logits(
                input=logits,
                target=output_labels.float(),
                pos_weight=pos_weight_tensor
            )

            # Compute training metrics
            scorer(logits.ge(0), output_labels)

            # Backward propagation
            loss.backward()

            # Update gradients
            opt.step()

            # Store the training loss
            train_loss += float(loss)

        # Divide the training loss by the number of batches
        train_loss /= len(train_dataloader)

        # Compute the training metrics
        train_f1s = scorer.compute()
        train_misinformation_f1 = train_f1s[0].item()
        train_factual_f1 = train_f1s[1].item()

        # Reset the metrics
        scorer.reset()

        # Evaluate model
        model.eval()
        for _, _, blocks in val_dataloader:
            with torch.no_grad():

                # Ensure that `blocks` are on the correct device
                blocks = [block.to(device) for block in blocks]

                # Get the input features and the output labels
                input_feats = {n: f.float()
                               for n, f in blocks[0].srcdata['feat'].items()}
                output_labels = blocks[-1].dstdata['label'][task].to(device)

                # Forward propagation
                logits = model(blocks, input_feats).squeeze()

                # Compute validation loss
                loss = F.binary_cross_entropy_with_logits(
                    input=logits,
                    target=output_labels.float(),
                    pos_weight=pos_weight_tensor
                )

                # Compute validation metrics
                scorer(logits.ge(0), output_labels)

                # Store the validation loss
                val_loss += float(loss)

        # Divide the validation loss by the number of batches
        val_loss /= len(val_dataloader)

        # Compute the validation metrics
        val_f1s = scorer.compute()
        val_misinformation_f1 = val_f1s[0].item()
        val_factual_f1 = val_f1s[1].item()

        # Gather statistics to be logged
        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'])
        ]

        # Report and log statistics
        config['epoch'] = epoch
        for statistic, value in stats:
            config[statistic] = value

        # Update progress bar description
        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)

        # Update learning rate
        scheduler.step()

    # Close progress bar
    epoch_pbar.close()

    # Reset loss
    val_loss = 0.0
    test_loss = 0.0

    # Reset metrics
    scorer.reset()

    # Final evaluation on the validation set
    model.eval()
    for _, _, blocks in tqdm(val_dataloader, desc='Evaluating'):
        with torch.no_grad():

            # Ensure that `blocks` are on the correct device
            blocks = [block.to(device) for block in blocks]

            # Get the input features and the output labels
            input_feats = {n: f.float()
                           for n, f in blocks[0].srcdata['feat'].items()}
            output_labels = blocks[-1].dstdata['label'][task].to(device)

            # Forward propagation
            logits = model(blocks, input_feats).squeeze()

            # Compute validation loss
            loss = F.binary_cross_entropy_with_logits(
                input=logits,
                target=output_labels.float(),
                pos_weight=pos_weight_tensor
            )

            # Compute validation metrics
            scorer(logits.ge(0), output_labels)

            # Store the validation loss
            val_loss += float(loss)

    # Divide the validation loss by the number of batches
    val_loss /= len(val_dataloader)

    # Compute the validation metrics
    val_f1s = scorer.compute()
    val_misinformation_f1 = val_f1s[0].item()
    val_factual_f1 = val_f1s[1].item()

    # Reset the metrics
    scorer.reset()

    # Final evaluation on the test set
    model.eval()
    for _, _, blocks in tqdm(test_dataloader, desc='Evaluating'):
        with torch.no_grad():

            # Ensure that `blocks` are on the correct device
            blocks = [block.to(device) for block in blocks]

            # Get the input features and the output labels
            input_feats = {n: f.float()
                           for n, f in blocks[0].srcdata['feat'].items()}
            output_labels = blocks[-1].dstdata['label'][task].to(device)

            # Forward propagation
            logits = model(blocks, input_feats).squeeze()

            # Compute test loss
            loss = F.binary_cross_entropy_with_logits(
                input=logits,
                target=output_labels.float(),
                pos_weight=pos_weight_tensor
            )

            # Compute test metrics
            scorer(logits.ge(0), output_labels)

            # Store the test loss
            test_loss += float(loss)

    # Divide the test loss by the number of batches
    test_loss /= len(test_dataloader)

    # Compute the test metrics
    test_f1s = scorer.compute()
    test_misinformation_f1 = test_f1s[0].item()
    test_factual_f1 = test_f1s[1].item()

    # Gather statistics to be logged
    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