-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
test_logger_connector.py
692 lines (590 loc) · 25.8 KB
/
test_logger_connector.py
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
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from functools import partial
from unittest import mock
import pytest
import torch
from torch.utils.data import DataLoader
from torchmetrics import Accuracy, AveragePrecision, MeanAbsoluteError, MeanSquaredError
from pytorch_lightning import LightningModule
from pytorch_lightning.callbacks.base import Callback
from pytorch_lightning.trainer import Trainer
from pytorch_lightning.trainer.connectors.logger_connector.fx_validator import _FxValidator
from pytorch_lightning.trainer.connectors.logger_connector.result import _ResultCollection
from pytorch_lightning.utilities.exceptions import MisconfigurationException
from tests.helpers.boring_model import BoringModel, RandomDataset
from tests.helpers.runif import RunIf
from tests.models.test_hooks import get_members
def test_fx_validator(tmpdir):
funcs_name = get_members(Callback)
callbacks_func = {
"on_before_backward",
"on_after_backward",
"on_before_optimizer_step",
"on_batch_end",
"on_batch_start",
"on_before_accelerator_backend_setup",
"on_before_zero_grad",
"on_epoch_end",
"on_epoch_start",
"on_fit_end",
"on_configure_sharded_model",
"on_fit_start",
"on_init_end",
"on_init_start",
"on_keyboard_interrupt",
"on_exception",
"on_load_checkpoint",
"on_pretrain_routine_end",
"on_pretrain_routine_start",
"on_sanity_check_end",
"on_sanity_check_start",
"on_save_checkpoint",
"on_test_batch_end",
"on_test_batch_start",
"on_test_end",
"on_test_epoch_end",
"on_test_epoch_start",
"on_test_start",
"on_train_batch_end",
"on_train_batch_start",
"on_train_end",
"on_train_epoch_end",
"on_train_epoch_start",
"on_train_start",
"on_validation_batch_end",
"on_validation_batch_start",
"on_validation_end",
"on_validation_epoch_end",
"on_validation_epoch_start",
"on_validation_start",
"on_predict_batch_end",
"on_predict_batch_start",
"on_predict_end",
"on_predict_epoch_end",
"on_predict_epoch_start",
"on_predict_start",
"setup",
"teardown",
}
not_supported = {
"on_before_accelerator_backend_setup",
"on_fit_end",
"on_fit_start",
"on_configure_sharded_model",
"on_init_end",
"on_init_start",
"on_keyboard_interrupt",
"on_exception",
"on_load_checkpoint",
"on_pretrain_routine_end",
"on_pretrain_routine_start",
"on_sanity_check_end",
"on_sanity_check_start",
"on_predict_batch_end",
"on_predict_batch_start",
"on_predict_end",
"on_predict_epoch_end",
"on_predict_epoch_start",
"on_predict_start",
"on_save_checkpoint",
"on_test_end",
"on_train_end",
"on_validation_end",
"setup",
"teardown",
}
# Detected new callback function. Need to add its logging permission to FxValidator and update this test
assert funcs_name == callbacks_func
validator = _FxValidator()
for func_name in funcs_name:
# This summarizes where and what is currently possible to log using `self.log`
is_stage = "train" in func_name or "test" in func_name or "validation" in func_name
is_start = "start" in func_name or "batch" in func_name
is_epoch = "epoch" in func_name
on_step = is_stage and not is_start and not is_epoch
on_epoch = True
# creating allowed condition
allowed = (
is_stage
or "batch" in func_name
or "epoch" in func_name
or "grad" in func_name
or "backward" in func_name
or "optimizer_step" in func_name
)
allowed = (
allowed
and "pretrain" not in func_name
and "predict" not in func_name
and func_name not in ["on_train_end", "on_test_end", "on_validation_end"]
)
if allowed:
validator.check_logging_levels(fx_name=func_name, on_step=on_step, on_epoch=on_epoch)
if not is_start and is_stage:
with pytest.raises(MisconfigurationException, match="must be one of"):
validator.check_logging_levels(fx_name=func_name, on_step=True, on_epoch=on_epoch)
else:
assert func_name in not_supported
with pytest.raises(MisconfigurationException, match="You can't"):
validator.check_logging(fx_name=func_name)
with pytest.raises(RuntimeError, match="Logging inside `foo` is not implemented"):
validator.check_logging("foo")
class HookedCallback(Callback):
def __init__(self, not_supported):
def call(hook, trainer, model=None, *_, **__):
lightning_module = trainer.lightning_module or model
if lightning_module is None:
# `on_init_{start,end}` do not have the `LightningModule` available
assert hook in ("on_init_start", "on_init_end")
return
if hook in not_supported:
with pytest.raises(MisconfigurationException, match=not_supported[hook]):
lightning_module.log("anything", 1)
else:
lightning_module.log(hook, 1)
for h in get_members(Callback):
setattr(self, h, partial(call, h))
class HookedModel(BoringModel):
def __init__(self, not_supported):
super().__init__()
pl_module_hooks = get_members(LightningModule)
pl_module_hooks.difference_update(
{
"log",
"log_dict",
# the following are problematic as they do have `self._current_fx_name` defined some times but
# not others depending on where they were called. So we cannot reliably `self.log` in them
"on_before_batch_transfer",
"transfer_batch_to_device",
"on_after_batch_transfer",
"get_progress_bar_dict",
}
)
# remove `nn.Module` hooks
module_hooks = get_members(torch.nn.Module)
pl_module_hooks.difference_update(module_hooks)
def call(hook, fn, *args, **kwargs):
out = fn(*args, **kwargs)
if hook in not_supported:
with pytest.raises(MisconfigurationException, match=not_supported[hook]):
self.log("anything", 1)
else:
self.log(hook, 1)
return out
for h in pl_module_hooks:
attr = getattr(self, h)
setattr(self, h, partial(call, h, attr))
def test_fx_validator_integration(tmpdir):
"""Tries to log inside all `LightningModule` and `Callback` hooks to check any expected errors."""
not_supported = {
None: "`self.trainer` reference is not registered",
"on_before_accelerator_backend_setup": "You can't",
"setup": "You can't",
"configure_sharded_model": "You can't",
"on_configure_sharded_model": "You can't",
"configure_optimizers": "You can't",
"on_fit_start": "You can't",
"on_pretrain_routine_start": "You can't",
"on_pretrain_routine_end": "You can't",
"on_train_dataloader": "You can't",
"train_dataloader": "You can't",
"on_val_dataloader": "You can't",
"val_dataloader": "You can't",
"on_validation_end": "You can't",
"on_train_end": "You can't",
"on_fit_end": "You can't",
"teardown": "You can't",
"on_sanity_check_start": "You can't",
"on_sanity_check_end": "You can't",
"prepare_data": "You can't",
"configure_callbacks": "You can't",
"on_validation_model_eval": "You can't",
"on_validation_model_train": "You can't",
"lr_scheduler_step": "You can't",
"summarize": "not managed by the `Trainer",
}
model = HookedModel(not_supported)
with pytest.warns(UserWarning, match=not_supported[None]):
model.log("foo", 1)
callback = HookedCallback(not_supported)
trainer = Trainer(
default_root_dir=tmpdir,
max_epochs=2,
limit_train_batches=1,
limit_val_batches=1,
limit_test_batches=1,
limit_predict_batches=1,
callbacks=callback,
)
with pytest.deprecated_call(match="on_train_dataloader` is deprecated in v1.5"):
trainer.fit(model)
not_supported.update(
{
# `lightning_module` ref is now present from the `fit` call
"on_before_accelerator_backend_setup": "You can't",
"on_test_dataloader": "You can't",
"test_dataloader": "You can't",
"on_test_model_eval": "You can't",
"on_test_model_train": "You can't",
"on_test_end": "You can't",
}
)
with pytest.deprecated_call(match="on_test_dataloader` is deprecated in v1.5"):
trainer.test(model, verbose=False)
not_supported.update({k: "result collection is not registered yet" for k in not_supported})
not_supported.update(
{
"on_predict_dataloader": "result collection is not registered yet",
"predict_dataloader": "result collection is not registered yet",
"on_predict_model_eval": "result collection is not registered yet",
"on_predict_start": "result collection is not registered yet",
"on_predict_epoch_start": "result collection is not registered yet",
"on_predict_batch_start": "result collection is not registered yet",
"predict_step": "result collection is not registered yet",
"on_predict_batch_end": "result collection is not registered yet",
"on_predict_epoch_end": "result collection is not registered yet",
"on_predict_end": "result collection is not registered yet",
}
)
with pytest.deprecated_call(match="on_predict_dataloader` is deprecated in v1.5"):
trainer.predict(model)
@RunIf(min_gpus=2)
def test_epoch_results_cache_dp(tmpdir):
root_device = torch.device("cuda", 0)
class TestModel(BoringModel):
def training_step(self, *args, **kwargs):
result = super().training_step(*args, **kwargs)
self.log("train_loss_epoch", result["loss"], on_step=False, on_epoch=True)
return result
def training_step_end(self, training_step_outputs): # required for dp
loss = training_step_outputs["loss"].mean()
return loss
def training_epoch_end(self, outputs):
assert all(out["loss"].device == root_device for out in outputs)
assert self.trainer.callback_metrics["train_loss_epoch"].device == root_device
def validation_step(self, *args, **kwargs):
val_loss = torch.rand(1, device=torch.device("cuda", 1))
self.log("val_loss_epoch", val_loss, on_step=False, on_epoch=True)
return val_loss
def validation_epoch_end(self, outputs):
assert all(loss.device == root_device for loss in outputs)
assert self.trainer.callback_metrics["val_loss_epoch"].device == root_device
def test_step(self, *args, **kwargs):
test_loss = torch.rand(1, device=torch.device("cuda", 1))
self.log("test_loss_epoch", test_loss, on_step=False, on_epoch=True)
return test_loss
def test_epoch_end(self, outputs):
assert all(loss.device == root_device for loss in outputs)
assert self.trainer.callback_metrics["test_loss_epoch"].device == root_device
def train_dataloader(self):
return DataLoader(RandomDataset(32, 64), batch_size=4)
def val_dataloader(self):
return DataLoader(RandomDataset(32, 64), batch_size=4)
def test_dataloader(self):
return DataLoader(RandomDataset(32, 64), batch_size=4)
model = TestModel()
trainer = Trainer(
default_root_dir=tmpdir, strategy="dp", gpus=2, limit_train_batches=2, limit_val_batches=2, max_epochs=1
)
trainer.fit(model)
trainer.test(model)
def test_can_return_tensor_with_more_than_one_element(tmpdir):
"""Ensure {validation,test}_step return values are not included as callback metrics.
#6623
"""
class TestModel(BoringModel):
def validation_step(self, batch, *args, **kwargs):
return {"val": torch.tensor([0, 1])}
def validation_epoch_end(self, outputs):
# ensure validation step returns still appear here
assert len(outputs) == 2
assert all(list(d) == ["val"] for d in outputs) # check keys
assert all(torch.equal(d["val"], torch.tensor([0, 1])) for d in outputs) # check values
def test_step(self, batch, *args, **kwargs):
return {"test": torch.tensor([0, 1])}
def test_epoch_end(self, outputs):
assert len(outputs) == 2
assert all(list(d) == ["test"] for d in outputs) # check keys
assert all(torch.equal(d["test"], torch.tensor([0, 1])) for d in outputs) # check values
model = TestModel()
trainer = Trainer(default_root_dir=tmpdir, fast_dev_run=2, enable_progress_bar=False)
trainer.fit(model)
trainer.validate(model)
trainer.test(model)
def test_logging_to_progress_bar_with_reserved_key(tmpdir):
"""Test that logging a metric with a reserved name to the progress bar raises a warning."""
class TestModel(BoringModel):
def training_step(self, *args, **kwargs):
output = super().training_step(*args, **kwargs)
self.log("loss", output["loss"], prog_bar=True)
return output
model = TestModel()
trainer = Trainer(default_root_dir=tmpdir, fast_dev_run=True)
with pytest.warns(UserWarning, match="The progress bar already tracks a metric with the .* 'loss'"):
trainer.fit(model)
@pytest.mark.parametrize("add_dataloader_idx", [False, True])
def test_auto_add_dataloader_idx(tmpdir, add_dataloader_idx):
"""test that auto_add_dataloader_idx argument works."""
class TestModel(BoringModel):
def val_dataloader(self):
dl = super().val_dataloader()
return [dl, dl]
def validation_step(self, *args, **kwargs):
output = super().validation_step(*args[:-1], **kwargs)
if add_dataloader_idx:
name = "val_loss"
else:
name = f"val_loss_custom_naming_{args[-1]}"
self.log(name, output["x"], add_dataloader_idx=add_dataloader_idx)
return output
model = TestModel()
model.validation_epoch_end = None
trainer = Trainer(default_root_dir=tmpdir, fast_dev_run=2)
trainer.fit(model)
logged = trainer.logged_metrics
# Check that the correct keys exist
if add_dataloader_idx:
assert "val_loss/dataloader_idx_0" in logged
assert "val_loss/dataloader_idx_1" in logged
else:
assert "val_loss_custom_naming_0" in logged
assert "val_loss_custom_naming_1" in logged
def test_metrics_reset(tmpdir):
"""Tests that metrics are reset correctly after the end of the train/val/test epoch."""
class TestModel(LightningModule):
def __init__(self):
super().__init__()
self.layer = torch.nn.Linear(32, 1)
def _create_metrics(self):
acc = Accuracy()
acc.reset = mock.Mock(side_effect=acc.reset)
ap = AveragePrecision(num_classes=1, pos_label=1)
ap.reset = mock.Mock(side_effect=ap.reset)
return acc, ap
def setup(self, stage):
fn = stage
if fn == "fit":
for stage in ("train", "validate"):
acc, ap = self._create_metrics()
self.add_module(f"acc_{fn}_{stage}", acc)
self.add_module(f"ap_{fn}_{stage}", ap)
else:
acc, ap = self._create_metrics()
stage = self.trainer.state.stage
self.add_module(f"acc_{fn}_{stage}", acc)
self.add_module(f"ap_{fn}_{stage}", ap)
def forward(self, x):
return self.layer(x)
def _step(self, batch):
fn, stage = self.trainer.state.fn, self.trainer.state.stage
logits = self(batch)
loss = logits.sum()
self.log(f"loss/{fn}_{stage}", loss)
acc = self._modules[f"acc_{fn}_{stage}"]
ap = self._modules[f"ap_{fn}_{stage}"]
preds = torch.rand(len(batch)) # Fake preds
labels = torch.randint(0, 1, [len(batch)]) # Fake targets
acc(preds, labels)
ap(preds, labels)
# Metric.forward calls reset so reset the mocks here
acc.reset.reset_mock()
ap.reset.reset_mock()
self.log(f"acc/{fn}_{stage}", acc)
self.log(f"ap/{fn}_{stage}", ap)
return loss
def training_step(self, batch, batch_idx, *args, **kwargs):
return self._step(batch)
def validation_step(self, batch, batch_idx, *args, **kwargs):
if self.trainer.sanity_checking:
return
return self._step(batch)
def test_step(self, batch, batch_idx, *args, **kwargs):
return self._step(batch)
def configure_optimizers(self):
optimizer = torch.optim.SGD(self.layer.parameters(), lr=0.1)
lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1)
return [optimizer], [lr_scheduler]
def train_dataloader(self):
return DataLoader(RandomDataset(32, 64))
def val_dataloader(self):
return DataLoader(RandomDataset(32, 64))
def test_dataloader(self):
return DataLoader(RandomDataset(32, 64))
def _assert_called(model, fn, stage):
acc = model._modules[f"acc_{fn}_{stage}"]
ap = model._modules[f"ap_{fn}_{stage}"]
acc.reset.assert_called_once()
ap.reset.assert_called_once()
model = TestModel()
trainer = Trainer(
default_root_dir=tmpdir,
limit_train_batches=2,
limit_val_batches=2,
limit_test_batches=2,
max_epochs=1,
enable_progress_bar=False,
num_sanity_val_steps=2,
enable_checkpointing=False,
)
trainer.fit(model)
_assert_called(model, "fit", "train")
_assert_called(model, "fit", "validate")
trainer.validate(model)
_assert_called(model, "validate", "validate")
trainer.test(model)
_assert_called(model, "test", "test")
def test_result_collection_on_tensor_with_mean_reduction():
result_collection = _ResultCollection(True)
product = [(True, True), (False, True), (True, False), (False, False)]
values = torch.arange(1, 10)
batches = values * values
for i, v in enumerate(values):
for prog_bar in [False, True]:
for logger in [False, True]:
for on_step, on_epoch in product:
name = "loss"
if on_step:
name += "_on_step"
if on_epoch:
name += "_on_epoch"
if prog_bar:
name += "_prog_bar"
if logger:
name += "_logger"
log_kwargs = dict(
fx="training_step",
name=name,
value=v,
on_step=on_step,
on_epoch=on_epoch,
batch_size=batches[i],
prog_bar=prog_bar,
logger=logger,
)
if not on_step and not on_epoch:
with pytest.raises(MisconfigurationException, match="on_step=False, on_epoch=False"):
result_collection.log(**log_kwargs)
else:
result_collection.log(**log_kwargs)
total_value = sum(values * batches)
total_batches = sum(batches)
assert result_collection["training_step.loss_on_step_on_epoch"].value == total_value
assert result_collection["training_step.loss_on_step_on_epoch"].cumulated_batch_size == total_batches
batch_metrics = result_collection.metrics(True)
max_ = max(values)
assert batch_metrics["pbar"] == {
"loss_on_step_on_epoch_prog_bar_step": max_,
"loss_on_step_on_epoch_prog_bar_logger_step": max_,
"loss_on_step_prog_bar": max_,
"loss_on_step_prog_bar_logger": max_,
}
assert batch_metrics["log"] == {
"loss_on_step_on_epoch_logger_step": max_,
"loss_on_step_logger": max_,
"loss_on_step_on_epoch_prog_bar_logger_step": max_,
"loss_on_step_prog_bar_logger": max_,
}
assert batch_metrics["callback"] == {
"loss_on_step": max_,
"loss_on_step_logger": max_,
"loss_on_step_on_epoch": max_,
"loss_on_step_on_epoch_logger": max_,
"loss_on_step_on_epoch_logger_step": max_,
"loss_on_step_on_epoch_prog_bar": max_,
"loss_on_step_on_epoch_prog_bar_logger": max_,
"loss_on_step_on_epoch_prog_bar_logger_step": max_,
"loss_on_step_on_epoch_prog_bar_step": max_,
"loss_on_step_on_epoch_step": max_,
"loss_on_step_prog_bar": max_,
"loss_on_step_prog_bar_logger": max_,
}
epoch_metrics = result_collection.metrics(False)
mean = total_value / total_batches
assert epoch_metrics["pbar"] == {
"loss_on_epoch_prog_bar": mean,
"loss_on_epoch_prog_bar_logger": mean,
"loss_on_step_on_epoch_prog_bar_epoch": mean,
"loss_on_step_on_epoch_prog_bar_logger_epoch": mean,
}
assert epoch_metrics["log"] == {
"loss_on_epoch_logger": mean,
"loss_on_epoch_prog_bar_logger": mean,
"loss_on_step_on_epoch_logger_epoch": mean,
"loss_on_step_on_epoch_prog_bar_logger_epoch": mean,
}
assert epoch_metrics["callback"] == {
"loss_on_epoch": mean,
"loss_on_epoch_logger": mean,
"loss_on_epoch_prog_bar": mean,
"loss_on_epoch_prog_bar_logger": mean,
"loss_on_step_on_epoch": mean,
"loss_on_step_on_epoch_epoch": mean,
"loss_on_step_on_epoch_logger": mean,
"loss_on_step_on_epoch_logger_epoch": mean,
"loss_on_step_on_epoch_prog_bar": mean,
"loss_on_step_on_epoch_prog_bar_epoch": mean,
"loss_on_step_on_epoch_prog_bar_logger": mean,
"loss_on_step_on_epoch_prog_bar_logger_epoch": mean,
}
def test_logged_metrics_has_logged_epoch_value(tmpdir):
class TestModel(BoringModel):
def training_step(self, batch, batch_idx):
self.log("epoch", -batch_idx, logger=True)
return super().training_step(batch, batch_idx)
model = TestModel()
trainer = Trainer(default_root_dir=tmpdir, fast_dev_run=2)
trainer.fit(model)
# should not get overridden if logged manually
assert trainer.logged_metrics == {"epoch": -1}
def test_result_collection_batch_size_extraction():
fx_name = "training_step"
log_val = torch.tensor(7.0)
results = _ResultCollection(training=True, device="cpu")
results.batch = torch.randn(1, 4)
train_mse = MeanSquaredError()
train_mse(torch.randn(4, 5), torch.randn(4, 5))
results.log(fx_name, "train_logs", {"mse": train_mse, "log_val": log_val}, on_step=False, on_epoch=True)
assert results.batch_size == 1
assert isinstance(results["training_step.train_logs"]["mse"].value, MeanSquaredError)
assert results["training_step.train_logs"]["log_val"].value == log_val
results = _ResultCollection(training=True, device="cpu")
results.batch = torch.randn(1, 4)
results.log(fx_name, "train_log", log_val, on_step=False, on_epoch=True)
assert results.batch_size == 1
assert results["training_step.train_log"].value == log_val
assert results["training_step.train_log"].cumulated_batch_size == 1
def test_result_collection_no_batch_size_extraction():
results = _ResultCollection(training=True, device="cpu")
results.batch = torch.randn(1, 4)
fx_name = "training_step"
batch_size = 10
log_val = torch.tensor(7.0)
train_mae = MeanAbsoluteError()
train_mae(torch.randn(4, 5), torch.randn(4, 5))
train_mse = MeanSquaredError()
train_mse(torch.randn(4, 5), torch.randn(4, 5))
results.log(fx_name, "step_log_val", log_val, on_step=True, on_epoch=False)
results.log(fx_name, "epoch_log_val", log_val, on_step=False, on_epoch=True, batch_size=batch_size)
results.log(fx_name, "epoch_sum_log_val", log_val, on_step=True, on_epoch=True, reduce_fx="sum")
results.log(fx_name, "train_mae", train_mae, on_step=True, on_epoch=False)
results.log(fx_name, "train_mse", {"mse": train_mse}, on_step=True, on_epoch=False)
assert results.batch_size is None
assert isinstance(results["training_step.train_mse"]["mse"].value, MeanSquaredError)
assert isinstance(results["training_step.train_mae"].value, MeanAbsoluteError)
assert results["training_step.step_log_val"].value == log_val
assert results["training_step.step_log_val"].cumulated_batch_size == 0
assert results["training_step.epoch_log_val"].value == log_val * batch_size
assert results["training_step.epoch_log_val"].cumulated_batch_size == batch_size
assert results["training_step.epoch_sum_log_val"].value == log_val