| 1 | # Licensed to the Apache Software Foundation (ASF) under one | ||
| 2 | # or more contributor license agreements. See the NOTICE file | ||
| 3 | # distributed with this work for additional information | ||
| 4 | # regarding copyright ownership. The ASF licenses this file | ||
| 5 | # to you under the Apache License, Version 2.0 (the | ||
| 6 | # "License"); you may not use this file except in compliance | ||
| 7 | # with the License. You may obtain a copy of the License at | ||
| 8 | # | ||
| 9 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
| 10 | # | ||
| 11 | # Unless required by applicable law or agreed to in writing, | ||
| 12 | # software distributed under the License is distributed on an | ||
| 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| 14 | # KIND, either express or implied. See the License for the | ||
| 15 | # specific language governing permissions and limitations | ||
| 16 | # under the License. | ||
| 17 | |||
| 18 | package AI::MXNet::InitDesc; | ||
| 19 | use Mouse; | ||
| 20 | use AI::MXNet::Function::Parameters; | ||
| 21 | |||
| 22 | =head1 NAME | ||
| 23 | |||
| 24 | AI::MXNet::InitDesc - A container for the initialization pattern serialization. | ||
| 25 | |||
| 26 | =head2 new | ||
| 27 | |||
| 28 | Parameters | ||
| 29 | --------- | ||
| 30 | name : str | ||
| 31 | name of variable | ||
| 32 | attrs : hash ref of str to str | ||
| 33 | attributes of this variable taken from AI::MXNet::Symbol->attr_dict | ||
| 34 | =cut | ||
| 35 | has 'name' => (is => 'ro', isa => 'Str', required => 1); | ||
| 36 | has 'attrs' => (is => 'rw', isa => 'HashRef[Str]', lazy => 1, default => sub { +{} }); | ||
| 37 | use overload '""' => sub { shift->name }; | ||
| 38 | around BUILDARGS => sub { | ||
| 39 | my $orig = shift; | ||
| 40 | my $class = shift; | ||
| 41 | return $class->$orig(name => $_[0]) if @_ == 1; | ||
| 42 | return $class->$orig(@_); | ||
| 43 | }; | ||
| 44 | |||
| 45 | # Base class for Initializers | ||
| 46 | package AI::MXNet::Initializer; | ||
| 47 | use Mouse; | ||
| 48 | use AI::MXNet::NS; | ||
| 49 | use AI::MXNet::Base qw(:DEFAULT pzeros pceil); | ||
| 50 | use AI::MXNet::NDArray; | ||
| 51 | use JSON::PP; | ||
| 52 | use overload "&{}" => sub { my $self = shift; sub { $self->call(@_) } }, | ||
| 53 | '""' => sub { | ||
| 54 | my $self = shift; | ||
| 55 | my ($name) = ref($self) =~ /::(\w+)$/; | ||
| 56 | encode_json( | ||
| 57 | [lc $name, | ||
| 58 | $self->kwargs//{ map { $_ => "".$self->$_ } $self->meta->get_attribute_list } | ||
| 59 | ]); | ||
| 60 | }, | ||
| 61 | fallback => 1; | ||
| 62 | has 'kwargs' => (is => 'rw', init_arg => undef, isa => 'HashRef'); | ||
| 63 | has '_verbose' => (is => 'rw', isa => 'Bool', lazy => 1, default => 0); | ||
| 64 | has '_print_func' => (is => 'rw', isa => 'CodeRef', lazy => 1, | ||
| 65 | default => sub { | ||
| 66 | return sub { | ||
| 67 | my $x = shift; | ||
| 68 | return ($x->norm/sqrt($x->size))->asscalar; | ||
| 69 | }; | ||
| 70 | } | ||
| 71 | ); | ||
| 72 | |||
| 73 | =head1 NAME | ||
| 74 | |||
| 75 | AI::MXNet::Initializer - Base class for all Initializers | ||
| 76 | |||
| 77 | =head1 DESCRIPTION | ||
| 78 | |||
| 79 | The base class AI::MXNet::Initializer defines the default behaviors to initialize various parameters, | ||
| 80 | such as set bias to 1, except for the weight. Other classes then define how to initialize the weights. | ||
| 81 | Currently following classes are available: | ||
| 82 | mx->init->Uniform Initializes weights with random values uniformly sampled from a given range. | ||
| 83 | mx->init->Normal Initializes weights with random values sampled from a normal distribution with a mean of zero and standard deviation of sigma. | ||
| 84 | mx->init->Load Initializes variables by loading data from file or dict. | ||
| 85 | mx->init->Mixed Initialize parameters using multiple initializers. | ||
| 86 | mx->init->Zero Initializes weights to zero. | ||
| 87 | mx->init->One Initializes weights to one. | ||
| 88 | mx->init->Constant Initializes the weights to a given value. | ||
| 89 | mx->init->Orthogonal Initialize weight as orthogonal matrix. | ||
| 90 | mx->init->Xavier Returns an initializer performing Xavier initialization for weights. | ||
| 91 | mx->init->MSRAPrelu Initialize the weight according to a MSRA paper. | ||
| 92 | mx->init->Bilinear Initialize weight for upsampling layers. | ||
| 93 | mx->init->FusedRNN Initialize parameters for fused rnn layers. | ||
| 94 | |||
| 95 | =head2 register | ||
| 96 | |||
| 97 | Register an initializer class to the AI::MXNet::Initializer factory. | ||
| 98 | =cut | ||
| 99 | |||
| 100 | =head2 set_verbosity | ||
| 101 | |||
| 102 | Switch on/off verbose mode | ||
| 103 | |||
| 104 | Parameters | ||
| 105 | ---------- | ||
| 106 | $verbose : bool | ||
| 107 | switch on/off verbose mode | ||
| 108 | $print_func : CodeRef | ||
| 109 | A function that computes statistics of initialized arrays. | ||
| 110 | Takes an AI::MXNet::NDArray and returns a scalar. Defaults to mean | ||
| 111 | absolute value |x|/size(x) | ||
| 112 | =cut | ||
| 113 | |||
| 114 | method set_verbosity(Bool $verbose=0, CodeRef $print_func=) | ||
| 115 | { | ||
| 116 | $self->_verbose($verbose); | ||
| 117 | $self->_print_func($print_func) if defined $print_func; | ||
| 118 | } | ||
| 119 | |||
| 120 | method _verbose_print($desc, $init, $arr) | ||
| 121 | { | ||
| 122 | if($self->_verbose and defined $self->_print_func) | ||
| 123 | { | ||
| 124 | AI::MXNet::Logging->info('Initialized %s as %s: %s', $desc, $init, $self->_print_func->($arr)); | ||
| 125 | } | ||
| 126 | } | ||
| 127 | |||
| 128 | my %init_registry; | ||
| 129 | method get_init_registry() | ||
| 130 | { | ||
| 131 | return \%init_registry; | ||
| 132 | } | ||
| 133 | |||
| 134 | method register() | ||
| 135 | { | ||
| 136 | my ($name) = $self =~ /::(\w+)$/; | ||
| 137 | my $orig_name = $name; | ||
| 138 | $name = lc $name; | ||
| 139 | if(exists $init_registry{ $name }) | ||
| 140 | { | ||
| 141 | my $existing = $init_registry{ $name }; | ||
| 142 | warn( | ||
| 143 | "WARNING: New initializer $self.$name" | ||
| 144 | ."is overriding existing initializer $existing.$name" | ||
| 145 | ); | ||
| 146 | } | ||
| 147 | $init_registry{ $name } = $self; | ||
| 148 | { | ||
| 149 | no strict 'refs'; | ||
| 150 | no warnings 'redefine'; | ||
| 151 | *{"$orig_name"} = sub { shift; $self->new(@_) }; | ||
| 152 | *InitDesc = sub { shift; AI::MXNet::InitDesc->new(@_) }; | ||
| 153 | } | ||
| 154 | } | ||
| 155 | |||
| 156 | =head2 init | ||
| 157 | |||
| 158 | Parameters | ||
| 159 | ---------- | ||
| 160 | $desc : AI::MXNet::InitDesc|str | ||
| 161 | a name of corresponding ndarray | ||
| 162 | or the object that describes the initializer. | ||
| 163 | |||
| 164 | $arr : AI::MXNet::NDArray | ||
| 165 | an ndarray to be initialized. | ||
| 166 | =cut | ||
| 167 | method call(Str|AI::MXNet::InitDesc $desc, AI::MXNet::NDArray $arr) | ||
| 168 | { | ||
| 169 | return $self->_legacy_init($desc, $arr) unless blessed $desc; | ||
| 170 | my $init = $desc->attrs->{ __init__ }; | ||
| 171 | if($init) | ||
| 172 | { | ||
| 173 | my ($klass, $kwargs); | ||
| 174 | if(exists $self->get_init_registry->{ lc $init }) | ||
| 175 | { | ||
| 176 | $klass = $init; | ||
| 177 | $kwargs = {}; | ||
| 178 | } | ||
| 179 | else | ||
| 180 | { | ||
| 181 | ($klass, $kwargs) = @{ decode_json($init) }; | ||
| 182 | } | ||
| 183 | $self->get_init_registry->{ lc $klass }->new(%{ $kwargs })->_init_weight("$desc", $arr); | ||
| 184 | $self->_verbose_print($desc, $init, $arr); | ||
| 185 | } | ||
| 186 | else | ||
| 187 | { | ||
| 188 | $desc = "$desc"; | ||
| 189 | if($desc =~ /(weight|bias|gamma|beta)$/) | ||
| 190 | { | ||
| 191 | my $method = "_init_$1"; | ||
| 192 | $self->$method($desc, $arr); | ||
| 193 | $self->_verbose_print($desc, $1, $arr); | ||
| 194 | } | ||
| 195 | elsif($desc =~ /min$/) | ||
| 196 | { | ||
| 197 | $self->_init_zero($desc, $arr); | ||
| 198 | $self->_verbose_print($desc, 'min', $arr); | ||
| 199 | } | ||
| 200 | elsif($desc =~ /max$/) | ||
| 201 | { | ||
| 202 | $self->_init_one($desc, $arr); | ||
| 203 | $self->_verbose_print($desc, 'max', $arr); | ||
| 204 | } | ||
| 205 | else | ||
| 206 | { | ||
| 207 | $self->_init_default($desc, $arr) | ||
| 208 | } | ||
| 209 | } | ||
| 210 | } | ||
| 211 | |||
| 212 | |||
| 213 | method _legacy_init(Str $name, AI::MXNet::NDArray $arr) | ||
| 214 | { | ||
| 215 | warnings::warnif( | ||
| 216 | 'deprecated', | ||
| 217 | 'Calling initializer with init($str, $NDArray) has been deprecated.'. | ||
| 218 | 'please use init(mx->init->InitDesc(...), NDArray) instead.' | ||
| 219 | ); | ||
| 220 | if($name =~ /^upsampling/) | ||
| 221 | { | ||
| 222 | $self->_init_bilinear($name, $arr); | ||
| 223 | } | ||
| 224 | elsif($name =~ /^stn_loc/ and $name =~ /weight$/) | ||
| 225 | { | ||
| 226 | $self->_init_zero($name, $arr); | ||
| 227 | } | ||
| 228 | elsif($name =~ /^stn_loc/ and $name =~ /bias$/) | ||
| 229 | { | ||
| 230 | $self->_init_loc_bias($name, $arr); | ||
| 231 | } | ||
| 232 | elsif($name =~ /bias$/) | ||
| 233 | { | ||
| 234 | $self->_init_bias($name, $arr); | ||
| 235 | } | ||
| 236 | elsif($name =~ /gamma$/) | ||
| 237 | { | ||
| 238 | $self->_init_gamma($name, $arr); | ||
| 239 | } | ||
| 240 | elsif($name =~ /beta$/) | ||
| 241 | { | ||
| 242 | $self->_init_beta($name, $arr); | ||
| 243 | } | ||
| 244 | elsif($name =~ /weight$/) | ||
| 245 | { | ||
| 246 | $self->_init_weight($name, $arr); | ||
| 247 | } | ||
| 248 | elsif($name =~ /moving_mean$/) | ||
| 249 | { | ||
| 250 | $self->_init_zero($name, $arr); | ||
| 251 | } | ||
| 252 | elsif($name =~ /moving_var$/) | ||
| 253 | { | ||
| 254 | $self->_init_one($name, $arr); | ||
| 255 | } | ||
| 256 | elsif($name =~ /moving_inv_var$/) | ||
| 257 | { | ||
| 258 | $self->_init_zero($name, $arr); | ||
| 259 | } | ||
| 260 | elsif($name =~ /moving_avg$/) | ||
| 261 | { | ||
| 262 | $self->_init_zero($name, $arr); | ||
| 263 | } | ||
| 264 | elsif($name =~ /min$/) | ||
| 265 | { | ||
| 266 | $self->_init_zero($name, $arr); | ||
| 267 | } | ||
| 268 | elsif($name =~ /max$/) | ||
| 269 | { | ||
| 270 | $self->_init_one($name, $arr); | ||
| 271 | } | ||
| 272 | else | ||
| 273 | { | ||
| 274 | $self->_init_default($name, $arr); | ||
| 275 | } | ||
| 276 | } | ||
| 277 | |||
| 278 | *slice = *call; | ||
| 279 | |||
| 280 | method _init_bilinear($name, $arr) | ||
| 281 | { | ||
| 282 | my $pdl_type = PDL::Type->new(DTYPE_MX_TO_PDL->{ 'float32' }); | ||
| 283 | my $weight = pzeros( | ||
| 284 | PDL::Type->new(DTYPE_MX_TO_PDL->{ 'float32' }), | ||
| 285 | $arr->size | ||
| 286 | ); | ||
| 287 | my $shape = $arr->shape; | ||
| 288 | my $size = $arr->size; | ||
| 289 | my $f = pceil($shape->[3] / 2)->at(0); | ||
| 290 | my $c = (2 * $f - 1 - $f % 2) / (2 * $f); | ||
| 291 | for my $i (0..($size-1)) | ||
| 292 | { | ||
| 293 | my $x = $i % $shape->[3]; | ||
| 294 | my $y = ($i / $shape->[3]) % $shape->[2]; | ||
| 295 | $weight->index($i) .= (1 - abs($x / $f - $c)) * (1 - abs($y / $f - $c)); | ||
| 296 | } | ||
| 297 | $arr .= $weight->reshape(reverse @{ $shape }); | ||
| 298 | } | ||
| 299 | |||
| 300 | method _init_loc_bias($name, $arr) | ||
| 301 | { | ||
| 302 | confess("assert error shape[0] == 6") | ||
| 303 | unless $arr->shape->[0] == 6; | ||
| 304 | $arr .= [1.0, 0, 0, 0, 1.0, 0]; | ||
| 305 | } | ||
| 306 | |||
| 307 | method _init_zero($name, $arr) | ||
| 308 | { | ||
| 309 | $arr .= 0; | ||
| 310 | } | ||
| 311 | |||
| 312 | method _init_one($name, $arr) | ||
| 313 | { | ||
| 314 | $arr .= 1; | ||
| 315 | } | ||
| 316 | |||
| 317 | method _init_bias($name, $arr) | ||
| 318 | { | ||
| 319 | $arr .= 0; | ||
| 320 | } | ||
| 321 | |||
| 322 | method _init_gamma($name, $arr) | ||
| 323 | { | ||
| 324 | $arr .= 1; | ||
| 325 | } | ||
| 326 | |||
| 327 | method _init_beta($name, $arr) | ||
| 328 | { | ||
| 329 | $arr .= 0; | ||
| 330 | } | ||
| 331 | |||
| 332 | method _init_weight($name, $arr) | ||
| 333 | { | ||
| 334 | confess("Virtual method, subclass must override it"); | ||
| 335 | } | ||
| 336 | |||
| 337 | method _init_default($name, $arr) | ||
| 338 | { | ||
| 339 | confess( | ||
| 340 | "Unknown initialization pattern for $name. " | ||
| 341 | .'Default initialization is now limited to ' | ||
| 342 | .'"weight", "bias", "gamma" (1.0), and "beta" (0.0).' | ||
| 343 | .'Please use mx.sym.Variable(init=mx.init.*) to set initialization pattern' | ||
| 344 | ); | ||
| 345 | } | ||
| 346 | |||
| 347 | =head1 NAME | ||
| 348 | |||
| 349 | AI::MXNet::Load - Initialize by loading a pretrained param from a hash ref. | ||
| 350 | =cut | ||
| 351 | |||
| 352 | =head2 new | ||
| 353 | |||
| 354 | Parameters | ||
| 355 | ---------- | ||
| 356 | param: HashRef[AI::MXNet::NDArray] | ||
| 357 | default_init: Initializer | ||
| 358 | default initializer when a name is not found in the param hash ref. | ||
| 359 | verbose: bool | ||
| 360 | log the names when initializing. | ||
| 361 | =cut | ||
| 362 | |||
| 363 | package AI::MXNet::Load; | ||
| 364 | use Mouse; | ||
| 365 | extends 'AI::MXNet::Initializer'; | ||
| 366 | |||
| 367 | has 'param' => (is => "rw", isa => 'HashRef[AI::MXNet::NDArray]', required => 1); | ||
| 368 | has 'default_init' => (is => "rw", isa => "AI::MXNet::Initializer"); | ||
| 369 | has 'verbose' => (is => "rw", isa => "Int", default => 0); | ||
| 370 | |||
| 371 | sub BUILD | ||
| 372 | { | ||
| 373 | my $self = shift; | ||
| 374 | my $param = AI::MXNet::NDArray->load($self->param) unless ref $self->param; | ||
| 375 | my %self_param; | ||
| 376 | while(my ($name, $arr) = each %{ $self->param }) | ||
| 377 | { | ||
| 378 | $name =~ s/^(?:arg|aux)://; | ||
| 379 | $self_param{ $name } = $arr; | ||
| 380 | } | ||
| 381 | $self->param(\%self_param); | ||
| 382 | } | ||
| 383 | |||
| 384 | method call(Str $name, AI::MXNet::NDArray $arr) | ||
| 385 | { | ||
| 386 | if(exists $self->param->{ $name }) | ||
| 387 | { | ||
| 388 | my $target_shape = join(',', @{ $arr->shape }); | ||
| 389 | my $param_shape = join(',', @{ $self->param->{ $name }->shape }); | ||
| 390 | confess( | ||
| 391 | "Parameter $name cannot be initialized from loading. " | ||
| 392 | ."Shape mismatch, target $target_shape vs loaded $param_shape" | ||
| 393 | ) unless $target_shape eq $param_shape; | ||
| 394 | $arr .= $self->param->{ $name }; | ||
| 395 | AI::MXNet::Log->info("Initialized $name by loading") if $self->verbose; | ||
| 396 | } | ||
| 397 | else | ||
| 398 | { | ||
| 399 | confess( | ||
| 400 | "Cannot Initialize $name. Not found in loaded param " | ||
| 401 | ."and no default Initializer is provided." | ||
| 402 | ) unless defined $self->default_init; | ||
| 403 | $self->default_init($name, $arr); | ||
| 404 | AI::MXNet::Log->info("Initialized $name by default") if $self->verbose; | ||
| 405 | } | ||
| 406 | } | ||
| 407 | |||
| 408 | *slice = *call; | ||
| 409 | |||
| 410 | =head1 NAME | ||
| 411 | |||
| 412 | AI::MXNet::Mixed - A container with multiple initializer patterns. | ||
| 413 | =cut | ||
| 414 | |||
| 415 | =head2 new | ||
| 416 | |||
| 417 | patterns: array ref of str | ||
| 418 | array ref of regular expression patterns to match parameter names. | ||
| 419 | initializers: array ref of AI::MXNet::Initializer objects. | ||
| 420 | array ref of Initializers corresponding to the patterns. | ||
| 421 | =cut | ||
| 422 | |||
| 423 | package AI::MXNet::Mixed; | ||
| 424 | use Mouse; | ||
| 425 | extends 'AI::MXNet::Initializer'; | ||
| 426 | |||
| 427 | has "map" => (is => "rw", init_arg => undef); | ||
| 428 | has "patterns" => (is => "ro", isa => 'ArrayRef[Str]'); | ||
| 429 | has "initializers" => (is => "ro", isa => 'ArrayRef[AI::MXnet::Initializer]'); | ||
| 430 | |||
| 431 | sub BUILD | ||
| 432 | { | ||
| 433 | my $self = shift; | ||
| 434 | confess("patterns count != initializers count") | ||
| 435 | unless (@{ $self->patterns } == @{ $self->initializers }); | ||
| 436 | my %map; | ||
| 437 | @map{ @{ $self->patterns } } = @{ $self->initializers }; | ||
| 438 | $self->map(\%map); | ||
| 439 | } | ||
| 440 | |||
| 441 | method call(Str $name, AI::MXNet::NDArray $arr) | ||
| 442 | { | ||
| 443 | for my $pattern (keys %{ $self->map }) | ||
| 444 | { | ||
| 445 | if($name =~ /$pattern/) | ||
| 446 | { | ||
| 447 | $self->map->{$pattern}->($name, $arr); | ||
| 448 | return; | ||
| 449 | } | ||
| 450 | } | ||
| 451 | confess( | ||
| 452 | "Parameter name $name did not match any pattern. Consider" | ||
| 453 | ."add a \".*\" pattern at the and with default Initializer." | ||
| 454 | ); | ||
| 455 | } | ||
| 456 | |||
| 457 | package AI::MXNet::Zero; | ||
| 458 | use Mouse; | ||
| 459 | extends 'AI::MXNet::Initializer'; | ||
| 460 | method _init_weight(Str $name, AI::MXNet::NDArray $arr) | ||
| 461 | { | ||
| 462 | $arr .= 0; | ||
| 463 | } | ||
| 464 | |||
| 465 | __PACKAGE__->register; | ||
| 466 | |||
| 467 | package AI::MXNet::Zeros; | ||
| 468 | use Mouse; | ||
| 469 | extends 'AI::MXNet::Zero'; | ||
| 470 | |||
| 471 | __PACKAGE__->register; | ||
| 472 | |||
| 473 | package AI::MXNet::One; | ||
| 474 | use Mouse; | ||
| 475 | extends 'AI::MXNet::Initializer'; | ||
| 476 | method _init_weight(Str $name, AI::MXNet::NDArray $arr) | ||
| 477 | { | ||
| 478 | $arr .= 1; | ||
| 479 | } | ||
| 480 | |||
| 481 | __PACKAGE__->register; | ||
| 482 | |||
| 483 | package AI::MXNet::Ones; | ||
| 484 | use Mouse; | ||
| 485 | extends 'AI::MXNet::One'; | ||
| 486 | |||
| 487 | __PACKAGE__->register; | ||
| 488 | |||
| 489 | package AI::MXNet::Constant; | ||
| 490 | use Mouse; | ||
| 491 | extends 'AI::MXNet::Initializer'; | ||
| 492 | has 'value' => (is => 'ro', isa => 'Num', required => 1); | ||
| 493 | around BUILDARGS => sub { | ||
| 494 | my $orig = shift; | ||
| 495 | my $class = shift; | ||
| 496 | return $class->$orig(value => $_[0]) if @_ == 1; | ||
| 497 | return $class->$orig(@_); | ||
| 498 | }; | ||
| 499 | |||
| 500 | method _init_weight(Str $name, AI::MXNet::NDArray $arr) | ||
| 501 | { | ||
| 502 | $arr .= $self->value; | ||
| 503 | } | ||
| 504 | |||
| 505 | __PACKAGE__->register; | ||
| 506 | |||
| 507 | =head1 NAME | ||
| 508 | |||
| 509 | AI::MXNet::Uniform - Initialize the weight with uniform random values. | ||
| 510 | =cut | ||
| 511 | |||
| 512 | =head1 DESCRIPTION | ||
| 513 | |||
| 514 | Initialize the weight with uniform random values contained within of [-scale, scale] | ||
| 515 | |||
| 516 | Parameters | ||
| 517 | ---------- | ||
| 518 | scale : float, optional | ||
| 519 | The scale of the uniform distribution. | ||
| 520 | =cut | ||
| 521 | |||
| 522 | package AI::MXNet::Uniform; | ||
| 523 | use Mouse; | ||
| 524 | extends 'AI::MXNet::Initializer'; | ||
| 525 | has "scale" => (is => "ro", isa => "Num", default => 0.07); | ||
| 526 | around BUILDARGS => sub { | ||
| 527 | my $orig = shift; | ||
| 528 | my $class = shift; | ||
| 529 | return $class->$orig(scale => $_[0]) if @_ == 1; | ||
| 530 | return $class->$orig(@_); | ||
| 531 | }; | ||
| 532 | |||
| 533 | method _init_weight(Str $name, AI::MXNet::NDArray $arr) | ||
| 534 | { | ||
| 535 | AI::MXNet::Random->uniform(-$self->scale, $self->scale, { out => $arr }); | ||
| 536 | } | ||
| 537 | |||
| 538 | __PACKAGE__->register; | ||
| 539 | |||
| 540 | =head1 NAME | ||
| 541 | |||
| 542 | AI::MXNet::Normal - Initialize the weight with gaussian random values. | ||
| 543 | =cut | ||
| 544 | |||
| 545 | =head1 DESCRIPTION | ||
| 546 | |||
| 547 | Initialize the weight with gaussian random values contained within of [0, sigma] | ||
| 548 | |||
| 549 | Parameters | ||
| 550 | ---------- | ||
| 551 | sigma : float, optional | ||
| 552 | Standard deviation for the gaussian distribution. | ||
| 553 | =cut | ||
| 554 | |||
| 555 | package AI::MXNet::Normal; | ||
| 556 | use Mouse; | ||
| 557 | extends 'AI::MXNet::Initializer'; | ||
| 558 | has "sigma" => (is => "ro", isa => "Num", default => 0.01); | ||
| 559 | around BUILDARGS => sub { | ||
| 560 | my $orig = shift; | ||
| 561 | my $class = shift; | ||
| 562 | return $class->$orig(sigma => $_[0]) if @_ == 1; | ||
| 563 | return $class->$orig(@_); | ||
| 564 | }; | ||
| 565 | |||
| 566 | method _init_weight(Str $name, AI::MXNet::NDArray $arr) | ||
| 567 | { | ||
| 568 | AI::MXNet::Random->normal(0, $self->sigma, { out => $arr }); | ||
| 569 | } | ||
| 570 | |||
| 571 | __PACKAGE__->register; | ||
| 572 | |||
| 573 | =head1 NAME | ||
| 574 | |||
| 575 | AI::MXNet::Orthogonal - Intialize the weight as an Orthogonal matrix. | ||
| 576 | =cut | ||
| 577 | |||
| 578 | =head1 DESCRIPTION | ||
| 579 | |||
| 580 | Intialize weight as Orthogonal matrix | ||
| 581 | |||
| 582 | Parameters | ||
| 583 | ---------- | ||
| 584 | scale : float, optional | ||
| 585 | scaling factor of weight | ||
| 586 | |||
| 587 | rand_type: string optional | ||
| 588 | use "uniform" or "normal" random number to initialize weight | ||
| 589 | |||
| 590 | Reference | ||
| 591 | --------- | ||
| 592 | Exact solutions to the nonlinear dynamics of learning in deep linear neural networks | ||
| 593 | arXiv preprint arXiv:1312.6120 (2013). | ||
| 594 | =cut | ||
| 595 | |||
| 596 | package AI::MXNet::Orthogonal; | ||
| 597 | use AI::MXNet::Base; | ||
| 598 | use Mouse; | ||
| 599 | use AI::MXNet::Types; | ||
| 600 | extends 'AI::MXNet::Initializer'; | ||
| 601 | has "scale" => (is => "ro", isa => "Num", default => 1.414); | ||
| 602 | has "rand_type" => (is => "ro", isa => enum([qw/uniform normal/]), default => 'uniform'); | ||
| 603 | |||
| 604 | method _init_weight(Str $name, AI::MXNet::NDArray $arr) | ||
| 605 | { | ||
| 606 | my @shape = @{ $arr->shape }; | ||
| 607 | my $nout = $shape[0]; | ||
| 608 | my $nin = AI::MXNet::NDArray->size([@shape[1..$#shape]]); | ||
| 609 | my $tmp = AI::MXNet::NDArray->zeros([$nout, $nin]); | ||
| 610 | if($self->rand_type eq 'uniform') | ||
| 611 | { | ||
| 612 | AI::MXNet::Random->uniform(-1, 1, { out => $tmp }); | ||
| 613 | } | ||
| 614 | else | ||
| 615 | { | ||
| 616 | AI::MXNet::Random->normal(0, 1, { out => $tmp }); | ||
| 617 | } | ||
| 618 | $tmp = $tmp->aspdl; | ||
| 619 | my ($u, $s, $v) = svd($tmp); | ||
| 620 | my $q; | ||
| 621 | if(join(',', @{ $u->shape->unpdl }) eq join(',', @{ $tmp->shape->unpdl })) | ||
| 622 | { | ||
| 623 | $q = $u; | ||
| 624 | } | ||
| 625 | else | ||
| 626 | { | ||
| 627 | $q = $v; | ||
| 628 | } | ||
| 629 | $q = $self->scale * $q->reshape(reverse(@shape)); | ||
| 630 | $arr .= $q; | ||
| 631 | } | ||
| 632 | |||
| 633 | *slice = *call; | ||
| 634 | __PACKAGE__->register; | ||
| 635 | |||
| 636 | =head1 NAME | ||
| 637 | |||
| 638 | AI::MXNet::Xavier - Initialize the weight with Xavier or similar initialization scheme. | ||
| 639 | =cut | ||
| 640 | |||
| 641 | =head1 DESCRIPTION | ||
| 642 | |||
| 643 | Parameters | ||
| 644 | ---------- | ||
| 645 | rnd_type: str, optional | ||
| 646 | Use gaussian or uniform. | ||
| 647 | factor_type: str, optional | ||
| 648 | Use avg, in, or out. | ||
| 649 | magnitude: float, optional | ||
| 650 | The scale of the random number range. | ||
| 651 | =cut | ||
| 652 | |||
| 653 | package AI::MXNet::Xavier; | ||
| 654 | use Mouse; | ||
| 655 | use AI::MXNet::Types; | ||
| 656 | extends 'AI::MXNet::Initializer'; | ||
| 657 | has "magnitude" => (is => "rw", isa => "Num", default => 3); | ||
| 658 | has "rnd_type" => (is => "ro", isa => enum([qw/uniform gaussian/]), default => 'uniform'); | ||
| 659 | has "factor_type" => (is => "ro", isa => enum([qw/avg in out/]), default => 'avg'); | ||
| 660 | |||
| 661 | method _init_weight(Str $name, AI::MXNet::NDArray $arr) | ||
| 662 | { | ||
| 663 | my @shape = @{ $arr->shape }; | ||
| 664 | confess(__PACKAGE__." initializer can not be applied on less than 2D tensor") | ||
| 665 | if @shape < 2; | ||
| 666 | my $hw_scale = 1; | ||
| 667 | if(@shape > 2) | ||
| 668 | { | ||
| 669 | $hw_scale = AI::MXNet::NDArray->size([@shape[2..$#shape]]); | ||
| 670 | } | ||
| 671 | my ($fan_in, $fan_out) = ($shape[1] * $hw_scale, $shape[0] * $hw_scale); | ||
| 672 | my $factor; | ||
| 673 | if($self->factor_type eq "avg") | ||
| 674 | { | ||
| 675 | $factor = ($fan_in + $fan_out) / 2; | ||
| 676 | } | ||
| 677 | elsif($self->factor_type eq "in") | ||
| 678 | { | ||
| 679 | $factor = $fan_in; | ||
| 680 | } | ||
| 681 | else | ||
| 682 | { | ||
| 683 | $factor = $fan_out; | ||
| 684 | } | ||
| 685 | my $scale = sqrt($self->magnitude / $factor); | ||
| 686 | if($self->rnd_type eq "iniform") | ||
| 687 | { | ||
| 688 | AI::MXNet::Random->uniform(-$scale, $scale, { out => $arr }); | ||
| 689 | } | ||
| 690 | else | ||
| 691 | { | ||
| 692 | AI::MXNet::Random->normal(0, $scale, { out => $arr }); | ||
| 693 | } | ||
| 694 | } | ||
| 695 | __PACKAGE__->register; | ||
| 696 | |||
| 697 | =head1 NAME | ||
| 698 | |||
| 699 | AI::MXNet::MSRAPrelu - Custom initialization scheme. | ||
| 700 | =cut | ||
| 701 | |||
| 702 | =head1 DESCRIPTION | ||
| 703 | |||
| 704 | Initialize the weight with initialization scheme from | ||
| 705 | Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification. | ||
| 706 | |||
| 707 | Parameters | ||
| 708 | ---------- | ||
| 709 | factor_type: str, optional | ||
| 710 | Use avg, in, or out. | ||
| 711 | slope: float, optional | ||
| 712 | initial slope of any PReLU (or similar) nonlinearities. | ||
| 713 | =cut | ||
| 714 | |||
| 715 | package AI::MXNet::MSRAPrelu; | ||
| 716 | use Mouse; | ||
| 717 | extends 'AI::MXNet::Xavier'; | ||
| 718 | |||
| 719 | has '+rnd_type' => (default => "gaussian"); | ||
| 720 | has '+factor_type' => (default => "avg"); | ||
| 721 | has 'slope' => (is => 'ro', isa => 'Num', default => 0.25); | ||
| 722 | |||
| 723 | sub BUILD | ||
| 724 | { | ||
| 725 | my $self = shift; | ||
| 726 | my $magnitude = 2 / (1 + $self->slope ** 2); | ||
| 727 | $self->magnitude($magnitude); | ||
| 728 | $self->kwargs({ slope => $self->slope, factor_type => $self->factor_type }); | ||
| 729 | } | ||
| 730 | __PACKAGE__->register; | ||
| 731 | |||
| 732 | package AI::MXNet::Bilinear; | ||
| 733 | use Mouse; | ||
| 734 | use AI::MXNet::Base; | ||
| 735 | extends 'AI::MXNet::Initializer'; | ||
| 736 | |||
| 737 | method _init_weight($name, $arr) | ||
| 738 | { | ||
| 739 | my $pdl_type = PDL::Type->new(DTYPE_MX_TO_PDL->{ 'float32' }); | ||
| 740 | my $weight = pzeros( | ||
| 741 | PDL::Type->new(DTYPE_MX_TO_PDL->{ 'float32' }), | ||
| 742 | $arr->size | ||
| 743 | ); | ||
| 744 | my $shape = $arr->shape; | ||
| 745 | my $size = $arr->size; | ||
| 746 | my $f = pceil($shape->[3] / 2)->at(0); | ||
| 747 | my $c = (2 * $f - 1 - $f % 2) / (2 * $f); | ||
| 748 | for my $i (0..($size-1)) | ||
| 749 | { | ||
| 750 | my $x = $i % $shape->[3]; | ||
| 751 | my $y = ($i / $shape->[3]) % $shape->[2]; | ||
| 752 | $weight->index($i) .= (1 - abs($x / $f - $c)) * (1 - abs($y / $f - $c)); | ||
| 753 | } | ||
| 754 | $arr .= $weight->reshape(reverse @{ $shape }); | ||
| 755 | } | ||
| 756 | |||
| 757 | __PACKAGE__->register; | ||
| 758 | |||
| 759 | package AI::MXNet::LSTMBias; | ||
| 760 | |||
| 761 | =head1 NAME | ||
| 762 | |||
| 763 | AI::MXNet::LSTMBias - Custom initializer for LSTM cells. | ||
| 764 | =cut | ||
| 765 | |||
| 766 | =head1 DESCRIPTION | ||
| 767 | |||
| 768 | Initializes all biases of an LSTMCell to 0.0 except for | ||
| 769 | the forget gate's bias that is set to a custom value. | ||
| 770 | |||
| 771 | Parameters | ||
| 772 | ---------- | ||
| 773 | forget_bias: float,a bias for the forget gate. | ||
| 774 | Jozefowicz et al. 2015 recommends setting this to 1.0. | ||
| 775 | =cut | ||
| 776 | |||
| 777 | use Mouse; | ||
| 778 | extends 'AI::MXNet::Initializer'; | ||
| 779 | has 'forget_bias' => (is => 'ro', isa => 'Num', required => 1); | ||
| 780 | around BUILDARGS => \&AI::MXNet::Base::process_arguments; | ||
| 781 | method python_constructor_arguments() { ['forget_bias'] } | ||
| 782 | |||
| 783 | method _init_weight(Str $name, AI::MXNet::NDArray $arr) | ||
| 784 | { | ||
| 785 | $arr .= 0; | ||
| 786 | # in the case of LSTMCell the forget gate is the second | ||
| 787 | # gate of the 4 LSTM gates, we modify the according values. | ||
| 788 | my $num_hidden = int($arr->shape->[0] / 4); | ||
| 789 | $arr->slice([$num_hidden, 2*$num_hidden-1]) .= $self->forget_bias; | ||
| 790 | } | ||
| 791 | |||
| 792 | __PACKAGE__->register; | ||
| 793 | |||
| 794 | package AI::MXNet::FusedRNN; | ||
| 795 | use Mouse; | ||
| 796 | use JSON::PP; | ||
| 797 | extends 'AI::MXNet::Initializer'; | ||
| 798 | |||
| 799 | =head1 NAME | ||
| 800 | |||
| 801 | AI::MXNet::FusedRNN - Custom initializer for fused RNN cells. | ||
| 802 | =cut | ||
| 803 | |||
| 804 | =head1 DESCRIPTION | ||
| 805 | |||
| 806 | Initializes parameters for fused rnn layer. | ||
| 807 | |||
| 808 | Parameters | ||
| 809 | ---------- | ||
| 810 | init : Initializer | ||
| 811 | initializer applied to unpacked weights. | ||
| 812 | All parameters below must be exactly the same as ones passed to the | ||
| 813 | FusedRNNCell constructor. | ||
| 814 | |||
| 815 | num_hidden : int | ||
| 816 | num_layers : int | ||
| 817 | mode : str | ||
| 818 | bidirectional : bool | ||
| 819 | forget_bias : float | ||
| 820 | =cut | ||
| 821 | |||
| 822 | has 'init' => (is => 'rw', isa => 'Str|AI::MXNet::Initializer', required => 1); | ||
| 823 | has 'forget_bias' => (is => 'ro', isa => 'Num', default => 1); | ||
| 824 | has [qw/num_hidden | ||
| 825 | num_layers/] => (is => 'ro', isa => 'Int', required => 1); | ||
| 826 | has 'mode' => (is => 'ro', isa => 'Str', required => 1); | ||
| 827 | has 'bidirectional' => (is => 'ro', isa => 'Bool', default => 0); | ||
| 828 | |||
| 829 | sub BUILD | ||
| 830 | { | ||
| 831 | my $self = shift; | ||
| 832 | if(not blessed $self->init) | ||
| 833 | { | ||
| 834 | my ($klass, $kwargs); | ||
| 835 | eval { | ||
| 836 | ($klass, $kwargs) = @{ decode_json($self->init) }; | ||
| 837 | }; | ||
| 838 | confess("FusedRNN failed to init $@") if $@; | ||
| 839 | $self->init($self->get_init_registry->{ lc $klass }->new(%$kwargs)); | ||
| 840 | } | ||
| 841 | } | ||
| 842 | |||
| 843 | method _init_weight($name, $arr) | ||
| 844 | { | ||
| 845 | my $cell = AI::MXNet::RNN::FusedCell->new( | ||
| 846 | num_hidden => $self->num_hidden, | ||
| 847 | num_layers => $self->num_layers, | ||
| 848 | mode => $self->mode, | ||
| 849 | bidirectional => $self->bidirectional, | ||
| 850 | forget_bias => $self->forget_bias, | ||
| 851 | prefix => '' | ||
| 852 | ); | ||
| 853 | |||
| 854 | my $args = $cell->unpack_weights({ parameters => $arr }); | ||
| 855 | for my $name (keys %{ $args }) | ||
| 856 | { | ||
| 857 | my $desc = AI::MXNet::InitDesc->new(name => $name); | ||
| 858 | # for lstm bias, we use a custom initializer | ||
| 859 | # which adds a bias to the forget gate | ||
| 860 | if($self->mode eq 'lstm' and $name =~ /f_bias$/) | ||
| 861 | { | ||
| 862 | $args->{$name} .= $self->forget_bias; | ||
| 863 | } | ||
| 864 | else | ||
| 865 | { | ||
| 866 | $self->init->($desc, $args->{$name}); | ||
| 867 | } | ||
| 868 | } | ||
| 869 | |||
| 870 | $arr .= $cell->pack_weights($args)->{parameters}; | ||
| 871 | } | ||
| 872 | |||
| 873 | __PACKAGE__->register; | ||
| 874 | |||
| 875 | 1; |