|
| 1 | +# Copyright (c) 2020 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 os |
| 16 | +import pickle |
| 17 | +import tempfile |
| 18 | +import unittest |
| 19 | +from io import BytesIO |
| 20 | + |
| 21 | +import numpy as np |
| 22 | +from test_imperative_base import new_program_scope |
| 23 | + |
| 24 | +import paddle |
| 25 | +from paddle import base, nn |
| 26 | +from paddle.jit.api import to_static |
| 27 | +from paddle.jit.translated_layer import INFER_PARAMS_INFO_SUFFIX |
| 28 | +from paddle.nn import Linear |
| 29 | +from paddle.static import InputSpec |
| 30 | + |
| 31 | +IMAGE_SIZE = 784 |
| 32 | +CLASS_NUM = 10 |
| 33 | + |
| 34 | +SEED = 10 |
| 35 | + |
| 36 | + |
| 37 | +class LinearNet(nn.Layer): |
| 38 | + def __init__(self): |
| 39 | + super().__init__() |
| 40 | + self._linear = nn.Linear(IMAGE_SIZE, CLASS_NUM) |
| 41 | + |
| 42 | + def forward(self, x): |
| 43 | + return self._linear(x) |
| 44 | + |
| 45 | + |
| 46 | +class LinearNetReturnHidden(paddle.nn.Layer): |
| 47 | + def __init__(self, in_size, out_size): |
| 48 | + super().__init__() |
| 49 | + self._linear_1 = Linear(in_size, out_size) |
| 50 | + self._linear_2 = Linear(in_size, out_size) |
| 51 | + |
| 52 | + @to_static |
| 53 | + def forward(self, x): |
| 54 | + y = self._linear_1(x) |
| 55 | + z = self._linear_2(y) |
| 56 | + loss = paddle.mean(z) |
| 57 | + return y, loss |
| 58 | + |
| 59 | + |
| 60 | +class TestSaveLoadProgram(unittest.TestCase): |
| 61 | + def test_save_load_program(self): |
| 62 | + paddle.enable_static() |
| 63 | + temp_dir = tempfile.TemporaryDirectory() |
| 64 | + |
| 65 | + with new_program_scope(): |
| 66 | + layer = LinearNet() |
| 67 | + data = paddle.static.data( |
| 68 | + name='x_static_save', shape=(None, IMAGE_SIZE), dtype='float32' |
| 69 | + ) |
| 70 | + y_static = layer(data) |
| 71 | + main_program = paddle.static.default_main_program() |
| 72 | + startup_program = paddle.static.default_startup_program() |
| 73 | + origin_main = main_program.desc.serialize_to_string() |
| 74 | + origin_startup = startup_program.desc.serialize_to_string() |
| 75 | + path1 = os.path.join( |
| 76 | + temp_dir.name, |
| 77 | + "test_paddle_save_load_program/main_program.pdmodel", |
| 78 | + ) |
| 79 | + path2 = os.path.join( |
| 80 | + temp_dir.name, |
| 81 | + "test_paddle_save_load_program/startup_program.pdmodel", |
| 82 | + ) |
| 83 | + paddle.save(main_program, path1) |
| 84 | + paddle.save(startup_program, path2) |
| 85 | + |
| 86 | + with new_program_scope(): |
| 87 | + load_main = paddle.load(path1).desc.serialize_to_string() |
| 88 | + load_startup = paddle.load(path2).desc.serialize_to_string() |
| 89 | + self.assertTrue(origin_main == load_main) |
| 90 | + self.assertTrue(origin_startup == load_startup) |
| 91 | + temp_dir.cleanup() |
| 92 | + |
| 93 | + |
| 94 | +class TestJitPruneModelAndLoad(unittest.TestCase): |
| 95 | + def setUp(self): |
| 96 | + self.linear_size = 4 |
| 97 | + self.temp_dir = tempfile.TemporaryDirectory() |
| 98 | + self.model_path = os.path.join( |
| 99 | + self.temp_dir.name, "jit_prune_model_and_load/model" |
| 100 | + ) |
| 101 | + # enable dygraph mode |
| 102 | + base.enable_dygraph() |
| 103 | + # config seed |
| 104 | + paddle.seed(SEED) |
| 105 | + paddle.framework.random._manual_program_seed(SEED) |
| 106 | + |
| 107 | + def tearDown(self): |
| 108 | + self.temp_dir.cleanup() |
| 109 | + |
| 110 | + def train_and_save(self): |
| 111 | + train_layer = LinearNetReturnHidden(8, 8) |
| 112 | + train_layer = to_static( |
| 113 | + train_layer, |
| 114 | + input_spec=[InputSpec([None, 8], name='x')], |
| 115 | + full_graph=True, |
| 116 | + ) |
| 117 | + adam = paddle.optimizer.Adam( |
| 118 | + learning_rate=0.1, parameters=train_layer.parameters() |
| 119 | + ) |
| 120 | + x = paddle.to_tensor(np.random.random((4, 8)).astype('float32')) |
| 121 | + for i in range(10): |
| 122 | + hidden, loss = train_layer(x) |
| 123 | + loss.backward() |
| 124 | + adam.minimize(loss) |
| 125 | + train_layer.clear_gradients() |
| 126 | + |
| 127 | + output_spec = train_layer.forward.outputs[:1] |
| 128 | + paddle.jit.save( |
| 129 | + layer=train_layer, |
| 130 | + path=self.model_path, |
| 131 | + input_spec=[x], |
| 132 | + output_spec=output_spec, |
| 133 | + ) |
| 134 | + |
| 135 | + return train_layer |
| 136 | + |
| 137 | + # pir has no need to save extra var info, param always saved with program, |
| 138 | + # and trainable info saved in program's op attr |
| 139 | + def test_load_var_not_in_extra_var_info(self): |
| 140 | + self.train_and_save() |
| 141 | + |
| 142 | + # chage extra var info |
| 143 | + var_info_path = self.model_path + INFER_PARAMS_INFO_SUFFIX |
| 144 | + with open(var_info_path, 'rb') as f: |
| 145 | + extra_var_info = pickle.load(f) |
| 146 | + extra_var_info.clear() |
| 147 | + with open(var_info_path, 'wb') as f: |
| 148 | + pickle.dump(extra_var_info, f, protocol=2) |
| 149 | + |
| 150 | + with self.assertRaises(RuntimeError): |
| 151 | + paddle.jit.load(self.model_path) |
| 152 | + |
| 153 | + |
| 154 | +class TestSaveLoadToMemory(unittest.TestCase): |
| 155 | + def test_static_save_to_memory(self): |
| 156 | + paddle.enable_static() |
| 157 | + with new_program_scope(): |
| 158 | + # create network |
| 159 | + x = paddle.static.data( |
| 160 | + name="x", shape=[None, IMAGE_SIZE], dtype='float32' |
| 161 | + ) |
| 162 | + z = paddle.static.nn.fc(x, 10, bias_attr=False) |
| 163 | + z = paddle.static.nn.fc(z, 128, bias_attr=False) |
| 164 | + loss = paddle.mean(z) |
| 165 | + place = ( |
| 166 | + base.CPUPlace() |
| 167 | + if not paddle.base.core.is_compiled_with_cuda() |
| 168 | + else base.CUDAPlace(0) |
| 169 | + ) |
| 170 | + prog = paddle.static.default_main_program() |
| 171 | + exe = paddle.static.Executor(place) |
| 172 | + exe.run(paddle.static.default_startup_program()) |
| 173 | + |
| 174 | + state_dict = prog.state_dict() |
| 175 | + keys = list(state_dict.keys()) |
| 176 | + tensor = state_dict[keys[0]] |
| 177 | + |
| 178 | + byio = BytesIO() |
| 179 | + byio2 = BytesIO() |
| 180 | + paddle.save(prog, byio2) |
| 181 | + paddle.save(tensor, byio) |
| 182 | + paddle.save(state_dict, byio) |
| 183 | + byio.seek(0) |
| 184 | + byio2.seek(0) |
| 185 | + |
| 186 | + prog_load = paddle.load(byio2) |
| 187 | + self.assertTrue( |
| 188 | + prog.desc.serialize_to_string() |
| 189 | + == prog_load.desc.serialize_to_string() |
| 190 | + ) |
| 191 | + |
| 192 | + tensor_load = paddle.load(byio, return_numpy=True) |
| 193 | + np.testing.assert_array_equal(tensor_load, np.array(tensor)) |
| 194 | + |
| 195 | + state_dict_load = paddle.load(byio, return_numpy=True) |
| 196 | + for k, v in state_dict.items(): |
| 197 | + np.testing.assert_array_equal(np.array(v), state_dict_load[k]) |
| 198 | + |
| 199 | + |
| 200 | +if __name__ == '__main__': |
| 201 | + unittest.main() |
0 commit comments