(model, dataloader, args, max_metric1, max_metric2)
| 84 | |
| 85 | |
| 86 | def evaluate_glue(model, dataloader, args, max_metric1, max_metric2): |
| 87 | |
| 88 | model.eval() |
| 89 | eval_loss = 0 |
| 90 | all_predictions = [] |
| 91 | all_true_labels = [] |
| 92 | |
| 93 | for batch in dataloader: |
| 94 | batch = {k: v.to(args.device) for k, v in batch.items()} |
| 95 | with torch.no_grad(): |
| 96 | |
| 97 | outputs = model(**batch) |
| 98 | |
| 99 | eval_loss += outputs.loss.detach().cpu().numpy() |
| 100 | |
| 101 | if args.task == "stsb": |
| 102 | predictions = outputs.logits.squeeze().cpu().numpy() |
| 103 | else: |
| 104 | predictions = outputs.logits.argmax(dim=-1).cpu().numpy() |
| 105 | all_predictions.extend(predictions) |
| 106 | all_true_labels.extend(batch["labels"].cpu().numpy()) |
| 107 | |
| 108 | eval_loss /= len(dataloader) |
| 109 | |
| 110 | # Calculate the metrics for the specific task |
| 111 | metric1, metric2 = calculate_metrics(all_true_labels, all_predictions, args.task) |
| 112 | |
| 113 | if metric1 > max_metric1: |
| 114 | max_metric1 = metric1 |
| 115 | |
| 116 | if metric2 is not None and metric2 > max_metric2: |
| 117 | max_metric2 = metric2 |
| 118 | |
| 119 | print(f"{args.task} - Eval Loss: {eval_loss:.4f}, Metric 1: {metric1:.4f}") |
| 120 | if metric2 is not None: |
| 121 | print(f"{args.task} - Metric 2: {metric2:.4f}") |
| 122 | print(f"{args.task} - Max Metric 1: {max_metric1:.4f}") |
| 123 | if max_metric2 is not None: |
| 124 | print(f"{args.task} - Max Metric 2: {max_metric2:.4f}") |
| 125 | |
| 126 | wandb.log( |
| 127 | { |
| 128 | f"eval_loss": eval_loss, |
| 129 | f"metric1": metric1, |
| 130 | f"metric2": metric2 if metric2 is not None else 0, |
| 131 | f"max_metric1": max_metric1, |
| 132 | f"max_metric2": max_metric2 if max_metric2 is not None else 0, |
| 133 | } |
| 134 | ) |
| 135 | |
| 136 | return max_metric1, max_metric2 |
| 137 | |
| 138 | |
| 139 | def get_lr_scheduler(optimizer, num_warmup_steps, num_training_steps): |
no test coverage detected