| 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 | use strict; | ||
| 19 | use warnings; | ||
| 20 | package AI::MXNet::Gluon::NN::Sequential; | ||
| 21 | use AI::MXNet::Function::Parameters; | ||
| 22 | |||
| 23 | =head1 NAME | ||
| 24 | |||
| 25 | AI::MXNet::Gluon::NN::Sequential | ||
| 26 | =cut | ||
| 27 | |||
| 28 | =head2 DESCRIPTION | ||
| 29 | |||
| 30 | Stacks `Block`s sequentially. | ||
| 31 | |||
| 32 | Example:: | ||
| 33 | |||
| 34 | my $net = nn->Sequential() | ||
| 35 | # use net's name_scope to give child Blocks appropriate names. | ||
| 36 | net->name_scope(sub { | ||
| 37 | $net->add($nn->Dense(10, activation=>'relu')); | ||
| 38 | $net->add($nn->Dense(20)); | ||
| 39 | }); | ||
| 40 | =cut | ||
| 41 | |||
| 42 | use AI::MXNet::Gluon::Mouse; | ||
| 43 | extends 'AI::MXNet::Gluon::Block'; | ||
| 44 | |||
| 45 | =head2 | ||
| 46 | |||
| 47 | Adds block on top of the stack. | ||
| 48 | =cut | ||
| 49 | |||
| 50 | method add(AI::MXNet::Gluon::Block @block) | ||
| 51 | { | ||
| 52 | $self->register_child($_) for @block; | ||
| 53 | } | ||
| 54 | |||
| 55 | |||
| 56 | method forward($x) | ||
| 57 | { | ||
| 58 | for my $block ($self->_children->values) | ||
| 59 | { | ||
| 60 | $x = $block->($x); | ||
| 61 | } | ||
| 62 | return $x; | ||
| 63 | } | ||
| 64 | |||
| 65 | use overload | ||
| 66 | '""' => sub | ||
| 67 | { | ||
| 68 | my $self = shift; | ||
| 69 | my $s = "%s(\n%s\n)"; | ||
| 70 | my @blocks; | ||
| 71 | my $k = 0; | ||
| 72 | for my $v ($self->_children->values) | ||
| 73 | { | ||
| 74 | push @blocks, " ($k): ".AI::MXNet::Base::_indent("$v", 2); | ||
| 75 | $k++; | ||
| 76 | } | ||
| 77 | sprintf("%s(\n%s\n)", $self->_class_name, join("\n", @blocks)); | ||
| 78 | }, | ||
| 79 | '@{}' => sub { [shift->_children->values] }; | ||
| 80 | |||
| 81 | method slice(Slice $slice) | ||
| 82 | { | ||
| 83 | my $new = __PACKAGE__->new; | ||
| 84 | $new->add(@{ $self }[ @$slice ]); | ||
| 85 | return $new; | ||
| 86 | } | ||
| 87 | |||
| 88 | __PACKAGE__->register('AI::MXNet::Gluon::NN'); | ||
| 89 | |||
| 90 | package AI::MXNet::Gluon::NN::HybridSequential; | ||
| 91 | |||
| 92 | =head1 NAME | ||
| 93 | |||
| 94 | AI::MXNet::Gluon::NN::HybridSequential | ||
| 95 | =cut | ||
| 96 | |||
| 97 | =head2 DESCRIPTION | ||
| 98 | |||
| 99 | Stacks `Block`s sequentially. | ||
| 100 | |||
| 101 | Example:: | ||
| 102 | |||
| 103 | my $net = nn->Sequential() | ||
| 104 | # use net's name_scope to give child Blocks appropriate names. | ||
| 105 | net->name_scope(sub { | ||
| 106 | $net->add($nn->Dense(10, activation=>'relu')); | ||
| 107 | $net->add($nn->Dense(20)); | ||
| 108 | }); | ||
| 109 | =cut | ||
| 110 | |||
| 111 | use AI::MXNet::Gluon::Mouse; | ||
| 112 | extends 'AI::MXNet::Gluon::HybridBlock'; | ||
| 113 | |||
| 114 | =head2 | ||
| 115 | |||
| 116 | Adds block on top of the stack. | ||
| 117 | =cut | ||
| 118 | |||
| 119 | method add(AI::MXNet::Gluon::HybridBlock @block) | ||
| 120 | { | ||
| 121 | $self->register_child($_) for @block; | ||
| 122 | } | ||
| 123 | |||
| 124 | |||
| 125 | method hybrid_forward($F, $x) | ||
| 126 | { | ||
| 127 | for my $block ($self->_children->values) | ||
| 128 | { | ||
| 129 | $x = $block->($x); | ||
| 130 | } | ||
| 131 | return $x; | ||
| 132 | } | ||
| 133 | |||
| 134 | use overload | ||
| 135 | '""' => sub | ||
| 136 | { | ||
| 137 | my $self = shift; | ||
| 138 | my $s = "%s(\n%s\n)"; | ||
| 139 | my @blocks; | ||
| 140 | my $k = 0; | ||
| 141 | for my $v ($self->_children->values) | ||
| 142 | { | ||
| 143 | push @blocks, " ($k): ".AI::MXNet::Base::_indent("$v", 2); | ||
| 144 | $k++; | ||
| 145 | } | ||
| 146 | sprintf("%s(\n%s\n)", $self->_class_name, join("\n", @blocks)); | ||
| 147 | }, | ||
| 148 | '@{}' => sub { [shift->_children->values] }; | ||
| 149 | |||
| 150 | method slice(Slice $slice) | ||
| 151 | { | ||
| 152 | my $new = __PACKAGE__->new; | ||
| 153 | $new->add(@{ $self }[ @$slice ]); | ||
| 154 | return $new; | ||
| 155 | } | ||
| 156 | |||
| 157 | __PACKAGE__->register('AI::MXNet::Gluon::NN'); | ||
| 158 | |||
| 159 | package AI::MXNet::Gluon::NN::Dense; | ||
| 160 | use AI::MXNet::Gluon::Mouse; | ||
| 161 | extends 'AI::MXNet::Gluon::HybridBlock'; | ||
| 162 | |||
| 163 | method python_constructor_arguments() | ||
| 164 | { | ||
| 165 | ['units']; | ||
| 166 | } | ||
| 167 | |||
| 168 | =head1 NAME | ||
| 169 | |||
| 170 | AI::MXNet::Gluon::NN::Dense | ||
| 171 | |||
| 172 | =head1 DESCRIPTION | ||
| 173 | |||
| 174 | Just your regular densely-connected NN layer. | ||
| 175 | |||
| 176 | `Dense` implements the operation: | ||
| 177 | `output = activation(dot(input, weight) + bias)` | ||
| 178 | where `activation` is the element-wise activation function | ||
| 179 | passed as the `activation` argument, `weight` is a weights matrix | ||
| 180 | created by the layer, and `bias` is a bias vector created by the layer | ||
| 181 | (only applicable if `use_bias` is `True`). | ||
| 182 | |||
| 183 | Note: the input must be a tensor with rank 2. Use `flatten` to convert it | ||
| 184 | to rank 2 manually if necessary. | ||
| 185 | |||
| 186 | Parameters | ||
| 187 | ---------- | ||
| 188 | units : int | ||
| 189 | Dimensionality of the output space. | ||
| 190 | activation : str | ||
| 191 | Activation function to use. See help on `Activation` layer. | ||
| 192 | If you don't specify anything, no activation is applied | ||
| 193 | (ie. "linear" activation: `a(x) = x`). | ||
| 194 | use_bias : bool | ||
| 195 | Whether the layer uses a bias vector. | ||
| 196 | flatten : bool, default true | ||
| 197 | Whether the input tensor should be flattened. | ||
| 198 | If true, all but the first axis of input data are collapsed together. | ||
| 199 | If false, all but the last axis of input data are kept the same, and the transformation | ||
| 200 | applies on the last axis. | ||
| 201 | weight_initializer : str or `Initializer` | ||
| 202 | Initializer for the `kernel` weights matrix. | ||
| 203 | bias_initializer: str or `Initializer` | ||
| 204 | Initializer for the bias vector. | ||
| 205 | in_units : int, optional | ||
| 206 | Size of the input data. If not specified, initialization will be | ||
| 207 | deferred to the first time `forward` is called and `in_units` | ||
| 208 | will be inferred from the shape of input data. | ||
| 209 | prefix : str or None | ||
| 210 | See document of `Block`. | ||
| 211 | params : ParameterDict or None | ||
| 212 | weight_initializer : str or `Initializer` | ||
| 213 | Initializer for the `kernel` weights matrix. | ||
| 214 | bias_initializer: str or `Initializer` | ||
| 215 | Initializer for the bias vector. | ||
| 216 | in_units : int, optional | ||
| 217 | Size of the input data. If not specified, initialization will be | ||
| 218 | deferred to the first time `forward` is called and `in_units` | ||
| 219 | will be inferred from the shape of input data. | ||
| 220 | prefix : str or None | ||
| 221 | See document of `Block`. | ||
| 222 | params : ParameterDict or None | ||
| 223 | See document of `Block`. | ||
| 224 | |||
| 225 | If flatten is set to be True, then the shapes are: | ||
| 226 | Input shape: | ||
| 227 | An N-D input with shape | ||
| 228 | `(batch_size, x1, x2, ..., xn) with x1 * x2 * ... * xn equal to in_units`. | ||
| 229 | |||
| 230 | Output shape: | ||
| 231 | The output would have shape `(batch_size, units)`. | ||
| 232 | |||
| 233 | If ``flatten`` is set to be false, then the shapes are: | ||
| 234 | Input shape: | ||
| 235 | An N-D input with shape | ||
| 236 | `(x1, x2, ..., xn, in_units)`. | ||
| 237 | |||
| 238 | Output shape: | ||
| 239 | The output would have shape `(x1, x2, ..., xn, units)`. | ||
| 240 | =cut | ||
| 241 | |||
| 242 | has 'units' => (is => 'rw', isa => 'Int', required => 1); | ||
| 243 | has 'activation' => (is => 'rw', isa => 'Str'); | ||
| 244 | has 'use_bias' => (is => 'rw', isa => 'Bool', default => 1); | ||
| 245 | has 'flatten' => (is => 'rw', isa => 'Bool', default => 1); | ||
| 246 | has 'weight_initializer' => (is => 'rw', isa => 'Initializer'); | ||
| 247 | has 'bias_initializer' => (is => 'rw', isa => 'Initializer', default => 'zeros'); | ||
| 248 | has 'in_units' => (is => 'rw', isa => 'Int', default => 0); | ||
| 249 | has [qw/weight bias act/] => (is => 'rw', init_arg => undef); | ||
| 250 | |||
| 251 | sub BUILD | ||
| 252 | { | ||
| 253 | my $self = shift; | ||
| 254 | $self->name_scope(sub { | ||
| 255 | $self->weight( | ||
| 256 | $self->params->get( | ||
| 257 | 'weight', shape => [$self->units, $self->in_units], | ||
| 258 | init => $self->weight_initializer, | ||
| 259 | allow_deferred_init => 1 | ||
| 260 | ) | ||
| 261 | ); | ||
| 262 | if($self->use_bias) | ||
| 263 | { | ||
| 264 | $self->bias( | ||
| 265 | $self->params->get( | ||
| 266 | 'bias', shape => [$self->units], | ||
| 267 | init => $self->bias_initializer, | ||
| 268 | allow_deferred_init => 1 | ||
| 269 | ) | ||
| 270 | ); | ||
| 271 | } | ||
| 272 | if(defined $self->activation) | ||
| 273 | { | ||
| 274 | $self->act( | ||
| 275 | AI::MXNet::Gluon::NN->Activation( | ||
| 276 | activation => $self->activation, | ||
| 277 | prefix => $self->activation.'_' | ||
| 278 | ) | ||
| 279 | ); | ||
| 280 | } | ||
| 281 | }); | ||
| 282 | } | ||
| 283 | |||
| 284 | method hybrid_forward(GluonClass $F, GluonInput $x, GluonInput :$weight, Maybe[GluonInput] :$bias=) | ||
| 285 | { | ||
| 286 | my $act; | ||
| 287 | if(not defined $bias) | ||
| 288 | { | ||
| 289 | $act = $F->FullyConnected($x, $weight, no_bias => 1, num_hidden => $self->units, name => 'fwd'); | ||
| 290 | } | ||
| 291 | else | ||
| 292 | { | ||
| 293 | $act = $F->FullyConnected($x, $weight, $bias, num_hidden => $self->units, flatten => $self->flatten, name => 'fwd') | ||
| 294 | } | ||
| 295 | if(defined $self->act) | ||
| 296 | { | ||
| 297 | $act = $self->act->($act); | ||
| 298 | } | ||
| 299 | return $act; | ||
| 300 | } | ||
| 301 | |||
| 302 | use overload '""' => sub { | ||
| 303 | my $self = shift; | ||
| 304 | "${\ $self->_class_name }(${\ $self->units } -> ${\ $self->in_units }," | ||
| 305 | ." @{[ $self->act ? $self->act : 'linear' ]})" | ||
| 306 | }; | ||
| 307 | |||
| 308 | __PACKAGE__->register('AI::MXNet::Gluon::NN'); | ||
| 309 | |||
| 310 | package AI::MXNet::Gluon::NN::Dropout; | ||
| 311 | use AI::MXNet::Gluon::Mouse; | ||
| 312 | extends 'AI::MXNet::Gluon::HybridBlock'; | ||
| 313 | |||
| 314 | =head1 NAME | ||
| 315 | |||
| 316 | AI::MXNet::Gluon::NN::Dropout | ||
| 317 | =cut | ||
| 318 | |||
| 319 | =head1 DESCRIPTION | ||
| 320 | |||
| 321 | Applies Dropout to the input. | ||
| 322 | |||
| 323 | Dropout consists in randomly setting a fraction `rate` of input units | ||
| 324 | to 0 at each update during training time, which helps prevent overfitting. | ||
| 325 | |||
| 326 | Parameters | ||
| 327 | ---------- | ||
| 328 | rate : float | ||
| 329 | Fraction of the input units to drop. Must be a number between 0 and 1. | ||
| 330 | |||
| 331 | |||
| 332 | Input shape: | ||
| 333 | Arbitrary. | ||
| 334 | |||
| 335 | Output shape: | ||
| 336 | Same shape as input. | ||
| 337 | |||
| 338 | References | ||
| 339 | ---------- | ||
| 340 | `Dropout: A Simple Way to Prevent Neural Networks from Overfitting | ||
| 341 | <http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf>`_ | ||
| 342 | =cut | ||
| 343 | has 'rate' => (is => 'ro', isa => 'Dropout', required => 1); | ||
| 344 | method python_constructor_arguments() { ['rate'] } | ||
| 345 | |||
| 346 | method hybrid_forward(GluonClass $F, GluonInput $x) | ||
| 347 | { | ||
| 348 | return $F->Dropout($x, p => $self->rate, name => 'fwd'); | ||
| 349 | } | ||
| 350 | |||
| 351 | use overload '""' => sub { my $self = shift; "${\ $self->_class_name }(p = ${\ $self->rate })"; }; | ||
| 352 | |||
| 353 | __PACKAGE__->register('AI::MXNet::Gluon::NN'); | ||
| 354 | |||
| 355 | package AI::MXNet::Gluon::NN::BatchNorm; | ||
| 356 | use AI::MXNet::Gluon::Mouse; | ||
| 357 | extends 'AI::MXNet::Gluon::HybridBlock'; | ||
| 358 | |||
| 359 | =head1 NAME | ||
| 360 | |||
| 361 | AI::MXNet::Gluon::NN::BatchNorm | ||
| 362 | =cut | ||
| 363 | |||
| 364 | =head1 DESCRIPTION | ||
| 365 | |||
| 366 | Batch normalization layer (Ioffe and Szegedy, 2014). | ||
| 367 | Normalizes the input at each batch, i.e. applies a transformation | ||
| 368 | that maintains the mean activation close to 0 and the activation | ||
| 369 | standard deviation close to 1. | ||
| 370 | |||
| 371 | Parameters | ||
| 372 | ---------- | ||
| 373 | axis : int, default 1 | ||
| 374 | The axis that should be normalized. This is typically the channels | ||
| 375 | (C) axis. For instance, after a `Conv2D` layer with `layout='NCHW'`, | ||
| 376 | set `axis=1` in `BatchNorm`. If `layout='NHWC'`, then set `axis=3`. | ||
| 377 | momentum: float, default 0.9 | ||
| 378 | Momentum for the moving average. | ||
| 379 | epsilon: float, default 1e-5 | ||
| 380 | Small float added to variance to avoid dividing by zero. | ||
| 381 | center: bool, default True | ||
| 382 | If True, add offset of `beta` to normalized tensor. | ||
| 383 | If False, `beta` is ignored. | ||
| 384 | scale: bool, default True | ||
| 385 | If True, multiply by `gamma`. If False, `gamma` is not used. | ||
| 386 | When the next layer is linear (also e.g. `nn.relu`), | ||
| 387 | this can be disabled since the scaling | ||
| 388 | will be done by the next layer. | ||
| 389 | beta_initializer: str or `Initializer`, default 'zeros' | ||
| 390 | Initializer for the beta weight. | ||
| 391 | gamma_initializer: str or `Initializer`, default 'ones' | ||
| 392 | Initializer for the gamma weight. | ||
| 393 | moving_mean_initializer: str or `Initializer`, default 'zeros' | ||
| 394 | Initializer for the moving mean. | ||
| 395 | moving_variance_initializer: str or `Initializer`, default 'ones' | ||
| 396 | Initializer for the moving variance. | ||
| 397 | in_channels : int, default 0 | ||
| 398 | Number of channels (feature maps) in input data. If not specified, | ||
| 399 | initialization will be deferred to the first time `forward` is called | ||
| 400 | and `in_channels` will be inferred from the shape of input data. | ||
| 401 | |||
| 402 | |||
| 403 | Input shape: | ||
| 404 | Arbitrary. | ||
| 405 | |||
| 406 | Output shape: | ||
| 407 | Same shape as input. | ||
| 408 | =cut | ||
| 409 | |||
| 410 | has 'axis' => (is => 'ro', isa => 'DimSize', default => 1); | ||
| 411 | has 'momentum' => (is => 'ro', isa => 'Num', default => 0.9); | ||
| 412 | has 'epsilon' => (is => 'ro', isa => 'Num', default => 1e-5); | ||
| 413 | has 'center' => (is => 'ro', isa => 'Bool', default => 1); | ||
| 414 | has 'scale' => (is => 'ro', isa => 'Bool', default => 1); | ||
| 415 | has 'beta_initializer' => (is => 'ro', isa => 'Initializer', default => 'zeros'); | ||
| 416 | has [qw/gamma_initializer | ||
| 417 | running_mean_initializer | ||
| 418 | running_variance_initializer | ||
| 419 | /] => (is => 'ro', isa => 'Initializer', default => 'ones'); | ||
| 420 | has 'in_channels' => (is => 'ro', isa => 'DimSize', default => 0); | ||
| 421 | has [qw/_kwargs | ||
| 422 | gamma | ||
| 423 | beta | ||
| 424 | running_mean | ||
| 425 | running_var/] => (is => 'rw', init_arg => undef); | ||
| 426 | |||
| 427 | sub BUILD | ||
| 428 | { | ||
| 429 | my $self = shift; | ||
| 430 | $self->_kwargs({ | ||
| 431 | axis => $self->axis, | ||
| 432 | eps => $self->epsilon, | ||
| 433 | momentum => $self->momentum, | ||
| 434 | fix_gamma => $self->scale ? 0 : 1 | ||
| 435 | }); | ||
| 436 | |||
| 437 | $self->gamma( | ||
| 438 | $self->params->get( | ||
| 439 | 'gamma', grad_req => $self->scale ? 'write' : 'null', | ||
| 440 | shape => [$self->in_channels], init => $self->gamma_initializer, | ||
| 441 | allow_deferred_init => 1, differentiable => $self->scale | ||
| 442 | ) | ||
| 443 | ); | ||
| 444 | $self->beta( | ||
| 445 | $self->params->get( | ||
| 446 | 'beta', grad_req => $self->center ? 'write' : 'null', | ||
| 447 | shape => [$self->in_channels], init => $self->beta_initializer, | ||
| 448 | allow_deferred_init => 1, differentiable => $self->center | ||
| 449 | ) | ||
| 450 | ); | ||
| 451 | $self->running_mean( | ||
| 452 | $self->params->get( | ||
| 453 | 'running_mean', grad_req => 'null', | ||
| 454 | shape => [$self->in_channels], init => $self->running_mean_initializer, | ||
| 455 | allow_deferred_init => 1, differentiable => 0 | ||
| 456 | ) | ||
| 457 | ); | ||
| 458 | $self->running_var( | ||
| 459 | $self->params->get( | ||
| 460 | 'running_var', grad_req => $self->center ? 'write' : 'null', | ||
| 461 | shape => [$self->in_channels], init => $self->running_variance_initializer, | ||
| 462 | allow_deferred_init => 1, differentiable => 0 | ||
| 463 | ) | ||
| 464 | ); | ||
| 465 | } | ||
| 466 | |||
| 467 | method hybrid_forward( | ||
| 468 | GluonClass $F, GluonInput $x, | ||
| 469 | GluonInput :$gamma, GluonInput :$beta, | ||
| 470 | GluonInput :$running_mean, GluonInput :$running_var | ||
| 471 | ) | ||
| 472 | { | ||
| 473 | return $F->BatchNorm( | ||
| 474 | $x, $gamma, $beta, $running_mean, $running_var, | ||
| 475 | name =>'fwd', %{ $self->_kwargs } | ||
| 476 | ); | ||
| 477 | } | ||
| 478 | |||
| 479 | use overload '""' => sub { | ||
| 480 | my $self = shift; | ||
| 481 | my $f = "%s(%s".($self->in_channels ? ", in_channels=".$self->in_channels : '').')'; | ||
| 482 | my $content = join(", ", map { join('=', $_, $self->_kwargs->{$_}) } keys %{ $self->_kwargs }); | ||
| 483 | return sprintf($f, $self->_class_name, $content); | ||
| 484 | }; | ||
| 485 | |||
| 486 | __PACKAGE__->register('AI::MXNet::Gluon::NN'); | ||
| 487 | |||
| 488 | package AI::MXNet::Gluon::NN::Embedding; | ||
| 489 | use AI::MXNet::Gluon::Mouse; | ||
| 490 | extends 'AI::MXNet::Gluon::HybridBlock'; | ||
| 491 | |||
| 492 | =head1 NAME | ||
| 493 | |||
| 494 | AI::MXNet::Gluon::NN::Embedding | ||
| 495 | =cut | ||
| 496 | |||
| 497 | =head1 DESCRIPTION | ||
| 498 | |||
| 499 | Turns non-negative integers (indexes/tokens) into dense vectors | ||
| 500 | of fixed size. eg. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]] | ||
| 501 | |||
| 502 | |||
| 503 | Parameters | ||
| 504 | ---------- | ||
| 505 | input_dim : int | ||
| 506 | Size of the vocabulary, i.e. maximum integer index + 1. | ||
| 507 | output_dim : int | ||
| 508 | Dimension of the dense embedding. | ||
| 509 | dtype : str or np.dtype, default 'float32' | ||
| 510 | Data type of output embeddings. | ||
| 511 | weight_initializer : Initializer | ||
| 512 | Initializer for the `embeddings` matrix. | ||
| 513 | sparse_grad: bool | ||
| 514 | If True, gradient w.r.t. weight will be a 'row_sparse' NDArray. | ||
| 515 | =cut | ||
| 516 | |||
| 517 | has [qw/input_dim | ||
| 518 | output_dim/] => (is => 'ro', isa => 'DimSize', required => 1); | ||
| 519 | has 'dtype' => (is => 'ro', isa => 'Dtype', default => 'float32'); | ||
| 520 | has 'weight_initalizer' => (is => 'ro', isa => 'Maybe[Initializer]'); | ||
| 521 | has 'sparse_grad' => (is => 'ro', isa => 'Bool', default => 0); | ||
| 522 | has [qw/_kwargs weight/] => (is => 'rw', init_arg => undef); | ||
| 523 | method python_constructor_arguments() | ||
| 524 | { | ||
| 525 | ['input_dim', 'output_dim']; | ||
| 526 | } | ||
| 527 | |||
| 528 | sub BUILD | ||
| 529 | { | ||
| 530 | my $self = shift; | ||
| 531 | $self->_kwargs({ | ||
| 532 | input_dim => $self->input_dim, | ||
| 533 | output_dim => $self->output_dim, | ||
| 534 | dtype => $self->dtype, | ||
| 535 | sparse_grad => $self->sparse_grad | ||
| 536 | }); | ||
| 537 | $self->weight( | ||
| 538 | $self->params->get( | ||
| 539 | 'weight', | ||
| 540 | shape => [$self->input_dim, $self->output_dim], | ||
| 541 | init => $self->weight_initializer, | ||
| 542 | allow_deferred_init => 1, | ||
| 543 | dtype => $self->dtype, | ||
| 544 | grad_stype => ($self->sparse_grad ? 'row_sparse' : 'default') | ||
| 545 | ) | ||
| 546 | ); | ||
| 547 | } | ||
| 548 | |||
| 549 | method hybrid_forward(GluonClass $F, GluonInput $x, GluonInput :$weight) | ||
| 550 | { | ||
| 551 | return $F->Embedding($x, $weight, name => 'fwd', %{ $self->_kwargs }); | ||
| 552 | } | ||
| 553 | |||
| 554 | use overload '""' => sub { | ||
| 555 | my $self = shift; | ||
| 556 | "${\ $self->_class_name }(${\ $self->input_dim } -> ${\ $self->output_dim }, ${\ $self->dtype })"; | ||
| 557 | }; | ||
| 558 | |||
| 559 | __PACKAGE__->register('AI::MXNet::Gluon::NN'); | ||
| 560 | |||
| 561 | package AI::MXNet::Gluon::NN::Flatten; | ||
| 562 | use AI::MXNet::Gluon::Mouse; | ||
| 563 | extends 'AI::MXNet::Gluon::HybridBlock'; | ||
| 564 | |||
| 565 | =head1 NAME | ||
| 566 | |||
| 567 | AI::MXNet::Gluon::NN::Flatten | ||
| 568 | =cut | ||
| 569 | |||
| 570 | =head1 DESCRIPTION | ||
| 571 | |||
| 572 | Flattens the input to two dimensional. | ||
| 573 | |||
| 574 | Input shape: | ||
| 575 | Arbitrary shape `(N, a, b, c, ...)` | ||
| 576 | |||
| 577 | Output shape: | ||
| 578 | 2D tensor with shape: `(N, a*b*c...)` | ||
| 579 | =cut | ||
| 580 | |||
| 581 | method hybrid_forward(GluonClass $F, GluonInput $x) | ||
| 582 | { | ||
| 583 | return $x->reshape([0, -1]); | ||
| 584 | } | ||
| 585 | |||
| 586 | use overload '""' => sub { shift->_class_name }; | ||
| 587 | |||
| 588 | __PACKAGE__->register('AI::MXNet::Gluon::NN'); | ||
| 589 | |||
| 590 | package AI::MXNet::Gluon::NN::InstanceNorm; | ||
| 591 | use AI::MXNet::Gluon::Mouse; | ||
| 592 | extends 'AI::MXNet::Gluon::HybridBlock'; | ||
| 593 | |||
| 594 | =head1 NAME | ||
| 595 | |||
| 596 | AI::MXNet::Gluon::NN::InstanceNorm - Applies instance normalization to the n-dimensional input array. | ||
| 597 | =cut | ||
| 598 | |||
| 599 | =head1 DESCRIPTION | ||
| 600 | |||
| 601 | Applies instance normalization to the n-dimensional input array. | ||
| 602 | This operator takes an n-dimensional input array where (n>2) and normalizes | ||
| 603 | the input using the following formula: | ||
| 604 | |||
| 605 | Parameters | ||
| 606 | ---------- | ||
| 607 | axis : int, default 1 | ||
| 608 | The axis that will be excluded in the normalization process. This is typically the channels | ||
| 609 | (C) axis. For instance, after a `Conv2D` layer with `layout='NCHW'`, | ||
| 610 | set `axis=1` in `InstanceNorm`. If `layout='NHWC'`, then set `axis=3`. Data will be | ||
| 611 | normalized along axes excluding the first axis and the axis given. | ||
| 612 | epsilon: float, default 1e-5 | ||
| 613 | Small float added to variance to avoid dividing by zero. | ||
| 614 | center: bool, default True | ||
| 615 | If True, add offset of `beta` to normalized tensor. | ||
| 616 | If False, `beta` is ignored. | ||
| 617 | scale: bool, default True | ||
| 618 | If True, multiply by `gamma`. If False, `gamma` is not used. | ||
| 619 | When the next layer is linear (also e.g. `nn.relu`), | ||
| 620 | this can be disabled since the scaling | ||
| 621 | will be done by the next layer. | ||
| 622 | beta_initializer: str or `Initializer`, default 'zeros' | ||
| 623 | Initializer for the beta weight. | ||
| 624 | gamma_initializer: str or `Initializer`, default 'ones' | ||
| 625 | Initializer for the gamma weight. | ||
| 626 | in_channels : int, default 0 | ||
| 627 | Number of channels (feature maps) in input data. If not specified, | ||
| 628 | initialization will be deferred to the first time `forward` is called | ||
| 629 | and `in_channels` will be inferred from the shape of input data. | ||
| 630 | |||
| 631 | References | ||
| 632 | ---------- | ||
| 633 | Instance Normalization: The Missing Ingredient for Fast Stylization | ||
| 634 | <https://arxiv.org/abs/1607.08022> | ||
| 635 | |||
| 636 | Examples | ||
| 637 | -------- | ||
| 638 | >>> # Input of shape (2,1,2) | ||
| 639 | >>> $x = mx->nd->array([[[ 1.1, 2.2]], | ||
| 640 | ... [[ 3.3, 4.4]]]); | ||
| 641 | >>> $layer = nn->InstanceNorm() | ||
| 642 | >>> $layer->initialize(ctx=>mx->cpu(0)) | ||
| 643 | >>> $layer->($x) | ||
| 644 | [[[-0.99998355 0.99998331]] | ||
| 645 | [[-0.99998319 0.99998361]]] | ||
| 646 | <NDArray 2x1x2 @cpu(0)> | ||
| 647 | =cut | ||
| 648 | |||
| 649 | has 'axis' => (is => 'ro', isa => 'Int', default => 1); | ||
| 650 | has 'epsilon' => (is => 'ro', isa => 'Num', default => 1e-5); | ||
| 651 | has 'center' => (is => 'ro', isa => 'Bool', default => 1); | ||
| 652 | has 'scale' => (is => 'ro', isa => 'Bool', default => 0); | ||
| 653 | has 'beta_initializer' => (is => 'rw', isa => 'Initializer', default => 'zeros'); | ||
| 654 | has 'gamma_initializer' => (is => 'rw', isa => 'Initializer', default => 'ones'); | ||
| 655 | has 'in_channels' => (is => 'rw', isa => 'Int', default => 0); | ||
| 656 | has [qw/_kwargs | ||
| 657 | gamma beta/] => (is => 'rw', init_arg => undef); | ||
| 658 | method python_constructor_arguments() | ||
| 659 | { | ||
| 660 | [qw/axis epsilon center scale beta_initializer gamma_initializer in_channels/]; | ||
| 661 | } | ||
| 662 | |||
| 663 | |||
| 664 | sub BUILD | ||
| 665 | { | ||
| 666 | my $self = shift; | ||
| 667 | $self->_kwargs(Hash::Ordered->new(eps => $self->epsilon, axis => $self->axis, center => $self->center, scale => $self->scale)); | ||
| 668 | $self->gamma( | ||
| 669 | $self->params->get( | ||
| 670 | 'gamma', grad_req => $self->scale ? 'write' :'null', | ||
| 671 | shape => [$self->in_channels], init => $self->gamma_initializer, | ||
| 672 | allow_deferred_init => 1 | ||
| 673 | ) | ||
| 674 | ); | ||
| 675 | $self->beta( | ||
| 676 | $self->params->get( | ||
| 677 | 'beta', grad_req => $self->scale ? 'write' :'null', | ||
| 678 | shape => [$self->in_channels], init => $self->beta_initializer, | ||
| 679 | allow_deferred_init => 1 | ||
| 680 | ) | ||
| 681 | ); | ||
| 682 | } | ||
| 683 | |||
| 684 | method hybrid_forward(GluonClass $F, GluonInput $x, GluonInput :$gamma, GluonInput :$beta) | ||
| 685 | { | ||
| 686 | if($self->axis == 1) | ||
| 687 | { | ||
| 688 | return $F->InstanceNorm( | ||
| 689 | $x, $gamma, $beta, | ||
| 690 | name=>'fwd', eps=>$self->epsilon | ||
| 691 | ); | ||
| 692 | } | ||
| 693 | $x = $x->swapaxes(1, $self->axis); | ||
| 694 | return $F->InstanceNorm( | ||
| 695 | $x, $gamma, $beta, name=>'fwd', | ||
| 696 | eps => $self->epsilon | ||
| 697 | )->swapaxes(1, $self->axis); | ||
| 698 | } | ||
| 699 | |||
| 700 | use overload '""' => sub { | ||
| 701 | my $self = shift; | ||
| 702 | my $in_channels = ", in_channels=${\ $self->in_channels }"; | ||
| 703 | my $content = join(', ', map { join('=', $_, $self->_kwargs->get($_)) } $self->_kwargs->keys); | ||
| 704 | return "${\ $self->_class_name }($content, $in_channels)"; | ||
| 705 | }; | ||
| 706 | |||
| 707 | __PACKAGE__->register('AI::MXNet::Gluon::NN'); | ||
| 708 | |||
| 709 | package AI::MXNet::Gluon::NN::LayerNorm; | ||
| 710 | use AI::MXNet::Gluon::Mouse; | ||
| 711 | extends 'AI::MXNet::Gluon::HybridBlock'; | ||
| 712 | |||
| 713 | =head1 NAME | ||
| 714 | |||
| 715 | AI::MXNet::Gluon::NN::LayerNorm - Applies layer normalization to the n-dimensional input array. | ||
| 716 | =cut | ||
| 717 | |||
| 718 | =head1 DESCRIPTION | ||
| 719 | |||
| 720 | Applies layer normalization to the n-dimensional input array. | ||
| 721 | This operator takes an n-dimensional input array and normalizes | ||
| 722 | the input using the given axis: | ||
| 723 | |||
| 724 | Parameters | ||
| 725 | ---------- | ||
| 726 | axis : int, default -1 | ||
| 727 | The axis that should be normalized. This is typically the axis of the channels. | ||
| 728 | epsilon: float, default 1e-5 | ||
| 729 | Small float added to variance to avoid dividing by zero. | ||
| 730 | center: bool, default True | ||
| 731 | If True, add offset of `beta` to normalized tensor. | ||
| 732 | If False, `beta` is ignored. | ||
| 733 | scale: bool, default True | ||
| 734 | If True, multiply by `gamma`. If False, `gamma` is not used. | ||
| 735 | beta_initializer: str or `Initializer`, default 'zeros' | ||
| 736 | Initializer for the beta weight. | ||
| 737 | gamma_initializer: str or `Initializer`, default 'ones' | ||
| 738 | Initializer for the gamma weight. | ||
| 739 | in_channels : int, default 0 | ||
| 740 | Number of channels (feature maps) in input data. If not specified, | ||
| 741 | initialization will be deferred to the first time `forward` is called | ||
| 742 | and `in_channels` will be inferred from the shape of input data. | ||
| 743 | |||
| 744 | References | ||
| 745 | ---------- | ||
| 746 | `Layer Normalization | ||
| 747 | <https://arxiv.org/pdf/1607.06450.pdf>`_ | ||
| 748 | |||
| 749 | Examples | ||
| 750 | -------- | ||
| 751 | >>> # Input of shape (2, 5) | ||
| 752 | >>> $x = mx->nd->array([[1, 2, 3, 4, 5], [1, 1, 2, 2, 2]]) | ||
| 753 | >>> # Layer normalization is calculated with the above formula | ||
| 754 | >>> $layer = nn->LayerNorm() | ||
| 755 | >>> $layer->initialize(ctx=>mx->cpu(0)) | ||
| 756 | >>> $layer->($x) | ||
| 757 | [[-1.41421 -0.707105 0. 0.707105 1.41421 ] | ||
| 758 | [-1.2247195 -1.2247195 0.81647956 0.81647956 0.81647956]] | ||
| 759 | <NDArray 2x5 @cpu(0)> | ||
| 760 | =cut | ||
| 761 | |||
| 762 | has 'axis' => (is => 'ro', isa => 'Int', default => -1); | ||
| 763 | has 'epsilon' => (is => 'ro', isa => 'Num', default => 1e-5); | ||
| 764 | has 'center' => (is => 'ro', isa => 'Bool', default => 1); | ||
| 765 | has 'scale' => (is => 'ro', isa => 'Bool', default => 0); | ||
| 766 | has 'beta_initializer' => (is => 'rw', isa => 'Initializer', default => 'zeros'); | ||
| 767 | has 'gamma_initializer' => (is => 'rw', isa => 'Initializer', default => 'ones'); | ||
| 768 | has 'in_channels' => (is => 'rw', isa => 'Int', default => 0); | ||
| 769 | has [qw/_kwargs | ||
| 770 | gamma beta/] => (is => 'rw', init_arg => undef); | ||
| 771 | method python_constructor_arguments() | ||
| 772 | { | ||
| 773 | [qw/axis epsilon center scale beta_initializer gamma_initializer in_channels/]; | ||
| 774 | } | ||
| 775 | |||
| 776 | sub BUILD | ||
| 777 | { | ||
| 778 | my $self = shift; | ||
| 779 | $self->_kwargs(Hash::Ordered->new(eps => $self->epsilon, axis => $self->axis, center => $self->center, scale => $self->scale)); | ||
| 780 | $self->gamma( | ||
| 781 | $self->params->get( | ||
| 782 | 'gamma', grad_req => $self->scale ? 'write' :'null', | ||
| 783 | shape => [$self->in_channels], init => $self->gamma_initializer, | ||
| 784 | allow_deferred_init => 1 | ||
| 785 | ) | ||
| 786 | ); | ||
| 787 | $self->beta( | ||
| 788 | $self->params->get( | ||
| 789 | 'beta', grad_req => $self->scale ? 'write' :'null', | ||
| 790 | shape => [$self->in_channels], init => $self->beta_initializer, | ||
| 791 | allow_deferred_init => 1 | ||
| 792 | ) | ||
| 793 | ); | ||
| 794 | } | ||
| 795 | |||
| 796 | method hybrid_forward(GluonClass $F, GluonInput $x, GluonInput :$gamma, GluonInput :$beta) | ||
| 797 | { | ||
| 798 | return $F->LayerNorm( | ||
| 799 | $x, $gamma, $beta, | ||
| 800 | eps => $self->epsilon, axis => $self->axis | ||
| 801 | ); | ||
| 802 | } | ||
| 803 | |||
| 804 | use overload '""' => sub { | ||
| 805 | my $self = shift; | ||
| 806 | my $in_channels = ", in_channels=${\ $self->in_channels }"; | ||
| 807 | my $content = join(', ', map { join('=', $_, $self->_kwargs->get($_)) } $self->_kwargs->keys); | ||
| 808 | return "${\ $self->_class_name }($content, $in_channels)"; | ||
| 809 | }; | ||
| 810 | |||
| 811 | __PACKAGE__->register('AI::MXNet::Gluon::NN'); | ||
| 812 | |||
| 813 | package AI::MXNet::Gluon::NN::Lambda; | ||
| 814 | use AI::MXNet::Gluon::Mouse; | ||
| 815 | extends 'AI::MXNet::Gluon::Block'; | ||
| 816 | |||
| 817 | =head1 NAME | ||
| 818 | |||
| 819 | AI::MXNet::Gluon::NN::Lambda - Wraps an operator or an expression as a Block object. | ||
| 820 | =cut | ||
| 821 | |||
| 822 | =head1 DESCRIPTION | ||
| 823 | |||
| 824 | Wraps an operator or an expression as a Block object. | ||
| 825 | |||
| 826 | Parameters | ||
| 827 | ---------- | ||
| 828 | function : str or sub | ||
| 829 | Function used in lambda must be one of the following: | ||
| 830 | 1) the name of an operator that is available in ndarray. For example | ||
| 831 | |||
| 832 | $block = nn->Lambda('tanh') | ||
| 833 | |||
| 834 | 2) a sub. For example | ||
| 835 | |||
| 836 | $block = nn->Lambda(sub { my $x = shift; nd->LeakyReLU($x, slope=>0.1) }); | ||
| 837 | =cut | ||
| 838 | |||
| 839 | has '_func_impl' => (is => 'rw', init_arg => 'function', isa => 'Str|CodeRef', required => 1); | ||
| 840 | has '_func_name' => (is => 'rw', init_arg => undef, default => 'custom_sub'); | ||
| 841 | method python_constructor_arguments() { ['function'] } | ||
| 842 | |||
| 843 | sub BUILD | ||
| 844 | { | ||
| 845 | my $self = shift; | ||
| 846 | if(not ref $self->_func_impl) | ||
| 847 | { | ||
| 848 | confess("Function name ${\ $self->_func_impl } is not found in ndarray.") | ||
| 849 | unless AI::MXNet::NDArray->can($self->_func_impl); | ||
| 850 | $self->_func_name($self->_func_impl); | ||
| 851 | my $f = $self->_func_impl; | ||
| 852 | $self->_func_impl(sub { return AI::MXNet::NDArray->$f(@_) }); | ||
| 853 | } | ||
| 854 | } | ||
| 855 | |||
| 856 | method forward(@args) | ||
| 857 | { | ||
| 858 | return $self->_func_impl->(@args); | ||
| 859 | } | ||
| 860 | |||
| 861 | use overload '""' => sub { | ||
| 862 | my $self = shift; | ||
| 863 | return "${\ $self->_class_name }(${\ $self->_func_name })"; | ||
| 864 | }; | ||
| 865 | |||
| 866 | __PACKAGE__->register('AI::MXNet::Gluon::NN'); | ||
| 867 | |||
| 868 | package AI::MXNet::Gluon::NN::HybridLambda; | ||
| 869 | use AI::MXNet::Gluon::Mouse; | ||
| 870 | extends 'AI::MXNet::Gluon::HybridBlock'; | ||
| 871 | |||
| 872 | =head1 NAME | ||
| 873 | |||
| 874 | AI::MXNet::Gluon::NN::HybridLambda - Wraps an operator or an expression as a HybridBlock object. | ||
| 875 | =cut | ||
| 876 | |||
| 877 | =head1 DESCRIPTION | ||
| 878 | |||
| 879 | Wraps an operator or an expression as a HybridBlock object. | ||
| 880 | |||
| 881 | Parameters | ||
| 882 | ---------- | ||
| 883 | function : str or sub | ||
| 884 | Function used in lambda must be one of the following: | ||
| 885 | 1) the name of an operator that is available in symbol and ndarray. For example | ||
| 886 | |||
| 887 | $block = nn->Lambda('tanh') | ||
| 888 | |||
| 889 | 2) a sub. For example | ||
| 890 | |||
| 891 | $block = nn->Lambda(sub { my $F = shift; $F->LeakyReLU($x, slope=>0.1) }); | ||
| 892 | =cut | ||
| 893 | |||
| 894 | has '_func_impl' => (is => 'rw', init_arg => 'function', isa => 'Str|CodeRef', required => 1); | ||
| 895 | has '_func_name' => (is => 'rw', init_arg => undef, default => 'custom_sub'); | ||
| 896 | method python_constructor_arguments() { ['function'] } | ||
| 897 | |||
| 898 | sub BUILD | ||
| 899 | { | ||
| 900 | my $self = shift; | ||
| 901 | if(not ref $self->_func_impl) | ||
| 902 | { | ||
| 903 | confess("Function name ${\ $self->_func_impl } is not found in ndarray.") | ||
| 904 | unless AI::MXNet::NDArray->can($self->_func_impl) or AI::MXNet::Symbol->can($self->_func_impl); | ||
| 905 | $self->_func_name($self->_func_impl); | ||
| 906 | my $f = $self->_func_impl; | ||
| 907 | $self->_func_impl(sub { my $F = shift; return $F->$f(@_) }); | ||
| 908 | } | ||
| 909 | } | ||
| 910 | |||
| 911 | method hybrid_forward(@args) | ||
| 912 | { | ||
| 913 | return $self->_func_impl->(@args); | ||
| 914 | } | ||
| 915 | |||
| 916 | use overload '""' => sub { | ||
| 917 | my $self = shift; | ||
| 918 | return "${\ $self->_class_name }(${\ $self->_func_name })"; | ||
| 919 | }; | ||
| 920 | |||
| 921 | __PACKAGE__->register('AI::MXNet::Gluon::NN'); | ||
| 922 | |||
| 923 | 1; |