MXNet/Module.pm untested

filter: Statementstmt 0.0% 0 / 435 Branchbran 0.0% 0 / 112 Conditioncond 0.0% 0 / 84 MC/DCmcdc 0.0% 0 / 51 Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 691 CC 3 SCAR 16.1
CC
3
Cov
0%
BUILD
12.0
BEGIN
2.0
BEGIN
2.0
CRAP 5.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 ## TODO
19 ## this class is here because of https://github.com/gfx/p5-Mouse/pull/67
20 ## once 2.4.7 version of Mouse in Ubuntu for affected Perl version
21 ## these accessors should be merged into main class
22  
23 package AI::MXNet::Module::Private;
24 use Mouse;
25 has [qw/_param_names _fixed_param_names
26 _aux_names _data_names _label_names _state_names
27 _output_names _arg_params _aux_params
28 _params_dirty _optimizer _kvstore
29 _update_on_kvstore _updater _work_load_list
30 _preload_opt_states _exec_group
31 _data_shapes _label_shapes _context _grad_req/
32 ] => (is => 'rw', init_arg => undef);
33  
34 package AI::MXNet::Module;
35 use AI::MXNet::NS;
36 use AI::MXNet::Base;
37 use AI::MXNet::Function::Parameters;
38 use List::Util qw(max);
39 use Data::Dumper ();
40 use Mouse;
41  
42 func _create_sparse_kvstore(Maybe[Str|AI::MXNet::KVStore] $kvstore)
43 {
44 # always update on kvstore
45 my $update_on_kvstore = 1;
46 my $kv;
47 if(blessed $kvstore)
48 {
49 $kv = $kvstore;
50 }
51 else
52 {
53 $kv = AI::MXNet::KVStore->create($kvstore);
54 }
55 return ($kv, $update_on_kvstore);
56 }
57  
58 func _create_kvstore(
59 Maybe[Str|AI::MXNet::KVStore] $kvstore,
60 Int $num_device,
61 HashRef[AI::MXNet::NDArray] $arg_params
62 )
63 {
64 my $update_on_kvstore = 1;
65 my $kv;
66 if(defined $kvstore)
67 {
68 if(blessed $kvstore)
69 {
70 $kv = $kvstore;
71 }
72 else
73 {
74 # create kvstore using the string type
75 if($num_device == 1 and $kvstore !~ /dist/)
76 {
77 # no need to use kv for single device and single machine
78 }
79 else
80 {
81 $kv = AI::MXNet::KVStore->create($kvstore);
82 if($kvstore eq 'local')
83 {
84 # automatically select a proper local
85 my $max_size = max(map { product(@{ $_->shape }) } values %{ $arg_params });
86 if($max_size > 1024 * 1024 * 16)
87 {
88 $update_on_kvstore = 0;
89 }
90 }
91 }
92 }
93 }
94  
95 $update_on_kvstore = 0 if not $kv;
96 return ($kv, $update_on_kvstore);
97 }
98  
99 func _initialize_kvstore(
100 AI::MXNet::KVStore :$kvstore,
101 HashRef[AI::MXNet::NDArray] :$arg_params,
102 ArrayRef[Str] :$param_names,
103 Bool :$update_on_kvstore,
104 ArrayRef[AI::MXNet::NDArray]|ArrayRef[ArrayRef[AI::MXNet::NDArray]] :$param_arrays
105 )
106 {
107 enumerate(sub{
108 my ($idx, $param_on_devs) = @_;
109 my $name = $param_names->[$idx];
110 $kvstore->init($name, $arg_params->{ $name });
111 if($update_on_kvstore)
112 {
113 $kvstore->pull($name, out => $param_on_devs, priority => -$idx);
114 }
115 }, $param_arrays);
116 }
117  
118 func _update_params_on_kvstore(
119 ArrayRef[AI::MXNet::NDArray]|ArrayRef[ArrayRef[AI::MXNet::NDArray]] $param_arrays,
120 ArrayRef[AI::MXNet::NDArray]|ArrayRef[ArrayRef[AI::MXNet::NDArray]] $grad_arrays,
121 AI::MXNet::KVStore $kvstore,
122 ArrayRef[Str] $param_names
123 )
124 {
125 enumerate(sub{
126 my ($index, $arg_list, $grad_list) = @_;
127 if(ref $grad_list eq 'ARRAY' and not defined $grad_list->[0])
128 {
129 return;
130 }
131 my $name = $param_names->[$index];
132 # push gradient, priority is negative index
133 $kvstore->push($name, $grad_list, priority => -$index);
134 # pull back the weights
135 $kvstore->pull($name, out => $arg_list, priority => -$index);
136 }, $param_arrays, $grad_arrays);
137 }
138  
139 func _update_params(
140 ArrayRef[ArrayRef[AI::MXNet::NDArray]] $param_arrays,
141 ArrayRef[ArrayRef[AI::MXNet::NDArray]] $grad_arrays,
142 AI::MXNet::Updater $updater,
143 Int $num_device,
144 Maybe[AI::MXNet::KVStore] $kvstore=,
145 Maybe[ArrayRef[Str]] $param_names=
146 )
147 {
148 enumerate(sub{
149 my ($index, $arg_list, $grad_list) = @_;
150 if(not defined $grad_list->[0])
151 {
152 return;
153 }
154 if($kvstore)
155 {
156 my $name = $param_names->[$index];
157 # push gradient, priority is negative index
158 $kvstore->push($name, $grad_list, priority => -$index);
159 # pull back the sum gradients, to the same locations.
160 $kvstore->pull($name, out => $grad_list, priority => -$index);
161 }
162 enumerate(sub {
163 my ($k, $w, $g) = @_;
164 # faked an index here, to make optimizer create diff
165 # state for the same index but on diff devs, TODO(mli)
166 # use a better solution later
167 $updater->($index*$num_device+$k, $g, $w);
168 }, $arg_list, $grad_list);
169 }, $param_arrays, $grad_arrays);
170 }
171  
172 method load_checkpoint(Str $prefix, Int $epoch)
173 {
174 my $symbol = AI::MXNet::Symbol->load("$prefix-symbol.json");
175 my %save_dict = %{ AI::MXNet::NDArray->load(sprintf('%s-%04d.params', $prefix, $epoch)) };
176 my %arg_params;
177 my %aux_params;
178 while(my ($k, $v) = each %save_dict)
179 {
180 my ($tp, $name) = split(/:/, $k, 2);
181 if($tp eq 'arg')
182 {
183 $arg_params{$name} = $v;
184 }
185 if($tp eq 'aux')
186 {
187 $aux_params{$name} = $v;
188 }
189 }
190 return ($symbol, \%arg_params, \%aux_params);
191 }
192  
193 =head1 NAME
194  
195 AI::MXNet::Module - FeedForward interface of MXNet.
196 See AI::MXNet::Module::Base for the details.
197 =cut
198  
199 extends 'AI::MXNet::Module::Base';
200  
201 has '_symbol' => (is => 'ro', init_arg => 'symbol', isa => 'AI::MXNet::Symbol', required => 1);
202 has '_data_names' => (is => 'ro', init_arg => 'data_names', isa => 'ArrayRef[Str]');
203 has '_label_names' => (is => 'ro', init_arg => 'label_names', isa => 'Maybe[ArrayRef[Str]]');
204 has 'work_load_list' => (is => 'rw', isa => 'Maybe[ArrayRef[Int]]');
205 has 'fixed_param_names' => (is => 'rw', isa => 'Maybe[ArrayRef[Str]]');
206 has 'state_names' => (is => 'rw', isa => 'Maybe[ArrayRef[Str]]');
207 has 'logger' => (is => 'ro', default => sub { AI::MXNet::Logging->get_logger });
208 has '_p' => (is => 'rw', init_arg => undef);
209 has 'context' => (
210 is => 'ro',
211 isa => 'AI::MXNet::Context|ArrayRef[AI::MXNet::Context]',
212 default => sub { AI::MXNet::Context->cpu }
213 );
214  
215 around BUILDARGS => sub {
216 my $orig = shift;
217 my $class = shift;
218 if(@_%2)
219 {
220 my $symbol = shift;
221 return $class->$orig(symbol => $symbol, @_);
222 }
223 return $class->$orig(@_);
224 };
225  
226 sub BUILD
227 {
228 my $self = shift;
229 $self->_p(AI::MXNet::Module::Private->new);
230 my $context = $self->context;
231 if(blessed $context)
232 {
233 $context = [$context];
234 }
235 $self->_p->_context($context);
236 my $work_load_list = $self->work_load_list;
237 if(not defined $work_load_list)
238 {
239 $work_load_list = [(1)x@{$self->_p->_context}];
240 }
241 assert(@{ $work_load_list } == @{ $self->_p->_context });
242 $self->_p->_work_load_list($work_load_list);
243 my @data_names = @{ $self->_data_names//['data'] };
244 my @label_names = @{ $self->_label_names//['softmax_label'] };
245 my @state_names = @{ $self->state_names//[] };
246 my $arg_names = $self->_symbol->list_arguments;
247 my @input_names = (@data_names, @label_names, @state_names);
248 my %input_names = map { $_ => 1 } @input_names;
249 $self->_p->_param_names([grep { not exists $input_names{$_} } @{ $arg_names }]);
250 $self->_p->_fixed_param_names($self->fixed_param_names//[]);
251 $self->_p->_state_names(\@state_names);
252 $self->_p->_aux_names($self->_symbol->list_auxiliary_states);
253 $self->_p->_data_names(\@data_names);
254 $self->_p->_label_names(\@label_names);
255 $self->_p->_output_names($self->_symbol->list_outputs);
256 $self->_p->_params_dirty(0);
257 $self->_check_input_names($self->_symbol, $self->_p->_data_names, "data", 1);
258 $self->_check_input_names($self->_symbol, $self->_p->_label_names, "label", 0);
259 $self->_check_input_names($self->_symbol, $self->_p->_state_names, "state", 1);
260 $self->_check_input_names($self->_symbol, $self->_p->_fixed_param_names, "fixed_param", 1);
261 }
262  
263 method Module(@args) { return @args ? __PACKAGE__->new(@args) : __PACKAGE__ }
264 method BucketingModule(@args) { return AI::MXNet::Module::Bucketing->new(@args) }
265  
266 =head2 load
267  
268 Create a model from previously saved checkpoint.
269  
270 Parameters
271 ----------
272 $prefix : Str
273 path prefix of saved model files. You should have
274 "prefix-symbol.json", "prefix-xxxx.params", and
275 optionally "prefix-xxxx.states", where xxxx is the
276 epoch number.
277 $epoch : Int
278 epoch to load.
279 $load_optimizer_states=0 : Bool
280 whether to load optimizer states. Checkpoint needs
281 to have been made with save_optimizer_states=True.
282 :$data_names : array ref of str
283 Default is ['data'] for a typical model used in image classification.
284 :$label_names : array ref of str
285 Default is ['softmax_label'] for a typical model used in image
286 classification.
287 :$logger : Logger
288 Default is AI::MXNet::Logging.
289 :$context : Context or list of Context
290 Default is cpu(0).
291 :$work_load_list : array ref of number
292 Default is undef, indicating an uniform workload.
293 :$fixed_param_names: array ref of str
294 Default is undef, indicating no network parameters are fixed.
295 =cut
296  
297 method load(
298 Str $prefix,
299 Int $epoch,
300 Bool $load_optimizer_states=0,
301 %kwargs
302 )
303 {
304 my ($sym, $args, $auxs) = __PACKAGE__->load_checkpoint($prefix, $epoch);
305 my $mod = $self->new(symbol => $sym, %kwargs);
306 $mod->_p->_arg_params($args);
307 $mod->_p->_aux_params($auxs);
308 $mod->params_initialized(1);
309 if($load_optimizer_states)
310 {
311 $mod->_p->_preload_opt_states(sprintf('%s-%04d.states', $prefix, $epoch));
312 }
313 return $mod;
314 }
315  
316 =head2 save_checkpoint
317  
318 Save current progress to a checkpoint.
319 Use mx->callback->module_checkpoint as epoch_end_callback to save during training.
320  
321 Parameters
322 ----------
323 $prefix : Str
324 The file prefix to checkpoint to
325 $epoch : Int
326 The current epoch number
327 $save_optimizer_states=0 : Bool
328 Whether to save optimizer states for later training
329 =cut
330  
331  
332 method save_checkpoint(Str $prefix, Int $epoch, Bool $save_optimizer_states=0)
333 {
334 $self->_symbol->save("$prefix-symbol.json");
335 my $param_name = sprintf('%s-%04d.params', $prefix, $epoch);
336 $self->save_params($param_name);
337 AI::MXNet::Logging->info('Saved checkpoint to "%s"', $param_name);
338 if($save_optimizer_states)
339 {
340 my $state_name = sprintf('%s-%04d.states', $prefix, $epoch);
341 $self->save_optimizer_states($state_name);
342 AI::MXNet::Logging->info('Saved optimizer state to "%s"', $state_name);
343 }
344 }
345  
346 =head2 model_save_checkpoint
347  
348 Checkpoint the model data into file.
349  
350 Parameters
351 ----------
352 $prefix : Str
353 Prefix of model name.
354 $epoch : Int
355 The epoch number of the model.
356 $symbol : AI::MXNet::Symbol
357 The input symbol
358 $arg_params : HashRef[AI::MXNet::NDArray]
359 Model's parameters, hash ref of name to AI::MXNet::NDArray of net's weights.
360 $aux_params : HashRef[AI::MXNet::NDArray]
361 Model's parameters, hash ref of name to AI::MXNet::NDArray of net's auxiliary states.
362 Notes
363 -----
364 - prefix-symbol.json will be saved for symbol.
365 - prefix-epoch.params will be saved for parameters.
366 =cut
367  
368 method model_save_checkpoint(
369 Str $prefix,
370 Int $epoch,
371 Maybe[AI::MXNet::Symbol] $symbol,
372 HashRef[AI::MXNet::NDArray] $arg_params,
373 HashRef[AI::MXNet::NDArray] $aux_params
374 )
375 {
376 if(defined $symbol)
377 {
378 $symbol->save("$prefix-symbol.json");
379 }
380 my $param_name = sprintf('%s-%04d.params', $prefix, $epoch);
381 $self->save_params($param_name, $arg_params, $aux_params);
382 AI::MXNet::Logging->info('Saved checkpoint to "%s"', $param_name);
383 }
384  
385 # Internal function to reset binded state.
386 method _reset_bind()
387 {
388 $self->binded(0);
389 $self->_p->_exec_group(undef);
390 $self->_p->_data_shapes(undef);
391 $self->_p->_label_shapes(undef);
392 }
393  
394 method data_names()
395 {
396 return $self->_p->_data_names;
397 }
398  
399 method label_names()
400 {
401 return $self->_p->_label_names;
402 }
403  
404 method output_names()
405 {
406 return $self->_p->_output_names;
407 }
408  
409 method data_shapes()
410 {
411 assert($self->binded);
412 return $self->_p->_data_shapes;
413 }
414  
415 method label_shapes()
416 {
417 assert($self->binded);
418 return $self->_p->_label_shapes;
419 }
420  
421 method output_shapes()
422 {
423 assert($self->binded);
424 return $self->_p->_exec_group->get_output_shapes;
425 }
426  
427 method get_params()
428 {
429 assert($self->binded and $self->params_initialized);
430 if($self->_p->_params_dirty)
431 {
432 $self->_sync_params_from_devices();
433 }
434 return ($self->_p->_arg_params, $self->_p->_aux_params);
435 }
436  
437 method init_params(
438 Maybe[AI::MXNet::Initializer] :$initializer=AI::MXNet::Initializer->Uniform(scale => 0.01),
439 Maybe[HashRef[AI::MXNet::NDArray]] :$arg_params=,
440 Maybe[HashRef[AI::MXNet::NDArray]] :$aux_params=,
441 Bool :$allow_missing=0,
442 Bool :$force_init=0,
443 Bool :$allow_extra=0
444 )
445 {
446 if($self->params_initialized and not $force_init)
447 {
448 AI::MXNet::Logging->warning(
449 "Parameters already initialized and force_init=0. "
450 ."init_params call ignored."
451 );
452 return;
453 }
454 assert($self->binded, 'call bind before initializing the parameters');
455 my $_impl = sub {
456 my ($name, $arr, $cache) = @_;
457 # Internal helper for parameter initialization
458 if(defined $cache)
459 {
460 if(exists $cache->{$name})
461 {
462 my $cache_arr = $cache->{$name};
463 # just in case the cached array is just the target itself
464 if($cache_arr->handle ne $arr->handle)
465 {
466 $cache_arr->copyto($arr);
467 }
468 }
469 else
470 {
471 if(not $allow_missing)
472 {
473 confess("$name is not presented");
474 }
475 if(defined $initializer)
476 {
477 $initializer->($name, $arr);
478 }
479 }
480 }
481 else
482 {
483 $initializer->($name, $arr) if defined $initializer;
484 }
485 };
486 my $attrs = $self->_symbol->attr_dict;
487 while(my ($name, $arr) = each %{ $self->_p->_arg_params })
488 {
489 $_impl->(
490 AI::MXNet::InitDesc->new(
491 name => $name,
492 ($attrs->{$name} ? (attrs => $attrs->{$name}) : ())
493 ),
494 $arr, $arg_params
495 );
496 }
497 while(my ($name, $arr) = each %{ $self->_p->_aux_params })
498 {
499 $_impl->(
500 AI::MXNet::InitDesc->new(
501 name => $name,
502 ($attrs->{$name} ? (attrs => $attrs->{$name}) : ())
503 ),
504 $arr, $aux_params
505 );
506 }
507 $self->params_initialized(1);
508 $self->_p->_params_dirty(0);
509  
510 # copy the initialized parameters to devices
511 $self->_p->_exec_group->set_params($self->_p->_arg_params, $self->_p->_aux_params, $allow_extra);
512 }
513  
514 method set_params(
515 HashRef[AI::MXNet::NDArray] $arg_params,
516 HashRef[AI::MXNet::NDArray] $aux_params,
517 Bool :$allow_missing=0,
518 Bool :$force_init=1,
519 Bool :$allow_extra=0
520 )
521 {
522 if(not $allow_missing)
523 {
524 $self->init_params(
525 arg_params => $arg_params, aux_params => $aux_params,
526 allow_missing => $allow_missing, force_init => $force_init,
527 allow_extra => $allow_extra
528 );
529 return;
530 }
531  
532 if($self->params_initialized and not $force_init)
533 {
534 AI::MXNet::Logging->warning(
535 "Parameters already initialized and force_init=False. "
536 ."set_params call ignored."
537 );
538 return;
539 }
540 $self->_p->_exec_group->set_params($arg_params, $aux_params, $allow_extra);
541 $self->_p->_params_dirty(1);
542 $self->params_initialized(1);
543 }
544  
545 =head2 bind
546  
547 Bind the symbols to construct executors. This is necessary before one
548 can perform computation with the module.
549  
550 Parameters
551 ----------
552 :$data_shapes : ArrayRef[AI::MXNet::DataDesc|NameShape]
553 Typically is $data_iter->provide_data.
554 :$label_shapes : Maybe[ArrayRef[AI::MXNet::DataDesc|NameShape]]
555 Typically is $data_iter->provide_label.
556 :$for_training : bool
557 Default is 1. Whether the executors should be bind for training.
558 :$inputs_need_grad : bool
559 Default is 0. Whether the gradients to the input data need to be computed.
560 Typically this is not needed. But this might be needed when implementing composition
561 of modules.
562 :$force_rebind : bool
563 Default is 0. This function does nothing if the executors are already
564 binded. But with this 1, the executors will be forced to rebind.
565 :$shared_module : Module
566 Default is undef. This is used in bucketing. When not undef, the shared module
567 essentially corresponds to a different bucket -- a module with different symbol
568 but with the same sets of parameters (e.g. unrolled RNNs with different lengths).
569 =cut
570  
571 method bind(
572 ArrayRef[AI::MXNet::DataDesc|NameShape] :$data_shapes,
573 Maybe[ArrayRef[AI::MXNet::DataDesc|NameShape]] :$label_shapes=,
574 Bool :$for_training=1,
575 Bool :$inputs_need_grad=0,
576 Bool :$force_rebind=0,
577 Maybe[AI::MXNet::Module] :$shared_module=,
578 GradReq|HashRef[GradReq]|ArrayRef[GradReq] :$grad_req='write',
579 Maybe[ArrayRef[Str]] :$state_names=$self->_p->_state_names
580 )
581 {
582 # force rebinding is typically used when one want to switch from
583 # training to prediction phase.
584 if($force_rebind)
585 {
586 $self->_reset_bind();
587 }
588 if($self->binded)
589 {
590 $self->logger->warning('Already binded, ignoring bind()');
591 return;
592 }
593 $self->for_training($for_training);
594 $self->inputs_need_grad($inputs_need_grad);
595 $self->binded(1);
596 $self->_p->_grad_req($grad_req);
597  
598 if(not $for_training)
599 {
600 assert(not $inputs_need_grad);
601 }
602 ($data_shapes, $label_shapes) = $self->_parse_data_desc(
603 $self->data_names, $self->label_names, $data_shapes, $label_shapes
604 );
605 $self->_p->_data_shapes($data_shapes);
606 $self->_p->_label_shapes($label_shapes);
607 my $shared_group;
608 if($shared_module)
609 {
610 assert($shared_module->binded and $shared_module->params_initialized);
611 $shared_group = $shared_module->_p->_exec_group;
612 }
613  
614 $self->_p->_exec_group(
615 AI::MXNet::DataParallelExecutorGroup->new(
616 symbol => $self->_symbol,
617 contexts => $self->_p->_context,
618 workload => $self->_p->_work_load_list,
619 data_shapes => $self->_p->_data_shapes,
620 label_shapes => $self->_p->_label_shapes,
621 param_names => $self->_p->_param_names,
622 state_names => $state_names,
623 for_training => $for_training,
624 inputs_need_grad => $inputs_need_grad,
625 shared_group => $shared_group,
626 logger => $self->logger,
627 fixed_param_names => $self->_p->_fixed_param_names,
628 grad_req => $grad_req
629 )
630 );
631 if($shared_module)
632 {
633 $self->params_initialized(1);
634 $self->_p->_arg_params($shared_module->_p->_arg_params);
635 $self->_p->_aux_params($shared_module->_p->_aux_params);
636 }
637 elsif($self->params_initialized)
638 {
639 # if the parameters are already initialized, we are re-binding
640 # so automatically copy the already initialized params
641 $self->_p->_exec_group->set_params($self->_p->_arg_params, $self->_p->_aux_params);
642 }
643 else
644 {
645 assert(not defined $self->_p->_arg_params and not $self->_p->_aux_params);
646 my @param_arrays = (
647 map { AI::MXNet::NDArray->zeros($_->[0]->shape, dtype => $_->[0]->dtype, stype => $_->[0]->stype) }
648 @{ $self->_p->_exec_group->_p->param_arrays }
649 );
650 my %arg_params;
651 @arg_params{ @{ $self->_p->_param_names } } = @param_arrays;
652 $self->_p->_arg_params(\%arg_params);
653 my @aux_arrays = (
654 map { AI::MXNet::NDArray->zeros($_->[0]->shape, dtype => $_->[0]->dtype) }
655 @{ $self->_p->_exec_group->_p->aux_arrays }
656 );
657 my %aux_params;
658 @aux_params{ @{ $self->_p->_aux_names } } = @aux_arrays;
659 $self->_p->_aux_params(\%aux_params);
660 }
661 if($shared_module and $shared_module->optimizer_initialized)
662 {
663 $self->borrow_optimizer($shared_module)
664 }
665 }
666  
667 =head2 reshape
668  
669 Reshape the module for new input shapes.
670 Parameters
671 ----------
672 :$data_shapes : ArrayRef[AI::MXNet::DataDesc]
673 Typically is $data_iter->provide_data.
674 :$label_shapes= : Maybe[ArrayRef[AI::MXNet::DataDesc]]
675 Typically is $data_iter->provide_label.
676 =cut
677  
678 method reshape(
679 ArrayRef[AI::MXNet::DataDesc|NameShape] :$data_shapes,
680 Maybe[ArrayRef[AI::MXNet::DataDesc|NameShape]] :$label_shapes=
681 )
682 {
683 assert($self->binded);
684 ($data_shapes, $label_shapes) = $self->_parse_data_desc(
685 $self->data_names, $self->label_names, $data_shapes, $label_shapes
686 );
687 $self->_p->_data_shapes($data_shapes);
688 $self->_p->_label_shapes($label_shapes);
689 $self->_p->_exec_group->reshape($self->_p->_data_shapes, $self->_p->_label_shapes);
690 }
691  
692 method init_optimizer(
693 Str|AI::MXNet::KVStore :$kvstore='local',
694 Optimizer :$optimizer='sgd',
695 HashRef :$optimizer_params={ learning_rate => 0.01 },
696 Bool :$force_init=0
697 )
698 {
699 assert($self->binded and $self->params_initialized);
700 if($self->optimizer_initialized and not $force_init)
701 {
702 $self->logger->warning('optimizer already initialized, ignoring...');
703 return;
704 }
705 if($self->_p->_params_dirty)
706 {
707 $self->_sync_params_from_devices;
708 }
709  
710 my ($kvstore, $update_on_kvstore) = _create_kvstore(
711 $kvstore,
712 scalar(@{$self->_p->_context}),
713 $self->_p->_arg_params
714 );
715 my $batch_size = $self->_p->_exec_group->_p->batch_size;
716 if($kvstore and $kvstore->type =~ /dist/ and $kvstore->type =~ /_sync/)
717 {
718 $batch_size *= $kvstore->num_workers;
719 }
720 my $rescale_grad = 1/$batch_size;
721  
722 if(not blessed $optimizer)
723 {
724 my %idx2name;
725 if($update_on_kvstore)
726 {
727 @idx2name{ 0..@{$self->_p->_exec_group->param_names}-1 } = @{$self->_p->_exec_group->param_names};
728 }
729 else
730 {
731 for my $k (0..@{$self->_p->_context}-1)
732 {
733 @idx2name{ map { $_ + $k } 0..@{$self->_p->_exec_group->param_names}-1 } = @{$self->_p->_exec_group->param_names};
734 }
735 }
736 if(not exists $optimizer_params->{rescale_grad})
737 {
738 $optimizer_params->{rescale_grad} = $rescale_grad;
739 }
740 $optimizer = AI::MXNet::Optimizer->create(
741 $optimizer,
742 sym => $self->symbol,
743 param_idx2name => \%idx2name,
744 %{ $optimizer_params }
745 );
746 if($optimizer->rescale_grad != $rescale_grad)
747 {
748 AI::MXNet::Logging->warning(
749 "Optimizer created manually outside Module but rescale_grad "
750 ."is not normalized to 1.0/batch_size/num_workers (%s vs. %s). "
751 ."Is this intended?",
752 $optimizer->rescale_grad, $rescale_grad
753 );
754 }
755 }
756  
757 $self->_p->_optimizer($optimizer);
758 $self->_p->_kvstore($kvstore);
759 $self->_p->_update_on_kvstore($update_on_kvstore);
760 $self->_p->_updater(undef);
761  
762 if($kvstore)
763 {
764 # copy initialized local parameters to kvstore
765 _initialize_kvstore(
766 kvstore => $kvstore,
767 param_arrays => $self->_p->_exec_group->_p->param_arrays,
768 arg_params => $self->_p->_arg_params,
769 param_names => $self->_p->_param_names,
770 update_on_kvstore => $update_on_kvstore
771 );
772 }
773 if($update_on_kvstore)
774 {
775 $kvstore->set_optimizer($self->_p->_optimizer);
776 }
777 else
778 {
779 $self->_p->_updater(AI::MXNet::Optimizer->get_updater($optimizer));
780 }
781 $self->optimizer_initialized(1);
782  
783 if($self->_p->_preload_opt_states)
784 {
785 $self->load_optimizer_states($self->_p->_preload_opt_states);
786 $self->_p->_preload_opt_states(undef);
787 }
788 }
789  
790 =head2 borrow_optimizer
791  
792 Borrow optimizer from a shared module. Used in bucketing, where exactly the same
793 optimizer (esp. kvstore) is used.
794  
795 Parameters
796 ----------
797 shared_module : AI::MXNet::Module
798 =cut
799  
800 method borrow_optimizer(AI::MXNet::Module $shared_module)
801 {
802 assert($shared_module->optimizer_initialized);
803 $self->_p->_optimizer($shared_module->_p->_optimizer);
804 $self->_p->_kvstore($shared_module->_p->_kvstore);
805 $self->_p->_update_on_kvstore($shared_module->_p->_update_on_kvstore);
806 $self->_p->_updater($shared_module->_p->_updater);
807 $self->optimizer_initialized(1);
808 }
809  
810 method forward(
811 AI::MXNet::DataBatch $data_batch,
812 Maybe[Bool] :$is_train=
813 )
814 {
815 assert($self->binded and $self->params_initialized);
816  
817 my @curr_data_shapes = map { $_->shape } @{ $self->data_shapes };
818 my @new_data_shapes = map { $_->shape } @{ $data_batch->data };
819 if(Data::Dumper->Dump(\@curr_data_shapes) ne Data::Dumper->Dump(\@new_data_shapes))
820 {
821 my $new_dshape;
822 if($data_batch->can('provide_data') and $data_batch->provide_data)
823 {
824 $new_dshape = $data_batch->provide_data;
825 }
826 else
827 {
828 $new_dshape = [];
829 for(zip($self->data_shapes, \@new_data_shapes)) {
830 my ($i, $shape) = @$_;
831 push @{ $new_dshape }, AI::MXNet::DataDesc->new(
832 $i->name, $shape, $i->dtype, $i->layout
833 );
834 }
835 }
836 my $new_lshape;
837 if($data_batch->can('provide_label') and $data_batch->provide_label)
838 {
839 $new_lshape = $data_batch->provide_label;
840 }
841 elsif($data_batch->can('label') and $data_batch->label)
842 {
843 $new_lshape = [];
844 for(zip($self->label_shapes, $data_batch->label)) {
845 my ($i, $j) = @$_;
846 push @{ $new_lshape }, AI::MXNet::DataDesc->new(
847 $i->name, $j->shape, $i->dtype, $i->layout
848 );
849 }
850 }
851 $self->reshape(data_shapes => $new_dshape, label_shapes => $new_lshape);
852 }
853 $self->_p->_exec_group->forward($data_batch, $is_train);
854 }
855  
856 method backward(Maybe[AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]] $out_grads=)
857 {
858 assert($self->binded and $self->params_initialized);
859 $self->_p->_exec_group->backward($out_grads);
860 }
861  
862 method update()
863 {
864 assert($self->binded and $self->params_initialized and $self->optimizer_initialized);
865 $self->_p->_params_dirty(1);
866 if($self->_p->_update_on_kvstore)
867 {
868 _update_params_on_kvstore(
869 $self->_p->_exec_group->_p->param_arrays,
870 $self->_p->_exec_group->_p->grad_arrays,
871 $self->_p->_kvstore,
872 $self->_p->_exec_group->param_names
873 );
874 }
875 else
876 {
877 _update_params(
878 $self->_p->_exec_group->_p->param_arrays,
879 $self->_p->_exec_group->_p->grad_arrays,
880 $self->_p->_updater,
881 scalar(@{ $self->_p->_context}),
882 $self->_p->_kvstore,
883 $self->_p->_exec_group->param_names
884 );
885 }
886 }
887  
888 method get_outputs(Bool $merge_multi_context=1)
889 {
890 assert($self->binded and $self->params_initialized);
891 return $self->_p->_exec_group->get_outputs($merge_multi_context);
892 }
893  
894 method get_input_grads(Bool $merge_multi_context=1)
895 {
896 assert($self->binded and $self->params_initialized and $self->inputs_need_grad);
897 return $self->_p->_exec_group->get_input_grads($merge_multi_context);
898 }
899  
900 method get_states(Bool $merge_multi_context=1)
901 {
902 assert($self->binded and $self->params_initialized);
903 return $self->_p->_exec_group->get_states($merge_multi_context);
904 }
905  
906 method set_states(:$states=, :$value=)
907 {
908 assert($self->binded and $self->params_initialized);
909 return $self->_p->_exec_group->set_states($states, $value);
910 }
911  
912 method update_metric(
913 AI::MXNet::EvalMetric $eval_metric,
914 ArrayRef[AI::MXNet::NDArray] $labels
915 )
916 {
917 $self->_p->_exec_group->update_metric($eval_metric, $labels);
918 }
919  
920 =head2 _sync_params_from_devices
921  
922 Synchronize parameters from devices to CPU. This function should be called after
923 calling 'update' that updates the parameters on the devices, before one can read the
924 latest parameters from $self->_arg_params and $self->_aux_params.
925 =cut
926  
927 method _sync_params_from_devices()
928 {
929 $self->_p->_exec_group->get_params($self->_p->_arg_params, $self->_p->_aux_params);
930 $self->_p->_params_dirty(0);
931 }
932  
933 method save_optimizer_states(Str $fname)
934 {
935 assert($self->optimizer_initialized);
936 if($self->_p->_update_on_kvstore)
937 {
938 $self->_p->_kvstore->save_optimizer_states($fname);
939 }
940 else
941 {
942 open(F, ">:raw", "$fname") or confess("can't open $fname for writing: $!");
943 print F $self->_p->_updater->get_states();
944 close(F);
945 }
946 }
947  
948 method load_optimizer_states(Str $fname)
949 {
950 assert($self->optimizer_initialized);
951 if($self->_p->_update_on_kvstore)
952 {
953 $self->_p->_kvstore->load_optimizer_states($fname);
954 }
955 else
956 {
957 open(F, "<:raw", "$fname") or confess("can't open $fname for reading: $!");
958 my $data;
959 { local($/) = undef; $data = <F>; }
960 close(F);
961 $self->_p->_updater->set_states($data);
962 }
963 }
964  
965 method install_monitor(AI::MXNet::Monitor $mon)
966 {
967 assert($self->binded);
968 $self->_p->_exec_group->install_monitor($mon);
969 }
970  
971 method _updater()
972 {
973 $self->_p->_updater;
974 }
975  
976 method _kvstore()
977 {
978 $self->_p->_kvstore;
979 }
980  
981 method _arg_params()
982 {
983 $self->_p->_arg_params;
984 }
985  
986  
987 1;