inferencer.py 2.7 KB
Newer Older
H
Helin Wang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2018 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.

15 16
import contextlib

H
Helin Wang 已提交
17
import core
D
daminglu 已提交
18

J
Jeff Wang 已提交
19
import executor
D
daminglu 已提交
20
import framework
J
Jeff Wang 已提交
21
import io
22
import parallel_executor
D
daminglu 已提交
23
import unique_name
Q
Qiao Longfei 已提交
24 25
from trainer import check_and_get_place

H
Helin Wang 已提交
26
__all__ = ['Inferencer', ]
H
Helin Wang 已提交
27 28 29


class Inferencer(object):
30
    def __init__(self, infer_func, param_path, place=None, parallel=False):
Q
Qiao Longfei 已提交
31
        """
D
daminglu 已提交
32 33
        :param infer_func: a function that will return predict Variable
        :param param_path: the path where the inference model is saved by fluid.io.save_params
Q
Qiao Longfei 已提交
34 35 36
        :param place: place to do the inference
        """
        self.param_path = param_path
H
Helin Wang 已提交
37
        self.scope = core.Scope()
38 39
        self.parallel = parallel
        self.place = check_and_get_place(place)
J
Jeff Wang 已提交
40

D
daminglu 已提交
41 42 43 44 45
        self.inference_program = framework.Program()
        with framework.program_guard(self.inference_program):
            with unique_name.guard():
                self.predict_var = infer_func()

46 47 48 49
        with self._prog_and_scope_guard():
            # load params from param_path into scope
            io.load_params(executor.Executor(self.place), param_path)

50
        if parallel:
51 52 53 54
            with self._prog_and_scope_guard():
                self.exe = parallel_executor.ParallelExecutor(
                    use_cuda=isinstance(self.place, core.CUDAPlace),
                    loss_name=self.predict_var.name)
55 56
        else:
            self.exe = executor.Executor(self.place)
Q
Qiao Longfei 已提交
57

58
    def infer(self, inputs):
Q
Qiao Longfei 已提交
59 60 61 62 63 64 65 66 67
        """
        :param inputs: a map of {"input_name": input_var} that will be feed into the inference program
        to get the predict value
        :return: the predict value of the inference model
        """
        if not isinstance(inputs, dict):
            raise ValueError(
                "inputs should be a map of {'input_name': input_var}")

68 69 70
        with self._prog_and_scope_guard():
            results = self.exe.run(feed=inputs,
                                   fetch_list=[self.predict_var.name])
Q
Qiao Longfei 已提交
71 72

        return results
73 74 75 76 77 78

    @contextlib.contextmanager
    def _prog_and_scope_guard(self):
        with framework.program_guard(main_program=self.inference_program):
            with executor.scope_guard(self.scope):
                yield