config_parser.py 120.3 KB
Newer Older
Z
zhangjinchao01 已提交
1 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 102
# Copyright (c) 2016 Baidu, Inc. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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 已提交
103
    format='[%(levelname)s %(asctime)s %(filename)s:%(lineno)s] %(message)s', )
Z
zhangjinchao01 已提交
104 105 106
logger = logging.getLogger('paddle')
logger.setLevel(logging.INFO)
__real_print__ = print
Q
qijun 已提交
107
print = logger.info
Z
zhangjinchao01 已提交
108 109 110 111

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

Q
qijun 已提交
112

Z
zhangjinchao01 已提交
113 114 115
# Initialize global variables. We use this function so that we can
# call parse_config() multiple times
def init_config_environment(
Q
qijun 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
        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={},
        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 141
        g_py_module_name_list=[],
        g_current_submodel=None,
        g_root_submodel=None,
        g_submodel_map={},
        g_submodel_stack=[],
        g_add_submodel_suffix=False, ):
Z
zhangjinchao01 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157

    for k, v in locals().iteritems():
        globals()[k] = copy.deepcopy(v)


# 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 已提交
158

Z
zhangjinchao01 已提交
159 160
g_config_funcs = {}

Q
qijun 已提交
161

Z
zhangjinchao01 已提交
162 163 164 165 166
# 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 已提交
167

Z
zhangjinchao01 已提交
168 169 170 171 172
# 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 已提交
173

Z
zhangjinchao01 已提交
174 175 176 177 178 179
# 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 已提交
180

Z
zhangjinchao01 已提交
181 182
    return wrap

Q
qijun 已提交
183

Z
zhangjinchao01 已提交
184 185 186
def gen_parameter_name(layer_name, input_index):
    return '_%s.w%d' % (layer_name, input_index)

Q
qijun 已提交
187

Z
zhangjinchao01 已提交
188 189 190
def gen_bias_parameter_name(layer_name):
    return '_%s.wbias' % layer_name

Q
qijun 已提交
191

Z
zhangjinchao01 已提交
192 193 194
def default(x, default_value):
    return default_value if x is None else x

Q
qijun 已提交
195

Z
zhangjinchao01 已提交
196 197 198 199 200 201
class Cfg(object):
    def add_keys(self, locals):
        for k, v in locals.iteritems():
            if not k.startswith('_'):
                self.__setattr__(k, v)

Q
qijun 已提交
202

Z
zhangjinchao01 已提交
203 204
# functions available in config file

Q
qijun 已提交
205

Z
zhangjinchao01 已提交
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
# 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 已提交
224

225 226
@config_func
def HasInputsSet():
227
    return len(g_current_submodel.input_layer_names) != 0
228

Z
zhangjinchao01 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252

# 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 已提交
253
    name = MakeLayerNameInParentSubmodel(name)  #rename in nested submodel
Z
zhangjinchao01 已提交
254 255 256 257 258 259 260 261 262

    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 已提交
263

Z
zhangjinchao01 已提交
264
@config_func
Q
qijun 已提交
265
def SubModelEnd(name=None):
Z
zhangjinchao01 已提交
266
    global g_current_submodel, g_root_submodel, g_submodel_stack
Q
qijun 已提交
267 268
    config_assert(g_current_submodel is not g_root_submodel,
                  "submodel not begin")
Z
zhangjinchao01 已提交
269
    if name is not None:
Q
qijun 已提交
270 271 272
        config_assert(
            g_current_submodel.name == MakeLayerNameInParentSubmodel(name),
            "submodel name error")
Z
zhangjinchao01 已提交
273 274 275

    g_current_submodel = g_submodel_stack.pop()

Q
qijun 已提交
276

Z
zhangjinchao01 已提交
277 278
def MakeLayerNameInParentSubmodel(name):
    suffix = ""
279 280
    if len(g_submodel_stack) > 1:
        suffix = "@" + g_submodel_stack[-1].name
Z
zhangjinchao01 已提交
281 282
    return name + suffix

Q
qijun 已提交
283

Z
zhangjinchao01 已提交
284 285 286
def GetLayerBaseName(name):
    return name.split('@')[0]

Q
qijun 已提交
287 288

def MakeLayerNameInSubmodel(name, submodel_name=None):
Z
zhangjinchao01 已提交
289 290
    global g_current_submodel
    global g_add_submodel_suffix
Q
qijun 已提交
291 292
    if (submodel_name is None and not g_add_submodel_suffix and
            not g_current_submodel.is_recurrent_layer_group):
Z
zhangjinchao01 已提交
293 294 295 296 297
        return name
    if submodel_name is None:
        submodel_name = g_current_submodel.name
    return name + "@" + submodel_name

Q
qijun 已提交
298

Z
zhangjinchao01 已提交
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
# 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,
322 323
                                            seq_reversed=False,
                                            target_inlinkname=""):
Z
zhangjinchao01 已提交
324 325 326 327 328 329 330
    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
331
    g_current_submodel.target_inlinkid = -1
Z
zhangjinchao01 已提交
332
    in_links_count = 0
333
    for linkid, link in enumerate(in_links):
Z
zhangjinchao01 已提交
334 335 336 337 338 339
        if isinstance(link, basestring):
            name = link
            has_subseq = False
        else:
            name = link.link_name
            has_subseq = link.has_subseq
340 341 342 343
        # assign target_inlinkid according to target_inlinkname
        if target_inlinkname == name:
            g_current_submodel.target_inlinkid = linkid

Z
zhangjinchao01 已提交
344 345 346
        if in_links_count == 0:
            in_links_has_subseq = has_subseq
        else:
Q
qijun 已提交
347 348 349 350
            config_assert(
                in_links_has_subseq == has_subseq,
                "The sequence type of in_links should be the same in RecurrentLayerGroup"
            )
Z
zhangjinchao01 已提交
351 352 353 354 355 356 357
        in_links_count += 1
        layer_name = MakeLayerNameInParentSubmodel(name)
        layer = g_layer_map[layer_name]
        if has_subseq:
            SequenceScatterAgentLayer(name=name, size=layer.size)
        else:
            ScatterAgentLayer(name=name, size=layer.size)
358

Z
zhangjinchao01 已提交
359 360 361 362 363
        pair = g_current_submodel.in_links.add()
        pair.layer_name = layer_name
        pair.link_name = MakeLayerNameInSubmodel(name)
        pair.has_subseq = has_subseq

Q
qijun 已提交
364

Z
zhangjinchao01 已提交
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
@config_func
def RecurrentLayerGroupSetOutLink(link):
    if isinstance(link, basestring):
        name = link
        has_subseq = False
    else:
        name = link.link_name
        has_subseq = link.has_subseq
    layer_name = MakeLayerNameInParentSubmodel(name)
    pair = g_current_submodel.out_links.add()
    pair.layer_name = MakeLayerNameInSubmodel(name)
    pair.link_name = layer_name
    pair.has_subseq = has_subseq


def RecurrentLayerGroupSetGenerator(generator=None):
Q
qijun 已提交
381
    generator.eos_layer_name = MakeLayerNameInSubmodel(generator.eos_layer_name)
Z
zhangjinchao01 已提交
382 383 384 385 386 387 388 389
    g_current_submodel.generator.CopyFrom(generator)


@config_func
def RecurrentLayerGroupBegin(name,
                             in_links,
                             out_links,
                             generator=None,
390
                             target_inlinkname="",
Z
zhangjinchao01 已提交
391
                             seq_reversed=False):
Q
qijun 已提交
392
    RecurrentLayerGroupWithoutOutLinksBegin(name, in_links, seq_reversed,
393
                                            target_inlinkname)
Z
zhangjinchao01 已提交
394 395 396 397 398
    for link in out_links:
        RecurrentLayerGroupSetOutLink(link)

    if generator is not None:
        RecurrentLayerGroupSetGenerator(generator)
Q
qijun 已提交
399 400 401 402 403
        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 已提交
404 405 406 407 408 409 410


@config_func
def RecurrentLayerGroupEnd(name):
    global g_current_submodel
    config_assert(g_current_submodel.is_recurrent_layer_group,
                  "RecurrentLayerGroup not begin")
Q
qijun 已提交
411
    for pair in g_current_submodel.memories:  #check exist
Z
zhangjinchao01 已提交
412
        layer = g_layer_map[pair.layer_name]
Y
Yu Yang 已提交
413 414
        config_assert(layer is not None,
                      "memory declare wrong name:%s" % pair.layer_name)
Z
zhangjinchao01 已提交
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
        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)
        elif pair.has_subseq:
            SequenceGatherAgentLayer(name=agent_name, size=layer.size)
        else:
            GatherAgentLayer(name=agent_name, size=layer.size)

Q
qijun 已提交
433

Z
zhangjinchao01 已提交
434 435 436 437 438 439
# 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 已提交
440

Z
zhangjinchao01 已提交
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
@config_class
class Bias(Cfg):
    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,
Q
qijun 已提交
458
            is_shared=None, ):
Z
zhangjinchao01 已提交
459 460
        self.add_keys(locals())

Q
qijun 已提交
461

Z
zhangjinchao01 已提交
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
# Define one input for a layer
@config_class
class Input(Cfg):
    def __init__(
            self,
            input_layer_name,
            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,
            sparse_update=None,
            gradient_clipping_threshold=None,
            conv=None,
L
liaogang 已提交
482
            bilinear_interp=None,
Z
zhangjinchao01 已提交
483 484 485 486
            norm=None,
            pool=None,
            image=None,
            block_expand=None,
487
            maxout=None,
Q
qijun 已提交
488
            spp=None,
Z
zhangjinchao01 已提交
489 490 491 492 493
            format=None,
            nnz=None,
            is_static=None,
            is_shared=None,
            update_hooks=None,
Q
qijun 已提交
494
            input_layer_argument=None, ):
Z
zhangjinchao01 已提交
495 496 497
        self.add_keys(locals())
        self.input_layer_name = MakeLayerNameInSubmodel(input_layer_name)

Q
qijun 已提交
498

Z
zhangjinchao01 已提交
499 500 501
# Define a projection for iexed layer
@config_class
class Projection(Input):
Q
qijun 已提交
502 503
    type = None  # subclass should set it correctly

Z
zhangjinchao01 已提交
504 505 506
    def __init__(
            self,
            input_layer_name,
Q
qijun 已提交
507
            size=0,  # projection output size
Z
zhangjinchao01 已提交
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
            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,
            sparse_update=None,
            gradient_clipping_threshold=None,
            ptype=None,
            format=None,
            nnz=None,
            is_static=None,
            is_shared=None,
            update_hooks=None,
Q
qijun 已提交
527
            input_layer_argument=None, ):
Z
zhangjinchao01 已提交
528 529 530 531 532 533 534 535 536 537 538 539 540
        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 已提交
541

Z
zhangjinchao01 已提交
542 543
    def calc_parameter_size(self, input_size, output_size):
        raise NotimplementedError
Q
qijun 已提交
544

Z
zhangjinchao01 已提交
545 546 547 548 549 550 551 552 553 554
    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 已提交
555

Z
zhangjinchao01 已提交
556 557
    def calc_parameter_size(self, input_size, output_size):
        return 0
Q
qijun 已提交
558

Z
zhangjinchao01 已提交
559 560 561
    def calc_parameter_dims(self, input_size, output_size):
        return []

Q
qijun 已提交
562

Z
zhangjinchao01 已提交
563 564 565 566 567 568
# 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 已提交
569 570 571
    def __init__(self, input_layer_name, offset, **xargs):
        super(IdentityOffsetProjection, self).__init__(input_layer_name,
                                                       **xargs)
Z
zhangjinchao01 已提交
572 573 574 575
        self.proj_conf.offset = offset

    def calc_parameter_size(self, input_size, output_size):
        return 0
Q
qijun 已提交
576

Z
zhangjinchao01 已提交
577 578 579
    def calc_parameter_dims(self, input_size, output_size):
        return []

Q
qijun 已提交
580

Z
zhangjinchao01 已提交
581 582 583 584 585 586 587
# 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 已提交
588

Z
zhangjinchao01 已提交
589 590
    def calc_parameter_size(self, input_size, output_size):
        return output_size
Q
qijun 已提交
591

Z
zhangjinchao01 已提交
592 593 594
    def calc_parameter_dims(self, input_size, output_size):
        return [1, output_size]

X
xuwei06 已提交
595 596 597 598 599 600 601 602 603 604 605 606 607 608
# 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 已提交
609

Z
zhangjinchao01 已提交
610 611 612 613 614 615
@config_class
class TableProjection(Projection):
    type = 'table'

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

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

Q
qijun 已提交
620

Z
zhangjinchao01 已提交
621 622 623 624 625 626
@config_class
class FullMatrixProjection(Projection):
    type = 'fc'

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

Z
zhangjinchao01 已提交
628 629 630
    def calc_parameter_dims(self, input_size, output_size):
        return [input_size, output_size]

Q
qijun 已提交
631

Z
zhangjinchao01 已提交
632 633 634 635 636 637
@config_class
class TransposedFullMatrixProjection(Projection):
    type = 'trans_fc'

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

Z
zhangjinchao01 已提交
639 640 641
    def calc_parameter_dims(self, input_size, output_size):
        return [output_size, input_size]

Q
qijun 已提交
642

Z
zhangjinchao01 已提交
643 644 645 646
@config_class
class ContextProjection(Projection):
    type = 'context'

Q
qijun 已提交
647 648
    def __init__(self, input_layer_name, context_start, context_length,
                 trainable_padding, **xargs):
Z
zhangjinchao01 已提交
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
        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


672 673 674 675
@config_class
class ConvProjection(Projection):
    type = 'conv'

Q
qijun 已提交
676 677 678 679 680
    def __init__(self,
                 input_layer_name,
                 num_filters=None,
                 conv_conf=None,
                 **xargs):
681 682 683 684 685
        super(ConvProjection, self).__init__(input_layer_name, **xargs)

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

Q
qijun 已提交
686
        parse_conv(conv_conf, input_layer_name, self.proj_conf.conv_conf,
687
                   num_filters)
688
        # TODO: support rectangle input
Y
Yu Yang 已提交
689 690
        self.proj_conf.output_size = (self.proj_conf.conv_conf.output_x
                                      **2) * num_filters
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707

    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
        return co * ci * fh * fw

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

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

Q
qijun 已提交
708

Z
zhangjinchao01 已提交
709 710 711
# Define a operator for mixed layer
@config_class
class Operator(Cfg):
Q
qijun 已提交
712 713
    type = None  # subclass should set it correctly

Z
zhangjinchao01 已提交
714 715
    def __init__(
            self,
Q
qijun 已提交
716
            input_layer_names, ):
Z
zhangjinchao01 已提交
717 718 719 720 721 722 723 724 725 726
        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 已提交
727

Z
zhangjinchao01 已提交
728 729 730
@config_class
class DotMulOperator(Operator):
    type = 'dot_mul'
Q
qijun 已提交
731 732 733

    def __init__(self, input_layer_names, scale=None, **xargs):
        super(DotMulOperator, self).__init__(input_layer_names, **xargs)
Z
zhangjinchao01 已提交
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
        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 已提交
752 753 754 755 756 757 758

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

762 763
        parse_conv(conv_conf,
                   MakeLayerNameInSubmodel(input_layer_names[0]),
Q
qijun 已提交
764 765 766
                   self.operator_conf.conv_conf, num_filters)
        self.operator_conf.output_size = (self.operator_conf.conv_conf.output_x
                                          **2) * num_filters
Z
zhangjinchao01 已提交
767 768 769

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

770 771
    def calc_output_size(self, input_sizes):
        return self.operator_conf.output_size
Z
zhangjinchao01 已提交
772 773 774 775 776


# please refer to the comments in proto/ModelConfig.proto
@config_class
class Conv(Cfg):
Q
qijun 已提交
777 778 779 780 781 782 783 784 785 786 787 788 789
    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):
Z
zhangjinchao01 已提交
790 791
        self.add_keys(locals())
        if filter_size_y is None:
Q
qijun 已提交
792
            self.filter_size_y = filter_size
Z
zhangjinchao01 已提交
793
        if padding_y is None:
Q
qijun 已提交
794
            self.padding_y = padding
Z
zhangjinchao01 已提交
795
        if stride_y is None:
Q
qijun 已提交
796
            self.stride_y = stride
Z
zhangjinchao01 已提交
797
        if output_x is not None:
Q
qijun 已提交
798 799
            config_assert(output_x <= 0)

Z
zhangjinchao01 已提交
800

L
liaogang 已提交
801 802 803
# please refer to the comments in proto/ModelConfig.proto
@config_class
class BilinearInterp(Cfg):
Q
qijun 已提交
804
    def __init__(self, out_size_x=None, out_size_y=None, num_channels=None):
L
liaogang 已提交
805 806
        self.add_keys(locals())

Q
qijun 已提交
807

Z
zhangjinchao01 已提交
808 809 810
# please refer to the comments in proto/ModelConfig.proto
@config_class
class Pool(Cfg):
Q
qijun 已提交
811 812 813 814 815 816 817
    def __init__(self,
                 pool_type,
                 channels,
                 size_x,
                 size_y=None,
                 img_width=None,
                 start=None,
D
dangqingqing 已提交
818
                 stride=None, # 1 by defalut in protobuf
Q
qijun 已提交
819
                 stride_y=None,
D
dangqingqing 已提交
820
                 padding=None, # 0 by defalut in protobuf
Q
qijun 已提交
821
                 padding_y=None):
Z
zhangjinchao01 已提交
822
        self.add_keys(locals())
Q
qijun 已提交
823 824


Q
qijun 已提交
825 826
# please refer to the comments in proto/ModelConfig.proto
@config_class
Q
qijun 已提交
827
class SpatialPyramidPool(Cfg):
Q
qijun 已提交
828
    def __init__(self, pool_type, pyramid_height, channels, img_width=None):
Q
qijun 已提交
829
        self.add_keys(locals())
Z
zhangjinchao01 已提交
830

Q
qijun 已提交
831

Z
zhangjinchao01 已提交
832 833 834
# please refer to the comments in proto/ModelConfig.proto
@config_class
class Norm(Cfg):
Q
qijun 已提交
835 836 837 838 839 840 841 842 843
    def __init__(self,
                 norm_type,
                 channels,
                 size,
                 scale,
                 pow,
                 output_x=None,
                 img_size=None,
                 blocked=None):
Z
zhangjinchao01 已提交
844 845
        self.add_keys(locals())

Q
qijun 已提交
846

Z
zhangjinchao01 已提交
847 848 849
# please refer to the comments in proto/ModelConfig.proto
@config_class
class Image(Cfg):
Q
qijun 已提交
850
    def __init__(self, channels, img_size=None):
Z
zhangjinchao01 已提交
851 852
        self.add_keys(locals())

Q
qijun 已提交
853

Z
zhangjinchao01 已提交
854 855
@config_class
class BlockExpand(Cfg):
Q
qijun 已提交
856 857 858 859 860 861 862 863 864 865 866 867
    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 已提交
868 869
        self.add_keys(locals())

Q
qijun 已提交
870

871 872
@config_class
class MaxOut(Cfg):
Q
qijun 已提交
873
    def __init__(self, channels, groups, img_size_x=0, img_size_y=0):
874 875
        self.add_keys(locals())

Q
qijun 已提交
876

Z
zhangjinchao01 已提交
877 878 879 880 881 882 883 884 885 886 887 888 889
def DataBase(async_load_data=False,
             constant_slots=None,
             data_ratio=1,
             is_main_data=True,
             usage_ratio=None):
    # 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 已提交
890 891
    data_config.data_ratio = data_ratio
    data_config.is_main_data = is_main_data
Z
zhangjinchao01 已提交
892

Q
qijun 已提交
893
    usage_ratio = default(usage_ratio, settings_deprecated["usage_ratio"])
Z
zhangjinchao01 已提交
894 895 896 897 898 899
    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 已提交
900

Z
zhangjinchao01 已提交
901
@config_func
Q
qijun 已提交
902 903 904 905 906
def SimpleData(files=None,
               feat_dim=None,
               context_len=None,
               buffer_capacity=None,
               **xargs):
Z
zhangjinchao01 已提交
907 908 909 910 911 912 913 914 915 916
    data_config = DataBase(**xargs)
    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 已提交
917

Z
zhangjinchao01 已提交
918
@config_func
Q
qijun 已提交
919 920 921 922 923 924 925 926 927 928
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):
Z
zhangjinchao01 已提交
929 930 931
    data_config = DataBase(**xargs)
    data_config.type = 'py'
    if load_data_module in g_py_module_name_list:
Q
qijun 已提交
932

Z
zhangjinchao01 已提交
933 934 935
        def get_path(module):
            m = __import__(load_data_module)
            return os.path.split(os.path.realpath(m.__file__))[0]
Q
qijun 已提交
936

Z
zhangjinchao01 已提交
937 938 939
        # 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 已提交
940 941
        module_new_name = "%s_copy_%d" % (load_data_module,
                                          len(g_py_module_name_list))
Z
zhangjinchao01 已提交
942
        g_py_module_name_list.append(module_new_name)
Q
qijun 已提交
943 944 945 946
        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 已提交
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
        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 已提交
971

Z
zhangjinchao01 已提交
972
@config_func
Q
qijun 已提交
973 974 975 976 977 978 979
def ProtoData(files=None,
              type=None,
              file_group_queue_capacity=None,
              load_file_count=None,
              constant_slots=None,
              load_thread_num=None,
              **xargs):
Z
zhangjinchao01 已提交
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
    data_config = DataBase(**xargs)
    if type is None:
        data_config.type = 'proto'
    else:
        data_config.type = type
    data_config.files = files

    # When type="proto_group", one data provider contains at most
    # load_file_count files, and there are at most
    # (queue_capacity + load_thread_num + 1) data providers in memory
    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 已提交
1000

Z
zhangjinchao01 已提交
1001 1002
#real data for training is actually provided by "sub_data" data providers.
@config_func
Q
qijun 已提交
1003
def MultiData(sub_data=[]):
Z
zhangjinchao01 已提交
1004 1005 1006 1007 1008
    data_config = DataConfig()
    data_config.type = 'multi'
    data_config.sub_data_configs.extend(sub_data)
    return data_config

Q
qijun 已提交
1009

Z
zhangjinchao01 已提交
1010
@config_func
Q
qijun 已提交
1011 1012 1013 1014 1015 1016 1017
def Data(type,
         files=None,
         feat_dim=None,
         slot_dims=None,
         context_len=None,
         buffer_capacity=None,
         **xargs):
Z
zhangjinchao01 已提交
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052

    data_config = DataBase(**xargs)
    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 已提交
1053

L
liaogang 已提交
1054
def parse_bilinear(bilinear, input_layer_name, bilinear_conf):
Q
qijun 已提交
1055 1056 1057 1058
    bilinear_conf.out_size_x = bilinear.out_size_x
    bilinear_conf.out_size_y = bilinear.out_size_y
    bilinear_conf.num_channels = bilinear.num_channels

L
liaogang 已提交
1059

1060 1061 1062 1063
'''
caffe_mode: compute the output size using floor instead of ceil,
            which is consistent of caffe and CuDNN's convention.
'''
Q
qijun 已提交
1064 1065


1066 1067 1068 1069 1070 1071 1072
def cnn_output_size(img_size, filter_size, padding, stride, caffe_mode):
    output = (2 * padding + img_size - filter_size) / float(stride)
    if caffe_mode:
        return 1 + int(math.floor(output))
    else:
        return 1 + int(math.ceil(output))

Q
qijun 已提交
1073

1074 1075 1076 1077
'''
calcualte image_size based on output_size for convolution. 
It is the reverse function of cnn_output_size
'''
Q
qijun 已提交
1078 1079


1080 1081 1082 1083
def cnn_image_size(output_size, filter_size, padding, stride, caffe_mode):
    if caffe_mode:
        img_size = (output_size - 1) * stride + filter_size - 2 * padding
    else:
Q
qijun 已提交
1084
        img_size = (output_size - 2) * stride + filter_size - 2 * padding + 1
1085 1086
    return img_size

Q
qijun 已提交
1087

Z
zhangjinchao01 已提交
1088 1089
def parse_pool(pool, input_layer_name, pool_conf):
    pool_conf.pool_type = pool.pool_type
Q
qijun 已提交
1090 1091 1092
    config_assert(pool.pool_type in [
        'max-projection', 'avg-projection', 'cudnn-max-pool', 'cudnn-avg-pool'
    ], "pool-type %s is not in "
Z
zhangjinchao01 已提交
1093
                  "['max-projection', 'avg-projection', "
Q
qijun 已提交
1094
                  "'cudnn-max-pool', 'cudnn-avg-pool']" % pool.pool_type)
Z
zhangjinchao01 已提交
1095 1096 1097 1098 1099 1100

    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 已提交
1101
    pool_conf.stride_y = default(pool.stride_y, pool_conf.stride)
Z
zhangjinchao01 已提交
1102 1103

    img_pixels = g_layer_map[input_layer_name].size / pool.channels
1104 1105
    # the img_width may be removed,
    # and it can be calculated automatically later.
Q
qijun 已提交
1106
    pool_conf.img_size = default(pool.img_width, int(img_pixels**0.5))
Z
zhangjinchao01 已提交
1107 1108
    pool_conf.img_size_y = img_pixels / pool_conf.img_size
    config_assert(pool_conf.img_size * pool_conf.img_size_y == img_pixels,
Q
qijun 已提交
1109 1110
                  "Incorrect input image size %d for input image pixels %d" %
                  (pool_conf.img_size, img_pixels))
Z
zhangjinchao01 已提交
1111

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

1114
    if pool.padding is not None:
D
dangqingqing 已提交
1115
        pool_conf.padding = pool.padding
1116 1117 1118 1119 1120 1121 1122
    pool_conf.padding_y = default(pool.padding_y, pool_conf.padding)
    pool_conf.output_x = cnn_output_size(
        pool_conf.img_size, pool_conf.size_x, pool_conf.padding,
        pool_conf.stride, False)
    pool_conf.output_y = cnn_output_size(
        pool_conf.img_size_y, pool_conf.size_y, pool_conf.padding_y,
        pool_conf.stride_y, False)
Q
qijun 已提交
1123

Z
zhangjinchao01 已提交
1124

Q
qijun 已提交
1125 1126 1127
def parse_spp(spp, input_layer_name, spp_conf):
    spp_conf.pool_type = spp.pool_type
    config_assert(spp.pool_type in ['max-projection', 'avg-projection'],
Q
qijun 已提交
1128 1129
                  "pool-type %s is not in "
                  "['max-projection', 'avg-projection']" % spp.pool_type)
Q
qijun 已提交
1130 1131 1132 1133 1134
    spp_conf.pyramid_height = spp.pyramid_height
    spp_conf.channels = spp.channels

    img_pixels = g_layer_map[input_layer_name].size / spp_conf.channels

Q
qijun 已提交
1135
    spp_conf.img_size = default(spp.img_width, int(img_pixels**0.5))
Q
qijun 已提交
1136 1137
    spp_conf.img_size_y = img_pixels / spp_conf.img_size
    config_assert(spp_conf.img_size * spp_conf.img_size_y == img_pixels,
Q
qijun 已提交
1138 1139 1140
                  "Incorrect input image size %d for input image pixels %d" %
                  (spp_conf.img_size, img_pixels))

Q
qijun 已提交
1141

Z
zhangjinchao01 已提交
1142 1143 1144
def parse_image(image, input_layer_name, image_conf):
    image_conf.channels = image.channels
    image_pixels = g_layer_map[input_layer_name].size / image_conf.channels
Q
qijun 已提交
1145 1146 1147 1148 1149
    image_conf.img_size = int(image_pixels**0.5)
    config_assert((image_conf.img_size**2) == image_pixels,
                  "Incorrect input image size %d for input image pixels %d" %
                  (image_conf.img_size, image_pixels))

Z
zhangjinchao01 已提交
1150 1151 1152 1153

def parse_norm(norm, input_layer_name, norm_conf):
    norm_conf.norm_type = norm.norm_type
    config_assert(norm.norm_type in ['rnorm', 'cmrnorm-projection'],
Q
qijun 已提交
1154 1155
                  "norm-type %s is not in [rnorm, 'cmrnorm-projection']" %
                  norm.norm_type)
Z
zhangjinchao01 已提交
1156 1157 1158 1159 1160 1161 1162
    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

    img_pixels = g_layer_map[input_layer_name].size / norm.channels
Q
qijun 已提交
1163 1164 1165 1166
    norm_conf.img_size = int(img_pixels**0.5)
    config_assert((norm_conf.img_size**2) == img_pixels,
                  "Incorrect input image size %d for input image pixels %d" %
                  (norm_conf.img_size, img_pixels))
Z
zhangjinchao01 已提交
1167 1168 1169 1170
    norm_conf.output_x = norm_conf.img_size
    if norm.norm_type in ['cmrnorm-projection']:
        norm_conf.scale /= norm.size
    else:
Q
qijun 已提交
1171 1172
        norm_conf.scale /= norm.size**2

1173

1174 1175 1176 1177
'''
caffe_mode: compute the output size using floor instead of ceil,
            which is consistent of caffe and CuDNN's convention.
'''
Q
qijun 已提交
1178 1179


1180
def parse_conv(conv, input_layer_name, conv_conf, num_filters, trans=False):
Z
zhangjinchao01 已提交
1181 1182 1183 1184 1185 1186 1187 1188 1189
    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
Q
qijun 已提交
1190

1191
    if not trans:
1192 1193
        conv_conf.filter_channels = conv.channels / conv.groups

1194
        img_pixels = g_layer_map[input_layer_name].size / conv.channels
Q
qijun 已提交
1195 1196 1197 1198 1199 1200 1201 1202
        print('channels=%d size=%d' % (conv.channels,
                                       g_layer_map[input_layer_name].size))
        conv_conf.img_size = int(img_pixels**0.5)
        config_assert((conv_conf.img_size**2) == img_pixels, (
            "Input layer %s: Incorrect input image size %d for input " +
            "image pixels %d") %
                      (input_layer_name, conv_conf.img_size, img_pixels))

1203
        conv_conf.output_x = cnn_output_size(
Q
qijun 已提交
1204 1205
            conv_conf.img_size, conv_conf.filter_size, conv_conf.padding,
            conv_conf.stride, conv_conf.caffe_mode)
1206
    else:
1207
        conv_conf.filter_channels = num_filters / conv.groups
Q
qijun 已提交
1208

1209
        outputSize = g_layer_map[input_layer_name].size / conv.channels
Q
qijun 已提交
1210 1211 1212 1213 1214 1215 1216
        print('channels=%d size=%d' % (conv.channels,
                                       g_layer_map[input_layer_name].size))
        conv_conf.output_x = int(outputSize**0.5)
        config_assert((conv_conf.output_x**2) == outputSize, (
            "Input layer %s: Incorrect input image size %d for input " +
            "image pixels %d") %
                      (input_layer_name, conv_conf.output_x, outputSize))
1217
        conv_conf.img_size = cnn_image_size(
Q
qijun 已提交
1218 1219 1220
            conv_conf.output_x, conv_conf.filter_size, conv_conf.padding,
            conv_conf.stride, conv_conf.caffe_mode)

1221

Z
zhangjinchao01 已提交
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
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:
1235
        block_expand_conf.output_x = cnn_output_size(
1236
            block_expand.img_size_x, block_expand.block_x,
1237
            block_expand.padding_x, block_expand.stride_x, False)
Z
zhangjinchao01 已提交
1238 1239

    if block_expand_conf.img_size_y == 0:
1240
        block_expand_conf.output_y = 0
Z
zhangjinchao01 已提交
1241
    else:
1242
        block_expand_conf.output_y = cnn_output_size(
1243
            block_expand.img_size_y, block_expand.block_y,
1244
            block_expand.padding_y, block_expand.stride_y, False)
Z
zhangjinchao01 已提交
1245

Q
qijun 已提交
1246

1247 1248 1249 1250 1251
def parse_maxout(maxout, input_layer_name, maxout_conf):
    maxout_conf.channels = maxout.channels
    maxout_conf.groups = maxout.groups
    maxout_conf.img_size_x = maxout.img_size_x
    maxout_conf.img_size_y = maxout.img_size_y
1252

Q
qijun 已提交
1253

Z
zhangjinchao01 已提交
1254 1255 1256 1257 1258 1259
# Define an evaluator
@config_func
def Evaluator(
        name,
        type,
        inputs,
Q
qijun 已提交
1260 1261 1262 1263 1264 1265 1266 1267
        chunk_scheme=None,
        num_chunk_types=None,
        classification_threshold=None,
        positive_label=None,
        dict_file=None,
        result_file=None,
        num_results=None,
        delimited=None, ):
Z
zhangjinchao01 已提交
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
    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)

1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
    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
    if delimited is not None:
        evaluator.delimited = delimited
Z
zhangjinchao01 已提交
1295

Q
qijun 已提交
1296

Z
zhangjinchao01 已提交
1297 1298 1299 1300 1301
class LayerBase(object):
    def __init__(
            self,
            name,
            type,
Q
qijun 已提交
1302
            size,  # size can be 0. In this case, subclass should set it.
Z
zhangjinchao01 已提交
1303 1304 1305 1306
            inputs,
            device=None,
            active_type="",
            drop_rate=0.,
1307
            coeff=None):
Z
zhangjinchao01 已提交
1308
        config_assert('@' not in name,
Q
qijun 已提交
1309
                      "layer name: %s contain special character @" % name)
Z
zhangjinchao01 已提交
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
        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()
1325
        assert isinstance(self.config, LayerConfig)
Z
zhangjinchao01 已提交
1326 1327 1328
        self.config.name = name
        self.config.type = type
        self.config.active_type = active_type
1329 1330
        if coeff is not None:
            self.config.coeff = float(coeff)
Z
zhangjinchao01 已提交
1331 1332 1333 1334 1335 1336 1337
        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
1338
        elif g_default_device is not None:
Z
zhangjinchao01 已提交
1339 1340 1341 1342 1343 1344 1345 1346 1347
            self.config.device = g_default_device

        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 已提交
1348 1349
                    input_layer_name=input,
                    parameter_name=gen_parameter_name(name, input_index))
Z
zhangjinchao01 已提交
1350 1351 1352 1353 1354 1355 1356 1357
                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 已提交
1358
                self.operators.append(input)
Z
zhangjinchao01 已提交
1359 1360 1361 1362
                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 已提交
1363
                raise ValueError('Wrong type for inputs: %s' % type_of(input))
Z
zhangjinchao01 已提交
1364
            config_assert(input_layer_name in g_layer_map,
Q
qijun 已提交
1365 1366
                          "Unknown input layer '%s' for layer %s" %
                          (input_layer_name, name))
Z
zhangjinchao01 已提交
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
            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 已提交
1384
            bias,  # True/False or BiasCfg
Z
zhangjinchao01 已提交
1385
            size,
Q
qijun 已提交
1386 1387 1388
            dims=None,
            for_self=True,  # whether create bias for layer self
    ):
Z
zhangjinchao01 已提交
1389 1390 1391 1392 1393 1394

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

Q
qijun 已提交
1395 1396 1397
        config_assert(
            type_of(bias) == bool or type_of(bias) == Bias,
            'Incorrect type for bias: %s' % type_of(bias))
Z
zhangjinchao01 已提交
1398 1399 1400 1401 1402 1403 1404 1405 1406

        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:
1407 1408
                assert isinstance(self.config, LayerConfig)

Z
zhangjinchao01 已提交
1409 1410 1411
                Parameter(
                    bias.parameter_name,
                    size,
Q
qijun 已提交
1412 1413
                    self.config.device
                    if self.config.HasField('device') else None,
Z
zhangjinchao01 已提交
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
                    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 已提交
1425 1426
                    gradient_clipping_threshold=bias.
                    gradient_clipping_threshold,
Z
zhangjinchao01 已提交
1427
                    is_static=bias.is_static,
Q
qijun 已提交
1428
                    is_shared=bias.is_shared, )
Z
zhangjinchao01 已提交
1429 1430 1431 1432 1433
            if for_self:
                self.config.bias_parameter_name = bias.parameter_name
            else:
                return bias.parameter_name

Q
qijun 已提交
1434 1435 1436 1437 1438 1439
    def create_input_parameter(self,
                               input_index,
                               size,
                               dims=None,
                               sparse=None,
                               format=None):
Z
zhangjinchao01 已提交
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
        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 已提交
1454 1455
            config_assert(size == para.size, (
                'Shared parameter "%s" does not ' + 'have same size: %s vs. %s')
Z
zhangjinchao01 已提交
1456 1457
                          % (input_config.parameter_name, para.size, size))

Q
qijun 已提交
1458 1459
            config_assert(dims == para.dims, (
                'Shared parameter "%s" does not ' + 'have same dims: %s vs. %s')
Z
zhangjinchao01 已提交
1460 1461 1462 1463 1464 1465
                          % (input_config.parameter_name, para.dims, dims))
            return

        Parameter(
            input_config.parameter_name,
            size,
1466
            self.config.device if self.config.HasField("device") else None,
Z
zhangjinchao01 已提交
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
            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 已提交
1479 1480
            gradient_clipping_threshold=input_config.
            gradient_clipping_threshold,
Z
zhangjinchao01 已提交
1481 1482 1483 1484
            sparse=sparse,
            format=format,
            is_static=input_config.is_static,
            is_shared=input_config.is_shared,
Q
qijun 已提交
1485
            update_hooks=input_config.update_hooks)
Z
zhangjinchao01 已提交
1486 1487 1488 1489 1490 1491 1492 1493 1494

    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)

Q
qijun 已提交
1495

Z
zhangjinchao01 已提交
1496 1497
@config_layer('multi_class_cross_entropy_with_selfnorm')
class MultiClassCrossEntropySelfNormCostLayer(LayerBase):
Q
qijun 已提交
1498 1499 1500
    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 已提交
1501 1502
        self.config.softmax_selfnorm_alpha = softmax_selfnorm_alpha

Q
qijun 已提交
1503

Z
zhangjinchao01 已提交
1504 1505
@config_layer('fc')
class FCLayer(LayerBase):
Q
qijun 已提交
1506
    def __init__(self, name, size, inputs, bias=True, **xargs):
Z
zhangjinchao01 已提交
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
        super(FCLayer, self).__init__(name, 'fc', size, inputs=inputs, **xargs)
        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"

            if sparse:
                psize = self.inputs[input_index].nnz
1517 1518
            else:
                sparse = None
Z
zhangjinchao01 已提交
1519

Q
qijun 已提交
1520 1521
            self.create_input_parameter(input_index, psize, dims, sparse,
                                        format)
Z
zhangjinchao01 已提交
1522 1523
        self.create_bias_parameter(bias, self.config.size)

Q
qijun 已提交
1524

Z
zhangjinchao01 已提交
1525 1526
@config_layer('selective_fc')
class SelectiveFCLayer(LayerBase):
Q
qijun 已提交
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
    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 已提交
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
        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 已提交
1557 1558
                          ("if indices of selected columns are not specified, "
                           "selective_fc Layer has at least two inputs"))
Z
zhangjinchao01 已提交
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
            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 已提交
1571 1572
            self.create_input_parameter(input_index, psize, dims, sparse,
                                        format)
Z
zhangjinchao01 已提交
1573 1574
        self.create_bias_parameter(bias, self.config.size)

Q
qijun 已提交
1575

1576 1577
@config_layer('print')
class PrintLayer(LayerBase):
Q
qijun 已提交
1578
    def __init__(self, name, inputs):
1579 1580
        super(PrintLayer, self).__init__(name, 'print', 0, inputs)

Q
qijun 已提交
1581

Z
zhangjinchao01 已提交
1582 1583
@config_layer('data')
class DataLayer(LayerBase):
Q
qijun 已提交
1584 1585 1586 1587
    def __init__(self, name, size, device=None):
        super(DataLayer, self).__init__(
            name, 'data', size, inputs=[], device=device)

Z
zhangjinchao01 已提交
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614

'''
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 已提交
1615 1616


Z
zhangjinchao01 已提交
1617 1618
@config_layer('data_norm')
class DataNormLayer(LayerBase):
Q
qijun 已提交
1619
    def __init__(self, name, inputs, data_norm_strategy="z-score", device=None):
Z
zhangjinchao01 已提交
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
        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 已提交
1631

Z
zhangjinchao01 已提交
1632 1633 1634
@config_layer('prelu')
class ParameterReluLayer(LayerBase):
    layer_type = 'prelu'
Q
qijun 已提交
1635 1636

    def __init__(self, name, inputs, partial_sum=1, **args):
Z
zhangjinchao01 已提交
1637 1638 1639 1640 1641 1642 1643 1644
        super(ParameterReluLayer, self).__init__(
            name, self.layer_type, 0, inputs=inputs, **args)
        config_assert(len(self.inputs) == 1)
        config_assert(self.input_layer.size % partial_sum == 0)
        input_layer = self.get_input_layer(0)
        self.set_layer_size(input_layer.size)
        self.create_input_parameter(0, input_layer.size / partial_sum)

Q
qijun 已提交
1645

Z
zhangjinchao01 已提交
1646 1647 1648
@config_layer('conv')
class ConvLayerBase(LayerBase):
    layer_type = 'conv'
Q
qijun 已提交
1649 1650 1651 1652 1653 1654 1655 1656

    def __init__(self,
                 name,
                 inputs=[],
                 bias=True,
                 num_filters=None,
                 shared_biases=False,
                 **xargs):
Z
zhangjinchao01 已提交
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
        super(ConvLayerBase, self).__init__(
            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))

        # Automatically select cudnn_type for GPU and exconv for CPU
        # if set type=conv, but still reserve the way user specify
        # exconv or cudnn_conv manually.
        if self.layer_type == "cudnn_conv":
            config_assert(use_gpu, "cudnn_conv only support GPU")

        if (use_gpu == 1 and self.layer_type != "exconv" and
Q
qijun 已提交
1673
            (parallel_nn == 0 or self.config.device > -1)):
Z
zhangjinchao01 已提交
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
            self.layer_type = "cudnn_conv"
        else:
            self.layer_type = "exconv"
        # 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)
Q
qijun 已提交
1685 1686
            parse_conv(self.inputs[input_index].conv, input_layer.name,
                       self.config.inputs[input_index].conv_conf, num_filters)
Z
zhangjinchao01 已提交
1687 1688 1689 1690 1691
            conv_conf = self.config.inputs[input_index].conv_conf
            psize = self.calc_parameter_size(conv_conf)
            print("output size for %s is %d " % (name, conv_conf.output_x))
            self.create_input_parameter(input_index, psize)
            self.set_layer_size(
Q
qijun 已提交
1692
                (conv_conf.output_x**2) * self.config.num_filters)
Z
zhangjinchao01 已提交
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702

        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)

Q
qijun 已提交
1703

Z
zhangjinchao01 已提交
1704 1705 1706 1707
@config_layer('exconv')
class ConvLayer(ConvLayerBase):
    layer_type = 'exconv'

Q
qijun 已提交
1708

Z
zhangjinchao01 已提交
1709 1710 1711 1712
@config_layer('cudnn_conv')
class ConvLayer(ConvLayerBase):
    layer_type = 'cudnn_conv'

1713 1714 1715 1716

@config_layer('convt')
class ConvTransLayerBase(LayerBase):
    layer_type = 'convt'
Q
qijun 已提交
1717 1718 1719 1720 1721 1722 1723 1724

    def __init__(self,
                 name,
                 inputs=[],
                 bias=True,
                 num_filters=None,
                 shared_biases=False,
                 **xargs):
1725
        super(ConvTransLayerBase, self).__init__(
1726 1727 1728 1729 1730 1731 1732 1733
            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))

1734 1735
        # cudnn_convt has not been implemented so use exconvt only
        self.layer_type = "exconvt"
1736 1737 1738 1739 1740 1741 1742 1743
        # 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)
1744
            parse_conv(
1745 1746
                self.inputs[input_index].conv,
                input_layer.name,
1747
                self.config.inputs[input_index].conv_conf,
1748
                num_filters,
1749
                trans=True)
1750 1751 1752 1753 1754
            conv_conf = self.config.inputs[input_index].conv_conf
            psize = self.calc_parameter_size(conv_conf)
            print("output size for %s is %d " % (name, conv_conf.output_x))
            self.create_input_parameter(input_index, psize)
            self.set_layer_size(
Q
qijun 已提交
1755
                (conv_conf.img_size**2) * self.config.num_filters)
1756 1757 1758 1759 1760 1761 1762

        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):
1763
        return conv_conf.channels * conv_conf.filter_channels \
1764 1765
                    * (conv_conf.filter_size * conv_conf.filter_size_y)

Q
qijun 已提交
1766

1767 1768 1769 1770
@config_layer('exconvt')
class ConvTransLayer(ConvTransLayerBase):
    layer_type = 'exconvt'

Q
qijun 已提交
1771

Z
zhangjinchao01 已提交
1772 1773
@config_layer('norm')
class NormLayer(LayerBase):
Q
qijun 已提交
1774 1775 1776
    def __init__(self, name, inputs, device=None):
        super(NormLayer, self).__init__(
            name, 'norm', 0, inputs=inputs, device=device)
Z
zhangjinchao01 已提交
1777 1778
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
Q
qijun 已提交
1779 1780
            parse_norm(self.inputs[input_index].norm, input_layer.name,
                       self.config.inputs[input_index].norm_conf)
Z
zhangjinchao01 已提交
1781
            norm_conf = self.config.inputs[input_index].norm_conf
Q
qijun 已提交
1782 1783
            self.set_layer_size((norm_conf.output_x**2) * norm_conf.channels)

Z
zhangjinchao01 已提交
1784 1785 1786

@config_layer('pool')
class PoolLayer(LayerBase):
Q
qijun 已提交
1787 1788 1789
    def __init__(self, name, inputs, device=None):
        super(PoolLayer, self).__init__(
            name, 'pool', 0, inputs=inputs, device=device)
Z
zhangjinchao01 已提交
1790 1791
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
Q
qijun 已提交
1792 1793
            parse_pool(self.inputs[input_index].pool, input_layer.name,
                       self.config.inputs[input_index].pool_conf)
Z
zhangjinchao01 已提交
1794
            pool_conf = self.config.inputs[input_index].pool_conf
Q
qijun 已提交
1795 1796 1797 1798 1799
            print("output size for %s is %d*%d " % (name, pool_conf.output_y,
                                                    pool_conf.output_x))
            self.set_layer_size(
                (pool_conf.output_x * pool_conf.output_y) * pool_conf.channels)

Z
zhangjinchao01 已提交
1800

Q
qijun 已提交
1801 1802
@config_layer('spp')
class SpatialPyramidPoolLayer(LayerBase):
Q
qijun 已提交
1803 1804 1805
    def __init__(self, name, inputs, device=None):
        super(SpatialPyramidPoolLayer, self).__init__(
            name, 'spp', 0, inputs=inputs, device=device)
Q
qijun 已提交
1806 1807
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
Q
qijun 已提交
1808 1809
            parse_spp(self.inputs[input_index].spp, input_layer.name,
                      self.config.inputs[input_index].spp_conf)
Q
qijun 已提交
1810 1811 1812 1813 1814
            spp_conf = self.config.inputs[input_index].spp_conf
            output_size = (pow(4, spp_conf.pyramid_height) - 1) / (4 - 1)
            print("output size for %s is %d " % (name, output_size))
            self.set_layer_size(output_size * spp_conf.channels)

Q
qijun 已提交
1815

Z
zhangjinchao01 已提交
1816 1817 1818
@config_layer('batch_norm')
class BatchNormLayer(LayerBase):
    layer_type = 'batch_norm'
Q
qijun 已提交
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829

    def __init__(self,
                 name,
                 inputs,
                 active_type="linear",
                 bias=True,
                 device=None,
                 use_global_stats=True,
                 moving_average_fraction=0.9,
                 batch_norm_type=None,
                 **xargs):
Z
zhangjinchao01 已提交
1830 1831 1832 1833
        if inputs is None:
            inputs = []
        elif not isinstance(inputs, list):
            inputs = [inputs]
Q
qijun 已提交
1834 1835
        config_assert(
            len(inputs) == 1, "BatchNormLayer must have one and only one input")
Z
zhangjinchao01 已提交
1836 1837 1838 1839 1840 1841 1842 1843
        # 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)))
        is_shared = True if not use_gpu else False
        for i in xrange(2):
Q
qijun 已提交
1844 1845 1846 1847 1848 1849 1850
            inputs.append(
                Input(
                    inputs[0].input_layer_name,
                    initial_std=0.0,
                    initial_mean=0.0,
                    is_static=True,
                    is_shared=is_shared, ))
Z
zhangjinchao01 已提交
1851 1852 1853 1854 1855 1856 1857

        parallel_nn = bool(int(g_command_config_args.get("parallel_nn", 0)))
        cudnn_version = int(g_command_config_args.get("cudnn_version", 0))
        # Automatically select cudnn_batch_norm for GPU and batch_norm for CPU.
        # Also based on cudnn version.
        use_cudnn = use_gpu and batch_norm_type != "batch_norm" and \
            ((not parallel_nn) or self.config.device > -1) and \
1858
            cudnn_version >= 4007
Z
zhangjinchao01 已提交
1859
        self.layer_type = "cudnn_batch_norm" if use_cudnn else "batch_norm"
Q
qijun 已提交
1860 1861 1862 1863 1864 1865 1866 1867
        super(BatchNormLayer, self).__init__(
            name,
            self.layer_type,
            0,
            active_type=active_type,
            inputs=inputs,
            device=device,
            **xargs)
Z
zhangjinchao01 已提交
1868 1869 1870 1871 1872 1873

        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

Q
qijun 已提交
1874 1875
        input_layer = self.get_input_layer(0)
        parse_image(self.inputs[0].image, input_layer.name,
Z
zhangjinchao01 已提交
1876 1877
                    self.config.inputs[0].image_conf)
        image_conf = self.config.inputs[0].image_conf
Q
qijun 已提交
1878
        self.set_layer_size((image_conf.img_size**2) * image_conf.channels)
Z
zhangjinchao01 已提交
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890

        psize = self.calc_parameter_size(image_conf)
        dims = [1, psize]
        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)

    def calc_parameter_size(self, image_conf):
        return image_conf.channels

Q
qijun 已提交
1891

Z
zhangjinchao01 已提交
1892 1893
@config_layer('trans')
class TransLayer(LayerBase):
Q
qijun 已提交
1894 1895 1896 1897 1898 1899
    def __init__(self, name, inputs, device=None):
        super(TransLayer, self).__init__(
            name, 'trans', 0, inputs=inputs, device=device)
        config_assert(
            len(self.inputs) == 1,
            'TransLayer must have one and only one input')
Z
zhangjinchao01 已提交
1900 1901
        self.set_layer_size(self.get_input_layer(0).size)

Q
qijun 已提交
1902

Z
zhangjinchao01 已提交
1903 1904
@config_layer('resize')
class ResizeLayer(LayerBase):
Q
qijun 已提交
1905 1906 1907 1908 1909 1910 1911
    def __init__(self, name, size, inputs, device=None):
        super(ResizeLayer, self).__init__(
            name, 'resize', size=size, inputs=inputs, device=device)
        config_assert(
            len(self.inputs) == 1,
            'ResizeLayer must have one and only one input')

Z
zhangjinchao01 已提交
1912 1913 1914

@config_layer('blockexpand')
class BlockExpandLayer(LayerBase):
Q
qijun 已提交
1915 1916 1917
    def __init__(self, name, inputs, device=None):
        super(BlockExpandLayer, self).__init__(
            name, 'blockexpand', 0, inputs=inputs, device=device)
Z
zhangjinchao01 已提交
1918 1919
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
Q
qijun 已提交
1920 1921
            parse_block_expand(
                self.inputs[input_index].block_expand, input_layer.name,
Z
zhangjinchao01 已提交
1922
                self.config.inputs[input_index].block_expand_conf)
Q
qijun 已提交
1923 1924 1925 1926 1927 1928
            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 已提交
1929

1930 1931
@config_layer('maxout')
class MaxOutLayer(LayerBase):
Q
qijun 已提交
1932 1933 1934
    def __init__(self, name, inputs, **xargs):
        super(MaxOutLayer, self).__init__(
            name, 'maxout', 0, inputs=inputs, **xargs)
1935
        input_layer = self.get_input_layer(0)
Q
qijun 已提交
1936
        parse_maxout(self.inputs[0].maxout, input_layer.name,
1937 1938
                     self.config.inputs[0].maxout_conf)
        maxout_conf = self.config.inputs[0].maxout_conf
Q
qijun 已提交
1939 1940 1941
        self.set_layer_size(g_layer_map[input_layer.name].size /
                            maxout_conf.groups)

1942

Z
zhangjinchao01 已提交
1943 1944 1945 1946
# key: cost type
# value: cost class
g_cost_map = {}

Q
qijun 已提交
1947

Z
zhangjinchao01 已提交
1948 1949 1950
# 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 已提交
1951 1952
        super(type(cls), cls).__init__(
            name, cost_type, 1, inputs, device=device, coeff=coeff)
Z
zhangjinchao01 已提交
1953

Q
qijun 已提交
1954
    cls = type(class_name, (LayerBase, ), dict(__init__=init))
Z
zhangjinchao01 已提交
1955 1956 1957
    global g_cost_map
    g_cost_map[cost_type] = cls

Q
qijun 已提交
1958

Z
zhangjinchao01 已提交
1959 1960 1961 1962 1963 1964 1965 1966
define_cost('MultiClassCrossEntropy', 'multi-class-cross-entropy')
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')
define_cost('HuberTwoClass', 'huber')
X
xuwei06 已提交
1967
define_cost('SumCost', 'sum_cost')
Z
zhangjinchao01 已提交
1968

Q
qijun 已提交
1969

Z
zhangjinchao01 已提交
1970 1971
@config_layer('hsigmoid')
class HierarchicalSigmoidLayer(LayerBase):
Q
qijun 已提交
1972
    def __init__(self, name, num_classes, inputs, device=None, bias=True):
Z
zhangjinchao01 已提交
1973 1974
        super(HierarchicalSigmoidLayer, self).__init__(
            name, 'hsigmoid', 1, inputs=inputs, device=device)
Q
qijun 已提交
1975 1976 1977
        config_assert(
            len(self.inputs) >= 2,
            'HierarchicalSigmoidLayer must have at least 2 inputs')
Z
zhangjinchao01 已提交
1978 1979 1980 1981 1982 1983 1984 1985
        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 已提交
1986

Z
zhangjinchao01 已提交
1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
'''
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,
          by ProtoDataProvider or PyDataProvider etc.. User should provide
          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 已提交
2011 2012


Z
zhangjinchao01 已提交
2013 2014
@config_layer('lambda_cost')
class LambdaCost(LayerBase):
Q
qijun 已提交
2015
    def __init__(self, name, inputs, NDCG_num=5, max_sort_size=-1, device=None):
Z
zhangjinchao01 已提交
2016 2017
        super(LambdaCost, self).__init__(
            name, 'lambda_cost', 1, inputs=inputs, device=device)
Q
qijun 已提交
2018
        config_assert(len(self.inputs) == 2, 'lambdaCost must have 2 inputs')
Z
zhangjinchao01 已提交
2019 2020
        self.config.NDCG_num = NDCG_num
        if max_sort_size != -1:
Q
qijun 已提交
2021 2022 2023
            config_assert(
                NDCG_num <= max_sort_size,
                'NDCG_num must be less than or equal to max_sort_size')
Z
zhangjinchao01 已提交
2024 2025
        self.config.max_sort_size = max_sort_size

Q
qijun 已提交
2026

Z
zhangjinchao01 已提交
2027 2028
@config_layer('nce')
class NCELayer(LayerBase):
Q
qijun 已提交
2029 2030 2031 2032 2033 2034 2035 2036
    def __init__(self,
                 name,
                 num_classes,
                 inputs,
                 num_neg_samples=10,
                 neg_sampling_dist=None,
                 bias=True,
                 **xargs):
Z
zhangjinchao01 已提交
2037
        super(NCELayer, self).__init__(name, 'nce', 1, inputs=inputs, **xargs)
Q
qijun 已提交
2038 2039
        config_assert(
            len(self.inputs) >= 2, 'NCELayer must have at least 2 inputs')
Z
zhangjinchao01 已提交
2040 2041
        self.config.num_classes = num_classes
        if neg_sampling_dist is not None:
Q
qijun 已提交
2042 2043 2044 2045
            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 已提交
2046
            s = sum(neg_sampling_dist)
Q
qijun 已提交
2047 2048 2049
            config_assert(
                abs(s - 1) < 1e-5,
                'The sum of neg_sampling_dist (%s) is not 1' % s)
Z
zhangjinchao01 已提交
2050 2051 2052 2053 2054

            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 已提交
2055
        input_layer = self.get_input_layer(num_real_inputs)
Z
zhangjinchao01 已提交
2056 2057 2058 2059
        config_assert(input_layer.type == 'data',
                      'Expecting the last input layer of an nce layer to be '
                      'a data layer')

Q
qijun 已提交
2060 2061
        if (num_real_inputs > 1 and input_layer.size == 1 and
                self.get_input_layer(num_real_inputs - 1).type == 'data'):
Z
zhangjinchao01 已提交
2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
            # 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):
Q
qijun 已提交
2075
    def __init__(self, name, inputs, bias=True, **xargs):
Z
zhangjinchao01 已提交
2076 2077
        super(AddToLayer, self).__init__(
            name, 'addto', 0, inputs=inputs, **xargs)
Q
qijun 已提交
2078
        config_assert(len(inputs) > 0, 'inputs cannot be empty for AddToLayer')
Z
zhangjinchao01 已提交
2079 2080 2081 2082 2083
        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 已提交
2084

Z
zhangjinchao01 已提交
2085 2086
@config_layer('agent')
class AgentLayer(LayerBase):
Q
qijun 已提交
2087 2088 2089 2090
    def __init__(self, name, size, device=None):
        super(AgentLayer, self).__init__(
            name, 'agent', size, inputs=[], device=device)

Z
zhangjinchao01 已提交
2091 2092 2093

@config_layer('sequence_agent')
class SequenceAgentLayer(LayerBase):
Q
qijun 已提交
2094
    def __init__(self, name, size, device=None):
Z
zhangjinchao01 已提交
2095 2096 2097
        super(SequenceAgentLayer, self).__init__(
            name, 'sequence_agent', size, inputs=[], device=device)

Q
qijun 已提交
2098

Z
zhangjinchao01 已提交
2099 2100
@config_layer('gather_agent')
class GatherAgentLayer(LayerBase):
Q
qijun 已提交
2101
    def __init__(self, name, size, device=None):
Z
zhangjinchao01 已提交
2102 2103 2104
        super(GatherAgentLayer, self).__init__(
            name, 'gather_agent', size, inputs=[], device=device)

Q
qijun 已提交
2105

Z
zhangjinchao01 已提交
2106 2107
@config_layer('scatter_agent')
class ScatterAgentLayer(LayerBase):
Q
qijun 已提交
2108
    def __init__(self, name, size, device=None):
Z
zhangjinchao01 已提交
2109 2110 2111
        super(ScatterAgentLayer, self).__init__(
            name, 'scatter_agent', size, inputs=[], device=device)

Q
qijun 已提交
2112

Z
zhangjinchao01 已提交
2113 2114
@config_layer('sequence_gather_agent')
class SequenceGatherAgentLayer(LayerBase):
Q
qijun 已提交
2115
    def __init__(self, name, size, device=None):
Z
zhangjinchao01 已提交
2116
        super(SequenceGatherAgentLayer, self).__init__(
Q
qijun 已提交
2117 2118
            name, 'sequence_gather_agent', size, inputs=[], device=device)

Z
zhangjinchao01 已提交
2119 2120 2121

@config_layer('sequence_scatter_agent')
class SequenceScatterAgentLayer(LayerBase):
Q
qijun 已提交
2122
    def __init__(self, name, size, device=None):
Z
zhangjinchao01 已提交
2123
        super(SequenceScatterAgentLayer, self).__init__(
Q
qijun 已提交
2124 2125
            name, 'sequence_scatter_agent', size, inputs=[], device=device)

Z
zhangjinchao01 已提交
2126 2127 2128

@config_layer('multiplex')
class MultiplexLayer(LayerBase):
Q
qijun 已提交
2129 2130 2131 2132 2133
    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 已提交
2134
        for i in range(1, len(inputs)):
Q
qijun 已提交
2135 2136 2137 2138 2139
            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 已提交
2140 2141

@config_func
Q
qijun 已提交
2142 2143 2144
def Link(
        name,
        has_subseq=False, ):
Z
zhangjinchao01 已提交
2145 2146 2147 2148 2149
    link_config = LinkConfig()
    link_config.link_name = name
    link_config.has_subseq = has_subseq
    return link_config

Q
qijun 已提交
2150

Z
zhangjinchao01 已提交
2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164
# memory for recurrent layer group.
# *name* and *size* are actual layer's name and size.
# will return name of the memory,
# 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
Q
qijun 已提交
2165 2166 2167 2168 2169 2170 2171 2172
def Memory(
        name,
        size,
        is_sequence=False,
        boot_layer=None,
        boot_bias=False,
        boot_bias_active_type="",
        boot_with_const_id=None, ):
Z
zhangjinchao01 已提交
2173 2174 2175 2176 2177 2178
    agent_name = name + "+delay1"
    if is_sequence:
        agent_layer = SequenceAgentLayer(agent_name, size)
    else:
        agent_layer = AgentLayer(agent_name, size)
    config_assert(g_current_submodel.is_recurrent_layer_group,
Q
qijun 已提交
2179
                  'Memory should be used in recurrent layer group only')
Z
zhangjinchao01 已提交
2180 2181 2182 2183
    memory = g_current_submodel.memories.add()
    memory.layer_name = MakeLayerNameInSubmodel(name)
    memory.link_name = MakeLayerNameInSubmodel(agent_name)
    memory.is_sequence = is_sequence
Q
qijun 已提交
2184
    options = sum((boot_layer is not None, bool(boot_bias),
Z
zhangjinchao01 已提交
2185
                   boot_with_const_id is not None))
Q
qijun 已提交
2186 2187 2188 2189
    config_assert(
        options <= 1,
        'take one option at most from boot_layer, boot_bias, or boot_with_const_id'
    )
Z
zhangjinchao01 已提交
2190 2191 2192
    if boot_layer is not None:
        boot_layer = MakeLayerNameInParentSubmodel(boot_layer)
        config_assert(boot_layer in g_layer_map,
Q
qijun 已提交
2193 2194
                      'boot_layer "%s" does not correspond to a layer name' %
                      boot_layer)
Z
zhangjinchao01 已提交
2195 2196 2197
        memory.boot_layer_name = boot_layer
    elif boot_bias:
        memory.boot_bias_parameter_name = agent_layer.create_bias_parameter(
Q
qijun 已提交
2198
            boot_bias, size, for_self=False)
Z
zhangjinchao01 已提交
2199 2200 2201 2202 2203
        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 已提交
2204

Z
zhangjinchao01 已提交
2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
# 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 已提交
2216 2217 2218 2219
        eos_layer_name="eos_check",
        num_results_per_sample=1,
        beam_size=1,
        log_prob=None, ):
Z
zhangjinchao01 已提交
2220 2221 2222 2223 2224 2225 2226 2227 2228
    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 已提交
2229

Z
zhangjinchao01 已提交
2230 2231
@config_layer('expand')
class ExpandLayer(LayerBase):
Q
qijun 已提交
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247
    def __init__(self,
                 name,
                 inputs,
                 trans_type='non-seq',
                 device=None,
                 bias=False):
        super(ExpandLayer, self).__init__(
            name, 'expand', 0, inputs=inputs, device=device)
        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 已提交
2248 2249 2250

@config_layer('featmap_expand')
class FeatMapExpandLayer(LayerBase):
Q
qijun 已提交
2251 2252 2253 2254 2255 2256
    def __init__(self, name, inputs, device=None, num_filters=None, bias=False):
        super(FeatMapExpandLayer, self).__init__(
            name, 'featmap_expand', 0, inputs=inputs, device=device)
        config_assert(
            len(self.inputs) == 1, 'ExpandLayer takes 1 and only 1 inputs')
        if num_filters is not None:
Z
zhangjinchao01 已提交
2257
            self.config.num_filters = num_filters
Q
qijun 已提交
2258
        else:
Z
zhangjinchao01 已提交
2259
            logger.fatal("FeatMapExpandLayer must specify num_filters.")
Q
qijun 已提交
2260
        self.set_layer_size(self.get_input_layer(0).size * num_filters)
Z
zhangjinchao01 已提交
2261 2262 2263 2264


@config_layer('max')
class MaxLayer(LayerBase):
Q
qijun 已提交
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
    def __init__(self,
                 name,
                 inputs,
                 trans_type='non-seq',
                 active_type='linear',
                 device=None,
                 bias=False,
                 output_max_index=None):
        super(MaxLayer, self).__init__(
            name, 'max', 0, inputs=inputs, device=device)
Z
zhangjinchao01 已提交
2275
        config_assert(len(self.inputs) == 1, 'MaxLayer must have 1 input')
Q
qijun 已提交
2276 2277
        self.config.trans_type = trans_type
        self.config.active_type = active_type
Z
zhangjinchao01 已提交
2278 2279 2280 2281
        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)
2282 2283
        if output_max_index is not None:
            self.config.output_max_index = output_max_index
Z
zhangjinchao01 已提交
2284 2285 2286 2287


@config_layer('maxid')
class MaxIdLayer(LayerBase):
Q
qijun 已提交
2288
    def __init__(self, name, inputs, beam_size=None, device=None):
Z
zhangjinchao01 已提交
2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305
        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 已提交
2306
    def __init__(self, name, inputs, eos_id, device=None):
Z
zhangjinchao01 已提交
2307 2308 2309
        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 已提交
2310
        self.set_layer_size(2)  # boolean output
Z
zhangjinchao01 已提交
2311 2312
        self.config.eos_id = eos_id

Q
qijun 已提交
2313

Z
zhangjinchao01 已提交
2314 2315
@config_layer('seqlastins')
class SequenceLastInstanceLayer(LayerBase):
Q
qijun 已提交
2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
    def __init__(self,
                 name,
                 inputs,
                 active_type='linear',
                 trans_type='non-seq',
                 device=None,
                 bias=False):
        super(SequenceLastInstanceLayer, self).__init__(
            name,
            'seqlastins',
            0,
            inputs=inputs,
            device=device,
            active_type=active_type)
        config_assert(
            len(inputs) == 1, 'SequenceLastInstanceLayer must have 1 input')
        self.config.trans_type = trans_type
Z
zhangjinchao01 已提交
2333 2334 2335 2336 2337
        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 已提交
2338

Z
zhangjinchao01 已提交
2339 2340 2341 2342 2343 2344 2345 2346 2347
@config_layer('seqfirstins')
class SequenceFirstInstanceLayer(SequenceLastInstanceLayer):
    def __init__(
            self,
            name,
            inputs,
            active_type='linear',
            trans_type='non-seq',
            device=None,
Q
qijun 已提交
2348 2349 2350 2351 2352 2353 2354 2355
            bias=False, ):
        super(SequenceFirstInstanceLayer, self).__init__(
            name,
            inputs=inputs,
            active_type=active_type,
            device=device,
            bias=bias)
        self.config.trans_type = trans_type
Z
zhangjinchao01 已提交
2356 2357
        self.config.select_first = True

Q
qijun 已提交
2358

Z
zhangjinchao01 已提交
2359 2360
@config_layer('seqconcat')
class SequenceConcatLayer(LayerBase):
Q
qijun 已提交
2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375
    def __init__(self,
                 name,
                 inputs,
                 active_type='linear',
                 device=None,
                 bias=False):
        super(SequenceConcatLayer, self).__init__(
            name,
            'seqconcat',
            0,
            inputs=inputs,
            device=device,
            active_type=active_type)
        config_assert(
            len(inputs) == 2, 'SequenceConcatLayer must have 2 inputs')
Z
zhangjinchao01 已提交
2376 2377 2378 2379 2380
        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 已提交
2381

Z
zhangjinchao01 已提交
2382 2383
@config_layer('seqreshape')
class SequenceReshapeLayer(LayerBase):
Q
qijun 已提交
2384 2385 2386 2387 2388 2389 2390 2391 2392 2393
    def __init__(self,
                 name,
                 size,
                 inputs,
                 active_type='linear',
                 device=None,
                 bias=False):
        super(SequenceReshapeLayer, self).__init__(
            name,
            'seqreshape',
Z
zhangjinchao01 已提交
2394
            size,
Q
qijun 已提交
2395 2396 2397 2398 2399
            inputs=inputs,
            device=device,
            active_type=active_type)
        config_assert(
            len(inputs) == 1, 'SequenceReshapeLayer must have 1 inputs')
Z
zhangjinchao01 已提交
2400 2401 2402
        self.set_layer_size(size)
        self.create_bias_parameter(bias, size)

Q
qijun 已提交
2403

Z
zhangjinchao01 已提交
2404 2405
@config_layer('subseq')
class SubSequenceLayer(LayerBase):
Q
qijun 已提交
2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418
    def __init__(self,
                 name,
                 inputs,
                 active_type='linear',
                 device=None,
                 bias=False):
        super(SubSequenceLayer, self).__init__(
            name,
            'subseq',
            0,
            inputs=inputs,
            device=device,
            active_type=active_type)
Z
zhangjinchao01 已提交
2419 2420 2421 2422 2423 2424
        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 已提交
2425

Z
zhangjinchao01 已提交
2426 2427
@config_layer('out_prod')
class OuterProdLayer(LayerBase):
Q
qijun 已提交
2428 2429 2430
    def __init__(self, name, inputs, device=None):
        super(OuterProdLayer, self).__init__(
            name, 'out_prod', 0, inputs=inputs, device=device)
Z
zhangjinchao01 已提交
2431 2432 2433 2434 2435
        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 已提交
2436

Z
zhangjinchao01 已提交
2437 2438
@config_layer('power')
class PowerLayer(LayerBase):
Q
qijun 已提交
2439 2440 2441
    def __init__(self, name, inputs, device=None):
        super(PowerLayer, self).__init__(
            name, 'power', 0, inputs=inputs, device=device)
Z
zhangjinchao01 已提交
2442 2443 2444 2445
        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 已提交
2446 2447 2448
        config_assert(1 == input_layer0.size,
                      'The left input is the exponent and should be of size 1')

Z
zhangjinchao01 已提交
2449 2450 2451

@config_layer('slope_intercept')
class SlopeInterceptLayer(LayerBase):
Q
qijun 已提交
2452 2453 2454
    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 已提交
2455 2456 2457 2458 2459 2460
        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 已提交
2461

Z
zhangjinchao01 已提交
2462 2463
@config_layer('scaling')
class ScalingLayer(LayerBase):
Q
qijun 已提交
2464 2465 2466
    def __init__(self, name, inputs, device=None):
        super(ScalingLayer, self).__init__(
            name, 'scaling', 0, inputs=inputs, device=device)
Z
zhangjinchao01 已提交
2467 2468 2469 2470
        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 已提交
2471 2472 2473
        config_assert(1 == input_layer0.size,
                      'The left input should be of size 1')

Z
zhangjinchao01 已提交
2474 2475 2476

@config_layer('conv_shift')
class ConvShiftLayer(LayerBase):
Q
qijun 已提交
2477 2478 2479
    def __init__(self, name, inputs, device=None):
        super(ConvShiftLayer, self).__init__(
            name, 'conv_shift', 0, inputs=inputs, device=device)
Z
zhangjinchao01 已提交
2480 2481 2482 2483
        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 已提交
2484

Z
zhangjinchao01 已提交
2485 2486
@config_layer('convex_comb')
class ConvexCombinationLayer(LayerBase):
Q
qijun 已提交
2487
    def __init__(self, name, size, inputs, device=None):
Z
zhangjinchao01 已提交
2488
        super(ConvexCombinationLayer, self).__init__(
Q
qijun 已提交
2489 2490 2491
            name, 'convex_comb', size, inputs=inputs, device=device)
        config_assert(
            len(self.inputs) == 2, 'ConvexCombinationLayer must have 2 inputs')
2492 2493 2494
        config_assert(
            size * self.get_input_layer(0).size == self.get_input_layer(1).size,
            'Wrong input size for ConvexCombinationLayer')
Z
zhangjinchao01 已提交
2495 2496
        self.set_layer_size(size)

Q
qijun 已提交
2497

Z
zhangjinchao01 已提交
2498 2499
@config_layer('interpolation')
class InterpolationLayer(LayerBase):
Q
qijun 已提交
2500
    def __init__(self, name, inputs, device=None):
Z
zhangjinchao01 已提交
2501 2502
        super(InterpolationLayer, self).__init__(
            name, 'interpolation', 0, inputs=inputs, device=device)
Q
qijun 已提交
2503 2504
        config_assert(
            len(self.inputs) == 3, 'InterpolationLayer must have 3 inputs')
Z
zhangjinchao01 已提交
2505 2506 2507 2508 2509 2510 2511 2512
        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 已提交
2513

L
liaogang 已提交
2514 2515
@config_layer('bilinear_interp')
class BilinearInterpLayer(LayerBase):
Q
qijun 已提交
2516
    def __init__(self, name, inputs, **xargs):
L
liaogang 已提交
2517
        super(BilinearInterpLayer, self).__init__(
L
liaogang 已提交
2518
            name, 'bilinear_interp', 0, inputs=inputs, **xargs)
L
liaogang 已提交
2519
        input_layer = self.get_input_layer(0)
Q
qijun 已提交
2520 2521
        parse_bilinear(self.inputs[0].bilinear_interp, input_layer.name,
                       self.config.inputs[0].bilinear_interp_conf)
L
liaogang 已提交
2522
        conf = self.inputs[0].bilinear_interp
Q
qijun 已提交
2523 2524 2525
        self.set_layer_size(conf.out_size_x * conf.out_size_y *
                            conf.num_channels)

L
liaogang 已提交
2526

Z
zhangjinchao01 已提交
2527 2528
@config_layer('sum_to_one_norm')
class SumToOneNormLayer(LayerBase):
Q
qijun 已提交
2529
    def __init__(self, name, inputs, device=None):
Z
zhangjinchao01 已提交
2530
        super(SumToOneNormLayer, self).__init__(
Q
qijun 已提交
2531 2532 2533
            name, 'sum_to_one_norm', 0, inputs=inputs, device=device)
        config_assert(
            len(self.inputs) == 1, 'SumToOneNormLayer must have 1 input')
Z
zhangjinchao01 已提交
2534 2535 2536
        input_layer0 = self.get_input_layer(0)
        self.set_layer_size(input_layer0.size)

Q
qijun 已提交
2537

Z
zhangjinchao01 已提交
2538 2539
@config_layer('cos_vm')
class CosSimVecMatLayer(LayerBase):
Q
qijun 已提交
2540
    def __init__(self, name, size, inputs, cos_scale=1.0, device=None):
Z
zhangjinchao01 已提交
2541
        super(CosSimVecMatLayer, self).__init__(
Q
qijun 已提交
2542
            name, 'cos_vm', size, inputs=inputs, device=device)
Z
zhangjinchao01 已提交
2543
        self.config.cos_scale = cos_scale
Q
qijun 已提交
2544 2545
        config_assert(
            len(self.inputs) == 2, 'CosSimVecMatLayer must have 2 inputs')
2546 2547 2548
        config_assert(
            size * self.get_input_layer(0).size == self.get_input_layer(1).size,
            'Wrong input size for CosSimVecMatLayer')
Z
zhangjinchao01 已提交
2549

Q
qijun 已提交
2550

Z
zhangjinchao01 已提交
2551 2552
@config_layer('sampling_id')
class SamplingIdLayer(LayerBase):
Q
qijun 已提交
2553
    def __init__(self, name, inputs, device=None):
Z
zhangjinchao01 已提交
2554 2555
        super(SamplingIdLayer, self).__init__(
            name, 'sampling_id', 0, inputs=inputs, device=device)
Q
qijun 已提交
2556 2557
        config_assert(
            len(self.inputs) == 1, 'SamplingIdLayer must have 1 input')
Z
zhangjinchao01 已提交
2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569
        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 已提交
2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584
    def __init__(self,
                 name,
                 inputs,
                 average_strategy='average',
                 trans_type='non-seq',
                 active_type='linear',
                 device=None,
                 bias=False):
        super(AverageLayer, self).__init__(
            name,
            'average',
            0,
            inputs=inputs,
            device=device,
            active_type=active_type)
Z
zhangjinchao01 已提交
2585
        self.config.average_strategy = average_strategy
Q
qijun 已提交
2586
        self.config.trans_type = trans_type
Z
zhangjinchao01 已提交
2587 2588 2589 2590 2591 2592
        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 已提交
2593

Z
zhangjinchao01 已提交
2594 2595
@config_layer('cos')
class CosSimLayer(LayerBase):
Q
qijun 已提交
2596
    def __init__(self, name, inputs, cos_scale=5, device=None):
Z
zhangjinchao01 已提交
2597 2598 2599 2600 2601 2602
        super(CosSimLayer, self).__init__(
            name, 'cos', 1, inputs=inputs, device=device)
        config_assert(len(self.inputs) == 2, 'CosSimLayer must have 2 inputs')
        config_assert(
            self.get_input_layer(0).size == self.get_input_layer(1).size,
            'inputs of CosSimLayer must have same dim')
2603
        self.config.cos_scale = cos_scale
Z
zhangjinchao01 已提交
2604 2605 2606 2607


@config_layer('tensor')
class TensorLayer(LayerBase):
Q
qijun 已提交
2608 2609 2610
    def __init__(self, name, size, inputs, device=None, bias=True, **xargs):
        super(TensorLayer, self).__init__(
            name, 'tensor', size, inputs=inputs, device=device, **xargs)
Z
zhangjinchao01 已提交
2611 2612
        config_assert(len(self.inputs) == 2, 'TensorLayer must have 2 inputs')
        config_assert(size > 0, 'size must be positive')
Q
qijun 已提交
2613 2614
        config_assert(inputs[1].parameter_name == None,
                      'second parameter should be None.')
Z
zhangjinchao01 已提交
2615 2616 2617 2618 2619 2620 2621 2622 2623 2624
        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):
Q
qijun 已提交
2625 2626 2627 2628 2629 2630 2631
    def __init__(self,
                 name,
                 inputs,
                 size=0,
                 bias=True,
                 error_clipping_threshold=None,
                 **xargs):
Z
zhangjinchao01 已提交
2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648
        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)
2649
            if self.config.size == 0:
Z
zhangjinchao01 已提交
2650 2651 2652
                size = operator.calc_output_size(operator_conf.input_sizes)
                if size != 0:
                    self.set_layer_size(size)
2653
            else:
2654 2655
                sz = operator.calc_output_size(operator_conf.input_sizes)
                if sz != 0:
Q
qijun 已提交
2656 2657 2658 2659
                    config_assert(
                        sz == self.config.size,
                        "different inputs have different size: %s vs. %s" %
                        (sz, self.config.size))
Z
zhangjinchao01 已提交
2660 2661 2662 2663
        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 已提交
2664 2665 2666
                config_assert(
                    isinstance(input, Projection),
                    "input should be projection or operation")
2667
            if self.config.size == 0 and isinstance(input, Projection):
Z
zhangjinchao01 已提交
2668 2669 2670
                size = input.calc_output_size(input_layer)
                if size != 0:
                    self.set_layer_size(size)
2671
            elif isinstance(input, Projection):
Q
qijun 已提交
2672 2673 2674 2675 2676 2677
                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 已提交
2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
        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 已提交
2689 2690
                input_config.proj_conf.name = gen_parameter_name(name,
                                                                 input_index)
Z
zhangjinchao01 已提交
2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701
                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)

2702 2703 2704 2705 2706 2707
        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 已提交
2708

2709 2710 2711
        if bias:
            self.config.bias_size = psize
            self.create_bias_parameter(bias, psize)
Z
zhangjinchao01 已提交
2712

2713 2714
        if error_clipping_threshold is not None:
            self.config.error_clipping_threshold = error_clipping_threshold
Z
zhangjinchao01 已提交
2715

Q
qijun 已提交
2716

Z
zhangjinchao01 已提交
2717 2718
# like MixedLayer, but no bias parameter
@config_func
Q
qijun 已提交
2719
def ExpressionLayer(name, inputs, **xargs):
Z
zhangjinchao01 已提交
2720 2721
    MixedLayer(name, inputs, bias=False, **xargs)

Q
qijun 已提交
2722

Z
zhangjinchao01 已提交
2723 2724
@config_layer('concat')
class ConcatenateLayer(LayerBase):
Q
qijun 已提交
2725
    def __init__(self, name, inputs, bias=False, **xargs):
Z
zhangjinchao01 已提交
2726
        config_assert(inputs, 'inputs cannot be empty')
2727
        config_assert(not bias, 'ConcatenateLayer cannot support bias.')
Z
zhangjinchao01 已提交
2728 2729 2730 2731 2732 2733
        super(ConcatenateLayer, self).__init__(
            name, 'concat', 0, inputs=inputs, **xargs)
        size = 0
        for input_index in xrange(len(self.inputs)):
            input_layer = self.get_input_layer(input_index)
            input = self.inputs[input_index]
Q
qijun 已提交
2734
            if self.config.size == 0:
Z
zhangjinchao01 已提交
2735 2736 2737 2738
                size += input_layer.size

        self.set_layer_size(size)

Q
qijun 已提交
2739

Z
zhangjinchao01 已提交
2740 2741 2742
# like concat layer, but each input layer was processed by a Projection.
@config_layer('concat2')
class ConcatenateLayer2(LayerBase):
Q
qijun 已提交
2743
    def __init__(self, name, inputs, bias=False, **xargs):
Z
zhangjinchao01 已提交
2744 2745 2746
        config_assert(inputs, 'inputs cannot be empty')
        super(ConcatenateLayer2, self).__init__(
            name, 'concat2', 0, inputs=inputs, **xargs)
2747 2748

        if isinstance(self.inputs[0], ConvProjection):
Q
qijun 已提交
2749 2750 2751 2752 2753 2754
            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.")
2755

Z
zhangjinchao01 已提交
2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775
        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 已提交
2776
                                              input.proj_conf.output_size)
Z
zhangjinchao01 已提交
2777
            dims = input.calc_parameter_dims(input.proj_conf.input_size,
Q
qijun 已提交
2778
                                             input.proj_conf.output_size)
Z
zhangjinchao01 已提交
2779 2780
            self.create_input_parameter(input_index, psize, dims)

2781 2782 2783 2784 2785 2786 2787
        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()

2788 2789 2790
        if bias:
            self.config.bias_size = psize
            self.create_bias_parameter(bias, psize)
2791

Q
qijun 已提交
2792

Z
zhangjinchao01 已提交
2793 2794
@config_layer('recurrent')
class RecurrentLayer(LayerBase):
Q
qijun 已提交
2795
    def __init__(self, name, inputs, reversed=False, bias=True, **xargs):
Y
Yu Yang 已提交
2796 2797
        super(RecurrentLayer, self).__init__(name, 'recurrent', 0, inputs,
                                             **xargs)
Z
zhangjinchao01 已提交
2798 2799 2800 2801 2802 2803 2804 2805 2806
        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 已提交
2807

Z
zhangjinchao01 已提交
2808 2809
@config_layer('lstmemory')
class LstmLayer(LayerBase):
Q
qijun 已提交
2810 2811 2812 2813 2814 2815 2816 2817
    def __init__(self,
                 name,
                 inputs,
                 reversed=False,
                 active_gate_type="sigmoid",
                 active_state_type="sigmoid",
                 bias=True,
                 **xargs):
Z
zhangjinchao01 已提交
2818 2819 2820 2821 2822 2823 2824 2825
        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 已提交
2826
        self.config.active_gate_type = active_gate_type
Z
zhangjinchao01 已提交
2827 2828 2829 2830 2831
        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 已提交
2832

Z
zhangjinchao01 已提交
2833 2834
@config_layer('lstm_step')
class LstmStepLayer(LayerBase):
Q
qijun 已提交
2835 2836 2837 2838 2839 2840 2841 2842 2843 2844
    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 已提交
2845 2846 2847
        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 已提交
2848 2849 2850 2851 2852
        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 已提交
2853 2854 2855
        self.config.active_state_type = active_state_type
        self.create_bias_parameter(bias, size * 3)

Q
qijun 已提交
2856

Z
zhangjinchao01 已提交
2857 2858 2859
# get the specific output from the input layer.
@config_layer('get_output')
class GetOutputLayer(LayerBase):
Q
qijun 已提交
2860 2861 2862 2863
    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 已提交
2864 2865 2866 2867
        inputs = self.inputs[0]
        config_assert(inputs.input_layer_argument,
                      'input_layer_argument cannot be empty')

Q
qijun 已提交
2868

Z
zhangjinchao01 已提交
2869 2870
@config_layer('mdlstmemory')
class MDLstmLayer(LayerBase):
Q
qijun 已提交
2871 2872 2873 2874 2875 2876 2877 2878
    def __init__(self,
                 name,
                 inputs,
                 directions=True,
                 active_gate_type="sigmoid",
                 active_state_type="sigmoid",
                 bias=True,
                 **xargs):
Y
Yu Yang 已提交
2879 2880
        super(MDLstmLayer, self).__init__(name, 'mdlstmemory', 0, inputs,
                                          **xargs)
Z
zhangjinchao01 已提交
2881 2882 2883 2884
        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 已提交
2885 2886
        config_assert(input_layer.size % (3 + dim_num) == 0,
                      "size % (dim_num) should be 0!")
Q
qijun 已提交
2887
        size = input_layer.size / (3 + dim_num)
Z
zhangjinchao01 已提交
2888
        self.set_layer_size(size)
Q
qijun 已提交
2889
        self.config.active_gate_type = active_gate_type
Z
zhangjinchao01 已提交
2890 2891 2892
        self.config.active_state_type = active_state_type
        for i in xrange(len(directions)):
            self.config.directions.append(int(directions[i]))
Y
Yu Yang 已提交
2893 2894
        self.create_input_parameter(0, size * size * (3 + dim_num),
                                    [size, size, 3 + dim_num])
Z
zhangjinchao01 已提交
2895
        #bias includes 3 kinds of peephole, 3+dim_num+2+dim_num
Q
qijun 已提交
2896 2897
        self.create_bias_parameter(bias, size * (5 + 2 * dim_num))

Z
zhangjinchao01 已提交
2898 2899 2900

@config_layer('gated_recurrent')
class GatedRecurrentLayer(LayerBase):
Q
qijun 已提交
2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911
    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 已提交
2912 2913 2914 2915 2916 2917
        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 已提交
2918
        self.config.active_gate_type = active_gate_type
Z
zhangjinchao01 已提交
2919 2920 2921
        self.create_input_parameter(0, size * size * 3, [size, size * 3])
        self.create_bias_parameter(bias, size * 3)

Q
qijun 已提交
2922

Z
zhangjinchao01 已提交
2923 2924
@config_layer('gru_step')
class GruStepLayer(LayerBase):
Q
qijun 已提交
2925 2926 2927 2928 2929 2930 2931
    def __init__(self,
                 name,
                 size,
                 inputs,
                 active_gate_type="sigmoid",
                 bias=True,
                 **xargs):
Y
Yu Yang 已提交
2932 2933
        super(GruStepLayer, self).__init__(name, 'gru_step', size, inputs,
                                           **xargs)
Z
zhangjinchao01 已提交
2934 2935 2936
        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 已提交
2937 2938 2939 2940 2941
        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
Z
zhangjinchao01 已提交
2942 2943 2944
        self.create_input_parameter(0, size * size * 3, [size, size * 3])
        self.create_bias_parameter(bias, size * 3)

Q
qijun 已提交
2945

Z
zhangjinchao01 已提交
2946 2947 2948 2949 2950 2951 2952
'''
 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 已提交
2953 2954


Z
zhangjinchao01 已提交
2955 2956
@config_layer('crf')
class CRFLayer(LayerBase):
Q
qijun 已提交
2957
    def __init__(self, name, size, inputs, coeff=1.0, device=None):
Z
zhangjinchao01 已提交
2958
        super(CRFLayer, self).__init__(name, 'crf', size, inputs, device=device)
Q
qijun 已提交
2959 2960
        config_assert(2 <= len(self.inputs) <= 3,
                      'CRFLayer must have 2 or 3 inputs')
Z
zhangjinchao01 已提交
2961 2962 2963
        self.create_input_parameter(0, size * (size + 2), [size, size + 2])
        self.config.coeff = coeff

Q
qijun 已提交
2964

Z
zhangjinchao01 已提交
2965 2966 2967 2968 2969 2970 2971 2972
'''
 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 已提交
2973 2974


Z
zhangjinchao01 已提交
2975 2976
@config_layer('crf_decoding')
class CRFDecodingLayer(LayerBase):
Q
qijun 已提交
2977
    def __init__(self, name, size, inputs, device=None):
Z
zhangjinchao01 已提交
2978 2979 2980 2981 2982 2983 2984
        super(CRFDecodingLayer, self).__init__(
            name, 'crf_decoding', size, inputs, device=device)
        config_assert(
            len(self.inputs) <= 2,
            'CRFDecodingLayer cannot have more than 2 inputs')
        self.create_input_parameter(0, size * (size + 2), [size, size + 2])

Q
qijun 已提交
2985

Z
zhangjinchao01 已提交
2986 2987
@config_layer('ctc')
class CTCLayer(LayerBase):
Q
qijun 已提交
2988
    def __init__(self, name, size, inputs, norm_by_times=False, device=None):
Z
zhangjinchao01 已提交
2989 2990 2991 2992
        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 已提交
2993

Z
zhangjinchao01 已提交
2994 2995
@config_layer('recurrent_layer_group')
class RecurrentLayerGroup(LayerBase):
Q
qijun 已提交
2996
    def __init__(self, name, device=None):
Z
zhangjinchao01 已提交
2997 2998 2999 3000 3001 3002
        super(RecurrentLayerGroup, self).__init__(
            name, 'recurrent_layer_group', 0, inputs=[], device=device)


# Deprecated, use a new layer specific class instead
@config_func
Q
qijun 已提交
3003
def Layer(name, type, **xargs):
Z
zhangjinchao01 已提交
3004 3005 3006 3007
    layers = {}
    layers.update(g_cost_map)
    layers.update(g_layer_type_map)
    layer_func = layers.get(type)
Q
qijun 已提交
3008
    config_assert(layer_func, "layer type '%s' not supported." % type)
X
xuwei06 已提交
3009
    return layer_func(name, **xargs)
Z
zhangjinchao01 已提交
3010

Q
qijun 已提交
3011

Z
zhangjinchao01 已提交
3012
@config_func
Q
qijun 已提交
3013
def ParameterHook(type, **kwargs):
Z
zhangjinchao01 已提交
3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025
    if type == 'pruning':
        mask_filename = kwargs.get('mask_filename', None)
        assert mask_filename is not None
        hook = ParameterUpdaterHookConfig()
        hook.type = type
        hook.purning_mask_filename = mask_filename
        return hook
    else:
        return None


@config_func
Q
qijun 已提交
3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047
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,
              update_hooks=None):
Z
zhangjinchao01 已提交
3048 3049 3050 3051 3052 3053 3054

    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
3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065
    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 已提交
3066 3067
    config_assert(not momentum or not decay_rate_l1,
                  "momentum and decay_rate_l1 cannot both be non-zero")
3068 3069 3070 3071 3072

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

Z
zhangjinchao01 已提交
3073 3074 3075 3076
    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)
3077

Q
qijun 已提交
3078 3079
    num_batches_regularization = default(num_batches_regularization,
                                         g_default_num_batches_regularization)
3080 3081 3082
    if num_batches_regularization is not None:
        para.num_batches_regularization = int(num_batches_regularization)

Z
zhangjinchao01 已提交
3083 3084 3085 3086 3087 3088
    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 已提交
3089 3090
    gradient_clipping_threshold = default(gradient_clipping_threshold,
                                          g_default_gradient_clipping_threshold)
3091 3092
    if gradient_clipping_threshold is not None:
        para.gradient_clipping_threshold = gradient_clipping_threshold
Q
qijun 已提交
3093 3094
    para.initial_strategy = default(initial_strategy,
                                    g_default_initial_strategy)
Z
zhangjinchao01 已提交
3095 3096 3097 3098 3099 3100
    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 已提交
3101 3102 3103
            print(
                "Use initial_smart, but dims not set. Initial_smart may not be used in this layer"
            )
Z
zhangjinchao01 已提交
3104 3105 3106 3107
            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)
3108 3109 3110 3111 3112 3113 3114

    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 已提交
3115 3116 3117 3118
    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")
3119 3120
    if is_shared is not None:
        para.is_shared = is_shared
Z
zhangjinchao01 已提交
3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141

    update_hooks = default(update_hooks, g_default_update_hooks)

    if update_hooks is not None:
        if hasattr(update_hooks, '__call__'):
            update_hooks = update_hooks(para.name)

        if isinstance(update_hooks, list):
            for hook in update_hooks:
                para.update_hooks.extend([hook])
        else:
            para.update_hooks.extend(update_hooks)

    g_parameter_map[name] = para


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

Q
qijun 已提交
3142

Z
zhangjinchao01 已提交
3143 3144 3145 3146 3147
@config_func
def default_initial_mean(val):
    global g_default_initial_mean
    g_default_initial_mean = val

Q
qijun 已提交
3148

Z
zhangjinchao01 已提交
3149 3150 3151 3152 3153
@config_func
def default_initial_strategy(val):
    global g_default_initial_strategy
    g_default_initial_strategy = val

Q
qijun 已提交
3154

Z
zhangjinchao01 已提交
3155 3156 3157 3158 3159
@config_func
def default_initial_smart(val):
    global g_default_initial_smart
    g_default_initial_smart = val

Q
qijun 已提交
3160

Z
zhangjinchao01 已提交
3161 3162 3163 3164 3165
@config_func
def default_momentum(val):
    global g_default_momentum
    g_default_momentum = val

Q
qijun 已提交
3166

Z
zhangjinchao01 已提交
3167 3168 3169 3170 3171
@config_func
def default_decay_rate(val):
    global g_default_decay_rate
    g_default_decay_rate = val

Q
qijun 已提交
3172

Z
zhangjinchao01 已提交
3173 3174 3175 3176 3177
@config_func
def default_num_batches_regularization(val):
    global g_default_num_batches_regularization
    g_default_num_batches_regularization = val

Q
qijun 已提交
3178

Z
zhangjinchao01 已提交
3179 3180 3181 3182 3183
@config_func
def default_gradient_clipping_threshold(val):
    global g_default_gradient_clipping_threshold
    g_default_gradient_clipping_threshold = val

Q
qijun 已提交
3184

Z
zhangjinchao01 已提交
3185 3186 3187 3188 3189
@config_func
def default_device(val):
    global g_default_device
    g_default_device = val

Q
qijun 已提交
3190

Z
zhangjinchao01 已提交
3191 3192 3193 3194 3195
@config_func
def default_update_hooks(val):
    global g_default_update_hooks
    g_default_update_hooks = val

Q
qijun 已提交
3196

Z
zhangjinchao01 已提交
3197 3198 3199 3200 3201
@config_func
def default_compact_func(val):
    global g_default_compact_func
    g_default_compact_func = val

Q
qijun 已提交
3202

Z
zhangjinchao01 已提交
3203 3204 3205 3206 3207
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 已提交
3208 3209 3210
        execfile(config_file,
                 make_config_environment(config_file, config_args), local_args)

Z
zhangjinchao01 已提交
3211 3212
    return Import

Q
qijun 已提交
3213

Z
zhangjinchao01 已提交
3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241
settings = dict(
    batch_size=None,
    mini_batch_size=None,
    algorithm='async_sgd',
    async_lagged_grad_discard_ratio=1.5,
    learning_method='momentum',
    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 已提交
3242 3243 3244
    adam_beta1=0.9,
    adam_beta2=0.999,
    adam_epsilon=1e-8, )
Z
zhangjinchao01 已提交
3245

Q
qijun 已提交
3246
settings_deprecated = dict(usage_ratio=1., )
Z
zhangjinchao01 已提交
3247 3248 3249 3250

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

Z
zhangjinchao01 已提交
3253 3254 3255 3256 3257

@config_func
def Settings(**args):
    for k, v in args.iteritems():
        if k == "usage_ratio":
Q
qijun 已提交
3258 3259
            logger.warning(
                "Deprecated: define usage_ratio in DataConfig instead")
Z
zhangjinchao01 已提交
3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270
            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 已提交
3271

Z
zhangjinchao01 已提交
3272 3273 3274 3275
@config_func
def cluster_config(**args):
    pass

Q
qijun 已提交
3276

Z
zhangjinchao01 已提交
3277 3278 3279 3280 3281 3282 3283 3284 3285
@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 已提交
3286

Z
zhangjinchao01 已提交
3287 3288 3289 3290
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 已提交
3291

Z
zhangjinchao01 已提交
3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306
        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 已提交
3307
        get_config_arg=make_get_config_arg(config_args), )
Z
zhangjinchao01 已提交
3308 3309 3310 3311 3312

    funcs.update(g_extended_config_funcs)

    return funcs

Q
qijun 已提交
3313

Z
zhangjinchao01 已提交
3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329
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 已提交
3330

Z
zhangjinchao01 已提交
3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342
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 已提交
3343

Z
zhangjinchao01 已提交
3344 3345 3346 3347
def my_fatal(s):
    logger.critical(s)
    raise Exception()

Q
qijun 已提交
3348

Z
zhangjinchao01 已提交
3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385
def parse_config(config_file, config_arg_str):
    '''
    @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
    '''
    init_config_environment()

    config_args = {}

    logger.findCaller = find_caller
    logger.fatal = my_fatal

    g_config.model_config.type = "nn"
    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)

    g_config.model_config.type = 'nn'

    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

    execfile(config_file, make_config_environment(config_file, config_args))
    for k, v in settings.iteritems():
        if v is None:
            continue
Q
qijun 已提交
3386
        g_config.opt_config.__setattr__(k, v)
Z
zhangjinchao01 已提交
3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412

    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


def parse_config_and_serialize(config_file, config_arg_str):
    try:
        config = parse_config(config_file, config_arg_str)
        #logger.info(config)
        return config.SerializeToString()
    except:
        traceback.print_exc()
        raise

Q
qijun 已提交
3413

Z
zhangjinchao01 已提交
3414 3415 3416 3417 3418 3419 3420 3421
if __name__ == '__main__':
    try:
        config = parse_config(sys.argv[1], '')
        config.SerializeToString()
        __real_print__(str(config))
    except:
        traceback.print_exc()
        raise