MXNet/Module/Bucketing.pm untested

filter: Statementstmt 0.0% 0 / 164 Branchbran 0.0% 0 / 28 Conditioncond 0.0% 0 / 55 MC/DCmcdc 0.0% 0 / 34 Subroutinesub 0.0% 0 / 4 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 286 CC 3 SCAR 19.5
CC
3
Cov
0%
BUILD
12.0
BEGIN
2.0
BEGIN
2.0
CRAP 7.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 package AI::MXNet::Module::Bucketing;
19 use Mouse;
20 use AI::MXNet::Function::Parameters;
21 use AI::MXNet::Base;
22  
23 =encoding UTF-8
24  
25 =head1 NAME
26  
27 AI::MXNet::Module::Bucketing
28  
29 =head1 SYNOPSIS
30  
31 my $buckets = [10, 20, 30, 40, 50, 60];
32 my $start_label = 1;
33 my $invalid_label = 0;
34  
35 my ($train_sentences, $vocabulary) = tokenize_text(
36 './data/sherlockholmes.train.txt', start_label => $start_label,
37 invalid_label => $invalid_label
38 );
39 my ($validation_sentences) = tokenize_text(
40 './data/sherlockholmes.test.txt', vocab => $vocabulary,
41 start_label => $start_label, invalid_label => $invalid_label
42 );
43 my $data_train = mx->rnn->BucketSentenceIter(
44 $train_sentences, $batch_size, buckets => $buckets,
45 invalid_label => $invalid_label
46 );
47 my $data_val = mx->rnn->BucketSentenceIter(
48 $validation_sentences, $batch_size, buckets => $buckets,
49 invalid_label => $invalid_label
50 );
51  
52 my $stack = mx->rnn->SequentialRNNCell();
53 for my $i (0..$num_layers-1)
54 {
55 $stack->add(mx->rnn->LSTMCell(num_hidden => $num_hidden, prefix => "lstm_l${i}_"));
56 }
57  
58 my $sym_gen = sub {
59 my $seq_len = shift;
60 my $data = mx->sym->Variable('data');
61 my $label = mx->sym->Variable('softmax_label');
62 my $embed = mx->sym->Embedding(
63 data => $data, input_dim => scalar(keys %$vocabulary),
64 output_dim => $num_embed, name => 'embed'
65 );
66 $stack->reset;
67 my ($outputs, $states) = $stack->unroll($seq_len, inputs => $embed, merge_outputs => 1);
68 my $pred = mx->sym->Reshape($outputs, shape => [-1, $num_hidden]);
69 $pred = mx->sym->FullyConnected(data => $pred, num_hidden => scalar(keys %$vocabulary), name => 'pred');
70 $label = mx->sym->Reshape($label, shape => [-1]);
71 $pred = mx->sym->SoftmaxOutput(data => $pred, label => $label, name => 'softmax');
72 return ($pred, ['data'], ['softmax_label']);
73 };
74  
75 my $contexts;
76 if(defined $gpus)
77 {
78 $contexts = [map { mx->gpu($_) } split(/,/, $gpus)];
79 }
80 else
81 {
82 $contexts = mx->cpu(0);
83 }
84  
85 my $model = mx->mod->BucketingModule(
86 sym_gen => $sym_gen,
87 default_bucket_key => $data_train->default_bucket_key,
88 context => $contexts
89 );
90  
91 $model->fit(
92 $data_train,
93 eval_data => $data_val,
94 eval_metric => mx->metric->Perplexity($invalid_label),
95 kvstore => $kv_store,
96 optimizer => $optimizer,
97 optimizer_params => {
98 learning_rate => $lr,
99 momentum => $mom,
100 wd => $wd,
101 },
102 initializer => mx->init->Xavier(factor_type => "in", magnitude => 2.34),
103 num_epoch => $num_epoch,
104 batch_end_callback => mx->callback->Speedometer($batch_size, $disp_batches),
105 ($chkp_epoch ? (epoch_end_callback => mx->rnn->do_rnn_checkpoint($stack, $chkp_prefix, $chkp_epoch)) : ())
106 );
107  
108 =head1 DESCRIPTION
109  
110 Implements the AI::MXNet::Module::Base API, and allows multiple
111 symbols to be used depending on the `bucket_key` provided by each different
112 mini-batch of data
113 =cut
114  
115  
116 =head2 new
117  
118 Parameters
119 ----------
120 $sym_gen : subref or any perl object that overloads &{} op
121 A sub when called with a bucket key, returns a list with triple
122 of ($symbol, $data_names, $label_names).
123 $default_bucket_key : str or anything else
124 The key for the default bucket.
125 $logger : Logger
126 $context : AI::MXNet::Context or array ref of AI::MXNet::Context objects
127 Default is cpu(0)
128 $work_load_list : array ref of Num
129 Default is undef, indicating uniform workload.
130 $fixed_param_names: arrayref of str
131 Default is undef, indicating no network parameters are fixed.
132 $state_names : arrayref of str
133 states are similar to data and label, but not provided by data iterator.
134 Instead they are initialized to 0 and can be set by set_states()
135 =cut
136  
137 extends 'AI::MXNet::Module::Base';
138 has '_sym_gen' => (is => 'ro', init_arg => 'sym_gen', required => 1);
139 has '_default_bucket_key' => (is => 'rw', init_arg => 'default_bucket_key', required => 1);
140 has '_context' => (
141 is => 'ro', isa => 'AI::MXNet::Context|ArrayRef[AI::MXNet::Context]',
142 lazy => 1, default => sub { AI::MXNet::Context->cpu },
143 init_arg => 'context'
144 );
145 has '_work_load_list' => (is => 'rw', init_arg => 'work_load_list', isa => 'ArrayRef[Num]');
146 has '_curr_module' => (is => 'rw', init_arg => undef);
147 has '_curr_bucket_key' => (is => 'rw', init_arg => undef);
148 has '_buckets' => (is => 'rw', init_arg => undef, default => sub { +{} });
149 has '_fixed_param_names' => (is => 'rw', isa => 'ArrayRef[Str]', init_arg => 'fixed_param_names');
150 has '_state_names' => (is => 'rw', isa => 'ArrayRef[Str]', init_arg => 'state_names');
151 has '_params_dirty' => (is => 'rw', init_arg => undef);
152  
153 sub BUILD
154 {
155 my ($self, $original_params) = @_;
156 $self->_fixed_param_names([]) unless defined $original_params->{fixed_param_names};
157 $self->_state_names([]) unless defined $original_params->{state_names};
158 $self->_params_dirty(0);
159 my ($symbol, $data_names, $label_names) = $self->_sym_gen->($self->_default_bucket_key);
160 $self->_check_input_names($symbol, $data_names//[], "data", 1);
161 $self->_check_input_names($symbol, $label_names//[], "label", 0);
162 $self->_check_input_names($symbol, $self->_state_names, "state", 1);
163 $self->_check_input_names($symbol, $self->_fixed_param_names, "fixed_param", 1);
164 }
165  
166 method _reset_bind()
167 {
168 $self->binded(0);
169 $self->_buckets({});
170 $self->_curr_module(undef);
171 $self->_curr_bucket_key(undef);
172 }
173  
174 method data_names()
175 {
176 if($self->binded)
177 {
178 return $self->_curr_module->data_names;
179 }
180 else
181 {
182 return ($self->_sym_gen->($self->_default_bucket_key))[1];
183 }
184 }
185  
186 method output_names()
187 {
188 if($self->binded)
189 {
190 return $self->_curr_module->ouput_names;
191 }
192 else
193 {
194 my ($symbol) = $self->_sym_gen->($self->_default_bucket_key);
195 return $symbol->list_ouputs;
196 }
197 }
198  
199 method data_shapes()
200 {
201 assert($self->binded);
202 return $self->_curr_module->data_shapes;
203 }
204  
205 method label_shapes()
206 {
207 assert($self->binded);
208 return $self->_curr_module->label_shapes;
209 }
210  
211 method output_shapes()
212 {
213 assert($self->binded);
214 return $self->_curr_module->output_shapes;
215 }
216  
217 method get_params()
218 {
219 assert($self->binded and $self->params_initialized);
220 $self->_curr_module->_p->_params_dirty($self->_params_dirty);
221 my ($arg_params, $aux_params) = $self->_curr_module->get_params;
222 $self->_params_dirty(0);
223 return ($arg_params, $aux_params);
224 }
225  
226 method set_params(
227 HashRef[AI::MXNet::NDArray] $arg_params,
228 HashRef[AI::MXNet::NDArray] $aux_params,
229 Bool $allow_missing=0,
230 Bool $force_init=1,
231 Bool $allow_extra=0
232 )
233 {
234 if(not $allow_missing)
235 {
236 $self->init_params(
237 arg_params => $arg_params, aux_params => $aux_params,
238 allow_missing => $allow_missing, force_init => $force_init,
239 allow_extra => $allow_extra
240 );
241 return;
242 }
243 if($self->params_initialized and not $force_init)
244 {
245 AI::MXNet::Logging->warning(
246 "Parameters already initialized and force_init=False. "
247 ."set_params call ignored."
248 );
249 return;
250 }
251 $self->_curr_module->set_params(
252 $arg_params, $aux_params,
253 allow_missing => $allow_missing,
254 force_init => $force_init,
255 allow_extra => $allow_extra
256 );
257 # because we didn't update self._arg_params, they are dirty now.
258 $self->_params_dirty(1);
259 $self->params_initialized(1);
260 }
261  
262 method init_params(
263 AI::MXNet::Initializer :$initializer=AI::MXNet::Initializer->Uniform(scale => 0.01),
264 Maybe[HashRef[AI::MXNet::NDArray]] :$arg_params=,
265 Maybe[HashRef[AI::MXNet::NDArray]] :$aux_params=,
266 Bool :$allow_missing=0,
267 Bool :$force_init=0,
268 Bool :$allow_extra=0
269 )
270 {
271 return if($self->params_initialized and not $force_init);
272 assert($self->binded, 'call bind before initializing the parameters');
273 $self->_curr_module->init_params(
274 initializer => $initializer,
275 arg_params => $arg_params,
276 aux_params => $aux_params,
277 allow_missing => $allow_missing,
278 force_init => $force_init,
279 allow_extra => $allow_extra
280 );
281 $self->_params_dirty(0);
282 $self->params_initialized(1);
283 }
284  
285 method get_states(Bool $merge_multi_context=1)
286 {
287 assert($self->binded and $self->params_initialized);
288 $self->_curr_module->get_states($merge_multi_context);
289 }
290  
291 method set_states(:$states=, :$value=)
292 {
293 assert($self->binded and $self->params_initialized);
294 $self->_curr_module->set_states(states => $states, value => $value);
295 }
296  
297 =head2 bind
298  
299 Binding for a AI::MXNet::Module::Bucketing means setting up the buckets and bind the
300 executor for the default bucket key. Executors corresponding to other keys are
301 binded afterwards with switch_bucket.
302  
303 Parameters
304 ----------
305 :$data_shapes : ArrayRef[AI::MXNet::DataDesc|NameShape]
306 This should correspond to the symbol for the default bucket.
307 :$label_shapes= : Maybe[ArrayRef[AI::MXNet::DataDesc|NameShape]]
308 This should correspond to the symbol for the default bucket.
309 :$for_training : Bool
310 Default is 1.
311 :$inputs_need_grad : Bool
312 Default is 0.
313 :$force_rebind : Bool
314 Default is 0.
315 :$shared_module : AI::MXNet::Module::Bucketing
316 Default is undef. This value is currently not used.
317 :$grad_req : str, array ref of str, hash ref of str to str
318 Requirement for gradient accumulation. Can be 'write', 'add', or 'null'
319 (defaults to 'write').
320 Can be specified globally (str) or for each argument (array ref, hash ref).
321 :$bucket_key : str
322 bucket key for binding. by default is to use the ->default_bucket_key
323 =cut
324  
325 method bind(
326 ArrayRef[AI::MXNet::DataDesc|NameShape] :$data_shapes,
327 Maybe[ArrayRef[AI::MXNet::DataDesc|NameShape]] :$label_shapes=,
328 Bool :$for_training=1,
329 Bool :$inputs_need_grad=0,
330 Bool :$force_rebind=0,
331 Maybe[AI::MXNet::BaseModule] :$shared_module=,
332 Str|ArrayRef[Str]|HashRef[Str] :$grad_req='write',
333 Maybe[Str] :$bucket_key=
334 )
335 {
336 # in case we already initialized params, keep it
337 my ($arg_params, $aux_params);
338 if($self->params_initialized)
339 {
340 ($arg_params, $aux_params) = $self->get_params;
341 }
342  
343 # force rebinding is typically used when one want to switch from
344 # training to prediction phase.
345 $self->_reset_bind if $force_rebind;
346  
347 if($self->binded)
348 {
349 $self->logger->warning('Already binded, ignoring bind()');
350 return;
351 }
352  
353 assert((not defined $shared_module), 'shared_module for BucketingModule is not supported');
354  
355 $self->for_training($for_training);
356 $self->inputs_need_grad($inputs_need_grad);
357 $self->binded(1);
358  
359 my ($symbol, $data_names, $label_names) = $self->_sym_gen->($bucket_key//$self->_default_bucket_key);
360 my $module = AI::MXNet::Module->new(
361 symbol => $symbol,
362 data_names => $data_names,
363 label_names => $label_names,
364 logger => $self->logger,
365 context => $self->_context,
366 work_load_list => $self->_work_load_list,
367 state_names => $self->_state_names,
368 fixed_param_names => $self->_fixed_param_names
369 );
370 $module->bind(
371 data_shapes => $data_shapes,
372 label_shapes => $label_shapes,
373 for_training => $for_training,
374 inputs_need_grad => $inputs_need_grad,
375 force_rebind => 0,
376 shared_module => undef,
377 grad_req => $grad_req
378 );
379 $self->_curr_module($module);
380 $self->_curr_bucket_key($self->_default_bucket_key);
381 $self->_buckets->{ $self->_default_bucket_key } = $module;
382  
383 # copy back saved params, if already initialized
384 if($self->params_initialized)
385 {
386 $self->set_params($arg_params, $aux_params);
387 }
388 }
389  
390 =head2 switch_bucket
391  
392 Switch to a different bucket. This will change $self->_curr_module.
393  
394 Parameters
395 ----------
396 :$bucket_key : str (or any perl object that overloads "" op)
397 The key of the target bucket.
398 :$data_shapes : Maybe[ArrayRef[AI::MXNet::DataDesc|NameShape]]
399 Typically $data_batch->provide_data.
400 :$label_shapes : Maybe[ArrayRef[AI::MXNet::DataDesc|NameShape]]
401 Typically $data_batch->provide_label.
402 =cut
403  
404 method switch_bucket(
405 Maybe[ArrayRef[AI::MXNet::DataDesc|NameShape]] :$data_shapes=,
406 Maybe[ArrayRef[AI::MXNet::DataDesc|NameShape]] :$label_shapes=,
407 :$bucket_key
408 )
409 {
410 assert($self->binded, 'call bind before switching bucket');
411 if(not exists $self->_buckets->{ $bucket_key })
412 {
413 my ($symbol, $data_names, $label_names) = $self->_sym_gen->($bucket_key);
414 my $module = AI::MXNet::Module->new(
415 symbol => $symbol,
416 data_names => $data_names,
417 label_names => $label_names,
418 logger => $self->logger,
419 context => $self->_context,
420 work_load_list => $self->_work_load_list
421 );
422 $module->bind(
423 data_shapes => $data_shapes,
424 label_shapes => $label_shapes,
425 for_training => $self->_curr_module->for_training,
426 inputs_need_grad => $self->_curr_module->inputs_need_grad,
427 force_rebind => 0,
428 shared_module => $self->_buckets->{ $self->_default_bucket_key },
429 );
430 $self->_buckets->{ $bucket_key } = $module;
431 }
432 $self->_curr_module($self->_buckets->{ $bucket_key });
433 $self->_curr_bucket_key($bucket_key);
434 }
435  
436 method init_optimizer(
437 Str :$kvstore='local',
438 Optimizer :$optimizer='sgd',
439 HashRef :$optimizer_params={ learning_rate => 0.01 },
440 Bool :$force_init=0
441 )
442 {
443 assert($self->binded and $self->params_initialized);
444 if($self->optimizer_initialized and not $force_init)
445 {
446 $self->logger->warning('optimizer already initialized, ignoring.');
447 return;
448 }
449  
450 $self->_curr_module->init_optimizer(
451 kvstore => $kvstore,
452 optimizer => $optimizer,
453 optimizer_params => $optimizer_params,
454 force_init => $force_init
455 );
456 for my $mod (values %{ $self->_buckets })
457 {
458 if($mod ne $self->_curr_module)
459 {
460 $mod->borrow_optimizer($self->_curr_module);
461 }
462 }
463 $self->optimizer_initialized(1);
464 }
465  
466 method prepare(AI::MXNet::DataBatch $data_batch)
467 {
468 assert($self->binded and $self->params_initialized);
469 ## perform bind if have not done so yet
470 my $original_bucket_key = $self->_curr_bucket_key;
471 $self->switch_bucket(
472 bucket_key => $data_batch->bucket_key,
473 data_shapes => $data_batch->provide_data,
474 label_shapes => $data_batch->provide_label
475 );
476 # switch back
477 $self->switch_bucket(bucket_key => $original_bucket_key);
478 }
479  
480 method forward(
481 AI::MXNet::DataBatch $data_batch,
482 Bool :$is_train=
483 )
484 {
485 assert($self->binded and $self->params_initialized);
486 $self->switch_bucket(
487 bucket_key => $data_batch->bucket_key,
488 data_shapes => $data_batch->provide_data,
489 label_shapes => $data_batch->provide_label
490 );
491 $self->_curr_module->forward($data_batch, is_train => $is_train);
492 }
493  
494 method backward(Maybe[ArrayRef[AI::MXNet::NDArray]|AI::MXNet::NDArray] $out_grads=)
495 {
496 assert($self->binded and $self->params_initialized);
497 $self->_curr_module->backward($out_grads);
498 }
499  
500 method update()
501 {
502 assert($self->binded and $self->params_initialized and $self->optimizer_initialized);
503 $self->_params_dirty(1);
504 $self->_curr_module->update;
505 }
506  
507 method get_outputs(Bool $merge_multi_context=1)
508 {
509 assert($self->binded and $self->params_initialized);
510 return $self->_curr_module->get_outputs($merge_multi_context);
511 }
512  
513 method get_input_grads(Bool $merge_multi_context=1)
514 {
515 assert($self->binded and $self->params_initialized and $self->inputs_need_grad);
516 return $self->_curr_module->get_input_grads($merge_multi_context);
517 }
518  
519 method update_metric(
520 AI::MXNet::EvalMetric $eval_metric,
521 ArrayRef[AI::MXNet::NDArray] $labels
522 )
523 {
524 assert($self->binded and $self->params_initialized);
525 $self->_curr_module->update_metric($eval_metric, $labels);
526 }
527  
528 method symbol()
529 {
530 assert($self->binded);
531 return $self->_curr_module->symbol;
532 }
533  
534 method get_symbol()
535 {
536 assert($self->binded);
537 return $self->_buckets->{ $self->_default_bucket_key }->symbol;
538 }
539  
540 method install_monitor(AI::MXNet::Monitor $mon)
541 {
542 assert($self->binded);
543 for my $mod (values %{ $self->_buckets })
544 {
545 $mod->install_monitor($mon);
546 }
547 }
548  
549 =head2 save_checkpoint
550  
551 Save current progress to a checkpoint.
552 Use mx->callback->module_checkpoint as epoch_end_callback to save during training.
553  
554 Parameters
555 ----------
556 prefix : str
557 The file prefix to checkpoint to
558 epoch : int
559 The current epoch number
560 save_optimizer_states : bool
561 Whether to save optimizer states for later training
562 =cut
563  
564  
565 method save_checkpoint(Str $prefix, Int $epoch, Bool $save_optimizer_states=0)
566 {
567 my %buckets = %{ $self->_buckets };
568 while(my ($key, $module) = each %buckets)
569 {
570 $module->save_checkpoint("${prefix}_$key", $epoch, $save_optimizer_states);
571 }
572 }
573  
574 1;