MXNet/Base.pm

filter: Statementstmt 88.8% 16 / 18 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 91.6% 22 / 24 CC 1 SCAR 0.5
CC
1
Cov
89%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« MXNet.pm ↑ Summary
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::Base;
19 31 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 31 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 31 ▶use PDL;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 31 ▶use PDL::Types ();
Subroutine BEGIN: called CC=1 SCAR=0.0
23 31 ▶use PDL::CCS::Nd;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 31 ▶use AI::MXNetCAPI 1.5;
Subroutine BEGIN: called CC=1 SCAR=2.6
25 use AI::NNVMCAPI 1.4;
26 use AI::MXNet::Types;
27 use Time::HiRes;
28 use Scalar::Util qw(blessed);
29 use Carp;
30 use Exporter;
31 use base qw(Exporter);
32 use List::Util qw(shuffle);
33 use Data::Dumper;
34  
35 our @EXPORT = qw(product enumerate assert zip check_call build_param_doc
36 pdl cat dog svd bisect_left pdl_shuffle as_array ascsr rand_sparse
37 DTYPE_STR_TO_MX DTYPE_MX_TO_STR DTYPE_MX_TO_PDL
38 DTYPE_PDL_TO_MX DTYPE_MX_TO_PERL GRAD_REQ_MAP
39 STORAGE_TYPE_UNDEFINED STORAGE_TYPE_DEFAULT
40 STORAGE_TYPE_ROW_SPARSE STORAGE_TYPE_CSR
41 STORAGE_TYPE_STR_TO_ID STORAGE_TYPE_ID_TO_STR STORAGE_AUX_TYPES);
42 our @EXPORT_OK = qw(pzeros pceil pones digitize hash array_index range);
43  
44 use constant DTYPE_STR_TO_MX => {
45 float32 => 0,
46 float64 => 1,
47 float16 => 2,
48 uint8 => 3,
49 int32 => 4,
50 int8 => 5,
51 int64 => 6
52 };
53 use constant DTYPE_MX_TO_STR => {
54 0 => 'float32',
55 1 => 'float64',
56 2 => 'float16',
57 3 => 'uint8',
58 4 => 'int32',
59 5 => 'int8',
60 6 => 'int64'
61 };
62 use constant DTYPE_MX_TO_PDL => {
63 0 => 6,
64 1 => 7,
65 2 => 6,
66 3 => 0,
67 4 => 3,
68 5 => 0,
69 6 => 5,
70 float32 => 6,
71 float64 => 7,
72 float16 => 6,
73 uint8 => 0,
74 int32 => 3,
75 int8 => 0,
76 int64 => 5
77 };
78 use constant DTYPE_PDL_TO_MX => {
79 6 => 0,
80 7 => 1,
81 0 => 3,
82 3 => 4,
83 5 => 6
84 };
85 use constant DTYPE_MX_TO_PERL => {
86 0 => 'f',
87 1 => 'd',
88 2 => 'S',
89 3 => 'C',
90 4 => 'l',
91 5 => 'c',
92 6 => 'q',
93 float32 => 'f',
94 float64 => 'd',
95 float16 => 'S',
96 uint8 => 'C',
97 int32 => 'l',
98 int8 => 'c',
99 int64 => 'q'
100 };
101 use constant GRAD_REQ_MAP => {
102 null => 0,
103 write => 1,
104 add => 3
105 };
106 use constant {
107 STORAGE_TYPE_UNDEFINED => -1,
108 STORAGE_TYPE_DEFAULT => 0,
109 STORAGE_TYPE_ROW_SPARSE => 1,
110 STORAGE_TYPE_CSR => 2
111 };
112 use constant STORAGE_TYPE_STR_TO_ID => {
113 undefined => STORAGE_TYPE_UNDEFINED,
114 default => STORAGE_TYPE_DEFAULT,
115 row_sparse => STORAGE_TYPE_ROW_SPARSE,
116 csr => STORAGE_TYPE_CSR
117 };
118 use constant STORAGE_TYPE_ID_TO_STR => {
119 STORAGE_TYPE_UNDEFINED() => 'undefined',
120 STORAGE_TYPE_DEFAULT() => 'default',
121 STORAGE_TYPE_ROW_SPARSE() => 'row_sparse',
122 STORAGE_TYPE_CSR() => 'csr'
123 };
124 use constant STORAGE_AUX_TYPES => {
125 row_sparse => ['int64'],
126 csr => ['int64', 'int64']
127 };
128  
129  
130 =head1 NAME
131  
132 AI::MXNet::Base - Helper functions
133  
134 =head1 DEFINITION
135  
136 Helper functions
137  
138 =head2 zip
139  
140 Perl version of for x,y,z in zip (arr_x, arr_y, arr_z)
141  
142 Parameters
143 ----------
144 $sub_ref, called with @_ filled with $arr_x->[$i], $arr_y->[$i], $arr_z->[$i]
145 for each loop iteration.
146  
147 @array_refs
148 =cut
149  
150 sub zip
151 {
152 if('CODE' eq ref $_[0])
153 {
154 # continue supporting the callback style
155 my $code = shift;
156 $code->(@$_) for AI::MXNetCAPI::py_zip(map { \@$_ } @_);
157 return;
158 }
159 # the map() here may seem like a no-op, but triggers overloading or
160 # whatever else is needed to make array-ish things actually arrays
161 # before entering the low level list builder.
162 return AI::MXNetCAPI::py_zip(map { \@$_ } @_);
163 }
164  
165 =head2 enumerate
166  
167 Same as zip, but the argument list in the anonymous sub is prepended
168 by the iteration count.
169 =cut
170  
171 sub enumerate
172 {
173 if('CODE' eq ref $_[0])
174 {
175 # continue supporting the callback style
176 my $code = shift;
177 my $len = @{ $_[0] };
178 $code->(@$_) for AI::MXNetCAPI::py_zip([0..$len-1], map { \@$_ } @_);
179 return;
180 }
181 my $len = @{ $_[0] };
182 return AI::MXNetCAPI::py_zip([0..$len-1], map { \@$_ } @_);
183 }
184  
185 =head2 product
186  
187 Calculates the product of the input agruments.
188 =cut
189  
190 sub product
191 {
192 my $p = 1;
193 map { $p = $p * $_ } @_;
194 return $p;
195 }
196  
197 =head2 bisect_left
198  
199 https://hg.python.org/cpython/file/2.7/Lib/bisect.py
200 =cut
201  
202 sub bisect_left
203 {
204 my ($a, $x, $lo, $hi) = @_;
205 $lo //= 0;
206 $hi //= @{ $a };
207 if($lo < 0)
208 {
209 Carp::confess('lo must be non-negative');
210 }
211 while($lo < $hi)
212 {
213 my $mid = int(($lo+$hi)/2);
214 if($a->[$mid] < $x)
215 {
216 $lo = $mid+1;
217 }
218 else
219 {
220 $hi = $mid;
221 }
222 }
223 return $lo;
224 }
225  
226 =head2 pdl_shuffle
227  
228 Shuffle the pdl by the last dimension
229  
230 Parameters
231 -----------
232 PDL $pdl
233 $preshuffle Maybe[ArrayRef[Index]], if defined the array elements are used
234 as shuffled last dimension's indexes
235 =cut
236  
237 sub pdl_shuffle
238 {
239 my ($pdl, $preshuffle) = @_;
240 my @shuffle = $preshuffle ? @{ $preshuffle } : shuffle(0..$pdl->dim(-1)-1);
241 return $pdl->dice_axis(-1, pdl(\@shuffle));
242 }
243  
244 =head2 assert
245  
246 Parameters
247 -----------
248 Bool $input
249 Str $error_str
250 Calls Carp::confess with $error_str//"AssertionError" if the $input is false
251 =cut
252  
253 sub assert
254 {
255 my ($input, $error_str) = @_;
256 local($Carp::CarpLevel) = 1;
257 Carp::confess($error_str//'AssertionError')
258 unless $input;
259 }
260  
261 =head2 check_call
262  
263 Checks the return value of C API call
264  
265 This function will raise an exception when error occurs.
266 Every API call is wrapped with this function.
267  
268 Returns the C API call return values stripped of first return value,
269 checks for return context and returns first element in
270 the values list when called in scalar context.
271 =cut
272  
273 sub check_call
274 {
275 Carp::confess(AI::MXNetCAPI::GetLastError()) if shift;
276 return wantarray ? @_ : $_[0];
277 }
278  
279 =head2 build_param_doc
280  
281 Builds argument docs in python style.
282  
283 arg_names : array ref of str
284 Argument names.
285  
286 arg_types : array ref of str
287 Argument type information.
288  
289 arg_descs : array ref of str
290 Argument description information.
291  
292 remove_dup : boolean, optional
293 Whether to remove duplication or not.
294  
295 Returns
296 -------
297 docstr : str
298 Python docstring of parameter sections.
299 =cut
300  
301 sub build_param_doc
302 {
303 my ($arg_names, $arg_types, $arg_descs, $remove_dup) = @_;
304 $remove_dup //= 1;
305 my %param_keys;
306 my @param_str;
307 for(zip($arg_names, $arg_types, $arg_descs)) {
308 my ($key, $type_info, $desc) = @$_;
309 next if exists $param_keys{$key} and $remove_dup;
310 $param_keys{$key} = 1;
311 my $ret = sprintf("%s : %s", $key, $type_info);
312 $ret .= "\n ".$desc if length($desc);
313 push @param_str, $ret;
314 }
315 return sprintf("Parameters\n----------\n%s\n", join("\n", @param_str));
316 }
317  
318 =head2 _notify_shutdown
319  
320 Notify MXNet about shutdown.
321 =cut
322  
323 sub _notify_shutdown
324 {
325 check_call(AI::MXNetCAPI::NotifyShutdown());
326 }
327  
328 sub _indent
329 {
330 my ($s_, $numSpaces) = @_;
331 my @s = split(/\n/, $s_);
332 if (@s == 1)
333 {
334 return $s_;
335 }
336 my $first = shift(@s);
337 @s = ($first, map { (' 'x$numSpaces) . $_ } @s);
338 return join("\n", @s);
339 }
340  
341 sub as_array
342 {
343 return ref $_[0] eq 'ARRAY' ? $_[0] : [$_[0]];
344 }
345  
346 my %internal_arguments = (prefix => 1, params => 1, shared => 1);
347 my %attributes_per_class;
348 sub process_arguments
349 {
350 my $orig = shift;
351 my $class = shift;
352 if($class->can('python_constructor_arguments'))
353 {
354 if(not exists $attributes_per_class{$class})
355 {
356 %{ $attributes_per_class{$class} } = map { $_->name => 1 } $class->meta->get_all_attributes;
357 }
358 my %kwargs;
359 while(@_ >= 2 and defined $_[-2] and not ref $_[-2] and (exists $attributes_per_class{$class}{ $_[-2] } or exists $internal_arguments{ $_[-2] }))
360 {
361 my $v = pop(@_);
362 my $k = pop(@_);
363 $kwargs{ $k } = $v;
364 }
365 if(@_)
366 {
367 my @named_params = @{ $class->python_constructor_arguments };
368 Carp::confess("Paramers mismatch expected ".Dumper(\@named_params).", but got ".Dumper(\@_))
369 if @_ > @named_params;
370 @kwargs{ @named_params[0..@_-1] } = @_;
371 }
372 return $class->$orig(%kwargs);
373 }
374 return $class->$orig(@_);
375 }
376  
377 END {
378 _notify_shutdown();
379 Time::HiRes::sleep(0.01);
380 }
381  
382 *pzeros = \&zeros;
383 *pones = \&ones;
384 *pceil = \&ceil;
385 ## making sure that we can stringify arbitrarily large piddles
386 $PDL::toolongtoprint = 1000_000_000;
387 ## convenience subs
388  
389 sub ascsr
390 {
391 my ($data, $indptr, $indices, $shape) = @_;
392 my @which;
393 my $i = 0;
394 my $j = 0;
395 while($i < $indices->nelem)
396 {
397 for($i = $indptr->at($j); $i < $indptr->at($j+1); $i++)
398 {
399 push @which, [$j, $indices->at($i)];
400 }
401 $j++;
402 }
403 return PDL::CCS::Nd->newFromWhich(
404 pdl(\@which), $data, pdims => blessed $shape ? $shape : pdl($shape)
405 )->xchg(0, 1);
406 }
407  
408 package AI::MXNet::COO::Nd;
409 use Mouse;
410 has ['data', 'row', 'col'] => (is => 'rw');
411 no Mouse;
412  
413 package AI::MXNet::Base;
414  
415 sub tocoo
416 {
417 my $csr = shift;
418 return AI::MXNet::COO::Nd->new(
419 data => $csr->data,
420 row => $csr->_whichND->slice(0)->flat,
421 col => $csr->_whichND->slice(1)->flat
422 );
423 }
424  
425 sub rand_sparse
426 {
427 my ($num_rows, $num_cols, $density, $dtype, $format) = @_;
428 $dtype //= 'float32';
429 $format //= 'csr';
430 my $pdl_type = PDL::Type->new(DTYPE_MX_TO_PDL->{ $dtype });
431 my $dense = random($pdl_type, $num_cols, $num_rows);
432 my $missing = 0;
433 $dense->where(random($num_cols, $num_rows)<=1-$density) .= $missing;
434 if($format eq 'csr')
435 {
436 return $dense->tocsr;
437 }
438 return $dense;
439 }
440  
441 {
442 no warnings 'once';
443 *PDL::CCS::Nd::data = sub { shift->_nzvals };
444 *PDL::CCS::Nd::indptr = sub { my $self = shift; ($self->hasptr ? $self->getptr : $self->ptr)[0] };
445 *PDL::CCS::Nd::indices = sub { shift->_whichND->slice(1)->flat };
446 *PDL::CCS::Nd::tocoo = sub { tocoo(shift) };
447 *PDL::CCS::Nd::shape = sub { shift->pdims };
448 *PDL::CCS::Nd::dtype = sub { DTYPE_MX_TO_STR->{ DTYPE_PDL_TO_MX->{ shift->type->numval } } };
449 *PDL::tocsr = sub { shift->xchg(0, 1)->toccs->xchg(0, 1) };
450 *PDL::rand_sparse = sub { shift; rand_sparse(@_) };
451 }
452  
453 {
454 my $orig_at = PDL->can('at');
455 no warnings 'redefine';
456 *PDL::at = sub {
457 my ($self, @args) = @_;
458 return $orig_at->($self, @args) if @args != 1;
459 return $orig_at->($self, @args) if $self->ndims == 1;
460 return $self->slice(('X')x($self->ndims-1), $args[0])->squeeze;
461 };
462 *PDL::len = sub { shift->dim(-1) };
463 *PDL::dtype = sub { DTYPE_MX_TO_STR->{ DTYPE_PDL_TO_MX->{ shift->type->numval } } };
464 }
465  
466 sub digitize
467 {
468 my ($d, $bins) = @_;
469 for(my $i = 0; $i < @$bins; $i++)
470 {
471 return $i if $d < $bins->[$i];
472 }
473 return scalar(@$bins);
474 }
475  
476 use B;
477 sub hash { hex(B::hash(shift)) }
478 use List::Util ();
479 sub array_index { my ($s, $array) = @_; return List::Util::first { $array->[$_] eq $s } 0..@$array-1 }
480 sub range { my ($begin, $end, $step) = @_; $step //= 1; grep { not (($_-$begin) % $step) } $begin..$end-1 }
481  
482 1;
« MXNet.pm ↑ Summary