pruner.py 29.0 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.

15
import logging
W
wanghaoshuang 已提交
16 17
import numpy as np
import paddle.fluid as fluid
18 19
import copy
from ..core import VarWrapper, OpWrapper, GraphWrapper
20
from ..common import get_logger
W
wanghaoshuang 已提交
21

22
__all__ = ["Pruner"]
W
wanghaoshuang 已提交
23

24 25
_logger = get_logger(__name__, level=logging.INFO)

W
wanghaoshuang 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

class Pruner():
    def __init__(self, criterion="l1_norm"):
        """
        Args:
            criterion(str): the criterion used to sort channels for pruning.
                            It only supports 'l1_norm' currently.
        """
        self.criterion = criterion

    def prune(self,
              program,
              scope,
              params,
              ratios,
              place=None,
              lazy=False,
              only_graph=False,
W
wanghaoshuang 已提交
44 45
              param_backup=False,
              param_shape_backup=False):
W
wanghaoshuang 已提交
46 47 48 49 50 51 52 53 54 55 56 57
        """
        Pruning the given parameters.
        Args:
            program(fluid.Program): The program to be pruned.
            scope(fluid.Scope): The scope storing paramaters to be pruned.
            params(list<str>): A list of parameter names to be pruned.
            ratios(list<float>): A list of ratios to be used to pruning parameters.
            place(fluid.Place): The device place of filter parameters. Defalut: None.
            lazy(bool): True means setting the pruned elements to zero.
                        False means cutting down the pruned elements. Default: False.
            only_graph(bool): True means only modifying the graph.
                              False means modifying graph and variables in scope. Default: False.
W
wanghaoshuang 已提交
58 59
            param_backup(bool): Whether to return a dict to backup the values of parameters. Default: False.
            param_shape_backup(bool): Whether to return a dict to backup the shapes of parameters. Default: False.
W
wanghaoshuang 已提交
60 61
        Returns:
            Program: The pruned program.
W
wanghaoshuang 已提交
62 63
            param_backup: A dict to backup the values of parameters.
            param_shape_backup: A dict to backup the shapes of parameters.
W
wanghaoshuang 已提交
64 65 66 67
        """

        self.pruned_list = []
        graph = GraphWrapper(program.clone())
W
wanghaoshuang 已提交
68 69
        param_backup = {} if param_backup else None
        param_shape_backup = {} if param_shape_backup else None
W
wanghaoshuang 已提交
70 71 72 73 74 75
        self._prune_parameters(
            graph,
            scope,
            params,
            ratios,
            place,
76 77 78 79
            lazy=lazy,
            only_graph=only_graph,
            param_backup=param_backup,
            param_shape_backup=param_shape_backup)
80 81 82 83
        for op in graph.ops():
            if op.type() == 'depthwise_conv2d' or op.type(
            ) == 'depthwise_conv2d_grad':
                op.set_attr('groups', op.inputs('Filter')[0].shape()[0])
W
wanghaoshuang 已提交
84
        return graph.program, param_backup, param_shape_backup
W
wanghaoshuang 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

    def _prune_filters_by_ratio(self,
                                scope,
                                params,
                                ratio,
                                place,
                                lazy=False,
                                only_graph=False,
                                param_shape_backup=None,
                                param_backup=None):
        """
        Pruning filters by given ratio.
        Args:
            scope(fluid.core.Scope): The scope used to pruning filters.
            params(list<VarWrapper>): A list of filter parameters.
            ratio(float): The ratio to be pruned.
            place(fluid.Place): The device place of filter parameters.
            lazy(bool): True means setting the pruned elements to zero.
                        False means cutting down the pruned elements.
            only_graph(bool): True means only modifying the graph.
                              False means modifying graph and variables in  scope.
        """
        if params[0].name() in self.pruned_list[0]:
            return
W
wanghaoshuang 已提交
109 110 111 112 113 114 115 116 117 118 119

        if only_graph:
            pruned_num = int(round(params[0].shape()[0] * ratio))
            for param in params:
                ori_shape = param.shape()
                if param_backup is not None and (
                        param.name() not in param_backup):
                    param_backup[param.name()] = copy.deepcopy(ori_shape)
                new_shape = list(ori_shape)
                new_shape[0] -= pruned_num
                param.set_shape(new_shape)
W
wanghaoshuang 已提交
120
                _logger.debug("prune [{}] from {} to {}".format(param.name(
W
wanghaoshuang 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
                ), ori_shape, new_shape))
                self.pruned_list[0].append(param.name())
            return range(pruned_num)

        else:

            param_t = scope.find_var(params[0].name()).get_tensor()
            pruned_idx = self._cal_pruned_idx(
                params[0].name(), np.array(param_t), ratio, axis=0)
            for param in params:
                assert isinstance(param, VarWrapper)
                param_t = scope.find_var(param.name()).get_tensor()
                if param_backup is not None and (
                        param.name() not in param_backup):
                    param_backup[param.name()] = copy.deepcopy(
                        np.array(param_t))
W
wanghaoshuang 已提交
137 138 139 140 141 142 143 144 145 146
                try:
                    pruned_param = self._prune_tensor(
                        np.array(param_t),
                        pruned_idx,
                        pruned_axis=0,
                        lazy=lazy)
                except IndexError as e:
                    _logger.error("Pruning {}, but get [{}]".format(param.name(
                    ), e))

W
wanghaoshuang 已提交
147
                param_t.set(pruned_param, place)
W
wanghaoshuang 已提交
148 149 150 151 152 153 154 155
                ori_shape = param.shape()
                if param_shape_backup is not None and (
                        param.name() not in param_shape_backup):
                    param_shape_backup[param.name()] = copy.deepcopy(
                        param.shape())
                new_shape = list(param.shape())
                new_shape[0] = pruned_param.shape[0]
                param.set_shape(new_shape)
W
wanghaoshuang 已提交
156
                _logger.debug("prune [{}] from {} to {}".format(param.name(
W
wanghaoshuang 已提交
157 158 159
                ), ori_shape, new_shape))
                self.pruned_list[0].append(param.name())
            return pruned_idx
W
wanghaoshuang 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185

    def _prune_parameter_by_idx(self,
                                scope,
                                params,
                                pruned_idx,
                                pruned_axis,
                                place,
                                lazy=False,
                                only_graph=False,
                                param_shape_backup=None,
                                param_backup=None):
        """
        Pruning parameters in given axis.
        Args:
            scope(fluid.core.Scope): The scope storing paramaters to be pruned.
            params(VarWrapper): The parameter to be pruned.
            pruned_idx(list): The index of elements to be pruned.
            pruned_axis(int): The pruning axis.
            place(fluid.Place): The device place of filter parameters.
            lazy(bool): True means setting the pruned elements to zero.
                        False means cutting down the pruned elements.
            only_graph(bool): True means only modifying the graph.
                              False means modifying graph and variables in  scope.
        """
        if params[0].name() in self.pruned_list[pruned_axis]:
            return
W
wanghaoshuang 已提交
186 187 188 189 190 191 192 193 194 195
        if only_graph:
            pruned_num = len(pruned_idx)
            for param in params:
                ori_shape = param.shape()
                if param_backup is not None and (
                        param.name() not in param_backup):
                    param_backup[param.name()] = copy.deepcopy(ori_shape)
                new_shape = list(ori_shape)
                new_shape[pruned_axis] -= pruned_num
                param.set_shape(new_shape)
W
wanghaoshuang 已提交
196
                _logger.debug("prune [{}] from {} to {}".format(param.name(
W
wanghaoshuang 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209
                ), ori_shape, new_shape))
                self.pruned_list[pruned_axis].append(param.name())

        else:
            for param in params:
                assert isinstance(param, VarWrapper)
                param_t = scope.find_var(param.name()).get_tensor()
                if param_backup is not None and (
                        param.name() not in param_backup):
                    param_backup[param.name()] = copy.deepcopy(
                        np.array(param_t))
                pruned_param = self._prune_tensor(
                    np.array(param_t), pruned_idx, pruned_axis, lazy=lazy)
W
wanghaoshuang 已提交
210
                param_t.set(pruned_param, place)
W
wanghaoshuang 已提交
211
                ori_shape = param.shape()
W
wanghaoshuang 已提交
212

W
wanghaoshuang 已提交
213 214 215 216 217 218 219
                if param_shape_backup is not None and (
                        param.name() not in param_shape_backup):
                    param_shape_backup[param.name()] = copy.deepcopy(
                        param.shape())
                new_shape = list(param.shape())
                new_shape[pruned_axis] = pruned_param.shape[pruned_axis]
                param.set_shape(new_shape)
W
wanghaoshuang 已提交
220
                _logger.debug("prune [{}] from {} to {}".format(param.name(
W
wanghaoshuang 已提交
221 222
                ), ori_shape, new_shape))
                self.pruned_list[pruned_axis].append(param.name())
W
wanghaoshuang 已提交
223

W
wanghaoshuang 已提交
224
    def _forward_search_related_op(self, graph, node):
W
wanghaoshuang 已提交
225 226 227 228
        """
        Forward search operators that will be affected by pruning of param.
        Args:
            graph(GraphWrapper): The graph to be searched.
W
wanghaoshuang 已提交
229
            node(VarWrapper|OpWrapper): The current pruned parameter or operator.
W
wanghaoshuang 已提交
230 231 232 233 234 235 236 237
        Returns:
            list<OpWrapper>: A list of operators.
        """
        visited = {}
        for op in graph.ops():
            visited[op.idx()] = False
        stack = []
        visit_path = []
W
wanghaoshuang 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
        if isinstance(node, VarWrapper):
            for op in graph.ops():
                if (not op.is_bwd_op()) and (node in op.all_inputs()):
                    next_ops = self._get_next_unvisited_op(graph, visited, op)
                    #                visit_path.append(op)
                    visited[op.idx()] = True
                    for next_op in next_ops:
                        if visited[next_op.idx()] == False:
                            stack.append(next_op)
                            visit_path.append(next_op)
                            visited[next_op.idx()] = True
        elif isinstance(node, OpWrapper):
            next_ops = self._get_next_unvisited_op(graph, visited, node)
            for next_op in next_ops:
                if visited[next_op.idx()] == False:
                    stack.append(next_op)
                    visit_path.append(next_op)
                    visited[next_op.idx()] = True
W
wanghaoshuang 已提交
256
        while len(stack) > 0:
W
wanghaoshuang 已提交
257 258
            #top_op = stack[len(stack) - 1]
            top_op = stack.pop(0)
W
wanghaoshuang 已提交
259
            next_ops = None
W
wanghaoshuang 已提交
260
            if top_op.type() in ["conv2d", "deformable_conv"]:
W
wanghaoshuang 已提交
261
                next_ops = None
W
wanghaoshuang 已提交
262
            elif top_op.type() in ["mul", "concat"]:
W
wanghaoshuang 已提交
263 264 265
                next_ops = None
            else:
                next_ops = self._get_next_unvisited_op(graph, visited, top_op)
W
wanghaoshuang 已提交
266 267 268 269 270 271 272
            if next_ops != None:
                for op in next_ops:
                    if visited[op.idx()] == False:
                        stack.append(op)
                        visit_path.append(op)
                        visited[op.idx()] = True

W
wanghaoshuang 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
        return visit_path

    def _get_next_unvisited_op(self, graph, visited, top_op):
        """
        Get next unvisited adjacent operators of given operators.
        Args:
            graph(GraphWrapper): The graph used to search. 
            visited(list): The ids of operators that has been visited.
            top_op: The given operator.
        Returns:
            list<OpWrapper>: A list of operators. 
        """
        assert isinstance(top_op, OpWrapper)
        next_ops = []
        for op in graph.next_ops(top_op):
            if (visited[op.idx()] == False) and (not op.is_bwd_op()):
                next_ops.append(op)
W
wanghaoshuang 已提交
290
        return next_ops
W
wanghaoshuang 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345

    def _get_accumulator(self, graph, param):
        """
        Get accumulators of given parameter. The accumulator was created by optimizer.
        Args:
            graph(GraphWrapper): The graph used to search.
            param(VarWrapper): The given parameter.
        Returns:
            list<VarWrapper>: A list of accumulators which are variables.
        """
        assert isinstance(param, VarWrapper)
        params = []
        for op in param.outputs():
            if op.is_opt_op():
                for out_var in op.all_outputs():
                    if graph.is_persistable(out_var) and out_var.name(
                    ) != param.name():
                        params.append(out_var)
        return params

    def _forward_pruning_ralated_params(self,
                                        graph,
                                        scope,
                                        param,
                                        place,
                                        ratio=None,
                                        pruned_idxs=None,
                                        lazy=False,
                                        only_graph=False,
                                        param_backup=None,
                                        param_shape_backup=None):
        """
        Pruning all the parameters affected by the pruning of given parameter.
        Args:
            graph(GraphWrapper): The graph to be searched.
            scope(fluid.core.Scope): The scope storing paramaters to be pruned.
            param(VarWrapper): The given parameter.
            place(fluid.Place): The device place of filter parameters.
            ratio(float): The target ratio to be pruned.
            pruned_idx(list): The index of elements to be pruned.
            lazy(bool): True means setting the pruned elements to zero.
                        False means cutting down the pruned elements.
            only_graph(bool): True means only modifying the graph.
                              False means modifying graph and variables in  scope.
        """
        assert isinstance(
            graph,
            GraphWrapper), "graph must be instance of slim.core.GraphWrapper"
        assert isinstance(
            param,
            VarWrapper), "param must be instance of slim.core.VarWrapper"

        if param.name() in self.pruned_list[0]:
            return
        related_ops = self._forward_search_related_op(graph, param)
W
wanghaoshuang 已提交
346 347
        for op in related_ops:
            _logger.debug("relate op: {};".format(op))
W
wanghaoshuang 已提交
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
        if ratio is None:
            assert pruned_idxs is not None
            self._prune_parameter_by_idx(
                scope, [param] + self._get_accumulator(graph, param),
                pruned_idxs,
                pruned_axis=0,
                place=place,
                lazy=lazy,
                only_graph=only_graph,
                param_backup=param_backup,
                param_shape_backup=param_shape_backup)

        else:
            pruned_idxs = self._prune_filters_by_ratio(
                scope, [param] + self._get_accumulator(graph, param),
                ratio,
                place,
                lazy=lazy,
                only_graph=only_graph,
                param_backup=param_backup,
                param_shape_backup=param_shape_backup)
W
wanghaoshuang 已提交
369 370
        self._prune_ops(related_ops, pruned_idxs, graph, scope, place, lazy,
                        only_graph, param_backup, param_shape_backup)
W
wanghaoshuang 已提交
371

W
wanghaoshuang 已提交
372 373 374 375
    def _prune_ops(self, ops, pruned_idxs, graph, scope, place, lazy,
                   only_graph, param_backup, param_shape_backup):
        for idx, op in enumerate(ops):
            if op.type() in ["conv2d", "deformable_conv"]:
W
wanghaoshuang 已提交
376 377 378 379 380 381
                for in_var in op.all_inputs():
                    if graph.is_parameter(in_var):
                        conv_param = in_var
                        self._prune_parameter_by_idx(
                            scope, [conv_param] + self._get_accumulator(
                                graph, conv_param),
W
wanghaoshuang 已提交
382
                            pruned_idxs,
W
wanghaoshuang 已提交
383 384 385 386 387 388 389 390 391 392 393 394 395
                            pruned_axis=1,
                            place=place,
                            lazy=lazy,
                            only_graph=only_graph,
                            param_backup=param_backup,
                            param_shape_backup=param_shape_backup)
            if op.type() == "depthwise_conv2d":
                for in_var in op.all_inputs():
                    if graph.is_parameter(in_var):
                        conv_param = in_var
                        self._prune_parameter_by_idx(
                            scope, [conv_param] + self._get_accumulator(
                                graph, conv_param),
W
wanghaoshuang 已提交
396
                            pruned_idxs,
W
wanghaoshuang 已提交
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
                            pruned_axis=0,
                            place=place,
                            lazy=lazy,
                            only_graph=only_graph,
                            param_backup=param_backup,
                            param_shape_backup=param_shape_backup)
            elif op.type() == "elementwise_add":
                # pruning bias
                for in_var in op.all_inputs():
                    if graph.is_parameter(in_var):
                        bias_param = in_var
                        self._prune_parameter_by_idx(
                            scope, [bias_param] + self._get_accumulator(
                                graph, bias_param),
                            pruned_idxs,
                            pruned_axis=0,
                            place=place,
                            lazy=lazy,
                            only_graph=only_graph,
                            param_backup=param_backup,
                            param_shape_backup=param_shape_backup)
            elif op.type() == "mul":  # pruning fc layer
                fc_input = None
                fc_param = None
                for in_var in op.all_inputs():
                    if graph.is_parameter(in_var):
                        fc_param = in_var
                    else:
                        fc_input = in_var

                idx = []
                feature_map_size = fc_input.shape()[2] * fc_input.shape()[3]
                range_idx = np.array(range(feature_map_size))
W
wanghaoshuang 已提交
430
                for i in pruned_idxs:
W
wanghaoshuang 已提交
431 432 433 434 435 436 437 438 439 440 441 442 443 444
                    idx += list(range_idx + i * feature_map_size)
                corrected_idxs = idx
                self._prune_parameter_by_idx(
                    scope, [fc_param] + self._get_accumulator(graph, fc_param),
                    corrected_idxs,
                    pruned_axis=0,
                    place=place,
                    lazy=lazy,
                    only_graph=only_graph,
                    param_backup=param_backup,
                    param_shape_backup=param_shape_backup)

            elif op.type() == "concat":
                concat_inputs = op.all_inputs()
W
wanghaoshuang 已提交
445 446 447 448 449 450 451 452 453
                last_op = ops[idx - 1]
                concat_idx = None
                for last_op in reversed(ops):
                    for out_var in last_op.all_outputs():
                        if out_var in concat_inputs:
                            concat_idx = concat_inputs.index(out_var)
                            break
                    if concat_idx is not None:
                        break
W
wanghaoshuang 已提交
454 455 456 457
                offset = 0
                for ci in range(concat_idx):
                    offset += concat_inputs[ci].shape()[1]
                corrected_idxs = [x + offset for x in pruned_idxs]
W
wanghaoshuang 已提交
458 459 460 461 462 463 464 465
                related_ops = self._forward_search_related_op(graph, op)

                for op in related_ops:
                    _logger.debug("concat relate op: {};".format(op))

                self._prune_ops(related_ops, corrected_idxs, graph, scope,
                                place, lazy, only_graph, param_backup,
                                param_shape_backup)
W
wanghaoshuang 已提交
466 467
            elif op.type() == "batch_norm":
                bn_inputs = op.all_inputs()
W
wanghaoshuang 已提交
468 469 470 471
                in_num = len(bn_inputs)
                beta = bn_inputs[0]
                mean = bn_inputs[1]
                alpha = bn_inputs[2]
W
wanghaoshuang 已提交
472 473 474
                variance = bn_inputs[3]
                self._prune_parameter_by_idx(
                    scope, [mean] + self._get_accumulator(graph, mean),
W
wanghaoshuang 已提交
475
                    pruned_idxs,
W
wanghaoshuang 已提交
476 477 478 479 480 481 482 483
                    pruned_axis=0,
                    place=place,
                    lazy=lazy,
                    only_graph=only_graph,
                    param_backup=param_backup,
                    param_shape_backup=param_shape_backup)
                self._prune_parameter_by_idx(
                    scope, [variance] + self._get_accumulator(graph, variance),
W
wanghaoshuang 已提交
484
                    pruned_idxs,
W
wanghaoshuang 已提交
485 486 487 488 489 490 491 492
                    pruned_axis=0,
                    place=place,
                    lazy=lazy,
                    only_graph=only_graph,
                    param_backup=param_backup,
                    param_shape_backup=param_shape_backup)
                self._prune_parameter_by_idx(
                    scope, [alpha] + self._get_accumulator(graph, alpha),
W
wanghaoshuang 已提交
493
                    pruned_idxs,
W
wanghaoshuang 已提交
494 495 496 497 498 499 500 501
                    pruned_axis=0,
                    place=place,
                    lazy=lazy,
                    only_graph=only_graph,
                    param_backup=param_backup,
                    param_shape_backup=param_shape_backup)
                self._prune_parameter_by_idx(
                    scope, [beta] + self._get_accumulator(graph, beta),
W
wanghaoshuang 已提交
502
                    pruned_idxs,
W
wanghaoshuang 已提交
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
                    pruned_axis=0,
                    place=place,
                    lazy=lazy,
                    only_graph=only_graph,
                    param_backup=param_backup,
                    param_shape_backup=param_shape_backup)

    def _prune_parameters(self,
                          graph,
                          scope,
                          params,
                          ratios,
                          place,
                          lazy=False,
                          only_graph=False,
                          param_backup=None,
                          param_shape_backup=None):
        """
        Pruning the given parameters.
        Args:
            graph(GraphWrapper): The graph to be searched.
            scope(fluid.core.Scope): The scope storing paramaters to be pruned.
            params(list<str>): A list of parameter names to be pruned.
            ratios(list<float>): A list of ratios to be used to pruning parameters.
            place(fluid.Place): The device place of filter parameters.
            pruned_idx(list): The index of elements to be pruned.
            lazy(bool): True means setting the pruned elements to zero.
                        False means cutting down the pruned elements.
            only_graph(bool): True means only modifying the graph.
                              False means modifying graph and variables in  scope.
        """
        assert len(params) == len(ratios)
        self.pruned_list = [[], []]
        for param, ratio in zip(params, ratios):
            assert isinstance(param, str) or isinstance(param, unicode)
W
wanghaoshuang 已提交
538 539 540
            if param in self.pruned_list[0]:
                _logger.info("Skip {}".format(param))
                continue
W
wanghaoshuang 已提交
541
            _logger.info("pruning param: {}".format(param))
W
wanghaoshuang 已提交
542 543 544 545 546 547 548 549 550 551 552 553 554
            param = graph.var(param)
            self._forward_pruning_ralated_params(
                graph,
                scope,
                param,
                place,
                ratio=ratio,
                lazy=lazy,
                only_graph=only_graph,
                param_backup=param_backup,
                param_shape_backup=param_shape_backup)
            ops = param.outputs()
            for op in ops:
W
wanghaoshuang 已提交
555
                if op.type() in ['conv2d', 'deformable_conv']:
W
wanghaoshuang 已提交
556 557
                    brother_ops = self._search_brother_ops(graph, op)
                    for broher in brother_ops:
W
wanghaoshuang 已提交
558
                        _logger.debug("pruning brother: {}".format(broher))
W
wanghaoshuang 已提交
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
                        for p in graph.get_param_by_op(broher):
                            self._forward_pruning_ralated_params(
                                graph,
                                scope,
                                p,
                                place,
                                ratio=ratio,
                                lazy=lazy,
                                only_graph=only_graph,
                                param_backup=param_backup,
                                param_shape_backup=param_shape_backup)

    def _search_brother_ops(self, graph, op_node):
        """
        Search brother operators that was affected by pruning of given operator.
        Args:
            graph(GraphWrapper): The graph to be searched.
            op_node(OpWrapper): The start node for searching.
        Returns: 
            list<VarWrapper>: A list of operators.
        """
W
wanghaoshuang 已提交
580 581
        _logger.debug("######################search: {}######################".
                      format(op_node))
W
wanghaoshuang 已提交
582 583 584 585
        visited = [op_node.idx()]
        stack = []
        brothers = []
        for op in graph.next_ops(op_node):
W
wanghaoshuang 已提交
586 587 588 589 590
            if ("conv2d" not in op.type()) and (
                    "concat" not in op.type()) and (
                        "deformable_conv" not in op.type()) and (
                            op.type() != 'fc') and (
                                not op.is_bwd_op()) and (not op.is_opt_op()):
W
wanghaoshuang 已提交
591 592 593 594
                stack.append(op)
                visited.append(op.idx())
        while len(stack) > 0:
            top_op = stack.pop()
W
wanghaoshuang 已提交
595 596 597 598 599 600
            for parent in graph.pre_ops(top_op):
                if parent.idx() not in visited and (
                        not parent.is_bwd_op()) and (not parent.is_opt_op()):
                    _logger.debug("----------go back from {} to {}----------".
                                  format(top_op, parent))
                    if (('conv2d' in parent.type()) or
W
wanghaoshuang 已提交
601
                        ("deformable_conv" in parent.type()) or
W
wanghaoshuang 已提交
602 603 604 605 606
                        (parent.type() == 'fc')):
                        brothers.append(parent)
                    else:
                        stack.append(parent)
                    visited.append(parent.idx())
W
wanghaoshuang 已提交
607 608

            for child in graph.next_ops(top_op):
W
wanghaoshuang 已提交
609 610 611 612 613 614 615
                if ('conv2d' not in child.type()) and (
                        "concat" not in child.type()) and (
                            'deformable_conv' not in child.type()) and (
                                child.type() != 'fc') and (
                                    child.idx() not in visited) and (
                                        not child.is_bwd_op()) and (
                                            not child.is_opt_op()):
W
wanghaoshuang 已提交
616 617
                    stack.append(child)
                    visited.append(child.idx())
W
wanghaoshuang 已提交
618 619 620 621
        _logger.debug("brothers: {}".format(brothers))
        _logger.debug(
            "######################Finish search######################".format(
                op_node))
W
wanghaoshuang 已提交
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
        return brothers

    def _cal_pruned_idx(self, name, param, ratio, axis):
        """
        Calculate the index to be pruned on axis by given pruning ratio.
        Args:
            name(str): The name of parameter to be pruned.
            param(np.array): The data of parameter to be pruned.
            ratio(float): The ratio to be pruned.
            axis(int): The axis to be used for pruning given parameter.
                       If it is None, the value in self.pruning_axis will be used.
                       default: None.
        Returns:
            list<int>: The indexes to be pruned on axis.
        """
        prune_num = int(round(param.shape[axis] * ratio))
        reduce_dims = [i for i in range(len(param.shape)) if i != axis]
        if self.criterion == 'l1_norm':
            criterions = np.sum(np.abs(param), axis=tuple(reduce_dims))
        pruned_idx = criterions.argsort()[:prune_num]
        return pruned_idx

    def _prune_tensor(self, tensor, pruned_idx, pruned_axis, lazy=False):
        """
        Pruning a array by indexes on given axis.
        Args:
            tensor(numpy.array): The target array to be pruned.
            pruned_idx(list<int>): The indexes to be pruned.
            pruned_axis(int): The axis of given array to be pruned on. 
            lazy(bool): True means setting the pruned elements to zero.
                        False means remove the pruned elements from memory.
                        default: False.
        Returns:
            numpy.array: The pruned array.
        """
        mask = np.zeros(tensor.shape[pruned_axis], dtype=bool)
        mask[pruned_idx] = True

        def func(data):
            return data[~mask]

        def lazy_func(data):
            data[mask] = 0
            return data

        if lazy:
            return np.apply_along_axis(lazy_func, pruned_axis, tensor)
        else:
            return np.apply_along_axis(func, pruned_axis, tensor)