MXNet/Executor.pm untested

filter: Statementstmt 0.0% 0 / 184 Branchbran 0.0% 0 / 48 Conditioncond 0.0% 0 / 5 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 9 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 248 CC 5 SCAR 25.5
CC
5
Cov
0%
BUILD
30.0
DEMOLISH
2.0
BEGIN
2.0
CRAP 12.8
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::Executor;
19 use strict;
20 use warnings;
21 use AI::MXNet::Base;
22 use AI::MXNet::Context;
23 use Mouse;
24 use AI::MXNet::Types;
25 use AI::MXNet::Function::Parameters;
26  
27 has 'handle' => (is => 'ro', isa => 'ExecutorHandle', required => 1);
28 has 'arg_arrays' => (is => 'rw', isa => 'Maybe[ArrayRef[AI::MXNet::NDArray]]');
29 has 'grad_arrays' => (is => 'rw', isa => 'Maybe[ArrayRef[Undef|AI::MXNet::NDArray]]');
30 has 'aux_arrays' => (is => 'rw', isa => 'Maybe[ArrayRef[AI::MXNet::NDArray]]');
31 has '_symbol' => (is => 'rw', init_arg => 'symbol', isa => 'AI::MXNet::Symbol');
32 has '_ctx' => (is => 'rw', init_arg => 'ctx', isa => 'AI::MXNet::Context' );
33 has '_grad_req' => (is => 'rw', init_arg => 'grad_req', isa => 'Maybe[Str|ArrayRef[Str]|HashRef[Str]]');
34 has '_group2ctx' => (is => 'rw', init_arg => 'group2ctx', isa => 'Maybe[HashRef[AI::MXNet::Context]]');
35 has [qw/_arg_dict
36 _grad_dict
37 _aux_dict
38 _output_dict
39 outputs
40 /] => (is => 'rw', init_arg => undef);
41 =head1 NAME
42  
43 AI::MXNet::Executor - The actual executing object of MXNet.
44 =cut
45  
46 =head1 SYNOPSIS
47  
48 my $executor = $sym->bind(
49 ctx => mx->Context('cpu'),
50 args => [$lhs_arr, $rhs_arr],
51 args_grad => [$lhs_grad, $rhs_grad]
52 );
53 $executor->forward(1);
54 print $executor->outputs->[0]->aspdl;
55 =cut
56  
57 =head2 new
58  
59 Constructor, used by AI::MXNet::Symbol->bind and by AI::MXNet::Symbol->simple_bind.
60  
61 Parameters
62 ----------
63 handle: ExecutorHandle
64 ExecutorHandle is generated by calling bind.
65  
66 See Also
67 --------
68 AI::MXNet::Symbol->bind : how to create the AI::MXNet::Executor.
69 =cut
70  
71 sub BUILD
72 {
73 my $self = shift;
74 my ($symbol, $ctx, $grad_req, $group2ctx)
75 =
76 ($self->_symbol, $self->_ctx, $self->_grad_req, $self->_group2ctx);
77 $symbol = $symbol->deepcopy;
78 $ctx = $ctx->deepcopy;
79 if(ref $grad_req)
80 {
81 if(ref $grad_req eq 'ARRAY')
82 {
83 $grad_req = [ @{ $grad_req }];
84 }
85 elsif(ref $grad_req eq 'HASH')
86 {
87 $grad_req = { %{ $grad_req } };
88  
89 }
90 }
91 if(ref $group2ctx)
92 {
93 $group2ctx = { %{ $group2ctx } };
94 }
95 $self->_symbol($symbol);
96 $self->_ctx($ctx);
97 $self->_grad_req($grad_req);
98 $self->_group2ctx($group2ctx);
99 $self->outputs($self->_get_outputs);
100 }
101  
102 sub DEMOLISH
103 {
104 check_call(AI::MXNetCAPI::ExecutorFree(shift->handle));
105 }
106  
107 # Get the dictionary given name and ndarray pairs.
108 func _get_dict(
109 ArrayRef[Str] $names,
110 ArrayRef[Maybe[AI::MXNet::NDArray]] $ndarrays
111 )
112 {
113 my %nset = ();
114 for my $nm (@{ $names })
115 {
116 if(exists $nset{ $nm })
117 {
118 confess("Duplicate names detected, @$names")
119 }
120 $nset{ $nm }++;
121 }
122 my %ret;
123 @ret{ @{ $names } } = @{ $ndarrays };
124 return \%ret;
125 }
126  
127 =head2 outputs
128  
129 The output ndarrays bound to this executor.
130  
131 Returns
132 -------
133 An array ref with AI::MXNet::NDArray objects bound to the heads of the executor.
134 =cut
135  
136 method _get_outputs()
137 {
138 return [
139 map {
140 AI::MXNet::NDArray->_ndarray_cls($_)
141 }
142 @{ check_call(AI::MXNetCAPI::ExecutorOutputs($self->handle)) }
143 ];
144 }
145  
146 =head2 forward
147  
148 Calculate the outputs specified by the bound symbol.
149  
150 Parameters
151 ----------
152 $is_train=0: Bool, optional
153 whether this forward is for evaluation purpose. If True,
154 a backward call is expected to follow. Otherwise following
155 backward is invalid.
156  
157 %kwargs
158 Additional specification of input arguments.
159  
160 Examples
161 --------
162 >>> # doing forward by specifying data
163 >>> $texec->forward(1, data => $mydata);
164 >>> # doing forward by not specifying things, but copy to the executor before hand
165 >>> $mydata->copyto($texec->arg_dict->{'data'});
166 >>> $texec->forward(1);
167 >>> # doing forward by specifying data and get outputs
168 >>> my $outputs = $texec->forward(1, data => $mydata);
169 >>> print $outputs->[0]->aspdl;
170 =cut
171  
172 method forward(Int $is_train=0, %kwargs)
173 {
174 if(%kwargs)
175 {
176 my $arg_dict = $self->arg_dict;
177 while (my ($name, $array) = each %kwargs)
178 {
179 if(not find_type_constraint('AcceptableInput')->check($array))
180 {
181 confess('only accept keyword argument of NDArrays/PDLs/Perl Array refs');
182 }
183 if(not exists $arg_dict->{ $name })
184 {
185 confess("unknown argument $name");
186 }
187 if(not blessed($array) or not $array->isa('AI::MXNet::NDArray'))
188 {
189 $array = AI::MXNet::NDArray->array($array);
190 }
191 if(join(',', @{ $arg_dict->{$name}->shape }) ne join(',', @{ $array->shape }))
192 {
193 my $expected = $arg_dict->{$name}->shape;
194 my $got = $array->shape;
195 confess("Shape not match! Argument $name, need: @$expected, received: @$got'");
196 }
197 $arg_dict->{ $name } .= $array;
198 }
199 }
200 check_call(AI::MXNetCAPI::ExecutorForward(
201 $self->handle,
202 $is_train
203 )
204 );
205 return $self->outputs;
206 }
207  
208 =head2 backward
209  
210 Do a backward pass to get the gradient of the arguments.
211  
212 Parameters
213 ----------
214 $out_grads : NDArray or an array ref of NDArrays or hash ref of NDArrays, optional.
215 The gradient on the outputs to be propagated back.
216 This parameter is only needed when bind is called
217 on outputs that are not a loss function.
218  
219 $is_train : Bool, default 1
220 Whether this backward is for training or inference. Note that in rare
221 cases you want to call backward with is_train=0 to get gradient
222 during inference.
223 =cut
224  
225 method backward(
226 Maybe[AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]|HashRef[AI::MXNet::NDArray]] $out_grads=,
227 Bool $is_train=1
228 )
229 {
230 $out_grads //= [];
231 if(blessed $out_grads)
232 {
233 $out_grads = [$out_grads];
234 }
235 elsif(ref $out_grads eq 'HASH')
236 {
237 $out_grads = [ @{ $out_grads }{ @{ $self->symbol->list_outputs() } } ];
238 }
239 check_call(
240 AI::MXNetCAPI::ExecutorBackwardEx(
241 $self->handle,
242 scalar(@{ $out_grads }),
243 [map { $_->handle } @{ $out_grads }],
244 $is_train
245 )
246 );
247 }
248  
249 =head2 set_monitor_callback
250  
251 Install callback.
252  
253 Parameters
254 ----------
255 $callback : CodeRef
256 Takes a string and an NDArrayHandle.
257 =cut
258  
259 method set_monitor_callback(CodeRef $callback)
260 {
261 check_call(
262 AI::MXNetCAPI::ExecutorSetMonitorCallback(
263 $self->handle,
264 $callback
265 )
266 );
267 }
268  
269 =head2 arg_dict
270  
271 Get a hash ref representation of the argument arrays.
272  
273 Returns
274 -------
275 $arg_dict : HashRef[AI::MXNet::NDArray]
276 The map that maps a name of the arguments to the NDArrays.
277 =cut
278  
279 method arg_dict()
280 {
281 if(not defined $self->_arg_dict)
282 {
283 $self->_arg_dict(_get_dict(
284 $self->_symbol->list_arguments(),
285 $self->arg_arrays
286 )
287 );
288 }
289 return $self->_arg_dict;
290 }
291  
292 =head2 grad_dict
293  
294 Get a hash ref representation of the gradient arrays.
295  
296 Returns
297 -------
298 $grad_dict : HashRef[AI::MXNet::NDArray]
299 The map that maps a name of the arguments to the gradient NDArrays.
300 =cut
301  
302 method grad_dict()
303 {
304 if(not defined $self->_grad_dict)
305 {
306 $self->_grad_dict(_get_dict(
307 $self->_symbol->list_arguments(),
308 $self->grad_arrays
309 )
310 );
311 }
312 return $self->_grad_dict;
313 }
314  
315 =head2 aux_dict
316  
317 Get a hash ref representation of the auxiliary states arrays.
318  
319 Returns
320 -------
321 $aux_dict : HashRef[AI::MXNet::NDArray]
322 The map that maps a name of the auxiliary states to the NDArrays.
323 =cut
324  
325 method aux_dict()
326 {
327 if(not defined $self->_aux_dict)
328 {
329 $self->_aux_dict(_get_dict(
330 $self->_symbol->list_auxiliary_states(),
331 $self->aux_arrays()
332 )
333 );
334 }
335 return $self->_aux_dict;
336 }
337  
338 =head2 output_dict
339  
340 Get a hash ref representation of the output arrays.
341  
342 Returns
343 -------
344 $output_dict : HashRef[AI::MXNet::NDArray]
345 The map that maps a name of the outputs to the NDArrays.
346 =cut
347  
348 method output_dict()
349 {
350 if(not defined $self->_output_dict)
351 {
352 $self->_output_dict(_get_dict(
353 $self->_symbol->list_outputs(),
354 $self->outputs
355 )
356 );
357 }
358 return $self->_output_dict;
359 }
360  
361 =head2 copy_params_from
362  
363 Copy parameters from arg_params, aux_params into the executor's internal array.
364  
365 Parameters
366 ----------
367 $arg_params : HashRef[AI::MXNet::NDArray]
368 Parameters, hash ref of name to NDArray of arguments
369  
370 $aux_params= : Maybe[HashRef[AI::MXNet::NDArray]], optional
371 Parameters, hash ref of name to NDArray of auxiliary states.
372  
373 $allow_extra_params= : Bool, optional
374 Whether to allow extra parameters that are not needed by symbol
375 If this is True, no error will be thrown when arg_params or aux_params
376 contain extra parameters that is not needed by the executor.
377 =cut
378  
379 method copy_params_from(
380 HashRef[AI::MXNet::NDArray] $arg_params,
381 Maybe[HashRef[AI::MXNet::NDArray]] $aux_params=,
382 Maybe[Bool] $allow_extra_params=
383 )
384 {
385 my %arg_dict = %{ $self->arg_dict };
386 while (my ($name, $array) = each %{ $arg_params })
387 {
388 if(exists $arg_dict{ $name })
389 {
390 my $dst = $arg_dict{ $name };
391 $array->astype($dst->dtype)->copyto($dst);
392 }
393 elsif(not $allow_extra_params)
394 {
395 confess("Found name \"$name\" that is not in the arguments");
396 }
397 }
398 if(defined $aux_params)
399 {
400 my %aux_dict = %{ $self->aux_dict };
401 while (my ($name, $array) = each %{ $aux_params })
402 {
403 if(exists $aux_dict{ $name })
404 {
405 my $dst = $aux_dict{ $name };
406 $array->astype($dst->dtype)->copyto($dst);
407 }
408 elsif(not $allow_extra_params)
409 {
410 confess("Found name \"$name\" that is not in the arguments");
411 }
412 }
413 }
414 }
415  
416 =head2 reshape
417  
418 Returns new executor with the same symbol and shared memory,
419 but different input/output shapes.
420 For runtime reshaping, variable length sequences, etc.
421 The returned executor shares state with the current one,
422 and cannot be used in parallel with it.
423  
424 Parameters
425 ----------
426 $kwargs : HashRef[Shape]
427 new shape for arguments.
428 :$partial_shaping : Bool
429 Whether to allow changing the shape of unspecified arguments.
430 :$allow_up_sizing : Bool
431 Whether to allow allocating new ndarrays that's larger than the original.
432  
433 Returns
434 -------
435 $exec : AI::MXNet::Executor
436 A new executor that shares memory with self.
437 =cut
438  
439  
440 method reshape(HashRef[Shape] $kwargs, Int :$partial_shaping=0, Int :$allow_up_sizing=0)
441 {
442 my @provided_arg_shape_data;
443 # argument shape index in sdata,
444 # e.g. [sdata[indptr[0]], sdata[indptr[1]]) is the shape of the first arg
445 my @provided_arg_shape_idx = (0);
446 my @provided_arg_shape_names = (); # provided argument names
447 while(my ($k, $v) = each %{ $kwargs })
448 {
449 if(ref $v eq 'ARRAY')
450 {
451 push @provided_arg_shape_names, $k;
452 push @provided_arg_shape_data, @{ $v };
453 push @provided_arg_shape_idx, scalar(@provided_arg_shape_data);
454 }
455 }
456  
457 my @ctx_map_keys;
458 my @ctx_map_dev_types;
459 my @ctx_map_dev_ids;
460  
461 if(ref $self->_group2ctx eq 'HASH')
462 {
463 while(my ($k, $v) = each %{ $self->_group2ctx })
464 {
465 push @ctx_map_keys, $k;
466 push @ctx_map_dev_types, $v->device_type_id;
467 push @ctx_map_dev_ids, $v->device_id;
468 }
469 }
470  
471 my $shared_handle = $self->handle;
472  
473 my ($in_args_and_grad_handles, $aux_state_handles, $handle) = check_call(
474 AI::MXNetCAPI::ExecutorReshapeEx(
475 $partial_shaping,
476 $allow_up_sizing,
477 $self->_ctx->device_type_id,
478 $self->_ctx->device_id,
479 scalar(@ctx_map_keys),
480 \@ctx_map_keys,
481 \@ctx_map_dev_types,
482 \@ctx_map_dev_ids,
483 scalar(@provided_arg_shape_names),
484 \@provided_arg_shape_names,
485 \@provided_arg_shape_data,
486 \@provided_arg_shape_idx,
487 $shared_handle
488 )
489 );
490 my ($in_args_handles, $arg_grad_handles) = @{ $in_args_and_grad_handles };
491 my @arg_arrays = map { AI::MXNet::NDArray->_ndarray_cls($_) } @{ $in_args_handles };
492 my @grad_arrays = map { defined($_) ? AI::MXNet::NDArray->_ndarray_cls($_) : undef } @{ $arg_grad_handles };
493 my @aux_arrays = map { AI::MXNet::NDArray->_ndarray_cls($_) } @{ $aux_state_handles };
494  
495 my $executor = __PACKAGE__->new(
496 handle => $handle,
497 symbol => $self->_symbol,
498 ctx => $self->_ctx,
499 grad_req => $self->_grad_req,
500 group2ctx => $self->_group2ctx
501 );
502 $executor->arg_arrays(\@arg_arrays);
503 $executor->grad_arrays(\@grad_arrays);
504 $executor->aux_arrays(\@aux_arrays);
505 return $executor;
506 }
507  
508 =head2 debug_str
509  
510 A debug string about the internal execution plan.
511  
512 Returns
513 -------
514 $debug_str : Str
515 Debug string of the executor.
516 =cut
517  
518 method debug_str()
519 {
520 return scalar(check_call(AI::MXNetCAPI::ExecutorPrint($self->handle)));
521 }
522  
523 1;