MXNet/Module/Base.pm untested

filter: Statementstmt 0.0% 0 / 319 Branchbran 0.0% 0 / 74 Conditioncond 0.0% 0 / 57 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 8 Podpod n/a totaltotal 0.0% 0 / 458 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
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::BatchEndParam;
21 use Mouse;
22 use AI::MXNet::Function::Parameters;
23 has [qw/epoch nbatch/] => (is => 'rw', isa => 'Int');
24 has 'eval_metric' => (is => 'rw', isa => 'AI::MXNet::EvalMetric');
25  
26 package AI::MXNet::Module::Base;
27 use Mouse;
28 use AI::MXNet::Base;
29 use Time::HiRes qw(time);
30 use Storable qw(dclone);
31  
32 =head1 NAME
33  
34 AI::MXNet::Module::Base - Base class for AI::MXNet::Module and AI::MXNet::Module::Bucketing
35 =cut
36  
37 func _as_list($obj)
38 {
39 return [$obj] if ((ref($obj)//'') ne 'ARRAY');
40 return $obj;
41 }
42  
43 # Check that all input names are in symbol's argument
44 method _check_input_names(
45 AI::MXNet::Symbol $symbol,
46 ArrayRef[Str] $names,
47 Str $typename,
48 Bool $throw
49 )
50 {
51 my @candidates;
52 my %args = map {
53 push @candidates, $_ if not /_(?:weight|bias|gamma|beta)$/;
54 $_ => 1
55 } @{ $symbol->list_arguments };
56 for my $name (@$names)
57 {
58 my $msg;
59 if(not exists $args{$name} and $name ne 'softmax_label')
60 {
61 $msg = sprintf("\033[91mYou created Module with Module(..., %s_names=%s) but "
62 ."input with name '%s' is not found in symbol.list_arguments(). "
63 ."Did you mean one of:\n\t%s\033[0m",
64 $typename, "@$names", $name, join("\n\t", @candidates)
65 );
66 if($throw)
67 {
68 confess($msg);
69 }
70 else
71 {
72 AI::MXNet::Logging->warning($msg);
73 }
74 }
75 }
76 }
77  
78 # Check that input names matches input data descriptors
79 method _check_names_match(
80 ArrayRef[Str] $data_names,
81 ArrayRef[NameShapeOrDataDesc] $data_shapes,
82 Str $name,
83 Bool $throw
84 )
85 {
86 return if (not @$data_shapes and @$data_names == 1 and $data_names->[0] eq 'softmax_label');
87 my @actual = sort map { @{$_}[0] } @{ $data_shapes };
88 my @data_names = sort @$data_names;
89 if("@data_names" ne "@actual")
90 {
91 my $msg = sprintf(
92 "Data provided by %s_shapes don't match names specified by %s_names (%s vs. %s)",
93 $name, $name, "@actual", "@data_names"
94 );
95 if($throw)
96 {
97 confess($msg);
98 }
99 else
100 {
101 AI::MXNet::Logging->warning($msg);
102 }
103 }
104 }
105  
106 method _parse_data_desc(
107 ArrayRef[Str] $data_names,
108 Maybe[ArrayRef[Str]] $label_names,
109 ArrayRef[NameShapeOrDataDesc] $data_shapes,
110 Maybe[ArrayRef[NameShapeOrDataDesc]] $label_shapes
111 )
112 {
113 $data_shapes = [map { blessed $_ ? $_ : AI::MXNet::DataDesc->new(@$_) } @$data_shapes];
114 $self->_check_names_match($data_names, $data_shapes, 'data', 1);
115 if($label_shapes)
116 {
117 $label_shapes = [map { blessed $_ ? $_ : AI::MXNet::DataDesc->new(@$_) } @$label_shapes];
118 $self->_check_names_match($label_names, $label_shapes, 'label', 0);
119 }
120 else
121 {
122 $self->_check_names_match($label_names, [], 'label', 0);
123 }
124 return ($data_shapes, $label_shapes);
125 }
126  
127 =head1 DESCRIPTION
128  
129 The base class of a modules. A module represents a computation component. The design
130 purpose of a module is that it abstract a computation "machine", that one can run forward,
131 backward, update parameters, etc. We aim to make the APIs easy to use, especially in the
132 case when we need to use imperative API to work with multiple modules (e.g. stochastic
133 depth network).
134  
135 A module has several states:
136  
137 - Initial state. Memory is not allocated yet, not ready for computation yet.
138 - Binded. Shapes for inputs, outputs, and parameters are all known, memory allocated,
139 ready for computation.
140 - Parameter initialized. For modules with parameters, doing computation before initializing
141 the parameters might result in undefined outputs.
142 - Optimizer installed. An optimizer can be installed to a module. After this, the parameters
143 of the module can be updated according to the optimizer after gradients are computed
144 (forward-backward).
145  
146 In order for a module to interact with others, a module should be able to report the
147 following information in its raw stage (before binded)
148  
149 - data_names: array ref of string indicating the names of required data.
150 - output_names: array ref of string indicating the names of required outputs.
151  
152 And also the following richer information after binded:
153  
154 - state information
155 - binded: bool, indicating whether the memory buffers needed for computation
156 has been allocated.
157 - for_training: whether the module is binded for training (if binded).
158 - params_initialized: bool, indicating whether the parameters of this modules
159 has been initialized.
160 - optimizer_initialized: bool, indicating whether an optimizer is defined
161 and initialized.
162 - inputs_need_grad: bool, indicating whether gradients with respect to the
163 input data is needed. Might be useful when implementing composition of modules.
164  
165 - input/output information
166 - data_shapes: am array ref of [name, shape]. In theory, since the memory is allocated,
167 we could directly provide the data arrays. But in the case of data parallelization,
168 the data arrays might not be of the same shape as viewed from the external world.
169 - label_shapes: an array ref of [name, shape]. This might be [] if the module does
170 not need labels (e.g. it does not contains a loss function at the top), or a module
171 is not binded for training.
172 - output_shapes: an array ref of [name, shape] for outputs of the module.
173  
174 - parameters (for modules with parameters)
175 - get_params(): return an array ($arg_params, $aux_params). Each of those
176 is a hash ref of name to NDArray mapping. Those NDArrays always on
177 CPU. The actual parameters used for computing might be on other devices (GPUs),
178 this function will retrieve (a copy of) the latest parameters. Therefore, modifying
179 - get_params($arg_params, $aux_params): assign parameters to the devices
180 doing the computation.
181 - init_params(...): a more flexible interface to assign or initialize the parameters.
182  
183 - setup
184 - bind(): prepare environment for computation.
185 - init_optimizer(): install optimizer for parameter updating.
186  
187 - computation
188 - forward(data_batch): forward operation.
189 - backward(out_grads=): backward operation.
190 - update(): update parameters according to installed optimizer.
191 - get_outputs(): get outputs of the previous forward operation.
192 - get_input_grads(): get the gradients with respect to the inputs computed
193 in the previous backward operation.
194 - update_metric(metric, labels): update performance metric for the previous forward
195 computed results.
196  
197 - other properties (mostly for backward compatability)
198 - symbol: the underlying symbolic graph for this module (if any)
199 This property is not necessarily constant. For example, for AI::MXNet::Module::Bucketing,
200 this property is simply the *current* symbol being used. For other modules,
201 this value might not be well defined.
202  
203 When those intermediate-level API are implemented properly, the following
204 high-level API will be automatically available for a module:
205  
206 - fit: train the module parameters on a data set
207 - predict: run prediction on a data set and collect outputs
208 - score: run prediction on a data set and evaluate performance
209 =cut
210  
211 has 'logger' => (is => 'rw', default => sub { AI::MXNet::Logging->get_logger });
212 has '_symbol' => (is => 'rw', init_arg => 'symbol', isa => 'AI::MXNet::Symbol');
213 has [
214 qw/binded for_training inputs_need_grad
215 params_initialized optimizer_initialized/
216 ] => (is => 'rw', isa => 'Bool', init_arg => undef, default => 0);
217  
218 ################################################################################
219 # High Level API
220 ################################################################################
221  
222 =head2 forward_backward
223  
224 A convenient function that calls both forward and backward.
225 =cut
226  
227 method forward_backward(AI::MXNet::DataBatch $data_batch)
228 {
229 $self->forward($data_batch, is_train => 1);
230 $self->backward();
231 }
232  
233 =head2 score
234  
235 Run prediction on eval_data and evaluate the performance according to
236 eval_metric.
237  
238 Parameters
239 ----------
240 $eval_data : AI::MXNet::DataIter
241 $eval_metric : AI::MXNet::EvalMetric
242 :$num_batch= : Maybe[Int]
243 Number of batches to run. Default is undef, indicating run until the AI::MXNet::DataIter
244 finishes.
245 :$batch_end_callback= : Maybe[Callback]
246 Could also be a array ref of functions.
247 :$reset=1 : Bool
248 Default 1, indicating whether we should reset $eval_data before starting
249 evaluating.
250 $epoch=0 : Int
251 Default is 0. For compatibility, this will be passed to callbacks (if any). During
252 training, this will correspond to the training epoch number.
253 =cut
254  
255 method score(
256 AI::MXNet::DataIter $eval_data,
257 EvalMetric|ArrayRef[EvalMetric] $eval_metric,
258 Maybe[Int] :$num_batch=,
259 Maybe[Callback]|ArrayRef[Callback] :$batch_end_callback=,
260 Maybe[Callback]|ArrayRef[Callback] :$score_end_callback=,
261 Bool :$reset=1,
262 Int :$epoch=0
263 )
264 {
265 assert($self->binded and $self->params_initialized);
266 $eval_data->reset if $reset;
267 if(not blessed $eval_metric or not $eval_metric->isa('AI::MXNet::EvalMetric'))
268 {
269 $eval_metric = AI::MXNet::Metric->create($eval_metric);
270 }
271  
272 $eval_metric->reset();
273 my $actual_num_batch = 0;
274 my $nbatch = 0;
275 while(my $eval_batch = <$eval_data>)
276 {
277 last if (defined $num_batch and $nbatch == $num_batch);
278 $self->forward($eval_batch, is_train => 0);
279 $self->update_metric($eval_metric, $eval_batch->label);
280  
281 if (defined $batch_end_callback)
282 {
283 my $batch_end_params = AI::MXNet::BatchEndParam->new(
284 epoch => $epoch,
285 nbatch => $nbatch,
286 eval_metric => $eval_metric
287 );
288 for my $callback (@{ _as_list($batch_end_callback) })
289 {
290 $callback->($batch_end_params);
291 }
292 }
293 $actual_num_batch++;
294 $nbatch++
295 }
296 if($score_end_callback)
297 {
298 my $params = AI::MXNet::BatchEndParam->new(
299 epoch => $epoch,
300 nbatch => $actual_num_batch,
301 eval_metric => $eval_metric,
302 );
303 for my $callback (@{ _as_list($score_end_callback) })
304 {
305 $callback->($params);
306 }
307 }
308 return $eval_metric->get_name_value;
309 }
310  
311 =head2 iter_predict
312  
313 Iterate over predictions.
314  
315 Parameters
316 ----------
317 $eval_data : AI::MXNet::DataIter
318 :$num_batch= : Maybe[Int]
319 Default is undef, indicating running all the batches in the data iterator.
320 :$reset=1 : bool
321 Default is 1, indicating whether we should reset the data iter before start
322 doing prediction.
323 =cut
324  
325 method iter_predict(AI::MXNet::DataIter $eval_data, Maybe[Int] :$num_batch=, Bool :$reset=1)
326 {
327 assert($self->binded and $self->params_initialized);
328 if($reset)
329 {
330 $eval_data->reset;
331 }
332 my $nbatch = 0;
333 my @out;
334 while(my $eval_batch = <$eval_data>)
335 {
336 last if defined $num_batch and $nbatch == $num_batch;
337 $self->forward($eval_batch, is_train => 0);
338 my $pad = $eval_batch->pad;
339 my $outputs = [
340 map { $_->slice([0, $_->shape->[0] - ($pad//0) - 1]) } @{ $self->get_outputs() }
341 ];
342 push @out, [$outputs, $nbatch, $eval_batch];
343 $nbatch++;
344 }
345 return @out;
346 }
347  
348 =head2 predict
349  
350 Run prediction and collect the outputs.
351  
352 Parameters
353 ----------
354 $eval_data : AI::MXNet::DataIter|AcceptableInput (PDL|NDArray)
355 :$num_batch= : Maybe[Int]
356 Default is undef, indicating running all the batches in the data iterator.
357 :$merge_batches=1 : Bool
358 Default is 1.
359 :$reset=1 : Bool
360 Default is 1, indicating whether we should reset the data iter before start
361 doing prediction.
362 :$always_output_list=0 : Bool
363 Default is 0, see the doc for return values.
364  
365 Returns
366 -------
367 If the input is AI::MXNet::NDArray|PDL then the return value is AI::MXNet::NDArray.
368  
369 When $merge_batches is 1 (by default), the return value will be an array ref
370 [$out1, $out2, $out3] where each element is concatenation of the outputs for
371 all the mini-batches. If $always_output_list` also is 0 (by default),
372 then in the case of a single output, $out1 is returned in stead of [$out1].
373  
374 When $merge_batches is 0, the return value will be a nested array ref like
375 [[$out1_batch1, $out2_batch1], [$out1_batch2], ...]. This mode is useful because
376 in some cases (e.g. bucketing), the module does not necessarily produce the same
377 number of outputs.
378  
379 The objects in the results are AI::MXNet::NDArray`s. If you need to work with pdl array,
380 just call ->aspdl() on each AI::MXNet::NDArray.
381 =cut
382  
383 method predict(
384 AI::MXNet::DataIter|AcceptableInput $eval_data,
385 Maybe[Int] :$num_batch=, Bool :$merge_batches=1, Bool :$reset=1, Bool :$always_output_list=0
386 )
387 {
388 assert($self->binded and $self->params_initialized);
389 if(not blessed $eval_data or not $eval_data->isa('AI::MXNet::DataIter'))
390 {
391 if(not blessed $eval_data or not $eval_data->isa('AI::MXNet::NDArray'))
392 {
393 $eval_data = AI::MXNet::NDArray->array($eval_data);
394 }
395 $self->forward(AI::MXNet::DataBatch->new(data => [$eval_data]));
396 return $self->get_outputs->[0];
397 }
398 $eval_data->reset() if $reset;
399 my @output_list;
400 my $nbatch = 0;
401 while(my $eval_batch = <$eval_data>)
402 {
403 last if defined $num_batch and $nbatch == $num_batch;
404 $self->forward($eval_batch, is_train => 0);
405 my $pad = $eval_batch->pad;
406 my $outputs = [map { $_->slice([0, $_->shape->[0]-($pad//0)-1])->copy } @{ $self->get_outputs }];
407 push @output_list, $outputs;
408 }
409 return () unless @output_list;
410 if($merge_batches)
411 {
412 my $num_outputs = @{ $output_list[0] };
413 for my $out (@output_list)
414 {
415 unless(@{ $out } == $num_outputs)
416 {
417 confess('Cannot merge batches, as num of outputs is not the same '
418 .'in mini-batches. Maybe bucketing is used?');
419 }
420 }
421 my @output_list2;
422 for my $i (0..$num_outputs-1)
423 {
424 push @output_list2,
425 AI::MXNet::NDArray->concatenate([map { $_->[$i] } @output_list]);
426 }
427 if($num_outputs == 1 and not $always_output_list)
428 {
429 return $output_list2[0];
430 }
431 return @output_list2;
432 }
433 return @output_list;
434 }
435  
436 =head2 fit
437  
438 Train the module parameters.
439  
440 Parameters
441 ----------
442 $train_data : AI::MXNet::DataIter
443 :$eval_data= : Maybe[AI::MXNet::DataIter]
444 If not undef, it will be used as a validation set to evaluate the performance
445 after each epoch.
446 :$eval_metric='acc' : str or AI::MXNet::EvalMetric subclass object.
447 Default is 'accuracy'. The performance measure used to display during training.
448 Other possible predefined metrics are:
449 'ce' (CrossEntropy), 'f1', 'mae', 'mse', 'rmse', 'top_k_accuracy'
450 :$epoch_end_callback= : Maybe[Callback]|ArrayRef[Callback] function or array ref of functions.
451 Each callback will be called with the current $epoch, $symbol, $arg_params
452 and $aux_params.
453 :$batch_end_callback= : Maybe[Callback]|ArrayRef[Callback] function or array ref of functions.
454 Each callback will be called with a AI::MXNet::BatchEndParam.
455 :$kvstore='local' : str or AI::MXNet::KVStore
456 Default is 'local'.
457 :$optimizer : str or AI::MXNet::Optimizer
458 Default is 'sgd'
459 :$optimizer_params : hash ref
460 Default { learning_rate => 0.01 }.
461 The parameters for the optimizer constructor.
462 :$eval_end_callback= : Maybe[Callback]|ArrayRef[Callback] function or array ref of functions
463 These will be called at the end of each full evaluation, with the metrics over
464 the entire evaluation set.
465 :$eval_batch_end_callback : Maybe[Callback]|ArrayRef[Callback] function or array ref of functions
466 These will be called at the end of each minibatch during evaluation
467 :$initializer= : Initializer
468 Will be called to initialize the module parameters if not already initialized.
469 :$arg_params= : hash ref
470 Default undef, if not undef, must be an existing parameters from a trained
471 model or loaded from a checkpoint (previously saved model). In this case,
472 the value here will be used to initialize the module parameters, unless they
473 are already initialized by the user via a call to init_params or fit.
474 $arg_params have higher priority than the $initializer.
475 :$aux_params= : hash ref
476 Default is undef. This is similar to the $arg_params, except for auxiliary states.
477 :$allow_missing=0 : Bool
478 Default is 0. Indicates whether we allow missing parameters when $arg_params
479 and $aux_params are not undefined. If this is 1, then the missing parameters
480 will be initialized via the $initializer.
481 :$force_rebind=0 : Bool
482 Default is 0. Whether to force rebinding the executors if already binded.
483 :$force_init=0 : Bool
484 Default is 0. Indicates whether we should force initialization even if the
485 parameters are already initialized.
486 :$begin_epoch=0 : Int
487 Default is 0. Indicates the starting epoch. Usually, if we are resuming from a
488 checkpoint saved at a previous training phase at epoch N, then we should specify
489 this value as N+1.
490 :$num_epoch : Int
491 Number of epochs for the training.
492 =cut
493  
494  
495 method fit(
496 AI::MXNet::DataIter $train_data,
497 Maybe[AI::MXNet::DataIter] :$eval_data=,
498 EvalMetric|ArrayRef[EvalMetric] :$eval_metric='acc',
499 Maybe[Callback]|ArrayRef[Callback] :$epoch_end_callback=,
500 Maybe[Callback]|ArrayRef[Callback] :$batch_end_callback=,
501 KVStore :$kvstore='local',
502 Optimizer :$optimizer='sgd',
503 HashRef :$optimizer_params={ learning_rate => 0.01 },
504 Maybe[Callback]|ArrayRef[Callback] :$eval_end_callback=,
505 Maybe[Callback]|ArrayRef[Callback] :$eval_batch_end_callback=,
506 AI::MXNet::Initializer :$initializer=AI::MXNet::Initializer->Uniform(scale => 0.01),
507 Maybe[HashRef[AI::MXNet::NDArray]] :$arg_params=,
508 Maybe[HashRef[AI::MXNet::NDArray]] :$aux_params=,
509 Bool :$allow_missing=0,
510 Bool :$force_rebind=0,
511 Bool :$force_init=0,
512 Int :$begin_epoch=0,
513 Int :$num_epoch,
514 Maybe[EvalMetric|ArrayRef[EvalMetric]] :$validation_metric=,
515 Maybe[AI::MXNet::Monitor] :$monitor=
516 )
517 {
518 $self->bind(
519 data_shapes => $train_data->provide_data,
520 label_shapes => $train_data->provide_label,
521 for_training => 1,
522 force_rebind => $force_rebind
523 );
524 if($monitor)
525 {
526 $self->install_monitor($monitor);
527 }
528 $self->init_params(
529 initializer => $initializer,
530 arg_params => $arg_params,
531 aux_params => $aux_params,
532 allow_missing => $allow_missing,
533 force_init => $force_init
534 );
535 $self->init_optimizer(
536 kvstore => $kvstore,
537 optimizer => $optimizer,
538 optimizer_params => $optimizer_params
539 );
540  
541 if(not defined $validation_metric)
542 {
543 $validation_metric = $eval_metric;
544 }
545 $eval_metric = AI::MXNet::Metric->create($eval_metric)
546 unless blessed $eval_metric;
547 my $epoch_eval_metric = dclone($eval_metric);
548  
549 ################################################################################
550 # training loop
551 ################################################################################
552 for my $epoch ($begin_epoch..$num_epoch-1)
553 {
554 my $tic = time;
555 $eval_metric->reset;
556 $epoch_eval_metric->reset;
557 my $nbatch = 0;
558 my $end_of_batch = 0;
559 my $next_data_batch = <$train_data>;
560 while(not $end_of_batch)
561 {
562 my $data_batch = $next_data_batch;
563 $monitor->tic if $monitor;
564 $self->forward_backward($data_batch);
565 $self->update;
566 $next_data_batch = <$train_data>;
567 if(defined $next_data_batch)
568 {
569 $self->prepare($next_data_batch);
570 }
571 else
572 {
573 $end_of_batch = 1;
574 }
575 $self->update_metric($epoch_eval_metric, $data_batch->label);
576 $monitor->toc_print if $monitor;
577 if(defined $batch_end_callback)
578 {
579 $self->update_metric($eval_metric, $data_batch->label);
580 my $batch_end_params = AI::MXNet::BatchEndParam->new(
581 epoch => $epoch,
582 nbatch => $nbatch,
583 eval_metric => $eval_metric
584 );
585 for my $callback (@{ _as_list($batch_end_callback) })
586 {
587 $callback->($batch_end_params);
588 }
589 }
590 $nbatch++;
591 }
592 # one epoch of training is finished
593 my $name_value = $epoch_eval_metric->get_name_value;
594 while(my ($name, $val) = each %{ $name_value })
595 {
596 $self->logger->info('Epoch[%d] Train-%s=%f', $epoch, $name, $val);
597 }
598 my $toc = time;
599 $self->logger->info('Epoch[%d] Time cost=%.3f', $epoch, ($toc-$tic));
600  
601 # sync aux params across devices
602 my ($arg_params, $aux_params) = $self->get_params;
603 $self->set_params($arg_params, $aux_params);
604  
605 if($epoch_end_callback)
606 {
607 for my $callback (@{ _as_list($epoch_end_callback) })
608 {
609 $callback->($epoch, $self->get_symbol, $arg_params, $aux_params);
610 }
611 }
612 #----------------------------------------
613 # evaluation on validation set
614 if(defined $eval_data)
615 {
616 my $res = $self->score(
617 $eval_data,
618 $validation_metric,
619 score_end_callback => $eval_end_callback,
620 batch_end_callback => $eval_batch_end_callback,
621 epoch => $epoch
622 );
623 #TODO: pull this into default
624 while(my ($name, $val) = each %{ $res })
625 {
626 $self->logger->info('Epoch[%d] Validation-%s=%f', $epoch, $name, $val);
627 }
628 }
629 # end of 1 epoch, reset the data-iter for another epoch
630 $train_data->reset;
631 }
632 }
633  
634 ################################################################################
635 # Symbol information
636 ################################################################################
637  
638 =head2 get_symbol
639  
640 The symbol used by this module.
641 =cut
642 method get_symbol() { $self->symbol }
643  
644 =head2 data_names
645  
646 An array ref of names for data required by this module.
647 =cut
648 method data_names() { confess("NotImplemented") }
649  
650 =head2 output_names
651  
652 An array ref of names for the outputs of this module.
653 =cut
654 method output_names() { confess("NotImplemented") }
655  
656 ################################################################################
657 # Input/Output information
658 ################################################################################
659  
660 =head2 data_shapes
661  
662 An array ref of AI::MXNet::DataDesc objects specifying the data inputs to this module.
663 =cut
664 method data_shapes() { confess("NotImplemented") }
665  
666 =head2 label_shapes
667  
668 A array ref of AI::MXNet::DataDesc objects specifying the label inputs to this module.
669 If this module does not accept labels -- either it is a module without a loss
670 function, or it is not binded for training, then this should return an empty
671 array ref.
672 =cut
673 method label_shapes() { confess("NotImplemented") }
674  
675 =head2 output_shapes
676  
677 An array ref of (name, shape) array refs specifying the outputs of this module.
678 =cut
679 method output_shapes() { confess("NotImplemented") }
680  
681 ################################################################################
682 # Parameters of a module
683 ################################################################################
684  
685 =head2 get_params
686  
687 The parameters, these are potentially a copies of the actual parameters used
688 to do computation on the device.
689  
690 Returns
691 -------
692 ($arg_params, $aux_params), a pair of hash refs of name to value mapping.
693 =cut
694  
695 method get_params() { confess("NotImplemented") }
696  
697 =head2 init_params
698  
699 Initialize the parameters and auxiliary states.
700  
701 Parameters
702 ----------
703 :$initializer : Maybe[AI::MXNet::Initializer]
704 Called to initialize parameters if needed.
705 :$arg_params= : Maybe[HashRef[AI::MXNet::NDArray]]
706 If not undef, should be a hash ref of existing arg_params.
707 :$aux_params : Maybe[HashRef[AI::MXNet::NDArray]]
708 If not undef, should be a hash ref of existing aux_params.
709 :$allow_missing=0 : Bool
710 If true, params could contain missing values, and the initializer will be
711 called to fill those missing params.
712 :$force_init=0 : Bool
713 If true, will force re-initialize even if already initialized.
714 :$allow_extra=0 : Boolean, optional
715 Whether allow extra parameters that are not needed by symbol.
716 If this is True, no error will be thrown when arg_params or aux_params
717 contain extra parameters that is not needed by the executor.
718 =cut
719  
720 method init_params(
721 Maybe[AI::MXNet::Initializer] :$initializer=AI::MXNet::Initializer->Uniform(0.01),
722 Maybe[HashRef[AI::MXNet::NDArray]] :$arg_params=,
723 Maybe[HashRef[AI::MXNet::NDArray]] :$aux_params=,
724 Bool :$allow_missing=0,
725 Bool :$force_init=0,
726 Bool :$allow_extra=0
727 )
728 {
729 confess("NotImplemented");
730 }
731  
732 =head2 set_params
733  
734 Assign parameter and aux state values.
735  
736 Parameters
737 ----------
738 $arg_params= : Maybe[HashRef[AI::MXNet::NDArray]]
739 Hash ref of name to value (NDArray) mapping.
740 $aux_params= : Maybe[HashRef[AI::MXNet::NDArray]]
741 Hash Ref of name to value (`NDArray`) mapping.
742 :$allow_missing=0 : Bool
743 If true, params could contain missing values, and the initializer will be
744 called to fill those missing params.
745 :$force_init=0 : Bool
746 If true, will force re-initialize even if already initialized.
747 :$allow_extra=0 : Bool
748 Whether allow extra parameters that are not needed by symbol.
749 If this is True, no error will be thrown when arg_params or aux_params
750 contain extra parameters that is not needed by the executor.
751 =cut
752  
753 method set_params(
754 Maybe[HashRef[AI::MXNet::NDArray]] $arg_params=,
755 Maybe[HashRef[AI::MXNet::NDArray]] $aux_params=,
756 Bool :$allow_missing=0,
757 Bool :$force_init=0,
758 Bool :$allow_extra=0
759 )
760 {
761 $self->init_params(
762 initializer => undef,
763 arg_params => $arg_params,
764 aux_params => $aux_params,
765 allow_missing => $allow_missing,
766 force_init => $force_init,
767 allow_extra => $allow_extra
768 );
769 }
770  
771 =head2 save_params
772  
773 Save model parameters to file.
774  
775 Parameters
776 ----------
777 $fname : str
778 Path to output param file.
779 $arg_params= : Maybe[HashRef[AI::MXNet::NDArray]]
780 $aux_params= : Maybe[HashRef[AI::MXNet::NDArray]]
781 =cut
782  
783 method save_params(
784 Str $fname,
785 Maybe[HashRef[AI::MXNet::NDArray]] $arg_params=,
786 Maybe[HashRef[AI::MXNet::NDArray]] $aux_params=
787 )
788 {
789 ($arg_params, $aux_params) = $self->get_params
790 unless (defined $arg_params and defined $aux_params);
791 my %save_dict;
792 while(my ($k, $v) = each %{ $arg_params })
793 {
794 $save_dict{"arg:$k"} = $v->as_in_context(AI::MXNet::Context->cpu);
795 }
796 while(my ($k, $v) = each %{ $aux_params })
797 {
798 $save_dict{"aux:$k"} = $v->as_in_context(AI::MXNet::Context->cpu);
799 }
800 AI::MXNet::NDArray->save($fname, \%save_dict);
801 }
802  
803 =head2 load_params
804  
805 Load model parameters from file.
806  
807 Parameters
808 ----------
809 $fname : str
810 Path to input param file.
811 =cut
812  
813 method load_params(Str $fname)
814 {
815 my %save_dict = %{ AI::MXNet::NDArray->load($fname) };
816 my %arg_params;
817 my %aux_params;
818 while(my ($k, $v) = each %save_dict)
819 {
820 my ($arg_type, $name) = split(/:/, $k, 2);
821 if($arg_type eq 'arg')
822 {
823 $arg_params{ $name } = $v;
824 }
825 elsif($arg_type eq 'aux')
826 {
827 $aux_params{ $name } = $v;
828 }
829 else
830 {
831 confess("Invalid param file $fname");
832 }
833 }
834 $self->set_params(\%arg_params, \%aux_params);
835 }
836  
837 =head2 get_states
838  
839 The states from all devices
840  
841 Parameters
842 ----------
843 $merge_multi_context=1 : Bool
844 Default is true (1). In the case when data-parallelism is used, the states
845 will be collected from multiple devices. A true value indicate that we
846 should merge the collected results so that they look like from a single
847 executor.
848  
849 Returns
850 -------
851 If $merge_multi_context is 1, it is like [$out1, $out2]. Otherwise, it
852 is like [[$out1_dev1, $out1_dev2], [$out2_dev1, $out2_dev2]]. All the output
853 elements are AI::MXNet::NDArray.
854 =cut
855  
856 method get_states(Bool $merge_multi_context=1)
857 {
858 assert($self->binded and $self->params_initialized);
859 assert(not $merge_multi_context);
860 return [];
861 }
862  
863 =head2 set_states
864  
865 Set value for states. You can specify either $states or $value, not both.
866  
867 Parameters
868 ----------
869 $states= : Maybe[ArrayRef[ArrayRef[AI::MXNet::NDArray]]]
870 source states arrays formatted like [[$state1_dev1, $state1_dev2],
871 [$state2_dev1, $state2_dev2]].
872 $value= : Maybe[Num]
873 a single scalar value for all state arrays.
874 =cut
875  
876 method set_states(Maybe[ArrayRef[ArrayRef[AI::MXNet::NDArray]]] $states=, Maybe[Num] $value=)
877 {
878 assert($self->binded and $self->params_initialized);
879 assert(not $states and not $value);
880 }
881  
882  
883 =head2 install_monitor
884  
885 Install monitor on all executors
886  
887 Parameters
888 ----------
889 $mon : AI::MXNet::Monitor
890 =cut
891  
892 method install_monitor(AI::MXNet::Monitor $mon) { confess("NotImplemented") }
893  
894 =head2 prepare
895  
896 Prepare the module for processing a data batch.
897  
898 Usually involves switching a bucket and reshaping.
899  
900 Parameters
901 ----------
902 $data_batch : AI::MXNet::DataBatch
903 =cut
904  
905 method prepare(AI::MXNet::DataBatch $data_batch){}
906  
907 ################################################################################
908 # Computations
909 ################################################################################
910  
911 =head2 forward
912  
913 Forward computation. It supports data batches with different shapes, such as
914 different batch sizes or different image sizes.
915 If reshaping of data batch relates to modification of symbol or module, such as
916 changing image layout ordering or switching from training to predicting, module
917 rebinding is required.
918  
919 Parameters
920 ----------
921 $data_batch : DataBatch
922 Could be anything with similar API implemented.
923 :$is_train= : Bool
924 Default is undef, which means is_train takes the value of $self->for_training.
925 =cut
926  
927 method forward(AI::MXNet::DataBatch $data_batch, Bool :$is_train=) { confess("NotImplemented") }
928  
929 =head2 backward
930  
931 Backward computation.
932  
933 Parameters
934 ----------
935 $out_grads : Maybe[AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]], optional
936 Gradient on the outputs to be propagated back.
937 This parameter is only needed when bind is called
938 on outputs that are not a loss function.
939 =cut
940  
941 method backward(Maybe[AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]] $out_grads=)
942 {
943 confess("NotImplemented")
944 }
945  
946 =head2 get_outputs
947  
948 The outputs of the previous forward computation.
949  
950 Parameters
951 ----------
952 $merge_multi_context=1 : Bool
953 =cut
954  
955 method get_outputs(Bool $merge_multi_context=1) { confess("NotImplemented") }
956  
957 =head2 get_input_grads
958  
959 The gradients to the inputs, computed in the previous backward computation.
960  
961 Parameters
962 ----------
963 $merge_multi_context=1 : Bool
964 =cut
965  
966 method get_input_grads(Bool $merge_multi_context=1) { confess("NotImplemented") }
967  
968 =head2 update
969  
970 Update parameters according to the installed optimizer and the gradients computed
971 in the previous forward-backward batch.
972 =cut
973  
974 method update() { confess("NotImplemented") }
975  
976 =head2 update_metric
977  
978 Evaluate and accumulate evaluation metric on outputs of the last forward computation.
979  
980 Parameters
981 ----------
982 $eval_metric : EvalMetric
983 $labels : ArrayRef[AI::MXNet::NDArray]
984 Typically $data_batch->label.
985 =cut
986  
987 method update_metric(EvalMetric $eval_metric, ArrayRef[AI::MXNet::NDArray] $labels)
988 {
989 confess("NotImplemented")
990 }
991  
992 ################################################################################
993 # module setup
994 ################################################################################
995  
996 =head2 bind
997  
998 Binds the symbols in order to construct the executors. This is necessary
999 before the computations can be performed.
1000  
1001 Parameters
1002 ----------
1003 $data_shapes : ArrayRef[AI::MXNet::DataDesc]
1004 Typically is $data_iter->provide_data.
1005 :$label_shapes= : Maybe[ArrayRef[AI::MXNet::DataDesc]]
1006 Typically is $data_iter->provide_label.
1007 :$for_training=1 : Bool
1008 Default is 1. Whether the executors should be bind for training.
1009 :$inputs_need_grad=0 : Bool
1010 Default is 0. Whether the gradients to the input data need to be computed.
1011 Typically this is not needed. But this might be needed when implementing composition
1012 of modules.
1013 :$force_rebind=0 : Bool
1014 Default is 0. This function does nothing if the executors are already
1015 binded. But with this as 1, the executors will be forced to rebind.
1016 :$shared_module= : A subclass of AI::MXNet::Module::Base
1017 Default is undef. This is used in bucketing. When not undef, the shared module
1018 essentially corresponds to a different bucket -- a module with different symbol
1019 but with the same sets of parameters (e.g. unrolled RNNs with different lengths).
1020 :$grad_req='write' : Str|ArrayRef[Str]|HashRef[Str]
1021 Requirement for gradient accumulation. Can be 'write', 'add', or 'null'
1022 (defaults to 'write').
1023 Can be specified globally (str) or for each argument (array ref, hash ref).
1024 =cut
1025  
1026 method bind(
1027 ArrayRef[AI::MXNet::DataDesc] $data_shapes,
1028 Maybe[ArrayRef[AI::MXNet::DataDesc]] :$label_shapes=,
1029 Bool :$for_training=1,
1030 Bool :$inputs_need_grad=0,
1031 Bool :$force_rebind=0,
1032 Maybe[AI::MXNet::BaseModule] :$shared_module=,
1033 Str|ArrayRef[Str]|HashRef[Str] :$grad_req='write'
1034 )
1035 {
1036 confess("NotImplemented")
1037 }
1038  
1039 =head2 init_optimizer
1040  
1041 Install and initialize optimizers.
1042  
1043 Parameters
1044 ----------
1045 :$kvstore='local' : str or KVStore
1046 :$optimizer='sgd' : str or Optimizer
1047 :$optimizer_params={ learning_rate => 0.01 } : hash ref
1048 :$force_init=0 : Bool
1049 =cut
1050  
1051 method init_optimizer(
1052 Str :$kvstore='local',
1053 Optimizer :$optimizer='sgd',
1054 HashRef :$optimizer_params={ learning_rate => 0.01 },
1055 Bool :$force_init=0
1056 )
1057 {
1058 confess("NotImplemented")
1059 }
1060  
1061 ################################################################################
1062 # misc
1063 ################################################################################
1064  
1065 =head2 symbol
1066  
1067 The symbol associated with this module.
1068  
1069 Except for AI::MXNet::Module, for other types of modules (e.g. AI::MXNet::Module::Bucketing), this
1070 property might not be a constant throughout its life time. Some modules might
1071 not even be associated with any symbols.
1072 =cut
1073  
1074 method symbol()
1075 {
1076 return $self->_symbol;
1077 }
1078  
1079 1;