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