MXNet/Symbol.pm untested

filter: Statementstmt 0.0% 0 / 530 Branchbran 0.0% 0 / 142 Conditioncond 0.0% 0 / 30 MC/DCmcdc 0.0% 0 / 18 Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 733 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::Symbol;
19  
20 =head1 NAME
21  
22 AI::MXNet::Symbol - Symbolic interface of MXNet.
23 =cut
24  
25 use strict;
26 use warnings;
27 use AI::MXNet::NS;
28 use AI::MXNet::Base;
29 use AI::MXNet::Symbol::Base;
30 use AI::MXNet::Symbol::Random;
31 use AI::MXNet::RunTime;
32 use AI::MXNet::Types;
33 use Mouse;
34 use AI::MXNet::Function::Parameters;
35 use overload
36 '""' => \&stringify,
37 '+' => \&add,
38 '-' => \&subtract,
39 '*' => \&multiply,
40 '/' => \&divide,
41 '/=' => \&idivide,
42 '**' => \&power,
43 '%' => \&mod,
44 '==' => \&equal,
45 '!=' => \&not_equal,
46 '>' => \&greater,
47 '>=' => \&greater_equal,
48 '<' => \&lesser,
49 '<=' => \&lesser_equal,
50 '&{}' => sub { my $self = shift; sub { $self->call(@_) } },
51 '@{}' => sub { my $self = shift; [map { $self->slice($_) } @{ $self->list_outputs }] };
52  
53 extends 'AI::MXNet::Symbol::Base';
54 has 'handle' => (is => 'rw', isa => 'SymbolHandle', required => 1);
55  
56 sub DEMOLISH
57 {
58 check_call(AI::NNVMCAPI::SymbolFree(shift->handle));
59 }
60  
61 method STORABLE_freeze($cloning)
62 {
63 return $self->tojson();
64 }
65  
66 method STORABLE_thaw($cloning, $json)
67 {
68 my $handle = check_call(
69 AI::MXNetCAPI::SymbolCreateFromJSON(
70 $json
71 )
72 );
73 $self->handle($handle);
74 }
75  
76 method stringify($other=, $reverse=)
77 {
78 my $name = $self->name;
79 sprintf(
80 "<%s %s%s>",
81 ref($self),
82 $name ? ($name, '') : ('group [', join(', ', map { $_->name } @{ $self }) . ']')
83 );
84 }
85  
86 method add(AI::MXNet::Symbol|Num $other, $reverse=)
87 {
88 return _ufunc_helper(
89 $self,
90 $other,
91 qw/_Plus _PlusScalar/
92 );
93 }
94  
95 method subtract(AI::MXNet::Symbol|Num $other, $reverse=)
96 {
97 return _ufunc_helper(
98 $self,
99 $other,
100 qw/_Minus _MinusScalar _RMinusScalar/,
101 $reverse
102 );
103 }
104  
105 method multiply(AI::MXNet::Symbol|Num $other, $reverse=)
106 {
107 return _ufunc_helper(
108 $self,
109 $other,
110 qw/_Mul _MulScalar/
111 );
112 }
113  
114 method divide(AI::MXNet::Symbol|Num $other, $reverse=)
115 {
116 return _ufunc_helper(
117 $self,
118 $other,
119 qw/_Div _DivScalar _RDivScalar/,
120 $reverse
121 );
122 }
123  
124 method power(AI::MXNet::Symbol|Num $other, $reverse=)
125 {
126 return _ufunc_helper(
127 $self,
128 $other,
129 qw/_Power _PowerScalar _RPowerScalar/,
130 $reverse
131 );
132 }
133  
134 method equal(AI::MXNet::Symbol|Num $other, $reverse=)
135 {
136 return _ufunc_helper(
137 $self,
138 $other,
139 qw/_equal _equal_scalar/
140 );
141 }
142  
143 method not_equal(AI::MXNet::Symbol|Num $other, $reverse=)
144 {
145 return _ufunc_helper(
146 $self,
147 $other,
148 qw/_not_equal _not_equal_scalar/
149 );
150 }
151  
152 method greater(AI::MXNet::Symbol|Num $other, $reverse=)
153 {
154 return _ufunc_helper(
155 $self,
156 $other,
157 qw/_greater _greater_scalar _lesser_scalar/,
158 $reverse
159 );
160 }
161  
162 method greater_equal(AI::MXNet::Symbol|Num $other, $reverse=)
163 {
164 return _ufunc_helper(
165 $self,
166 $other,
167 qw/_greater_equal _greater_equal_scalar _lesser_equal_scalar/,
168 $reverse
169 );
170 }
171  
172 method lesser(AI::MXNet::Symbol|Num $other, $reverse=)
173 {
174 return _ufunc_helper(
175 $self,
176 $other,
177 qw/_lesser _lesser_scalar _greater_scalar/,
178 $reverse
179 );
180 }
181  
182 method lesser_equal(AI::MXNet::Symbol|Num $other, $reverse=)
183 {
184 return _ufunc_helper(
185 $self,
186 $other,
187 qw/_lesser_equal _lesser_equal_scalar _greater_equal_scalar/,
188 $reverse
189 );
190 }
191  
192 method true_divide(AI::MXNet::Symbol|Num $other, $reverse=)
193 {
194 return $self->divide($other, $reverse);
195 }
196  
197 method mod(AI::MXNet::Symbol|Num $other, $reverse=)
198 {
199 return _ufunc_helper(
200 $self,
201 $other,
202 qw/_Mod _ModScalar _RModScalar/,
203 $reverse
204 );
205 }
206  
207 method maximum(AI::MXNet::Symbol|Num $other)
208 {
209 return _ufunc_helper(
210 $self,
211 $other,
212 qw/_Maximum _MaximumScalar/
213 );
214 }
215  
216 method minimum(AI::MXNet::Symbol|Num $other)
217 {
218 return _ufunc_helper(
219 $self,
220 $other,
221 qw/_Minimum _MinimumScalar/
222 );
223 }
224  
225 method hypot(AI::MXNet::Symbol|Num $other)
226 {
227 return _ufunc_helper(
228 $self,
229 $other,
230 qw/_Hypot _HypotScalar/
231 );
232 }
233  
234 method reshape(@args)
235 {
236 if(@args%2)
237 {
238 unshift @args, 'shape';
239 }
240 return $self->SUPER::reshape(@args);
241 }
242  
243  
244 method deepcopy()
245 {
246 my $handle = check_call(AI::MXNetCAPI::SymbolCopy($self->handle));
247 return __PACKAGE__->new(handle => $handle);
248 }
249  
250 method call(@args)
251 {
252 my $s = $self->deepcopy();
253 $s->_compose(@args);
254 return $s;
255 }
256  
257 method slice(@slices)
258 {
259 confess("No slices supplied") unless @slices;
260 if(@slices > 1)
261 {
262 return $self->SUPER::slice(@slices);
263 }
264 my $index = $slices[0];
265 ## __getitem__ tie needs to die
266 if(not find_type_constraint('Index')->check($index))
267 {
268 my $i = 0;
269 my $idx;
270 for my $name (@{ $self->list_outputs() })
271 {
272 if($name eq $index)
273 {
274 if(defined $idx)
275 {
276 confess(qq/There are multiple outputs with name "$index"/);
277 }
278 $idx = $i;
279 }
280 $i++;
281 }
282 confess(qq/Cannot find output that matches name "$index"/) unless defined $idx;
283 $index = $idx;
284 }
285 elsif($index >= @{ $self->list_outputs() })
286 {
287 confess("Index: [$index] is outside of the range of the symbol: $self outputs");
288 }
289 my $handle = check_call(AI::MXNetCAPI::SymbolGetOutput($self->handle, $index));
290 return __PACKAGE__->new(handle => $handle);
291 }
292  
293 =head2 name
294  
295 Get name string from the symbol, this function only works for non-grouped symbol.
296  
297 Returns
298 -------
299 value : str
300 The name of this symbol, returns None for grouped symbol.
301 =cut
302  
303 method name()
304 {
305 my ($name, $success) = check_call(AI::MXNetCAPI::SymbolGetName($self->handle));
306 return $success ? $name : undef;
307 }
308  
309 =head2 attr
310  
311 Get an attribute string from the symbol, this function only works for non-grouped symbol.
312  
313 Parameters
314 ----------
315 key : str
316 The key to get attribute from.
317  
318 Returns
319 -------
320 value : str
321 The attribute value of the key, returns None if attribute do not exist.
322 =cut
323  
324  
325 method attr(Str $key)
326 {
327 my ($attr, $success) = check_call(
328 AI::MXNetCAPI::SymbolGetAttr($self->handle, $key)
329 );
330 return $success ? $attr : undef;
331 }
332  
333 =head2 list_attr
334  
335 Get all attributes from the symbol.
336  
337 Returns
338 -------
339 ret : hash ref of str to str
340 a dicitonary mapping attribute keys to values
341 =cut
342  
343 method list_attr()
344 {
345 my %ret;
346 my @attrs = @{ check_call(AI::MXNetCAPI::SymbolListAttrShallow($self->handle)) };
347 while(@attrs)
348 {
349 my $k = shift(@attrs);
350 my $v = shift(@attrs);
351 $ret{ $k } = $v;
352 }
353 return \%ret;
354 }
355  
356 =head2 attr_dict
357  
358 Recursively get all attributes from the symbol and its childrens
359  
360 Returns
361 -------
362 ret : hash ref of str to hash ref.
363 Returns a dict whose keys are names of the symbol and its children.
364 Values of the returned dict are dictionaries that map attribute keys to values.
365 =cut
366  
367 method attr_dict()
368 {
369 my %ret;
370 my @attrs = @{ check_call(AI::MXNetCAPI::SymbolListAttr($self->handle)) };
371 my $size = @attrs/2;
372 for (my $i = 0; $i < $size; $i++)
373 {
374 my ($name, $key) = split(/\$/, $attrs[$i*2]);
375 my $val = $attrs[$i*2+1];
376 $ret{ $name }{ $key } = $val;
377 }
378 return \%ret;
379 }
380  
381 method _set_attr(Str @args)
382 {
383 my %kwargs = @args;
384 while(my ($key, $val) = each(%kwargs))
385 {
386 check_call(
387 AI::MXNetCAPI::SymbolSetAttr(
388 $self->handle, $key, $val
389 )
390 );
391 }
392 }
393  
394 =head2 get_internals
395  
396 Get a new grouped symbol whose output contains all the internal outputs of this symbol.
397  
398 Returns
399 -------
400 sgroup : AI::MXNet::Symbol
401 The internal symbol of the symbol.
402 =cut
403  
404 method get_internals()
405 {
406 my $handle = check_call(AI::MXNetCAPI::SymbolGetInternals($self->handle));
407 return __PACKAGE__->new(handle => $handle);
408 }
409  
410 =head2 get_children
411  
412 Get a new grouped symbol whose output contains
413 inputs to output nodes of the original symbol
414  
415 Returns
416 -------
417 sgroup : Symbol or undef
418 The children of the head node. If the symbol has no
419 inputs undef will be returned.
420 =cut
421  
422  
423 method get_children()
424 {
425 my $handle = check_call(AI::MXNetCAPI::SymbolGetChildren($self->handle));
426 my $ret = __PACKAGE__->new(handle => $handle);
427 return undef unless @{ $ret->list_outputs };
428 return $ret;
429 }
430  
431 =head2 list_arguments
432  
433 List all the arguments in the symbol.
434  
435 Returns
436 -------
437 args : array ref of strings
438 =cut
439  
440 method list_arguments()
441 {
442 return scalar(check_call(AI::MXNetCAPI::SymbolListArguments($self->handle)));
443 }
444  
445 =head2 list_outputs()
446  
447 List all outputs in the symbol.
448  
449 Returns
450 -------
451 $out : array ref of strings.
452 =cut
453  
454 method list_outputs()
455 {
456 return scalar(check_call(AI::MXNetCAPI::SymbolListOutputs($self->handle)));
457 }
458  
459  
460 =head2 list_auxiliary_states()
461  
462 List all auxiliary states in the symbol.
463  
464 Returns
465 -------
466 aux_states : array ref of string
467 List the names of the auxiliary states.
468  
469 Notes
470 -----
471 Auxiliary states are special states of symbols that do not corresponds to an argument,
472 and do not have gradient. But still be useful for the specific operations.
473 A common example of auxiliary state is the moving_mean and moving_variance in BatchNorm.
474 Most operators do not have Auxiliary states.
475 =cut
476  
477 method list_auxiliary_states()
478 {
479 return scalar(check_call(AI::MXNetCAPI::SymbolListAuxiliaryStates($self->handle)));
480 }
481  
482  
483 =head2 list_inputs
484  
485 Lists all arguments and auxiliary states of this Symbol.
486  
487 Returns
488 -------
489 inputs : array ref of str
490 List of all inputs.
491  
492 Examples
493 --------
494 >>> my $bn = mx->sym->BatchNorm(name=>'bn');
495 =cut
496  
497 method list_inputs()
498 {
499 return scalar(check_call(AI::NNVMCAPI::SymbolListInputNames($self->handle, 0)));
500 }
501  
502 =head2 infer_type
503  
504 Infer the type of outputs and arguments of given known types of arguments.
505  
506 User can either pass in the known types in positional way or keyword argument way.
507 Tuple of Nones is returned if there is not enough information passed in.
508 An error will be raised if there is inconsistency found in the known types passed in.
509  
510 Parameters
511 ----------
512 args : Array
513 Provide type of arguments in a positional way.
514 Unknown type can be marked as None
515  
516 kwargs : Hash ref, must ne ssupplied as as sole argument to the method.
517 Provide keyword arguments of known types.
518  
519 Returns
520 -------
521 arg_types : array ref of Dtype or undef
522 List of types of arguments.
523 The order is in the same order as list_arguments()
524 out_types : array ref of Dtype or undef
525 List of types of outputs.
526 The order is in the same order as list_outputs()
527 aux_types : array ref of Dtype or undef
528 List of types of outputs.
529 The order is in the same order as list_auxiliary()
530 =cut
531  
532  
533 method infer_type(Maybe[Str] @args)
534 {
535 my ($positional_arguments, $kwargs, $kwargs_order) = _parse_arguments("Dtype", @args);
536 my $sdata = [];
537 my $keys = [];
538 if(@$positional_arguments)
539 {
540 @{ $sdata } = map { defined($_) ? DTYPE_STR_TO_MX->{ $_ } : -1 } @{ $positional_arguments };
541 }
542 else
543 {
544 @{ $keys } = @{ $kwargs_order };
545 @{ $sdata } = map { DTYPE_STR_TO_MX->{ $_ } } @{ $kwargs }{ @{ $kwargs_order } };
546 }
547 my ($arg_type, $out_type, $aux_type, $complete) = check_call(AI::MXNetCAPI::SymbolInferType(
548 $self->handle,
549 scalar(@{ $sdata }),
550 $keys,
551 $sdata
552 )
553 );
554 if($complete)
555 {
556 return (
557 [ map { DTYPE_MX_TO_STR->{ $_ } } @{ $arg_type }],
558 [ map { DTYPE_MX_TO_STR->{ $_ } } @{ $out_type }],
559 [ map { DTYPE_MX_TO_STR->{ $_ } } @{ $aux_type }]
560 );
561 }
562 else
563 {
564 return (undef, undef, undef);
565 }
566 }
567  
568 =head2 infer_shape
569  
570 Infer the shape of outputs and arguments of given known shapes of arguments.
571  
572 User can either pass in the known shapes in positional way or keyword argument way.
573 Tuple of Nones is returned if there is not enough information passed in.
574 An error will be raised if there is inconsistency found in the known shapes passed in.
575  
576 Parameters
577 ----------
578 *args :
579 Provide shape of arguments in a positional way.
580 Unknown shape can be marked as undef
581  
582 **kwargs :
583 Provide keyword arguments of known shapes.
584  
585 Returns
586 -------
587 arg_shapes : array ref of Shape or undef
588 List of shapes of arguments.
589 The order is in the same order as list_arguments()
590 out_shapes : array ref of Shape or undef
591 List of shapes of outputs.
592 The order is in the same order as list_outputs()
593 aux_shapes : array ref of Shape or undef
594 List of shapes of outputs.
595 The order is in the same order as list_auxiliary()
596 =cut
597  
598 method infer_shape(Maybe[Str|Shape] @args)
599 {
600 my @res = $self->_infer_shape_impl(0, @args);
601 if(not defined $res[1])
602 {
603 my ($arg_shapes) = $self->_infer_shape_impl(1, @args);
604 my $arg_names = $self->list_arguments;
605 my @unknowns;
606 for(zip($arg_names, $arg_shapes)) {
607 my ($name, $shape) = @$_;
608 if(not ref $shape or not @$shape or not product(@$shape))
609 {
610 if(@unknowns >= 10)
611 {
612 $unknowns[10] = '...';
613 }
614 else
615 {
616 my @shape = eval { @$shape };
617 push @unknowns, "$name @shape";
618 }
619 }
620 }
621 AI::MXNet::Logging->warning(
622 "Cannot decide shape for the following arguments "
623 ."(0s in shape means unknown dimensions). "
624 ."Consider providing them as input:\n\t"
625 ."\n\t"
626 .join(", ", @unknowns)
627 );
628 }
629 return @res;
630 }
631  
632 =head2 infer_shape_partial
633  
634 Partially infer the shape. The same as infer_shape, except that the partial
635 results can be returned.
636 =cut
637  
638 method infer_shape_partial(Maybe[Str|Shape] @args)
639 {
640 $self->_infer_shape_impl(1, @args)
641 }
642  
643 # The actual implementation for calling shape inference API.
644 method _infer_shape_impl(Maybe[Str|Shape] @args)
645 {
646 my $partial = shift(@args);
647 my ($positional_arguments, $kwargs, $kwargs_order) = _parse_arguments("Shape", @args);
648 my $sdata = [];
649 my $indptr = [0];
650 my $keys = [];
651 if(@{ $positional_arguments })
652 {
653 for my $shape (grep { defined } @{ $positional_arguments })
654 {
655 push @{ $sdata }, @{ $shape };
656 push @{ $indptr }, scalar(@{ $sdata });
657 }
658 }
659 {
660 for my $k (@{ $kwargs_order })
661 {
662 push @{ $keys }, $k;
663 push @{ $sdata }, @{ $kwargs->{ $k } };
664 push @{ $indptr }, scalar(@{ $sdata });
665 }
666 }
667 my $is64 = AI::MXNet::RunTime->Features()->is_enabled('INT64_TENSOR_SIZE');
668 my $infer_func = $partial
669 ? (
670 $is64 ? \&AI::MXNetCAPI::SymbolInferShapePartialEx64
671 : \&AI::MXNetCAPI::SymbolInferShapePartialEx
672 )
673 : (
674 $is64 ? \&AI::MXNetCAPI::SymbolInferShapeEx64
675 : \&AI::MXNetCAPI::SymbolInferShapeEx
676 );
677 my ($arg_shapes, $out_shapes, $aux_shapes, $complete) = check_call(
678 $infer_func->(
679 $self->handle,
680 scalar(@{ $indptr }) - 1,
681 $keys,
682 $indptr,
683 $sdata,
684 )
685 );
686 if($complete)
687 {
688 return $arg_shapes, $out_shapes, $aux_shapes;
689 }
690 else
691 {
692 return (undef, undef, undef);
693 }
694 }
695  
696 =head2 debug_str
697  
698 The debug string.
699  
700 Returns
701 -------
702 debug_str : string
703 Debug string of the symbol.
704 =cut
705  
706 method debug_str()
707 {
708 return scalar(check_call(AI::MXNetCAPI::SymbolPrint($self->handle)));
709 }
710  
711 =head2 save
712  
713 Save the symbol into a file.
714  
715 You can also use Storable to do the job if you only work with Perl.
716 The advantage of load/save is the file is language agnostic.
717 This means the file saved using save can be loaded by other language binding of mxnet.
718 You also get the benefit being able to directly load/save from cloud storage(S3, HDFS)
719  
720 Parameters
721 ----------
722 fname : str
723 The name of the file
724 - s3://my-bucket/path/my-s3-symbol
725 - hdfs://my-bucket/path/my-hdfs-symbol
726 - /path-to/my-local-symbol
727  
728 See Also
729 --------
730 load : Used to load symbol from file.
731 =cut
732  
733 method save(Str $fname)
734 {
735 check_call(AI::MXNetCAPI::SymbolSaveToFile($self->handle, $fname));
736 }
737  
738 =head2 tojson
739  
740 Save the symbol into a JSON string.
741  
742 See Also
743 --------
744 load_json : Used to load symbol from JSON string.
745 =cut
746  
747 method tojson()
748 {
749 return scalar(check_call(AI::MXNetCAPI::SymbolSaveToJSON($self->handle)));
750 }
751  
752 method _get_ndarray_inputs(
753 Str $arg_key,
754 HashRef[AI::MXNet::NDArray]|ArrayRef[AI::MXNet::NDArray] $args,
755 ArrayRef[Str] $arg_names,
756 Bool $allow_missing=0
757 )
758 {
759 my ($arg_handles, $arg_arrays) = ([], []);
760 if(ref $args eq 'ARRAY')
761 {
762 confess("Length of $arg_key do not match number of arguments")
763 unless @$args == @$arg_names;
764 @{ $arg_handles } = map { $_->handle } @{ $args };
765 $arg_arrays = $args;
766 }
767 else
768 {
769 my %tmp = ((map { $_ => undef } @$arg_names), %$args);
770 if(not $allow_missing and grep { not defined } values %tmp)
771 {
772 my ($missing) = grep { not defined $tmp{ $_ } } (keys %tmp);
773 confess("key $missing is missing in $arg_key");
774 }
775 for my $name (@$arg_names)
776 {
777 push @$arg_handles, defined($tmp{ $name }) ? $tmp{ $name }->handle : undef;
778 push @$arg_arrays, defined($tmp{ $name }) ? $tmp{ $name } : undef;
779 }
780 }
781 return ($arg_handles, $arg_arrays);
782 }
783  
784 =head2 simple_bind
785  
786 Bind current symbol to get an executor, allocate all the ndarrays needed.
787 Allows specifying data types.
788  
789 This function will ask user to pass in ndarray of position
790 they like to bind to, and it will automatically allocate the ndarray
791 for arguments and auxiliary states that user did not specify explicitly.
792  
793 Parameters
794 ----------
795 :$ctx : AI::MXNet::Context
796 The device context the generated executor to run on.
797  
798 :$grad_req: string
799 {'write', 'add', 'null'}, or list of str or dict of str to str, optional
800 Specifies how we should update the gradient to the args_grad.
801 - 'write' means everytime gradient is write to specified args_grad NDArray.
802 - 'add' means everytime gradient is add to the specified NDArray.
803 - 'null' means no action is taken, the gradient may not be calculated.
804  
805 :$type_dict : hash ref of str->Dtype
806 Input type map, name->dtype
807  
808 :$type_dict : hash ref of str->Stype
809 Storage type map, name->stype (for sparse operations)
810  
811 :$group2ctx : hash ref of string to AI::MXNet::Context
812 The mapping of the ctx_group attribute to the context assignment.
813  
814 :$shapes : hash ref of str->Shape
815 Input shape map, name->shape
816  
817 :$shared_arg_names : Maybe[ArrayRef[Str]]
818 The argument names whose 'NDArray' of shared_exec can be reused for initializing
819 the current executor.
820  
821 :$shared_exec : Maybe[AI::MXNet::Executor]
822 The executor whose arg_arrays, arg_arrays, grad_arrays, and aux_arrays can be
823 reused for initializing the current executor.
824  
825 :$shared_buffer : Maybe[HashRef[AI::MXNet::NDArray]]
826 The dict mapping argument names to the `NDArray` that can be reused for initializing
827 the current executor. This buffer will be checked for reuse if one argument name
828 of the current executor is not found in `shared_arg_names`.
829  
830 Returns
831 -------
832 $executor : AI::MXNet::Executor
833 The generated Executor
834 =cut
835  
836 method simple_bind(
837 AI::MXNet::Context :$ctx=AI::MXNet::Context->current_ctx,
838 GradReq|ArrayRef[GradReq]|HashRef[GradReq] :$grad_req='write',
839 Maybe[HashRef[Shape]] :$shapes=,
840 Maybe[HashRef[Dtype]] :$type_dict=,
841 Maybe[HashRef[Stype]] :$stype_dict=,
842 Maybe[HashRef[AI::MXNet::Context]] :$group2ctx=,
843 Maybe[ArrayRef[Str]] :$shared_arg_names=,
844 Maybe[AI::MXNet::Executor] :$shared_exec=,
845 Maybe[HashRef[AI::MXNet::NDArray]] :$shared_buffer=
846 )
847 {
848 my $num_provided_arg_types = 0;
849 my @provided_arg_type_names;
850 my @provided_arg_type_data;
851 if(defined $type_dict)
852 {
853 while(my ($k, $v) = each %{ $type_dict })
854 {
855 push @provided_arg_type_names, $k;
856 push @provided_arg_type_data, DTYPE_STR_TO_MX->{$v};
857 }
858 $num_provided_arg_types = @provided_arg_type_names;
859 }
860 my $num_provided_arg_stypes = 0;
861 my @provided_arg_stype_names;
862 my @provided_arg_stype_data;
863 if(defined $stype_dict)
864 {
865 while(my ($k, $v) = each %{ $stype_dict })
866 {
867 push @provided_arg_stype_names, $k;
868 push @provided_arg_stype_data, STORAGE_TYPE_STR_TO_ID->{$v};
869 }
870 $num_provided_arg_stypes = @provided_arg_stype_names;
871 }
872 my @provided_arg_shape_data;
873 # argument shape index in sdata,
874 # e.g. [sdata[indptr[0]], sdata[indptr[1]]) is the shape of the first arg
875 my @provided_arg_shape_idx = (0);
876 my @provided_arg_shape_names;
877 while(my ($k, $v) = each %{ $shapes//{} })
878 {
879 push @provided_arg_shape_names, $k;
880 push @provided_arg_shape_data, @{ $v };
881 push @provided_arg_shape_idx, scalar(@provided_arg_shape_data);
882 }
883 $num_provided_arg_types = @provided_arg_type_names;
884  
885 my $provided_req_type_list_len = 0;
886 my @provided_grad_req_types;
887 my @provided_grad_req_names;
888 if(defined $grad_req)
889 {
890 if(not ref $grad_req)
891 {
892 push @provided_grad_req_types, $grad_req;
893 }
894 elsif(ref $grad_req eq 'ARRAY')
895 {
896 assert((@{ $grad_req } != 0), 'grad_req in simple_bind cannot be an empty list');
897 @provided_grad_req_types = @{ $grad_req };
898 $provided_req_type_list_len = @provided_grad_req_types;
899 }
900 elsif(ref $grad_req eq 'HASH')
901 {
902 assert((keys %{ $grad_req } != 0), 'grad_req in simple_bind cannot be an empty hash');
903 while(my ($k, $v) = each %{ $grad_req })
904 {
905 push @provided_grad_req_names, $k;
906 push @provided_grad_req_types, $v;
907 }
908 $provided_req_type_list_len = @provided_grad_req_types;
909 }
910 }
911 my $num_ctx_map_keys = 0;
912 my @ctx_map_keys;
913 my @ctx_map_dev_types;
914 my @ctx_map_dev_ids;
915 if(defined $group2ctx)
916 {
917 while(my ($k, $v) = each %{ $group2ctx })
918 {
919 push @ctx_map_keys, $k;
920 push @ctx_map_dev_types, $v->device_type_id;
921 push @ctx_map_dev_ids, $v->device_id;
922 }
923 $num_ctx_map_keys = @ctx_map_keys;
924 }
925  
926 my @shared_arg_name_list;
927 if(defined $shared_arg_names)
928 {
929 @shared_arg_name_list = @{ $shared_arg_names };
930 }
931 my %shared_data;
932 if(defined $shared_buffer)
933 {
934 while(my ($k, $v) = each %{ $shared_buffer })
935 {
936 $shared_data{$k} = $v->handle;
937 }
938 }
939 my $shared_exec_handle = defined $shared_exec ? $shared_exec->handle : undef;
940 my (
941 $updated_shared_data,
942 $in_arg_handles,
943 $arg_grad_handles,
944 $aux_state_handles,
945 $exe_handle
946 );
947 my $sub = AI::MXNet::RunTime->Features()->is_enabled('INT64_TENSOR_SIZE')
948 ? \&AI::MXNetCAPI::ExecutorSimpleBindEx64
949 : \&AI::MXNetCAPI::ExecutorSimpleBindEx;
950 eval {
951 ($updated_shared_data, $in_arg_handles, $arg_grad_handles, $aux_state_handles, $exe_handle)
952 =
953 check_call(
954 $sub->(
955 $self->handle,
956 $ctx->device_type_id,
957 $ctx->device_id,
958 $num_ctx_map_keys,
959 \@ctx_map_keys,
960 \@ctx_map_dev_types,
961 \@ctx_map_dev_ids,
962 $provided_req_type_list_len,
963 \@provided_grad_req_names,
964 \@provided_grad_req_types,
965 scalar(@provided_arg_shape_names),
966 \@provided_arg_shape_names,
967 \@provided_arg_shape_data,
968 \@provided_arg_shape_idx,
969 $num_provided_arg_types,
970 \@provided_arg_type_names,
971 \@provided_arg_type_data,
972 $num_provided_arg_stypes,
973 \@provided_arg_stype_names,
974 \@provided_arg_stype_data,
975 scalar(@shared_arg_name_list),
976 \@shared_arg_name_list,
977 defined $shared_buffer ? \%shared_data : undef,
978 $shared_exec_handle
979 )
980 );
981 };
982 if($@)
983 {
984 confess(
985 "simple_bind failed: Error: $@; Arguments: ".
986 Data::Dumper->new(
987 [$shapes//{}]
988 )->Purity(1)->Deepcopy(1)->Terse(1)->Dump
989 );
990 }
991 if(defined $shared_buffer)
992 {
993 while(my ($k, $v) = each %{ $updated_shared_data })
994 {
995 $shared_buffer->{$k} = AI::MXNet::NDArray->_ndarray_cls($v);
996 }
997 }
998 my @arg_arrays = map { AI::MXNet::NDArray->_ndarray_cls($_) } @{ $in_arg_handles };
999 my @grad_arrays = map { defined $_ ? AI::MXNet::NDArray->_ndarray_cls($_) : undef } @{ $arg_grad_handles };
1000 my @aux_arrays = map { AI::MXNet::NDArray->_ndarray_cls($_) } @{ $aux_state_handles };
1001 my $executor = AI::MXNet::Executor->new(
1002 handle => $exe_handle,
1003 symbol => $self,
1004 ctx => $ctx,
1005 grad_req => $grad_req,
1006 group2ctx => $group2ctx
1007 );
1008 $executor->arg_arrays(\@arg_arrays);
1009 $executor->grad_arrays(\@grad_arrays);
1010 $executor->aux_arrays(\@aux_arrays);
1011 return $executor;
1012 }
1013  
1014 =head2 bind
1015  
1016 Bind current symbol to get an executor.
1017  
1018 Parameters
1019 ----------
1020 :$ctx : AI::MXNet::Context
1021 The device context the generated executor to run on.
1022  
1023 :$args : HashRef[AI::MXNet::NDArray]|ArrayRef[AI::MXNet::NDArray]
1024 Input arguments to the symbol.
1025 - If type is array ref of NDArray, the position is in the same order of list_arguments.
1026 - If type is hash ref of str to NDArray, then it maps the name of arguments
1027 to the corresponding NDArray.
1028 - In either case, all the arguments must be provided.
1029  
1030 :$args_grad : Maybe[HashRef[AI::MXNet::NDArray]|ArrayRef[AI::MXNet::NDArray]]
1031 When specified, args_grad provide NDArrays to hold
1032 the result of gradient value in backward.
1033 - If type is array ref of NDArray, the position is in the same order of list_arguments.
1034 - If type is hash ref of str to NDArray, then it maps the name of arguments
1035 to the corresponding NDArray.
1036 - When the type is hash ref of str to NDArray, users only need to provide the dict
1037 for needed argument gradient.
1038 Only the specified argument gradient will be calculated.
1039  
1040 :$grad_req : {'write', 'add', 'null'}, or array ref of str or hash ref of str to str, optional
1041 Specifies how we should update the gradient to the args_grad.
1042 - 'write' means everytime gradient is write to specified args_grad NDArray.
1043 - 'add' means everytime gradient is add to the specified NDArray.
1044 - 'null' means no action is taken, the gradient may not be calculated.
1045  
1046 :$aux_states : array ref of NDArray, or hash ref of str to NDArray, optional
1047 Input auxiliary states to the symbol, only need to specify when
1048 list_auxiliary_states is not empty.
1049 - If type is array ref of NDArray, the position is in the same order of list_auxiliary_states
1050 - If type is hash ref of str to NDArray, then it maps the name of auxiliary_states
1051 to the corresponding NDArray,
1052 - In either case, all the auxiliary_states need to be provided.
1053  
1054 :$group2ctx : hash ref of string to AI::MXNet::Context
1055 The mapping of the ctx_group attribute to the context assignment.
1056  
1057 :$shared_exec : AI::MXNet::Executor
1058 Executor to share memory with. This is intended for runtime reshaping, variable length
1059 sequences, etc. The returned executor shares state with shared_exec, and should not be
1060 used in parallel with it.
1061  
1062 Returns
1063 -------
1064 $executor : AI::MXNet::Executor
1065 The generated Executor
1066  
1067 Notes
1068 -----
1069 Auxiliary states are special states of symbols that do not corresponds to an argument,
1070 and do not have gradient. But still be useful for the specific operations.
1071 A common example of auxiliary state is the moving_mean and moving_variance in BatchNorm.
1072 Most operators do not have auxiliary states and this parameter can be safely ignored.
1073  
1074 User can give up gradient by using a hash ref in args_grad and only specify
1075 the gradient they're interested in.
1076 =cut
1077  
1078 method bind(
1079 AI::MXNet::Context :$ctx,
1080 HashRef[AI::MXNet::NDArray]|ArrayRef[AI::MXNet::NDArray] :$args,
1081 Maybe[HashRef[AI::MXNet::NDArray]|ArrayRef[AI::MXNet::NDArray]] :$args_grad=,
1082 Str|HashRef[Str]|ArrayRef[Str] :$grad_req='write',
1083 Maybe[HashRef[AI::MXNet::NDArray]|ArrayRef[AI::MXNet::NDArray]] :$aux_states=,
1084 Maybe[HashRef[AI::MXNet::Context]] :$group2ctx=,
1085 Maybe[AI::MXNet::Executor] :$shared_exec=
1086 )
1087 {
1088 $grad_req //= 'write';
1089 my $listed_arguments = $self->list_arguments();
1090 my ($args_handle, $args_grad_handle, $aux_args_handle) = ([], [], []);
1091 ($args_handle, $args) = $self->_get_ndarray_inputs('args', $args, $listed_arguments);
1092 if(not defined $args_grad)
1093 {
1094 @$args_grad_handle = ((undef) x (@$args));
1095 }
1096 else
1097 {
1098 ($args_grad_handle, $args_grad) = $self->_get_ndarray_inputs(
1099 'args_grad', $args_grad, $listed_arguments, 1
1100 );
1101 }
1102  
1103 if(not defined $aux_states)
1104 {
1105 $aux_states = [];
1106 }
1107 ($aux_args_handle, $aux_states) = $self->_get_ndarray_inputs(
1108 'aux_states', $aux_states, $self->list_auxiliary_states()
1109 );
1110  
1111 # setup requirements
1112 my $req_map = { null => 0, write => 1, add => 3 };
1113 my $req_array = [];
1114 if(not ref $grad_req)
1115 {
1116 confess('grad_req must be one of "null,write,add"')
1117 unless exists $req_map->{ $grad_req };
1118 @{ $req_array } = (($req_map->{ $grad_req }) x @{ $listed_arguments });
1119 }
1120 elsif(ref $grad_req eq 'ARRAY')
1121 {
1122 @{ $req_array } = map { $req_map->{ $_ } } @{ $grad_req };
1123 }
1124 else
1125 {
1126 for my $name (@{ $listed_arguments })
1127 {
1128 if(exists $grad_req->{ $name })
1129 {
1130 push @{ $req_array }, $req_map->{ $grad_req->{ $name } };
1131 }
1132 else
1133 {
1134 push @{ $req_array }, 0;
1135 }
1136 }
1137 }
1138  
1139 my $ctx_map_keys = [];
1140 my $ctx_map_dev_types = [];
1141 my $ctx_map_dev_ids = [];
1142  
1143 if(defined $group2ctx)
1144 {
1145 while(my ($key, $val) = each %{ $group2ctx })
1146 {
1147 push @{ $ctx_map_keys } , $key;
1148 push @{ $ctx_map_dev_types }, $val->device_type_id;
1149 push @{ $ctx_map_dev_ids }, $val->device_id;
1150 }
1151 }
1152 my $shared_handle = $shared_exec->handle if $shared_exec;
1153 my $handle = check_call(AI::MXNetCAPI::ExecutorBindEX(
1154 $self->handle,
1155 $ctx->device_type_id,
1156 $ctx->device_id,
1157 scalar(@{ $ctx_map_keys }),
1158 $ctx_map_keys,
1159 $ctx_map_dev_types,
1160 $ctx_map_dev_ids,
1161 scalar(@{ $args }),
1162 $args_handle,
1163 $args_grad_handle,
1164 $req_array,
1165 scalar(@{ $aux_states }),
1166 $aux_args_handle,
1167 $shared_handle
1168 )
1169 );
1170 my $executor = AI::MXNet::Executor->new(
1171 handle => $handle,
1172 symbol => $self,
1173 ctx => $ctx,
1174 grad_req => $grad_req,
1175 group2ctx => $group2ctx
1176 );
1177 $executor->arg_arrays($args);
1178 $executor->grad_arrays($args_grad);
1179 $executor->aux_arrays($aux_states);
1180 return $executor;
1181 }
1182  
1183 =head2 eval
1184  
1185 Evaluate a symbol given arguments
1186  
1187 The `eval` method combines a call to `bind` (which returns an executor)
1188 with a call to `forward` (executor method).
1189 For the common use case, where you might repeatedly evaluate with same arguments,
1190 eval is slow.
1191 In that case, you should call `bind` once and then repeatedly call forward.
1192 Eval allows simpler syntax for less cumbersome introspection.
1193  
1194 Parameters
1195 ----------
1196 :$ctx : Context
1197 The device context the generated executor to run on.
1198 Optional, defaults to cpu(0)
1199  
1200 :$args array ref of NDArray or hash ref of NDArray
1201  
1202 - If the type is an array ref of NDArray, the position is in the same order of list_arguments.
1203 - If the type is a hash of str to NDArray, then it maps the name of the argument
1204 to the corresponding NDArray.
1205 - In either case, all arguments must be provided.
1206  
1207 Returns
1208 ----------
1209 result : an array ref of NDArrays corresponding to the values
1210 taken by each symbol when evaluated on given args.
1211 When called on a single symbol (not a group),
1212 the result will be an array ref with one element.
1213  
1214 Examples:
1215 my $result = $symbol->eval(ctx => mx->gpu, args => {data => mx->nd->ones([5,5])});
1216 my $result = $symbol->eval(args => {data => mx->nd->ones([5,5])});
1217  
1218 =cut
1219  
1220 method eval(:$ctx=AI::MXNet::Context->cpu, HashRef[AI::MXNet::NDArray]|ArrayRef[AI::MXNet::NDArray] :$args)
1221 {
1222 return $self->bind(ctx => $ctx, args => $args)->forward;
1223 }
1224  
1225 =head2 grad
1226  
1227 Get the autodiff of current symbol.
1228 This function can only be used if current symbol is a loss function.
1229  
1230 Parameters
1231 ----------
1232 $wrt : Array of String
1233 keyword arguments of the symbol that the gradients are taken.
1234  
1235 Returns
1236 -------
1237 grad : AI::MXNet::Symbol
1238 A gradient Symbol with returns to be the corresponding gradients.
1239 =cut
1240  
1241 method grad(ArrayRef[Str] $wrt)
1242 {
1243 my $handle = check_call(AI::MXNetCAPI::SymbolGrad(
1244 $self->handle,
1245 scalar(@$wrt),
1246 $wrt
1247 )
1248 );
1249 return __PACKAGE__->new(handle => $handle);
1250 }
1251  
1252 =head2 Variable
1253  
1254 Create a symbolic variable with specified name.
1255  
1256 Parameters
1257 ----------
1258 name : str
1259 Name of the variable.
1260 attr : hash ref of string -> string
1261 Additional attributes to set on the variable.
1262 shape : array ref of positive integers
1263 Optionally, one can specify the shape of a variable. This will be used during
1264 shape inference. If user specified a different shape for this variable using
1265 keyword argument when calling shape inference, this shape information will be ignored.
1266 lr_mult : float
1267 Specify learning rate muliplier for this variable.
1268 wd_mult : float
1269 Specify weight decay muliplier for this variable.
1270 dtype : Dtype
1271 Similar to shape, we can specify dtype for this variable.
1272 init : initializer (mx->init->*)
1273 Specify initializer for this variable to override the default initializer
1274 kwargs : hash ref
1275 other additional attribute variables
1276 Returns
1277 -------
1278 variable : Symbol
1279 The created variable symbol.
1280 =cut
1281  
1282 method Variable(
1283 Str $name,
1284 HashRef[Str] :$attr={},
1285 Maybe[Shape] :$shape=,
1286 Maybe[Num] :$lr_mult=,
1287 Maybe[Num] :$wd_mult=,
1288 Maybe[Dtype] :$dtype=,
1289 Maybe[Stype] :$stype=,
1290 Maybe[Initializer] :$init=,
1291 HashRef[Str] :$kwargs={},
1292 Maybe[Str] :$__layout__=
1293 )
1294 {
1295 my $handle = check_call(AI::MXNetCAPI::SymbolCreateVariable($name));
1296 my $ret = __PACKAGE__->new(handle => $handle);
1297 $attr = AI::MXNet::Symbol::AttrScope->current->get($attr);
1298 $attr->{__shape__} = "(".join(',', @{ $shape }).")" if $shape;
1299 $attr->{__lr_mult__} = $lr_mult if defined $lr_mult;
1300 $attr->{__wd_mult__} = $wd_mult if defined $wd_mult;
1301 $attr->{__dtype__} = DTYPE_STR_TO_MX->{ $dtype } if $dtype;
1302 $attr->{__init__} = "$init" if defined $init;
1303 $attr->{__layout__} = $__layout__ if defined $__layout__;
1304 $attr->{__storage_type__} = STORAGE_TYPE_STR_TO_ID->{$stype} if defined $stype;
1305 while(my ($k, $v) = each %{ $kwargs })
1306 {
1307 if($k =~ /^__/ and $k =~ /__$/)
1308 {
1309 $attr->{$k} = "$v";
1310 }
1311 else
1312 {
1313 confess("Attribute name=$k is not supported.".
1314 ' Additional attributes must start and end with double underscores,'.
1315 ' e.g, __yourattr__'
1316 );
1317 }
1318 }
1319 $ret->_set_attr(%{ $attr });
1320 return $ret;
1321 }
1322  
1323 =head2 var
1324  
1325 A synonym to Variable.
1326 =cut
1327  
1328 *var = \&Variable;
1329  
1330 =head2 Group
1331  
1332 Create a symbol that groups symbols together.
1333  
1334 Parameters
1335 ----------
1336 symbols : array ref
1337 List of symbols to be grouped.
1338  
1339 Returns
1340 -------
1341 sym : Symbol
1342 The created group symbol.
1343 =cut
1344  
1345 method Group(ArrayRef[AI::MXNet::Symbol] $symbols)
1346 {
1347 my @handles = map { $_->handle } @{ $symbols };
1348 my $handle = check_call(AI::MXNetCAPI::SymbolCreateGroup(scalar(@handles), \@handles));
1349 return __PACKAGE__->new(handle => $handle);
1350 }
1351  
1352 =head2 load
1353  
1354 Load symbol from a JSON file.
1355  
1356 You can also use Storable to do the job if you only work with Perl.
1357 The advantage of load/save is the file is language agnostic.
1358 This means the file saved using save can be loaded by other language binding of mxnet.
1359 You also get the benefit being able to directly load/save from cloud storage(S3, HDFS)
1360  
1361 Parameters
1362 ----------
1363 fname : str
1364 The name of the file, examples:
1365  
1366 - `s3://my-bucket/path/my-s3-symbol`
1367 - `hdfs://my-bucket/path/my-hdfs-symbol`
1368 - `/path-to/my-local-symbol`
1369  
1370 Returns
1371 -------
1372 sym : Symbol
1373 The loaded symbol.
1374  
1375 See Also
1376 --------
1377 AI::MXNet::Symbol->save : Used to save symbol into file.
1378 =cut
1379  
1380 method load(Str $fname)
1381 {
1382 my $handle = check_call(AI::MXNetCAPI::SymbolCreateFromFile($fname));
1383 return __PACKAGE__->new(handle => $handle);
1384 }
1385  
1386 =head2 load_json
1387  
1388 Load symbol from json string.
1389  
1390 Parameters
1391 ----------
1392 json_str : str
1393 A json string.
1394  
1395 Returns
1396 -------
1397 sym : Symbol
1398 The loaded symbol.
1399  
1400 See Also
1401 --------
1402 AI::MXNet::Symbol->tojson : Used to save symbol into json string.
1403 =cut
1404  
1405 method load_json(Str $json)
1406 {
1407 my $handle = check_call(AI::MXNetCAPI::SymbolCreateFromJSON($json));
1408 return __PACKAGE__->new(handle => $handle);
1409 }
1410  
1411 method zeros(Shape :$shape, Dtype :$dtype='float32', Maybe[Str] :$name=, Maybe[Str] :$__layout__=)
1412 {
1413 return __PACKAGE__->_zeros({ shape => $shape, dtype => $dtype, name => $name, ($__layout__ ? (__layout__ => $__layout__) : ()) });
1414 }
1415  
1416 method ones(Shape :$shape, Dtype :$dtype='float32', Maybe[Str] :$name=, Maybe[Str] :$__layout__=)
1417 {
1418 return __PACKAGE__->_ones({ shape => $shape, dtype => $dtype, name => $name, ($__layout__ ? (__layout__ => $__layout__) : ()) });
1419 }
1420  
1421 =head2 arange
1422  
1423 Simlar function in the MXNet ndarray as numpy.arange
1424 See Also https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html.
1425  
1426 Parameters
1427 ----------
1428 :$start=0 : number
1429 Start of interval. The interval includes this value. The default start value is 0.
1430 :$stop= : number, optional
1431 End of interval. The interval does not include this value.
1432 :$step=1.0 : number, optional
1433 Spacing between values
1434 :$repeat=1 : int, optional
1435 "The repeating time of all elements.
1436 E.g repeat=3, the element a will be repeated three times --> a, a, a.
1437 :$infer_range=0 : Bool
1438 When set to 1, infer stop position from start, step, repeat, and
1439 output tensor size.
1440 :$dtype='float32' : type, optional
1441 The value type of the NDArray, default to np.float32
1442  
1443 Returns
1444 -------
1445 out : Symbol
1446 The created Symbol
1447 =cut
1448  
1449 method arange(Index :$start=0, Index :$stop=, Num :$step=1.0, Index :$repeat=1, Bool :$infer_range=0, Maybe[Str] :$name=, Dtype :$dtype='float32')
1450 {
1451 return __PACKAGE__->_arange({
1452 start => $start, (defined $stop ? (stop => $stop) : ()),
1453 step => $step, repeat => $repeat, name => $name, dtype => $dtype,
1454 infer_range => $infer_range
1455 });
1456 }
1457  
1458  
1459 sub _parse_arguments
1460 {
1461 my $type = shift;
1462 my @args = @_;
1463 my $type_c = find_type_constraint($type);
1464 my $str_c = find_type_constraint("Str");
1465 my @positional_arguments;
1466 my %kwargs;
1467 my @kwargs_order;
1468 my $only_dtypes_and_undefs = (@args == grep { not defined($_) or $type_c->check($_) } @args);
1469 my $only_dtypes_and_strs = (@args == grep { $type_c->check($_) or $str_c->check($_) } @args);
1470 if(@args % 2 and $only_dtypes_and_undefs)
1471 {
1472 @positional_arguments = @args;
1473 }
1474 else
1475 {
1476 if($only_dtypes_and_undefs)
1477 {
1478 @positional_arguments = @args;
1479 }
1480 elsif($only_dtypes_and_strs)
1481 {
1482 my %tmp = @args;
1483 if(values(%tmp) == grep { $type_c->check($_) } values(%tmp))
1484 {
1485 %kwargs = %tmp;
1486 my $i = 0;
1487 @kwargs_order = grep { $i ^= 1 } @args;
1488 }
1489 else
1490 {
1491 confess("Argument needs to be of type $type");
1492 }
1493 }
1494 else
1495 {
1496 confess("Argument needs to be one type $type");
1497 }
1498 }
1499 return (\@positional_arguments, \%kwargs, \@kwargs_order);
1500 }
1501  
1502 sub _ufunc_helper
1503 {
1504 my ($lhs, $rhs, $fn_symbol, $lfn_scalar, $rfn_scalar, $reverse) = @_;
1505 ($rhs, $lhs) = ($lhs, $rhs) if $reverse and $rfn_scalar;
1506 if(not ref $lhs)
1507 {
1508 if(not $rfn_scalar)
1509 {
1510 return __PACKAGE__->can($lfn_scalar)->(__PACKAGE__, $rhs, { "scalar" => $lhs });
1511 }
1512 else
1513 {
1514 return __PACKAGE__->can($rfn_scalar)->(__PACKAGE__, $rhs, { "scalar" => $lhs });
1515 }
1516 }
1517 elsif(not ref $rhs)
1518 {
1519 return __PACKAGE__->can($lfn_scalar)->(__PACKAGE__, $lhs, { "scalar" => $rhs });
1520 }
1521 else
1522 {
1523 return __PACKAGE__->can($fn_symbol)->(__PACKAGE__, $lhs, $rhs);
1524 }
1525 }
1526  
1527 method histogram(@args) { __PACKAGE__->_histogram(@args%2 ? ('data', @args) : @args) }
1528  
1529 sub contrib { 'AI::MXNet::Contrib::Symbol' }
1530 sub random { 'AI::MXNet::Symbol::Random' }
1531 sub sparse { 'AI::MXNet::Symbol::Sparse' }
1532 sub linalg { 'AI::MXNet::LinAlg::Symbol' }
1533 sub image { 'AI::MXNet::Image::Symbol' }
1534  
1535 1;