exporter.py 6.7 KB
Newer Older
C
chenxuyi 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#   Copyright (c) 2019 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.
C
chenxuyi 已提交
14 15 16
"""
exporters
"""
C
chenxuyi 已提交
17 18 19 20 21 22 23 24
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals

import sys
import os
import itertools
import six
C
chenxuyi 已提交
25
import inspect
C
chenxuyi 已提交
26 27 28 29 30 31 32
import abc
import logging

import numpy as np
import paddle.fluid as F
import paddle.fluid.layers as L

M
Meiyim 已提交
33
from propeller.util import map_structure
C
chenxuyi 已提交
34 35
from propeller.paddle.train import Saver
from propeller.types import InferenceSpec
C
chenxuyi 已提交
36 37 38 39 40
from propeller.train.model import Model
from propeller.paddle.train.trainer import _build_net
from propeller.paddle.train.trainer import _build_model_fn
from propeller.types import RunMode
from propeller.types import ProgramPair
C
chenxuyi 已提交
41 42 43 44 45

log = logging.getLogger(__name__)


@six.add_metaclass(abc.ABCMeta)
C
chenxuyi 已提交
46 47 48
class Exporter(object):
    """base exporter"""

C
chenxuyi 已提交
49 50
    @abc.abstractmethod
    def export(self, exe, program, eval_result, state):
C
chenxuyi 已提交
51
        """export"""
C
chenxuyi 已提交
52 53 54 55
        raise NotImplementedError()


class BestExporter(Exporter):
C
chenxuyi 已提交
56 57
    """export saved model accordingto `cmp_fn`"""

C
chenxuyi 已提交
58
    def __init__(self, export_dir, cmp_fn):
C
chenxuyi 已提交
59
        """doc"""
C
chenxuyi 已提交
60 61 62 63 64
        self._export_dir = export_dir
        self._best = None
        self.cmp_fn = cmp_fn

    def export(self, exe, program, eval_model_spec, eval_result, state):
C
chenxuyi 已提交
65
        """doc"""
C
chenxuyi 已提交
66 67
        log.debug('New evaluate result: %s \nold: %s' %
                  (repr(eval_result), repr(self._best)))
M
Meiyim 已提交
68 69 70
        if self._best is None and state['best_model'] is not None:
            self._best = state['best_model']
            log.debug('restoring best state %s' % repr(self._best))
C
chenxuyi 已提交
71 72 73 74 75 76
        if self._best is None or self.cmp_fn(old=self._best, new=eval_result):
            log.debug('[Best Exporter]: export to %s' % self._export_dir)
            eval_program = program.train_program
            # FIXME: all eval datasets has same name/types/shapes now!!! so every eval program are the smae

            saver = Saver(
M
Meiyim 已提交
77
                self._export_dir, exe, program=program, max_ckpt_to_keep=1)
C
chenxuyi 已提交
78
            saver.save(state)
M
Meiyim 已提交
79
            eval_result = map_structure(float, eval_result)
C
chenxuyi 已提交
80
            self._best = eval_result
M
Meiyim 已提交
81
            state['best_model'] = eval_result
C
chenxuyi 已提交
82 83 84 85 86
        else:
            log.debug('[Best Exporter]: skip step %s' % state.gstep)


class BestInferenceModelExporter(Exporter):
C
chenxuyi 已提交
87 88 89 90 91 92 93 94 95
    """export inference model accordingto `cmp_fn`"""

    def __init__(self,
                 export_dir,
                 cmp_fn,
                 model_class_or_model_fn=None,
                 hparams=None,
                 dataset=None):
        """doc"""
C
chenxuyi 已提交
96 97 98
        self._export_dir = export_dir
        self._best = None
        self.cmp_fn = cmp_fn
C
chenxuyi 已提交
99 100 101
        self.model_class_or_model_fn = model_class_or_model_fn
        self.hparams = hparams
        self.dataset = dataset
C
chenxuyi 已提交
102 103

    def export(self, exe, program, eval_model_spec, eval_result, state):
C
chenxuyi 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
        """doc"""
        if self.model_class_or_model_fn is not None and self.hparams is not None \
                and self.dataset is not None:
            log.info('Building program by user defined model function')
            if issubclass(self.model_class_or_model_fn, Model):
                _model_fn = _build_model_fn(self.model_class_or_model_fn)
            elif inspect.isfunction(self.model_class_or_model_fn):
                _model_fn = self.model_class_or_model_fn
            else:
                raise ValueError('unknown model %s' %
                                 self.model_class_or_model_fn)

            # build net
            infer_program = F.Program()
            startup_prog = F.Program()
            with F.program_guard(infer_program, startup_prog):
                #share var with Train net
                with F.unique_name.guard():
                    log.info('Building Infer Graph')
                    infer_fea = self.dataset.features()
                    # run_config is None
                    self.model_spec = _build_net(_model_fn, infer_fea,
                                                 RunMode.PREDICT, self.hparams,
                                                 None)
                    log.info('Done')
            infer_program = infer_program.clone(for_test=True)
            self.program = ProgramPair(
                train_program=infer_program, startup_program=startup_prog)

        else:
            self.program = program
            self.model_spec = eval_model_spec
M
Meiyim 已提交
136 137 138
        if self._best is None and state['best_inf_model'] is not None:
            self._best = state['best_inf_model']
            log.debug('restoring best state %s' % repr(self._best))
C
chenxuyi 已提交
139 140
        log.debug('New evaluate result: %s \nold: %s' %
                  (repr(eval_result), repr(self._best)))
M
Meiyim 已提交
141

C
chenxuyi 已提交
142 143
        if self._best is None or self.cmp_fn(old=self._best, new=eval_result):
            log.debug('[Best Exporter]: export to %s' % self._export_dir)
C
chenxuyi 已提交
144
            if self.model_spec.inference_spec is None:
C
chenxuyi 已提交
145 146
                raise ValueError('model_fn didnt return InferenceSpec')

C
chenxuyi 已提交
147 148 149 150 151 152 153
            inf_spec_dict = self.model_spec.inference_spec
            if not isinstance(inf_spec_dict, dict):
                inf_spec_dict = {'inference': inf_spec_dict}
            for inf_spec_name, inf_spec in six.iteritems(inf_spec_dict):
                if not isinstance(inf_spec, InferenceSpec):
                    raise ValueError('unknow inference spec type: %s' %
                                     inf_spec)
C
chenxuyi 已提交
154

C
chenxuyi 已提交
155
                save_dir = os.path.join(self._export_dir, inf_spec_name)
C
chenxuyi 已提交
156
                log.debug('[Best Exporter]: save inference model: "%s" to %s' %
C
chenxuyi 已提交
157 158 159
                          (inf_spec_name, save_dir))
                feed_var = [i.name for i in inf_spec.inputs]
                fetch_var = inf_spec.outputs
C
chenxuyi 已提交
160

C
chenxuyi 已提交
161
                infer_program = self.program.train_program
C
chenxuyi 已提交
162 163 164 165 166 167
                startup_prog = F.Program()
                F.io.save_inference_model(
                    save_dir,
                    feed_var,
                    fetch_var,
                    exe,
C
chenxuyi 已提交
168
                    main_program=infer_program)
M
Meiyim 已提交
169 170
            eval_result = map_structure(float, eval_result)
            state['best_inf_model'] = eval_result
C
chenxuyi 已提交
171 172 173
            self._best = eval_result
        else:
            log.debug('[Best Exporter]: skip step %s' % state.gstep)