pytorch_decoder.py 2.5 KB
Newer Older
S
SunAhong1993 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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.

S
SunAhong1993 已提交
15 16
import os
import sys
S
SunAhong1993 已提交
17
import torch
S
SunAhong1993 已提交
18
import numpy as np
S
SunAhong1993 已提交
19 20


S
SunAhong1993 已提交
21 22
class Decoder(object):
     def _optimize_graph(self, graph):
S
SunAhong1993 已提交
23 24 25 26 27 28 29 30 31 32
        torch._C._jit_pass_constant_propagation(graph)
        torch._C._jit_pass_dce(graph)
        torch._C._jit_pass_lint(graph)
        torch._C._jit_pass_peephole(graph)
        torch._C._jit_pass_lint(graph)
        torch._C._jit_pass_dce(graph)
        torch._C._jit_pass_lint(graph)
        torch._C._jit_pass_canonicalize(graph)
        torch._C._jit_pass_lint(graph)
        torch._C._jit_pass_constant_propagation(graph)
S
SunAhong1993 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
        return graph       


class ScriptDecoder(Decoder):
    """ 当script_path非None,直接load ScriptModule;
        当model_path非None,load PyTorchModule后使用script方式转换为ScriptModule。
        
        Args:
            script_path (str): ScriptModule保存路径。
            model_path (str): PyTorchModule保存路径。
    """
    def __init__(self, script_path=None):
        self.script = torch.jit.load(script_path)
        self.graph = self._optimize_graph(self.script.inlined_graph)
            
class TraceDecoder(Decoder):
    """ PyTorchModule后使用trace方式转换为ScriptModule。
        
        Args:
            model_path (str): PyTorchModule保存路径。
            input_files (list): 输入网络的numpy,每个numpy保存成.npy文件, 
                                文件路径存储在input_files中。
    """
    def __init__(self, model_path, input_files=list()):
        # TODO(syf): 传入pytorch的Module(即import),否则出错
        model = torch.load(model_path)
        model.eval()
        input_list = list()
        for npy_file in input_files:
            input_list.append(torch.tensor(np.load(npy_file)))
        self.script = torch.jit.trace(model, input_list, strict=False)
        self.graph = self._optimize_graph(self.script.inlined_graph)
#         print(self.graph)
#         print(getattr(getattr(self.script.decoder.block, "5").layer, "2"))