latency.py 8.7 KB
Newer Older
W
wanghaoshuang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 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
ceci3 已提交
15 16
from paddle.fluid import Program
from ..core import GraphWrapper, OpWrapper
W
wanghaoshuang 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
__all__ = ["LatencyEvaluator", "TableLatencyEvaluator"]


class LatencyEvaluator(object):
    def __init__(self):
        pass

    def latency(self, graph):
        pass

    def _get_ops_from_graph(self, graph):
        assert isinstance(graph, GraphWrapper)
        ops = []
        i = 0
        for op in graph.ops():
            if op.type() in ['conv2d', 'depthwise_conv2d']:
C
ceci3 已提交
33
                tmp = self._conv_op_args(op)
W
wanghaoshuang 已提交
34 35 36
            elif op.type() in [
                    'elementwise_add', 'elementwise_mul', 'elementwise_max'
            ]:
C
ceci3 已提交
37
                tmp = self._eltwise_op_args(op)
W
wanghaoshuang 已提交
38 39 40 41
            elif op.type() in [
                    'relu', 'prelu', 'sigmoid', 'relu6', 'elu', 'brelu',
                    'leaky_relu'
            ]:
C
ceci3 已提交
42
                tmp = self._activation_op_args(op)
W
wanghaoshuang 已提交
43
            elif op.type() == 'batch_norm':
C
ceci3 已提交
44
                tmp = self._batch_norm_op_args(op)
W
wanghaoshuang 已提交
45
            elif op.type() == 'pool2d':
C
ceci3 已提交
46
                tmp = self._pooling_op_args(op)
W
wanghaoshuang 已提交
47
            elif op.type() == 'batch_norm':
C
ceci3 已提交
48
                tmp = self._batch_norm_op_args(op)
W
wanghaoshuang 已提交
49
            elif op.type() == 'softmax':
C
ceci3 已提交
50
                tmp = self._softmax_op_args(op)
W
wanghaoshuang 已提交
51
            elif op.type() == 'mul':
C
ceci3 已提交
52
                tmp = self._fc_op_args(op)
W
wanghaoshuang 已提交
53 54 55 56 57 58
            else:
                tmp = None
            if tmp:
                ops.append(tmp)
        return ops

C
ceci3 已提交
59
    def _conv_op_args(self, op):
W
wanghaoshuang 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73
        assert isinstance(op, OpWrapper)
        tmp, res = [], []
        # op_name
        tmp.append('conv')
        # flag_bias
        if len(op.inputs('Bias')) == 0:
            tmp.append(0)
        else:
            tmp.append(1)
        # flag_relu
        tmp.append(int(op.attr('fuse_relu')))
        # batch size
        tmp.append(1)
        # channels, height, width
C
ceci3 已提交
74
        in_shapes = op.inputs('Input')[0].shape()
W
wanghaoshuang 已提交
75 76 77
        tmp = tmp + [int(in_shapes[1]), int(in_shapes[2]), int(in_shapes[3])]

        # output channels
C
ceci3 已提交
78
        w_shapes = op.inputs('Filter')[0].shape()
W
wanghaoshuang 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
        tmp.append(int(w_shapes[0]))

        # group
        tmp.append(int(op.attr('groups')))

        # kernel size
        tmp.append(int(w_shapes[2]))
        if w_shapes[2] != w_shapes[3]:
            res.append(int(w_shapes[3]))

        # padding
        paddings = op.attr('paddings')
        tmp.append(int(paddings[0]))
        if paddings[0] != paddings[1]:
            res.append(int(paddings[0]))

        # strides
        strides = op.attr('strides')
        tmp.append(int(strides[0]))
        if strides[0] != strides[1]:
            res.append(int(strides[1]))

        # dilations
        dilations = op.attr('dilations')
        tmp.append(int(dilations[0]))
        if dilations[0] != dilations[1]:
            res.append(int(dilations[1]))
        tmp = tmp + res
        return tmp

C
ceci3 已提交
109
    def _batch_norm_op_args(self, op):
W
wanghaoshuang 已提交
110 111 112 113 114 115 116 117 118 119 120
        tmp = []
        # op name
        tmp.append('batch_norm')
        # activation type
        if not op.attr('fuse_with_relu'):
            tmp.append('None')
        else:
            tmp.append('relu')
        # batch size
        tmp.append(1)
        # input channels, height, width
C
ceci3 已提交
121
        in_shapes = op.inputs("X")[0].shape()
W
wanghaoshuang 已提交
122 123 124
        tmp = tmp + [int(in_shapes[1]), int(in_shapes[2]), int(in_shapes[3])]
        return tmp

C
ceci3 已提交
125
    def _eltwise_op_args(self, op):
W
wanghaoshuang 已提交
126 127 128 129 130 131 132 133 134 135 136 137
        # op name
        tmp = ['eltwise']
        # elementwise type, TODO: add more ops
        if op.type() == 'elementwise_mul':
            tmp.append(1)
        elif op.type() == 'elementwise_add':
            tmp.append(2)
        else:
            tmp.append(3)
        # batch size
        tmp.append(1)
        # input channels, height, width 
C
ceci3 已提交
138
        in_shapes = op.inputs('X')[0].shape()
W
wanghaoshuang 已提交
139 140 141 142 143 144 145
        while len(in_shapes) < 4:
            in_shapes = in_shapes + (1, )

        for i in range(1, len(in_shapes)):
            tmp.append(int(in_shapes[i]))
        return tmp

C
ceci3 已提交
146
    def _activation_op_args(self, op):
W
wanghaoshuang 已提交
147 148 149 150 151 152
        tmp = []
        # activation type
        tmp.append(op.type())
        # batch size
        tmp.append(1)
        # input channels, height, width
C
ceci3 已提交
153
        in_shapes = op.inputs('X')[0].shape()
W
wanghaoshuang 已提交
154 155 156 157 158 159 160
        while len(in_shapes) < 4:
            in_shapes = in_shapes + (1, )

        for i in range(1, len(in_shapes)):
            tmp.append(int(in_shapes[i]))
        return tmp

C
ceci3 已提交
161
    def _pooling_op_args(self, op):
W
wanghaoshuang 已提交
162 163 164 165 166 167 168 169
        tmp, res = [], []
        # op name
        tmp.append('pooling')
        # global pooling
        tmp.append(int(op.attr('global_pooling')))
        # batch size
        tmp.append(1)
        # channels, height, width
C
ceci3 已提交
170
        in_shapes = op.inputs('X')[0].shape()
W
wanghaoshuang 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
        tmp = tmp + [int(in_shapes[1]), int(in_shapes[2]), int(in_shapes[3])]
        # kernel size
        ksize = op.attr('ksize')
        tmp.append(int(ksize[0]))
        if ksize[0] != ksize[1]:
            res.append(int(ksize[1]))

        # padding
        paddings = op.attr('paddings')
        tmp.append(int(paddings[0]))
        if paddings[0] != paddings[1]:
            res.append(int(paddings[1]))

        # stride
        strides = op.attr('strides')
        tmp.append(int(strides[0]))
        if strides[0] != strides[1]:
            res.append(int(strides[1]))

        # ceil mode
        tmp.append(int(op.attr('ceil_mode')))

        # pool type
        pool_type = op.attr('pooling_type')
        exclusive = op.attr('exclusive')
        if pool_type == 'max' and (not exclusive):
            tmp.append(1)
        elif pool_type == 'avg' and (not exclusive):
            tmp.append(2)
        else:
            tmp.append(3)

        tmp = tmp + res
        return tmp

C
ceci3 已提交
206
    def _softmax_op_args(self, op):
W
wanghaoshuang 已提交
207 208 209 210 211 212 213
        # op name
        tmp = ['softmax']
        # axis
        tmp.append(op.attr('axis'))
        # batch size
        tmp.append(1)
        # input channels, height, width
C
ceci3 已提交
214
        in_shapes = op.inputs('X')[0].shape()
W
wanghaoshuang 已提交
215 216 217 218 219 220 221 222
        while len(in_shapes) < 4:
            in_shapes = in_shapes + (1, )

        for i in range(1, len(in_shapes)):
            tmp.append(int(in_shapes[i]))

        return tmp

C
ceci3 已提交
223
    def _fc_op_args(self, op):
W
wanghaoshuang 已提交
224 225 226 227 228 229 230 231 232 233
        # op name
        tmp = ['conv']
        # flag bias
        tmp.append(0)
        # flag relu
        tmp.append(0)
        # batch size 
        tmp.append(1)
        # input channels, height, width
        channels = 1
C
ceci3 已提交
234
        in_shape = op.inputs('X')[0].shape()
W
wanghaoshuang 已提交
235 236 237 238
        for i in range(1, len(in_shape)):
            channels *= in_shape[i]
        tmp = tmp + [int(channels), 1, 1]
        # output channels
C
ceci3 已提交
239
        tmp.append(int(op.outputs('Out')[0].shape()[1]))
W
wanghaoshuang 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
        # groups, kernel size, padding, stride, dilation
        tmp = tmp + [1, 1, 0, 1, 1]
        return tmp


class TableLatencyEvaluator(LatencyEvaluator):
    def __init__(self, table_file, delimiter=","):
        """
        The evaluator used to get graph's latency on some devices and infer engines.
        Args:
          - table_file(str): The path of file that records the devices latency of operators.
          - delimiter(str): The delimiter used in `table_file`.
        """
        self._table = self._load_table(table_file)
        self._delimiter = delimiter

    def _load_table(self, table_file):
        table = {}
        with open(table_file) as f:
            line = f.readline()
            self.infer_engine_name, self.device_name, self.create_time = line.strip(
            ).split("\t")
            for line in f:
                op_str, latency = line.strip().split("\t")
                table[op_str] = float(latency)
        return table

    def _op_latency(self, op_str):
        assert op_str in self._table
        return self._table[op_str]

    def latency(self, graph):
        """
        Get latency of target graph.
        Args:
            - graph(GrapWrapper | Program): The graph to be evaluated.
        Returns:
            latency(float): The latency of given graph on current evaluator.
        """
        total_latency = 0
        if isinstance(graph, Program):
            graph = GraphWrapper(graph)
        assert isinstance(graph, GraphWrapper)
        for op in self._get_ops_from_graph(graph):
C
ceci3 已提交
284 285
            total_latency += self._op_latency(
                self._delimiter.join(map(lambda x: str(x), op)))
W
wanghaoshuang 已提交
286
        return total_latency