@@ -48,6 +48,33 @@ def test_module_is_mean_absolute_error(self):
4848 value = metric_wrapper .compute ()
4949 torch .testing .assert_close (value , torch .tensor (0.11 ))
5050
51+ def test_state_restore_and_reset (self ):
52+ metric_wrapper = TrainMetricWrapper (
53+ torchmetrics .MeanAbsoluteError (), decay_rate = 0.9 , decay_step = 1
54+ )
55+ preds = torch .tensor ([0.1 , 0.2 ])
56+ metric_wrapper .update (preds , torch .tensor ([0.6 , 0.7 ]))
57+ torch .testing .assert_close (metric_wrapper .compute (), torch .tensor (0.5 ))
58+ self .assertEqual (
59+ list (metric_wrapper .state_dict ().keys ()), ["_value" , "_step_cnt" ]
60+ )
61+ self .assertEqual (list (metric_wrapper .parameters ()), [])
62+
63+ # continue train restores the running metric of the interrupted job.
64+ restored = TrainMetricWrapper (
65+ torchmetrics .MeanAbsoluteError (), decay_rate = 0.9 , decay_step = 1
66+ )
67+ restored .load_state_dict (metric_wrapper .state_dict ())
68+ torch .testing .assert_close (restored .compute (), torch .tensor (0.5 ))
69+ restored .update (preds , torch .tensor ([0.2 , 0.3 ]))
70+ torch .testing .assert_close (restored .compute (), torch .tensor (0.46 ))
71+
72+ # fine tune resets it, so the next value is not blended with the old one.
73+ restored .reset ()
74+ torch .testing .assert_close (restored .compute (), torch .tensor (0.0 ))
75+ restored .update (preds , torch .tensor ([0.2 , 0.3 ]))
76+ torch .testing .assert_close (restored .compute (), torch .tensor (0.1 ))
77+
5178
5279if __name__ == "__main__" :
5380 unittest .main ()
0 commit comments