Compute metrics/loss every n batches Pytorch Lightning
I'm trying to use Pytorch lighning but I don't have clear all the steps. Anyway I'm trying to calculate the train_loss (for example) not only for each step(=batch) but every n bacthes (i.e. 500) but I'm not sure how to compute it (compute, reset etc). I tried this approach but this is not working. Can you help me? thanks
def training_step(self, batch: tuple, batch_nb: int, *args, **kwargs) -&gt; dict:
        &quot;&quot;&quot; 
        Runs one training step. This usually consists in the forward function followed
            by the loss function.
        
        :param batch: The output of your dataloader. 
        :param batch_nb: Integer displaying which batch this is
        Returns:
            - dictionary containing the loss and the metrics to be added to the lightning logger.
        &quot;&quot;&quot;
        inputs, targets = batch
        model_out = self.forward(**inputs)
        loss_val = self.loss(model_out, targets)
        


        y = targets[&quot;labels&quot;]
        y_hat = model_out[&quot;logits&quot;]
        
        labels_hat = torch.argmax(y_hat, dim=1)
        val_acc = self.metric_acc(labels_hat, y)
        tqdm_dict = {&quot;train_loss&quot;: loss_val, 'batch_nb': batch_nb}
        self.log('train_loss', loss_val, on_step=True, on_epoch=True,prog_bar=True)
        self.log('train_acc', val_acc, on_step=True, prog_bar=True,on_epoch=True)

        # reset the metric to restart accumulating
        self.loss_val_bn = self.loss(model_out, targets) #accumulate state
        if batch_nb % 500 == 0:
            self.log(&quot;x batches test loss_train&quot;, self.loss_val_bn.compute(),batch_nb) # perform a compute every 10 batches
            self.loss_val_bn.reset() 


        #output = OrderedDict(
            #{&quot;loss&quot;: loss_val, &quot;progress_bar&quot;: tqdm_dict, &quot;log&quot;: tqdm_dict})

        # can also return just a scalar instead of a dict (return loss_val)
        #return output
        return loss_val



Write your custom logger following (https://pytorch-lightning.readthedocs.io/en/stable/extensions/logging.html#make-a-custom-logger). The one I present here stores the values generated in every step in a dict where each metric name is a key.

class History_dict(LightningLoggerBase):
    def __init__(self):
        super().__init__()

        self.history = collections.defaultdict(list) # copy not necessary here  
        # The defaultdict in contrast will simply create any items that you try to access

    @property
    def name(self):
        return &quot;Logger_custom_plot&quot;

    @property
    def version(self):
        return &quot;1.0&quot;

    @property
    @rank_zero_experiment
    def experiment(self):
        # Return the experiment object associated with this logger.
        pass

    @rank_zero_only
    def log_metrics(self, metrics, step):
        # metrics is a dictionary of metric names and values
        # your code to record metrics goes here
        for metric_name, metric_value in metrics.items():
            if metric_name != 'epoch':
                self.history[metric_name].append(metric_value)
            else: # case epoch. We want to avoid adding multiple times the same. It happens for multiple losses.
                if (not len(self.history['epoch']) or    # len == 0:
                    not self.history['epoch'][-1] == metric_value) : # the last values of epochs is not the one we are currently trying to add.
                    self.history['epoch'].append(metric_value)
                else:
                    pass
        return

    def log_hyperparams(self, params):
        pass


Make the model reduce the stored metrics every n steps. I assume that taking the mean is how you want to reduce here. Empty the list after reducing.

class MNISTModel(LightningModule):
    def __init__(self):
        super().__init__()
        self.l1 = torch.nn.Linear(28 * 28, 10)

    def forward(self, x):
        return torch.relu(self.l1(x.view(x.size(0), -1)))

    def training_step(self, batch, batch_nb):
        x, y = batch
        loss = F.cross_entropy(self(x), y)
        self.log('loss_epoch', loss, on_step=False, on_epoch=True)
        self.log('loss_step', loss, on_step=True, on_epoch=False)
        print(self.global_step)
        if batch_nb % 50 == 0 and self.global_step != 0:
            step_metrics = self.logger.history['loss_step']
            # I am assuming that the reduction function you want over the saved step values are mean
            reduced = sum(step_metrics) / len(step_metrics)  
            print(reduced)
            # Empty the loss list
            self.logger.history['loss_step'] = []
        return loss

    def configure_optimizers(self):
        return torch.optim.Adam(self.parameters(), lr=0.02)


Pass this custom logger to your trainer

hd = History_dict()

# Initialize a trainer
trainer = Trainer(
    accelerator=&quot;auto&quot;,
    devices=1 if torch.cuda.is_available() else None,  # limiting got iPython runs
    max_epochs=3,
    callbacks=[TQDMProgressBar(refresh_rate=20)],
    log_every_n_steps=10,
    logger=[hd],
)

You should see the following being printed with this exact configuration:
0
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
0.9309097290039062
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
0.9098988473415375
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
0.8920584758122762
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
0.8698084503412247
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
0.8622475385665893
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
0.8433656434218089
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
0.8188161773341043
...

