create_programs.py 4.7 KB
Newer Older
R
eol  
rensilin 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#!/usr/bin/env python
#-*- coding:utf-8 -*-

from __future__ import print_function, division
import os
import sys
import paddle
from paddle import fluid
import yaml

def print_help(this_name):
    """Print help
    """
    dirname = os.path.dirname(this_name)
R
rensilin 已提交
15 16
    print('Usage: {} <network building filename> [model_dir]\n'.format(this_name))
    print('    example: {} {}'.format(this_name, os.path.join(dirname, 'example.py')))
R
eol  
rensilin 已提交
17

R
rensilin 已提交
18 19 20 21
class ModelBuilder:
    """
    Attributes:
        _save_path: Save path of programs
R
fix  
rensilin 已提交
22 23 24 25 26 27 28 29 30 31 32

        def _inference():
            Build inference network(without loss and optimizer)
            **This function is declared in the network_desc_path file, and will be set in initialize()**

            Returns:
                list<Variable>: inputs
                and
                list<Variable>: outputs
            pass

R
rensilin 已提交
33
        def _loss_function(*outputs):
R
fix  
rensilin 已提交
34 35
            **This function is declared in the network_desc_path file, and will be set in initialize()**
            Args:
R
rensilin 已提交
36
                *outputs: the second result of inference()
R
fix  
rensilin 已提交
37 38 39 40 41 42

            Returns:
                Variable: loss
                and
                list<Variable>: labels
            pass
R
rensilin 已提交
43
    """
R
rensilin 已提交
44

R
rensilin 已提交
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
    def initialize(self, network_desc_path, save_path=None):
        """compile the network description module
        Args:
            network_desc_path: path
            save_path: model save path, default is ./model/<network_desc_path without .py>/

        Returns:
            bool: True if succeed else False
        """
        if not isinstance(network_desc_path, str):
            print('network_desc_path must be str')
            return False

        if not network_desc_path.endswith('.py'):
            print('network_desc_path must be end with .py')
            return False

        if not os.path.exists(network_desc_path):
            print('file not exists:', network_desc_path)
            return False

        scope = dict()
        with open(network_desc_path, 'r') as f:
            code = f.read()
            compiled = compile(code, network_desc_path, 'exec')
            exec(compiled, scope)

        if not 'inference' in scope:
            print('inference not defined')
            return False

        if not 'loss_function' in scope:
            print('loss_function not defined')
            return False

        if save_path is None:
            # example /a/b/c.d -> ./model/c
            save_path = os.path.join('./model', os.path.splitext(os.path.split(network_desc_path)[1])[0])
            print('save in the default path:', save_path)

        self._save_path = save_path

        self._inference = scope['inference']
        self._loss_function = scope['loss_function']

        return True

    def build_and_save(self):
        """Build programs and save to _save_path
        """
        main_program = fluid.Program()
        startup_program = fluid.Program()
        with fluid.program_guard(main_program, startup_program):
            inputs, outputs = self._inference()
            test_program = main_program.clone(for_test=True)
R
rensilin 已提交
100
            loss, labels = self._loss_function(*outputs)
R
rensilin 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

            optimizer = fluid.optimizer.SGD(learning_rate=1.0)
            params_grads = optimizer.backward(loss)

        if not os.path.exists(self._save_path):
            os.makedirs(self._save_path)

        programs = {
            'startup_program': startup_program,
            'main_program': main_program,
            'test_program': test_program,
        }
        for name, program in programs.items():
            with open(os.path.join(self._save_path, name), 'w') as f:
                f.write(program.desc.serialize_to_string())

        model_desc_path = os.path.join(self._save_path, 'model.yaml')
        model_desc = {
            'inputs': [{"name": var.name, "shape": var.shape} for var in inputs],
            'outputs': [{"name": var.name, "shape": var.shape} for var in outputs],
            'labels': [{"name": var.name, "shape": var.shape} for var in labels],
R
rensilin 已提交
122
            'vars': [{"name": var.name, "shape": var.shape} for var in main_program.list_vars() if fluid.io.is_parameter(var)],
R
rensilin 已提交
123 124 125 126
            'loss': loss.name,
        }

        with open(model_desc_path, 'w') as f:
R
rensilin 已提交
127
            yaml.safe_dump(model_desc, f, encoding='utf-8', allow_unicode=True, default_flow_style=None)
R
rensilin 已提交
128

R
eol  
rensilin 已提交
129 130 131 132 133 134

def main(argv):
    """Create programs
    Args:
        argv: arg list, length should be 2
    """
R
rensilin 已提交
135
    if len(argv) < 2:
R
eol  
rensilin 已提交
136 137
        print_help(argv[0])
        exit(1)
R
rensilin 已提交
138
    network_desc_path = argv[1]
R
eol  
rensilin 已提交
139

R
rensilin 已提交
140
    if len(argv) > 2:
R
rensilin 已提交
141
        save_path = argv[2]
R
eol  
rensilin 已提交
142
    else:
R
rensilin 已提交
143
        save_path = None
R
eol  
rensilin 已提交
144

R
rensilin 已提交
145 146 147 148 149
    builder = ModelBuilder()
    if not builder.initialize(network_desc_path, save_path):
        print_help(argv[0])
        exit(1)
    builder.build_and_save()
R
eol  
rensilin 已提交
150 151 152

if __name__ == "__main__":
    main(sys.argv)