test_directory_migration.py 8.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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.

import os
import sys
17
import tempfile
18 19
import subprocess
import unittest
20

21 22

class TestDirectory(unittest.TestCase):
23 24 25 26 27 28
    def setUp(self):
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()

29 30
    def get_import_command(self, module):
        paths = module.split('.')
P
pangyoki 已提交
31 32
        if len(paths) == 1:
            return 'import {}'.format(module)
33 34 35 36 37 38 39
        package = '.'.join(paths[:-1])
        func = paths[-1]
        cmd = 'from {} import {}'.format(package, func)
        return cmd

    def test_new_directory(self):
        new_directory = [
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
            'paddle.enable_static',
            'paddle.disable_static',
            'paddle.in_dynamic_mode',
            'paddle.to_tensor',
            'paddle.grad',
            'paddle.no_grad',
            'paddle.static.save',
            'paddle.static.load',
            'paddle.distributed.ParallelEnv',
            'paddle.DataParallel',
            'paddle.jit',
            'paddle.jit.TracedLayer',
            'paddle.jit.to_static',
            'paddle.jit.ProgramTranslator',
            'paddle.jit.TranslatedLayer',
            'paddle.jit.save',
            'paddle.jit.load',
            'paddle.optimizer.lr.LRScheduler',
            'paddle.optimizer.lr.NoamDecay',
59 60 61 62 63 64 65
            'paddle.optimizer.lr.PiecewiseDecay',
            'paddle.optimizer.lr.NaturalExpDecay',
            'paddle.optimizer.lr.ExponentialDecay',
            'paddle.optimizer.lr.InverseTimeDecay',
            'paddle.optimizer.lr.PolynomialDecay',
            'paddle.optimizer.lr.CosineAnnealingDecay',
            'paddle.optimizer.lr.MultiStepDecay',
66 67
            'paddle.optimizer.lr.StepDecay',
            'paddle.optimizer.lr.LambdaDecay',
68
            'paddle.optimizer.lr.ReduceOnPlateau',
69 70 71 72 73 74 75 76
            'paddle.optimizer.lr.LinearWarmup',
            'paddle.static.Executor',
            'paddle.static.global_scope',
            'paddle.static.scope_guard',
            'paddle.static.append_backward',
            'paddle.static.gradients',
            'paddle.static.BuildStrategy',
            'paddle.static.CompiledProgram',
77
            'paddle.static.ExecutionStrategy',
78
            'paddle.static.default_main_program',
79 80 81 82 83 84
            'paddle.static.default_startup_program',
            'paddle.static.Program',
            'paddle.static.name_scope',
            'paddle.static.program_guard',
            'paddle.static.Print',
            'paddle.static.py_func',
85
            'paddle.static.ParallelExecutor',
86 87
            'paddle.static.WeightNormParamAttr',
            'paddle.static.nn.fc',
88 89
            'paddle.static.nn.batch_norm',
            'paddle.static.nn.bilinear_tensor_product',
90 91 92 93
            'paddle.static.nn.conv2d',
            'paddle.static.nn.conv2d_transpose',
            'paddle.static.nn.conv3d',
            'paddle.static.nn.conv3d_transpose',
94
            'paddle.static.nn.create_parameter',
95 96 97 98 99 100 101 102 103 104 105 106
            'paddle.static.nn.crf_decoding',
            'paddle.static.nn.data_norm',
            'paddle.static.nn.deform_conv2d',
            'paddle.static.nn.group_norm',
            'paddle.static.nn.instance_norm',
            'paddle.static.nn.layer_norm',
            'paddle.static.nn.multi_box_head',
            'paddle.static.nn.nce',
            'paddle.static.nn.prelu',
            'paddle.static.nn.row_conv',
            'paddle.static.nn.spectral_norm',
            'paddle.static.nn.embedding',
107 108
        ]

109
        import_file = os.path.join(self.temp_dir.name, 'run_import_modules.py')
110 111 112 113 114 115 116 117 118

        with open(import_file, "w") as wb:
            for module in new_directory:
                run_cmd = self.get_import_command(module)
                wb.write("{}\n".format(run_cmd))

        _python = sys.executable

        ps_cmd = "{} {}".format(_python, import_file)
119 120 121 122 123
        ps_proc = subprocess.Popen(
            ps_cmd.strip().split(" "),
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
124 125
        stdout, stderr = ps_proc.communicate()

126 127 128 129
        self.assertFalse(
            "Error" in str(stderr),
            "ErrorMessage:\n{}".format(bytes.decode(stderr)),
        )
130 131 132

    def test_old_directory(self):
        old_directory = [
133 134 135 136 137 138 139 140 141 142
            'paddle.enable_imperative',
            'paddle.disable_imperative',
            'paddle.in_imperative_mode',
            'paddle.imperative.to_variable',
            'paddle.imperative.enable',
            'paddle.imperative.guard',
            'paddle.imperative.grad',
            'paddle.imperative.no_grad',
            'paddle.imperative.save',
            'paddle.imperative.load',
143 144
            'paddle.imperative.ParallelEnv',
            'paddle.imperative.prepare_context',
145 146 147 148
            'paddle.imperative.DataParalell',
            'paddle.imperative.jit',
            'paddle.imperative.TracedLayer',
            'paddle.imperative.declarative',
149
            'paddle.imperative.ProgramTranslator',
150 151 152 153
            'paddle.imperative.TranslatedLayer',
            'paddle.imperative.jit.save',
            'paddle.imperative.jit.load',
            'paddle.imperative.NoamDecay' 'paddle.imperative.PiecewiseDecay',
154 155 156 157
            'paddle.imperative.NaturalExpDecay',
            'paddle.imperative.ExponentialDecay',
            'paddle.imperative.InverseTimeDecay',
            'paddle.imperative.PolynomialDecay',
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
            'paddle.imperative.CosineDecay',
            'paddle.Executor',
            'paddle.global_scope',
            'paddle.scope_guard',
            'paddle.append_backward',
            'paddle.gradients',
            'paddle.BuildStrategy',
            'paddle.CompiledProgram',
            'paddle.ExecutionStrategy',
            'paddle.name_scope',
            'paddle.program_guard',
            'paddle.Print',
            'paddle.py_func',
            'paddle.ParallelExecutor',
            'paddle.default_main_program',
            'paddle.default_startup_program',
            'paddle.Program',
            'paddle.WeightNormParamAttr',
            'paddle.declarative.fc',
177 178
            'paddle.declarative.batch_norm',
            'paddle.declarative.bilinear_tensor_product',
179 180 181 182
            'paddle.declarative.conv2d',
            'paddle.declarative.conv2d_transpose',
            'paddle.declarative.conv3d',
            'paddle.declarative.conv3d_transpose',
183
            'paddle.declarative.create_parameter',
184 185
            'paddle.declarative.crf_decoding',
            'paddle.declarative.data_norm',
186
            'paddle.declarative.deformable_conv',
187 188 189 190 191 192 193 194 195 196
            'paddle.declarative.group_norm',
            'paddle.declarative.hsigmoid',
            'paddle.declarative.instance_norm',
            'paddle.declarative.layer_norm',
            'paddle.declarative.multi_box_head',
            'paddle.declarative.nce',
            'paddle.declarative.prelu',
            'paddle.declarative.row_conv',
            'paddle.declarative.spectral_norm',
            'paddle.declarative.embedding',
197 198
        ]

199 200 201
        import_file = os.path.join(
            self.temp_dir.name, 'run_old_import_modules.py'
        )
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219

        with open(import_file, "w") as wb:
            cmd_context_count = """
count = 0
err_module = ""
"""
            wb.write(cmd_context_count)
            for module in old_directory:
                run_cmd = self.get_import_command(module)
                cmd_context_loop_template = """
try:
    {run_cmd}
except:
    count += 1
else:
    err_module = "{module}"
"""
                cmd_context_loop = cmd_context_loop_template.format(
220 221
                    run_cmd=run_cmd, module=module
                )
222 223 224 225 226 227
                wb.write(cmd_context_loop)
            cmd_context_print_template = """
if count != {len_old_directory}:
    print("Error: Module " + err_module + " should not be imported")
"""
            cmd_context_print = cmd_context_print_template.format(
228 229
                len_old_directory=str(len(old_directory))
            )
230 231 232 233 234
            wb.write(cmd_context_print)

        _python = sys.executable

        ps_cmd = "{} {}".format(_python, import_file)
235 236 237 238 239
        ps_proc = subprocess.Popen(
            ps_cmd.strip().split(" "),
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
240 241
        stdout, stderr = ps_proc.communicate()

P
pangyoki 已提交
242
        self.assertFalse("Error" in str(stdout), bytes.decode(stdout))
243 244 245 246


if __name__ == '__main__':
    unittest.main()