| 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::RNN::Layer; | ||
| 21 | use AI::MXNet::Function::Parameters; | ||
| 22 | use AI::MXNet::Gluon::Mouse; | ||
| 23 | use AI::MXNet::Base; | ||
| 24 | extends 'AI::MXNet::Gluon::HybridBlock'; | ||
| 25 | |||
| 26 | has 'hidden_size' => (is => 'rw', isa => 'Int'); | ||
| 27 | has 'num_layers' => (is => 'rw', isa => 'Int'); | ||
| 28 | has 'layout' => (is => 'rw', isa => 'Str'); | ||
| 29 | has 'dropout' => (is => 'rw', isa => 'Num'); | ||
| 30 | has 'bidirectional' => (is => 'rw', isa => 'Bool'); | ||
| 31 | has 'input_size' => (is => 'rw', isa => 'Int', default => 0); | ||
| 32 | has 'projection_size' => (is => 'rw', isa => 'Maybe[Int]'); | ||
| 33 | has [qw/lstm_state_clip_min | ||
| 34 | lstm_state_clip_max/] => (is => 'rw', isa => 'Maybe[Num]'); | ||
| 35 | has 'lstm_state_clip_nan' => (is => 'rw', isa => 'Bool', default => 0); | ||
| 36 | has [qw/ | ||
| 37 | i2h_weight_initializer | ||
| 38 | h2h_weight_initializer | ||
| 39 | i2h_bias_initializer | ||
| 40 | h2h_bias_initializer | ||
| 41 | h2r_weight_initializer | ||
| 42 | /] => (is => 'rw', isa => 'Maybe[Initializer]'); | ||
| 43 | has 'mode' => (is => 'rw', isa => 'Str'); | ||
| 44 | has [qw/dir gates | ||
| 45 | unfused/] => (is => 'rw', init_arg => undef); | ||
| 46 | |||
| 47 | method python_constructor_arguments() | ||
| 48 | { | ||
| 49 | [qw/ | ||
| 50 | hidden_size num_layers layout | ||
| 51 | dropout bidirectional input_size | ||
| 52 | i2h_weight_initializer h2h_weight_initializer | ||
| 53 | i2h_bias_initializer h2h_bias_initializer | ||
| 54 | mode projection_size h2r_weight_initializer | ||
| 55 | lstm_state_clip_min lstm_state_clip_max lstm_state_clip_nan | ||
| 56 | /]; | ||
| 57 | } | ||
| 58 | |||
| 59 | sub BUILD | ||
| 60 | { | ||
| 61 | my $self = shift; | ||
| 62 | assert( | ||
| 63 | ($self->layout eq 'TNC' or $self->layout eq 'NTC'), | ||
| 64 | "Invalid layout [${\ $self->layout }]; must be one of ['TNC' or 'NTC']" | ||
| 65 | ); | ||
| 66 | $self->dir($self->bidirectional ? 2 : 1); | ||
| 67 | $self->gates({qw/rnn_relu 1 rnn_tanh 1 lstm 4 gru 3/}->{$self->mode}); | ||
| 68 | my ($ng, $ni, $nh) = ($self->gates, $self->input_size, $self->hidden_size); | ||
| 69 | if(not $self->projection_size) | ||
| 70 | { | ||
| 71 | for my $i (0..$self->num_layers-1) | ||
| 72 | { | ||
| 73 | for my $j ($self->dir == 2 ? ('l', 'r') : ('l')) | ||
| 74 | { | ||
| 75 | $self->_register_param( | ||
| 76 | "$j${i}_i2h_weight", [$ng*$nh, $ni], | ||
| 77 | $self->i2h_weight_initializer | ||
| 78 | ); | ||
| 79 | $self->_register_param( | ||
| 80 | "$j${i}_h2h_weight", [$ng*$nh, $nh], | ||
| 81 | $self->h2h_weight_initializer | ||
| 82 | ); | ||
| 83 | $self->_register_param( | ||
| 84 | "$j${i}_i2h_bias", [$ng*$nh], | ||
| 85 | $self->i2h_bias_initializer, | ||
| 86 | ); | ||
| 87 | $self->_register_param( | ||
| 88 | "$j${i}_h2h_bias", [$ng*$nh], | ||
| 89 | $self->h2h_bias_initializer, | ||
| 90 | ); | ||
| 91 | } | ||
| 92 | $ni = $nh * $self->dir; | ||
| 93 | } | ||
| 94 | } | ||
| 95 | else | ||
| 96 | { | ||
| 97 | my $np = $self->projection_size; | ||
| 98 | for my $i (0..$self->num_layers-1) | ||
| 99 | { | ||
| 100 | for my $j ($self->dir == 2 ? ('l', 'r') : ('l')) | ||
| 101 | { | ||
| 102 | $self->_register_param( | ||
| 103 | "$j${i}_i2h_weight", [$ng*$nh, $ni], | ||
| 104 | $self->i2h_weight_initializer | ||
| 105 | ); | ||
| 106 | $self->_register_param( | ||
| 107 | "$j${i}_h2h_weight", [$ng*$nh, $np], | ||
| 108 | $self->h2h_weight_initializer | ||
| 109 | ); | ||
| 110 | $self->_register_param( | ||
| 111 | "$j${i}_i2h_bias", [$ng*$nh], | ||
| 112 | $self->i2h_bias_initializer, | ||
| 113 | ); | ||
| 114 | $self->_register_param( | ||
| 115 | "$j${i}_h2h_bias", [$ng*$nh], | ||
| 116 | $self->h2h_bias_initializer, | ||
| 117 | ); | ||
| 118 | $self->_register_param( | ||
| 119 | "$j${i}_h2r_weight", [$np, $nh], | ||
| 120 | $self->h2r_weight_initializer, | ||
| 121 | ); | ||
| 122 | } | ||
| 123 | $ni = $np * $self->dir; | ||
| 124 | } | ||
| 125 | } | ||
| 126 | } | ||
| 127 | |||
| 128 | method _register_param($name, $shape, $init) | ||
| 129 | { | ||
| 130 | my $p = $self->params->get( | ||
| 131 | $name, shape=>$shape, init=>$init, | ||
| 132 | allow_deferred_init=>1 | ||
| 133 | ); | ||
| 134 | $self->$name($p); | ||
| 135 | return $p; | ||
| 136 | } | ||
| 137 | |||
| 138 | use overload '""' => sub { | ||
| 139 | my $self = shift; | ||
| 140 | my $name = $self->_class_name; | ||
| 141 | my $mapping = $self->input_size ? $self->input_size.' -> '.$self->hidden_size : $self->hidden_size; | ||
| 142 | my $s = "$name($mapping, ${\ $self->layout }"; | ||
| 143 | if($self->num_layers != 1) | ||
| 144 | { | ||
| 145 | $s .= ', num_layers='.$self->num_layers; | ||
| 146 | } | ||
| 147 | if($self->dropout != 0) | ||
| 148 | { | ||
| 149 | $s .= ', dropout='.$self->dropout; | ||
| 150 | } | ||
| 151 | if($self->dir == 2) | ||
| 152 | { | ||
| 153 | $s .= ', bidirectional'; | ||
| 154 | } | ||
| 155 | $s .= ')'; | ||
| 156 | return $s; | ||
| 157 | }; | ||
| 158 | |||
| 159 | method _collect_params_with_prefix(Str $prefix='') | ||
| 160 | { | ||
| 161 | $prefix .= '.' if($prefix); | ||
| 162 | my $pattern = qr/(l|r)(\d+)_(i2h|h2h)_(weight|bias)$/; | ||
| 163 | my $convert_key = sub { my ($m, $bidirectional) = @_; | ||
| 164 | my ($d, $l, $g, $t) = @$m; | ||
| 165 | if($bidirectional) | ||
| 166 | { | ||
| 167 | return "_unfused.$l.${d}_cell.${g}_$t"; | ||
| 168 | } | ||
| 169 | else | ||
| 170 | { | ||
| 171 | return "_unfused.$l.${g}_$t"; | ||
| 172 | } | ||
| 173 | }; | ||
| 174 | my $bidirectional = 0; | ||
| 175 | my %params = %{ $self->_reg_params }; | ||
| 176 | for my $k (keys %params) | ||
| 177 | { | ||
| 178 | $k =~ $pattern; | ||
| 179 | $bidirectional = 1 if $1 and $1 eq 'r'; | ||
| 180 | } | ||
| 181 | my %ret; | ||
| 182 | for my $k (keys %params) | ||
| 183 | { | ||
| 184 | $k =~ $pattern; | ||
| 185 | $ret{ $prefix . $convert_key->([$1, $2, $3, $4], $bidirectional) } = $params{$k}; | ||
| 186 | } | ||
| 187 | my $iter = $self->_children->iterator; | ||
| 188 | while(my ($name, $child) = $iter->()) | ||
| 189 | { | ||
| 190 | %ret = (%ret, %{ $child->_collect_params_with_prefix("$prefix$name") }); | ||
| 191 | } | ||
| 192 | return \%ret; | ||
| 193 | } | ||
| 194 | |||
| 195 | method state_info($batch_size=0) | ||
| 196 | { | ||
| 197 | confess('NotImplementedError'); | ||
| 198 | } | ||
| 199 | |||
| 200 | |||
| 201 | method _unfuse() | ||
| 202 | { | ||
| 203 | assert((not $self->projection_size), "_unfuse does not support projection layer yet!"); | ||
| 204 | assert( | ||
| 205 | (not $self->lstm_state_clip_min and not $self->lstm_state_clip_max), | ||
| 206 | "_unfuse does not support state clipping yet!" | ||
| 207 | ); | ||
| 208 | my $get_cell = { | ||
| 209 | rnn_relu => sub { | ||
| 210 | my %kwargs = @_; | ||
| 211 | AI::MXNet::Gluon::RNN::RNNCell->new( | ||
| 212 | $self->hidden_size, | ||
| 213 | activation => 'relu', | ||
| 214 | %kwargs | ||
| 215 | ) | ||
| 216 | }, | ||
| 217 | rnn_tanh => sub { | ||
| 218 | my %kwargs = @_; | ||
| 219 | AI::MXNet::Gluon::RNN::RNNCell->new( | ||
| 220 | $self->hidden_size, | ||
| 221 | activation => 'tanh', | ||
| 222 | %kwargs | ||
| 223 | ) | ||
| 224 | }, | ||
| 225 | lstm => sub { | ||
| 226 | my %kwargs = @_; | ||
| 227 | AI::MXNet::Gluon::RNN::LSTMCell->new( | ||
| 228 | $self->hidden_size, | ||
| 229 | %kwargs | ||
| 230 | ) | ||
| 231 | }, | ||
| 232 | gru => sub { | ||
| 233 | my %kwargs = @_; | ||
| 234 | AI::MXNet::Gluon::RNN::GRUCell->new( | ||
| 235 | $self->hidden_size, | ||
| 236 | %kwargs | ||
| 237 | ) | ||
| 238 | } | ||
| 239 | }->{$self->mode}; | ||
| 240 | my $stack = AI::MXNet::Gluon::RNN::SequentialRNNCell->new(prefix => $self->prefix, params => $self->params); | ||
| 241 | $stack->name_scope(sub { | ||
| 242 | my $ni = $self->input_size; | ||
| 243 | for my $i (0..$self->num_layers-1) | ||
| 244 | { | ||
| 245 | my %kwargs = ( | ||
| 246 | input_size => $ni, | ||
| 247 | i2h_weight_initializer => $self->i2h_weight_initializer, | ||
| 248 | h2h_weight_initializer => $self->h2h_weight_initializer, | ||
| 249 | i2h_bias_initializer => $self->i2h_bias_initializer, | ||
| 250 | h2h_bias_initializer => $self->h2h_bias_initializer | ||
| 251 | ); | ||
| 252 | if($self->dir == 2) | ||
| 253 | { | ||
| 254 | $stack->add( | ||
| 255 | AI::MXNet::Gluon::RNN::BidirectionalCell->new( | ||
| 256 | $get_cell->(prefix=> "l${i}_", %kwargs), | ||
| 257 | $get_cell->(prefix=> "r${i}_", %kwargs), | ||
| 258 | ) | ||
| 259 | ); | ||
| 260 | } | ||
| 261 | else | ||
| 262 | { | ||
| 263 | $stack->add($get_cell->(prefix=> "l${i}_", %kwargs)); | ||
| 264 | } | ||
| 265 | if($self->dropout > 0 and $i != ($self->_num_layers - 1)) | ||
| 266 | { | ||
| 267 | $stack->add(AI::MXNet::Gluon::RNN::DropoutCell->new($self->dropout)); | ||
| 268 | } | ||
| 269 | $ni = $self->hidden_size * $self->dir; | ||
| 270 | } | ||
| 271 | }); | ||
| 272 | return $stack; | ||
| 273 | } | ||
| 274 | |||
| 275 | method begin_state( | ||
| 276 | $batch_size=0, | ||
| 277 | CodeRef :$func=sub { my %kwargs = @_; my $shape = delete $kwargs{shape}; AI::MXNet::NDArray->zeros($shape, %kwargs) }, | ||
| 278 | %kwargs | ||
| 279 | ) | ||
| 280 | { | ||
| 281 | my @states; | ||
| 282 | enumerate(sub { | ||
| 283 | my ($i, $info) = @_; | ||
| 284 | if(defined $info) | ||
| 285 | { | ||
| 286 | %$info = (%$info, %kwargs); | ||
| 287 | } | ||
| 288 | else | ||
| 289 | { | ||
| 290 | %$info = %kwargs; | ||
| 291 | } | ||
| 292 | push @states, $func->(name=> $self->prefix."h0_$i", %$info); | ||
| 293 | }, $self->state_info($batch_size)); | ||
| 294 | return \@states; | ||
| 295 | } | ||
| 296 | |||
| 297 | use Data::Dumper; | ||
| 298 | method hybrid_forward(GluonClass $F, GluonInput $inputs, @args) | ||
| 299 | { | ||
| 300 | my $states; | ||
| 301 | if(@args) | ||
| 302 | { | ||
| 303 | if(not defined $args[0] or ref $args[0]) | ||
| 304 | { | ||
| 305 | $states = shift(@args); | ||
| 306 | undef $states if(ref $states eq 'ARRAY' and not @$states); | ||
| 307 | } | ||
| 308 | } | ||
| 309 | use Data::Dumper; | ||
| 310 | |||
| 311 | my $batch_size; | ||
| 312 | if($F eq 'AI::MXNet::NDArray') | ||
| 313 | { | ||
| 314 | $batch_size = $inputs->shape->[index($self->layout, 'N')]; | ||
| 315 | } | ||
| 316 | my $skip_states = not defined $states; | ||
| 317 | if($skip_states) | ||
| 318 | { | ||
| 319 | if($F eq 'AI::MXNet::NDArray') | ||
| 320 | { | ||
| 321 | $states = $self->begin_state($batch_size, ctx=>$inputs->context, dtype=>$inputs->dtype); | ||
| 322 | } | ||
| 323 | else | ||
| 324 | { | ||
| 325 | $states = $self->begin_state(0, func=>sub { return AI::MXNet::Symbol->zeros(@_) }); | ||
| 326 | } | ||
| 327 | } | ||
| 328 | if(blessed $states and ($states->isa('AI::MXNet::NDArray') or $states->isa('AI::MXNet::Symbol'))) | ||
| 329 | { | ||
| 330 | $states = [$states]; | ||
| 331 | } | ||
| 332 | if($F eq 'AI::MXNet::NDArray') | ||
| 333 | { | ||
| 334 | for(zip($states, $self->state_info($batch_size))) | ||
| 335 | { | ||
| 336 | my ($state, $info) = @$_; | ||
| 337 | if(Dumper($state->shape) ne Dumper($info->{shape})) | ||
| 338 | { | ||
| 339 | my @state_shape = @{ $state->shape }; | ||
| 340 | confess("Invalid recurrent state shape. Expecting @{$info->{shape}}, got @state_shape."); | ||
| 341 | } | ||
| 342 | } | ||
| 343 | } | ||
| 344 | my $out = $self->_forward_kernel($F, $inputs, $states, @args); | ||
| 345 | return $skip_states ? $out->[0] : $out; | ||
| 346 | } | ||
| 347 | |||
| 348 | method _forward_kernel($F, $inputs, $states, %kwargs) | ||
| 349 | { | ||
| 350 | if($self->layout eq 'NTC') | ||
| 351 | { | ||
| 352 | $inputs = $F->swapaxes($inputs, dim1=>0, dim2=>1); | ||
| 353 | } | ||
| 354 | my @params; | ||
| 355 | if(not defined $self->projection_size) | ||
| 356 | { | ||
| 357 | for my $t ('weight', 'bias') | ||
| 358 | { | ||
| 359 | for my $l (0..$self->num_layers-1) | ||
| 360 | { | ||
| 361 | for my $d ($self->dir == 2 ? ('l', 'r') : ('l')) | ||
| 362 | { | ||
| 363 | for my $g ('i2h', 'h2h') | ||
| 364 | { | ||
| 365 | push @params, $kwargs{"$d${l}_${g}_$t"}->reshape([-1]); | ||
| 366 | } | ||
| 367 | } | ||
| 368 | } | ||
| 369 | } | ||
| 370 | } | ||
| 371 | else | ||
| 372 | { | ||
| 373 | for my $t ('weight', 'bias') | ||
| 374 | { | ||
| 375 | for my $l (0..$self->num_layers-1) | ||
| 376 | { | ||
| 377 | for my $d ($self->dir == 2 ? ('l', 'r') : ('l')) | ||
| 378 | { | ||
| 379 | for my $g ('i2h', 'h2h', 'h2r') | ||
| 380 | { | ||
| 381 | push @params, $kwargs{"$d${l}_${g}_$t"}->reshape([-1]) | ||
| 382 | unless($g eq 'h2r' and $t eq 'bias'); | ||
| 383 | } | ||
| 384 | } | ||
| 385 | } | ||
| 386 | } | ||
| 387 | } | ||
| 388 | my $params = $F->_rnn_param_concat(@params, dim=>0); | ||
| 389 | my $rnn = $F->RNN( | ||
| 390 | $inputs, $params, @{ $states }, { state_size => $self->hidden_size, | ||
| 391 | num_layers => $self->num_layers, bidirectional => $self->dir == 2 ? 1 : 0, | ||
| 392 | p => $self->dropout, state_outputs => 1, mode => $self->mode, | ||
| 393 | (defined $self->lstm_state_clip_min ? (lstm_state_clip_min=>$self->lstm_state_clip_min) : ()), | ||
| 394 | (defined $self->lstm_state_clip_max ? (lstm_state_clip_max=>$self->lstm_state_clip_max) : ()), | ||
| 395 | (defined $self->lstm_state_clip_nan ? (lstm_state_clip_nan=>$self->lstm_state_clip_nan) : ()) | ||
| 396 | }); | ||
| 397 | my $outputs; | ||
| 398 | my @rnn = @{$rnn}; | ||
| 399 | if($self->mode eq 'lstm') | ||
| 400 | { | ||
| 401 | ($outputs, $states) = ($rnn[0], [$rnn[1], $rnn[2]]); | ||
| 402 | } | ||
| 403 | else | ||
| 404 | { | ||
| 405 | ($outputs, $states) = ($rnn[0], [$rnn[1]]); | ||
| 406 | } | ||
| 407 | if($self->layout eq 'NTC') | ||
| 408 | { | ||
| 409 | $outputs = $outputs->swapaxes(dim1 => 0, dim2 => 1); | ||
| 410 | } | ||
| 411 | return [$outputs, $states]; | ||
| 412 | } | ||
| 413 | |||
| 414 | package AI::MXNet::Gluon::RNN::RNN; | ||
| 415 | |||
| 416 | =head1 NAME | ||
| 417 | |||
| 418 | AI::MXNet::Gluon::RNN::RNN | ||
| 419 | =cut | ||
| 420 | |||
| 421 | =head1 DESCRIPTION | ||
| 422 | |||
| 423 | Applies a multi-layer Elman RNN with `tanh` or `ReLU` non-linearity to an input sequence. | ||
| 424 | |||
| 425 | For each element in the input sequence, each layer computes the following | ||
| 426 | function: | ||
| 427 | |||
| 428 | .. math:: | ||
| 429 | h_t = \tanh(w_{ih} * x_t + b_{ih} + w_{hh} * h_{(t-1)} + b_{hh}) | ||
| 430 | |||
| 431 | where :math:`h_t` is the hidden state at time `t`, and :math:`x_t` is the hidden | ||
| 432 | state of the previous layer at time `t` or :math:`input_t` for the first layer. | ||
| 433 | If nonlinearity='relu', then `ReLU` is used instead of `tanh`. | ||
| 434 | |||
| 435 | Parameters | ||
| 436 | ---------- | ||
| 437 | hidden_size: int | ||
| 438 | The number of features in the hidden state h. | ||
| 439 | num_layers: int, default 1 | ||
| 440 | Number of recurrent layers. | ||
| 441 | activation: {'relu' or 'tanh'}, default 'tanh' | ||
| 442 | The activation function to use. | ||
| 443 | layout : str, default 'TNC' | ||
| 444 | The format of input and output tensors. T, N and C stand for | ||
| 445 | sequence length, batch size, and feature dimensions respectively. | ||
| 446 | dropout: float, default 0 | ||
| 447 | If non-zero, introduces a dropout layer on the outputs of each | ||
| 448 | RNN layer except the last layer. | ||
| 449 | bidirectional: bool, default False | ||
| 450 | If `True`, becomes a bidirectional RNN. | ||
| 451 | i2h_weight_initializer : str or Initializer | ||
| 452 | Initializer for the input weights matrix, used for the linear | ||
| 453 | transformation of the inputs. | ||
| 454 | h2h_weight_initializer : str or Initializer | ||
| 455 | Initializer for the recurrent weights matrix, used for the linear | ||
| 456 | transformation of the recurrent state. | ||
| 457 | i2h_bias_initializer : str or Initializer | ||
| 458 | Initializer for the bias vector. | ||
| 459 | h2h_bias_initializer : str or Initializer | ||
| 460 | Initializer for the bias vector. | ||
| 461 | input_size: int, default 0 | ||
| 462 | The number of expected features in the input x. | ||
| 463 | If not specified, it will be inferred from input. | ||
| 464 | prefix : str or None | ||
| 465 | Prefix of this `Block`. | ||
| 466 | params : ParameterDict or None | ||
| 467 | Shared Parameters for this `Block`. | ||
| 468 | |||
| 469 | |||
| 470 | Input shapes: | ||
| 471 | The input shape depends on `layout`. For `layout='TNC'`, the | ||
| 472 | input has shape `(sequence_length, batch_size, input_size)` | ||
| 473 | |||
| 474 | |||
| 475 | Output shape: | ||
| 476 | The output shape depends on `layout`. For `layout='TNC'`, the | ||
| 477 | output has shape `(sequence_length, batch_size, num_hidden)`. | ||
| 478 | If `bidirectional` is True, output shape will instead be | ||
| 479 | `(sequence_length, batch_size, 2*num_hidden)` | ||
| 480 | |||
| 481 | Recurrent state: | ||
| 482 | The recurrent state is an NDArray with shape `(num_layers, batch_size, num_hidden)`. | ||
| 483 | If `bidirectional` is True, the recurrent state shape will instead be | ||
| 484 | `(2*num_layers, batch_size, num_hidden)` | ||
| 485 | If input recurrent state is None, zeros are used as default begin states, | ||
| 486 | and the output recurrent state is omitted. | ||
| 487 | |||
| 488 | |||
| 489 | Examples | ||
| 490 | -------- | ||
| 491 | >>> layer = mx.gluon.rnn.RNN(100, 3) | ||
| 492 | >>> layer.initialize() | ||
| 493 | >>> input = mx.nd.random.uniform(shape=(5, 3, 10)) | ||
| 494 | >>> # by default zeros are used as begin state | ||
| 495 | >>> output = layer(input) | ||
| 496 | >>> # manually specify begin state. | ||
| 497 | >>> h0 = mx.nd.random.uniform(shape=(3, 3, 100)) | ||
| 498 | >>> output, hn = layer(input, h0) | ||
| 499 | =cut | ||
| 500 | use AI::MXNet::Gluon::Mouse; | ||
| 501 | extends 'AI::MXNet::Gluon::RNN::Layer'; | ||
| 502 | |||
| 503 | has '+num_layers' => (default => 1); | ||
| 504 | has 'activation' => (is => 'rw', default => 'relu'); | ||
| 505 | has '+layout' => (default => 'TNC'); | ||
| 506 | has '+dropout' => (default => 0); | ||
| 507 | has '+bidirectional' => (default => 0); | ||
| 508 | has [qw/ | ||
| 509 | +i2h_bias_initializer | ||
| 510 | +h2h_bias_initializer | ||
| 511 | /] => (default => 'zeros'); | ||
| 512 | has '+mode' => (default => sub { 'rnn_' . shift->activation }, lazy => 1); | ||
| 513 | method python_constructor_arguments() | ||
| 514 | { | ||
| 515 | [qw/ | ||
| 516 | hidden_size num_layers activation layout | ||
| 517 | dropout bidirectional input_size | ||
| 518 | i2h_weight_initializer h2h_weight_initializer | ||
| 519 | i2h_bias_initializer h2h_bias_initializer | ||
| 520 | /]; | ||
| 521 | } | ||
| 522 | |||
| 523 | method state_info(DimSize $batch_size=0) | ||
| 524 | { | ||
| 525 | return [{ | ||
| 526 | shape => [$self->num_layers * $self->dir, $batch_size, $self->hidden_size], | ||
| 527 | __layout__ => 'LNC' | ||
| 528 | }]; | ||
| 529 | } | ||
| 530 | |||
| 531 | __PACKAGE__->register('AI::MXNet::Gluon::RNN'); | ||
| 532 | |||
| 533 | package AI::MXNet::Gluon::RNN::LSTM; | ||
| 534 | |||
| 535 | =head1 NANE | ||
| 536 | |||
| 537 | AI::MXNet::Gluon::RNN::LSTM | ||
| 538 | =cut | ||
| 539 | |||
| 540 | =head1 DESCRIPTION | ||
| 541 | |||
| 542 | Applies a multi-layer long short-term memory (LSTM) RNN to an input sequence. | ||
| 543 | |||
| 544 | For each element in the input sequence, each layer computes the following | ||
| 545 | function: | ||
| 546 | |||
| 547 | .. math:: | ||
| 548 | \begin{array}{ll} | ||
| 549 | i_t = sigmoid(W_{ii} x_t + b_{ii} + W_{hi} h_{(t-1)} + b_{hi}) \\ | ||
| 550 | f_t = sigmoid(W_{if} x_t + b_{if} + W_{hf} h_{(t-1)} + b_{hf}) \\ | ||
| 551 | g_t = \tanh(W_{ig} x_t + b_{ig} + W_{hc} h_{(t-1)} + b_{hg}) \\ | ||
| 552 | o_t = sigmoid(W_{io} x_t + b_{io} + W_{ho} h_{(t-1)} + b_{ho}) \\ | ||
| 553 | c_t = f_t * c_{(t-1)} + i_t * g_t \\ | ||
| 554 | h_t = o_t * \tanh(c_t) | ||
| 555 | \end{array} | ||
| 556 | |||
| 557 | where :math:`h_t` is the hidden state at time `t`, :math:`c_t` is the | ||
| 558 | cell state at time `t`, :math:`x_t` is the hidden state of the previous | ||
| 559 | layer at time `t` or :math:`input_t` for the first layer, and :math:`i_t`, | ||
| 560 | :math:`f_t`, :math:`g_t`, :math:`o_t` are the input, forget, cell, and | ||
| 561 | out gates, respectively. | ||
| 562 | |||
| 563 | Parameters | ||
| 564 | ---------- | ||
| 565 | hidden_size: int | ||
| 566 | The number of features in the hidden state h. | ||
| 567 | num_layers: int, default 1 | ||
| 568 | Number of recurrent layers. | ||
| 569 | layout : str, default 'TNC' | ||
| 570 | The format of input and output tensors. T, N and C stand for | ||
| 571 | sequence length, batch size, and feature dimensions respectively. | ||
| 572 | dropout: float, default 0 | ||
| 573 | If non-zero, introduces a dropout layer on the outputs of each | ||
| 574 | RNN layer except the last layer. | ||
| 575 | bidirectional: bool, default False | ||
| 576 | If `True`, becomes a bidirectional RNN. | ||
| 577 | i2h_weight_initializer : str or Initializer | ||
| 578 | Initializer for the input weights matrix, used for the linear | ||
| 579 | transformation of the inputs. | ||
| 580 | h2h_weight_initializer : str or Initializer | ||
| 581 | Initializer for the recurrent weights matrix, used for the linear | ||
| 582 | transformation of the recurrent state. | ||
| 583 | i2h_bias_initializer : str or Initializer, default 'lstmbias' | ||
| 584 | Initializer for the bias vector. By default, bias for the forget | ||
| 585 | gate is initialized to 1 while all other biases are initialized | ||
| 586 | to zero. | ||
| 587 | h2h_bias_initializer : str or Initializer | ||
| 588 | Initializer for the bias vector. | ||
| 589 | input_size: int, default 0 | ||
| 590 | The number of expected features in the input x. | ||
| 591 | If not specified, it will be inferred from input. | ||
| 592 | prefix : str or None | ||
| 593 | Prefix of this `Block`. | ||
| 594 | params : `ParameterDict` or `None` | ||
| 595 | Shared Parameters for this `Block`. | ||
| 596 | |||
| 597 | |||
| 598 | Input shapes: | ||
| 599 | The input shape depends on `layout`. For `layout='TNC'`, the | ||
| 600 | input has shape `(sequence_length, batch_size, input_size)` | ||
| 601 | |||
| 602 | Output shape: | ||
| 603 | The output shape depends on `layout`. For `layout='TNC'`, the | ||
| 604 | output has shape `(sequence_length, batch_size, num_hidden)`. | ||
| 605 | If `bidirectional` is True, output shape will instead be | ||
| 606 | `(sequence_length, batch_size, 2*num_hidden)` | ||
| 607 | |||
| 608 | Recurrent state: | ||
| 609 | The recurrent state is a list of two NDArrays. Both has shape | ||
| 610 | `(num_layers, batch_size, num_hidden)`. | ||
| 611 | If `bidirectional` is True, each recurrent state will instead have shape | ||
| 612 | `(2*num_layers, batch_size, num_hidden)`. | ||
| 613 | If input recurrent state is None, zeros are used as default begin states, | ||
| 614 | and the output recurrent state is omitted. | ||
| 615 | |||
| 616 | |||
| 617 | Examples | ||
| 618 | -------- | ||
| 619 | >>> layer = mx.gluon.rnn.LSTM(100, 3) | ||
| 620 | >>> layer.initialize() | ||
| 621 | >>> input = mx.nd.random.uniform(shape=(5, 3, 10)) | ||
| 622 | >>> # by default zeros are used as begin state | ||
| 623 | >>> output = layer(input) | ||
| 624 | >>> # manually specify begin state. | ||
| 625 | >>> h0 = mx.nd.random.uniform(shape=(3, 3, 100)) | ||
| 626 | >>> c0 = mx.nd.random.uniform(shape=(3, 3, 100)) | ||
| 627 | >>> output, hn = layer(input, [h0, c0]) | ||
| 628 | =cut | ||
| 629 | |||
| 630 | use AI::MXNet::Gluon::Mouse; | ||
| 631 | extends 'AI::MXNet::Gluon::RNN::Layer'; | ||
| 632 | |||
| 633 | has '+num_layers' => (default => 1); | ||
| 634 | has '+layout' => (default => 'TNC'); | ||
| 635 | has '+dropout' => (default => 0); | ||
| 636 | has '+bidirectional' => (default => 0); | ||
| 637 | has [qw/ | ||
| 638 | +i2h_bias_initializer | ||
| 639 | +h2h_bias_initializer | ||
| 640 | /] => (default => 'zeros'); | ||
| 641 | has '+mode' => (default => 'lstm'); | ||
| 642 | |||
| 643 | method state_info(DimSize $batch_size=0) | ||
| 644 | { | ||
| 645 | return [ | ||
| 646 | { | ||
| 647 | shape => [ | ||
| 648 | $self->num_layers * $self->dir, $batch_size, | ||
| 649 | defined $self->projection_size ? $self->projection_size : $self->hidden_size | ||
| 650 | ], | ||
| 651 | __layout__ => 'LNC' | ||
| 652 | }, | ||
| 653 | { | ||
| 654 | shape => [$self->num_layers * $self->dir, $batch_size, $self->hidden_size], | ||
| 655 | __layout__ => 'LNC' | ||
| 656 | } | ||
| 657 | ]; | ||
| 658 | } | ||
| 659 | |||
| 660 | __PACKAGE__->register('AI::MXNet::Gluon::RNN'); | ||
| 661 | |||
| 662 | package AI::MXNet::Gluon::RNN::GRU; | ||
| 663 | |||
| 664 | =head1 NANE | ||
| 665 | |||
| 666 | AI::MXNet::Gluon::RNN::GRU | ||
| 667 | =cut | ||
| 668 | |||
| 669 | =head1 DESCRIPTION | ||
| 670 | |||
| 671 | Applies a multi-layer gated recurrent unit (GRU) RNN to an input sequence. | ||
| 672 | |||
| 673 | For each element in the input sequence, each layer computes the following | ||
| 674 | function: | ||
| 675 | |||
| 676 | .. math:: | ||
| 677 | \begin{array}{ll} | ||
| 678 | r_t = sigmoid(W_{ir} x_t + b_{ir} + W_{hr} h_{(t-1)} + b_{hr}) \\ | ||
| 679 | i_t = sigmoid(W_{ii} x_t + b_{ii} + W_hi h_{(t-1)} + b_{hi}) \\ | ||
| 680 | n_t = \tanh(W_{in} x_t + b_{in} + r_t * (W_{hn} h_{(t-1)}+ b_{hn})) \\ | ||
| 681 | h_t = (1 - i_t) * n_t + i_t * h_{(t-1)} \\ | ||
| 682 | \end{array} | ||
| 683 | |||
| 684 | where :math:`h_t` is the hidden state at time `t`, :math:`x_t` is the hidden | ||
| 685 | state of the previous layer at time `t` or :math:`input_t` for the first layer, | ||
| 686 | and :math:`r_t`, :math:`i_t`, :math:`n_t` are the reset, input, and new gates, respectively. | ||
| 687 | |||
| 688 | Parameters | ||
| 689 | ---------- | ||
| 690 | hidden_size: int | ||
| 691 | The number of features in the hidden state h | ||
| 692 | num_layers: int, default 1 | ||
| 693 | Number of recurrent layers. | ||
| 694 | layout : str, default 'TNC' | ||
| 695 | The format of input and output tensors. T, N and C stand for | ||
| 696 | sequence length, batch size, and feature dimensions respectively. | ||
| 697 | dropout: float, default 0 | ||
| 698 | If non-zero, introduces a dropout layer on the outputs of each | ||
| 699 | RNN layer except the last layer | ||
| 700 | bidirectional: bool, default False | ||
| 701 | If True, becomes a bidirectional RNN. | ||
| 702 | i2h_weight_initializer : str or Initializer | ||
| 703 | Initializer for the input weights matrix, used for the linear | ||
| 704 | transformation of the inputs. | ||
| 705 | h2h_weight_initializer : str or Initializer | ||
| 706 | Initializer for the recurrent weights matrix, used for the linear | ||
| 707 | transformation of the recurrent state. | ||
| 708 | i2h_bias_initializer : str or Initializer | ||
| 709 | Initializer for the bias vector. | ||
| 710 | h2h_bias_initializer : str or Initializer | ||
| 711 | Initializer for the bias vector. | ||
| 712 | input_size: int, default 0 | ||
| 713 | The number of expected features in the input x. | ||
| 714 | If not specified, it will be inferred from input. | ||
| 715 | prefix : str or None | ||
| 716 | Prefix of this `Block`. | ||
| 717 | params : ParameterDict or None | ||
| 718 | Shared Parameters for this `Block`. | ||
| 719 | |||
| 720 | |||
| 721 | Input shapes: | ||
| 722 | The input shape depends on `layout`. For `layout='TNC'`, the | ||
| 723 | input has shape `(sequence_length, batch_size, input_size)` | ||
| 724 | |||
| 725 | Output shape: | ||
| 726 | The output shape depends on `layout`. For `layout='TNC'`, the | ||
| 727 | output has shape `(sequence_length, batch_size, num_hidden)`. | ||
| 728 | If `bidirectional` is True, output shape will instead be | ||
| 729 | `(sequence_length, batch_size, 2*num_hidden)` | ||
| 730 | |||
| 731 | Recurrent state: | ||
| 732 | The recurrent state is an NDArray with shape `(num_layers, batch_size, num_hidden)`. | ||
| 733 | If `bidirectional` is True, the recurrent state shape will instead be | ||
| 734 | `(2*num_layers, batch_size, num_hidden)` | ||
| 735 | If input recurrent state is None, zeros are used as default begin states, | ||
| 736 | and the output recurrent state is omitted. | ||
| 737 | |||
| 738 | |||
| 739 | Examples | ||
| 740 | -------- | ||
| 741 | >>> layer = mx.gluon.rnn.GRU(100, 3) | ||
| 742 | >>> layer.initialize() | ||
| 743 | >>> input = mx.nd.random.uniform(shape=(5, 3, 10)) | ||
| 744 | >>> # by default zeros are used as begin state | ||
| 745 | >>> output = layer(input) | ||
| 746 | >>> # manually specify begin state. | ||
| 747 | >>> h0 = mx.nd.random.uniform(shape=(3, 3, 100)) | ||
| 748 | >>> output, hn = layer(input, h0) | ||
| 749 | =cut | ||
| 750 | |||
| 751 | use AI::MXNet::Gluon::Mouse; | ||
| 752 | extends 'AI::MXNet::Gluon::RNN::Layer'; | ||
| 753 | |||
| 754 | has '+num_layers' => (default => 1); | ||
| 755 | has '+layout' => (default => 'TNC'); | ||
| 756 | has '+dropout' => (default => 0); | ||
| 757 | has '+bidirectional' => (default => 0); | ||
| 758 | has [qw/ | ||
| 759 | +i2h_bias_initializer | ||
| 760 | +h2h_bias_initializer | ||
| 761 | /] => (default => 'zeros'); | ||
| 762 | has '+mode' => (default => 'gru'); | ||
| 763 | |||
| 764 | method state_info(DimSize $batch_size=0) | ||
| 765 | { | ||
| 766 | return [ | ||
| 767 | { | ||
| 768 | shape => [$self->num_layers * $self->dir, $batch_size, $self->hidden_size], | ||
| 769 | __layout__ => 'LNC' | ||
| 770 | } | ||
| 771 | ]; | ||
| 772 | } | ||
| 773 | |||
| 774 | __PACKAGE__->register('AI::MXNet::Gluon::RNN'); | ||
| 775 | |||
| 776 | 1; |