|
| 1 | +# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import paddle.fluid as fluid |
| 16 | +import unittest |
| 17 | + |
| 18 | + |
| 19 | +class TestCheckpoint(unittest.TestCase): |
| 20 | + def setUp(self): |
| 21 | + self.dirname = "/tmp/ckpt" |
| 22 | + self.max_num_checkpoints = 3 |
| 23 | + self.epoch_interval = 1 |
| 24 | + self.step_interval = 1 |
| 25 | + self.trainer_id = 0 |
| 26 | + self.chief = self.trainer_id == 0 |
| 27 | + self.place = fluid.CPUPlace() |
| 28 | + self.epoch_id = 100 |
| 29 | + self.step_id = 20 |
| 30 | + |
| 31 | + def test_checkpoint(self): |
| 32 | + self.save_checkpoint() |
| 33 | + serial = fluid.io.get_latest_checkpoint_serial(self.dirname) |
| 34 | + self.assertTrue(serial >= 0) |
| 35 | + trainer_args = ["epoch_id", "step_id"] |
| 36 | + epoch_id, step_id = fluid.io.load_trainer_args( |
| 37 | + self.dirname, serial, self.trainer_id, trainer_args) |
| 38 | + self.assertEqual(self.step_id, step_id) |
| 39 | + self.assertEqual(self.epoch_id, epoch_id) |
| 40 | + |
| 41 | + program = fluid.Program() |
| 42 | + with fluid.program_guard(program): |
| 43 | + exe = fluid.Executor(self.place) |
| 44 | + fluid.io.load_checkpoint(exe, self.dirname, serial, program) |
| 45 | + |
| 46 | + fluid.io.clean_checkpoint(self.dirname, delete_dir=True) |
| 47 | + |
| 48 | + def save_checkpoint(self): |
| 49 | + config = fluid.CheckpointConfig(self.dirname, self.max_num_checkpoints, |
| 50 | + self.epoch_interval, self.step_interval) |
| 51 | + |
| 52 | + trainer_args = {} |
| 53 | + trainer_args["epoch_id"] = self.epoch_id |
| 54 | + trainer_args["step_id"] = self.step_id |
| 55 | + |
| 56 | + program = fluid.Program() |
| 57 | + with fluid.program_guard(program): |
| 58 | + program.global_block().create_var( |
| 59 | + name="scale_0", |
| 60 | + psersistable=True, |
| 61 | + dtype="float32", |
| 62 | + shape=[32, 32]) |
| 63 | + |
| 64 | + exe = fluid.Executor(self.place) |
| 65 | + for i in xrange(10): |
| 66 | + fluid.io.save_checkpoint( |
| 67 | + exe, config.checkpoint_dir, self.trainer_id, self.chief, |
| 68 | + trainer_args, program, config.max_num_checkpoints) |
| 69 | + |
| 70 | + |
| 71 | +if __name__ == '__main__': |
| 72 | + unittest.main() |
0 commit comments