Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

wandb_callbacks.py 5.7 KB

You have to be logged in to leave a comment. Sign In
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
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
  1. import glob
  2. import os
  3. import wandb
  4. from pytorch_lightning import Callback, Trainer
  5. from pytorch_lightning.loggers import LoggerCollection, WandbLogger
  6. def get_wandb_logger(trainer: Trainer) -> WandbLogger:
  7. if isinstance(trainer.logger, WandbLogger):
  8. return trainer.logger
  9. if isinstance(trainer.logger, LoggerCollection):
  10. for logger in trainer.logger:
  11. if isinstance(logger, WandbLogger):
  12. return logger
  13. raise Exception(
  14. "You are using wandb related callback, but WandbLogger was not found for some reason..."
  15. )
  16. class WatchModelWithWandb(Callback):
  17. """Make WandbLogger watch model at the beginning of the run."""
  18. def __init__(self, log: str = "gradients", log_freq: int = 100):
  19. self.log = log
  20. self.log_freq = log_freq
  21. def on_train_start(self, trainer, pl_module):
  22. logger = get_wandb_logger(trainer=trainer)
  23. logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq)
  24. class UploadCodeToWandbAsArtifact(Callback):
  25. """Upload all *.py files to wandb as an artifact, at the beginning of the run."""
  26. def __init__(self, code_dir: str):
  27. self.code_dir = code_dir
  28. def on_train_start(self, trainer, pl_module):
  29. logger = get_wandb_logger(trainer=trainer)
  30. experiment = logger.experiment
  31. code = wandb.Artifact("project-source", type="code")
  32. for path in glob.glob(os.path.join(self.code_dir, "**/*.py"), recursive=True):
  33. code.add_file(path)
  34. experiment.use_artifact(code)
  35. class UploadCheckpointsToWandbAsArtifact(Callback):
  36. """Upload checkpoints to wandb as an artifact, at the end of run."""
  37. def __init__(self, ckpt_dir: str = "checkpoints/", upload_best_only: bool = False):
  38. self.ckpt_dir = ckpt_dir
  39. self.upload_best_only = upload_best_only
  40. def on_train_end(self, trainer, pl_module):
  41. logger = get_wandb_logger(trainer=trainer)
  42. experiment = logger.experiment
  43. ckpts = wandb.Artifact("experiment-ckpts", type="checkpoints")
  44. if self.upload_best_only:
  45. ckpts.add_file(trainer.checkpoint_callback.best_model_path)
  46. else:
  47. for path in glob.glob(
  48. os.path.join(self.ckpt_dir, "**/*.ckpt"), recursive=True
  49. ):
  50. ckpts.add_file(path)
  51. experiment.use_artifact(ckpts)
  52. # source: https://github.com/PyTorchLightning/pytorch-lightning/discussions/9910
  53. class LogConfusionMatrixToWandbVal(Callback):
  54. def __init__(self):
  55. self.preds = []
  56. self.targets = []
  57. self.ready = True
  58. def on_sanity_check_start(self, trainer, pl_module) -> None:
  59. self.ready = False
  60. def on_sanity_check_end(self, trainer, pl_module):
  61. self.ready = True
  62. # def on_validation_batch_end(
  63. # self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx
  64. # ):
  65. # if self.ready:
  66. # self.preds.append(outputs[OutputKeys.PREDICTION].detach().cpu().numpy())
  67. # self.targets.append(outputs[OutputKeys.TARGET].detach().cpu().numpy())
  68. # #@rank_zero_only
  69. # def on_validation_epoch_end(self, trainer, pl_module):
  70. # if not self.ready:
  71. # return
  72. # logger = get_wandb_logger(trainer)
  73. # experiment = logger.experiment
  74. # experiment.log(
  75. # {
  76. # "conf_mat": wandb.plot.confusion_matrix(
  77. # probs=None,
  78. # y_true=target,
  79. # preds=prediction,
  80. # class_names=["BG", "NEEDLELEAF", "BROADLEAF"],
  81. # )
  82. # }
  83. # )
  84. # conf_mat_name = f'CM_epoch_{trainer.current_epoch}'
  85. # logger = get_wandb_logger(trainer)
  86. # experiment = logger.experiment
  87. # preds = []
  88. # for step_pred in self.preds:
  89. # preds.append(trainer.model.module.module.to_metrics_format(np.array(step_pred)))
  90. # preds = np.concatenate(preds).flatten()
  91. # targets = np.concatenate(np.array(self.targets)).flatten()
  92. # num_classes = max(np.max(preds), np.max(targets)) + 1
  93. # conf_mat = confusion_matrix(
  94. # target=torch.tensor(targets),
  95. # preds=torch.tensor(preds),
  96. # num_classes=num_classes
  97. # )
  98. # # set figure size
  99. # plt.figure(figsize=(14, 8))
  100. # # set labels size
  101. # sn.set(font_scale=1.4)
  102. # # set font size
  103. # fig = sn.heatmap(conf_mat, annot=True, annot_kws={"size": 8}, fmt="g")
  104. # for i in range(conf_mat.shape[0]):
  105. # fig.add_patch(Rectangle((i, i), 1, 1, fill=False, edgecolor='yellow', lw=3))
  106. # plt.xlabel('Predictions')
  107. # plt.ylabel('Targets')
  108. # plt.title(conf_mat_name)
  109. # conf_mat_path = Path(os.getcwd()) / 'conf_mats' / 'val'
  110. # conf_mat_path.mkdir(parents=True, exist_ok=True)
  111. # conf_mat_file_path = conf_mat_path / (conf_mat_name + '.txt')
  112. # df = pd.DataFrame(conf_mat.detach().cpu().numpy())
  113. # # save as csv or tsv to disc
  114. # df.to_csv(path_or_buf=conf_mat_file_path, sep='\t')
  115. # # save tsv to wandb
  116. # experiment.save(glob_str=str(conf_mat_file_path), base_path=os.getcwd())
  117. # # names should be uniqe or else charts from different experiments in wandb will overlap
  118. # experiment.log({f"confusion_matrix_val_img/ep_{trainer.current_epoch}": wandb.Image(plt)},
  119. # commit=False)
  120. # # according to wandb docs this should also work but it crashes
  121. # # experiment.log(f{"confusion_matrix/{experiment.name}": plt})
  122. # # reset plot
  123. # plt.clf()
  124. self.preds.clear()
  125. self.targets.clear()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...