config_parser.py 160.3 KB
Newer Older
1
# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
#
# 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.

from __future__ import print_function
'''
The following functions are available in the config file:

Bias: define bias. To be used as value of bias argument in Layer().

Data: define data provider.

Input: define input layer for a layer. To be used as element of inputs argument
       in Layer().

Conv: define a convolution operation for an input of a layer.

Norm: define a normalization operation for an input of a layer.

Pool: define a pooling operation for an input of a layer.

Layer: define a layer.

Parameter: define a parameter.

Import: import another config file. If the imported config file name is
        a relative path, then it will be searched under the directory of the
        current config file.

Inputs(layer_names...):
    Define the name of the input layers of the NeuralNetwork.
    The type of these layers must be "data".
    These layers will be provided with the DataBatch obtained
    from DataProvider. The data streams from DataProvider must
    have the same order.

Outputs(layer_names...):
    Define the name of the output layers of the NeuralNetwork.
    Usually the output is simply the cost layer.
    You can specify other layers as outputs and  calculate the
    cost (and its derivative) yourself.


default_initial_std(val)
default_initial_mean(val)
default_momentum(val):
default_decay_rate(val): Set the default value for these parameters


get_config_arg(name, type, default): Get the value for a config parameter.


*** customized extension to config_parser ***
The functionality of the config_parser can be extended.
If the config_arg_str for parse_config() contains
extension_module_name=[MODULE_NAME], then config_parser will call
MODULE_NAME.get_config_funcs(g_config)
MODULE_NAME.get_config_funcs() should return a dictionary of name to functions,
those functions will be available in the config file.
See trainer/tests/config_parser_test.py for example

To use this from paddle_trainer, paddle_trainer should be called with
--config_args=extension_module_name=[MODULE_NAME]

'''
import copy
import logging
import os
import sys
import traceback
import math
import shutil

try:
    from paddle.proto.DataConfig_pb2 import DataConfig
    from paddle.proto.ModelConfig_pb2 import ModelConfig
    from paddle.proto.ModelConfig_pb2 import LayerConfig
    from paddle.proto.ModelConfig_pb2 import LayerInputConfig
    from paddle.proto.ModelConfig_pb2 import ProjectionConfig
    from paddle.proto.ModelConfig_pb2 import OperatorConfig
    from paddle.proto.ModelConfig_pb2 import GeneratorConfig
    from paddle.proto.ModelConfig_pb2 import LinkConfig
    from paddle.proto.ParameterConfig_pb2 import ParameterConfig
    from paddle.proto.ParameterConfig_pb2 import ParameterUpdaterHookConfig
    from paddle.proto.TrainerConfig_pb2 import TrainerConfig

except Exception as e:
    traceback.print_exc()
    raise

logging.basicConfig(
Q
qijun 已提交
102
    format='[%(levelname)s %(asctime)s %(filename)s:%(lineno)s] %(message)s', )
Z
zhangjinchao01 已提交
103 104 105
logger = logging.getLogger('paddle')
logger.setLevel(logging.INFO)
__real_print__ = print
Q
qijun 已提交
106
print = logger.info
Z
zhangjinchao01 已提交
107 108 109 110

# from layer type name to layer class
g_layer_type_map = {}

Q
qijun 已提交
111

Z
zhangjinchao01 已提交
112 113 114
# Initialize global variables. We use this function so that we can
# call parse_config() multiple times
def init_config_environment(
Q
qijun 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128
        g_default_momentum=None,
        g_default_decay_rate=None,
        g_default_initial_mean=0.,
        g_default_initial_std=0.01,
        g_default_num_batches_regularization=None,
        g_default_initial_strategy=0,
        g_default_initial_smart=False,
        g_default_gradient_clipping_threshold=None,
        g_default_device=None,
        g_default_update_hooks=None,
        g_default_compact_func=None,
        g_config=TrainerConfig(),
        g_layer_map={},
        g_parameter_map={},
X
xuwei06 已提交
129
        g_parameter_initializer_map={},
Q
qijun 已提交
130
        g_extended_config_funcs={},
Z
zhangjinchao01 已提交
131 132

        # store command args of paddle_trainer
Q
qijun 已提交
133
        g_command_config_args={},
Z
zhangjinchao01 已提交
134 135

        # Used for PyDataProvider to avoid duplicate module name
Q
qijun 已提交
136 137 138 139 140
        g_py_module_name_list=[],
        g_current_submodel=None,
        g_root_submodel=None,
        g_submodel_map={},
        g_submodel_stack=[],
141
        g_add_submodel_suffix=False, ):
Z
zhangjinchao01 已提交
142

X
Xi Chen 已提交
143 144 145 146 147 148 149
    # directly iterate through locals().iteritems() will change
    # the size of locals() due to introducting k, v into scope
    # which will break the process in some env

    local_vars = copy.deepcopy(locals())
    for k, v in local_vars.iteritems():
        globals()[k] = v
Z
zhangjinchao01 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162


# Because type is widely used as a variable name in this code.
# we need a different function name for the builtin type()
def type_of(x):
    return type(x)


# Check a condition derived config file
def config_assert(b, msg):
    if not b:
        logger.fatal(msg)

Q
qijun 已提交
163

Z
zhangjinchao01 已提交
164 165
g_config_funcs = {}

Q
qijun 已提交
166

Z
zhangjinchao01 已提交
167 168 169 170 171
# decorator for indicating a function which can be used in config file
def config_func(func):
    g_config_funcs[func.func_name] = func
    return func

Q
qijun 已提交
172

Z
zhangjinchao01 已提交
173 174 175 176 177
# decorator for indicating a class which can be used in config file
def config_class(cls):
    g_config_funcs[cls.__name__] = cls
    return cls

Q
qijun 已提交
178

Z
zhangjinchao01 已提交
179 180 181 182 183 184
# decorator for indicating a class for a layer type
def config_layer(layer_type):
    def wrap(cls):
        g_config_funcs[cls.__name__] = cls
        g_layer_type_map[layer_type] = cls
        return cls
Q
qijun 已提交
185

Z
zhangjinchao01 已提交
186 187
    return wrap

Q
qijun 已提交
188

Z
zhangjinchao01 已提交
189 190 191
def gen_parameter_name(layer_name, input_index):
    return '_%s.w%d' % (layer_name, input_index)

Q
qijun 已提交
192

Z
zhangjinchao01 已提交
193 194 195
def gen_bias_parameter_name(layer_name):
    return '_%s.wbias' % layer_name

Q
qijun 已提交
196

Z
zhangjinchao01 已提交
197 198 199
def default(x, default_value):
    return default_value if x is None else x

Q
qijun 已提交
200

Z
zhangjinchao01 已提交
201 202 203 204 205 206
class Cfg(object):
    def add_keys(self, locals):
        for k, v in locals.iteritems():
            if not k.startswith('_'):
                self.__setattr__(k, v)

Q
qijun 已提交
207

Z
zhangjinchao01 已提交
208 209
# functions available in config file

Q
qijun 已提交
210

Z
zhangjinchao01 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
# Define the name of the input layers of the NeuralNetwork.
# The type of these layers must be "data".
# These layers will be provided with the DataBatch obtained
# from DataProvider. The data streams from DataProvider must
# have the same order.
@config_func
def Inputs(*args):
    for name in args:
        name = MakeLayerNameInSubmodel(name)
        global g_current_submodel, g_root_submodel
        if g_current_submodel.is_recurrent_layer_group:
            config_assert(False, "Do not set Inputs in recurrent layer group")
        else:
            g_current_submodel.input_layer_names.append(name)

        if g_current_submodel is g_root_submodel:
            g_config.model_config.input_layer_names.append(name)

Q
qijun 已提交
229

230 231
@config_func
def HasInputsSet():
232
    return len(g_current_submodel.input_layer_names) != 0
233

Z
zhangjinchao01 已提交
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257

# Define the name of the output layers of the NeuralNetwork.
# Usually the output is simply the cost layer.
# You can specify other layers as outputs and calculate the
# cost (and its derivative) yourself.
@config_func
def Outputs(*args):
    for name in args:
        name = MakeLayerNameInSubmodel(name)
        global g_current_submodel, g_root_submodel
        if g_current_submodel.is_recurrent_layer_group:
            config_assert(False, "Do not set Outputs in recurrent layer group")
        else:
            g_current_submodel.output_layer_names.append(name)

        if g_current_submodel is g_root_submodel:
            g_config.model_config.output_layer_names.append(name)


@config_func
def SubModelBegin(name):
    global g_current_submodel, g_root_submodel, g_submodel_stack
    g_submodel_stack.append(g_current_submodel)

Q
qijun 已提交
258
    name = MakeLayerNameInParentSubmodel(name)  #rename in nested submodel
Z
zhangjinchao01 已提交
259 260 261 262 263 264 265 266 267

    config_assert(name not in g_submodel_map,
                  'Duplicated submodel name: %s' % name)

    sub_model = g_config.model_config.sub_models.add()
    sub_model.name = name
    g_submodel_map[name] = sub_model
    g_current_submodel = sub_model

Q
qijun 已提交
268

Z
zhangjinchao01 已提交
269
@config_func
Q
qijun 已提交
270
def SubModelEnd(name=None):
Z
zhangjinchao01 已提交
271
    global g_current_submodel, g_root_submodel, g_submodel_stack
Q
qijun 已提交
272 273
    config_assert(g_current_submodel is not g_root_submodel,
                  "submodel not begin")
Z
zhangjinchao01 已提交
274
    if name is not None:
Q
qijun 已提交
275 276 277
        config_assert(
            g_current_submodel.name == MakeLayerNameInParentSubmodel(name),
            "submodel name error")
Z
zhangjinchao01 已提交
278 279 280

    g_current_submodel = g_submodel_stack.pop()

Q
qijun 已提交
281

Z
zhangjinchao01 已提交
282 283
def MakeLayerNameInParentSubmodel(name):
    suffix = ""
284 285
    if len(g_submodel_stack) > 1:
        suffix = "@" + g_submodel_stack[-1].name
Z
zhangjinchao01 已提交
286 287
    return name + suffix

Q
qijun 已提交
288

Z
zhangjinchao01 已提交
289 290 291
def GetLayerBaseName(name):
    return name.split('@')[0]

Q
qijun 已提交
292 293

def MakeLayerNameInSubmodel(name, submodel_name=None):
Z
zhangjinchao01 已提交
294 295
    global g_current_submodel
    global g_add_submodel_suffix
Q
qijun 已提交
296 297
    if (submodel_name is None and not g_add_submodel_suffix and
            not g_current_submodel.is_recurrent_layer_group):
Z
zhangjinchao01 已提交
298 299 300 301 302
        return name
    if submodel_name is None:
        submodel_name = g_current_submodel.name
    return name + "@" + submodel_name

Q
qijun 已提交
303

Z
zhangjinchao01 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
# Define a recurrent layer group begin with RecurrentLayerGroupBegin
# and end with RecurrentLayerGroupEnd.
# A recurrent layer group forward/backward one frame after previous frame
# forward/backward through all layers in layer group.
# in_links are names of layer used as input layer in the layer group.
# out_links are names of layer in layer group used as outside layer's input.
#
# If generator is set, the layer group need one or more than one outlinks.
# The first outlink should always be the generated token ids.
# If generator.num_results_per_sample is not set, the output for one sample is
# a ids sequence. Else if num_results_per_sample is more than one,
# the output for one sample is up to #num_results_per_sample generated
# sequences, which are packed in one sequence in output ids vector. Each
# generated sequence has a generation probability. The probabilities for one
# sample are stored in one row of output value matrix.
# Packed generated sequences format, for each i:
#   seq_i_length: one interger, seq_i content length,
#   [seq_i content], length = seq_i_length
#   seq_i_end_mark: one interger, for format check, always -1
# You can use "seq_text_printer" to print the output of the generator.
@config_func
def RecurrentLayerGroupWithoutOutLinksBegin(name,
                                            in_links,
327 328
                                            seq_reversed=False,
                                            target_inlinkname=""):
Z
zhangjinchao01 已提交
329 330 331 332 333 334 335 336
    global g_current_submodel
    config_assert(g_config.model_config.type == "recurrent_nn",
                  "RecurrentLayerGroup should be used only in recurrent_nn")
    RecurrentLayerGroup(name=name)  # add to father model
    SubModelBegin(name)
    g_current_submodel.is_recurrent_layer_group = True
    g_current_submodel.reversed = seq_reversed
    in_links_count = 0
337
    for linkid, link in enumerate(in_links):
Z
zhangjinchao01 已提交
338 339 340 341
        if isinstance(link, basestring):
            name = link
        else:
            name = link.link_name
342

Z
zhangjinchao01 已提交
343 344 345
        in_links_count += 1
        layer_name = MakeLayerNameInParentSubmodel(name)
        layer = g_layer_map[layer_name]
346 347
        ScatterAgentLayer(
            name=name, size=layer.size, width=layer.width, height=layer.height)
348

Z
zhangjinchao01 已提交
349 350 351 352
        pair = g_current_submodel.in_links.add()
        pair.layer_name = layer_name
        pair.link_name = MakeLayerNameInSubmodel(name)

Q
qijun 已提交
353

Z
zhangjinchao01 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366
@config_func
def RecurrentLayerGroupSetOutLink(link):
    if isinstance(link, basestring):
        name = link
    else:
        name = link.link_name
    layer_name = MakeLayerNameInParentSubmodel(name)
    pair = g_current_submodel.out_links.add()
    pair.layer_name = MakeLayerNameInSubmodel(name)
    pair.link_name = layer_name


def RecurrentLayerGroupSetGenerator(generator=None):
Q
qijun 已提交
367
    generator.eos_layer_name = MakeLayerNameInSubmodel(generator.eos_layer_name)
Z
zhangjinchao01 已提交
368 369 370 371 372 373 374 375
    g_current_submodel.generator.CopyFrom(generator)


@config_func
def RecurrentLayerGroupBegin(name,
                             in_links,
                             out_links,
                             generator=None,
376
                             target_inlinkname="",
Z
zhangjinchao01 已提交
377
                             seq_reversed=False):
378
    RecurrentLayerGroupWithoutOutLinksBegin(name, in_links, seq_reversed)
Z
zhangjinchao01 已提交
379 380 381 382 383
    for link in out_links:
        RecurrentLayerGroupSetOutLink(link)

    if generator is not None:
        RecurrentLayerGroupSetGenerator(generator)
Q
qijun 已提交
384 385 386 387 388
        config_assert(
            len(in_links) == 0, "no in_links should be passed to generator")
        config_assert(
            len(out_links) >= 1,
            "one or more than one out_links should be passed to generator")
Z
zhangjinchao01 已提交
389 390 391 392 393 394 395


@config_func
def RecurrentLayerGroupEnd(name):
    global g_current_submodel
    config_assert(g_current_submodel.is_recurrent_layer_group,
                  "RecurrentLayerGroup not begin")
Q
qijun 已提交
396
    for pair in g_current_submodel.memories:  #check exist
Z
zhangjinchao01 已提交
397
        layer = g_layer_map[pair.layer_name]
Y
Yu Yang 已提交
398 399
        config_assert(layer is not None,
                      "memory declare wrong name:%s" % pair.layer_name)
Z
zhangjinchao01 已提交
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
        memory_link = g_layer_map[pair.link_name]
        config_assert(layer.size == memory_link.size,
                      "memory declare wrong size:%d" % memory_link.size)

    prev_submodel = g_current_submodel
    SubModelEnd(name)

    for pair in prev_submodel.out_links:
        layer = g_layer_map[pair.layer_name]
        # add out agent to father model
        agent_name = GetLayerBaseName(pair.link_name)
        if prev_submodel.HasField("generator"):
            DataLayer(name=agent_name, size=layer.size)
        else:
            GatherAgentLayer(name=agent_name, size=layer.size)

Q
qijun 已提交
416

Z
zhangjinchao01 已提交
417 418 419 420 421 422
# Define the model type
# currently, the paddle supports "nn", "recurrent_nn", "recursive_nn" and "multi_nn"
@config_func
def model_type(name):
    g_config.model_config.type = name

Q
qijun 已提交
423

Z
zhangjinchao01 已提交
424 425
@config_class
class Bias(Cfg):
X
xuwei06 已提交
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
    def __init__(self,
                 parameter_name=None,
                 learning_rate=None,
                 momentum=None,
                 decay_rate=None,
                 decay_rate_l1=None,
                 initial_mean=None,
                 initial_std=None,
                 initial_strategy=None,
                 initial_smart=None,
                 num_batches_regularization=None,
                 sparse_remote_update=None,
                 gradient_clipping_threshold=None,
                 is_static=None,
                 is_shared=None,
                 initializer=None):
Z
zhangjinchao01 已提交
442 443
        self.add_keys(locals())

Q
qijun 已提交
444

Z
zhangjinchao01 已提交
445 446 447 448 449 450 451
# Define one input for a layer
@config_class
class Input(Cfg):
    def __init__(
            self,
            input_layer_name,
            parameter_name=None,
X
xuwei06 已提交
452
            initializer=None,
Z
zhangjinchao01 已提交
453 454 455 456 457 458 459 460 461 462 463 464 465
            learning_rate=None,
            momentum=None,
            decay_rate=None,
            decay_rate_l1=None,
            initial_mean=None,
            initial_std=None,
            initial_strategy=None,
            initial_smart=None,
            num_batches_regularization=None,
            sparse_remote_update=None,
            sparse_update=None,
            gradient_clipping_threshold=None,
            conv=None,
L
liaogang 已提交
466
            bilinear_interp=None,
Z
zhangjinchao01 已提交
467 468 469 470
            norm=None,
            pool=None,
            image=None,
            block_expand=None,
471
            maxout=None,
Q
qijun 已提交
472
            spp=None,
D
dangqingqing 已提交
473
            pad=None,
Z
zhangjinchao01 已提交
474 475 476 477 478
            format=None,
            nnz=None,
            is_static=None,
            is_shared=None,
            update_hooks=None,
479
            input_layer_argument=None,
D
dangqingqing 已提交
480 481 482 483 484
            make_layer_name_in_submodel=True, ):
        """
        @param make_layer_name_in_submodel True by defalut, you might need to
        set it carefully when adding Input in config_parser.py.
        """
Z
zhangjinchao01 已提交
485
        self.add_keys(locals())
D
dangqingqing 已提交
486 487 488
        self.input_layer_name = MakeLayerNameInSubmodel(
            input_layer_name
        ) if make_layer_name_in_submodel else input_layer_name
Z
zhangjinchao01 已提交
489

Q
qijun 已提交
490

Z
zhangjinchao01 已提交
491 492 493
# Define a projection for iexed layer
@config_class
class Projection(Input):
Q
qijun 已提交
494 495
    type = None  # subclass should set it correctly

Z
zhangjinchao01 已提交
496 497 498
    def __init__(
            self,
            input_layer_name,
Q
qijun 已提交
499
            size=0,  # projection output size
Z
zhangjinchao01 已提交
500 501 502 503 504 505 506 507 508
            parameter_name=None,
            learning_rate=None,
            momentum=None,
            decay_rate=None,
            decay_rate_l1=None,
            initial_mean=None,
            initial_std=None,
            initial_strategy=None,
            initial_smart=None,
X
xuwei06 已提交
509
            initializer=None,
Z
zhangjinchao01 已提交
510 511 512 513 514 515 516 517 518 519
            num_batches_regularization=None,
            sparse_remote_update=None,
            sparse_update=None,
            gradient_clipping_threshold=None,
            ptype=None,
            format=None,
            nnz=None,
            is_static=None,
            is_shared=None,
            update_hooks=None,
Q
qijun 已提交
520
            input_layer_argument=None, ):
Z
zhangjinchao01 已提交
521 522 523 524 525 526 527 528 529 530 531 532 533
        self.add_keys(locals())
        self.input_layer_name = MakeLayerNameInSubmodel(input_layer_name)

        self.proj_conf = ProjectionConfig()
        if ptype is not None:
            self.proj_conf.type = ptype
        else:
            self.proj_conf.type = self.type

    # calculate the output_size given input_size. return 0
    # to indicate using the size from Layer config
    def calc_output_size(self, input_layer_config):
        return self.size
Q
qijun 已提交
534

Z
zhangjinchao01 已提交
535 536
    def calc_parameter_size(self, input_size, output_size):
        raise NotimplementedError
Q
qijun 已提交
537

Z
zhangjinchao01 已提交
538 539 540 541 542 543 544 545 546 547
    def calc_parameter_dims(self, input_size, output_size):
        raise NotimplementedError


@config_class
class IdentityProjection(Projection):
    type = 'identity'

    def calc_output_size(self, input_layer_config):
        return input_layer_config.size
Q
qijun 已提交
548

Z
zhangjinchao01 已提交
549 550
    def calc_parameter_size(self, input_size, output_size):
        return 0
Q
qijun 已提交
551

Z
zhangjinchao01 已提交
552 553 554
    def calc_parameter_dims(self, input_size, output_size):
        return []

Q
qijun 已提交
555

Z
zhangjinchao01 已提交
556 557 558 559 560 561
# Like IdentityProjection, but layer size may smaller than input size,
# the projection select dimesions [offset, offset+layer_size) from input
@config_class
class IdentityOffsetProjection(Projection):
    type = 'identity_offset'

Q
qijun 已提交
562 563 564
    def __init__(self, input_layer_name, offset, **xargs):
        super(IdentityOffsetProjection, self).__init__(input_layer_name,
                                                       **xargs)
Z
zhangjinchao01 已提交
565 566
        self.proj_conf.offset = offset

567 568 569
    def calc_output_size(self, input_layer_config):
        return 0  # depends on the outside MixedLayer

Z
zhangjinchao01 已提交
570 571
    def calc_parameter_size(self, input_size, output_size):
        return 0
Q
qijun 已提交
572

Z
zhangjinchao01 已提交
573 574 575
    def calc_parameter_dims(self, input_size, output_size):
        return []

Q
qijun 已提交
576

577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
@config_class
class SliceProjection(Projection):
    type = 'slice'

    def __init__(self, input_layer_name, slices, **xargs):
        super(SliceProjection, self).__init__(input_layer_name, **xargs)
        input = g_layer_map[input_layer_name]
        if input.type in ["exconv", "cudnn_conv"]:
            # the slice operator is for the channel dimension
            assert input.num_filters is not None
            channels = input.num_filters
            image_size = input.size / channels
            assert slices[len(slices) - 1][1] <= channels
            for i in xrange(len(slices)):
                slice = self.proj_conf.slices.add()
                slice.start = slices[i][0] * image_size
                slice.end = slices[i][1] * image_size
                self.size += slice.end - slice.start
        else:
            config_assert(False,
                          'Currently the input should be convolution layer')

    def calc_parameter_size(self, input_size, output_size):
        return 0

    def calc_parameter_dims(self, input_size, output_size):
        return []


Z
zhangjinchao01 已提交
606 607 608 609 610 611 612
# DotMulProjection performs element-wise multiplication with weight
@config_class
class DotMulProjection(Projection):
    type = 'dot_mul'

    def calc_output_size(self, input_layer_config):
        return input_layer_config.size
Q
qijun 已提交
613

Z
zhangjinchao01 已提交
614 615
    def calc_parameter_size(self, input_size, output_size):
        return output_size
Q
qijun 已提交
616

Z
zhangjinchao01 已提交
617 618 619
    def calc_parameter_dims(self, input_size, output_size):
        return [1, output_size]

L
Luo Tao 已提交
620

X
xuwei06 已提交
621 622 623 624 625 626 627 628 629 630 631 632 633 634
# ScalingProjection
@config_class
class ScalingProjection(Projection):
    type = 'scaling'

    def calc_output_size(self, input_layer_config):
        return input_layer_config.size

    def calc_parameter_size(self, input_size, output_size):
        return 1

    def calc_parameter_dims(self, input_size, output_size):
        return [1, 1]

Q
qijun 已提交
635

Z
zhangjinchao01 已提交
636 637 638 639 640 641
@config_class
class TableProjection(Projection):
    type = 'table'

    def calc_parameter_size(self, input_size, output_size):
        return input_size * output_size
Q
qijun 已提交
642

Z
zhangjinchao01 已提交
643 644 645
    def calc_parameter_dims(self, input_size, output_size):
        return [input_size, output_size]

Q
qijun 已提交
646

Z
zhangjinchao01 已提交
647 648 649 650 651 652
@config_class
class FullMatrixProjection(Projection):
    type = 'fc'

    def calc_parameter_size(self, input_size, output_size):
        return input_size * output_size
Q
qijun 已提交
653

Z
zhangjinchao01 已提交
654 655 656
    def calc_parameter_dims(self, input_size, output_size):
        return [input_size, output_size]

Q
qijun 已提交
657

Z
zhangjinchao01 已提交
658 659 660 661 662 663
@config_class
class TransposedFullMatrixProjection(Projection):
    type = 'trans_fc'

    def calc_parameter_size(self, input_size, output_size):
        return input_size * output_size
Q
qijun 已提交
664

Z
zhangjinchao01 已提交
665 666 667
    def calc_parameter_dims(self, input_size, output_size):
        return [output_size, input_size]

Q
qijun 已提交
668

Z
zhangjinchao01 已提交
669 670 671 672
@config_class
class ContextProjection(Projection):
    type = 'context'

Q
qijun 已提交
673 674
    def __init__(self, input_layer_name, context_start, context_length,
                 trainable_padding, **xargs):
Z
zhangjinchao01 已提交
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
        super(ContextProjection, self).__init__(input_layer_name, **xargs)
        self.proj_conf.context_start = context_start
        self.proj_conf.context_length = context_length
        self.proj_conf.trainable_padding = trainable_padding
        self._total_pad = max(0, -self.proj_conf.context_start) \
                          + max(0, self.proj_conf.context_start \
                                + self.proj_conf.context_length - 1)

    def calc_output_size(self, input_layer_config):
        return input_layer_config.size * self.proj_conf.context_length

    def calc_parameter_size(self, input_size, output_size):
        if self.proj_conf.trainable_padding == False:
            return 0
        else:
            return input_size * self._total_pad

    def calc_parameter_dims(self, input_size, output_size):
        return [self._total_pad, input_size]

    _total_pad = 0


698
@config_class
699
class ConvBaseProjection(Projection):
Q
qijun 已提交
700 701 702 703 704
    def __init__(self,
                 input_layer_name,
                 num_filters=None,
                 conv_conf=None,
                 **xargs):
705
        super(ConvBaseProjection, self).__init__(input_layer_name, **xargs)
706 707 708 709 710 711 712 713 714 715 716 717

        if num_filters is not None:
            self.proj_conf.num_filters = num_filters

    def calc_output_size(self, input_layer_config):
        return self.proj_conf.output_size

    def calc_parameter_size(self, input_size, output_size):
        co = self.proj_conf.num_filters
        ci = self.proj_conf.conv_conf.channels
        fh = self.proj_conf.conv_conf.filter_size
        fw = self.proj_conf.conv_conf.filter_size_y
718 719
        gr = self.proj_conf.conv_conf.groups
        return co * ci * fh * fw / gr
720 721 722 723 724 725 726

    def calc_bias_size(self):
        return self.proj_conf.num_filters

    def calc_parameter_dims(self, input_size, output_size):
        return None

Q
qijun 已提交
727

728 729 730 731 732 733 734 735 736
@config_class
class ConvProjection(ConvBaseProjection):
    type = 'conv'

    def __init__(self,
                 input_layer_name,
                 num_filters=None,
                 conv_conf=None,
                 **xargs):
737 738
        super(ConvProjection, self).__init__(input_layer_name, num_filters,
                                             conv_conf, **xargs)
739

740
        parse_conv(conv_conf, self.input_layer_name, self.proj_conf.conv_conf,
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
                   num_filters)
        self.proj_conf.output_size = self.proj_conf.conv_conf.output_x * \
                                     self.proj_conf.conv_conf.output_y * \
                                     num_filters


@config_class
class ConvTransProjection(ConvBaseProjection):
    type = 'convt'

    def __init__(self,
                 input_layer_name,
                 num_filters=None,
                 conv_conf=None,
                 **xargs):
756 757
        super(ConvTransProjection, self).__init__(input_layer_name, num_filters,
                                                  conv_conf, **xargs)
758 759 760

        parse_conv(
            conv_conf,
761
            self.input_layer_name,
762 763 764 765 766 767 768 769
            self.proj_conf.conv_conf,
            num_filters,
            trans=True)
        self.proj_conf.output_size = self.proj_conf.conv_conf.img_size_y * \
                                     self.proj_conf.conv_conf.img_size * \
                                     num_filters


Z
zhangjinchao01 已提交
770 771 772
# Define a operator for mixed layer
@config_class
class Operator(Cfg):
Q
qijun 已提交
773 774
    type = None  # subclass should set it correctly

Z
zhangjinchao01 已提交
775 776
    def __init__(
            self,
Q
qijun 已提交
777
            input_layer_names, ):
Z
zhangjinchao01 已提交
778 779 780 781 782 783 784 785 786 787
        self.add_keys(locals())
        self.operator_conf = OperatorConfig()
        self.operator_conf.type = self.type

    def check_dims(self):
        pass

    def calc_output_size(self, input_sizes):
        return 0

Q
qijun 已提交
788

Z
zhangjinchao01 已提交
789 790 791
@config_class
class DotMulOperator(Operator):
    type = 'dot_mul'
Q
qijun 已提交
792 793 794

    def __init__(self, input_layer_names, scale=None, **xargs):
        super(DotMulOperator, self).__init__(input_layer_names, **xargs)
Z
zhangjinchao01 已提交
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
        if scale is not None:
            self.operator_conf.dotmul_scale = scale

        config_assert(len(input_layer_names) == 2, "DotMul is binary operator")

    def check_dims(self):
        for i in range(2):
            config_assert(self.operator_conf.input_sizes[i] ==
                          self.operator_conf.output_size,
                          "DotMul input_size != output_size")

    def calc_output_size(self, input_sizes):
        return input_sizes[0]


@config_class
class ConvOperator(Operator):
    type = 'conv'
Q
qijun 已提交
813 814 815 816 817 818 819

    def __init__(self,
                 input_layer_names,
                 num_filters=None,
                 conv_conf=None,
                 **xargs):
        super(ConvOperator, self).__init__(input_layer_names, **xargs)
Z
zhangjinchao01 已提交
820 821 822
        if num_filters is not None:
            self.operator_conf.num_filters = num_filters

823 824
        parse_conv(conv_conf,
                   MakeLayerNameInSubmodel(input_layer_names[0]),
Q
qijun 已提交
825
                   self.operator_conf.conv_conf, num_filters)
L
Luo Tao 已提交
826 827 828
        self.operator_conf.output_size = self.operator_conf.conv_conf.output_x * \
                                         self.operator_conf.conv_conf.output_y * \
                                         num_filters
Z
zhangjinchao01 已提交
829 830 831

        config_assert(len(input_layer_names) == 2, "Conv is binary operator")

832 833
    def calc_output_size(self, input_sizes):
        return self.operator_conf.output_size
Z
zhangjinchao01 已提交
834 835


836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
@config_class
class ConvTransOperator(Operator):
    type = 'convt'

    def __init__(self,
                 input_layer_names,
                 num_filters=None,
                 conv_conf=None,
                 **xargs):
        super(ConvTransOperator, self).__init__(input_layer_names, **xargs)
        if num_filters is not None:
            self.operator_conf.num_filters = num_filters

        parse_conv(
            conv_conf,
            MakeLayerNameInSubmodel(input_layer_names[0]),
            self.operator_conf.conv_conf,
            num_filters,
            trans=True)
        self.operator_conf.output_size = \
            self.operator_conf.conv_conf.img_size * \
            self.operator_conf.conv_conf.img_size_y * \
            num_filters

        config_assert(len(input_layer_names) == 2, "Conv is binary operator")

    def calc_output_size(self, input_sizes):
        return self.operator_conf.output_size


Z
zhangjinchao01 已提交
866 867 868
# please refer to the comments in proto/ModelConfig.proto
@config_class
class Conv(Cfg):
Q
qijun 已提交
869 870 871 872 873 874 875 876 877 878 879 880
    def __init__(self,
                 filter_size,
                 channels,
                 padding=None,
                 stride=None,
                 groups=None,
                 filter_channels=None,
                 output_x=None,
                 img_size=None,
                 caffe_mode=True,
                 filter_size_y=None,
                 padding_y=None,
W
wanghaoshuang 已提交
881 882 883
                 stride_y=None,
                 dilation=None,
                 dilation_y=None):
Z
zhangjinchao01 已提交
884 885
        self.add_keys(locals())
        if filter_size_y is None:
Q
qijun 已提交
886
            self.filter_size_y = filter_size
Z
zhangjinchao01 已提交
887
        if padding_y is None:
Q
qijun 已提交
888
            self.padding_y = padding
889 890
        if dilation_y is None:
            self.dilation_y = dilation
Z
zhangjinchao01 已提交
891
        if stride_y is None:
Q
qijun 已提交
892
            self.stride_y = stride
Z
zhangjinchao01 已提交
893
        if output_x is not None:
Q
qijun 已提交
894 895
            config_assert(output_x <= 0)

Z
zhangjinchao01 已提交
896

897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
# please refer to the comments in proto/ModelConfig.proto
@config_class
class Conv3D(Cfg):
    def __init__(self,
                 filter_size,
                 channels,
                 padding=None,
                 stride=None,
                 groups=None,
                 filter_channels=None,
                 output_x=None,
                 img_size=None,
                 caffe_mode=True,
                 filter_size_y=None,
                 padding_y=None,
                 stride_y=None,
                 filter_size_z=None,
                 padding_z=None,
                 stride_z=None):
        self.add_keys(locals())
C
chengduoZH 已提交
917 918 919 920 921 922
        self.filter_size_y = filter_size_y if filter_size_y else filter_size
        self.filter_size_z = filter_size_z if filter_size_z else filter_size
        self.padding_y = padding_y if padding_y else padding
        self.padding_z = padding_z if padding_z else padding
        self.stride_y = stride_y if stride_y else stride
        self.stride_z = stride_z if stride_z else stride
923 924 925 926
        if output_x is not None:
            config_assert(output_x <= 0)


L
liaogang 已提交
927 928
@config_class
class BilinearInterp(Cfg):
L
Luo Tao 已提交
929
    def __init__(self, out_size_x=None, out_size_y=None, channels=None):
L
liaogang 已提交
930 931
        self.add_keys(locals())

Q
qijun 已提交
932

Z
zhangjinchao01 已提交
933 934
@config_class
class Pool(Cfg):
D
dangqingqing 已提交
935 936 937 938 939 940 941 942 943 944 945
    def __init__(
            self,
            pool_type,
            channels,
            size_x,
            size_y=None,
            start=None,
            stride=None,  # 1 by defalut in protobuf
            stride_y=None,
            padding=None,  # 0 by defalut in protobuf
            padding_y=None):
Z
zhangjinchao01 已提交
946
        self.add_keys(locals())
Q
qijun 已提交
947 948


C
chengduoZH 已提交
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
@config_class
class Pool3d(Cfg):
    def __init__(
            self,
            pool_type,
            channels,
            size_x,
            size_y=None,
            size_z=None,
            start=None,
            stride=None,  # 1 by defalut in protobuf
            stride_y=None,
            stride_z=None,
            padding=None,  # 0 by defalut in protobuf
            padding_y=None,
            padding_z=None):
        self.add_keys(locals())
        self.filter_size_y = size_y if size_y else size_x
        self.filter_size_z = size_z if size_z else size_x
        self.padding_y = padding_y if padding_y else padding
        self.padding_z = padding_z if padding_z else padding
        self.stride_y = stride_y if stride_y else stride
        self.stride_z = stride_z if stride_z else stride


Q
qijun 已提交
974
@config_class
Q
qijun 已提交
975
class SpatialPyramidPool(Cfg):
L
Luo Tao 已提交
976
    def __init__(self, pool_type, pyramid_height, channels):
Q
qijun 已提交
977
        self.add_keys(locals())
Z
zhangjinchao01 已提交
978

Q
qijun 已提交
979

D
dangqingqing 已提交
980 981 982 983 984 985
@config_class
class Pad(Cfg):
    def __init__(self, channels, pad_c, pad_h, pad_w):
        self.add_keys(locals())


Z
zhangjinchao01 已提交
986 987
@config_class
class Norm(Cfg):
Q
qijun 已提交
988 989 990 991 992 993 994 995 996
    def __init__(self,
                 norm_type,
                 channels,
                 size,
                 scale,
                 pow,
                 output_x=None,
                 img_size=None,
                 blocked=None):
Z
zhangjinchao01 已提交
997 998
        self.add_keys(locals())

Q
qijun 已提交
999

Z
zhangjinchao01 已提交
1000 1001
@config_class
class Image(Cfg):
Q
qijun 已提交
1002
    def __init__(self, channels, img_size=None):
Z
zhangjinchao01 已提交
1003 1004
        self.add_keys(locals())

Q
qijun 已提交
1005

Z
zhangjinchao01 已提交
1006 1007
@config_class
class BlockExpand(Cfg):
Q
qijun 已提交
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    def __init__(self,
                 channels,
                 padding_x=0,
                 padding_y=0,
                 stride_x=0,
                 stride_y=0,
                 block_x=0,
                 block_y=0,
                 img_size_x=0,
                 img_size_y=0,
                 output_x=0,
                 output_y=0):
Z
zhangjinchao01 已提交
1020 1021
        self.add_keys(locals())

Q
qijun 已提交
1022

1023 1024
@config_class
class MaxOut(Cfg):
Q
qijun 已提交
1025
    def __init__(self, channels, groups, img_size_x=0, img_size_y=0):
1026 1027
        self.add_keys(locals())

Q
qijun 已提交
1028

1029
def create_data_config_proto(async_load_data=False,
1030
                             constant_slots=None,
王益 已提交
1031 1032 1033
                             data_ratio=1,
                             is_main_data=True,
                             usage_ratio=None):
Z
zhangjinchao01 已提交
1034 1035 1036 1037 1038 1039 1040 1041
    # default: all sub dataproviders are treat as "main data".
    # see proto/DataConfig.proto for is_main_data
    data_config = DataConfig()

    data_config.async_load_data = async_load_data

    if constant_slots:
        data_config.constant_slots.extend(constant_slots)
Q
qijun 已提交
1042 1043
    data_config.data_ratio = data_ratio
    data_config.is_main_data = is_main_data
Z
zhangjinchao01 已提交
1044

Q
qijun 已提交
1045
    usage_ratio = default(usage_ratio, settings_deprecated["usage_ratio"])
Z
zhangjinchao01 已提交
1046 1047 1048 1049 1050 1051
    config_assert(usage_ratio >= 0 and usage_ratio <= 1,
                  "The range of usage_ratio is [0, 1]")
    data_config.usage_ratio = usage_ratio

    return data_config

Q
qijun 已提交
1052

Z
zhangjinchao01 已提交
1053
@config_func
Q
qijun 已提交
1054 1055 1056 1057 1058
def SimpleData(files=None,
               feat_dim=None,
               context_len=None,
               buffer_capacity=None,
               **xargs):
1059
    data_config = create_data_config_proto(**xargs)
Z
zhangjinchao01 已提交
1060 1061 1062 1063 1064 1065 1066 1067 1068
    data_config.type = 'simple'
    data_config.files = files
    data_config.feat_dim = feat_dim
    if context_len is not None:
        data_config.context_len = context_len
    if buffer_capacity:
        data_config.buffer_capacity = buffer_capacity
    return data_config

Q
qijun 已提交
1069

Z
zhangjinchao01 已提交
1070
@config_func
Q
qijun 已提交
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
def PyData(files=None,
           type=None,
           file_group_queue_capacity=None,
           load_data_module=None,
           load_data_object=None,
           load_data_args="",
           load_file_count=None,
           constant_slots=None,
           load_thread_num=None,
           **xargs):
1081
    data_config = create_data_config_proto(**xargs)
Z
zhangjinchao01 已提交
1082 1083
    data_config.type = 'py'
    if load_data_module in g_py_module_name_list:
Q
qijun 已提交
1084

Z
zhangjinchao01 已提交
1085 1086 1087
        def get_path(module):
            m = __import__(load_data_module)
            return os.path.split(os.path.realpath(m.__file__))[0]
Q
qijun 已提交
1088

Z
zhangjinchao01 已提交
1089 1090 1091
        # python C-api is not thread safe, one module can only be import once,
        # so here we nedd to copy the module with different names if it has to be
        # imported several times.
Q
qijun 已提交
1092 1093
        module_new_name = "%s_copy_%d" % (load_data_module,
                                          len(g_py_module_name_list))
Z
zhangjinchao01 已提交
1094
        g_py_module_name_list.append(module_new_name)
Q
qijun 已提交
1095 1096 1097 1098
        module_path = "%s/%s.py" % (get_path(load_data_module),
                                    load_data_module)
        new_module_path = "%s/%s.py" % (get_path(load_data_module),
                                        module_new_name)
Z
zhangjinchao01 已提交
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
        if os.path.isfile(module_path) == False:
            raise Exception("File %s is not exist." % module_path)
        shutil.copy2(module_path, new_module_path)
        load_data_module = module_new_name
    else:
        g_py_module_name_list.append(load_data_module)
    if load_data_module is not None and load_data_object is not None:
        data_config.load_data_module = load_data_module
        data_config.load_data_object = load_data_object
    else:
        raise ValueError('load_data_module, load_data_object is not defined.')
    data_config.load_data_args = load_data_args

    data_config.files = files or ''
    if file_group_queue_capacity is not None:
        data_config.file_group_conf.queue_capacity = file_group_queue_capacity
    if load_file_count is not None:
        data_config.file_group_conf.load_file_count = load_file_count
    if load_thread_num is not None:
        data_config.file_group_conf.load_thread_num = load_thread_num
    if constant_slots:
        data_config.constant_slots.extend(constant_slots)
    return data_config

Q
qijun 已提交
1123

Z
zhangjinchao01 已提交
1124 1125
#real data for training is actually provided by "sub_data" data providers.
@config_func
Q
qijun 已提交
1126
def MultiData(sub_data=[]):
Z
zhangjinchao01 已提交
1127 1128 1129 1130 1131
    data_config = DataConfig()
    data_config.type = 'multi'
    data_config.sub_data_configs.extend(sub_data)
    return data_config

Q
qijun 已提交
1132

Z
zhangjinchao01 已提交
1133
@config_func
Q
qijun 已提交
1134 1135 1136 1137 1138 1139 1140
def Data(type,
         files=None,
         feat_dim=None,
         slot_dims=None,
         context_len=None,
         buffer_capacity=None,
         **xargs):
Z
zhangjinchao01 已提交
1141

1142
    data_config = create_data_config_proto(**xargs)
Z
zhangjinchao01 已提交
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
    data_config.type = type
    data_config.files = files
    data_config.feat_dim = feat_dim
    data_config.slot_dims.extend(slot_dims)
    if context_len is not None:
        data_config.context_len = context_len
    data_config.buffer_capacity = buffer_capacity
    return data_config


@config_func
def TrainData(data_config, async_load_data=None):
    config_assert(not g_config.HasField('data_config'),
                  'Only one TrainData definition is allowed')
    g_config.data_config.CopyFrom(data_config)
    g_config.data_config.for_test = False
    if async_load_data is not None:
        logger.warning("Deprecated: async_load_data should be used inside"
                       " Data definition")
        g_config.data_config.async_load_data = async_load_data


@config_func
def TestData(data_config, async_load_data=None):
    config_assert(not g_config.HasField('test_data_config'),
                  'Only one TestData definition is allowed')
    g_config.test_data_config.CopyFrom(data_config)
    g_config.test_data_config.for_test = True
    if async_load_data is not None:
        logger.warning("Deprecated: async_load_data should be used inside"
                       " Data definition")
        g_config.test_data_config.async_load_data = async_load_data

Q
qijun 已提交
1176

L
Luo Tao 已提交
1177 1178
#caffe_mode: compute the output size using floor instead of ceil,
#            which is consistent of caffe and CuDNN's convention.
X
xzl 已提交
1179 1180 1181 1182 1183 1184 1185 1186
def cnn_output_size(img_size,
                    filter_size,
                    padding,
                    stride,
                    caffe_mode,
                    dilation=1):
    filter_s = (filter_size - 1) * dilation + 1
    output = (2 * padding + img_size - filter_s) / float(stride)
1187 1188 1189 1190 1191
    if caffe_mode:
        return 1 + int(math.floor(output))
    else:
        return 1 + int(math.ceil(output))

Q
qijun 已提交
1192

1193
#calcualte image_size based on output_size for de-convolution (ConvTransLayer).
L
Luo Tao 已提交
1194
#It is the reverse function of cnn_output_size
X
xzl 已提交
1195 1196 1197 1198 1199 1200 1201 1202
def cnn_image_size(output_size,
                   filter_size,
                   padding,
                   stride,
                   caffe_mode,
                   dilation=1):
    filter_s = (filter_size - 1) * dilation + 1
    img_size = (output_size - 1) * stride + filter_s - 2 * padding
L
Luo Tao 已提交
1203 1204
    if not caffe_mode:
        img_size = img_size + 1
1205 1206
    return img_size

Q
qijun 已提交
1207

L
Luo Tao 已提交
1208
def get_img_size(input_layer_name, channels):
L
Luo Tao 已提交
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
    input = g_layer_map[input_layer_name]
    img_pixels = input.size / channels
    img_size = input.width if input.width > 0 else int(img_pixels**0.5)
    img_size_y = input.height if input.height > 0 else int(img_pixels /
                                                           img_size)
    config_assert(
        img_size * img_size_y == img_pixels,
        "Input layer %s: Incorrect input image size %d * %d for input image pixels %d"
        % (input_layer_name, img_size, img_size_y, img_pixels))
    return img_size, img_size_y


C
chengduoZH 已提交
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
def get_img3d_size(input_layer_name, channels):
    input = g_layer_map[input_layer_name]
    img_pixels = input.size / channels
    img_size = input.width
    img_size_y = input.height
    img_size_z = input.depth

    config_assert(
        img_size * img_size_y * img_size_z == img_pixels,
        "Input layer %s: Incorrect input image size %d * %d * %d for input image pixels %d"
        % (input_layer_name, img_size, img_size_y, img_size_z, img_pixels))
    return img_size, img_size_y, img_size_z


L
Luo Tao 已提交
1235 1236 1237 1238 1239 1240
def parse_bilinear(bilinear, input_layer_name, bilinear_conf):
    parse_image(bilinear, input_layer_name, bilinear_conf.image_conf)
    bilinear_conf.out_size_x = bilinear.out_size_x
    bilinear_conf.out_size_y = bilinear.out_size_y


1241
def parse_pool(pool, input_layer_name, pool_conf, ceil_mode, exclude_mode):
Z
zhangjinchao01 已提交
1242
    pool_conf.pool_type = pool.pool_type
Q
qijun 已提交
1243
    config_assert(pool.pool_type in [
X
xzl 已提交
1244 1245 1246
        'max-projection', 'avg-projection', 'max-pool-with-mask', 'cudnn-max-pool', 'cudnn-avg-pool'
    ], "pool-type %s is not in " \
              "['max-projection', 'avg-projection', 'max-pool-with-mask'," \
Q
qijun 已提交
1247
                  "'cudnn-max-pool', 'cudnn-avg-pool']" % pool.pool_type)
Z
zhangjinchao01 已提交
1248 1249 1250 1251 1252 1253

    pool_conf.channels = pool.channels
    pool_conf.size_x = pool.size_x
    pool_conf.stride = pool.stride

    pool_conf.size_y = default(pool.size_y, pool_conf.size_x)
Q
qijun 已提交
1254
    pool_conf.stride_y = default(pool.stride_y, pool_conf.stride)
Z
zhangjinchao01 已提交
1255

L
Luo Tao 已提交
1256
    pool_conf.img_size, pool_conf.img_size_y = \
L
Luo Tao 已提交
1257
        get_img_size(input_layer_name, pool.channels)
Z
zhangjinchao01 已提交
1258

1259
    config_assert(not pool.start, "start is deprecated in pooling.")
Z
zhangjinchao01 已提交
1260

1261
    if pool.padding is not None:
Z
zhangjinchao01 已提交
1262
        pool_conf.padding = pool.padding
1263
    pool_conf.padding_y = default(pool.padding_y, pool_conf.padding)
D
dangqingqing 已提交
1264 1265
    pool_conf.output_x = cnn_output_size(pool_conf.img_size, pool_conf.size_x,
                                         pool_conf.padding, pool_conf.stride,
1266
                                         not ceil_mode)
D
dangqingqing 已提交
1267 1268
    pool_conf.output_y = cnn_output_size(pool_conf.img_size_y, pool_conf.size_y,
                                         pool_conf.padding_y,
1269
                                         pool_conf.stride_y, not ceil_mode)
1270 1271
    if exclude_mode != None:
        pool_conf.exclude_mode = exclude_mode
1272

Z
zhangjinchao01 已提交
1273

C
chengduoZH 已提交
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
def parse_pool3d(pool, input_layer_name, pool_conf, ceil_mode):
    pool_conf.pool_type = pool.pool_type
    config_assert(pool.pool_type in ['max-projection', 'avg-projection'],
                  "pool-type %s is not in "
                  "['max-projection', 'avg-projection']" % pool.pool_type)

    pool_conf.channels = pool.channels

    pool_conf.size_x = pool.size_x
    pool_conf.stride = pool.stride
    pool_conf.padding = pool.padding

    pool_conf.size_y = default(pool.size_y, pool_conf.size_x)
    pool_conf.size_z = default(pool.size_z, pool_conf.size_x)
    pool_conf.stride_y = default(pool.stride_y, pool_conf.stride)
    pool_conf.stride_z = default(pool.stride_z, pool_conf.stride)
    pool_conf.padding_y = default(pool.padding_y, pool_conf.padding)
    pool_conf.padding_z = default(pool.padding_z, pool_conf.padding)

    pool_conf.img_size, pool_conf.img_size_y, pool_conf.img_size_z = \
        get_img3d_size(input_layer_name, pool.channels)

    config_assert(not pool.start, "start is deprecated in pooling.")

    if pool.padding is not None:
        pool_conf.padding = pool.padding
    pool_conf.padding_y = default(pool.padding_y, pool_conf.padding)
    pool_conf.padding_z = default(pool.padding_z, pool_conf.padding)
    pool_conf.output_x = cnn_output_size(pool_conf.img_size, pool_conf.size_x,
                                         pool_conf.padding, pool_conf.stride,
                                         not ceil_mode)
    pool_conf.output_y = cnn_output_size(pool_conf.img_size_y, pool_conf.size_y,
                                         pool_conf.padding_y,
                                         pool_conf.stride_y, not ceil_mode)
    pool_conf.output_z = cnn_output_size(pool_conf.img_size_z, pool_conf.size_z,
                                         pool_conf.padding_z,
                                         pool_conf.stride_z, not ceil_mode)


Q
qijun 已提交
1313
def parse_spp(spp, input_layer_name, spp_conf):
L
Luo Tao 已提交
1314
    parse_image(spp, input_layer_name, spp_conf.image_conf)
Q
qijun 已提交
1315 1316
    spp_conf.pool_type = spp.pool_type
    config_assert(spp.pool_type in ['max-projection', 'avg-projection'],
Q
qijun 已提交
1317 1318
                  "pool-type %s is not in "
                  "['max-projection', 'avg-projection']" % spp.pool_type)
Q
qijun 已提交
1319
    spp_conf.pyramid_height = spp.pyramid_height
Q
qijun 已提交
1320

Q
qijun 已提交
1321

Z
zhangjinchao01 已提交
1322 1323
def parse_image(image, input_layer_name, image_conf):
    image_conf.channels = image.channels
L
Luo Tao 已提交
1324
    image_conf.img_size, image_conf.img_size_y = \
L
Luo Tao 已提交
1325
        get_img_size(input_layer_name, image_conf.channels)
Q
qijun 已提交
1326

Z
zhangjinchao01 已提交
1327

C
chengduoZH 已提交
1328 1329 1330 1331 1332 1333
def parse_image3d(image, input_layer_name, image_conf):
    image_conf.channels = image.channels
    image_conf.img_size, image_conf.img_size_y, image_conf.img_size_z = \
        get_img3d_size(input_layer_name, image_conf.channels)


Z
zhangjinchao01 已提交
1334 1335
def parse_norm(norm, input_layer_name, norm_conf):
    norm_conf.norm_type = norm.norm_type
1336 1337 1338 1339 1340
    config_assert(
        norm.norm_type in
        ['rnorm', 'cmrnorm-projection', 'cross-channel-norm'],
        "norm-type %s is not in [rnorm, cmrnorm-projection, cross-channel-norm]"
        % norm.norm_type)
Z
zhangjinchao01 已提交
1341 1342 1343 1344 1345 1346
    norm_conf.channels = norm.channels
    norm_conf.size = norm.size
    norm_conf.scale = norm.scale
    norm_conf.pow = norm.pow
    norm_conf.blocked = norm.blocked

L
Luo Tao 已提交
1347
    norm_conf.img_size, norm_conf.img_size_y = \
L
Luo Tao 已提交
1348
        get_img_size(input_layer_name, norm.channels)
Z
zhangjinchao01 已提交
1349
    norm_conf.output_x = norm_conf.img_size
L
Luo Tao 已提交
1350
    norm_conf.output_y = norm_conf.img_size_y
Z
zhangjinchao01 已提交
1351 1352 1353
    if norm.norm_type in ['cmrnorm-projection']:
        norm_conf.scale /= norm.size
    else:
Q
qijun 已提交
1354 1355
        norm_conf.scale /= norm.size**2

1356

L
Luo Tao 已提交
1357 1358
#caffe_mode: compute the output size using floor instead of ceil,
#            which is consistent of caffe and CuDNN's convention.
1359
def parse_conv(conv, input_layer_name, conv_conf, num_filters, trans=False):
Z
zhangjinchao01 已提交
1360 1361 1362 1363 1364 1365 1366 1367 1368
    conv_conf.filter_size = conv.filter_size
    conv_conf.filter_size_y = conv.filter_size_y
    conv_conf.channels = conv.channels
    conv_conf.padding = conv.padding
    conv_conf.padding_y = conv.padding_y
    conv_conf.stride = conv.stride
    conv_conf.stride_y = conv.stride_y
    conv_conf.groups = conv.groups
    conv_conf.caffe_mode = conv.caffe_mode
X
xzl 已提交
1369 1370 1371 1372 1373 1374
    if not conv.dilation:
        conv.dilation = 1
        conv.dilation_y = 1
    else:
        conv_conf.dilation = conv.dilation
        conv_conf.dilation_y = conv.dilation_y
Q
qijun 已提交
1375

1376
    if not trans:
1377
        conv_conf.filter_channels = conv.channels / conv.groups
L
Luo Tao 已提交
1378
        conv_conf.img_size, conv_conf.img_size_y = \
L
Luo Tao 已提交
1379
            get_img_size(input_layer_name, conv.channels)
1380
        conv_conf.output_x = cnn_output_size(
Q
qijun 已提交
1381
            conv_conf.img_size, conv_conf.filter_size, conv_conf.padding,
X
xzl 已提交
1382
            conv_conf.stride, conv_conf.caffe_mode, conv.dilation)
L
Luo Tao 已提交
1383 1384
        conv_conf.output_y = cnn_output_size(
            conv_conf.img_size_y, conv_conf.filter_size_y, conv_conf.padding_y,
X
xzl 已提交
1385
            conv_conf.stride_y, conv_conf.caffe_mode, conv.dilation_y)
1386
    else:
1387
        conv_conf.filter_channels = num_filters / conv.groups
L
Luo Tao 已提交
1388
        conv_conf.output_x, conv_conf.output_y = \
L
Luo Tao 已提交
1389
            get_img_size(input_layer_name, conv.channels)
1390
        conv_conf.img_size = cnn_image_size(
Q
qijun 已提交
1391
            conv_conf.output_x, conv_conf.filter_size, conv_conf.padding,
X
xzl 已提交
1392
            conv_conf.stride, conv_conf.caffe_mode, conv.dilation)
L
Luo Tao 已提交
1393
        conv_conf.img_size_y = cnn_image_size(
L
Luo Tao 已提交
1394
            conv_conf.output_y, conv_conf.filter_size_y, conv_conf.padding_y,
X
xzl 已提交
1395
            conv_conf.stride_y, conv_conf.caffe_mode, conv.dilation_y)
Q
qijun 已提交
1396

1397

1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
#caffe_mode: compute the output size using floor instead of ceil,
#            which is consistent of caffe and CuDNN's convention.
def parse_conv3d(conv, input_layer_name, conv_conf, num_filters, trans=False):
    conv_conf.filter_size = conv.filter_size
    conv_conf.filter_size_y = conv.filter_size_y
    conv_conf.filter_size_z = conv.filter_size_z
    conv_conf.channels = conv.channels
    conv_conf.padding = conv.padding
    conv_conf.padding_y = conv.padding_y
    conv_conf.padding_z = conv.padding_z
    conv_conf.stride = conv.stride
    conv_conf.stride_y = conv.stride_y
    conv_conf.stride_z = conv.stride_z
    conv_conf.groups = conv.groups
    conv_conf.caffe_mode = conv.caffe_mode

    if not trans:
        conv_conf.filter_channels = conv.channels / conv.groups
        conv_conf.img_size, conv_conf.img_size_y, conv_conf.img_size_z = \
            get_img3d_size(input_layer_name, conv.channels)
        conv_conf.output_x = cnn_output_size(
            conv_conf.img_size, conv_conf.filter_size, conv_conf.padding,
            conv_conf.stride, conv_conf.caffe_mode)
        conv_conf.output_y = cnn_output_size(
            conv_conf.img_size_y, conv_conf.filter_size_y, conv_conf.padding_y,
            conv_conf.stride_y, conv_conf.caffe_mode)
        conv_conf.output_z = cnn_output_size(
            conv_conf.img_size_z, conv_conf.filter_size_z, conv_conf.padding_z,
            conv_conf.stride_z, conv_conf.caffe_mode)
    else:
        conv_conf.filter_channels = num_filters / conv.groups
        conv_conf.output_x, conv_conf.output_y, conv_conf.output_z = \
            get_img3d_size(input_layer_name, conv.channels)
        conv_conf.img_size = cnn_image_size(
            conv_conf.output_x, conv_conf.filter_size, conv_conf.padding,
            conv_conf.stride, conv_conf.caffe_mode)
        conv_conf.img_size_y = cnn_image_size(
            conv_conf.output_y, conv_conf.filter_size_y, conv_conf.padding_y,
            conv_conf.stride_y, conv_conf.caffe_mode)
        conv_conf.img_size_z = cnn_image_size(
            conv_conf.output_z, conv_conf.filter_size_z, conv_conf.padding_z,
            conv_conf.stride_z, conv_conf.caffe_mode)


Z
zhangjinchao01 已提交
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
def parse_block_expand(block_expand, input_layer_name, block_expand_conf):
    block_expand_conf.channels = block_expand.channels
    block_expand_conf.stride_x = block_expand.stride_x
    block_expand_conf.stride_y = block_expand.stride_y
    block_expand_conf.padding_x = block_expand.padding_x
    block_expand_conf.padding_y = block_expand.padding_y
    block_expand_conf.block_x = block_expand.block_x
    block_expand_conf.block_y = block_expand.block_y
    block_expand_conf.img_size_x = block_expand.img_size_x
    block_expand_conf.img_size_y = block_expand.img_size_y
    if block_expand_conf.img_size_x == 0:
        block_expand_conf.output_x = 0
    else:
1455
        block_expand_conf.output_x = cnn_output_size(
1456
            block_expand.img_size_x, block_expand.block_x,
1457
            block_expand.padding_x, block_expand.stride_x, False)
Z
zhangjinchao01 已提交
1458 1459

    if block_expand_conf.img_size_y == 0:
1460
        block_expand_conf.output_y = 0
Z
zhangjinchao01 已提交
1461
    else:
1462
        block_expand_conf.output_y = cnn_output_size(
1463
            block_expand.img_size_y, block_expand.block_y,
1464
            block_expand.padding_y, block_expand.stride_y, False)
Z
zhangjinchao01 已提交
1465

Q
qijun 已提交
1466

1467
def parse_maxout(maxout, input_layer_name, maxout_conf):
L
Luo Tao 已提交
1468
    parse_image(maxout, input_layer_name, maxout_conf.image_conf)
1469
    maxout_conf.groups = maxout.groups
1470

Q
qijun 已提交
1471

Z
zhangjinchao01 已提交
1472 1473
# Define an evaluator
@config_func
Y
yangyaming 已提交
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
def Evaluator(name,
              type,
              inputs,
              chunk_scheme=None,
              num_chunk_types=None,
              classification_threshold=None,
              positive_label=None,
              dict_file=None,
              result_file=None,
              num_results=None,
              top_k=None,
              delimited=None,
              excluded_chunk_types=None,
              overlap_threshold=None,
              background_id=None,
              evaluate_difficult=None,
              ap_type=None):
Z
zhangjinchao01 已提交
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
    evaluator = g_config.model_config.evaluators.add()
    evaluator.type = type
    evaluator.name = MakeLayerNameInSubmodel(name)
    if type_of(inputs) == str:
        inputs = [inputs]

    evaluator.input_layers.extend(
        [MakeLayerNameInSubmodel(name) for name in inputs])

    if chunk_scheme is not None:
        evaluator.chunk_scheme = chunk_scheme
        evaluator.num_chunk_types = num_chunk_types
    g_current_submodel.evaluator_names.append(evaluator.name)

1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
    if classification_threshold is not None:
        evaluator.classification_threshold = classification_threshold
    if positive_label is not None:
        evaluator.positive_label = positive_label
    if dict_file is not None:
        evaluator.dict_file = dict_file

    if result_file is not None:
        evaluator.result_file = result_file
    if num_results is not None:
        evaluator.num_results = num_results
L
Liang Zhao 已提交
1516 1517
    if top_k is not None:
        evaluator.top_k = top_k
1518 1519
    if delimited is not None:
        evaluator.delimited = delimited
Z
zhangjinchao01 已提交
1520

1521 1522 1523
    if excluded_chunk_types:
        evaluator.excluded_chunk_types.extend(excluded_chunk_types)

Y
yangyaming 已提交
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
    if overlap_threshold is not None:
        evaluator.overlap_threshold = overlap_threshold

    if background_id is not None:
        evaluator.background_id = background_id

    if evaluate_difficult is not None:
        evaluator.evaluate_difficult = evaluate_difficult

    if ap_type is not None:
        evaluator.ap_type = ap_type

Q
qijun 已提交
1536

Z
zhangjinchao01 已提交
1537 1538 1539 1540 1541
class LayerBase(object):
    def __init__(
            self,
            name,
            type,
Q
qijun 已提交
1542
            size,  # size can be 0. In this case, subclass should set it.
Z
zhangjinchao01 已提交
1543 1544 1545 1546
            inputs,
            device=None,
            active_type="",
            drop_rate=0.,
C
caoying03 已提交
1547 1548
            coeff=None,
            error_clipping_threshold=None):
Z
zhangjinchao01 已提交
1549
        config_assert('@' not in name,
Q
qijun 已提交
1550
                      "layer name: %s contain special character @" % name)
Z
zhangjinchao01 已提交
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
        global g_current_submodel
        name = MakeLayerNameInSubmodel(name)

        config_assert(name not in g_layer_map,
                      'Duplicated layer name: %s' % name)

        self.inputs = copy.deepcopy(inputs)
        self.operators = []

        if self.inputs is None:
            self.inputs = []
        elif type_of(self.inputs) != list:
            self.inputs = [self.inputs]

        self.config = g_config.model_config.layers.add()
1566
        assert isinstance(self.config, LayerConfig)
1567
        use_mkldnn = bool(int(g_command_config_args.get("use_mkldnn", 0)))
T
tensor-tang 已提交
1568
        mkldnn_acts = ['relu', 'tanh', 'softmax']
1569 1570
        if use_mkldnn and active_type in mkldnn_acts:
            active_type = "mkldnn_" + active_type
Z
zhangjinchao01 已提交
1571 1572 1573
        self.config.name = name
        self.config.type = type
        self.config.active_type = active_type
1574 1575
        if coeff is not None:
            self.config.coeff = float(coeff)
Z
zhangjinchao01 已提交
1576 1577 1578 1579 1580 1581 1582
        if size != 0:
            self.config.size = size
        if drop_rate != 0:
            self.config.drop_rate = drop_rate

        if device is not None:
            self.config.device = device
1583
        elif g_default_device is not None:
Z
zhangjinchao01 已提交
1584 1585
            self.config.device = g_default_device

C
caoying03 已提交
1586 1587 1588
        if error_clipping_threshold is not None:
            self.config.error_clipping_threshold = error_clipping_threshold

Z
zhangjinchao01 已提交
1589 1590 1591 1592 1593 1594 1595
        for input_index in xrange(len(self.inputs)):
            input = self.inputs[input_index]
            input_config = None
            input_layer_name = ''
            if type_of(input) == str:
                input_layer_name = input
                input_config = Input(
Q
qijun 已提交
1596 1597
                    input_layer_name=input,
                    parameter_name=gen_parameter_name(name, input_index))
Z
zhangjinchao01 已提交
1598 1599 1600 1601 1602 1603 1604 1605
                input_layer_name = input_config.input_layer_name
            elif isinstance(input, Input):
                input_layer_name = input.input_layer_name
                input_config = input
                if input_config.parameter_name is None:
                    input_config.parameter_name = \
                        gen_parameter_name(name, input_index)
            elif isinstance(input, Operator):
Q
qijun 已提交
1606
                self.operators.append(input)
Z
zhangjinchao01 已提交
1607 1608 1609 1610
                input.operator_conf.input_indices.append(input_index)
                input_config = Input(input.input_layer_names[0])
                input_layer_name = input_config.input_layer_name
            else:
Q
qijun 已提交
1611
                raise ValueError('Wrong type for inputs: %s' % type_of(input))
Z
zhangjinchao01 已提交
1612
            config_assert(input_layer_name in g_layer_map,
Q
qijun 已提交
1613 1614
                          "Unknown input layer '%s' for layer %s" %
                          (input_layer_name, name))
Z
zhangjinchao01 已提交
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
            self.inputs[input_index] = input_config
            layer_input = self.config.inputs.add()
            layer_input.input_layer_name = input_config.input_layer_name
            if input_config.input_layer_argument is not None:
                layer_input.input_layer_argument = \
                    input_config.input_layer_argument

        g_layer_map[name] = self.config

        g_current_submodel.layer_names.append(self.config.name)

    def get_input_layer(self, input_index):
        return g_layer_map[self.config.inputs[input_index].input_layer_name]

    # will return the bias created if not *for_self*
    def create_bias_parameter(
            self,
Q
qijun 已提交
1632
            bias,  # True/False or BiasCfg
Z
zhangjinchao01 已提交
1633
            size,
Q
qijun 已提交
1634 1635 1636
            dims=None,
            for_self=True,  # whether create bias for layer self
    ):
Z
zhangjinchao01 已提交
1637 1638 1639 1640 1641 1642

        if size == 0:
            return
        if dims is None:
            dims = [1, size]

Q
qijun 已提交
1643 1644 1645
        config_assert(
            type_of(bias) == bool or type_of(bias) == Bias,
            'Incorrect type for bias: %s' % type_of(bias))
Z
zhangjinchao01 已提交
1646 1647 1648 1649 1650 1651 1652 1653 1654

        if type_of(bias) == bool:
            if bias:
                bias = Bias()

        if type_of(bias) == Bias:
            if bias.parameter_name is None:
                bias.parameter_name = gen_bias_parameter_name(self.config.name)
            if bias.parameter_name not in g_parameter_map:
1655 1656
                assert isinstance(self.config, LayerConfig)

Z
zhangjinchao01 已提交
1657 1658 1659
                Parameter(
                    bias.parameter_name,
                    size,
Q
qijun 已提交
1660 1661
                    self.config.device
                    if self.config.HasField('device') else None,
Z
zhangjinchao01 已提交
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
                    dims,
                    bias.learning_rate,
                    bias.momentum,
                    decay_rate=bias.decay_rate,
                    decay_rate_l1=bias.decay_rate_l1,
                    initial_mean=bias.initial_mean,
                    initial_std=bias.initial_std,
                    initial_strategy=bias.initial_strategy,
                    initial_smart=bias.initial_smart,
                    num_batches_regularization=bias.num_batches_regularization,
                    sparse_remote_update=bias.sparse_remote_update,
Q
qijun 已提交
1673 1674
                    gradient_clipping_threshold=bias.
                    gradient_clipping_threshold,
Z
zhangjinchao01 已提交
1675
                    is_static=bias.is_static,
X
xuwei06 已提交
1676 1677
                    is_shared=bias.is_shared,
                    initializer=bias.initializer)
Z
zhangjinchao01 已提交
1678 1679 1680 1681 1682
            if for_self:
                self.config.bias_parameter_name = bias.parameter_name
            else:
                return bias.parameter_name

Q
qijun 已提交
1683 1684 1685 1686 1687 1688
    def create_input_parameter(self,
                               input_index,
                               size,
                               dims=None,
                               sparse=None,
                               format=None):
Z
zhangjinchao01 已提交
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
        if dims is None:
            # TODO(yuyang18): print warning and callstack here!
            dims = list()

        if size == 0:
            return

        input_config = self.inputs[input_index]

        self.config.inputs[input_index].input_parameter_name = \
            input_config.parameter_name

        if input_config.parameter_name in g_parameter_map:
            para = g_parameter_map[input_config.parameter_name]
Q
qijun 已提交
1703 1704
            config_assert(size == para.size, (
                'Shared parameter "%s" does not ' + 'have same size: %s vs. %s')
Z
zhangjinchao01 已提交
1705 1706
                          % (input_config.parameter_name, para.size, size))

Q
qijun 已提交
1707 1708
            config_assert(dims == para.dims, (
                'Shared parameter "%s" does not ' + 'have same dims: %s vs. %s')
Z
zhangjinchao01 已提交
1709 1710 1711 1712 1713 1714
                          % (input_config.parameter_name, para.dims, dims))
            return

        Parameter(
            input_config.parameter_name,
            size,
1715
            self.config.device if self.config.HasField("device") else None,
Z
zhangjinchao01 已提交
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
            dims,
            input_config.learning_rate,
            input_config.momentum,
            decay_rate=input_config.decay_rate,
            decay_rate_l1=input_config.decay_rate_l1,
            initial_mean=input_config.initial_mean,
            initial_std=input_config.initial_std,
            initial_strategy=input_config.initial_strategy,
            initial_smart=input_config.initial_smart,
            num_batches_regularization=input_config.num_batches_regularization,
            sparse_remote_update=input_config.sparse_remote_update,
            sparse_update=input_config.sparse_update,
Q
qijun 已提交
1728 1729
            gradient_clipping_threshold=input_config.
            gradient_clipping_threshold,
Z
zhangjinchao01 已提交
1730 1731 1732 1733
            sparse=sparse,
            format=format,
            is_static=input_config.is_static,
            is_shared=input_config.is_shared,
X
xuwei06 已提交
1734 1735
            update_hooks=input_config.update_hooks,
            initializer=input_config.initializer)
Z
zhangjinchao01 已提交
1736 1737 1738 1739 1740 1741 1742 1743 1744

    def set_layer_size(self, size):
        if self.config.size == 0:
            self.config.size = size
        else:
            config_assert(self.config.size == size,
                          'Different inputs result in' +
                          'different layer size at layer %s' % self.config.name)

L
Luo Tao 已提交
1745 1746 1747 1748
    def set_layer_height_width(self, height, width):
        self.config.height = height
        self.config.width = width

C
chengduoZH 已提交
1749 1750 1751
    def set_layer_depth(self, depth):
        self.config.depth = depth

L
Luo Tao 已提交
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
    def set_cnn_layer(self,
                      input_layer_name,
                      height,
                      width,
                      channels,
                      is_print=True):
        size = height * width * channels
        self.set_layer_size(size)
        self.set_layer_height_width(height, width)
        if is_print:
            print("output for %s: c = %d, h = %d, w = %d, size = %d" %
                  (input_layer_name, channels, height, width, size))

Q
qijun 已提交
1765

Z
zhangjinchao01 已提交
1766 1767
@config_layer('multi_class_cross_entropy_with_selfnorm')
class MultiClassCrossEntropySelfNormCostLayer(LayerBase):
Q
qijun 已提交
1768 1769 1770
    def __init__(self, name, inputs, softmax_selfnorm_alpha=0.1, **xargs):
        super(MultiClassCrossEntropySelfNormCostLayer, self).__init__(
            name, 'multi_class_cross_entropy_with_selfnorm', 0, inputs, **xargs)
Z
zhangjinchao01 已提交
1771 1772
        self.config.softmax_selfnorm_alpha = softmax_selfnorm_alpha

Q
qijun 已提交
1773

C
caoying03 已提交
1774 1775 1776
@config_layer('cross_entropy_over_beam')
class CrossEntropyOverBeamLayer(LayerBase):
    def __init__(self, name, inputs, **xargs):
C
caoying03 已提交
1777
        config_assert(len(inputs) % 3 == 0, "Error input number.")
C
caoying03 已提交
1778 1779 1780 1781
        super(CrossEntropyOverBeamLayer, self).__init__(
            name, 'cross_entropy_over_beam', 0, inputs, **xargs)
        input_num = len(inputs) / 3
        for i in range(input_num):
C
caoying03 已提交
1782 1783 1784 1785 1786
            input_layer = self.get_input_layer(i * 3)
            config_assert(input_layer.size == 1, (
                "Inputs for this layer are made up of "
                "several triples, in which the first one is scores over "
                "all candidate paths, whose size should be equal to 1."))
C
caoying03 已提交
1787 1788


Z
zhangjinchao01 已提交
1789 1790
@config_layer('fc')
class FCLayer(LayerBase):
T
tensor-tang 已提交
1791 1792
    layer_type = 'fc'

L
lianxiaochen 已提交
1793 1794 1795 1796 1797 1798 1799
    def __init__(self,
                 name,
                 size,
                 inputs,
                 bias=True,
                 error_clipping_threshold=None,
                 **xargs):
T
tensor-tang 已提交
1800
        use_mkldnn = bool(int(g_command_config_args.get("use_mkldnn", 0)))
1801 1802
        use_mkldnn_wgt = bool(
            int(g_command_config_args.get("use_mkldnn_wgt", 0)))
T
tensor-tang 已提交
1803 1804 1805 1806
        if use_mkldnn:
            self.layer_type = 'mkldnn_fc'
            config_assert(
                len(inputs) == 1,
T
tensor-tang 已提交
1807
                "MKLDNNFCLayer support one and only one input!")
T
tensor-tang 已提交
1808 1809
        super(FCLayer, self).__init__(
            name, self.layer_type, size, inputs=inputs, **xargs)
Z
zhangjinchao01 已提交
1810 1811 1812 1813 1814 1815
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
            psize = self.config.size * input_layer.size
            dims = [input_layer.size, self.config.size]
            format = self.inputs[input_index].format
            sparse = format == "csr" or format == "csc"
T
tensor-tang 已提交
1816 1817
            if use_mkldnn:
                config_assert(not sparse,
T
tensor-tang 已提交
1818
                              "MKLDNNFCLayer do not support sparse format yet")
T
tensor-tang 已提交
1819 1820
                if use_mkldnn_wgt:
                    dims = [self.config.size, input_layer.size]
Z
zhangjinchao01 已提交
1821 1822
            if sparse:
                psize = self.inputs[input_index].nnz
1823 1824
            else:
                sparse = None
Z
zhangjinchao01 已提交
1825

Q
qijun 已提交
1826 1827
            self.create_input_parameter(input_index, psize, dims, sparse,
                                        format)
Z
zhangjinchao01 已提交
1828
        self.create_bias_parameter(bias, self.config.size)
L
lianxiaochen 已提交
1829 1830
        if error_clipping_threshold is not None:
            self.config.error_clipping_threshold = error_clipping_threshold
Z
zhangjinchao01 已提交
1831

Q
qijun 已提交
1832

T
tensor-tang 已提交
1833
@config_layer('mkldnn_fc')
T
tensor-tang 已提交
1834
class MKLDNNFcLayer(FCLayer):
T
tensor-tang 已提交
1835 1836 1837
    layer_type = 'mkldnn_fc'


Z
zhangjinchao01 已提交
1838 1839
@config_layer('selective_fc')
class SelectiveFCLayer(LayerBase):
Q
qijun 已提交
1840 1841 1842 1843 1844 1845 1846 1847 1848 1849
    def __init__(self,
                 name,
                 size,
                 inputs,
                 bias=True,
                 selective_fc_pass_generation=False,
                 has_selected_colums=True,
                 selective_fc_full_mul_ratio=0.02,
                 selective_fc_parallel_plain_mul_thread_num=None,
                 **xargs):
Z
zhangjinchao01 已提交
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
        super(SelectiveFCLayer, self).__init__(
            name, 'selective_fc', size, inputs=inputs, **xargs)
        # user MUST know if selctive fc is used in training,
        # parameter matrices saved by this layer are automatically transposed,
        # BUT bias is not.

        # if selective_fc is used only in testing mode, and parameters for
        # this layer are trained by fully connected layers,
        # then TranposedFullMatrixProjectin MUST be used in training
        # to avoid manual transpose in testing.

        self.config.selective_fc_pass_generation = selective_fc_pass_generation
        self.config.has_selected_colums = has_selected_colums
        self.config.selective_fc_full_mul_ratio = selective_fc_full_mul_ratio
        if selective_fc_parallel_plain_mul_thread_num is not None:
            self.config.selective_fc_parallel_plain_mul_thread_num = selective_fc_parallel_plain_mul_thread_num

        input_num = len(self.inputs)
        if has_selected_colums:
            config_assert(input_num >= 2,
Q
qijun 已提交
1870 1871
                          ("if indices of selected columns are not specified, "
                           "selective_fc Layer has at least two inputs"))
Z
zhangjinchao01 已提交
1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883
            input_num -= 1

        for input_index in xrange(input_num):
            input_layer = self.get_input_layer(input_index)
            psize = self.config.size * input_layer.size
            dims = [input_layer.size, self.config.size]
            dims = dims[::-1]  # transpose the parameter
            format = self.inputs[input_index].format
            sparse = format == "csr" or format == "csc"
            if sparse:
                psize = self.inputs[input_index].nnz

Q
qijun 已提交
1884 1885
            self.create_input_parameter(input_index, psize, dims, sparse,
                                        format)
Z
zhangjinchao01 已提交
1886 1887
        self.create_bias_parameter(bias, self.config.size)

Q
qijun 已提交
1888

1889 1890
@config_layer('print')
class PrintLayer(LayerBase):
1891
    def __init__(self, name, inputs, format=None):
1892
        super(PrintLayer, self).__init__(name, 'print', 0, inputs)
1893 1894 1895 1896 1897 1898
        if format is None:
            format = "\n".join([
                "layer=" + input.input_layer_name + " %s"
                for input in self.inputs
            ])
        self.config.user_arg = format
1899

Q
qijun 已提交
1900

Y
yuan 已提交
1901 1902
@config_layer('priorbox')
class PriorBoxLayer(LayerBase):
G
gaoyuan 已提交
1903 1904
    def __init__(self, name, inputs, size, min_size, max_size, aspect_ratio,
                 variance):
Y
yuan 已提交
1905
        super(PriorBoxLayer, self).__init__(name, 'priorbox', 0, inputs)
G
gaoyuan 已提交
1906
        config_assert(len(inputs) == 2, 'PriorBoxLayer must have 2 inputs')
G
gaoyuan 已提交
1907 1908 1909 1910 1911 1912 1913
        input_layer = self.get_input_layer(1)
        config_assert(
            input_layer.type == 'data',
            'Expecting the second input layer of an priorbox layer to be '
            'a data layer')
        config_assert(input_layer.width > 0, 'The data layer must set width')
        config_assert(input_layer.height > 0, 'The data layer must set height')
G
gaoyuan 已提交
1914
        config_assert(len(variance) == 4, 'The variance must have 4 inputs')
Y
yuan 已提交
1915 1916 1917 1918 1919 1920
        self.config.inputs[0].priorbox_conf.min_size.extend(min_size)
        self.config.inputs[0].priorbox_conf.max_size.extend(max_size)
        self.config.inputs[0].priorbox_conf.aspect_ratio.extend(aspect_ratio)
        self.config.inputs[0].priorbox_conf.variance.extend(variance)
        self.config.size = size

Q
qijun 已提交
1921

1922 1923 1924
@config_layer('multibox_loss')
class MultiBoxLossLayer(LayerBase):
    def __init__(self, name, inputs, input_num, num_classes, overlap_threshold,
1925
                 neg_pos_ratio, neg_overlap, background_id, **xargs):
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
        super(MultiBoxLossLayer, self).__init__(name, 'multibox_loss', 0,
                                                inputs)
        config_assert(
            len(inputs) == (input_num * 2 + 2),
            'MultiBoxLossLayer does not have enough inputs')
        config_assert(num_classes > background_id,
                      'Classes number must greater than background ID')
        self.config.inputs[0].multibox_loss_conf.num_classes = num_classes
        self.config.inputs[
            0].multibox_loss_conf.overlap_threshold = overlap_threshold
        self.config.inputs[0].multibox_loss_conf.neg_pos_ratio = neg_pos_ratio
        self.config.inputs[0].multibox_loss_conf.neg_overlap = neg_overlap
        self.config.inputs[0].multibox_loss_conf.background_id = background_id
        self.config.inputs[0].multibox_loss_conf.input_num = input_num
        self.config.size = 1


@config_layer('detection_output')
class DetectionOutputLayer(LayerBase):
    def __init__(self, name, inputs, size, input_num, num_classes,
                 nms_threshold, nms_top_k, keep_top_k, confidence_threshold,
1947
                 background_id, **xargs):
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
        super(DetectionOutputLayer, self).__init__(name, 'detection_output', 0,
                                                   inputs)
        config_assert(
            len(inputs) == (input_num * 2 + 1),
            'DetectionOutputLayer does not have enough inputs')
        config_assert(num_classes > background_id,
                      'Classes number must greater than background ID')
        self.config.inputs[0].detection_output_conf.num_classes = num_classes
        self.config.inputs[
            0].detection_output_conf.nms_threshold = nms_threshold
        self.config.inputs[0].detection_output_conf.nms_top_k = nms_top_k
        self.config.inputs[0].detection_output_conf.keep_top_k = keep_top_k
        self.config.inputs[
            0].detection_output_conf.confidence_threshold = confidence_threshold
        self.config.inputs[
            0].detection_output_conf.background_id = background_id
        self.config.inputs[0].detection_output_conf.input_num = input_num
        self.config.size = size


G
guosheng 已提交
1968 1969
@config_layer('roi_pool')
class ROIPoolLayer(LayerBase):
1970 1971
    def __init__(self, name, inputs, pooled_width, pooled_height, spatial_scale,
                 num_channels, **xargs):
G
guosheng 已提交
1972 1973 1974 1975 1976
        super(ROIPoolLayer, self).__init__(name, 'roi_pool', 0, inputs)
        config_assert(len(inputs) == 2, 'ROIPoolLayer must have 2 inputs')
        self.config.inputs[0].roi_pool_conf.pooled_width = pooled_width
        self.config.inputs[0].roi_pool_conf.pooled_height = pooled_height
        self.config.inputs[0].roi_pool_conf.spatial_scale = spatial_scale
1977
        self.set_cnn_layer(name, pooled_height, pooled_width, num_channels)
G
guosheng 已提交
1978 1979


Z
zhangjinchao01 已提交
1980 1981
@config_layer('data')
class DataLayer(LayerBase):
C
chengduoZH 已提交
1982 1983 1984 1985 1986 1987 1988
    def __init__(self,
                 name,
                 size,
                 depth=None,
                 height=None,
                 width=None,
                 device=None):
Q
qijun 已提交
1989 1990
        super(DataLayer, self).__init__(
            name, 'data', size, inputs=[], device=device)
L
Luo Tao 已提交
1991 1992
        if height and width:
            self.set_layer_height_width(height, width)
C
chengduoZH 已提交
1993 1994
        if depth:
            self.set_layer_depth(depth)
Q
qijun 已提交
1995

Z
zhangjinchao01 已提交
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022

'''
DataNormLayer: A layer for data normalization
Input: One and only one input layer is accepted. The input layer must
       be DataLayer with dense data type
Output: The normalization of the input data

Reference:
    LA Shalabi, Z Shaaban, B Kasasbeh. Data mining: A preprocessing engine

Example:
    Layer(
        name = "norm_input_layer",
        type = "data_norm",
        inputs = [Input("input_layer",
                        parameter_name = "_slot0.stats")],
        data_norm_strategy = "z-score",
    )

Note:
  (1) The parameter has been calculated in the preprocessing stage,
      and should be initialized by --init_model_path when training.
  (2) Three data normalization methoeds are considered
          z-score: y = (x-mean)/std
          min-max: y = (x-min)/(max-min)
          decimal-scaling: y = x/10^j, where j is the smallest integer such that max(|y|)<1
'''
Q
qijun 已提交
2023 2024


Z
zhangjinchao01 已提交
2025 2026
@config_layer('data_norm')
class DataNormLayer(LayerBase):
Q
qijun 已提交
2027
    def __init__(self, name, inputs, data_norm_strategy="z-score", device=None):
Z
zhangjinchao01 已提交
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
        super(DataNormLayer, self).__init__(
            name, 'data_norm', 0, inputs=inputs, device=device)
        self.config.data_norm_strategy = data_norm_strategy
        config_assert(len(inputs) == 1, 'DataNormLayer must have 1 input')
        input_layer = self.get_input_layer(0)
        self.set_layer_size(input_layer.size)
        para_size = 5 * input_layer.size
        para_dims = [5, input_layer.size]
        self.inputs[0].is_static = True
        self.create_input_parameter(0, para_size, para_dims)

Q
qijun 已提交
2039

Z
zhangjinchao01 已提交
2040 2041 2042
@config_layer('prelu')
class ParameterReluLayer(LayerBase):
    layer_type = 'prelu'
Q
qijun 已提交
2043 2044

    def __init__(self, name, inputs, partial_sum=1, **args):
Z
zhangjinchao01 已提交
2045 2046
        super(ParameterReluLayer, self).__init__(
            name, self.layer_type, 0, inputs=inputs, **args)
X
xzl 已提交
2047

Z
zhangjinchao01 已提交
2048
        input_layer = self.get_input_layer(0)
2049 2050 2051
        config_assert(len(self.inputs) == 1, "prelu layer has only one input.")
        config_assert(input_layer.size % partial_sum == 0,
                      "a wrong setting for partial_sum")
2052 2053

        dims = [1, input_layer.size / partial_sum]
Z
zhangjinchao01 已提交
2054
        self.set_layer_size(input_layer.size)
C
caoying03 已提交
2055
        self.config.partial_sum = partial_sum
2056 2057 2058 2059 2060
        self.create_input_parameter(0, input_layer.size / partial_sum, dims)

        self.set_layer_height_width(self.get_input_layer(0).height, \
                                        self.get_input_layer(0).width)
        self.set_layer_depth(self.get_input_layer(0).depth)
Z
zhangjinchao01 已提交
2061

Q
qijun 已提交
2062

Z
zhangjinchao01 已提交
2063 2064 2065
@config_layer('conv')
class ConvLayerBase(LayerBase):
    layer_type = 'conv'
Q
qijun 已提交
2066 2067 2068 2069 2070 2071 2072 2073

    def __init__(self,
                 name,
                 inputs=[],
                 bias=True,
                 num_filters=None,
                 shared_biases=False,
                 **xargs):
Z
zhangjinchao01 已提交
2074 2075 2076 2077 2078 2079
        super(ConvLayerBase, self).__init__(
            name, self.layer_type, 0, inputs=inputs, **xargs)

        if num_filters is not None:
            self.config.num_filters = num_filters

2080
        use_mkldnn = int(g_command_config_args.get("use_mkldnn", 0))
Z
zhangjinchao01 已提交
2081 2082 2083
        use_gpu = int(g_command_config_args.get("use_gpu", 0))
        parallel_nn = int(g_command_config_args.get("parallel_nn", 0))

2084 2085
        # Automatically select cudnn_type for GPU, exconv for CPU
        # and mkldnn_conv for MKLDNN
Z
zhangjinchao01 已提交
2086
        # if set type=conv, but still reserve the way user specify
2087
        # exconv, mkldnn_conv or cudnn_conv manually.
Z
zhangjinchao01 已提交
2088 2089 2090
        if self.layer_type == "cudnn_conv":
            config_assert(use_gpu, "cudnn_conv only support GPU")

2091 2092 2093
        if self.layer_type == "mkldnn_conv":
            config_assert(use_mkldnn, "mkldnn_conv only support MKLDNN")

Z
zhangjinchao01 已提交
2094
        if (use_gpu == 1 and self.layer_type != "exconv" and
2095
                self.layer_type != "mkldnn_conv" and
Q
qijun 已提交
2096
            (parallel_nn == 0 or self.config.device > -1)):
Z
zhangjinchao01 已提交
2097 2098
            self.layer_type = "cudnn_conv"
        else:
2099
            self.layer_type = "mkldnn_conv" if use_mkldnn else "exconv"
Z
zhangjinchao01 已提交
2100 2101 2102 2103 2104 2105 2106 2107 2108
        # need to specify layer in config
        self.config.type = self.layer_type

        if shared_biases is not None:
            self.config.shared_biases = shared_biases

        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
            conv_conf = self.config.inputs[input_index].conv_conf
L
Luo Tao 已提交
2109 2110
            parse_conv(self.inputs[input_index].conv, input_layer.name,
                       conv_conf, num_filters)
Z
zhangjinchao01 已提交
2111 2112
            psize = self.calc_parameter_size(conv_conf)
            self.create_input_parameter(input_index, psize)
L
Luo Tao 已提交
2113 2114
            self.set_cnn_layer(name, conv_conf.output_y, conv_conf.output_x,
                               self.config.num_filters)
Z
zhangjinchao01 已提交
2115 2116 2117 2118 2119 2120 2121 2122

        psize = self.config.size
        if shared_biases:
            psize = self.config.num_filters
        self.create_bias_parameter(bias, psize, [psize, 1])

    def calc_parameter_size(self, conv_conf):
        return self.config.num_filters * conv_conf.filter_channels \
2123
               * (conv_conf.filter_size * conv_conf.filter_size_y)
Z
zhangjinchao01 已提交
2124

Q
qijun 已提交
2125

Z
zhangjinchao01 已提交
2126 2127 2128 2129
@config_layer('exconv')
class ConvLayer(ConvLayerBase):
    layer_type = 'exconv'

Q
qijun 已提交
2130

2131 2132 2133 2134 2135
@config_layer('mkldnn_conv')
class ConvLayer(ConvLayerBase):
    layer_type = 'mkldnn_conv'


Z
zhangjinchao01 已提交
2136 2137 2138 2139
@config_layer('cudnn_conv')
class ConvLayer(ConvLayerBase):
    layer_type = 'cudnn_conv'

2140 2141 2142 2143

@config_layer('convt')
class ConvTransLayerBase(LayerBase):
    layer_type = 'convt'
Q
qijun 已提交
2144 2145 2146 2147 2148 2149 2150 2151

    def __init__(self,
                 name,
                 inputs=[],
                 bias=True,
                 num_filters=None,
                 shared_biases=False,
                 **xargs):
2152
        super(ConvTransLayerBase, self).__init__(
2153 2154 2155 2156 2157 2158 2159 2160
            name, self.layer_type, 0, inputs=inputs, **xargs)

        if num_filters is not None:
            self.config.num_filters = num_filters

        use_gpu = int(g_command_config_args.get("use_gpu", 0))
        parallel_nn = int(g_command_config_args.get("parallel_nn", 0))

2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171
        # Automatically select cudnn_type for GPU and exconvt for CPU
        # if set type=exconvt, but still reserve the way user specify
        # exconvt or cudnn_convt manually.
        if self.layer_type == "cudnn_convt":
            config_assert(use_gpu, "cudnn_convt only support GPU")

        if (use_gpu == 1 and self.layer_type != "exconvt" and
            (parallel_nn == 0 or self.config.device > -1)):
            self.layer_type = "cudnn_convt"
        else:
            self.layer_type = "exconvt"
2172 2173 2174 2175 2176 2177 2178 2179
        # need to specify layer in config
        self.config.type = self.layer_type

        if shared_biases is not None:
            self.config.shared_biases = shared_biases

        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
2180
            parse_conv(
2181 2182
                self.inputs[input_index].conv,
                input_layer.name,
2183
                self.config.inputs[input_index].conv_conf,
2184
                num_filters,
2185
                trans=True)
2186 2187 2188
            conv_conf = self.config.inputs[input_index].conv_conf
            psize = self.calc_parameter_size(conv_conf)
            self.create_input_parameter(input_index, psize)
2189 2190
            self.set_cnn_layer(name, conv_conf.img_size_y, conv_conf.img_size,
                               self.config.num_filters)
2191 2192 2193 2194 2195 2196 2197

        psize = self.config.size
        if shared_biases:
            psize = self.config.num_filters
        self.create_bias_parameter(bias, psize, [psize, 1])

    def calc_parameter_size(self, conv_conf):
2198
        return conv_conf.channels * conv_conf.filter_channels \
2199 2200
                    * (conv_conf.filter_size * conv_conf.filter_size_y)

Q
qijun 已提交
2201

2202 2203 2204 2205
@config_layer('exconvt')
class ConvTransLayer(ConvTransLayerBase):
    layer_type = 'exconvt'

Q
qijun 已提交
2206

2207 2208 2209 2210 2211
@config_layer('cudnn_convt')
class ConvTransLayer(ConvTransLayerBase):
    layer_type = 'cudnn_convt'


C
chengduoZH 已提交
2212 2213
@config_layer('conv_3d')
class Conv3DLayerBase(LayerBase):
2214 2215 2216 2217 2218
    def __init__(self,
                 name,
                 inputs=[],
                 bias=True,
                 num_filters=None,
C
chengduoZH 已提交
2219
                 shared_biases=True,
2220
                 **xargs):
C
chengduoZH 已提交
2221
        super(Conv3DLayerBase, self).__init__(
2222 2223 2224 2225 2226 2227 2228 2229
            name, self.layer_type, 0, inputs=inputs, **xargs)

        if num_filters is not None:
            self.config.num_filters = num_filters

        # need to specify layer in config
        self.config.type = self.layer_type

C
chengduoZH 已提交
2230 2231 2232 2233
        trans = False
        if self.config.type == "deconv3d":
            trans = True

2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
        if shared_biases is not None:
            self.config.shared_biases = shared_biases

        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
            conv_conf = self.config.inputs[input_index].conv_conf
            parse_conv3d(
                self.inputs[input_index].conv,
                input_layer.name,
                conv_conf,
                num_filters,
C
chengduoZH 已提交
2245
                trans=trans
2246 2247 2248
            )  # for z-axis pad:0, strid:1, filter_size:1, img_size:1
            psize = self.calc_parameter_size(conv_conf)
            self.create_input_parameter(input_index, psize)
C
chengduoZH 已提交
2249 2250 2251 2252 2253 2254 2255
            if trans:
                self.set_cnn_layer(name, conv_conf.img_size_z,
                                   conv_conf.img_size_y, conv_conf.img_size,
                                   self.config.num_filters)
            else:
                self.set_cnn_layer(name, conv_conf.output_z, conv_conf.output_y,
                                   conv_conf.output_x, self.config.num_filters)
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275

        psize = self.config.size
        if shared_biases:
            psize = self.config.num_filters
        self.create_bias_parameter(bias, psize, [psize, 1])

    def calc_parameter_size(self, conv_conf):
        return self.config.num_filters * conv_conf.filter_channels \
               * (conv_conf.filter_size * conv_conf.filter_size_y \
                  * conv_conf.filter_size_z)

    def set_cnn_layer(self,
                      input_layer_name,
                      depth,
                      height,
                      width,
                      channels,
                      is_print=True):
        size = depth * height * width * channels
        self.set_layer_size(size)
C
chengduoZH 已提交
2276 2277
        self.set_layer_height_width(height, width)
        self.set_layer_depth(depth)
2278 2279 2280 2281 2282
        if is_print:
            print("output for %s: c = %d, d = %d, h = %d, w = %d, size = %d" %
                  (input_layer_name, channels, depth, height, width, size))


C
chengduoZH 已提交
2283 2284 2285
@config_layer('conv3d')
class Conv3DLayer(Conv3DLayerBase):
    layer_type = 'conv3d'
2286

Q
qijun 已提交
2287

C
chengduoZH 已提交
2288 2289 2290
@config_layer('deconv3d')
class Conv3DLayer(Conv3DLayerBase):
    layer_type = 'deconv3d'
2291 2292


Z
zhangjinchao01 已提交
2293 2294
@config_layer('norm')
class NormLayer(LayerBase):
2295 2296
    def __init__(self, name, inputs, **xargs):
        super(NormLayer, self).__init__(name, 'norm', 0, inputs=inputs, **xargs)
2297 2298 2299 2300
        use_mkldnn = bool(int(g_command_config_args.get("use_mkldnn", 0)))
        use_mkldnn = True if use_mkldnn and self.inputs[
            0].norm.norm_type == 'cmrnorm-projection' else False
        self.config.type = 'mkldnn_lrn' if use_mkldnn else self.config.type
Z
zhangjinchao01 已提交
2301 2302 2303
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
            norm_conf = self.config.inputs[input_index].norm_conf
L
Luo Tao 已提交
2304 2305
            parse_norm(self.inputs[input_index].norm, input_layer.name,
                       norm_conf)
2306 2307
            norm_conf.scale = self.inputs[
                input_index].norm.scale if use_mkldnn else norm_conf.scale
L
Luo Tao 已提交
2308 2309
            self.set_cnn_layer(name, norm_conf.output_y, norm_conf.output_x,
                               norm_conf.channels, False)
2310 2311 2312
            if norm_conf.norm_type == "cross-channel-norm":
                self.create_input_parameter(0, norm_conf.channels,
                                            [norm_conf.channels, 1])
Q
qijun 已提交
2313

Z
zhangjinchao01 已提交
2314 2315 2316

@config_layer('pool')
class PoolLayer(LayerBase):
2317 2318
    layer_type = 'pool'

2319
    def __init__(self, name, inputs, ceil_mode=True, exclude_mode=None,
2320
                 **xargs):
2321 2322 2323 2324 2325 2326
        use_mkldnn = int(g_command_config_args.get("use_mkldnn", 0))
        if self.layer_type == "mkldnn_pool":
            config_assert(use_mkldnn, "mkldnn_pool only support MKLDNN")
        self.layer_type = 'mkldnn_pool' if use_mkldnn else 'pool'
        super(PoolLayer, self).__init__(
            name, self.layer_type, 0, inputs=inputs, **xargs)
Z
zhangjinchao01 已提交
2327 2328 2329
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
            pool_conf = self.config.inputs[input_index].pool_conf
L
Luo Tao 已提交
2330
            parse_pool(self.inputs[input_index].pool, input_layer.name,
2331
                       pool_conf, ceil_mode, exclude_mode)
L
Luo Tao 已提交
2332 2333
            self.set_cnn_layer(name, pool_conf.output_y, pool_conf.output_x,
                               pool_conf.channels)
Q
qijun 已提交
2334

Z
zhangjinchao01 已提交
2335

2336 2337 2338 2339 2340
@config_layer('mkldnn_pool')
class MKLDNNPoolLayer(PoolLayer):
    layer_type = 'mkldnn_pool'


C
chengduoZH 已提交
2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369
@config_layer('pool3d')
class Pool3DLayer(LayerBase):
    def __init__(self, name, inputs, ceil_mode=True, **xargs):
        super(Pool3DLayer, self).__init__(
            name, 'pool3d', 0, inputs=inputs, **xargs)
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
            pool_conf = self.config.inputs[input_index].pool_conf
            parse_pool3d(self.inputs[input_index].pool, input_layer.name,
                         pool_conf, ceil_mode)
            self.set_cnn_layer(name, pool_conf.output_z, pool_conf.output_y,
                               pool_conf.output_x, pool_conf.channels)

    def set_cnn_layer(self,
                      input_layer_name,
                      depth,
                      height,
                      width,
                      channels,
                      is_print=True):
        size = depth * height * width * channels
        self.set_layer_size(size)
        self.set_layer_height_width(height, width)
        self.set_layer_depth(depth)
        if is_print:
            print("output for %s: c = %d, d = %d, h = %d, w = %d, size = %d" %
                  (input_layer_name, channels, depth, height, width, size))


Q
qijun 已提交
2370 2371
@config_layer('spp')
class SpatialPyramidPoolLayer(LayerBase):
2372
    def __init__(self, name, inputs, **xargs):
Q
qijun 已提交
2373
        super(SpatialPyramidPoolLayer, self).__init__(
2374
            name, 'spp', 0, inputs=inputs, **xargs)
Q
qijun 已提交
2375 2376 2377
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
            spp_conf = self.config.inputs[input_index].spp_conf
L
Luo Tao 已提交
2378 2379 2380
            parse_spp(self.inputs[input_index].spp, input_layer.name, spp_conf)
            output_x = (pow(4, spp_conf.pyramid_height) - 1) / (4 - 1)
            self.set_cnn_layer(name, 1, output_x, spp_conf.image_conf.channels)
Q
qijun 已提交
2381

Q
qijun 已提交
2382

D
dangqingqing 已提交
2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401
@config_layer('pad')
class PadLayer(LayerBase):
    def __init__(self, name, inputs, **xargs):
        super(PadLayer, self).__init__(name, 'pad', 0, inputs=inputs, **xargs)
        pad = self.inputs[0].pad
        self.config.inputs[0].pad_conf.pad_c.extend(pad.pad_c)
        self.config.inputs[0].pad_conf.pad_h.extend(pad.pad_h)
        self.config.inputs[0].pad_conf.pad_w.extend(pad.pad_w)

        input_layer = self.get_input_layer(0)
        image_conf = self.config.inputs[0].pad_conf.image_conf
        parse_image(pad, input_layer.name, image_conf)
        out_ch = pad.channels + pad.pad_c[0] + pad.pad_c[1]
        out_h = image_conf.img_size_y + pad.pad_h[0] + pad.pad_h[1]
        out_w = image_conf.img_size + pad.pad_w[0] + pad.pad_w[1]
        self.set_cnn_layer(name, out_h, out_w, out_ch)
        self.config.size = out_ch * out_h * out_w


2402 2403
@config_layer('crop')
class CropLayer(LayerBase):
2404
    def __init__(self, name, inputs, axis, offset, shape, **xargs):
2405
        super(CropLayer, self).__init__(name, 'crop', 0, inputs=inputs, **xargs)
2406 2407 2408
        self.config.axis = axis
        self.config.offset.extend(offset)
        self.config.shape.extend(shape)
2409 2410 2411 2412 2413 2414 2415 2416

        # get channel, width and height from input_0 layer
        input_layer = self.get_input_layer(0)
        image_conf = self.config.inputs[0].image_conf
        image_conf.img_size = input_layer.width
        image_conf.img_size_y = input_layer.height
        image_conf.channels = input_layer.size / (input_layer.width *
                                                  input_layer.height)
W
wanghaoshuang 已提交
2417
        # only support for 4-dims inputs and NCHW order
2418 2419 2420 2421 2422 2423
        if (len(self.config.inputs) == 2):
            self.set_layer_height_width(
                self.get_input_layer(1).height, self.get_input_layer(1).width)
            self.set_layer_size(self.get_input_layer(1).size)
        else:
            self.set_layer_height_width(shape[-2], shape[-1])
W
wanghaoshuang 已提交
2424
            self.set_layer_size(reduce(lambda x, y: x * y, shape[1:]))
2425 2426


Z
zhangjinchao01 已提交
2427 2428 2429
@config_layer('batch_norm')
class BatchNormLayer(LayerBase):
    layer_type = 'batch_norm'
Q
qijun 已提交
2430 2431 2432 2433 2434

    def __init__(self,
                 name,
                 inputs,
                 bias=True,
C
chengduoZH 已提交
2435
                 img3D=False,
Q
qijun 已提交
2436
                 use_global_stats=True,
P
peterzhang2029 已提交
2437
                 epsilon=1e-5,
Q
qijun 已提交
2438 2439
                 moving_average_fraction=0.9,
                 batch_norm_type=None,
C
chengduoZH 已提交
2440
                 mean_var_names=None,
Q
qijun 已提交
2441
                 **xargs):
Z
zhangjinchao01 已提交
2442 2443 2444 2445
        if inputs is None:
            inputs = []
        elif not isinstance(inputs, list):
            inputs = [inputs]
Q
qijun 已提交
2446 2447
        config_assert(
            len(inputs) == 1, "BatchNormLayer must have one and only one input")
Z
zhangjinchao01 已提交
2448 2449 2450 2451 2452 2453
        # Create Input for moving mean and std,
        # in batch normalization layer.
        # These paras no need to update, so set is_static is true.
        # If not use is_static, even set learning_rate = 0, decay_rate = 0,
        # these paras will change if set average_window in configure.
        use_gpu = bool(int(g_command_config_args.get("use_gpu", 0)))
2454
        use_mkldnn = bool(int(g_command_config_args.get("use_mkldnn", 0)))
Z
zhangjinchao01 已提交
2455 2456
        is_shared = True if not use_gpu else False
        for i in xrange(2):
Q
qijun 已提交
2457 2458 2459 2460 2461 2462
            inputs.append(
                Input(
                    inputs[0].input_layer_name,
                    initial_std=0.0,
                    initial_mean=0.0,
                    is_static=True,
2463
                    is_shared=is_shared,
D
dangqingqing 已提交
2464
                    make_layer_name_in_submodel=False, ))
Z
zhangjinchao01 已提交
2465 2466 2467

        parallel_nn = bool(int(g_command_config_args.get("parallel_nn", 0)))
        cudnn_version = int(g_command_config_args.get("cudnn_version", 0))
2468 2469 2470 2471
        # Automatically select cudnn_batch_norm for GPU, batch_norm for CPU
        # and mkldnn_batch_norm for MKLDNN. Also based on cudnn version.
        if batch_norm_type == "mkldnn_batch_norm":
            config_assert(use_mkldnn, "mkldnn_batch_norm only support MKLDNN")
Z
zhangjinchao01 已提交
2472
        use_cudnn = use_gpu and batch_norm_type != "batch_norm" and \
2473
                not use_mkldnn and batch_norm_type != "mkldnn_batch_norm" and \
2474
                ((not parallel_nn) or self.config.device > -1)
2475 2476 2477 2478
        if use_cudnn:
            self.layer_type = "cudnn_batch_norm"
        else:
            self.layer_type = "mkldnn_batch_norm" if use_mkldnn else "batch_norm"
Q
qijun 已提交
2479
        super(BatchNormLayer, self).__init__(
X
xuwei06 已提交
2480
            name, self.layer_type, 0, inputs=inputs, **xargs)
Z
zhangjinchao01 已提交
2481 2482 2483 2484 2485

        if use_global_stats is not None:
            self.config.use_global_stats = use_global_stats
        if moving_average_fraction is not None:
            self.config.moving_average_fraction = moving_average_fraction
P
peterzhang2029 已提交
2486 2487 2488
        if epsilon is not None:
            assert epsilon >= 1e-5, "epsilon must be no less than 1e-5."
            self.config.epsilon = epsilon
Z
zhangjinchao01 已提交
2489

Q
qijun 已提交
2490
        input_layer = self.get_input_layer(0)
Z
zhangjinchao01 已提交
2491
        image_conf = self.config.inputs[0].image_conf
C
chengduoZH 已提交
2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505
        if img3D:
            parse_image3d(self.inputs[0].image, input_layer.name, image_conf)
            # Only pass the width and height of input to batch_norm layer
            # when either of it is non-zero.
            if input_layer.width != 0 or input_layer.height != 0:
                self.set_cnn_layer(
                    input_layer_name=name,
                    depth=image_conf.img_size_z,
                    height=image_conf.img_size_y,
                    width=image_conf.img_size,
                    channels=image_conf.channels,
                    is_print=True)
            else:
                self.set_layer_size(input_layer.size)
2506
        else:
C
chengduoZH 已提交
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518
            parse_image(self.inputs[0].image, input_layer.name, image_conf)
            # Only pass the width and height of input to batch_norm layer
            # when either of it is non-zero.
            if input_layer.width != 0 or input_layer.height != 0:
                self.set_cnn_layer(
                    input_layer_name=name,
                    height=image_conf.img_size_y,
                    width=image_conf.img_size,
                    channels=image_conf.channels,
                    is_print=True)
            else:
                self.set_layer_size(input_layer.size)
Z
zhangjinchao01 已提交
2519 2520 2521

        psize = self.calc_parameter_size(image_conf)
        dims = [1, psize]
C
chengduoZH 已提交
2522 2523 2524 2525
        if mean_var_names is not None:
            assert len(mean_var_names) == 2
            self.inputs[1].parameter_name = mean_var_names[0]
            self.inputs[2].parameter_name = mean_var_names[1]
C
chengduoZH 已提交
2526

Z
zhangjinchao01 已提交
2527 2528 2529 2530 2531 2532
        self.create_input_parameter(0, psize)
        self.create_input_parameter(1, psize, dims)
        self.create_input_parameter(2, psize, dims)

        self.create_bias_parameter(bias, psize)

C
chengduoZH 已提交
2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554
    def set_cnn_layer(self,
                      input_layer_name,
                      depth=None,
                      height=None,
                      width=None,
                      channels=None,
                      is_print=True):
        depthIsNone = False
        if depth is None:
            depth = 1
            depthIsNone = True
        size = depth * height * width * channels
        self.set_layer_size(size)
        self.set_layer_height_width(height, width)
        self.set_layer_depth(depth)
        if is_print and depthIsNone:
            print("output for %s: c = %d, h = %d, w = %d, size = %d" %
                  (input_layer_name, channels, height, width, size))
        elif is_print:
            print("output for %s: c = %d, d = %d, h = %d, w = %d, size = %d" %
                  (input_layer_name, channels, depth, height, width, size))

Z
zhangjinchao01 已提交
2555 2556 2557
    def calc_parameter_size(self, image_conf):
        return image_conf.channels

Q
qijun 已提交
2558

Z
zhangjinchao01 已提交
2559 2560
@config_layer('trans')
class TransLayer(LayerBase):
2561
    def __init__(self, name, inputs, **xargs):
Q
qijun 已提交
2562
        super(TransLayer, self).__init__(
2563
            name, 'trans', 0, inputs=inputs, **xargs)
Q
qijun 已提交
2564 2565 2566
        config_assert(
            len(self.inputs) == 1,
            'TransLayer must have one and only one input')
Z
zhangjinchao01 已提交
2567 2568
        self.set_layer_size(self.get_input_layer(0).size)

Q
qijun 已提交
2569

Z
zhangjinchao01 已提交
2570 2571
@config_layer('resize')
class ResizeLayer(LayerBase):
2572
    def __init__(self, name, size, inputs, **xargs):
Q
qijun 已提交
2573
        super(ResizeLayer, self).__init__(
2574
            name, 'resize', size=size, inputs=inputs, **xargs)
Q
qijun 已提交
2575 2576 2577 2578
        config_assert(
            len(self.inputs) == 1,
            'ResizeLayer must have one and only one input')

Z
zhangjinchao01 已提交
2579

2580 2581
@config_layer('rotate')
class RotateLayer(LayerBase):
H
Haonan 已提交
2582
    def __init__(self, name, inputs, height, width, device=None):
2583 2584 2585 2586 2587
        super(RotateLayer, self).__init__(
            name, 'rotate', 0, inputs=inputs, device=device)
        config_assert(
            len(self.inputs) == 1,
            'RotateLayer must have one and only one input')
H
Haonan 已提交
2588
        self.set_layer_height_width(height, width)
2589 2590 2591
        self.set_layer_size(self.get_input_layer(0).size)


Z
zhangjinchao01 已提交
2592 2593
@config_layer('blockexpand')
class BlockExpandLayer(LayerBase):
2594
    def __init__(self, name, inputs, **xargs):
Q
qijun 已提交
2595
        super(BlockExpandLayer, self).__init__(
2596
            name, 'blockexpand', 0, inputs=inputs, **xargs)
Z
zhangjinchao01 已提交
2597 2598
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
Q
qijun 已提交
2599 2600
            parse_block_expand(
                self.inputs[input_index].block_expand, input_layer.name,
Z
zhangjinchao01 已提交
2601
                self.config.inputs[input_index].block_expand_conf)
Q
qijun 已提交
2602 2603 2604 2605 2606 2607
            block_expand_conf = self.config.inputs[
                input_index].block_expand_conf
            self.set_layer_size(block_expand_conf.block_x *
                                block_expand_conf.block_y *
                                block_expand_conf.channels)

Z
zhangjinchao01 已提交
2608

2609 2610
@config_layer('maxout')
class MaxOutLayer(LayerBase):
Q
qijun 已提交
2611 2612 2613
    def __init__(self, name, inputs, **xargs):
        super(MaxOutLayer, self).__init__(
            name, 'maxout', 0, inputs=inputs, **xargs)
2614 2615
        input_layer = self.get_input_layer(0)
        maxout_conf = self.config.inputs[0].maxout_conf
L
Luo Tao 已提交
2616
        parse_maxout(self.inputs[0].maxout, input_layer.name, maxout_conf)
L
Luo Tao 已提交
2617
        out_channels = maxout_conf.image_conf.channels / maxout_conf.groups
2618 2619
        self.set_cnn_layer(name, maxout_conf.image_conf.img_size_y,
                           maxout_conf.image_conf.img_size, out_channels)
Q
qijun 已提交
2620

2621

D
dangqingqing 已提交
2622 2623 2624 2625
@config_layer('row_conv')
class RowConvLayer(LayerBase):
    def __init__(self, name, inputs, context_length, **xargs):
        super(RowConvLayer, self).__init__(
2626
            name, 'row_conv', 0, inputs=inputs, **xargs)
D
dangqingqing 已提交
2627 2628
        config_assert(
            len(self.inputs) == 1,
2629
            'row convolution layer must have one and only one input.')
D
dangqingqing 已提交
2630 2631 2632 2633 2634 2635 2636 2637 2638
        input_layer = self.get_input_layer(0)
        row_conv_conf = self.config.inputs[0].row_conv_conf
        row_conv_conf.context_length = context_length
        self.set_layer_size(input_layer.size)
        psize = context_length * input_layer.size
        dims = [context_length, input_layer.size]
        self.create_input_parameter(0, psize, dims)


G
guosheng 已提交
2639 2640
@config_layer('clip')
class ClipLayer(LayerBase):
2641 2642
    def __init__(self, name, inputs, min, max, **xargs):
        super(ClipLayer, self).__init__(name, 'clip', 0, inputs=inputs, **xargs)
G
guosheng 已提交
2643 2644
        config_assert(
            len(self.inputs) == 1,
2645 2646
            'ClipLayer must have one and only one input.')
        config_assert(min < max, 'min must be less than max.')
G
guosheng 已提交
2647 2648
        input_layer = self.get_input_layer(0)
        self.set_layer_size(input_layer.size)
2649 2650
        self.config.inputs[0].clip_conf.min = min
        self.config.inputs[0].clip_conf.max = max
G
guosheng 已提交
2651 2652


G
guosheng 已提交
2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666
@config_layer('scale_shift')
class ScaleShiftLayer(LayerBase):
    def __init__(self, name, inputs, bias=True, **xargs):
        super(ScaleShiftLayer, self).__init__(
            name, 'scale_shift', 0, inputs=inputs, **xargs)
        config_assert(
            len(self.inputs) == 1,
            'ScaleShiftLayer must have one and only one input.')
        input_layer = self.get_input_layer(0)
        self.set_layer_size(input_layer.size)
        self.create_input_parameter(0, 1, [1, 1])
        self.create_bias_parameter(bias, 1)


Z
zhangjinchao01 已提交
2667 2668 2669 2670
# key: cost type
# value: cost class
g_cost_map = {}

Q
qijun 已提交
2671

Z
zhangjinchao01 已提交
2672 2673 2674
# define a cost layer without any parameters
def define_cost(class_name, cost_type):
    def init(cls, name, inputs, device=None, coeff=1.):
Q
qijun 已提交
2675 2676
        super(type(cls), cls).__init__(
            name, cost_type, 1, inputs, device=device, coeff=coeff)
Z
zhangjinchao01 已提交
2677

Q
qijun 已提交
2678
    cls = type(class_name, (LayerBase, ), dict(__init__=init))
Z
zhangjinchao01 已提交
2679 2680 2681
    global g_cost_map
    g_cost_map[cost_type] = cls

Q
qijun 已提交
2682

Z
zhangjinchao01 已提交
2683
define_cost('MultiClassCrossEntropy', 'multi-class-cross-entropy')
C
caoying03 已提交
2684
define_cost('CrossEntropyOverBeamCostLayer', 'cross_entropy_over_beam')
Z
zhangjinchao01 已提交
2685 2686 2687 2688 2689 2690
define_cost('RankingCost', 'rank-cost')
define_cost('AucValidation', 'auc-validation')
define_cost('PnpairValidation', 'pnpair-validation')
define_cost('SumOfSquaresCostLayer', 'square_error')
define_cost('MultiBinaryLabelCrossEntropy', 'multi_binary_label_cross_entropy')
define_cost('SoftBinaryClassCrossEntropy', 'soft_binary_class_cross_entropy')
2691
define_cost('HuberTwoClassification', 'huber_classification')
X
xuwei06 已提交
2692
define_cost('SumCost', 'sum_cost')
D
dangqingqing 已提交
2693
define_cost('SmoothL1Cost', 'smooth_l1')
Z
zhangjinchao01 已提交
2694

Q
qijun 已提交
2695

Z
zhangjinchao01 已提交
2696 2697
@config_layer('hsigmoid')
class HierarchicalSigmoidLayer(LayerBase):
Q
qijun 已提交
2698
    def __init__(self, name, num_classes, inputs, device=None, bias=True):
Z
zhangjinchao01 已提交
2699 2700
        super(HierarchicalSigmoidLayer, self).__init__(
            name, 'hsigmoid', 1, inputs=inputs, device=device)
Q
qijun 已提交
2701 2702 2703
        config_assert(
            len(self.inputs) >= 2,
            'HierarchicalSigmoidLayer must have at least 2 inputs')
Z
zhangjinchao01 已提交
2704 2705 2706 2707 2708 2709 2710 2711
        self.config.num_classes = num_classes
        for input_index in xrange(len(self.inputs) - 1):
            input_layer = self.get_input_layer(input_index)
            psize = (num_classes - 1) * input_layer.size
            dims = [num_classes - 1, input_layer.size]
            self.create_input_parameter(input_index, psize, dims)
        self.create_bias_parameter(bias, num_classes - 1)

Q
qijun 已提交
2712

Z
zhangjinchao01 已提交
2713 2714 2715 2716 2717 2718 2719 2720
'''
lambdaCost for lambdaRank LTR approach

Usage:
  Example: Layer(name = "cost", type = "lambda_cost", NDCG_num = 8,
             max_sort_size = -1, inputs = ["output", "score"])

  Input data: Samples of the same query should be loaded as a sequence,
L
Luo Tao 已提交
2721
          by PyDataProvider etc.. User should provide
Z
zhangjinchao01 已提交
2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736
          scores for each sample. The score slot should be the 2nd
          input of lambdaRank layer.

  NDCG_num = the size of NDCG, e.g., 5 for NDCG@5.
    Note: NDCG_num must be less than or equal to the minimum
          size of lists.

  max_sort_size = the size of partial sorting in calculating gradient.
    Note: If max_sort_size = -1, then for each list, the algorithm will
          sort the entire list to get gradient.
          In other cases, max_sort_size must be greater than or equal
          to NDCG_num.
          max_sort_size can be greater than the size of a list, in which
          case the algorithm will sort the entire list to get gradient.
'''
Q
qijun 已提交
2737 2738


Z
zhangjinchao01 已提交
2739 2740
@config_layer('lambda_cost')
class LambdaCost(LayerBase):
Q
qijun 已提交
2741
    def __init__(self, name, inputs, NDCG_num=5, max_sort_size=-1, device=None):
Z
zhangjinchao01 已提交
2742 2743
        super(LambdaCost, self).__init__(
            name, 'lambda_cost', 1, inputs=inputs, device=device)
Q
qijun 已提交
2744
        config_assert(len(self.inputs) == 2, 'lambdaCost must have 2 inputs')
Z
zhangjinchao01 已提交
2745 2746
        self.config.NDCG_num = NDCG_num
        if max_sort_size != -1:
Q
qijun 已提交
2747 2748 2749
            config_assert(
                NDCG_num <= max_sort_size,
                'NDCG_num must be less than or equal to max_sort_size')
Z
zhangjinchao01 已提交
2750 2751
        self.config.max_sort_size = max_sort_size

Q
qijun 已提交
2752

L
Luo Tao 已提交
2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763
@config_layer('huber_regression')
class HuberRegressionLoss(LayerBase):
    def __init__(self, name, inputs, delta=1., coeff=1., device=None):
        super(HuberRegressionLoss, self).__init__(
            name, 'huber_regression', 1, inputs=inputs, device=device)
        config_assert(
            len(self.inputs) == 2, 'HuberRegression must have 2 inputs')
        self.config.delta = delta
        self.config.coeff = coeff


Z
zhangjinchao01 已提交
2764 2765
@config_layer('nce')
class NCELayer(LayerBase):
Q
qijun 已提交
2766 2767 2768 2769 2770 2771 2772 2773
    def __init__(self,
                 name,
                 num_classes,
                 inputs,
                 num_neg_samples=10,
                 neg_sampling_dist=None,
                 bias=True,
                 **xargs):
Z
zhangjinchao01 已提交
2774
        super(NCELayer, self).__init__(name, 'nce', 1, inputs=inputs, **xargs)
Q
qijun 已提交
2775 2776
        config_assert(
            len(self.inputs) >= 2, 'NCELayer must have at least 2 inputs')
Z
zhangjinchao01 已提交
2777 2778
        self.config.num_classes = num_classes
        if neg_sampling_dist is not None:
Q
qijun 已提交
2779 2780 2781 2782
            config_assert(
                len(neg_sampling_dist) == num_classes,
                'len(neg_sampling_dist)(%s) is not same as num_classes (%s)' %
                (len(neg_sampling_dist), num_classes))
Z
zhangjinchao01 已提交
2783
            s = sum(neg_sampling_dist)
Q
qijun 已提交
2784 2785 2786
            config_assert(
                abs(s - 1) < 1e-5,
                'The sum of neg_sampling_dist (%s) is not 1' % s)
Z
zhangjinchao01 已提交
2787 2788 2789 2790 2791

            self.config.neg_sampling_dist.extend(neg_sampling_dist)

        self.config.num_neg_samples = num_neg_samples
        num_real_inputs = len(self.inputs) - 1
Q
qijun 已提交
2792
        input_layer = self.get_input_layer(num_real_inputs)
Z
zhangjinchao01 已提交
2793 2794 2795 2796
        config_assert(input_layer.type == 'data',
                      'Expecting the last input layer of an nce layer to be '
                      'a data layer')

Q
qijun 已提交
2797 2798
        if (num_real_inputs > 1 and input_layer.size == 1 and
                self.get_input_layer(num_real_inputs - 1).type == 'data'):
Z
zhangjinchao01 已提交
2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811
            # This input layer is assumed to be a sample weight layer
            num_real_inputs -= 1

        for input_index in xrange(num_real_inputs):
            input_layer = self.get_input_layer(input_index)
            psize = num_classes * input_layer.size
            dims = [num_classes, input_layer.size]
            self.create_input_parameter(input_index, psize, dims)
        self.create_bias_parameter(bias, num_classes)


@config_layer('addto')
class AddToLayer(LayerBase):
T
tensor-tang 已提交
2812 2813
    layer_type = 'addto'

Q
qijun 已提交
2814
    def __init__(self, name, inputs, bias=True, **xargs):
T
tensor-tang 已提交
2815 2816 2817 2818
        use_mkldnn = bool(int(g_command_config_args.get("use_mkldnn", 0)))
        if self.layer_type == "mkldnn_addto":
            config_assert(use_mkldnn, "mkldnn_addto only support MKLDNN")
        self.layer_type = 'mkldnn_addto' if use_mkldnn else 'addto'
Z
zhangjinchao01 已提交
2819
        super(AddToLayer, self).__init__(
T
tensor-tang 已提交
2820
            name, self.layer_type, 0, inputs=inputs, **xargs)
Q
qijun 已提交
2821
        config_assert(len(inputs) > 0, 'inputs cannot be empty for AddToLayer')
2822

G
guosheng 已提交
2823 2824 2825 2826 2827 2828 2829 2830
        layer_size = self.get_input_layer(0).size
        # To reserve heght, width, depth.
        layer_with_hwc = self.get_input_layer(0)
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
            assert layer_size == input_layer.size
            if input_layer.height and input_layer.height and input_layer.height:
                layer_with_hwc = input_layer
2831

G
guosheng 已提交
2832 2833 2834
        self.set_layer_size(layer_with_hwc.size)
        self.set_layer_height_width(layer_with_hwc.height, layer_with_hwc.width)
        self.set_layer_depth(layer_with_hwc.depth)
Z
zhangjinchao01 已提交
2835 2836
        self.create_bias_parameter(bias, self.config.size)

Q
qijun 已提交
2837

T
tensor-tang 已提交
2838 2839 2840 2841 2842
@config_layer('mkldnn_addto')
class MKLDNNAddtoLayer(AddToLayer):
    layer_type = 'mkldnn_addto'


Z
zhangjinchao01 已提交
2843 2844
@config_layer('agent')
class AgentLayer(LayerBase):
Q
qijun 已提交
2845 2846 2847 2848
    def __init__(self, name, size, device=None):
        super(AgentLayer, self).__init__(
            name, 'agent', size, inputs=[], device=device)

Z
zhangjinchao01 已提交
2849 2850 2851

@config_layer('gather_agent')
class GatherAgentLayer(LayerBase):
Q
qijun 已提交
2852
    def __init__(self, name, size, device=None):
Z
zhangjinchao01 已提交
2853 2854 2855
        super(GatherAgentLayer, self).__init__(
            name, 'gather_agent', size, inputs=[], device=device)

Q
qijun 已提交
2856

Z
zhangjinchao01 已提交
2857 2858
@config_layer('scatter_agent')
class ScatterAgentLayer(LayerBase):
2859
    def __init__(self, name, size, width=None, height=None, device=None):
Z
zhangjinchao01 已提交
2860 2861
        super(ScatterAgentLayer, self).__init__(
            name, 'scatter_agent', size, inputs=[], device=device)
2862 2863
        if height and width:
            self.set_layer_height_width(height, width)
Z
zhangjinchao01 已提交
2864

Q
qijun 已提交
2865

Z
zhangjinchao01 已提交
2866 2867
@config_layer('multiplex')
class MultiplexLayer(LayerBase):
Q
qijun 已提交
2868 2869 2870 2871 2872
    def __init__(self, name, inputs, size, device=None):
        super(MultiplexLayer, self).__init__(
            name, 'multiplex', size, inputs=inputs, device=device)
        config_assert(
            len(inputs) > 2, 'MultiplexLayer should have more than 2 inputs.')
Z
zhangjinchao01 已提交
2873
        for i in range(1, len(inputs)):
Q
qijun 已提交
2874 2875 2876 2877 2878
            config_assert(
                self.get_input_layer(i).size == size,
                "All the input layers except the first one should"
                "have the same size as the MultiplexLayer.")

Z
zhangjinchao01 已提交
2879 2880

@config_func
2881 2882 2883 2884
def Link(name, has_subseq=False):
    """
    Still keeping has_subseq for backward compatibility
    """
Z
zhangjinchao01 已提交
2885 2886 2887 2888
    link_config = LinkConfig()
    link_config.link_name = name
    return link_config

Q
qijun 已提交
2889

Z
zhangjinchao01 已提交
2890 2891
# memory for recurrent layer group.
# *name* and *size* are actual layer's name and size.
2892 2893 2894 2895
# If *name* is None, need to provide *memory_name* and need to use
# SetMemoryInput() later to specify the layer which this memory remembers.
#
# return the name of the memory,
Z
zhangjinchao01 已提交
2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906
# use this name if you assign the memory as other layer's input
#
# boot frame of memory is zeroed by default,
# or initialize by boot layer output if *boot_layer* set,
# or initialize by trainable bias if *boot_bias* set,
# or initialize by a constant id if *boot_with_const_id* set
#
# Memory can be a sequence if *is_sequence* set, this type of memory
# can only be initailized by a *boot_layer* which is a sequence.
#
@config_func
2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918
def Memory(name,
           size,
           is_sequence=False,
           boot_layer=None,
           boot_bias=False,
           boot_bias_active_type="",
           boot_with_const_id=None,
           memory_name=None):
    if not memory_name:
        config_assert(name is not None, "name needs cannot be None")
        memory_name = name + "+delay1"
    agent_name = memory_name
2919
    agent_layer = AgentLayer(agent_name, size)
Z
zhangjinchao01 已提交
2920
    config_assert(g_current_submodel.is_recurrent_layer_group,
Q
qijun 已提交
2921
                  'Memory should be used in recurrent layer group only')
Z
zhangjinchao01 已提交
2922
    memory = g_current_submodel.memories.add()
2923 2924
    if name is not None:
        memory.layer_name = MakeLayerNameInSubmodel(name)
Z
zhangjinchao01 已提交
2925
    memory.link_name = MakeLayerNameInSubmodel(agent_name)
Q
qijun 已提交
2926
    options = sum((boot_layer is not None, bool(boot_bias),
Z
zhangjinchao01 已提交
2927
                   boot_with_const_id is not None))
Q
qijun 已提交
2928 2929 2930 2931
    config_assert(
        options <= 1,
        'take one option at most from boot_layer, boot_bias, or boot_with_const_id'
    )
Z
zhangjinchao01 已提交
2932 2933 2934
    if boot_layer is not None:
        boot_layer = MakeLayerNameInParentSubmodel(boot_layer)
        config_assert(boot_layer in g_layer_map,
Q
qijun 已提交
2935 2936
                      'boot_layer "%s" does not correspond to a layer name' %
                      boot_layer)
Z
zhangjinchao01 已提交
2937 2938 2939
        memory.boot_layer_name = boot_layer
    elif boot_bias:
        memory.boot_bias_parameter_name = agent_layer.create_bias_parameter(
Q
qijun 已提交
2940
            boot_bias, size, for_self=False)
Z
zhangjinchao01 已提交
2941 2942 2943 2944 2945
        memory.boot_bias_active_type = boot_bias_active_type
    elif boot_with_const_id is not None:
        memory.boot_with_const_id = boot_with_const_id
    return agent_name

Q
qijun 已提交
2946

2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957
@config_func
def SetMemoryInput(memory_name, layer_name):
    memory_name = MakeLayerNameInSubmodel(memory_name)
    layer_name = MakeLayerNameInSubmodel(layer_name)
    for mem in g_current_submodel.memories:
        if mem.link_name == memory_name:
            mem.layer_name = layer_name
            return
    logger.fatal("Nonexistent memory name: " + memory_name)


Z
zhangjinchao01 已提交
2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968
# Generator for recurrent layer group, to use it:
#  1. define a id layer as output of layer group
#  2. define a memory of this id layer, and assign a boot id(begin of sequence)
#  3. define a eos check layer and fill its name in generator's *eos_layer_name*
# Sequence generation will stop when eos check return 1 or *max_num_frames* reached.
# If *beam_size* is greater than one, generator will use beam search.
#   in beam search, if *num_results_per_sample* set, one sample sequence can output
#   multiple results each with a probility.
@config_func
def Generator(
        max_num_frames,
Q
qijun 已提交
2969 2970 2971 2972
        eos_layer_name="eos_check",
        num_results_per_sample=1,
        beam_size=1,
        log_prob=None, ):
Z
zhangjinchao01 已提交
2973 2974 2975 2976 2977 2978 2979 2980 2981
    generator_config = GeneratorConfig()
    generator_config.max_num_frames = max_num_frames
    generator_config.eos_layer_name = eos_layer_name
    generator_config.num_results_per_sample = num_results_per_sample
    generator_config.beam_size = beam_size
    if log_prob is not None:
        generator_config.log_prob = log_prob
    return generator_config

Q
qijun 已提交
2982

Z
zhangjinchao01 已提交
2983 2984
@config_layer('expand')
class ExpandLayer(LayerBase):
2985
    def __init__(self, name, inputs, trans_type='non-seq', bias=False, **xargs):
Q
qijun 已提交
2986
        super(ExpandLayer, self).__init__(
2987
            name, 'expand', 0, inputs=inputs, **xargs)
Q
qijun 已提交
2988 2989 2990 2991 2992 2993 2994 2995
        config_assert(
            len(self.inputs) == 2, 'ExpandLayer takes 2 and only 2 inputs')
        self.config.trans_type = trans_type
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
        self.set_layer_size(self.get_input_layer(0).size)
        self.create_bias_parameter(bias, self.config.size)

Z
zhangjinchao01 已提交
2996 2997 2998

@config_layer('featmap_expand')
class FeatMapExpandLayer(LayerBase):
X
xuwei06 已提交
2999 3000 3001 3002 3003
    def __init__(self,
                 name,
                 inputs,
                 num_filters=None,
                 as_row_vector=True,
X
xuwei06 已提交
3004 3005
                 bias=False,
                 **xargs):
Q
qijun 已提交
3006
        super(FeatMapExpandLayer, self).__init__(
X
xuwei06 已提交
3007
            name, 'featmap_expand', 0, inputs=inputs, **xargs)
Q
qijun 已提交
3008 3009 3010
        config_assert(
            len(self.inputs) == 1, 'ExpandLayer takes 1 and only 1 inputs')
        if num_filters is not None:
Z
zhangjinchao01 已提交
3011
            self.config.num_filters = num_filters
Q
qijun 已提交
3012
        else:
Z
zhangjinchao01 已提交
3013
            logger.fatal("FeatMapExpandLayer must specify num_filters.")
X
xuwei06 已提交
3014 3015
        if not as_row_vector:
            self.config.user_arg = "as_col_vec"
Q
qijun 已提交
3016
        self.set_layer_size(self.get_input_layer(0).size * num_filters)
Z
zhangjinchao01 已提交
3017 3018 3019 3020


@config_layer('max')
class MaxLayer(LayerBase):
Q
qijun 已提交
3021 3022 3023 3024 3025
    def __init__(self,
                 name,
                 inputs,
                 trans_type='non-seq',
                 bias=False,
3026
                 output_max_index=None,
3027
                 stride=-1,
3028
                 **xargs):
3029
        super(MaxLayer, self).__init__(name, 'max', 0, inputs=inputs, **xargs)
Z
zhangjinchao01 已提交
3030
        config_assert(len(self.inputs) == 1, 'MaxLayer must have 1 input')
3031 3032
        if trans_type == 'seq':
            config_assert(stride == -1, 'subseq does not support stride window')
Q
qijun 已提交
3033
        self.config.trans_type = trans_type
3034
        self.config.seq_pool_stride = stride
Z
zhangjinchao01 已提交
3035 3036 3037 3038
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
            self.set_layer_size(input_layer.size)
        self.create_bias_parameter(bias, self.config.size)
3039 3040
        if output_max_index is not None:
            self.config.output_max_index = output_max_index
Z
zhangjinchao01 已提交
3041 3042 3043 3044


@config_layer('maxid')
class MaxIdLayer(LayerBase):
Q
qijun 已提交
3045
    def __init__(self, name, inputs, beam_size=None, device=None):
Z
zhangjinchao01 已提交
3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062
        super(MaxIdLayer, self).__init__(
            name, 'maxid', 0, inputs=inputs, device=device)
        config_assert(len(self.inputs) == 1, 'MaxIdLayer must have 1 input')
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
            self.set_layer_size(input_layer.size)

        if beam_size is None:
            global g_current_submodel
            if g_current_submodel.HasField("generator"):
                self.config.beam_size = g_current_submodel.generator.beam_size
        else:
            self.config.beam_size = beam_size


@config_layer('eos_id')
class EosIdLayer(LayerBase):
Q
qijun 已提交
3063
    def __init__(self, name, inputs, eos_id, device=None):
Z
zhangjinchao01 已提交
3064 3065 3066
        super(EosIdLayer, self).__init__(
            name, 'eos_id', 0, inputs=inputs, device=device)
        config_assert(len(self.inputs) == 1, 'EosIdLayer must have 1 input')
Q
qijun 已提交
3067
        self.set_layer_size(2)  # boolean output
Z
zhangjinchao01 已提交
3068 3069
        self.config.eos_id = eos_id

Q
qijun 已提交
3070

Z
zhangjinchao01 已提交
3071 3072
@config_layer('seqlastins')
class SequenceLastInstanceLayer(LayerBase):
Q
qijun 已提交
3073 3074 3075 3076
    def __init__(self,
                 name,
                 inputs,
                 trans_type='non-seq',
3077
                 bias=False,
3078
                 stride=-1,
3079
                 **xargs):
Q
qijun 已提交
3080
        super(SequenceLastInstanceLayer, self).__init__(
X
xuwei06 已提交
3081
            name, 'seqlastins', 0, inputs=inputs, **xargs)
Q
qijun 已提交
3082 3083
        config_assert(
            len(inputs) == 1, 'SequenceLastInstanceLayer must have 1 input')
3084
        if trans_type == 'seq':
L
Luo Tao 已提交
3085
            config_assert(stride == -1, 'subseq does not support stride window')
Q
qijun 已提交
3086
        self.config.trans_type = trans_type
3087 3088
        self.config.seq_pool_stride = stride
        self.set_layer_size(self.get_input_layer(0).size)
Z
zhangjinchao01 已提交
3089 3090
        self.create_bias_parameter(bias, self.config.size)

Q
qijun 已提交
3091

Z
zhangjinchao01 已提交
3092 3093
@config_layer('seqfirstins')
class SequenceFirstInstanceLayer(SequenceLastInstanceLayer):
3094 3095 3096 3097 3098
    def __init__(self,
                 name,
                 inputs,
                 trans_type='non-seq',
                 bias=False,
3099
                 stride=-1,
3100
                 **xargs):
Q
qijun 已提交
3101
        super(SequenceFirstInstanceLayer, self).__init__(
3102 3103 3104 3105 3106 3107
            name,
            inputs=inputs,
            trans_type=trans_type,
            bias=bias,
            stride=stride,
            **xargs)
Z
zhangjinchao01 已提交
3108 3109
        self.config.select_first = True

Q
qijun 已提交
3110

Z
zhangjinchao01 已提交
3111 3112
@config_layer('seqconcat')
class SequenceConcatLayer(LayerBase):
X
xuwei06 已提交
3113
    def __init__(self, name, inputs, bias=False, **xargs):
Q
qijun 已提交
3114
        super(SequenceConcatLayer, self).__init__(
X
xuwei06 已提交
3115
            name, 'seqconcat', 0, inputs=inputs, **xargs)
Q
qijun 已提交
3116 3117
        config_assert(
            len(inputs) == 2, 'SequenceConcatLayer must have 2 inputs')
Z
zhangjinchao01 已提交
3118 3119 3120 3121 3122
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
            self.set_layer_size(input_layer.size)
        self.create_bias_parameter(bias, self.config.size)

Q
qijun 已提交
3123

Z
zhangjinchao01 已提交
3124 3125
@config_layer('seqreshape')
class SequenceReshapeLayer(LayerBase):
X
xuwei06 已提交
3126
    def __init__(self, name, size, inputs, bias=False, **xargs):
Q
qijun 已提交
3127
        super(SequenceReshapeLayer, self).__init__(
X
xuwei06 已提交
3128
            name, 'seqreshape', size, inputs=inputs, **xargs)
Q
qijun 已提交
3129 3130
        config_assert(
            len(inputs) == 1, 'SequenceReshapeLayer must have 1 inputs')
Z
zhangjinchao01 已提交
3131 3132 3133
        self.set_layer_size(size)
        self.create_bias_parameter(bias, size)

Q
qijun 已提交
3134

Z
zhangjinchao01 已提交
3135 3136
@config_layer('subseq')
class SubSequenceLayer(LayerBase):
X
xuwei06 已提交
3137
    def __init__(self, name, inputs, bias=False, **xargs):
Q
qijun 已提交
3138
        super(SubSequenceLayer, self).__init__(
X
xuwei06 已提交
3139
            name, 'subseq', 0, inputs=inputs, **xargs)
Z
zhangjinchao01 已提交
3140 3141 3142 3143 3144 3145
        config_assert(len(inputs) == 3, 'SubSequenceLayer must have 3 inputs')
        input_layer0 = self.get_input_layer(0)
        size = input_layer0.size
        self.set_layer_size(size)
        self.create_bias_parameter(bias, size)

Q
qijun 已提交
3146

3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175
@config_layer('seq_slice')
class SeqSliceLayer(LayerBase):
    def __init__(self, name, inputs, starts, ends, bias=False, **xargs):
        if isinstance(inputs, list):
            assert len(inputs) == 1, ('the first input of sequence slice layer '
                                      'is a single sequence input.')
        else:
            inputs = [inputs]

        if starts is not None:
            if isinstance(starts, list):
                assert len(starts) == 1, (
                    'the start indices for sequence slice layer cannot '
                    'be a list having more than one element.')
                starts = starts[0]
            inputs.append(starts)

        if ends is not None:
            if isinstance(ends, list):
                assert len(ends) == 1, (
                    'the end indices for sequence slice layer cannot '
                    'be a list having more than one element.')
                ends = ends[0]
            inputs.append(ends)
        assert len(inputs) >= 2, (
            'the sequence slice layer has at least two inputs.')

        super(SeqSliceLayer, self).__init__(
            name, 'seq_slice', 0, inputs=inputs, **xargs)
3176

3177 3178 3179 3180 3181 3182 3183 3184 3185 3186
        input_layer0 = self.get_input_layer(0)
        size = input_layer0.size
        self.set_layer_size(size)

        if len(inputs) == 3:
            assert (
                self.get_input_layer(1).size == self.get_input_layer(2).size), (
                    'If start and end indices are both given to'
                    'sequence slice layer, they should have the same width.')
        elif len(inputs) == 2:
C
caoying03 已提交
3187
            self.config.select_first = (starts is not None)
3188 3189


C
caoying03 已提交
3190 3191
@config_layer('sub_nested_seq')
class SubNestedSequenceLayer(LayerBase):
3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203
    def __init__(self, name, inputs, selected_indices, bias=False, **xargs):
        if isinstance(inputs, list):
            assert len(inputs) == 1, ('the first input of sub_nested_seq '
                                      'layer is a single nested sequence.')
            inputs = inputs[0]
        if isinstance(selected_indices, list):
            assert len(selected_indices) == 1, (
                'the second input of '
                'sub_nested_seq layer is a single layer which is a '
                'set of selected indices.')
            selected_indices = selected_indices[0]

C
caoying03 已提交
3204
        super(SubNestedSequenceLayer, self).__init__(
3205 3206 3207 3208 3209
            name,
            'sub_nested_seq',
            0,
            inputs=[inputs, selected_indices],
            **xargs)
C
caoying03 已提交
3210 3211 3212 3213 3214
        input_layer0 = self.get_input_layer(0)
        size = input_layer0.size
        self.set_layer_size(size)


R
ranqiu 已提交
3215 3216 3217 3218 3219
@config_layer('dot_prod')
class DotProdLayer(LayerBase):
    def __init__(self, name, inputs, device=None):
        super(DotProdLayer, self).__init__(
            name, 'dot_prod', 0, inputs, device=device)
R
ranqiu 已提交
3220 3221 3222 3223
        config_assert(len(inputs) == 2, 'DotProdLayer must have 2 inputs.')
        config_assert(
            self.get_input_layer(0).size == self.get_input_layer(1).size,
            "Two inputs should have the same size.")
R
ranqiu 已提交
3224 3225 3226
        self.set_layer_size(1)


Z
zhangjinchao01 已提交
3227 3228
@config_layer('out_prod')
class OuterProdLayer(LayerBase):
Q
qijun 已提交
3229 3230 3231
    def __init__(self, name, inputs, device=None):
        super(OuterProdLayer, self).__init__(
            name, 'out_prod', 0, inputs=inputs, device=device)
Z
zhangjinchao01 已提交
3232 3233 3234 3235 3236
        config_assert(len(inputs) == 2, 'OuterProdLayer must have 2 inputs')
        input_layer0 = self.get_input_layer(0)
        input_layer1 = self.get_input_layer(1)
        self.set_layer_size(input_layer0.size * input_layer1.size)

Q
qijun 已提交
3237

Z
zhangjinchao01 已提交
3238 3239
@config_layer('power')
class PowerLayer(LayerBase):
Q
qijun 已提交
3240 3241 3242
    def __init__(self, name, inputs, device=None):
        super(PowerLayer, self).__init__(
            name, 'power', 0, inputs=inputs, device=device)
Z
zhangjinchao01 已提交
3243 3244 3245 3246
        config_assert(len(inputs) == 2, 'PowerLayer must have 2 inputs')
        input_layer1 = self.get_input_layer(1)
        self.set_layer_size(input_layer1.size)
        input_layer0 = self.get_input_layer(0)
Q
qijun 已提交
3247 3248 3249
        config_assert(1 == input_layer0.size,
                      'The left input is the exponent and should be of size 1')

Z
zhangjinchao01 已提交
3250 3251 3252

@config_layer('slope_intercept')
class SlopeInterceptLayer(LayerBase):
Q
qijun 已提交
3253 3254 3255
    def __init__(self, name, inputs, slope=1.0, intercept=0.0, device=None):
        super(SlopeInterceptLayer, self).__init__(
            name, 'slope_intercept', 0, inputs=inputs, device=device)
Z
zhangjinchao01 已提交
3256 3257 3258 3259 3260 3261
        self.config.slope = slope
        self.config.intercept = intercept
        config_assert(len(inputs) == 1, 'SlopeInterceptLayer must have 1 input')
        input_layer0 = self.get_input_layer(0)
        self.set_layer_size(input_layer0.size)

Q
qijun 已提交
3262

Z
zhangjinchao01 已提交
3263 3264
@config_layer('scaling')
class ScalingLayer(LayerBase):
Q
qijun 已提交
3265 3266 3267
    def __init__(self, name, inputs, device=None):
        super(ScalingLayer, self).__init__(
            name, 'scaling', 0, inputs=inputs, device=device)
Z
zhangjinchao01 已提交
3268 3269 3270 3271
        config_assert(len(inputs) == 2, 'ScalingLayer must have 2 inputs')
        input_layer1 = self.get_input_layer(1)
        self.set_layer_size(input_layer1.size)
        input_layer0 = self.get_input_layer(0)
Q
qijun 已提交
3272 3273 3274
        config_assert(1 == input_layer0.size,
                      'The left input should be of size 1')

Z
zhangjinchao01 已提交
3275 3276 3277

@config_layer('conv_shift')
class ConvShiftLayer(LayerBase):
Q
qijun 已提交
3278 3279 3280
    def __init__(self, name, inputs, device=None):
        super(ConvShiftLayer, self).__init__(
            name, 'conv_shift', 0, inputs=inputs, device=device)
Z
zhangjinchao01 已提交
3281 3282 3283 3284
        config_assert(len(inputs) == 2, 'ConvShiftLayer must have 2 inputs')
        input_layer0 = self.get_input_layer(0)
        self.set_layer_size(input_layer0.size)

Q
qijun 已提交
3285

Z
zhangjinchao01 已提交
3286 3287
@config_layer('convex_comb')
class ConvexCombinationLayer(LayerBase):
Q
qijun 已提交
3288
    def __init__(self, name, size, inputs, device=None):
Z
zhangjinchao01 已提交
3289
        super(ConvexCombinationLayer, self).__init__(
Q
qijun 已提交
3290 3291 3292
            name, 'convex_comb', size, inputs=inputs, device=device)
        config_assert(
            len(self.inputs) == 2, 'ConvexCombinationLayer must have 2 inputs')
3293 3294 3295
        config_assert(
            size * self.get_input_layer(0).size == self.get_input_layer(1).size,
            'Wrong input size for ConvexCombinationLayer')
Z
zhangjinchao01 已提交
3296 3297
        self.set_layer_size(size)

Q
qijun 已提交
3298

Z
zhangjinchao01 已提交
3299 3300
@config_layer('interpolation')
class InterpolationLayer(LayerBase):
Q
qijun 已提交
3301
    def __init__(self, name, inputs, device=None):
Z
zhangjinchao01 已提交
3302 3303
        super(InterpolationLayer, self).__init__(
            name, 'interpolation', 0, inputs=inputs, device=device)
Q
qijun 已提交
3304 3305
        config_assert(
            len(self.inputs) == 3, 'InterpolationLayer must have 3 inputs')
Z
zhangjinchao01 已提交
3306 3307 3308 3309 3310 3311 3312 3313
        input_layer0 = self.get_input_layer(0)
        input_layer1 = self.get_input_layer(1)
        input_layer2 = self.get_input_layer(2)
        self.set_layer_size(input_layer1.size)
        config_assert(input_layer0.size == 1, 'weight should be of size 1')
        config_assert(input_layer1.size == input_layer2.size,
                      'the two vector inputs should be of the same size')

Q
qijun 已提交
3314

L
liaogang 已提交
3315 3316
@config_layer('bilinear_interp')
class BilinearInterpLayer(LayerBase):
Q
qijun 已提交
3317
    def __init__(self, name, inputs, **xargs):
L
liaogang 已提交
3318
        super(BilinearInterpLayer, self).__init__(
L
liaogang 已提交
3319
            name, 'bilinear_interp', 0, inputs=inputs, **xargs)
L
liaogang 已提交
3320
        input_layer = self.get_input_layer(0)
L
Luo Tao 已提交
3321 3322 3323 3324
        conf = self.config.inputs[0].bilinear_interp_conf
        parse_bilinear(self.inputs[0].bilinear_interp, input_layer.name, conf)
        self.set_cnn_layer(name, conf.out_size_y, conf.out_size_x,
                           conf.image_conf.channels)
Q
qijun 已提交
3325

L
liaogang 已提交
3326

Z
zhangjinchao01 已提交
3327 3328
@config_layer('sum_to_one_norm')
class SumToOneNormLayer(LayerBase):
Q
qijun 已提交
3329
    def __init__(self, name, inputs, device=None):
Z
zhangjinchao01 已提交
3330
        super(SumToOneNormLayer, self).__init__(
Q
qijun 已提交
3331 3332 3333
            name, 'sum_to_one_norm', 0, inputs=inputs, device=device)
        config_assert(
            len(self.inputs) == 1, 'SumToOneNormLayer must have 1 input')
Z
zhangjinchao01 已提交
3334 3335 3336
        input_layer0 = self.get_input_layer(0)
        self.set_layer_size(input_layer0.size)

Q
qijun 已提交
3337

G
guosheng 已提交
3338 3339
@config_layer('row_l2_norm')
class RowL2NormLayer(LayerBase):
3340
    def __init__(self, name, inputs, **xargs):
G
guosheng 已提交
3341
        super(RowL2NormLayer, self).__init__(
3342
            name, 'row_l2_norm', 0, inputs=inputs, **xargs)
G
guosheng 已提交
3343
        config_assert(len(self.inputs) == 1, 'RowL2NormLayer must have 1 input')
3344 3345
        input_layer = self.get_input_layer(0)
        self.set_layer_size(input_layer.size)
G
guosheng 已提交
3346 3347


C
caoying03 已提交
3348 3349 3350 3351 3352
@config_layer('cos')
class CosSimLayer(LayerBase):
    def __init__(self, name, inputs, cos_scale=1, device=None):
        super(CosSimLayer, self).__init__(
            name, 'cos', 1, inputs=inputs, device=device)
3353 3354 3355
        config_assert(
            len(self.inputs) == 2,
            'The CosSimLayer expects two and only two inputs.')
C
caoying03 已提交
3356 3357
        config_assert(
            self.get_input_layer(0).size == self.get_input_layer(1).size,
C
caoying03 已提交
3358
            'The two inputs of CosSimLayer must have the same dimensionality.')
C
caoying03 已提交
3359 3360 3361
        self.config.cos_scale = cos_scale


Z
zhangjinchao01 已提交
3362 3363
@config_layer('cos_vm')
class CosSimVecMatLayer(LayerBase):
Q
qijun 已提交
3364
    def __init__(self, name, size, inputs, cos_scale=1.0, device=None):
Z
zhangjinchao01 已提交
3365
        super(CosSimVecMatLayer, self).__init__(
Q
qijun 已提交
3366
            name, 'cos_vm', size, inputs=inputs, device=device)
Z
zhangjinchao01 已提交
3367
        self.config.cos_scale = cos_scale
Q
qijun 已提交
3368
        config_assert(
3369
            len(self.inputs) == 2, 'The CosSimVecMatLayer must have 2 inputs.')
3370 3371
        config_assert(
            size * self.get_input_layer(0).size == self.get_input_layer(1).size,
3372
            'Wrong input size for CosSimVecMatLayer.')
Z
zhangjinchao01 已提交
3373

Q
qijun 已提交
3374

C
caoying03 已提交
3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386
@config_layer('l2_distance')
class L2DistanceLayer(LayerBase):
    def __init__(self, name, inputs, device=None):
        super(L2DistanceLayer, self).__init__(
            name, 'l2_distance', 1, inputs=inputs, device=device)
        config_assert(
            len(self.inputs) == 2, ('The L2DistanceLayer must have '
                                    'and only have 2 inputs.'))
        config_assert(
            self.get_input_layer(0).size == self.get_input_layer(1).size,
            ('Two inputs of the L2DistanceLayer must have '
             'the same dimensionality.'))
Z
zhangjinchao01 已提交
3387

Q
qijun 已提交
3388

Z
zhangjinchao01 已提交
3389 3390
@config_layer('sampling_id')
class SamplingIdLayer(LayerBase):
Q
qijun 已提交
3391
    def __init__(self, name, inputs, device=None):
Z
zhangjinchao01 已提交
3392 3393
        super(SamplingIdLayer, self).__init__(
            name, 'sampling_id', 0, inputs=inputs, device=device)
Q
qijun 已提交
3394 3395
        config_assert(
            len(self.inputs) == 1, 'SamplingIdLayer must have 1 input')
Z
zhangjinchao01 已提交
3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
            self.set_layer_size(input_layer.size)


# AverageLayer: "average" for each sample within a sequence.
# average_stratrgy: set to one of the following:
# 'average': plain average.
# 'sum': sum each sample instead of average (which is divide by sample_num).
# 'squarerootn': sum each sample, but divide by sqrt(sample_num).
@config_layer('average')
class AverageLayer(LayerBase):
Q
qijun 已提交
3408 3409 3410 3411 3412
    def __init__(self,
                 name,
                 inputs,
                 average_strategy='average',
                 trans_type='non-seq',
3413
                 bias=False,
3414
                 stride=-1,
3415
                 **xargs):
Q
qijun 已提交
3416
        super(AverageLayer, self).__init__(
X
xuwei06 已提交
3417
            name, 'average', 0, inputs=inputs, **xargs)
Z
zhangjinchao01 已提交
3418
        self.config.average_strategy = average_strategy
3419 3420
        if trans_type == 'seq':
            config_assert(stride == -1, 'subseq does not support stride window')
Q
qijun 已提交
3421
        self.config.trans_type = trans_type
3422
        self.config.seq_pool_stride = stride
Z
zhangjinchao01 已提交
3423 3424 3425 3426 3427 3428
        config_assert(len(inputs) == 1, 'AverageLayer must have 1 input')
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
            self.set_layer_size(input_layer.size)
        self.create_bias_parameter(bias, self.config.size)

Q
qijun 已提交
3429

Z
zhangjinchao01 已提交
3430 3431
@config_layer('tensor')
class TensorLayer(LayerBase):
3432
    def __init__(self, name, size, inputs, bias=True, **xargs):
Q
qijun 已提交
3433
        super(TensorLayer, self).__init__(
3434
            name, 'tensor', size, inputs=inputs, **xargs)
Z
zhangjinchao01 已提交
3435 3436
        config_assert(len(self.inputs) == 2, 'TensorLayer must have 2 inputs')
        config_assert(size > 0, 'size must be positive')
Q
qijun 已提交
3437 3438
        config_assert(inputs[1].parameter_name == None,
                      'second parameter should be None.')
Z
zhangjinchao01 已提交
3439 3440 3441 3442 3443 3444 3445 3446 3447 3448
        input_layer0 = self.get_input_layer(0)
        input_layer1 = self.get_input_layer(1)
        psize = size * input_layer0.size * input_layer1.size
        dims = [input_layer0.size, input_layer1.size, size]
        self.create_input_parameter(0, psize, dims)
        self.create_bias_parameter(bias, size)


@config_layer('mixed')
class MixedLayer(LayerBase):
C
caoying03 已提交
3449
    def __init__(self, name, inputs, size=0, bias=True, **xargs):
Z
zhangjinchao01 已提交
3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466
        config_assert(inputs, 'inputs cannot be empty')
        super(MixedLayer, self).__init__(
            name, 'mixed', size, inputs=inputs, **xargs)
        operator_input_index = []
        for operator in self.operators:
            operator_conf = operator.operator_conf
            for i in xrange(1, len(operator.input_layer_names)):
                input_index = len(self.config.inputs)
                operator_conf.input_indices.append(input_index)
                input_config = Input(operator.input_layer_names[i])
                self.inputs.append(input_config)
                layer_input = self.config.inputs.add()
                layer_input.input_layer_name = input_config.input_layer_name
            for input_index in operator_conf.input_indices:
                input_layer = self.get_input_layer(input_index)
                operator_conf.input_sizes.append(input_layer.size)
                operator_input_index.append(input_index)
3467
            if self.config.size == 0:
Z
zhangjinchao01 已提交
3468 3469 3470
                size = operator.calc_output_size(operator_conf.input_sizes)
                if size != 0:
                    self.set_layer_size(size)
3471
            else:
3472 3473
                sz = operator.calc_output_size(operator_conf.input_sizes)
                if sz != 0:
Q
qijun 已提交
3474 3475 3476 3477
                    config_assert(
                        sz == self.config.size,
                        "different inputs have different size: %s vs. %s" %
                        (sz, self.config.size))
Z
zhangjinchao01 已提交
3478 3479 3480 3481
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
            input = self.inputs[input_index]
            if input_index not in operator_input_index:
Q
qijun 已提交
3482 3483 3484
                config_assert(
                    isinstance(input, Projection),
                    "input should be projection or operation")
3485
            if self.config.size == 0 and isinstance(input, Projection):
Z
zhangjinchao01 已提交
3486 3487 3488
                size = input.calc_output_size(input_layer)
                if size != 0:
                    self.set_layer_size(size)
3489
            elif isinstance(input, Projection):
Q
qijun 已提交
3490 3491 3492 3493 3494 3495
                sz = input.calc_output_size(input_layer)
                if sz != 0:
                    config_assert(
                        sz == self.config.size,
                        "different inputs have different size: %s vs. %s" %
                        (sz, self.config.size))
Z
zhangjinchao01 已提交
3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506
        config_assert(size != 0, "size is not set")

        for input_index in xrange(len(self.inputs)):
            input = self.inputs[input_index]
            if isinstance(input, Projection):
                input_layer = self.get_input_layer(input_index)
                input.proj_conf.input_size = input_layer.size
                input.proj_conf.output_size = size

                input_config = self.config.inputs[input_index]
                input_config.proj_conf.CopyFrom(input.proj_conf)
Q
qijun 已提交
3507 3508
                input_config.proj_conf.name = gen_parameter_name(name,
                                                                 input_index)
Z
zhangjinchao01 已提交
3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519
                psize = input.calc_parameter_size(input_layer.size, size)
                dims = input.calc_parameter_dims(input_layer.size, size)
                self.create_input_parameter(input_index, psize, dims)

        for operator in self.operators:
            operator_conf = operator.operator_conf
            operator_conf.output_size = self.config.size
            operator.check_dims()
            record_operator_conf = self.config.operator_confs.add()
            record_operator_conf.CopyFrom(operator_conf)

3520 3521 3522 3523 3524 3525
        psize = self.config.size
        if isinstance(self.inputs[0], ConvProjection):
            self.config.shared_biases = True
            psize = 0
            for input in self.inputs:
                psize += input.calc_bias_size()
Z
zhangjinchao01 已提交
3526

3527 3528 3529
        if bias:
            self.config.bias_size = psize
            self.create_bias_parameter(bias, psize)
Z
zhangjinchao01 已提交
3530

Q
qijun 已提交
3531

Z
zhangjinchao01 已提交
3532 3533
# like MixedLayer, but no bias parameter
@config_func
Q
qijun 已提交
3534
def ExpressionLayer(name, inputs, **xargs):
Z
zhangjinchao01 已提交
3535 3536
    MixedLayer(name, inputs, bias=False, **xargs)

Q
qijun 已提交
3537

Z
zhangjinchao01 已提交
3538 3539
@config_layer('concat')
class ConcatenateLayer(LayerBase):
3540 3541
    layer_type = 'concat'

Q
qijun 已提交
3542
    def __init__(self, name, inputs, bias=False, **xargs):
Z
zhangjinchao01 已提交
3543
        config_assert(inputs, 'inputs cannot be empty')
3544
        config_assert(not bias, 'ConcatenateLayer cannot support bias.')
3545 3546 3547 3548
        use_mkldnn = bool(int(g_command_config_args.get("use_mkldnn", 0)))
        if self.layer_type == "mkldnn_concat":
            config_assert(use_mkldnn, "mkldnn_concat only support MKLDNN")
        self.layer_type = 'mkldnn_concat' if use_mkldnn else 'concat'
Z
zhangjinchao01 已提交
3549
        super(ConcatenateLayer, self).__init__(
3550
            name, self.layer_type, 0, inputs=inputs, **xargs)
Z
zhangjinchao01 已提交
3551 3552
        size = 0
        for input_index in xrange(len(self.inputs)):
3553 3554 3555 3556 3557 3558
            assert self.get_input_layer(0).height == self.get_input_layer(
                input_index).height
            assert self.get_input_layer(0).width == self.get_input_layer(
                input_index).width
            assert self.get_input_layer(0).depth == self.get_input_layer(
                input_index).depth
Z
zhangjinchao01 已提交
3559 3560
            input_layer = self.get_input_layer(input_index)
            input = self.inputs[input_index]
Q
qijun 已提交
3561
            if self.config.size == 0:
Z
zhangjinchao01 已提交
3562 3563
                size += input_layer.size

3564 3565 3566
        self.set_layer_height_width(self.get_input_layer(0).height, \
                                    self.get_input_layer(0).width)
        self.set_layer_depth(self.get_input_layer(0).depth)
Z
zhangjinchao01 已提交
3567 3568
        self.set_layer_size(size)

Q
qijun 已提交
3569

3570 3571 3572 3573 3574
@config_layer('mkldnn_concat')
class MKLDNNConcatLayer(ConcatenateLayer):
    layer_type = 'mkldnn_concat'


Z
zhangjinchao01 已提交
3575 3576 3577
# like concat layer, but each input layer was processed by a Projection.
@config_layer('concat2')
class ConcatenateLayer2(LayerBase):
Q
qijun 已提交
3578
    def __init__(self, name, inputs, bias=False, **xargs):
Z
zhangjinchao01 已提交
3579 3580 3581
        config_assert(inputs, 'inputs cannot be empty')
        super(ConcatenateLayer2, self).__init__(
            name, 'concat2', 0, inputs=inputs, **xargs)
3582 3583

        if isinstance(self.inputs[0], ConvProjection):
Q
qijun 已提交
3584 3585 3586 3587 3588 3589
            for input_index in xrange(len(self.inputs) - 1):
                input = self.inputs[input_index + 1]
                config_assert(
                    isinstance(input, ConvProjection),
                    "The first input of ConcatenateLayer2 is ConvProjection, "
                    "the other inputs should also be ConvProjection.")
3590

Z
zhangjinchao01 已提交
3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610
        size = 0
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
            input = self.inputs[input_index]
            output_size = input.calc_output_size(input_layer)
            config_assert(output_size != 0, "proj output size is not set")
            size += output_size

        self.set_layer_size(size)

        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
            input = self.inputs[input_index]
            input.proj_conf.input_size = input_layer.size
            input.proj_conf.output_size = input.calc_output_size(input_layer)

            input_config = self.config.inputs[input_index]
            input_config.proj_conf.CopyFrom(input.proj_conf)
            input_config.proj_conf.name = gen_parameter_name(name, input_index)
            psize = input.calc_parameter_size(input.proj_conf.input_size,
Q
qijun 已提交
3611
                                              input.proj_conf.output_size)
Z
zhangjinchao01 已提交
3612
            dims = input.calc_parameter_dims(input.proj_conf.input_size,
Q
qijun 已提交
3613
                                             input.proj_conf.output_size)
Z
zhangjinchao01 已提交
3614 3615
            self.create_input_parameter(input_index, psize, dims)

3616 3617 3618 3619 3620 3621 3622
        psize = self.config.size
        if isinstance(self.inputs[0], ConvProjection):
            self.config.shared_biases = True
            psize = 0
            for input in self.inputs:
                psize += input.calc_bias_size()

3623 3624 3625
        if bias:
            self.config.bias_size = psize
            self.create_bias_parameter(bias, psize)
3626

Q
qijun 已提交
3627

Z
zhangjinchao01 已提交
3628 3629
@config_layer('recurrent')
class RecurrentLayer(LayerBase):
3630 3631
    layer_type = 'recurrent'

Q
qijun 已提交
3632
    def __init__(self, name, inputs, reversed=False, bias=True, **xargs):
3633 3634 3635 3636
        use_mkl_packed = bool(
            int(g_command_config_args.get("use_mkl_packed", 0)))
        self.layer_type = 'mkl_packed_recurrent' if use_mkl_packed else 'recurrent'
        super(RecurrentLayer, self).__init__(name, self.layer_type, 0, inputs,
Y
Yu Yang 已提交
3637
                                             **xargs)
Z
zhangjinchao01 已提交
3638 3639 3640 3641 3642 3643 3644 3645 3646
        config_assert(len(self.inputs) == 1, 'RecurrentLayer must have 1 input')
        input_layer = self.get_input_layer(0)
        size = input_layer.size
        self.set_layer_size(size)
        self.config.reversed = reversed
        dims = [size, size]
        self.create_input_parameter(0, size * size, dims)
        self.create_bias_parameter(bias, self.config.size)

Q
qijun 已提交
3647

Z
zhangjinchao01 已提交
3648 3649
@config_layer('lstmemory')
class LstmLayer(LayerBase):
Q
qijun 已提交
3650 3651 3652 3653 3654 3655 3656 3657
    def __init__(self,
                 name,
                 inputs,
                 reversed=False,
                 active_gate_type="sigmoid",
                 active_state_type="sigmoid",
                 bias=True,
                 **xargs):
Z
zhangjinchao01 已提交
3658 3659 3660 3661 3662 3663 3664 3665
        super(LstmLayer, self).__init__(name, 'lstmemory', 0, inputs, **xargs)
        config_assert(len(self.inputs) == 1, 'LstmLayer must have 1 input')
        input_layer = self.get_input_layer(0)
        #check input_layer.size is divided by 4
        config_assert(input_layer.size % 4 == 0, "size % 4 should be 0!")
        size = input_layer.size / 4
        self.set_layer_size(size)
        self.config.reversed = reversed
Q
qijun 已提交
3666
        self.config.active_gate_type = active_gate_type
Z
zhangjinchao01 已提交
3667 3668 3669 3670 3671
        self.config.active_state_type = active_state_type
        self.create_input_parameter(0, size * size * 4, [size, size, 4])
        #bias includes 3 kinds of peephole, 4 + 3 = 7
        self.create_bias_parameter(bias, size * 7)

Q
qijun 已提交
3672

Z
zhangjinchao01 已提交
3673 3674
@config_layer('lstm_step')
class LstmStepLayer(LayerBase):
Q
qijun 已提交
3675 3676 3677 3678 3679 3680 3681 3682 3683 3684
    def __init__(self,
                 name,
                 size,
                 inputs,
                 active_gate_type="sigmoid",
                 active_state_type="sigmoid",
                 bias=True,
                 **xargs):
        super(LstmStepLayer, self).__init__(name, 'lstm_step', size, inputs,
                                            **xargs)
Z
zhangjinchao01 已提交
3685 3686 3687
        config_assert(len(inputs) == 2, 'LstmStepLayer must have 2 inputs')
        input_layer0 = self.get_input_layer(0)
        input_layer1 = self.get_input_layer(1)
Q
qijun 已提交
3688 3689 3690 3691 3692
        config_assert(input_layer0.size == 4 * size,
                      'input_layer0.size != 4 * layer.size')
        config_assert(input_layer1.size == size,
                      'input_layer1.size != layer.size')
        self.config.active_gate_type = active_gate_type
Z
zhangjinchao01 已提交
3693 3694 3695
        self.config.active_state_type = active_state_type
        self.create_bias_parameter(bias, size * 3)

Q
qijun 已提交
3696

Z
zhangjinchao01 已提交
3697 3698 3699
# get the specific output from the input layer.
@config_layer('get_output')
class GetOutputLayer(LayerBase):
Q
qijun 已提交
3700 3701 3702 3703
    def __init__(self, name, size, inputs):
        super(GetOutputLayer, self).__init__(name, 'get_output', size, inputs)
        config_assert(
            len(self.inputs) == 1, 'GetOutputLayer must have 1 inputs')
Z
zhangjinchao01 已提交
3704 3705 3706 3707
        inputs = self.inputs[0]
        config_assert(inputs.input_layer_argument,
                      'input_layer_argument cannot be empty')

Q
qijun 已提交
3708

Z
zhangjinchao01 已提交
3709 3710
@config_layer('mdlstmemory')
class MDLstmLayer(LayerBase):
Q
qijun 已提交
3711 3712 3713 3714 3715 3716 3717 3718
    def __init__(self,
                 name,
                 inputs,
                 directions=True,
                 active_gate_type="sigmoid",
                 active_state_type="sigmoid",
                 bias=True,
                 **xargs):
Y
Yu Yang 已提交
3719 3720
        super(MDLstmLayer, self).__init__(name, 'mdlstmemory', 0, inputs,
                                          **xargs)
Z
zhangjinchao01 已提交
3721 3722 3723 3724
        config_assert(len(self.inputs) == 1, 'MDLstmLayer must have 1 input')
        input_layer = self.get_input_layer(0)
        dim_num = len(directions)
        #check input_layer.size is divided by (3+dim_num)
Y
Yu Yang 已提交
3725 3726
        config_assert(input_layer.size % (3 + dim_num) == 0,
                      "size % (dim_num) should be 0!")
Q
qijun 已提交
3727
        size = input_layer.size / (3 + dim_num)
Z
zhangjinchao01 已提交
3728
        self.set_layer_size(size)
Q
qijun 已提交
3729
        self.config.active_gate_type = active_gate_type
Z
zhangjinchao01 已提交
3730 3731 3732
        self.config.active_state_type = active_state_type
        for i in xrange(len(directions)):
            self.config.directions.append(int(directions[i]))
Y
Yu Yang 已提交
3733 3734
        self.create_input_parameter(0, size * size * (3 + dim_num),
                                    [size, size, 3 + dim_num])
Z
zhangjinchao01 已提交
3735
        #bias includes 3 kinds of peephole, 3+dim_num+2+dim_num
Q
qijun 已提交
3736 3737
        self.create_bias_parameter(bias, size * (5 + 2 * dim_num))

Z
zhangjinchao01 已提交
3738 3739 3740

@config_layer('gated_recurrent')
class GatedRecurrentLayer(LayerBase):
Q
qijun 已提交
3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751
    def __init__(self,
                 name,
                 inputs,
                 reversed=False,
                 active_gate_type="sigmoid",
                 bias=True,
                 **xargs):
        super(GatedRecurrentLayer, self).__init__(name, 'gated_recurrent', 0,
                                                  inputs, **xargs)
        config_assert(
            len(self.inputs) == 1, 'GatedRecurrentLayer must have 1 input')
Z
zhangjinchao01 已提交
3752 3753 3754 3755 3756 3757
        input_layer = self.get_input_layer(0)
        #check input_layer.size is divided by 3
        config_assert(input_layer.size % 3 == 0, "size % 3 should be 0!")
        size = input_layer.size / 3
        self.set_layer_size(size)
        self.config.reversed = reversed
Q
qijun 已提交
3758
        self.config.active_gate_type = active_gate_type
Z
zhangjinchao01 已提交
3759 3760 3761
        self.create_input_parameter(0, size * size * 3, [size, size * 3])
        self.create_bias_parameter(bias, size * 3)

Q
qijun 已提交
3762

Z
zhangjinchao01 已提交
3763 3764
@config_layer('gru_step')
class GruStepLayer(LayerBase):
Q
qijun 已提交
3765 3766 3767 3768 3769 3770 3771
    def __init__(self,
                 name,
                 size,
                 inputs,
                 active_gate_type="sigmoid",
                 bias=True,
                 **xargs):
Y
Yu Yang 已提交
3772 3773
        super(GruStepLayer, self).__init__(name, 'gru_step', size, inputs,
                                           **xargs)
Z
zhangjinchao01 已提交
3774 3775 3776
        config_assert(len(self.inputs) == 2, 'GruStepLayer must have 2 input')
        input_layer0 = self.get_input_layer(0)
        input_layer1 = self.get_input_layer(1)
Q
qijun 已提交
3777 3778 3779 3780 3781
        config_assert(input_layer0.size == 3 * size,
                      'input_layer0.size != 3 * layer.size')
        config_assert(input_layer1.size == size,
                      'input_layer1.size != layer.size')
        self.config.active_gate_type = active_gate_type
H
Haonan 已提交
3782
        self.create_input_parameter(0, size * size * 3, [size, size * 3])
Z
zhangjinchao01 已提交
3783 3784
        self.create_bias_parameter(bias, size * 3)

Q
qijun 已提交
3785

Z
zhangjinchao01 已提交
3786 3787 3788 3789 3790 3791 3792
'''
 A layer for calculating the cost of sequential conditional random field model.
 Example: CRFLayer(name="crf_cost", size=label_num,
                   inputs=["output", "label", "weight"])
          where "weight" is optional, one weight for each sequence
 @param coeff: weight of the layer
'''
Q
qijun 已提交
3793 3794


Z
zhangjinchao01 已提交
3795 3796
@config_layer('crf')
class CRFLayer(LayerBase):
Q
qijun 已提交
3797
    def __init__(self, name, size, inputs, coeff=1.0, device=None):
Z
zhangjinchao01 已提交
3798
        super(CRFLayer, self).__init__(name, 'crf', size, inputs, device=device)
Q
qijun 已提交
3799 3800
        config_assert(2 <= len(self.inputs) <= 3,
                      'CRFLayer must have 2 or 3 inputs')
3801
        self.create_input_parameter(0, size * (size + 2), [size + 2, size])
Z
zhangjinchao01 已提交
3802 3803
        self.config.coeff = coeff

Q
qijun 已提交
3804

Z
zhangjinchao01 已提交
3805 3806 3807 3808 3809 3810 3811 3812
'''
 A layer for calculating the decoding sequence of sequential conditional
 random field model.
 The decoding sequence is stored in output_.ids
 If a second input is provided, it is treated as the ground-truth label, and
 this layer will also calculate error, output_.value[i] is 1 for incorrect
 decoding or 0 for correct decoding
'''
Q
qijun 已提交
3813 3814


Z
zhangjinchao01 已提交
3815 3816
@config_layer('crf_decoding')
class CRFDecodingLayer(LayerBase):
Q
qijun 已提交
3817
    def __init__(self, name, size, inputs, device=None):
Z
zhangjinchao01 已提交
3818 3819 3820 3821 3822
        super(CRFDecodingLayer, self).__init__(
            name, 'crf_decoding', size, inputs, device=device)
        config_assert(
            len(self.inputs) <= 2,
            'CRFDecodingLayer cannot have more than 2 inputs')
3823
        self.create_input_parameter(0, size * (size + 2), [size + 2, size])
Z
zhangjinchao01 已提交
3824

Q
qijun 已提交
3825

Z
zhangjinchao01 已提交
3826 3827
@config_layer('ctc')
class CTCLayer(LayerBase):
Q
qijun 已提交
3828
    def __init__(self, name, size, inputs, norm_by_times=False, device=None):
Z
zhangjinchao01 已提交
3829 3830 3831 3832
        super(CTCLayer, self).__init__(name, 'ctc', size, inputs, device=device)
        self.config.norm_by_times = norm_by_times
        config_assert(len(self.inputs) == 2, 'CTCLayer must have 2 inputs')

Q
qijun 已提交
3833

3834 3835 3836 3837 3838 3839 3840 3841 3842 3843
@config_layer('kmax_seq_score')
class KmaxSeqScoreLayer(LayerBase):
    def __init__(self, name, inputs, beam_size, **xargs):
        super(KmaxSeqScoreLayer, self).__init__(
            name, 'kmax_seq_score', 0, inputs=inputs, **xargs)
        config_assert(
            len(self.inputs) == 1, 'KmaxSeqScoreLayer has only one input.')
        self.config.beam_size = beam_size


3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864
@config_layer('warp_ctc')
class WarpCTCLayer(LayerBase):
    def __init__(self,
                 name,
                 size,
                 inputs,
                 blank=0,
                 norm_by_times=False,
                 device=None):
        super(WarpCTCLayer, self).__init__(
            name, 'warp_ctc', size=size, inputs=inputs, device=device)
        self.config.blank = blank
        self.config.norm_by_times = norm_by_times
        config_assert(len(self.inputs) == 2, 'WarpCTCLayer must have 2 inputs')
        input_layer = self.get_input_layer(0)
        config_assert(
            (input_layer.active_type == '' or
             input_layer.active_type == 'linear'),
            "Expecting the active_type of input layer to be linear or null")


Z
zhangjinchao01 已提交
3865 3866
@config_layer('recurrent_layer_group')
class RecurrentLayerGroup(LayerBase):
Q
qijun 已提交
3867
    def __init__(self, name, device=None):
Z
zhangjinchao01 已提交
3868 3869 3870 3871
        super(RecurrentLayerGroup, self).__init__(
            name, 'recurrent_layer_group', 0, inputs=[], device=device)


3872 3873 3874 3875 3876
@config_layer('switch_order')
class SwitchOrderLayer(LayerBase):
    def __init__(self, name, inputs, reshape, **xargs):
        super(SwitchOrderLayer, self).__init__(
            name, 'switch_order', 0, inputs=inputs, **xargs)
W
wanghaoshuang 已提交
3877 3878
        self.config.reshape_conf.height_axis.extend(reshape['height'])
        self.config.reshape_conf.width_axis.extend(reshape['width'])
3879 3880 3881 3882
        input_layer = self.get_input_layer(0)
        if reshape is None:
            self.set_layer_size(input_layer.size)
        else:
W
wanghaoshuang 已提交
3883 3884
            in_h = input_layer.height
            in_w = input_layer.width
W
wanghaoshuang 已提交
3885
            out_dims = None
W
wanghaoshuang 已提交
3886
            if input_layer.has_depth():
W
wanghaoshuang 已提交
3887 3888
                in_d = input_layer.depth
                in_c = input_layer.size / in_h / in_w / in_d
W
wanghaoshuang 已提交
3889
                # batch_size, depth, height, width, channel
W
wanghaoshuang 已提交
3890
                out_dims = [0, in_d, in_h, in_w, in_c]
W
wanghaoshuang 已提交
3891
            else:
W
wanghaoshuang 已提交
3892
                in_c = input_layer.size / in_h / in_w
W
wanghaoshuang 已提交
3893
                # batch_size, height, width, channel
W
wanghaoshuang 已提交
3894
                out_dims = [0, in_h, in_w, in_c]
W
wanghaoshuang 已提交
3895 3896 3897
            # Because (reshape['width'][0] > 0) always be true.
            # So out_dims[0] won't be used.
            size = reduce(lambda x, y: x * y, out_dims[reshape['width'][0]:])
3898
            self.set_layer_size(size)
3899 3900


Y
yangyaming 已提交
3901 3902
@config_layer('scale_sub_region')
class ScaleSubRegionLayer(LayerBase):
Y
yangyaming 已提交
3903
    def __init__(self, name, inputs, value, **xargs):
Y
yangyaming 已提交
3904 3905 3906 3907
        super(ScaleSubRegionLayer, self).__init__(
            name, 'scale_sub_region', 0, inputs=inputs, **xargs)
        scale_sub_region_conf = self.config.inputs[0].scale_sub_region_conf
        scale_sub_region_conf.value = value
Y
yangyaming 已提交
3908 3909 3910

        # get channel, width and height from input_0 layer
        input_layer = self.get_input_layer(0)
Y
yangyaming 已提交
3911
        image_conf = scale_sub_region_conf.image_conf
Y
yangyaming 已提交
3912 3913 3914 3915
        image_conf.img_size = input_layer.width
        image_conf.img_size_y = input_layer.height
        image_conf.channels = input_layer.size / (input_layer.width *
                                                  input_layer.height)
Y
yangyaming 已提交
3916 3917
        self.set_cnn_layer(name, image_conf.img_size_y, image_conf.img_size,
                           image_conf.channels)
Y
yangyaming 已提交
3918 3919


3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930
@config_layer('factorization_machine')
class FactorizationMachineLayer(LayerBase):
    def __init__(self, name, inputs, factor_size, **xargs):
        super(FactorizationMachineLayer, self).__init__(
            name, 'factorization_machine', size=1, inputs=inputs, **xargs)
        config_assert(
            len(self.inputs) == 1,
            'factorization machine layer must have one and only one input.')
        self.config.factor_size = factor_size
        input_layer = self.get_input_layer(0)
        psize = input_layer.size * factor_size
3931
        dims = [input_layer.size, factor_size]
3932 3933 3934
        self.create_input_parameter(0, psize, dims)


Z
zhangjinchao01 已提交
3935 3936
# Deprecated, use a new layer specific class instead
@config_func
Q
qijun 已提交
3937
def Layer(name, type, **xargs):
Z
zhangjinchao01 已提交
3938 3939 3940 3941
    layers = {}
    layers.update(g_cost_map)
    layers.update(g_layer_type_map)
    layer_func = layers.get(type)
Q
qijun 已提交
3942
    config_assert(layer_func, "layer type '%s' not supported." % type)
X
xuwei06 已提交
3943
    return layer_func(name, **xargs)
Z
zhangjinchao01 已提交
3944

Q
qijun 已提交
3945

Z
zhangjinchao01 已提交
3946
@config_func
Q
qijun 已提交
3947
def ParameterHook(type, **kwargs):
3948
    if type == 'pruning':
Z
zhangjinchao01 已提交
3949 3950
        hook = ParameterUpdaterHookConfig()
        hook.type = type
X
xzl 已提交
3951
        sparsity_ratio = kwargs.get('sparsity_ratio', None)
X
xzl 已提交
3952 3953
        if sparsity_ratio is not None:
            hook.sparsity_ratio = sparsity_ratio
Z
zhangjinchao01 已提交
3954
        return hook
3955 3956 3957 3958
    elif type == 'dpruning':
        hook = ParameterUpdaterHookConfig()
        hook.type = type
        return hook
Z
zhangjinchao01 已提交
3959 3960 3961 3962 3963
    else:
        return None


@config_func
Q
qijun 已提交
3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984
def Parameter(name,
              size,
              device,
              dims,
              learning_rate=None,
              momentum=None,
              decay_rate=None,
              decay_rate_l1=None,
              initial_mean=None,
              initial_std=None,
              initial_strategy=None,
              initial_smart=None,
              num_batches_regularization=None,
              sparse_remote_update=None,
              sparse_update=None,
              gradient_clipping_threshold=None,
              sparse=None,
              format=None,
              need_compact=None,
              is_static=None,
              is_shared=None,
X
xuwei06 已提交
3985 3986
              update_hooks=None,
              initializer=None):
Z
zhangjinchao01 已提交
3987 3988 3989 3990 3991 3992 3993

    config_assert(name not in g_parameter_map,
                  'Duplicated parameter name: ' + name)

    para = g_config.model_config.parameters.add()
    para.name = name
    para.size = size
3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004
    if device is not None:
        para.device = int(device)
    para.dims.extend(dims)

    if learning_rate is not None:
        para.learning_rate = float(learning_rate)

    momentum = default(momentum, g_default_momentum)
    if momentum is not None:
        para.momentum = float(momentum)

Z
zhangjinchao01 已提交
4005 4006
    config_assert(not momentum or not decay_rate_l1,
                  "momentum and decay_rate_l1 cannot both be non-zero")
4007 4008 4009 4010 4011

    decay_rate = default(decay_rate, g_default_decay_rate)
    if decay_rate is not None:
        para.decay_rate = decay_rate

Z
zhangjinchao01 已提交
4012 4013 4014 4015
    if decay_rate_l1 is not None:
        para.decay_rate_l1 = decay_rate_l1
    para.initial_std = default(initial_std, g_default_initial_std)
    para.initial_mean = default(initial_mean, g_default_initial_mean)
4016

Q
qijun 已提交
4017 4018
    num_batches_regularization = default(num_batches_regularization,
                                         g_default_num_batches_regularization)
4019 4020 4021
    if num_batches_regularization is not None:
        para.num_batches_regularization = int(num_batches_regularization)

Z
zhangjinchao01 已提交
4022 4023 4024 4025 4026 4027
    if sparse_remote_update is not None:
        para.sparse_remote_update = sparse_remote_update
        if sparse_remote_update:
            g_config.opt_config.use_sparse_remote_updater = True
    if sparse_update is not None:
        para.sparse_update = sparse_update
Q
qijun 已提交
4028 4029
    gradient_clipping_threshold = default(gradient_clipping_threshold,
                                          g_default_gradient_clipping_threshold)
4030 4031
    if gradient_clipping_threshold is not None:
        para.gradient_clipping_threshold = gradient_clipping_threshold
Q
qijun 已提交
4032 4033
    para.initial_strategy = default(initial_strategy,
                                    g_default_initial_strategy)
Z
zhangjinchao01 已提交
4034 4035 4036 4037 4038 4039
    para.initial_smart = default(initial_smart, g_default_initial_smart)
    if para.initial_smart:
        para.initial_mean = 0.
        if len(para.dims) != 0:
            para.initial_std = 1. / math.sqrt(para.dims[0])
        else:
Q
qijun 已提交
4040 4041 4042
            print(
                "Use initial_smart, but dims not set. Initial_smart may not be used in this layer"
            )
Z
zhangjinchao01 已提交
4043 4044 4045 4046
            traceback.print_exc()
            para.initial_std = 1. / math.sqrt(para.size)
    if g_default_compact_func is not None:
        sparse, format, need_compact = g_default_compact_func(para.name)
4047 4048 4049 4050 4051 4052 4053

    if sparse is not None:
        para.is_sparse = sparse
    if format is not None:
        para.format = format
    if need_compact is not None:
        para.need_compact = need_compact
Z
zhangjinchao01 已提交
4054 4055 4056 4057
    if is_static is not None:
        para.is_static = is_static
    config_assert(not para.sparse_remote_update or not para.is_static,
                  "sparse_remote_update and is_static cannot both be true")
4058 4059
    if is_shared is not None:
        para.is_shared = is_shared
Z
zhangjinchao01 已提交
4060 4061 4062 4063 4064

    update_hooks = default(update_hooks, g_default_update_hooks)

    if update_hooks is not None:
        if hasattr(update_hooks, '__call__'):
X
xzl 已提交
4065
            update_hooks = update_hooks()
Z
zhangjinchao01 已提交
4066 4067 4068 4069 4070

        if isinstance(update_hooks, list):
            for hook in update_hooks:
                para.update_hooks.extend([hook])
        else:
X
xzl 已提交
4071
            para.update_hooks.extend([update_hooks])
Z
zhangjinchao01 已提交
4072 4073

    g_parameter_map[name] = para
X
xuwei06 已提交
4074 4075 4076 4077 4078
    if initializer is not None:
        config_assert(
            callable(initializer),
            "parameter initializer should be a callable object")
        g_parameter_initializer_map[name] = initializer
Z
zhangjinchao01 已提交
4079 4080 4081 4082 4083 4084 4085


@config_func
def default_initial_std(val):
    global g_default_initial_std
    g_default_initial_std = val

Q
qijun 已提交
4086

Z
zhangjinchao01 已提交
4087 4088 4089 4090 4091
@config_func
def default_initial_mean(val):
    global g_default_initial_mean
    g_default_initial_mean = val

Q
qijun 已提交
4092

Z
zhangjinchao01 已提交
4093 4094 4095 4096 4097
@config_func
def default_initial_strategy(val):
    global g_default_initial_strategy
    g_default_initial_strategy = val

Q
qijun 已提交
4098

Z
zhangjinchao01 已提交
4099 4100 4101 4102 4103
@config_func
def default_initial_smart(val):
    global g_default_initial_smart
    g_default_initial_smart = val

Q
qijun 已提交
4104

Z
zhangjinchao01 已提交
4105 4106 4107 4108 4109
@config_func
def default_momentum(val):
    global g_default_momentum
    g_default_momentum = val

Q
qijun 已提交
4110

Z
zhangjinchao01 已提交
4111 4112 4113 4114 4115
@config_func
def default_decay_rate(val):
    global g_default_decay_rate
    g_default_decay_rate = val

Q
qijun 已提交
4116

Z
zhangjinchao01 已提交
4117 4118 4119 4120 4121
@config_func
def default_num_batches_regularization(val):
    global g_default_num_batches_regularization
    g_default_num_batches_regularization = val

Q
qijun 已提交
4122

Z
zhangjinchao01 已提交
4123 4124 4125 4126 4127
@config_func
def default_gradient_clipping_threshold(val):
    global g_default_gradient_clipping_threshold
    g_default_gradient_clipping_threshold = val

Q
qijun 已提交
4128

Z
zhangjinchao01 已提交
4129 4130 4131 4132 4133
@config_func
def default_device(val):
    global g_default_device
    g_default_device = val

Q
qijun 已提交
4134

Z
zhangjinchao01 已提交
4135 4136 4137 4138 4139
@config_func
def default_update_hooks(val):
    global g_default_update_hooks
    g_default_update_hooks = val

Q
qijun 已提交
4140

Z
zhangjinchao01 已提交
4141 4142 4143 4144 4145
@config_func
def default_compact_func(val):
    global g_default_compact_func
    g_default_compact_func = val

Q
qijun 已提交
4146

Z
zhangjinchao01 已提交
4147 4148 4149 4150 4151
def make_importer(config_dir, config_args):
    def Import(config_file, local_args={}):
        if not config_file.startswith('/'):
            config_file = config_dir + '/' + config_file
            g_config.config_files.append(config_file)
Q
qijun 已提交
4152 4153 4154
        execfile(config_file,
                 make_config_environment(config_file, config_args), local_args)

Z
zhangjinchao01 已提交
4155 4156
    return Import

Q
qijun 已提交
4157

X
xuwei06 已提交
4158
DEFAULT_SETTING = dict(
Z
zhangjinchao01 已提交
4159 4160 4161 4162 4163
    batch_size=None,
    mini_batch_size=None,
    algorithm='async_sgd',
    async_lagged_grad_discard_ratio=1.5,
    learning_method='momentum',
4164
    gradient_clipping_threshold=None,
Z
zhangjinchao01 已提交
4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186
    num_batches_per_send_parameter=None,
    num_batches_per_get_parameter=None,
    center_parameter_update_method=None,
    learning_rate=1.,
    learning_rate_decay_a=0.,
    learning_rate_decay_b=0.,
    learning_rate_schedule='poly',
    learning_rate_args='',
    l1weight=0.1,
    l2weight=0.,
    l2weight_zero_iter=0,
    c1=0.0001,
    backoff=0.5,
    owlqn_steps=10,
    max_backoff=5,
    average_window=0,
    do_average_in_cpu=False,
    max_average_window=None,
    ada_epsilon=1e-6,
    ada_rou=0.95,
    delta_add_rate=1.0,
    shrink_parameter_value=0,
Q
qijun 已提交
4187 4188 4189
    adam_beta1=0.9,
    adam_beta2=0.999,
    adam_epsilon=1e-8, )
Z
zhangjinchao01 已提交
4190

X
xuwei06 已提交
4191
settings = copy.deepcopy(DEFAULT_SETTING)
X
xuwei06 已提交
4192

Q
qijun 已提交
4193
settings_deprecated = dict(usage_ratio=1., )
Z
zhangjinchao01 已提交
4194 4195 4196 4197

trainer_settings = dict(
    save_dir="./output/model",
    init_model_path=None,
Q
qijun 已提交
4198 4199
    start_pass=0, )

Z
zhangjinchao01 已提交
4200 4201 4202 4203 4204

@config_func
def Settings(**args):
    for k, v in args.iteritems():
        if k == "usage_ratio":
Q
qijun 已提交
4205 4206
            logger.warning(
                "Deprecated: define usage_ratio in DataConfig instead")
Z
zhangjinchao01 已提交
4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217
            if g_config.HasField("data_config"):
                g_config.data_config.__setattr__(k, v)
            settings_deprecated[k] = v
            continue
        elif k in settings:
            settings[k] = v
        elif k in trainer_settings:
            trainer_settings[k] = v
        else:
            logger.fatal('Unkown setting: %s' % k)

Q
qijun 已提交
4218

Z
zhangjinchao01 已提交
4219 4220 4221 4222
@config_func
def cluster_config(**args):
    pass

Q
qijun 已提交
4223

Z
zhangjinchao01 已提交
4224 4225 4226 4227 4228 4229 4230 4231 4232
@config_func
def EnableSubmodelSuffix(flag=True):
    """
    If enabled, the layer and evaluator names in submodel will be automatically
    appended with @submodel_name
    """
    global g_add_submodel_suffix
    g_add_submodel_suffix = flag

Q
qijun 已提交
4233

Z
zhangjinchao01 已提交
4234 4235 4236 4237
def make_config_environment(config_file, config_args):
    def make_setter(k):
        def setter(v):
            logger.fatal("Obsolete: use Settings(%s=%s, ...) instead" % (k, v))
Q
qijun 已提交
4238

Z
zhangjinchao01 已提交
4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253
        return setter

    funcs = {}
    funcs.update(g_config_funcs)

    for k in settings.iterkeys():
        funcs[k] = make_setter(k)
    for k in settings_deprecated.iterkeys():
        funcs[k] = make_setter(k)
    config_dir = os.path.dirname(config_file)
    if not config_dir:
        config_dir = '.'

    funcs.update(
        Import=make_importer(config_dir, config_args),
Q
qijun 已提交
4254
        get_config_arg=make_get_config_arg(config_args), )
Z
zhangjinchao01 已提交
4255 4256 4257 4258 4259

    funcs.update(g_extended_config_funcs)

    return funcs

Q
qijun 已提交
4260

Z
zhangjinchao01 已提交
4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276
def make_get_config_arg(config_args):
    def get_config_arg(name, type, default=None):
        if type == bool:
            s = config_args.get(name)
            if not s:
                return default
            if s == 'True' or s == '1' or s == 'true':
                return True
            if s == 'False' or s == '0' or s == 'false':
                return False
            raise ValueError('Value of config_arg %s is not boolean' % name)
        else:
            return type(config_args.get(name, default))

    return get_config_arg

Q
qijun 已提交
4277

Z
zhangjinchao01 已提交
4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289
def importlib(name):
    __import__(name)
    return sys.modules[name]


def find_caller():
    stack = traceback.extract_stack()
    for s in stack[-4::-1]:
        if not s[0].endswith('config_parser.py'):
            return s[0], s[1], s[2]
    return "(unknown file)", 0, "(unknown function)"

Q
qijun 已提交
4290

Z
zhangjinchao01 已提交
4291 4292 4293 4294
def my_fatal(s):
    logger.critical(s)
    raise Exception()

Y
Yu Yang 已提交
4295

4296
_parse_config_hooks = set()
Y
Yu Yang 已提交
4297 4298


4299 4300 4301 4302 4303 4304 4305
def register_parse_config_hook(f):
    """
    Register a hook function for parse_config. parse_config will invoke the hook
    at the beginning of parse. This make it possible to reset global state for
    for constructing the model.
    """
    _parse_config_hooks.add(f)
Q
qijun 已提交
4306

Y
Yu Yang 已提交
4307

4308
def update_g_config():
Z
zhangjinchao01 已提交
4309
    '''
4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332
    Update g_config after execute config_file or config_functions.
    '''
    for k, v in settings.iteritems():
        if v is None:
            continue
        g_config.opt_config.__setattr__(k, v)

    for k, v in trainer_settings.iteritems():
        if v is None:
            continue
        g_config.__setattr__(k, v)

    for name in g_config.model_config.input_layer_names:
        assert name in g_layer_map, \
            'input name "%s" does not correspond to a layer name' % name
        assert (g_layer_map[name].type == "data" or g_layer_map[name].type == "data_trim"), \
            'The type of input layer "%s" is not "data"' % name
    for name in g_config.model_config.output_layer_names:
        assert name in g_layer_map, \
            'input name "%s" does not correspond to a layer name' % name
    return g_config


4333
def begin_parse():
Z
zhangjinchao01 已提交
4334
    init_config_environment()
4335 4336
    for hook in _parse_config_hooks:
        hook()
Z
zhangjinchao01 已提交
4337 4338 4339 4340 4341

    logger.findCaller = find_caller
    logger.fatal = my_fatal

    g_config.model_config.type = "nn"
X
xuwei06 已提交
4342 4343 4344 4345 4346 4347 4348 4349 4350

    global g_current_submodel, g_root_submodel
    g_root_submodel = g_config.model_config.sub_models.add()
    g_root_submodel.name = 'root'
    g_root_submodel.is_recurrent_layer_group = False
    g_current_submodel = g_root_submodel


def parse_config(trainer_config, config_arg_str):
4351 4352 4353 4354
    '''
    @param config_arg_str: a string of the form var1=val1,var2=val2. It will be
    passed to config script as a dictionary CONFIG_ARGS
    '''
X
xuwei06 已提交
4355

4356
    begin_parse()
X
xuwei06 已提交
4357 4358
    config_args = {}

Z
zhangjinchao01 已提交
4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370
    if config_arg_str:
        config_args = dict([f.split('=') for f in config_arg_str.split(',')])

    global g_command_config_args
    g_command_config_args.update(config_args)

    extension_module_name = config_args.get('extension_module_name')
    if extension_module_name:
        global g_extended_config_funcs
        extension_module = importlib(extension_module_name)
        g_extended_config_funcs = extension_module.get_config_funcs(g_config)

4371 4372
    if hasattr(trainer_config, '__call__'):
        trainer_config.func_globals.update(
L
Luo Tao 已提交
4373
            make_config_environment("", config_args))
4374
        trainer_config()
H
hanchao 已提交
4375
    else:
4376 4377
        execfile(trainer_config,
                 make_config_environment(trainer_config, config_args))
Z
zhangjinchao01 已提交
4378

4379
    return update_g_config()
Z
zhangjinchao01 已提交
4380 4381


4382
def parse_config_and_serialize(trainer_config, config_arg_str):
Z
zhangjinchao01 已提交
4383
    try:
4384
        config = parse_config(trainer_config, config_arg_str)
Z
zhangjinchao01 已提交
4385 4386 4387 4388 4389 4390
        #logger.info(config)
        return config.SerializeToString()
    except:
        traceback.print_exc()
        raise

Q
qijun 已提交
4391

Z
zhangjinchao01 已提交
4392 4393 4394 4395 4396 4397 4398 4399
if __name__ == '__main__':
    try:
        config = parse_config(sys.argv[1], '')
        config.SerializeToString()
        __real_print__(str(config))
    except:
        traceback.print_exc()
        raise