MXNet/KVStore.pm untested

filter: Statementstmt 0.0% 0 / 138 Branchbran 0.0% 0 / 18 Conditioncond 0.0% 0 / 16 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 184 CC 1 SCAR 6.9
CC
1
Cov
0%
DEMOLISH
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 package AI::MXNet::KVStore;
19 use strict;
20 use warnings;
21 use AI::MXNet::NS;
22 use AI::MXNet::Base;
23 use AI::MXNet::NDArray;
24 use AI::MXNet::Optimizer;
25 use MIME::Base64;
26 use Storable;
27 use Mouse;
28 use AI::MXNet::Function::Parameters;
29  
30 =head1 NAME
31  
32 AI::MXNet::KVStore - Key value store interface of MXNet.
33  
34 =head1 DESCRIPTION
35  
36 Key value store interface of MXNet for parameter synchronization, over multiple devices.
37 =cut
38  
39 has 'handle' => (is => 'ro', isa => 'KVStoreHandle', required => 1);
40 has '_updater' => (is => 'rw', isa => 'AI::MXNet::Updater');
41  
42 sub DEMOLISH
43 {
44 check_call(AI::MXNetCAPI::KVStoreFree(shift->handle));
45 }
46  
47 =head2 init
48  
49 Initialize a single or a sequence of key-value pairs into the store.
50 For each key, one must init it before push and pull.
51 Only worker 0's (rank == 0) data are used.
52 This function returns after data have been initialized successfully
53  
54 Parameters
55 ----------
56 $key : Str|ArrayRef[Str]
57 The keys.
58 $value : AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]|ArrayRef[ArrayRef[AI::MXNet::NDArray]]
59 The values.
60  
61 Examples
62 --------
63 >>> # init a single key-value pair
64 >>> $shape = [2,3]
65 >>> $kv = mx->kv->create('local')
66 >>> $kv->init(3, mx->nd->ones($shape)*2)
67 >>> $a = mx->nd->zeros($shape)
68 >>> $kv->pull(3, out=>$a)
69 >>> print $a->aspdl
70 [[ 2 2 2]
71 [ 2 2 2]]
72  
73 >>> # init a list of key-value pairs
74 >>> $keys = [5, 7, 9]
75 >>> $kv->init(keys, [map { mx->nd->ones($shape) } 0..@$keys-1])
76 =cut
77  
78 method init(
79 Str|ArrayRef[Str] $key,
80 AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]|ArrayRef[ArrayRef[AI::MXNet::NDArray]] $value
81 )
82 {
83 my ($keys, $vals) = _key_value($key, $value);
84 check_call(
85 AI::MXNetCAPI::KVStoreInitEx(
86 $self->handle, scalar(@{ $keys }), $keys, $vals
87 )
88 );
89 }
90  
91 =head2 push
92  
93 Push a single or a sequence of key-value pairs into the store.
94 Data consistency:
95 1. this function returns after adding an operator to the engine.
96 2. push is always called after all previous push and pull on the same
97 key are finished.
98 3. there is no synchronization between workers. One can use _barrier()
99 to sync all workers.
100  
101 Parameters
102 ----------
103 $key : Str|ArrayRef[Str]
104 $value : AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]|ArrayRef[ArrayRef[AI::MXNet::NDArray]]
105 :$priority=0 : Int, optional
106 The priority of the push operation.
107 The higher the priority, the faster this action is likely
108 to be executed before other push actions.
109  
110 Examples
111 --------
112 >>> # push a single key-value pair
113 >>> $kv->push(3, mx->nd->ones($shape)*8)
114 >>> $kv->pull(3, out=>$a) # pull out the value
115 >>> print $a->aspdl()
116 [[ 8. 8. 8.]
117 [ 8. 8. 8.]]
118  
119 >>> # aggregate the value and the push
120 >>> $gpus = [map { mx->gpu($_) } 0..3]
121 >>> $b = [map { mx->nd->ones($shape, ctx => $_) } @$gpus]
122 >>> $kv->push(3, $b)
123 >>> $kv->pull(3, out=>$a)
124 >>> print $a->aspdl
125 [[ 4. 4. 4.]
126 [ 4. 4. 4.]]
127  
128 >>> # push a list of keys.
129 >>> # single device
130 >>> $kv->push($keys, [map { mx->nd->ones($shape) } 0..@$keys-1)
131 >>> $b = [map { mx->nd->zeros(shape) } 0..@$keys-1]
132 >>> $kv->pull($keys, out=>$b)
133 >>> print $b->[1]->aspdl
134 [[ 1. 1. 1.]
135 [ 1. 1. 1.]]
136  
137 >>> # multiple devices:
138 >>> $b = [map { [map { mx->nd->ones($shape, ctx => $_) } @$gpus] } @$keys-1]
139 >>> $kv->push($keys, $b)
140 >>> $kv->pull($keys, out=>$b)
141 >>> print $b->[1][1]->aspdl()
142 [[ 4. 4. 4.]
143 [ 4. 4. 4.]]
144 =cut
145  
146 method push(
147 Str|ArrayRef[Str] $key,
148 AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]|ArrayRef[ArrayRef[AI::MXNet::NDArray]] $value,
149 Int :$priority=0
150 )
151 {
152 my ($keys, $vals) = _key_value($key, $value);
153 check_call(
154 AI::MXNetCAPI::KVStorePushEx(
155 $self->handle, scalar(@{ $keys }), $keys, $vals, $priority
156 )
157 );
158 }
159  
160 =head2 pull
161  
162 Pull a single value or a sequence of values from the store.
163  
164 Data consistency:
165  
166 1. this function returns after adding an operator to the engine. But any
167 further read on out will be blocked until it is finished.
168 2. pull is always called after all previous push and pull on the same
169 key are finished.
170 3. It pulls the newest value from the store.
171  
172 Parameters
173 ----------
174 $key : Str|ArrayRef[Str]
175 Keys
176 :$out: AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]|ArrayRef[ArrayRef[AI::MXNet::NDArray]]
177 According values
178  
179 :$priority=0 : Int, optional
180 The priority of the push operation.
181 The higher the priority, the faster this action is likely
182 to be executed before other push actions.
183  
184 Examples
185 --------
186 >>> # pull a single key-value pair
187 >>> $a = mx->nd->zeros($shape)
188 >>> $kv->pull(3, out=>$a)
189 >>> print $a->aspdl
190 [[ 2. 2. 2.]
191 [ 2. 2. 2.]]
192  
193 >>> # pull into multiple devices
194 >>> $b = [map { mx->nd->ones($shape, $_) } @$gpus]
195 >>> $kv->pull(3, out=>$b)
196 >>> print $b->[1]->aspdl()
197 [[ 2. 2. 2.]
198 [ 2. 2. 2.]]
199  
200 >>> # pull a list of key-value pairs.
201 >>> # On single device
202 >>> $keys = [5, 7, 9]
203 >>> $b = [map { mx->nd->zeros($shape) } 0..@$keys-1]
204 >>> $kv->pull($keys, out=>$b)
205 >>> print $b->[1]->aspdl()
206 [[ 2. 2. 2.]
207 [ 2. 2. 2.]]
208 >>> # On multiple devices
209 >>> $b = [map { [map { mx->nd->ones($shape, ctx => $_) } @$gpus ] } 0..@$keys-1]
210 >>> $kv->pull($keys, out=>$b)
211 >>> print $b->[1][1]->aspdl()
212 [[ 2. 2. 2.]
213 [ 2. 2. 2.]]
214 =cut
215  
216 method pull(
217 Str|ArrayRef[Str] $key,
218 AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]|ArrayRef[ArrayRef[AI::MXNet::NDArray]] :$out,
219 Int :$priority=0,
220 Bool :$ignore_sparse=1
221 )
222 {
223 my ($keys, $vals) = _key_value($key, $out);
224 check_call(
225 AI::MXNetCAPI::KVStorePullWithSparseEx(
226 $self->handle, scalar(@{ $keys }), $keys, $vals, $priority, $ignore_sparse
227 )
228 );
229 }
230  
231 =head2 row_sparse_pull
232  
233 Pulls a single AI::MXNet::NDArray::RowSparse value or an array ref of AI::MXNet::NDArray::RowSparse values
234 from the store with specified row_ids. When there is only one row_id, KVStoreRowSparsePull
235 is invoked just once and the result is broadcast to all the rest of outputs.
236  
237 `row_sparse_pull` is executed asynchronously after all previous
238 `pull`/`row_sparse_pull` calls and the last `push` call for the
239 same input key(s) are finished.
240  
241 The returned values are guaranteed to be the latest values in the store.
242  
243 Parameters
244 ----------
245 $key : Str|ArrayRef[Str] $key
246 Keys.
247  
248 :$out: AI::MXNet::NDArray::RowSparse|ArrayRef[AI::MXNet::NDArray::RowSparse]|ArrayRef[ArrayRef[AI::MXNet::NDArray::RowSparse]]
249 Values corresponding to the keys. The stype is expected to be row_sparse
250  
251 :$priority=0 : Int, optional
252 The priority of the pull operation.
253 Higher priority pull operations are likely to be executed before
254 other pull actions.
255  
256 :$row_ids : AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]|ArrayRef[ArrayRef[AI::MXNet::NDArray]]
257 The row_ids for which to pull for each value. Each row_id is an 1D NDArray
258 whose values don't have to be unique nor sorted.
259  
260 Examples
261 --------
262 >>> $shape = [3, 3]
263 >>> $kv->init('3', mx->nd->ones($shape)->tostype('row_sparse'))
264 >>> $a = mx->nd->sparse->zeros('row_sparse', $shape)
265 >>> $row_ids = mx->nd->array([0, 2], dtype=>'int64')
266 >>> $kv->row_sparse_pull('3', out=>$a, row_ids=>$row_ids)
267 >>> print $a->aspdl
268 [[ 1. 1. 1.]
269 [ 0. 0. 0.]
270 [ 1. 1. 1.]]
271 >>> $duplicate_row_ids = mx->nd->array([2, 2], dtype=>'int64')
272 >>> $kv->row_sparse_pull('3', out=>$a, row_ids=>$duplicate_row_ids)
273 >>> print $a->aspdl
274 [[ 0. 0. 0.]
275 [ 0. 0. 0.]
276 [ 1. 1. 1.]]
277 >>> $unsorted_row_ids = mx->nd->array([1, 0], dtype=>'int64')
278 >>> $kv->row_sparse_pull('3', out=>$a, row_ids=>$unsorted_row_ids)
279 >>> print $a->aspdl
280 [[ 1. 1. 1.]
281 [ 1. 1. 1.]
282 [ 0. 0. 0.]]
283 =cut
284  
285  
286 method row_sparse_pull(
287 Str|ArrayRef[Str] $key,
288 AI::MXNet::NDArray::RowSparse|ArrayRef[AI::MXNet::NDArray::RowSparse]|ArrayRef[ArrayRef[AI::MXNet::NDArray::RowSparse]] :$out,
289 Int :$priority=0,
290 AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]|ArrayRef[ArrayRef[AI::MXNet::NDArray]] :$row_ids
291 )
292 {
293 if(blessed $row_ids)
294 {
295 $row_ids = [$row_ids];
296 }
297 my $first_out = $out;
298 # whether row_ids are the same
299 my $single_rowid = 0;
300 if(@$row_ids == 1 and ref $out eq 'ARRAY')
301 {
302 $single_rowid = 1;
303 $first_out = [$out->[0]];
304 }
305 my ($ckeys, $cvals) = _key_value($key, $first_out);
306 my (undef, $crow_ids) = _key_value($key, $row_ids);
307 assert(
308 (@$crow_ids == @$cvals),
309 "the number of row_ids doesn't match the number of values"
310 );
311 check_call(
312 AI::MXNetCAPI::KVStorePullRowSparseEx(
313 $self->handle, scalar(@$ckeys), $ckeys, $cvals, $crow_ids, $priority
314 )
315 );
316 # the result can be copied to other devices without invoking row_sparse_pull
317 # if the indices are the same
318 if($single_rowid)
319 {
320 for my $out_i (@{ $out } [1..@{ $out }-1])
321 {
322 $out->[0]->copyto($out_i);
323 }
324 }
325 }
326  
327 =head2 set_gradient_compression
328  
329 Specifies type of low-bit quantization for gradient compression \
330 and additional arguments depending on the type of compression being used.
331  
332 2bit Gradient Compression takes a positive float `threshold`.
333 The technique works by thresholding values such that positive values in the
334 gradient above threshold will be set to threshold. Negative values whose absolute
335 values are higher than threshold, will be set to the negative of threshold.
336 Values whose absolute values are less than threshold will be set to 0.
337 By doing so, each value in the gradient is in one of three states. 2bits are
338 used to represent these states, and every 16 float values in the original
339 gradient can be represented using one float. This compressed representation
340 can reduce communication costs. The difference between these thresholded values and
341 original values is stored at the sender's end as residual and added to the
342 gradient in the next iteration.
343  
344 When kvstore is 'local', gradient compression is used to reduce communication
345 between multiple devices (gpus). Gradient is quantized on each GPU which
346 computed the gradients, then sent to the GPU which merges the gradients. This
347 receiving GPU dequantizes the gradients and merges them. Note that this
348 increases memory usage on each GPU because of the residual array stored.
349  
350 When kvstore is 'dist', gradient compression is used to reduce communication
351 from worker to sender. Gradient is quantized on each worker which
352 computed the gradients, then sent to the server which dequantizes
353 this data and merges the gradients from each worker. Note that this
354 increases CPU memory usage on each worker because of the residual array stored.
355 Only worker to server communication is compressed in this setting.
356 If each machine has multiple GPUs, currently this GPU to GPU or GPU to CPU communication
357 is not compressed. Server to worker communication (in the case of pull)
358 is also not compressed.
359  
360 To use 2bit compression, we need to specify `type` as `2bit`.
361 Only specifying `type` would use default value for the threshold.
362 To completely specify the arguments for 2bit compression, we would need to pass
363 a dictionary which includes `threshold` like:
364 {'type': '2bit', 'threshold': 0.5}
365  
366 Parameters
367 ----------
368 $compression_params : HashRef[Str]
369 A dictionary specifying the type and parameters for gradient compression.
370 The key `type` in this dictionary is a
371 required string argument and specifies the type of gradient compression.
372 Currently `type` can be only `2bit`
373 Other keys in this dictionary are optional and specific to the type
374 of gradient compression.
375 =cut
376  
377 method set_gradient_compression(HashRef[Str] $compression_params)
378 {
379 if($self->type =~ /(?:device|dist)/)
380 {
381 check_call(
382 AI::MXNetCAPI::KVStoreSetGradientCompression(
383 $self->handle,
384 scalar(keys %$compression_params),
385 $compression_params
386 )
387 );
388 }
389 else
390 {
391 confess('Gradient compression is not supported for this type of kvstore');
392 }
393 }
394  
395 =head2 set_optimizer
396  
397 Register an optimizer to the store
398  
399 If there are multiple machines, this process (should be a worker node)
400 will pack this optimizer and send it to all servers. It returns after
401 this action is done.
402  
403 Parameters
404 ----------
405 $optimizer : AI::MXNet::Optimizer
406 the optimizer
407 =cut
408  
409 method set_optimizer(AI::MXNet::Optimizer $optimizer)
410 {
411 my $is_worker = check_call(AI::MXNetCAPI::KVStoreIsWorkerNode());
412 if($self->type =~ /dist/ and $is_worker)
413 {
414 my $optim_str = MIME::Base64::encode_base64(Storable::freeze($optimizer), "");
415 $self->_send_command_to_servers(0, $optim_str);
416 }
417 else
418 {
419 $self->_updater(AI::MXNet::Optimizer->get_updater($optimizer));
420 $self->_set_updater($self->_updater);
421 }
422 }
423  
424 =head2 type
425  
426 Get the type of this kvstore
427  
428 Returns
429 -------
430 $type : Str
431 the string type
432 =cut
433  
434 method type()
435 {
436 return scalar(check_call(AI::MXNetCAPI::KVStoreGetType($self->handle)));
437 }
438  
439 =head2 rank
440  
441 Get the rank of this worker node
442  
443 Returns
444 -------
445 $rank : Int
446 The rank of this node, which is in [0, get_num_workers())
447 =cut
448  
449 method rank()
450 {
451 return scalar(check_call(AI::MXNetCAPI::KVStoreGetRank($self->handle)));
452 }
453  
454 =head2 num_workers
455  
456 Get the number of worker nodes
457  
458 Returns
459 -------
460 $size : Int
461 The number of worker nodes
462 =cut
463  
464 method num_workers()
465 {
466 return scalar(check_call(AI::MXNetCAPI::KVStoreGetGroupSize($self->handle)));
467 }
468  
469 =head2 save_optimizer_states
470  
471 Save optimizer (updater) state to file
472  
473 Parameters
474 ----------
475 $fname : Str
476 Path to output states file.
477 :$dump_optimizer=0 : Bool, default False
478 Whether to also save the optimizer itself. This would also save optimizer
479 information such as learning rate and weight decay schedules.
480 =cut
481  
482 method save_optimizer_states(Str $fname, Bool :$dump_optimizer=0)
483 {
484 confess("Cannot save states for distributed training")
485 unless defined $self->_updater;
486 open(F, ">:raw", "$fname") or confess("can't open $fname for writing: $!");
487 print F $self->_updater->get_states($dump_optimizer);
488 close(F);
489 }
490  
491 =head2 load_optimizer_states
492  
493 Load optimizer (updater) state from file.
494  
495 Parameters
496 ----------
497 $fname : Str
498 Path to input states file.
499 =cut
500  
501 method load_optimizer_states(Str $fname)
502 {
503 confess("Cannot save states for distributed training")
504 unless defined $self->_updater;
505 open(F, "<:raw", "$fname") or confess("can't open $fname for reading: $!");
506 my $data;
507 { local($/) = undef; $data = <F>; }
508 close(F);
509 $self->_updater->set_states($data);
510 }
511  
512 =head2 _set_updater
513  
514 Set a push updater into the store.
515  
516 This function only changes the local store. Use set_optimizer for
517 multi-machines.
518  
519 Parameters
520 ----------
521 $updater : Undater
522 the updater function
523  
524 Examples
525 --------
526 >>> my $update = sub { my ($key, input, stored) = @_;
527 ... print "update on key: $key\n";
528 ... $stored += $input * 2; };
529 >>> $kv->_set_updater($update)
530 >>> $kv->pull(3, out=>$a)
531 >>> print $a->aspdl()
532 [[ 4. 4. 4.]
533 [ 4. 4. 4.]]
534 >>> $kv->push(3, mx->nd->ones($shape))
535 update on key: 3
536 >>> $kv->pull(3, out=>$a)
537 >>> print $a->aspdl()
538 [[ 6. 6. 6.]
539 [ 6. 6. 6.]]
540 =cut
541  
542 method _set_updater(Updater $updater_func)
543 {
544 check_call(
545 AI::MXNetCAPI::KVStoreSetUpdater(
546 $self->handle,
547 sub {
548 my ($index, $input_handle, $storage_handle) = @_;
549 $updater_func->(
550 $index,
551 AI::MXNet::NDArray->_ndarray_cls($input_handle),
552 AI::MXNet::NDArray->_ndarray_cls($storage_handle)
553 );
554 }
555 )
556 );
557 }
558  
559 =head2 _barrier
560  
561 Global barrier between all worker nodes.
562  
563 For example, assume there are n machines, we want to let machine 0 first
564 init the values, and then pull the inited value to all machines. Before
565 pulling, we can place a barrier to guarantee that the initialization is
566 finished.
567 =cut
568  
569 method _barrier()
570 {
571 check_call(AI::MXNetCAPI::KVStoreBarrier($self->handle));
572 }
573  
574 =head2 _send_command_to_servers
575  
576 Send a command to all server nodes
577 Send a command to all server nodes, which will make each server node run
578 KVStoreServer.controller
579 This function returns after the command has been executed in all server
580 nodes.
581  
582 Parameters
583 ----------
584 $head : Int
585 the head of the command
586 $body : Str
587 the body of the command
588 =cut
589  
590 method _send_command_to_servers(Int $head, Str $body)
591 {
592 check_call(
593 AI::MXNetCAPI::KVStoreSendCommmandToServers(
594 $self->handle,
595 $head,
596 $body
597 )
598 );
599 }
600  
601 =head2 create
602  
603 Create a new KVStore.
604  
605 Parameters
606 ----------
607 $name='local' : Str
608 The type of KVStore
609 - local works for multiple devices on a single machine (single process)
610 - dist works for multi-machines (multiple processes)
611 Returns
612 -------
613 kv : KVStore
614 The created AI::MXNet::KVStore
615 =cut
616  
617 method create(Str $name='local')
618 {
619 my $handle = check_call(AI::MXNetCAPI::KVStoreCreate($name));
620 return __PACKAGE__->new(handle => $handle);
621 }
622  
623 sub _key_value
624 {
625 my ($keys, $vals) = @_;
626 if(not ref $keys)
627 {
628 if(blessed $vals)
629 {
630 return ([$keys], [$vals->handle]);
631 }
632 else
633 {
634 for my $value (@{ $vals })
635 {
636 assert(blessed($value) and $value->isa('AI::MXNet::NDArray'));
637 return ([($keys)x@$vals], [map { $_->handle } @$vals]);
638 }
639 }
640 }
641 else
642 {
643 assert(not blessed($vals) and @$keys == @$vals);
644 my @c_keys;
645 my @c_vals;
646 for(zip($keys, $vals)) {
647 my ($key, $val) = @$_;
648 my ($c_key, $c_val) = _key_value($key, $val);
649 push @c_keys, @$c_key;
650 push @c_vals, @$c_val;
651 }
652 return (\@c_keys, \@c_vals);
653 }
654 }
655  
656 1;