exporter.py 6.1 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 33 34
import abc
import logging

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

from propeller.paddle.train import Saver
from propeller.types import InferenceSpec
C
chenxuyi 已提交
35 36 37 38 39
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 已提交
40 41 42 43 44

log = logging.getLogger(__name__)


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

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


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

C
chenxuyi 已提交
57
    def __init__(self, export_dir, cmp_fn):
C
chenxuyi 已提交
58
        """doc"""
C
chenxuyi 已提交
59 60 61 62 63
        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 已提交
64
        """doc"""
C
chenxuyi 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
        log.debug('New evaluate result: %s \nold: %s' %
                  (repr(eval_result), repr(self._best)))
        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(
                self._export_dir,
                exe,
                program=eval_program,
                max_ckpt_to_keep=1)
            saver.save(state)
            self._best = eval_result
        else:
            log.debug('[Best Exporter]: skip step %s' % state.gstep)


class BestInferenceModelExporter(Exporter):
C
chenxuyi 已提交
84 85 86 87 88 89 90 91 92
    """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 已提交
93 94 95
        self._export_dir = export_dir
        self._best = None
        self.cmp_fn = cmp_fn
C
chenxuyi 已提交
96 97 98
        self.model_class_or_model_fn = model_class_or_model_fn
        self.hparams = hparams
        self.dataset = dataset
C
chenxuyi 已提交
99 100

    def export(self, exe, program, eval_model_spec, eval_result, state):
C
chenxuyi 已提交
101 102 103 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
        """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

C
chenxuyi 已提交
134 135 136 137
        log.debug('New evaluate result: %s \nold: %s' %
                  (repr(eval_result), repr(self._best)))
        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 已提交
138
            if self.model_spec.inference_spec is None:
C
chenxuyi 已提交
139 140
                raise ValueError('model_fn didnt return InferenceSpec')

C
chenxuyi 已提交
141 142 143 144 145 146 147
            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 已提交
148

C
chenxuyi 已提交
149
                save_dir = os.path.join(self._export_dir, inf_spec_name)
C
chenxuyi 已提交
150
                log.debug('[Best Exporter]: save inference model: "%s" to %s' %
C
chenxuyi 已提交
151 152 153
                          (inf_spec_name, save_dir))
                feed_var = [i.name for i in inf_spec.inputs]
                fetch_var = inf_spec.outputs
C
chenxuyi 已提交
154

C
chenxuyi 已提交
155
                infer_program = self.program.train_program
C
chenxuyi 已提交
156 157 158 159 160 161
                startup_prog = F.Program()
                F.io.save_inference_model(
                    save_dir,
                    feed_var,
                    fetch_var,
                    exe,
C
chenxuyi 已提交
162
                    main_program=infer_program)
C
chenxuyi 已提交
163 164 165
            self._best = eval_result
        else:
            log.debug('[Best Exporter]: skip step %s' % state.gstep)