MXNet/Gluon/Trainer.pm untested

filter: Statementstmt 0.0% 0 / 226 Branchbran 0.0% 0 / 84 Conditioncond 0.0% 0 / 40 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 7 Podpod n/a totaltotal 0.0% 0 / 357 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::Gluon::Trainer;
21 use AI::MXNet::NS;
22 use AI::MXNet::Base;
23 use AI::MXNet::Function::Parameters;
24 use IO::File;
25 use Mouse;
26  
27  
28 =head1 NAME
29  
30 AI::MXNet::Gluon::Trainer
31 =cut
32  
33 =head1 DESCRIPTION
34  
35 Applies an `Optimizer` on a set of Parameters. Trainer should
36 be used together with `autograd`.
37  
38 Parameters
39 ----------
40 params : AI::MXNet::Gluon::ParameterDict
41 The set of parameters to optimize.
42 optimizer : str or Optimizer
43 The optimizer to use. See
44 `help <https://mxnet.io/api/python/optimization/optimization.html#the-mxnet-optimizer-package>`_
45 on Optimizer for a list of available optimizers.
46 optimizer_params : hash ref
47 Key-word arguments to be passed to optimizer constructor. For example,
48 {learning_rate => 0.1}. All optimizers accept learning_rate, wd (weight decay),
49 clip_gradient, and lr_scheduler. See each optimizer's
50 constructor for a list of additional supported arguments.
51 kvstore : str or KVStore
52 kvstore type for multi-gpu and distributed training. See help on
53 mx->kvstore->create for more information.
54 compression_params : hash ref
55 Specifies type of gradient compression and additional arguments depending
56 on the type of compression being used. For example, 2bit compression requires a threshold.
57 Arguments would then be {type => '2bit', threshold => 0.5}
58 See AI::MXNet::KVStore->set_gradient_compression method for more details on gradient compression.
59 update_on_kvstore : Bool, default undef
60 Whether to perform parameter updates on kvstore. If undef, then trainer will choose the more
61 suitable option depending on the type of kvstore.
62  
63 Properties
64 ----------
65 learning_rate : float
66 The current learning rate of the optimizer. Given an Optimizer object
67 optimizer, its learning rate can be accessed as optimizer->learning_rate.
68 =cut
69  
70 has 'params' => (is => 'rw', isa => 'HashRef|ArrayRef|AI::MXNet::Gluon::ParameterDict');
71 has 'optimizer' => (is => 'ro', isa => 'Optimizer');
72 has 'optimizer_params' => (is => 'ro', isa => 'Maybe[HashRef]');
73 has 'compression_params' => (is => 'ro', isa => 'Maybe[HashRef]');
74 has 'kvstore' => (is => 'rw', isa => 'Maybe[KVStore]', default => 'device');
75 has 'update_on_kvstore' => (is => 'rw', isa => 'Maybe[Bool]');
76 has [qw/_scale _contexts
77 _kv_initialized
78 _param2idx
79 _kvstore_params
80 _contains_sparse
81 _params_to_init
82 _updaters
83 _optimizer/] => (is => 'rw', init_arg => undef);
84 around BUILDARGS => \&AI::MXNet::Base::process_arguments;
85 method python_constructor_arguments()
86 {
87 [qw/params optimizer optimizer_params kvstore compression_params update_on_kvstore/]
88 }
89  
90 sub BUILD
91 {
92 my $self = shift;
93 my @params;
94 if(blessed $self->params)
95 {
96 @params = $self->params->values;
97 }
98 elsif(ref $self->params eq 'HASH')
99 {
100 @params = values %{ $self->params };
101 }
102 else
103 {
104 @params = @{ $self->params };
105 }
106 $self->params([]);
107 $self->_contains_sparse(0);
108 $self->_param2idx({});
109 for(enumerate(\@params))
110 {
111 my ($i, $param) = @$_;
112 if(not(blessed $param and $param->isa('AI::MXNet::Gluon::Parameter')))
113 {
114 confess(
115 "First argument must be a array or hash of Parameters, ".
116 "got list of [$param]."
117 );
118 }
119 $self->_param2idx->{ $param->name } = $i;
120 push @{ $self->params }, $param;
121 $param->_set_trainer($self);
122 if($param->stype ne 'default')
123 {
124 $self->_contains_sparse(1);
125 }
126 }
127 my $optimizer_params = $self->optimizer_params//{};
128 $self->_scale(delete $optimizer_params->{rescale_grad}//1);
129 $self->_contexts($self->_check_contexts);
130 $self->_init_optimizer($self->optimizer, $optimizer_params);
131 $self->_kvstore_params({
132 kvstore => $self->kvstore,
133 update_on_kvstore => $self->update_on_kvstore
134 });
135 $self->_kv_initialized(0);
136 $self->kvstore(undef);
137 $self->update_on_kvstore(undef);
138 $self->_params_to_init([]);
139 $self->_reset_kvstore();
140 }
141  
142 method _check_contexts()
143 {
144 my $contexts;
145 for my $param (@{ $self->params })
146 {
147 my $ctx = $param->list_ctx;
148 assert(
149 (not defined $contexts or join('', @{ $contexts }) eq join('', @{ $ctx })),
150 "All Parameters must be initialized on the same set of contexts, ".
151 "but Parameter ${\ $param->name } is initialized on @{ $ctx//[] } while previous Parameters ".
152 "are initialized on @{ $contexts//[] }."
153 );
154 $contexts = $ctx;
155 }
156 return $contexts;
157 }
158  
159 method _init_optimizer($optimizer, $optimizer_params)
160 {
161 my %param_dict = map { $_ => $self->params->[$_] } 0 .. @{ $self->params } - 1;
162 if(blessed $optimizer and $optimizer->isa('AI::MXNet::Optimizer'))
163 {
164 assert(
165 (not %{ $optimizer_params }),
166 "optimizer_params must be empty if optimizer is an instance of ".
167 "Optimizer instead of str"
168 );
169 $self->_optimizer($optimizer);
170 $self->_optimizer->param_dict(\%param_dict);
171 }
172 else
173 {
174 $self->_optimizer(
175 AI::MXNet::Optimizer->create(
176 $optimizer, param_dict => \%param_dict,
177 %{ $optimizer_params }
178 )
179 );
180 }
181 $self->_updaters([
182 map { AI::MXNet::Optimizer->get_updater($self->_optimizer) } @{ $self->_contexts }
183 ]);
184 }
185  
186 method _init_params()
187 {
188 assert(
189 $self->_kv_initialized,
190 "Cannot initialize parameters in KVStore ".
191 "when KVStore is not initialized."
192 );
193 my @params_to_init;
194 if($self->kvstore)
195 {
196 for my $param (@{ $self->_params_to_init })
197 {
198 if(@{ $param->_deferred_init })
199 {
200 push @params_to_init, $param;
201 }
202 else
203 {
204 my $param_arrays = $param->_check_and_get($param->_data, []);
205 my $idx = $self->_param2idx->{ $param->name };
206 $self->kvstore->init($idx, $param_arrays->[0]);
207 if($param->stype eq 'default')
208 {
209 $self->kvstore->pull($idx, out => $param_arrays, priority=>-$idx);
210 }
211 }
212 }
213 }
214 $self->_params_to_init(\@params_to_init);
215 }
216  
217 method _reset_kvstore()
218 {
219 if($self->kvstore and $self->kvstore->type =~ /dist/)
220 {
221 confess("Cannot reset distributed KVStore.");
222 }
223 $self->_kv_initialized(0);
224 $self->kvstore(undef);
225 $self->update_on_kvstore(undef);
226 $self->_params_to_init([@{ $self->params }]);
227 }
228  
229 method _init_kvstore()
230 {
231 my $config = $self->_kvstore_params;
232 my ($kvstore, $update_on_kvstore);
233 if($self->_contains_sparse)
234 {
235 ($kvstore, $update_on_kvstore) = AI::MXNet::Module::_create_sparse_kvstore($config->{kvstore});
236 # update_on_kvstore is set to False by the user
237 if(defined $config->{update_on_kvstore} and not $config->{update_on_kvstore})
238 {
239 confess(
240 "Cannot set update_on_kvstore to False when sparse ".
241 "gradients and/or sparse weights are present."
242 )
243 }
244 }
245 else
246 {
247 my %arg_arrays = map { $_->name => $_->data($self->_contexts->[0]) } @{ $self->params };
248 ($kvstore, $update_on_kvstore) = AI::MXNet::Module::_create_kvstore(
249 $config->{kvstore}, scalar(@{$self->_contexts }), \%arg_arrays
250 );
251 if(defined $config->{update_on_kvstore})
252 {
253 $update_on_kvstore = $config->{update_on_kvstore};
254 }
255 }
256 if($kvstore)
257 {
258 if($self->compression_params)
259 {
260 $kvstore->set_gradient_compression($self->compression_params);
261 }
262 # kv->pull(row_sparse_grad) is not supported
263 if($kvstore->type =~ /dist/ and not $self->_contains_sparse)
264 {
265 $update_on_kvstore = 0;
266 }
267 if($update_on_kvstore)
268 {
269 # optimizer preferably needs to be set before init for multiprecision
270 $kvstore->set_optimizer($self->_optimizer);
271 }
272 $self->kvstore($kvstore);
273 $self->update_on_kvstore($update_on_kvstore);
274 }
275 else
276 {
277 $self->kvstore(undef);
278 $self->update_on_kvstore(undef);
279 }
280 $self->_kv_initialized(1);
281 }
282  
283 # Internal method to invoke pull operations on KVStore. If $full_idx is set to 1,
284 # $kv->pull is preferred instead of $kv->row_sparse_pull.
285  
286 method _row_sparse_pull($parameter, $out, $row_id, $full_idx=0)
287 {
288 # initialize kv and params if not already
289 $self->_init_kvstore() unless $self->_kv_initialized;
290 $self->_init_params() if scalar(@{ $self->_params_to_init });
291 my $idx = $self->_param2idx->{ $parameter->name };
292 if($full_idx and not $self->kvstore->type =~ /dist/)
293 {
294 assert($row_id->size == $out->shape->[0]);
295 $self->kvstore->pull($idx, out => $out, priority => -$idx, ignore_sparse => 0);
296 }
297 else
298 {
299 $self->kvstore->row_sparse_pull($idx, out => $out, row_ids => $row_id, priority => -$idx);
300 }
301 }
302  
303 =head2 step
304  
305 Makes one step of parameter update. Should be called after
306 `autograd->backward()` and outside of `record()` scope.
307  
308 For normal parameter updates, `step()` should be used, which internally calls
309 `allreduce_grads()` and then `update()`. However, if you need to get the reduced
310 gradients to perform certain transformation, such as in gradient clipping, then
311 you may want to manually call `allreduce_grads()` and `update()` separately.
312  
313 Parameters
314 ----------
315 $batch_size : Int
316 Batch size of data processed. Gradient will be normalized by `1/batch_size`.
317 Set this to 1 if you normalized loss manually with `loss = mean(loss)`.
318 $ignore_stale_grad : Bool, optional, default=False
319 If true, ignores Parameters with stale gradient (gradient that has not
320 been updated by `backward` after last step) and skip update.
321 =cut
322  
323 method step(Int $batch_size, Bool $ignore_stale_grad=0)
324 {
325 $self->_init_kvstore() unless $self->_kv_initialized;
326 $self->_init_params() if scalar(@{ $self->_params_to_init });
327 $self->_optimizer->rescale_grad($self->_scale/$batch_size);
328 $self->_allreduce_grads();
329 $self->_update($ignore_stale_grad);
330 }
331  
332 =head2 allreduce_grads
333  
334 For each parameter, reduce the gradients from different contexts.
335  
336 Should be called after `autograd.backward()`, outside of `record()` scope,
337 and before `trainer.update()`.
338  
339 For normal parameter updates, `step()` should be used, which internally calls
340 `allreduce_grads()` and then `update()`. However, if you need to get the reduced
341 gradients to perform certain transformation, such as in gradient clipping, then
342 you may want to manually call `allreduce_grads()` and `update()` separately.
343 =cut
344  
345 method allreduce_grads()
346 {
347 $self->_init_kvstore() unless $self->_kv_initialized;
348 $self->_init_params() if scalar(@{ $self->_params_to_init });
349 assert(
350 (not ($self->kvstore and $self->update_on_kvstore)),
351 'allreduce_grads() when parameters are updated on kvstore '.
352 'is not supported. Try setting `update_on_kvstore` '.
353 'to False when creating trainer.'
354 );
355 $self->_allreduce_grads();
356 }
357  
358 method _allreduce_grads()
359 {
360 if($self->kvstore)
361 {
362 for(enumerate($self->params))
363 {
364 my ($i, $param) = @$_;
365 if($param->grad_req ne 'null')
366 {
367 $self->kvstore->push($i, $param->list_grad(), priority=>-$i);
368 if(not $self->update_on_kvstore)
369 {
370 $self->kvstore->pull($i, out => $param->list_grad(), priority=>-$i);
371 }
372 }
373 }
374 }
375 }
376  
377 method learning_rate(Maybe [Num] $lr)
378 {
379 if(not blessed $self->_optimizer)
380 {
381 AI::MXNet::Logging->warning(
382 "Optimizer has to be defined before its learning ".
383 "rate can be accessed."
384 );
385 return;
386 }
387 else
388 {
389 if(defined $lr)
390 {
391 $self->_optimizer->lr($lr);
392 }
393 return $self->_optimizer->lr;
394 }
395 }
396  
397 =head2 set_learning_rate
398  
399 Sets a new learning rate of the optimizer.
400  
401 Parameters
402 ----------
403 lr : float
404 The new learning rate of the optimizer.
405 =cut
406  
407 method set_learning_rate(Num $lr)
408 {
409 $self->learning_rate($lr);
410 }
411  
412 =head2 update
413  
414 Makes one step of parameter update.
415  
416 Should be called after autograd->backward() and outside of record() scope,
417 and after trainer->update`.
418  
419  
420 For normal parameter updates, step() should be used, which internally calls
421 allreduce_grads() and then update(). However, if you need to get the reduced
422 gradients to perform certain transformation, such as in gradient clipping, then
423 you may want to manually call allreduce_grads() and update() separately.
424  
425 Parameters
426 ----------
427 $batch_size : Int
428 Batch size of data processed. Gradient will be normalized by `1/$batch_size`.
429 Set this to 1 if you normalized loss manually with $loss = mean($loss).
430 $ignore_stale_grad : Bool, optional, default=False
431 If true, ignores Parameters with stale gradient (gradient that has not
432 been updated by backward() after last step) and skip update.
433 =cut
434  
435 method update(Int $batch_size, Bool $ignore_stale_grad=0)
436 {
437 $self->_init_kvstore() unless $self->_kv_initialized;
438 $self->_init_params() if scalar(@{ $self->_params_to_init });
439 assert(
440 (not ($self->kvstore and $self->update_on_kvstore)),
441 'update() when parameters are updated on kvstore '.
442 'is not supported. Try setting `update_on_kvstore` '.
443 'to False when creating trainer.'
444 );
445 $self->_optimizer->rescale_grad($self->_scale/$batch_size);
446 $self->_update($ignore_stale_grad);
447 }
448  
449 method _update(Bool $ignore_stale_grad=0):
450 {
451 for(enumerate($self->params))
452 {
453 my ($i, $param) = @$_;
454 next if($param->grad_req eq 'null');
455  
456 if(not $ignore_stale_grad)
457 {
458 for my $data (@{ $param->_check_and_get($param->_data, []) })
459 {
460 if(not $data->_fresh_grad)
461 {
462 AI::MXNet::Logging->warning(
463 "Gradient of Parameter '%s' on context %s has not been updated ".
464 "by backward since last `step`. This could mean a bug in your ".
465 "model that made it only use a subset of the Parameters (Blocks) ".
466 "for this iteration. If you are intentionally only using a subset, ".
467 "call step with ignore_stale_grad=True to suppress this ".
468 "warning and skip updating of Parameters with stale gradient",
469 $param->name, $data->context
470 );
471 }
472 }
473 }
474 if($self->kvstore and $self->update_on_kvstore)
475 {
476 if($param->stype eq 'default')
477 {
478 # 'row_sparse' parameters are not pulled immediately - they're pulled
479 # in `SparseBlock.sparse_forward`
480 $self->kvstore->pull($i, out => $param->list_data(), priority=>-$i);
481 }
482 next;
483 }
484  
485 for(zip($self->_updaters, $param->list_data(), $param->list_grad()))
486 {
487 my ($upd, $arr, $grad) = @$_;
488 if(not $ignore_stale_grad or $arr->_fresh_grad)
489 {
490 $upd->($i, $grad, $arr);
491 $arr->_fresh_grad(0);
492 }
493 }
494 }
495 }
496  
497 =head2 save_states
498  
499 Saves trainer states (e.g. optimizer, momentum) to a file.
500  
501 Parameters
502 ----------
503 fname : str
504 Path to output states file.
505 =cut
506  
507 method save_states(Str $fname)
508 {
509 assert(defined $self->_optimizer);
510 $self->_init_kvstore() unless $self->_kv_initialized;
511 $self->_init_params() if scalar(@{ $self->_params_to_init });
512  
513 if($self->update_on_kvstore)
514 {
515 $self->kvstore->save_optimizer_states($fname, dump_optimizer=>1);
516 }
517 else
518 {
519 open(F, ">$fname") or Carp::confess("can not open $fname: $1");
520 print F $self->_updaters->[0]->get_states(dump_optimizer => 1);
521 close(F);
522 }
523 }
524  
525 =head2 load_states
526  
527 Loads trainer states (e.g. optimizer, momentum) from a file.
528  
529 Parameters
530 ----------
531 fname : str
532 Path to input states file.
533 =cut
534  
535 method load_states(Str $fname)
536 {
537 $self->_init_kvstore() unless $self->_kv_initialized;
538 $self->_init_params() if scalar(@{ $self->_params_to_init });
539  
540 if($self->update_on_kvstore)
541 {
542 $self->kvstore->load_optimizer_states($fname);
543 $self->_optimizer($self->kvstore->_updater->optimizer);
544 $self->_optimizer->param_dict({ map { $_->[0] => $_->[1] } enumerate($self->params) });
545 }
546 else
547 {
548 my $states = join('', IO::File->new($fname)->getlines);
549 for my $updater (@{ $self->_updaters })
550 {
551 $updater->set_states($states);
552 $updater->optimizer($self->_updaters->[0]->optimizer);
553 }
554 $self->_optimizer($self->_updaters->[0]->optimizer);
555 }
556 }
557  
558 __PACKAGE__->AI::MXNet::NS::register('AI::MXNet::Gluon');
559  
560 1;