| 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::NDArray; | ||
| 19 | |||
| 20 | =head1 NAME | ||
| 21 | |||
| 22 | AI::MXNet::NDArray - Multidimensional tensor object of MXNet. | ||
| 23 | =cut | ||
| 24 | |||
| 25 | =head1 DESCRIPTION | ||
| 26 | |||
| 27 | AI::MXNet::NDArray - Imperative tensor operations on CPU/GPU | ||
| 28 | In AI::MXNet, NDArray is the core data structure for all mathematical computations. | ||
| 29 | An NDArray represents a multidimensional, fixed-size homogenous array. | ||
| 30 | If you're familiar with the PDL, you might notice some similarities. | ||
| 31 | However, NDArray is row-major, unlike the PDL that is column-major. | ||
| 32 | Like the PDL, MXNet's NDArray enables imperative computation. | ||
| 33 | |||
| 34 | Some NDArray advandages compared to PDL: | ||
| 35 | MXNet's NDArray supports fast execution on a wide range of hardware configurations, including CPU, GPU, and multi-GPU machines. | ||
| 36 | MXNet also scales to distributed systems in the cloud. | ||
| 37 | MXNet's NDArray executes code lazily, allowing it to automatically parallelize multiple operations across the available hardware. | ||
| 38 | |||
| 39 | An NDArray is a multidimensional array of numbers with the same type. | ||
| 40 | We could represent the coordinates of a point in 3D space, e.g. [2, 1, 6] as a 1D array with shape (3). | ||
| 41 | Similarly, we could represent a 2D array. | ||
| 42 | Below, we present an array with length 2 along the first axis and length 3 along the second axis. | ||
| 43 | |||
| 44 | [[0, 1, 2] | ||
| 45 | [3, 4, 5]] | ||
| 46 | Note that here the use of 'dimension' is overloaded. When we say a 2D array, we mean an array with 2 axes, not an array with two components. | ||
| 47 | |||
| 48 | Each NDArray supports some important attributes that you'll often want to query: | ||
| 49 | |||
| 50 | $ndarray->shape: The dimensions of the array. | ||
| 51 | It is an array ref of integers indicating the length of the array along each axis. | ||
| 52 | For a matrix with $n rows and $m columns, its shape will be [$n, $m]. | ||
| 53 | $ndarray->dtype: A string describing the type of its elements. | ||
| 54 | Dtype (defined in AI::MXNet::Types) is one of (float32 float64 float16 uint8 int8 int32 int64) | ||
| 55 | $ndarray->size: The total number of components in the array - equal to the product of the components of its shape. | ||
| 56 | $ndarray->context: The device on which this array is stored, represented by an object of AI::MXNet::Context class, e.g. cpu() or gpu(1). | ||
| 57 | |||
| 58 | =cut | ||
| 59 | |||
| 60 | use strict; | ||
| 61 | use warnings; | ||
| 62 | use AI::MXNet::NS; | ||
| 63 | use AI::MXNet::Base; | ||
| 64 | use AI::MXNet::NDArray::Slice; | ||
| 65 | use AI::MXNet::Context; | ||
| 66 | use AI::MXNet::RunTime; | ||
| 67 | use Mouse; | ||
| 68 | use AI::MXNet::Function::Parameters; | ||
| 69 | use overload ( | ||
| 70 | '""' => \&stringify, | ||
| 71 | '+' => \&add, | ||
| 72 | '+=' => \&iadd, | ||
| 73 | '-' => \&subtract, | ||
| 74 | '-=' => \&isubtract, | ||
| 75 | '*' => \&multiply, | ||
| 76 | '*=' => \&imultiply, | ||
| 77 | '/' => \÷, | ||
| 78 | '/=' => \&idivide, | ||
| 79 | '%' => \&modulo, | ||
| 80 | '%=' => \&imodulo, | ||
| 81 | '**' => \&power, | ||
| 82 | '==' => \&equal, | ||
| 83 | '!=' => \¬_equal, | ||
| 84 | '>' => \&greater, | ||
| 85 | '>=' => \&greater_equal, | ||
| 86 | '<' => \&lesser, | ||
| 87 | '<=' => \&lesser_equal, | ||
| 88 | '.=' => \&set, | ||
| 89 | '@{}'=> \&split_array, | ||
| 90 | '=' => sub { $_[0] }, | ||
| 91 | |||
| 92 | 'sqrt' => sub { $_[0]->sqrt() }, | ||
| 93 | 'abs' => sub { $_[0]->abs() }, | ||
| 94 | 'sin' => sub { $_[0]->sin() }, | ||
| 95 | 'cos' => sub { $_[0]->cos() }, | ||
| 96 | 'atan2' => \&atan2, | ||
| 97 | 'log' => sub { $_[0]->log() }, | ||
| 98 | 'exp' => sub { $_[0]->exp() }, | ||
| 99 | ); | ||
| 100 | |||
| 101 | extends 'AI::MXNet::NDArray::Base'; | ||
| 102 | has 'writable' => (is => 'rw', isa => 'Int', default => 1, lazy => 1); | ||
| 103 | has 'handle' => (is => 'rw', isa => 'NDArrayHandle', required => 1); | ||
| 104 | |||
| 105 | sub DEMOLISH | ||
| 106 | { | ||
| 107 | check_call(AI::MXNetCAPI::NDArrayFree(shift->handle)); | ||
| 108 | } | ||
| 109 | |||
| 110 | method STORABLE_freeze($cloning) | ||
| 111 | { | ||
| 112 | my $buf = check_call(AI::MXNetCAPI::NDArraySaveRawBytes($self->handle)); | ||
| 113 | return ($buf,\ $self->writable); | ||
| 114 | } | ||
| 115 | |||
| 116 | method STORABLE_thaw($cloning, $buf, $writable) | ||
| 117 | { | ||
| 118 | my $handle = check_call( | ||
| 119 | AI::MXNetCAPI::NDArrayLoadFromRawBytes( | ||
| 120 | $buf, length($buf) | ||
| 121 | ) | ||
| 122 | ); | ||
| 123 | $self->handle($handle); | ||
| 124 | $self->writable($$writable); | ||
| 125 | } | ||
| 126 | |||
| 127 | method split_array(@args) | ||
| 128 | { | ||
| 129 | my $shape = $self->shape; | ||
| 130 | return [] if $shape->[0] == 0; | ||
| 131 | my $list = $self->split(num_outputs=>$shape->[0], | ||
| 132 | squeeze_axis=>int(@$shape > 1), axis=>0); | ||
| 133 | $shape->[0] == 1 ? [ $list ] : $list; | ||
| 134 | } | ||
| 135 | |||
| 136 | method at(Index @indices) | ||
| 137 | { | ||
| 138 | confess("No idxs supplied") unless @indices; | ||
| 139 | my $shape = $self->shape; | ||
| 140 | my $dsize = @$shape; | ||
| 141 | my $isize = @indices; | ||
| 142 | confess("Dimensions size $dsize < indexes size $isize") | ||
| 143 | if $dsize < $isize; | ||
| 144 | confess("Dimensions size $dsize = indexes size $isize, | ||
| 145 | ndarray only supports either ->at on dimension 0 | ||
| 146 | or full crop") | ||
| 147 | if $isize > 1 and $dsize != $isize; | ||
| 148 | my $i = 0; | ||
| 149 | for(zip(\@indices, $shape)) { | ||
| 150 | my ($idx, $dim_size) = @$_; | ||
| 151 | confess("Dimension $i mismatch Idx: $idx >= Dim Size: $dim_size") | ||
| 152 | if $idx >= $dim_size or ($idx + $dim_size) < 0; | ||
| 153 | ++$i; | ||
| 154 | } | ||
| 155 | $i = 0; | ||
| 156 | for my $v (@indices) | ||
| 157 | { | ||
| 158 | $v += $shape->[$i] if $v < 0; | ||
| 159 | ++$i; | ||
| 160 | } | ||
| 161 | return $self->_at($indices[0]) if @indices == 1; | ||
| 162 | return $self->slice(@indices); | ||
| 163 | } | ||
| 164 | |||
| 165 | method len() { $self->shape->[0] } | ||
| 166 | |||
| 167 | method slice(Slice|AdvancedSlice|InternalSlice @slices) | ||
| 168 | { | ||
| 169 | confess("No slices supplied") unless @slices; | ||
| 170 | if(grep { not ref and /^(?:begin|end|slice)$/ } @slices) | ||
| 171 | { | ||
| 172 | return $self->SUPER::slice(@slices); | ||
| 173 | } | ||
| 174 | if(ref $slices[0] eq 'ARRAY' and ref $slices[0]->[0]) | ||
| 175 | { | ||
| 176 | my @indices; | ||
| 177 | my $key = $slices[0]; | ||
| 178 | my $dtype = 'int32'; | ||
| 179 | for my $idx_i (@{ $key }) | ||
| 180 | { | ||
| 181 | if(not (blessed $idx_i and $idx_i->isa(__PACKAGE__))) | ||
| 182 | { | ||
| 183 | $idx_i = __PACKAGE__->array($idx_i, ctx=>$self->context, dtype=>$dtype); | ||
| 184 | } | ||
| 185 | else | ||
| 186 | { | ||
| 187 | $dtype = $idx_i->dtype; | ||
| 188 | } | ||
| 189 | push @indices, $idx_i; | ||
| 190 | } | ||
| 191 | my $indices = __PACKAGE__->stack(@indices); | ||
| 192 | return __PACKAGE__->gather_nd($self, $indices); | ||
| 193 | } | ||
| 194 | my $shape = $self->shape; | ||
| 195 | my $dsize = @$shape; | ||
| 196 | my $isize = @slices; | ||
| 197 | confess("Dimensions size $dsize < slices size $isize") | ||
| 198 | if $dsize < $isize; | ||
| 199 | confess("Dimensions size $dsize != slices size $isize, | ||
| 200 | ndarray only supports either ->slice on dimension 0 | ||
| 201 | or full crop") | ||
| 202 | if $isize > 1 and $dsize != $isize; | ||
| 203 | my $i = -1; | ||
| 204 | @slices = map { | ||
| 205 | ++$i; | ||
| 206 | ref $_ ? (@$_ == 1 ? [$_->[0], $_->[0]] : $_) : ($_ eq 'X' ? [0, $shape->[$i] - 1] : [$_, $_]); | ||
| 207 | } @slices; | ||
| 208 | for(zip(\@slices, $shape)) { | ||
| 209 | my ($slice, $dim_size) = @$_; | ||
| 210 | my ($begin, $end, $stride) = @$slice; | ||
| 211 | confess("NDArray does not support slice strides != 1") | ||
| 212 | if ($stride//0) > 1; | ||
| 213 | confess("Dimension $i mismatch slice begin : $begin >= Dim Size: $dim_size") | ||
| 214 | if $begin >= $dim_size or ($begin + $dim_size) < 0; | ||
| 215 | confess("Dimension $i mismatch slice end : $end >= Dim Size: $dim_size") | ||
| 216 | if $end >= $dim_size or ($end + $dim_size) < 0; | ||
| 217 | } | ||
| 218 | $i = 0; | ||
| 219 | my ($begin, $end) = ([], []); | ||
| 220 | for my $s (@slices) | ||
| 221 | { | ||
| 222 | $s->[0] += $shape->[$i] if $s->[0] < 0; | ||
| 223 | $s->[1] += $shape->[$i] if $s->[1] < 0; | ||
| 224 | confess("Dimension $i slice mismatch (begin $s->[0] > end $s->[1])") | ||
| 225 | if($s->[0] > $s->[1]); | ||
| 226 | push @$begin, $s->[0]; | ||
| 227 | push @$end, $s->[1] + 1; | ||
| 228 | $i++; | ||
| 229 | } | ||
| 230 | return $self->_slice($begin->[0], $end->[0]) if @slices == 1; | ||
| 231 | return AI::MXNet::NDArray::Slice->new(parent => $self, begin => $begin, end => $end); | ||
| 232 | } | ||
| 233 | |||
| 234 | method set(AcceptableInput $value, $reverse=) | ||
| 235 | { | ||
| 236 | confess("set value must be defined") unless defined $value; | ||
| 237 | confess("Array is not writable") if not $self->writable; | ||
| 238 | ## plain number | ||
| 239 | if(not ref $value) | ||
| 240 | { | ||
| 241 | $self->_set_value($value, out => $self); | ||
| 242 | } | ||
| 243 | # ndarray | ||
| 244 | elsif(blessed($value) and $value->isa(__PACKAGE__)) | ||
| 245 | { | ||
| 246 | $value->copyto($self); | ||
| 247 | } | ||
| 248 | # slice of another ndarray | ||
| 249 | elsif(blessed($value) and $value->isa('AI::MXNet::NDArray::Slice')) | ||
| 250 | { | ||
| 251 | $value->sever->copyto($self); | ||
| 252 | } | ||
| 253 | # perl array, PDL, PDL::Matrix | ||
| 254 | else | ||
| 255 | { | ||
| 256 | $self->_sync_copyfrom($value); | ||
| 257 | } | ||
| 258 | return $self; | ||
| 259 | } | ||
| 260 | |||
| 261 | method asscalar() | ||
| 262 | { | ||
| 263 | confess("ndarray size must be 1") unless $self->size == 1; | ||
| 264 | return $self->aspdl->at(0); | ||
| 265 | ## code below works happily on CPU/segfaults on GPU | ||
| 266 | #$self->wait_to_read; | ||
| 267 | #my $perl_pack_type = DTYPE_MX_TO_PERL->{$self->dtype}; | ||
| 268 | #my $length = {qw/f 4 d 8 S 2 C 1 l 4/}->{$perl_pack_type}; | ||
| 269 | #return | ||
| 270 | #(map { | ||
| 271 | # $perl_pack_type eq 'S' ? AI::MXNetCAPI::_half_to_float($_) : $_ | ||
| 272 | # } unpack("$perl_pack_type", check_call(AI::MXNetCAPI::NDArrayGetData($self->handle, $length))) | ||
| 273 | #)[0]; | ||
| 274 | } | ||
| 275 | |||
| 276 | method _sync_copyfrom(ArrayRef|PDL|PDL::Matrix $source_array) | ||
| 277 | { | ||
| 278 | my $dtype = $self->dtype; | ||
| 279 | my $pdl_type = PDL::Type->new(DTYPE_MX_TO_PDL->{ $dtype }); | ||
| 280 | if(not blessed($source_array)) | ||
| 281 | { | ||
| 282 | $source_array = eval { | ||
| 283 | pdl($pdl_type, $source_array); | ||
| 284 | }; | ||
| 285 | confess($@) if $@; | ||
| 286 | } | ||
| 287 | if($pdl_type->numval != $source_array->type->numval) | ||
| 288 | { | ||
| 289 | my $convert_func = $pdl_type->convertfunc; | ||
| 290 | $source_array = $source_array->$convert_func; | ||
| 291 | } | ||
| 292 | $source_array = pdl($pdl_type, [@{ $source_array->unpdl } ? $source_array->unpdl->[0] : 0 ]) | ||
| 293 | unless @{ $source_array->shape->unpdl }; | ||
| 294 | my $pdl_shape = $source_array->shape->unpdl; | ||
| 295 | my $pdl_shape_str = join(',', ref($source_array) eq 'PDL' ? reverse @{ $pdl_shape } : @{ $pdl_shape }); | ||
| 296 | my $ndary_shape_str = join(',', @{ $self->shape }); | ||
| 297 | if($pdl_shape_str ne $ndary_shape_str) | ||
| 298 | { | ||
| 299 | confess("Shape inconsistant: expected $ndary_shape_str vs got $pdl_shape_str") | ||
| 300 | } | ||
| 301 | my $perl_pack_type = DTYPE_MX_TO_PERL->{$dtype}; | ||
| 302 | my $ptr = $source_array->get_dataref; | ||
| 303 | ## special handling for float16 | ||
| 304 | if($perl_pack_type eq 'S') | ||
| 305 | { | ||
| 306 | $ptr = \( pack("S*", map { AI::MXNetCAPI::_float_to_half($_) } unpack ("f*", $$ptr)) ); | ||
| 307 | } | ||
| 308 | check_call(AI::MXNetCAPI::NDArraySyncCopyFromCPU($self->handle, $$ptr, $self->size)); | ||
| 309 | return $self; | ||
| 310 | } | ||
| 311 | |||
| 312 | =head2 aspdl | ||
| 313 | |||
| 314 | Returns a copied PDL array of current array. | ||
| 315 | |||
| 316 | Returns | ||
| 317 | ------- | ||
| 318 | array : PDL | ||
| 319 | A copy of the array content. | ||
| 320 | =cut | ||
| 321 | |||
| 322 | method aspdl() | ||
| 323 | { | ||
| 324 | my $dtype = $self->dtype; | ||
| 325 | my $pdl_type = PDL::Type->new(DTYPE_MX_TO_PDL->{ $dtype }); | ||
| 326 | my $pdl = PDL->new_from_specification($pdl_type, reverse @{ $self->shape }); | ||
| 327 | my $perl_pack_type = DTYPE_MX_TO_PERL->{$dtype}; | ||
| 328 | my $ptr = $pdl->get_dataref; | ||
| 329 | check_call(AI::MXNetCAPI::NDArraySyncCopyToCPU($self->handle, $$ptr, $self->size)); | ||
| 330 | ## special handling for float16 | ||
| 331 | if($perl_pack_type eq 'S') | ||
| 332 | { | ||
| 333 | $$ptr = pack("f*", map { AI::MXNetCAPI::_half_to_float($_) } unpack("S*", $$ptr)); | ||
| 334 | } | ||
| 335 | $pdl->upd_data; | ||
| 336 | return $pdl; | ||
| 337 | } | ||
| 338 | |||
| 339 | |||
| 340 | =head2 asmpdl | ||
| 341 | |||
| 342 | Returns copied PDL::Matrix objectt of current array. | ||
| 343 | |||
| 344 | Requires caller to "use PDL::Matrix" in user space. | ||
| 345 | |||
| 346 | Returns | ||
| 347 | ------- | ||
| 348 | array : PDL::Matrix | ||
| 349 | A copy of array content. | ||
| 350 | =cut | ||
| 351 | |||
| 352 | method asmpdl() | ||
| 353 | { | ||
| 354 | my $dtype = $self->dtype; | ||
| 355 | my $pdl_type = PDL::Type->new(DTYPE_MX_TO_PDL->{ $dtype }); | ||
| 356 | my $pdl = PDL::Matrix->new_from_specification($pdl_type, @{ $self->shape }); | ||
| 357 | my $perl_pack_type = DTYPE_MX_TO_PERL->{$dtype}; | ||
| 358 | my $ptr = $pdl->get_dataref; | ||
| 359 | check_call(AI::MXNetCAPI::NDArraySyncCopyToCPU($self->handle, $$ptr, $self->size)); | ||
| 360 | ## special handling for float16 | ||
| 361 | if($perl_pack_type eq 'S') | ||
| 362 | { | ||
| 363 | $$ptr = pack("f*", map { AI::MXNetCAPI::_half_to_float($_) } unpack("S*", $$ptr)); | ||
| 364 | } | ||
| 365 | $pdl->upd_data; | ||
| 366 | return $pdl; | ||
| 367 | } | ||
| 368 | |||
| 369 | |||
| 370 | =head2 _slice | ||
| 371 | |||
| 372 | Returns sliced NDArray that shares memory with the current one. | ||
| 373 | |||
| 374 | Parameters | ||
| 375 | ---------- | ||
| 376 | start : int | ||
| 377 | Starting index of slice. | ||
| 378 | stop : int | ||
| 379 | Finishing index of slice. | ||
| 380 | =cut | ||
| 381 | |||
| 382 | method _slice ( | ||
| 383 | Index $start, | ||
| 384 | Index $stop | ||
| 385 | ) | ||
| 386 | { | ||
| 387 | confess("start $start > stop $stop") if $start > $stop; | ||
| 388 | my $sub = AI::MXNet::RunTime->Features()->is_enabled('INT64_TENSOR_SIZE') | ||
| 389 | ? \&AI::MXNetCAPI::NDArraySlice64 | ||
| 390 | : \&AI::MXNetCAPI::NDArraySlice; | ||
| 391 | my $handle = check_call( | ||
| 392 | $sub->( | ||
| 393 | $self->handle, | ||
| 394 | $start, | ||
| 395 | $stop | ||
| 396 | ) | ||
| 397 | ); | ||
| 398 | return __PACKAGE__->_ndarray_cls($handle, $self->writable); | ||
| 399 | } | ||
| 400 | |||
| 401 | =head2 _at | ||
| 402 | |||
| 403 | Returns a sub NDArray that shares memory with current one. | ||
| 404 | |||
| 405 | Parameters | ||
| 406 | ---------- | ||
| 407 | idx : int | ||
| 408 | index of the sub array. | ||
| 409 | =cut | ||
| 410 | |||
| 411 | |||
| 412 | method _at(Index $idx) | ||
| 413 | { | ||
| 414 | my $sub = AI::MXNet::RunTime->Features()->is_enabled('INT64_TENSOR_SIZE') | ||
| 415 | ? \&AI::MXNetCAPI::NDArrayAt64 | ||
| 416 | : \&AI::MXNetCAPI::NDArrayAt; | ||
| 417 | my $handle = check_call( | ||
| 418 | $sub->( | ||
| 419 | $self->handle, $idx >=0 ? $idx : $self->shape->[0] + $idx | ||
| 420 | ) | ||
| 421 | ); | ||
| 422 | return __PACKAGE__->_ndarray_cls($handle, $self->writable); | ||
| 423 | } | ||
| 424 | |||
| 425 | =head2 reshape | ||
| 426 | |||
| 427 | Returns a **view** of this array with a new shape without altering any data. | ||
| 428 | One shape dimension can be -1. In this case, the value is inferred | ||
| 429 | from the length of the array and remaining dimensions. | ||
| 430 | |||
| 431 | Parameters | ||
| 432 | ---------- | ||
| 433 | $new_shape : Shape | ||
| 434 | new shape of NDArray | ||
| 435 | :$reverse : bool, default 0 | ||
| 436 | If true then the special values are inferred from right to left. | ||
| 437 | =cut | ||
| 438 | |||
| 439 | method reshape(ArrayRef[Int] $new_shape, Bool :$reverse=0) | ||
| 440 | { | ||
| 441 | my $handle = check_call( | ||
| 442 | AI::MXNetCAPI::NDArrayReshape64( | ||
| 443 | $self->handle, | ||
| 444 | scalar(@$new_shape), | ||
| 445 | $new_shape, | ||
| 446 | $reverse | ||
| 447 | ) | ||
| 448 | ); | ||
| 449 | return __PACKAGE__->_ndarray_cls($handle, $self->writable); | ||
| 450 | } | ||
| 451 | |||
| 452 | =head2 ndim | ||
| 453 | |||
| 454 | Returns the number of dimensions of this array. | ||
| 455 | =cut | ||
| 456 | |||
| 457 | method ndim() | ||
| 458 | { | ||
| 459 | scalar(@{ $self->shape }); | ||
| 460 | } | ||
| 461 | |||
| 462 | =head2 moveaxis | ||
| 463 | |||
| 464 | Moves the 'source' axis into the 'destination' position | ||
| 465 | while leaving the other axes in their original order | ||
| 466 | |||
| 467 | Parameters | ||
| 468 | ---------- | ||
| 469 | source : int | ||
| 470 | Original position of the axes to move. | ||
| 471 | destination : int | ||
| 472 | Destination position for each of the original axes. | ||
| 473 | |||
| 474 | Returns | ||
| 475 | ------- | ||
| 476 | result :NDArray | ||
| 477 | Array with moved axes. | ||
| 478 | |||
| 479 | Examples | ||
| 480 | -------- | ||
| 481 | > $X = mx->nd->array([[1, 2, 3], | ||
| 482 | [4, 5, 6]]); | ||
| 483 | > print Dumper($X->moveaxis(0, 1)->shape) | ||
| 484 | > [3, 2] | ||
| 485 | =cut | ||
| 486 | |||
| 487 | method moveaxis(Int $source, Int $dest) | ||
| 488 | { | ||
| 489 | my @axes = 0..$self->ndim-1; | ||
| 490 | $source += @axes if $source < 0; | ||
| 491 | $dest += @axes if $dest < 0; | ||
| 492 | assert($source < @axes); | ||
| 493 | assert($dest < @axes); | ||
| 494 | my ($to_move) = splice(@axes, $source, 1); | ||
| 495 | splice(@axes, $dest, 0, $to_move); | ||
| 496 | return __PACKAGE__->transpose($self, \@axes); | ||
| 497 | } | ||
| 498 | |||
| 499 | =head2 broadcast_to | ||
| 500 | |||
| 501 | Broadcasting the current NDArray into the given shape. | ||
| 502 | |||
| 503 | Parameters | ||
| 504 | --------- | ||
| 505 | Shape $shape : the shape to broadcast | ||
| 506 | =cut | ||
| 507 | |||
| 508 | method broadcast_to(Shape $shape) | ||
| 509 | { | ||
| 510 | my $cur_shape = $self->shape; | ||
| 511 | my $err_str = "operands could not be broadcast together with remapped shapes" | ||
| 512 | ."[original->remapped]: [@$cur_shape] and requested shape [@$shape]"; | ||
| 513 | if(@$shape < @$cur_shape) | ||
| 514 | { | ||
| 515 | confess($err_str); | ||
| 516 | } | ||
| 517 | @$cur_shape = ((1)x(@$shape - @$cur_shape), @$cur_shape); | ||
| 518 | my $cur_shape_arr = pdl($cur_shape); | ||
| 519 | my $broadcasting_axes = ($cur_shape_arr != pdl($shape))->which->unpdl; | ||
| 520 | if (grep { $cur_shape->[$_] != 1 } @$broadcasting_axes) | ||
| 521 | { | ||
| 522 | confess($err_str); | ||
| 523 | } | ||
| 524 | if(join(',',@$cur_shape) ne join(',',@{ $self->shape })) | ||
| 525 | { | ||
| 526 | return __PACKAGE__->SUPER::broadcast_to($self->reshape($cur_shape),{ shape => $shape }); | ||
| 527 | } | ||
| 528 | else | ||
| 529 | { | ||
| 530 | return __PACKAGE__->SUPER::broadcast_to($self, { shape => $shape }); | ||
| 531 | } | ||
| 532 | } | ||
| 533 | |||
| 534 | =head2 wait_to_read | ||
| 535 | |||
| 536 | Block until all pending write operations on the NDArray are finished. | ||
| 537 | |||
| 538 | This function will return when all the pending writes to the current | ||
| 539 | NDArray are finished. There can be pending reads going on when the | ||
| 540 | function returns. | ||
| 541 | =cut | ||
| 542 | |||
| 543 | method wait_to_read() | ||
| 544 | { | ||
| 545 | check_call(AI::MXNetCAPI::NDArrayWaitToRead($self->handle)); | ||
| 546 | } | ||
| 547 | |||
| 548 | =head2 shape | ||
| 549 | |||
| 550 | Get the shape of current NDArray. | ||
| 551 | |||
| 552 | Returns | ||
| 553 | ------- | ||
| 554 | an array ref representing the shape of current ndarray | ||
| 555 | =cut | ||
| 556 | |||
| 557 | method shape() | ||
| 558 | { | ||
| 559 | if(AI::MXNet::RunTime->Features()->is_enabled('INT64_TENSOR_SIZE')) | ||
| 560 | { | ||
| 561 | return [map { $_ + 0 } @{ scalar(check_call(AI::MXNetCAPI::NDArrayGetShapeEx64($self->handle))) }]; | ||
| 562 | } | ||
| 563 | else | ||
| 564 | { | ||
| 565 | return scalar(check_call(AI::MXNetCAPI::NDArrayGetShapeEx($self->handle))); | ||
| 566 | } | ||
| 567 | } | ||
| 568 | |||
| 569 | =head2 size | ||
| 570 | |||
| 571 | Number of elements in the array. | ||
| 572 | =cut | ||
| 573 | |||
| 574 | method size(Shape|Undef $shape=) | ||
| 575 | { | ||
| 576 | my $size = 1; | ||
| 577 | map { $size *= $_ } @{ $shape//$self->shape }; | ||
| 578 | return $size; | ||
| 579 | } | ||
| 580 | |||
| 581 | |||
| 582 | =head2 context | ||
| 583 | |||
| 584 | The context of the NDArray. | ||
| 585 | |||
| 586 | Returns | ||
| 587 | ------- | ||
| 588 | $context : AI::MXNet::Context | ||
| 589 | =cut | ||
| 590 | |||
| 591 | method context() | ||
| 592 | { | ||
| 593 | my ($dev_type_id, $dev_id) = check_call( | ||
| 594 | AI::MXNetCAPI::NDArrayGetContext($self->handle) | ||
| 595 | ); | ||
| 596 | return AI::MXNet::Context->new( | ||
| 597 | device_type => AI::MXNet::Context::devtype2str->{ $dev_type_id }, | ||
| 598 | device_id => $dev_id | ||
| 599 | ); | ||
| 600 | } | ||
| 601 | |||
| 602 | =head2 dtype | ||
| 603 | |||
| 604 | The data type of current NDArray. | ||
| 605 | |||
| 606 | Returns | ||
| 607 | ------- | ||
| 608 | a data type string ('float32', 'float64', 'float16', 'uint8', 'int32') | ||
| 609 | representing the data type of the ndarray. | ||
| 610 | 'float32' is the default dtype for the ndarray class. | ||
| 611 | =cut | ||
| 612 | |||
| 613 | method dtype() | ||
| 614 | { | ||
| 615 | my $dtype = check_call( | ||
| 616 | AI::MXNetCAPI::NDArrayGetDType( | ||
| 617 | $self->handle | ||
| 618 | ) | ||
| 619 | ); | ||
| 620 | return DTYPE_MX_TO_STR->{ $dtype }; | ||
| 621 | } | ||
| 622 | |||
| 623 | =head2 copyto | ||
| 624 | |||
| 625 | Copy the content of current array to another entity. | ||
| 626 | |||
| 627 | When another entity is the NDArray, the content is copied over. | ||
| 628 | When another entity is AI::MXNet::Context, a new NDArray in the context | ||
| 629 | will be created. | ||
| 630 | |||
| 631 | Parameters | ||
| 632 | ---------- | ||
| 633 | other : NDArray or Context | ||
| 634 | Target NDArray or context we want to copy data to. | ||
| 635 | |||
| 636 | Returns | ||
| 637 | ------- | ||
| 638 | dst : NDArray | ||
| 639 | =cut | ||
| 640 | |||
| 641 | method copyto(AI::MXNet::Context|AI::MXNet::NDArray $other) | ||
| 642 | { | ||
| 643 | if(blessed($other) and $other->isa('AI::MXNet::Context')) | ||
| 644 | { | ||
| 645 | my $hret = __PACKAGE__->empty( | ||
| 646 | $self->shape, | ||
| 647 | ctx => $other, | ||
| 648 | dtype => $self->dtype | ||
| 649 | ); | ||
| 650 | return __PACKAGE__->_copyto($self, { out => $hret }); | ||
| 651 | } | ||
| 652 | else | ||
| 653 | { | ||
| 654 | if ($other->handle eq $self->handle) | ||
| 655 | { | ||
| 656 | Carp::cluck('copy an array to itself, is it intended?'); | ||
| 657 | } | ||
| 658 | return __PACKAGE__->_copyto($self, { out => $other }); | ||
| 659 | } | ||
| 660 | } | ||
| 661 | |||
| 662 | =head2 copy | ||
| 663 | |||
| 664 | Makes a copy of the current ndarray in the same context | ||
| 665 | |||
| 666 | Returns | ||
| 667 | ------ | ||
| 668 | $copy : NDArray | ||
| 669 | =cut | ||
| 670 | |||
| 671 | method copy() | ||
| 672 | { | ||
| 673 | return $self->copyto($self->context); | ||
| 674 | } | ||
| 675 | |||
| 676 | ## alias for PDL::NiceSlice | ||
| 677 | *sever = \© | ||
| 678 | |||
| 679 | =head2 T | ||
| 680 | |||
| 681 | Get transpose of the NDArray. | ||
| 682 | Works only on 2-D matrices. | ||
| 683 | =cut | ||
| 684 | |||
| 685 | method T() | ||
| 686 | { | ||
| 687 | if (@{$self->shape} > 2) | ||
| 688 | { | ||
| 689 | confess('Only 2D matrix is allowed to be transposed'); | ||
| 690 | } | ||
| 691 | return __PACKAGE__->transpose($self); | ||
| 692 | } | ||
| 693 | |||
| 694 | =head2 astype | ||
| 695 | |||
| 696 | Returns copied ndarray of current array with the specified type. | ||
| 697 | |||
| 698 | Parameters | ||
| 699 | ---------- | ||
| 700 | $dtype : Dtype | ||
| 701 | |||
| 702 | Returns | ||
| 703 | ------- | ||
| 704 | $array : ndarray | ||
| 705 | A copy of the array content. | ||
| 706 | =cut | ||
| 707 | |||
| 708 | method astype(Dtype $dtype) | ||
| 709 | { | ||
| 710 | my $res = __PACKAGE__->empty($self->shape, ctx => $self->context, dtype => $dtype); | ||
| 711 | $self->copyto($res); | ||
| 712 | return $res; | ||
| 713 | } | ||
| 714 | |||
| 715 | =head2 as_in_context | ||
| 716 | |||
| 717 | Returns an NDArray in the target context. | ||
| 718 | If the array is already in that context, self is returned. Otherwise, a copy is | ||
| 719 | made. | ||
| 720 | |||
| 721 | Parameters | ||
| 722 | ---------- | ||
| 723 | context : AI::MXNet::Context | ||
| 724 | The target context we want the return value to live in. | ||
| 725 | |||
| 726 | Returns | ||
| 727 | ------- | ||
| 728 | A copy or self as an NDArray in the target context. | ||
| 729 | =cut | ||
| 730 | |||
| 731 | method as_in_context(AI::MXNet::Context $context) | ||
| 732 | { | ||
| 733 | return $self if $self->context == $context; | ||
| 734 | return $self->copyto($context); | ||
| 735 | } | ||
| 736 | |||
| 737 | =head2 onehot_encode | ||
| 738 | |||
| 739 | One hot encoding indices into matrix out. | ||
| 740 | |||
| 741 | Parameters | ||
| 742 | ---------- | ||
| 743 | indices: NDArray | ||
| 744 | An NDArray containing indices of the categorical features. | ||
| 745 | |||
| 746 | out: NDArray | ||
| 747 | The result of the encoding. | ||
| 748 | |||
| 749 | Returns | ||
| 750 | ------- | ||
| 751 | $out: NDArray | ||
| 752 | =cut | ||
| 753 | |||
| 754 | method onehot_encode(AI::MXNet::NDArray $indices, AI::MXNet::NDArray $out) | ||
| 755 | { | ||
| 756 | return __PACKAGE__->_onehot_encode($indices, $out, { out => $out }); | ||
| 757 | } | ||
| 758 | |||
| 759 | sub _ufunc_helper | ||
| 760 | { | ||
| 761 | my ($lhs, $rhs, $fn_array, $lfn_scalar, $rfn_scalar, $reverse) = @_; | ||
| 762 | ($rhs, $lhs) = ($lhs, $rhs) if $reverse and $rfn_scalar; | ||
| 763 | if(not ref $lhs) | ||
| 764 | { | ||
| 765 | if(not $rfn_scalar) | ||
| 766 | { | ||
| 767 | return __PACKAGE__->can($lfn_scalar)->(__PACKAGE__, $rhs, $lhs); | ||
| 768 | } | ||
| 769 | else | ||
| 770 | { | ||
| 771 | return __PACKAGE__->can($rfn_scalar)->(__PACKAGE__, $rhs, $lhs); | ||
| 772 | } | ||
| 773 | } | ||
| 774 | elsif(not ref $rhs) | ||
| 775 | { | ||
| 776 | return __PACKAGE__->can($lfn_scalar)->(__PACKAGE__, $lhs, $rhs); | ||
| 777 | } | ||
| 778 | else | ||
| 779 | { | ||
| 780 | return __PACKAGE__->can($fn_array)->(__PACKAGE__, $lhs, $rhs); | ||
| 781 | } | ||
| 782 | } | ||
| 783 | |||
| 784 | method stringify($other=, $reverse=) | ||
| 785 | { | ||
| 786 | sprintf("<%s %s @%s>", ref($self), join('x', @{ $self->shape }), $self->context); | ||
| 787 | } | ||
| 788 | |||
| 789 | method atan2($other=, $reverse=) | ||
| 790 | { | ||
| 791 | my $val = $reverse ? $other / $self : $self / $other; | ||
| 792 | return __PACKAGE__->arctan($val); | ||
| 793 | } | ||
| 794 | |||
| 795 | method iadd(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 796 | { | ||
| 797 | confess('trying to add to a readonly NDArray') unless $self->writable; | ||
| 798 | return ref $other | ||
| 799 | ? __PACKAGE__->broadcast_add($self, $other, { out => $self }) | ||
| 800 | : __PACKAGE__->_plus_scalar($self, $other, { out => $self }) | ||
| 801 | } | ||
| 802 | |||
| 803 | method add(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 804 | { | ||
| 805 | return _ufunc_helper( | ||
| 806 | $self, | ||
| 807 | $other, | ||
| 808 | qw/broadcast_add _plus_scalar/ | ||
| 809 | ); | ||
| 810 | } | ||
| 811 | |||
| 812 | |||
| 813 | method subtract(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 814 | { | ||
| 815 | return _ufunc_helper( | ||
| 816 | $self, | ||
| 817 | $other, | ||
| 818 | qw/broadcast_sub _minus_scalar _rminus_scalar/, | ||
| 819 | $reverse | ||
| 820 | ); | ||
| 821 | } | ||
| 822 | |||
| 823 | method isubtract(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 824 | { | ||
| 825 | confess('trying to add to a readonly NDArray') unless $self->writable; | ||
| 826 | return ref $other | ||
| 827 | ? __PACKAGE__->broadcast_sub($self, $other, { out => $self }) | ||
| 828 | : __PACKAGE__->_minus_scalar($self, $other, { out => $self }) | ||
| 829 | } | ||
| 830 | |||
| 831 | method multiply(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 832 | { | ||
| 833 | return _ufunc_helper( | ||
| 834 | $self, | ||
| 835 | $other, | ||
| 836 | qw/broadcast_mul _mul_scalar/ | ||
| 837 | ); | ||
| 838 | } | ||
| 839 | |||
| 840 | method imultiply(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 841 | { | ||
| 842 | confess('trying to add to a readonly NDArray') unless $self->writable; | ||
| 843 | return ref $other | ||
| 844 | ? __PACKAGE__->broadcast_mul($self, $other, { out => $self }) | ||
| 845 | : __PACKAGE__->_mul_scalar($self, $other, { out => $self }) | ||
| 846 | } | ||
| 847 | |||
| 848 | method divide(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 849 | { | ||
| 850 | return _ufunc_helper( | ||
| 851 | $self, | ||
| 852 | $other, | ||
| 853 | qw/broadcast_div _div_scalar _rdiv_scalar/, | ||
| 854 | $reverse | ||
| 855 | ); | ||
| 856 | } | ||
| 857 | |||
| 858 | method idivide(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 859 | { | ||
| 860 | confess('trying to add to a readonly NDArray') unless $self->writable; | ||
| 861 | return ref $other | ||
| 862 | ? __PACKAGE__->broadcast_div($self, $other, { out => $self }) | ||
| 863 | : __PACKAGE__->_div_scalar($self, $other, { out => $self }) | ||
| 864 | } | ||
| 865 | |||
| 866 | method power(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 867 | { | ||
| 868 | return _ufunc_helper( | ||
| 869 | $self, | ||
| 870 | $other, | ||
| 871 | qw/broadcast_power _power_scalar _rpower_scalar/, | ||
| 872 | $reverse | ||
| 873 | ); | ||
| 874 | } | ||
| 875 | |||
| 876 | method maximum(AI::MXNet::NDArray|Num $other) | ||
| 877 | { | ||
| 878 | return _ufunc_helper( | ||
| 879 | $self, | ||
| 880 | $other, | ||
| 881 | qw/broadcast_maximum _maximum_scalar/ | ||
| 882 | ); | ||
| 883 | } | ||
| 884 | |||
| 885 | method minimum(AI::MXNet::NDArray|Num $other) | ||
| 886 | { | ||
| 887 | return _ufunc_helper( | ||
| 888 | $self, | ||
| 889 | $other, | ||
| 890 | qw/broadcast_minimum _minimum_scalar/ | ||
| 891 | ); | ||
| 892 | } | ||
| 893 | |||
| 894 | method equal(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 895 | { | ||
| 896 | return _ufunc_helper( | ||
| 897 | $self, | ||
| 898 | $other, | ||
| 899 | qw/broadcast_equal _equal_scalar/ | ||
| 900 | ); | ||
| 901 | } | ||
| 902 | |||
| 903 | method not_equal(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 904 | { | ||
| 905 | return _ufunc_helper( | ||
| 906 | $self, | ||
| 907 | $other, | ||
| 908 | qw/broadcast_not_equal _not_equal_scalar/ | ||
| 909 | ); | ||
| 910 | } | ||
| 911 | |||
| 912 | method greater(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 913 | { | ||
| 914 | return _ufunc_helper( | ||
| 915 | $self, | ||
| 916 | $other, | ||
| 917 | qw/broadcast_greater _greater_scalar _lesser_scalar/, | ||
| 918 | $reverse | ||
| 919 | ); | ||
| 920 | } | ||
| 921 | |||
| 922 | method greater_equal(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 923 | { | ||
| 924 | return _ufunc_helper( | ||
| 925 | $self, | ||
| 926 | $other, | ||
| 927 | qw/broadcast_greater_equal _greater_equal_scalar _lesser_equal_scalar/, | ||
| 928 | $reverse | ||
| 929 | ); | ||
| 930 | } | ||
| 931 | |||
| 932 | method lesser(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 933 | { | ||
| 934 | return _ufunc_helper( | ||
| 935 | $self, | ||
| 936 | $other, | ||
| 937 | qw/broadcast_lesser _lesser_scalar _greater_scalar/, | ||
| 938 | $reverse | ||
| 939 | ); | ||
| 940 | } | ||
| 941 | |||
| 942 | method lesser_equal(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 943 | { | ||
| 944 | return _ufunc_helper( | ||
| 945 | $self, | ||
| 946 | $other, | ||
| 947 | qw/broadcast_lesser_equal _lesser_equal_scalar _greater_equal_scalar/, | ||
| 948 | $reverse | ||
| 949 | ); | ||
| 950 | } | ||
| 951 | |||
| 952 | method true_divide(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 953 | { | ||
| 954 | return $self->divide($other, $reverse); | ||
| 955 | } | ||
| 956 | |||
| 957 | method modulo(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 958 | { | ||
| 959 | return _ufunc_helper( | ||
| 960 | $self, | ||
| 961 | $other, | ||
| 962 | qw/broadcast_mod _mod_scalar _rmod_scalar/, | ||
| 963 | $reverse | ||
| 964 | ); | ||
| 965 | } | ||
| 966 | |||
| 967 | method imodulo(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 968 | { | ||
| 969 | confess('trying to modulo to a readonly NDArray') unless $self->writable; | ||
| 970 | return ref $other | ||
| 971 | ? __PACKAGE__->broadcast_mod($self, $other, { out => $self }) | ||
| 972 | : __PACKAGE__->_mod_scalar($self, $other, { out => $self }) | ||
| 973 | } | ||
| 974 | |||
| 975 | =head2 empty | ||
| 976 | |||
| 977 | Creates an empty uninitialized NDArray, with the specified shape. | ||
| 978 | |||
| 979 | Parameters | ||
| 980 | ---------- | ||
| 981 | $shape : Shape | ||
| 982 | shape of the NDArray. | ||
| 983 | |||
| 984 | :$ctx : AI::MXNet::Context, optional | ||
| 985 | The context of the NDArray, defaults to current default context. | ||
| 986 | |||
| 987 | :$dtype : Dtype, optional | ||
| 988 | The dtype of the NDArray, defaults to 'float32'. | ||
| 989 | |||
| 990 | :$stype: Stype, optional | ||
| 991 | The stype of the NDArray, defaults to 'default' | ||
| 992 | |||
| 993 | Returns | ||
| 994 | ------- | ||
| 995 | out: Array | ||
| 996 | The created NDArray. | ||
| 997 | =cut | ||
| 998 | |||
| 999 | method empty(Shape $shape, AI::MXNet::Context :$ctx=AI::MXNet::Context->current_ctx, Dtype :$dtype='float32', Stype :$stype='default') | ||
| 1000 | { | ||
| 1001 | if($stype ne 'default') | ||
| 1002 | { | ||
| 1003 | return AI::MXNet::NDArray::Sparse->empty($stype, $shape, ctx => $ctx, dtype => $dtype); | ||
| 1004 | } | ||
| 1005 | return __PACKAGE__->new( | ||
| 1006 | handle => _new_alloc_handle( | ||
| 1007 | $shape, | ||
| 1008 | $ctx, | ||
| 1009 | 0, | ||
| 1010 | DTYPE_STR_TO_MX->{$dtype} | ||
| 1011 | ) | ||
| 1012 | ); | ||
| 1013 | } | ||
| 1014 | |||
| 1015 | =head2 zeros | ||
| 1016 | |||
| 1017 | Creates a new NDArray filled with 0, with specified shape. | ||
| 1018 | |||
| 1019 | Parameters | ||
| 1020 | ---------- | ||
| 1021 | $shape : Shape | ||
| 1022 | shape of the NDArray. | ||
| 1023 | |||
| 1024 | :$ctx : AI::MXNet::Context, optional | ||
| 1025 | The context of the NDArray, defaults to current default context. | ||
| 1026 | |||
| 1027 | :$dtype : Dtype, optional | ||
| 1028 | The dtype of the NDArray, defaults to 'float32'. | ||
| 1029 | |||
| 1030 | :$stype: Stype, optional | ||
| 1031 | The stype of the NDArray, defaults to 'default' | ||
| 1032 | Returns | ||
| 1033 | ------- | ||
| 1034 | out: Array | ||
| 1035 | The created NDArray. | ||
| 1036 | =cut | ||
| 1037 | |||
| 1038 | method zeros( | ||
| 1039 | Shape $shape, | ||
| 1040 | AI::MXNet::Context :$ctx=AI::MXNet::Context->current_ctx, | ||
| 1041 | Dtype :$dtype='float32', | ||
| 1042 | Maybe[AI::MXNet::NDArray] :$out=, | ||
| 1043 | Maybe[Str] :$name=, | ||
| 1044 | Maybe[Str] :$__layout__=, | ||
| 1045 | Stype :$stype='default' | ||
| 1046 | ) | ||
| 1047 | { | ||
| 1048 | if($stype ne 'default') | ||
| 1049 | { | ||
| 1050 | return AI::MXNet::NDArray::Sparse->zeros($stype, $shape, ctx => $ctx, dtype => $dtype, out => $out); | ||
| 1051 | } | ||
| 1052 | return __PACKAGE__->_zeros({ shape => $shape, ctx => "$ctx", dtype => $dtype, ($out ? (out => $out) : ()) }); | ||
| 1053 | } | ||
| 1054 | |||
| 1055 | =head2 ones | ||
| 1056 | |||
| 1057 | Creates a new NDArray filled with 1, with specified shape. | ||
| 1058 | |||
| 1059 | Parameters | ||
| 1060 | ---------- | ||
| 1061 | $shape : Shape | ||
| 1062 | shape of the NDArray. | ||
| 1063 | |||
| 1064 | :$ctx : AI::MXNet::Context, optional | ||
| 1065 | The context of the NDArray, defaults to current default context. | ||
| 1066 | |||
| 1067 | :$dtype : Dtype, optional | ||
| 1068 | The dtype of the NDArray, defaults to 'float32'. | ||
| 1069 | |||
| 1070 | Returns | ||
| 1071 | ------- | ||
| 1072 | out: Array | ||
| 1073 | The created NDArray. | ||
| 1074 | =cut | ||
| 1075 | |||
| 1076 | method ones( | ||
| 1077 | Shape $shape, | ||
| 1078 | AI::MXNet::Context :$ctx=AI::MXNet::Context->current_ctx, | ||
| 1079 | Dtype :$dtype='float32', | ||
| 1080 | Maybe[AI::MXNet::NDArray] :$out=, | ||
| 1081 | Maybe[Str] :$name=, | ||
| 1082 | Maybe[Str] :$__layout__=, | ||
| 1083 | ) | ||
| 1084 | { | ||
| 1085 | return __PACKAGE__->_ones({ shape => $shape, ctx => "$ctx", dtype => $dtype, ($out ? (out => $out) : ()) }); | ||
| 1086 | } | ||
| 1087 | |||
| 1088 | =head2 full | ||
| 1089 | |||
| 1090 | Creates a new NDArray filled with given value, with specified shape. | ||
| 1091 | |||
| 1092 | Parameters | ||
| 1093 | ---------- | ||
| 1094 | $shape : Shape | ||
| 1095 | shape of the NDArray. | ||
| 1096 | |||
| 1097 | val : float or int | ||
| 1098 | The value to be filled with. | ||
| 1099 | |||
| 1100 | :$ctx : AI::MXNet::Context, optional | ||
| 1101 | The context of the NDArray, defaults to current default context. | ||
| 1102 | |||
| 1103 | :$dtype : Dtype, optional | ||
| 1104 | The dtype of the NDArray, defaults to 'float32'. | ||
| 1105 | |||
| 1106 | Returns | ||
| 1107 | ------- | ||
| 1108 | out: Array | ||
| 1109 | The created NDArray. | ||
| 1110 | =cut | ||
| 1111 | |||
| 1112 | method full( | ||
| 1113 | Shape $shape, Num $val, | ||
| 1114 | AI::MXNet::Context :$ctx=AI::MXNet::Context->current_ctx, | ||
| 1115 | Dtype :$dtype='float32', Maybe[AI::MXNet::NDArray] :$out=, | ||
| 1116 | Maybe[Str] :$name=, | ||
| 1117 | Maybe[Str] :$__layout__= | ||
| 1118 | ) | ||
| 1119 | { | ||
| 1120 | return __PACKAGE__->_set_value({ src => $val, out => $out ? $out : __PACKAGE__->empty($shape, ctx => $ctx, dtype => $dtype) }); | ||
| 1121 | } | ||
| 1122 | |||
| 1123 | =head2 array | ||
| 1124 | |||
| 1125 | Creates a new NDArray that is a copy of the source_array. | ||
| 1126 | |||
| 1127 | Parameters | ||
| 1128 | ---------- | ||
| 1129 | $source_array : AI::MXNet::NDArray PDL, PDL::Matrix, Array ref in PDL::pdl format | ||
| 1130 | Source data to create NDArray from. | ||
| 1131 | |||
| 1132 | :$ctx : AI::MXNet::Context, optional | ||
| 1133 | The context of the NDArray, defaults to current default context. | ||
| 1134 | |||
| 1135 | :$dtype : Dtype, optional | ||
| 1136 | The dtype of the NDArray, defaults to 'float32'. | ||
| 1137 | |||
| 1138 | Returns | ||
| 1139 | ------- | ||
| 1140 | out: Array | ||
| 1141 | The created NDArray. | ||
| 1142 | =cut | ||
| 1143 | |||
| 1144 | method array(PDL|PDL::Matrix|PDL::CCS::Nd|ArrayRef|AI::MXNet::NDArray $source_array, AI::MXNet::Context :$ctx=AI::MXNet::Context->current_ctx, Dtype :$dtype='float32') | ||
| 1145 | { | ||
| 1146 | if(blessed $source_array and $source_array->isa('AI::MXNet::NDArray')) | ||
| 1147 | { | ||
| 1148 | return AI::MXNet::NDArray::Sparse->array($source_array, ctx => $ctx, dtype => $dtype) unless $source_array->stype eq 'default'; | ||
| 1149 | my $arr = __PACKAGE__->empty($source_array->shape, ctx => $ctx, dtype => $dtype); | ||
| 1150 | $arr .= $source_array; | ||
| 1151 | return $arr; | ||
| 1152 | } | ||
| 1153 | elsif(blessed $source_array and $source_array->isa('PDL::CCS::Nd')) | ||
| 1154 | { | ||
| 1155 | return AI::MXNet::NDArray::Sparse->array($source_array, ctx => $ctx, dtype => $dtype); | ||
| 1156 | } | ||
| 1157 | my $pdl_type = PDL::Type->new(DTYPE_MX_TO_PDL->{ $dtype }); | ||
| 1158 | if(not blessed($source_array)) | ||
| 1159 | { | ||
| 1160 | $source_array = eval { | ||
| 1161 | pdl($pdl_type, $source_array); | ||
| 1162 | }; | ||
| 1163 | confess($@) if $@; | ||
| 1164 | } | ||
| 1165 | $source_array = pdl($pdl_type, [@{ $source_array->unpdl } ? $source_array->unpdl->[0] : 0 ]) unless @{ $source_array->shape->unpdl }; | ||
| 1166 | my $shape = $source_array->shape->unpdl; | ||
| 1167 | my $arr = __PACKAGE__->empty([ref($source_array) eq 'PDL' ? reverse @{ $shape } : @{ $shape }], ctx => $ctx, dtype => $dtype ); | ||
| 1168 | $arr .= $source_array; | ||
| 1169 | return $arr; | ||
| 1170 | } | ||
| 1171 | |||
| 1172 | |||
| 1173 | =head2 concatenate | ||
| 1174 | |||
| 1175 | Concatenates an array ref of NDArrays along the first dimension. | ||
| 1176 | |||
| 1177 | Parameters | ||
| 1178 | ---------- | ||
| 1179 | $arrays : array ref of NDArrays | ||
| 1180 | Arrays to be concatenate. They must have identical shape except | ||
| 1181 | for the first dimension. They also must have the same data type. | ||
| 1182 | :$axis=0 : int | ||
| 1183 | The axis along which to concatenate. | ||
| 1184 | :$always_copy=1 : bool | ||
| 1185 | Default is 1. When not 1, if the arrays only contain one | ||
| 1186 | NDArray, that element will be returned directly, avoid copying. | ||
| 1187 | |||
| 1188 | Returns | ||
| 1189 | ------- | ||
| 1190 | An NDArray in the same context as $arrays->[0]->context. | ||
| 1191 | =cut | ||
| 1192 | |||
| 1193 | method concatenate(ArrayRef[AI::MXNet::NDArray] $arrays, Index :$axis=0, :$always_copy=1) | ||
| 1194 | { | ||
| 1195 | confess("no arrays provided") unless @$arrays > 0; | ||
| 1196 | if(not $always_copy and @$arrays == 1) | ||
| 1197 | { | ||
| 1198 | return $arrays->[0]; | ||
| 1199 | } | ||
| 1200 | my $shape_axis = $arrays->[0]->shape->[$axis]; | ||
| 1201 | my $shape_rest1 = [@{ $arrays->[0]->shape }[0..($axis-1)]]; | ||
| 1202 | my $shape_rest2 = [@{ $arrays->[0]->shape }[($axis+1)..(@{ $arrays->[0]->shape }-1)]]; | ||
| 1203 | my $dtype = $arrays->[0]->dtype; | ||
| 1204 | my $i = 1; | ||
| 1205 | for my $arr (@{ $arrays }[1..(@{ $arrays }-1)]) | ||
| 1206 | { | ||
| 1207 | $shape_axis += $arr->shape->[$axis]; | ||
| 1208 | my $arr_shape_rest1 = [@{ $arr->shape }[0..($axis-1)]]; | ||
| 1209 | my $arr_shape_rest2 = [@{ $arr->shape }[($axis+1)..(@{ $arr->shape }-1)]]; | ||
| 1210 | confess("first array $arrays->[0] and $i array $arr do not match") | ||
| 1211 | unless join(',',@$arr_shape_rest1) eq join(',',@$shape_rest1); | ||
| 1212 | confess("first array $arrays->[0] and $i array $arr do not match") | ||
| 1213 | unless join(',',@$arr_shape_rest2) eq join(',',@$shape_rest2); | ||
| 1214 | confess("first array $arrays->[0] and $i array $arr dtypes do not match") | ||
| 1215 | unless join(',',@$arr_shape_rest2) eq join(',',@$shape_rest2); | ||
| 1216 | $i++; | ||
| 1217 | } | ||
| 1218 | my $ret_shape = [@$shape_rest1, $shape_axis, @$shape_rest2]; | ||
| 1219 | my $ret = __PACKAGE__->empty($ret_shape, ctx => $arrays->[0]->context, dtype => $dtype); | ||
| 1220 | my $idx = 0; | ||
| 1221 | my $begin = [(0)x@$ret_shape]; | ||
| 1222 | my $end = [@$ret_shape]; | ||
| 1223 | for my $arr (@$arrays) | ||
| 1224 | { | ||
| 1225 | if ($axis == 0) | ||
| 1226 | { | ||
| 1227 | $ret->slice([$idx,($idx+$arr->shape->[0]-1)]) .= $arr; | ||
| 1228 | } | ||
| 1229 | else | ||
| 1230 | { | ||
| 1231 | $begin->[$axis] = $idx; | ||
| 1232 | $end->[$axis] = $idx+$arr->shape->[$axis]; | ||
| 1233 | __PACKAGE__->_crop_assign( | ||
| 1234 | $ret, $arr, | ||
| 1235 | { | ||
| 1236 | out => $ret, | ||
| 1237 | begin => $begin, | ||
| 1238 | end => $end | ||
| 1239 | } | ||
| 1240 | ); | ||
| 1241 | } | ||
| 1242 | $idx += $arr->shape->[$axis]; | ||
| 1243 | } | ||
| 1244 | return $ret | ||
| 1245 | } | ||
| 1246 | |||
| 1247 | =head2 arange | ||
| 1248 | |||
| 1249 | Similar function in the MXNet ndarray as numpy.arange | ||
| 1250 | See Also https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html. | ||
| 1251 | |||
| 1252 | Parameters | ||
| 1253 | ---------- | ||
| 1254 | :$start=0 : number, optional | ||
| 1255 | Start of interval. The interval includes this value. The default start value is 0. | ||
| 1256 | :$stop= : number, optional | ||
| 1257 | End of interval. The interval does not include this value. | ||
| 1258 | :$step=1 : number, optional | ||
| 1259 | Spacing between the values | ||
| 1260 | :$repeat=1 : number, optional | ||
| 1261 | The repeating time of all elements. | ||
| 1262 | E.g repeat=3, the element a will be repeated three times --> a, a, a. | ||
| 1263 | :$infer_range=0 : Bool | ||
| 1264 | When set to 1, infer stop position from start, step, repeat, and | ||
| 1265 | output tensor size. | ||
| 1266 | :$ctx : Context, optional | ||
| 1267 | The context of the NDArray, defaultw to current default context. | ||
| 1268 | :$dtype : data type, optional | ||
| 1269 | The value type of the NDArray, defaults to float32 | ||
| 1270 | |||
| 1271 | Returns | ||
| 1272 | ------- | ||
| 1273 | $out : NDArray | ||
| 1274 | The created NDArray | ||
| 1275 | =cut | ||
| 1276 | |||
| 1277 | method arange(Index :$start=0, Maybe[Index] :$stop=, Index :$step=1, Index :$repeat=1, Bool :$infer_range=0, | ||
| 1278 | AI::MXNet::Context :$ctx=AI::MXNet::Context->current_ctx, Dtype :$dtype='float32') | ||
| 1279 | { | ||
| 1280 | return __PACKAGE__->_arange({ | ||
| 1281 | start => $start, | ||
| 1282 | (defined $stop ? (stop => $stop) : ()), | ||
| 1283 | step => $step, | ||
| 1284 | repeat => $repeat, | ||
| 1285 | dtype => $dtype, | ||
| 1286 | infer_range => $infer_range, | ||
| 1287 | ctx => "$ctx" | ||
| 1288 | }); | ||
| 1289 | } | ||
| 1290 | |||
| 1291 | =head2 load | ||
| 1292 | |||
| 1293 | Loads ndarrays from a binary file. | ||
| 1294 | |||
| 1295 | You can also use Storable to do the job if you only work with Perl. | ||
| 1296 | The advantage of load/save is the file is language agnostic. | ||
| 1297 | This means the file saved using save can be loaded by other language binding of mxnet. | ||
| 1298 | You also get the benefit being able to directly load/save from cloud storage(S3, HDFS) | ||
| 1299 | |||
| 1300 | Parameters | ||
| 1301 | ---------- | ||
| 1302 | fname : str | ||
| 1303 | The name of the file.Can be S3 or HDFS address (remember built with S3 support). | ||
| 1304 | Example of fname: | ||
| 1305 | |||
| 1306 | - `s3://my-bucket/path/my-s3-ndarray` | ||
| 1307 | - `hdfs://my-bucket/path/my-hdfs-ndarray` | ||
| 1308 | - `/path-to/my-local-ndarray` | ||
| 1309 | |||
| 1310 | Returns | ||
| 1311 | ------- | ||
| 1312 | $out : array ref of NDArrays or hash ref with NDArrays | ||
| 1313 | =cut | ||
| 1314 | |||
| 1315 | method load(Str $filename) | ||
| 1316 | { | ||
| 1317 | my ($handles, $names) = check_call(AI::MXNetCAPI::NDArrayLoad($filename)); | ||
| 1318 | if (not @$names) | ||
| 1319 | { | ||
| 1320 | return [map { __PACKAGE__->_ndarray_cls($_) } @$handles]; | ||
| 1321 | } | ||
| 1322 | else | ||
| 1323 | { | ||
| 1324 | my $n = @$names; | ||
| 1325 | my $h = @$handles; | ||
| 1326 | confess("Handles [$h] and names [$n] count mismatch") unless $h == $n; | ||
| 1327 | my %ret; | ||
| 1328 | @ret{ @$names } = map { __PACKAGE__->_ndarray_cls($_) } @$handles; | ||
| 1329 | return \%ret; | ||
| 1330 | } | ||
| 1331 | } | ||
| 1332 | |||
| 1333 | =head2 load_frombuffer | ||
| 1334 | |||
| 1335 | Loads an array dictionary or list from a buffer | ||
| 1336 | |||
| 1337 | See more details in 'save'. | ||
| 1338 | |||
| 1339 | Parameters | ||
| 1340 | ---------- | ||
| 1341 | buf : str | ||
| 1342 | Binary string containing contents of a file. | ||
| 1343 | |||
| 1344 | Returns | ||
| 1345 | ------- | ||
| 1346 | array ref of AI::MXNet::NDArray, AI::MXNet::NDArrayRowSparseNDArray or AI::MXNet::NDArray::CSR, or | ||
| 1347 | hash ref of AI::MXNet::NDArray, AI::MXNet::NDArrayRowSparseNDArray or AI::MXNet::NDArray::CSR | ||
| 1348 | Loaded data. | ||
| 1349 | =cut | ||
| 1350 | |||
| 1351 | method load_frombuffer(Str $buf) | ||
| 1352 | { | ||
| 1353 | my ($handles, $names) = check_call(AI::MXNetCAPI::NDArrayLoadFromBuffer($buf, length($buf))); | ||
| 1354 | if (not @$names) | ||
| 1355 | { | ||
| 1356 | return [map { __PACKAGE__->_ndarray_cls($_) } @$handles]; | ||
| 1357 | } | ||
| 1358 | else | ||
| 1359 | { | ||
| 1360 | my $n = @$names; | ||
| 1361 | my $h = @$handles; | ||
| 1362 | confess("Handles [$h] and names [$n] count mismatch") unless $h == $n; | ||
| 1363 | my %ret; | ||
| 1364 | @ret{ @$names } = map { __PACKAGE__->_ndarray_cls($_) } @$handles; | ||
| 1365 | return \%ret; | ||
| 1366 | } | ||
| 1367 | } | ||
| 1368 | |||
| 1369 | =head2 save | ||
| 1370 | |||
| 1371 | Save array ref of NDArray or hash of str->NDArray to a binary file. | ||
| 1372 | |||
| 1373 | You can also use Storable to do the job if you only work with Perl. | ||
| 1374 | The advantage of load/save is the file is language agnostic. | ||
| 1375 | This means the file saved using save can be loaded by other language binding of mxnet. | ||
| 1376 | You also get the benefit being able to directly load/save from cloud storage(S3, HDFS) | ||
| 1377 | |||
| 1378 | Parameters | ||
| 1379 | ---------- | ||
| 1380 | fname : str | ||
| 1381 | The name of the file.Can be S3 or HDFS address (remember built with S3 support). | ||
| 1382 | Example of fname: | ||
| 1383 | |||
| 1384 | - `s3://my-bucket/path/my-s3-ndarray` | ||
| 1385 | - `hdfs://my-bucket/path/my-hdfs-ndarray` | ||
| 1386 | - `/path-to/my-local-ndarray` | ||
| 1387 | |||
| 1388 | $data : array ref of NDArrays or hash ref of NDArrays | ||
| 1389 | The data to be saved. | ||
| 1390 | =cut | ||
| 1391 | |||
| 1392 | method save(Str $filename, ArrayRef[AI::MXNet::NDArray]|HashRef[AI::MXNet::NDArray] $data) | ||
| 1393 | { | ||
| 1394 | my $handles = []; | ||
| 1395 | my $names = []; | ||
| 1396 | if(ref $data eq 'HASH') | ||
| 1397 | { | ||
| 1398 | for my $name (keys %$data) | ||
| 1399 | { | ||
| 1400 | push @$names, $name; | ||
| 1401 | push @$handles, $data->{ $name }->handle; | ||
| 1402 | } | ||
| 1403 | } | ||
| 1404 | else | ||
| 1405 | { | ||
| 1406 | @$handles = map { $_->handle } @$data; | ||
| 1407 | } | ||
| 1408 | check_call( | ||
| 1409 | AI::MXNetCAPI::NDArraySave( | ||
| 1410 | $filename, | ||
| 1411 | scalar(@$handles), | ||
| 1412 | $handles, | ||
| 1413 | $names | ||
| 1414 | ) | ||
| 1415 | ); | ||
| 1416 | } | ||
| 1417 | |||
| 1418 | =head2 imdecode | ||
| 1419 | |||
| 1420 | Decode an image from string. Requires OpenCV to work. | ||
| 1421 | |||
| 1422 | Parameters | ||
| 1423 | ---------- | ||
| 1424 | $str_img : str | ||
| 1425 | binary image data | ||
| 1426 | :$clip_rect : iterable of 4 int | ||
| 1427 | clip decoded image to rectangle (x0, y0, x1, y1) | ||
| 1428 | :$out= : Maybe[NDArray] | ||
| 1429 | output buffer. can be 3 dimensional (c, h, w) or 4 dimensional (n, c, h, w) | ||
| 1430 | :$index : int | ||
| 1431 | output decoded image to i-th slice of 4 dimensional buffer | ||
| 1432 | :$channels=3 : int | ||
| 1433 | number of channels to output. Decode to grey scale when channels = 1. | ||
| 1434 | $mean= : Maybe[NDArray] | ||
| 1435 | subtract mean from decode image before outputting. | ||
| 1436 | =cut | ||
| 1437 | |||
| 1438 | method imdecode($str_img, ArrayRef[Int] :$clip_rect=[0, 0, 0, 0], | ||
| 1439 | Maybe[AI::MXNet::NDArray] :$out=, Int :$index=0, Int :$channels=3, Maybe[AI::MXNet::NDArray] :$mean=) | ||
| 1440 | { | ||
| 1441 | return __PACKAGE__->_imdecode( | ||
| 1442 | $mean//__PACKAGE__->_new_empty_handle(), | ||
| 1443 | $index, | ||
| 1444 | @$clip_rect, | ||
| 1445 | $channels, | ||
| 1446 | length($str_img), | ||
| 1447 | { str_img => $str_img, ($out ? (out => $out) : ()) } | ||
| 1448 | ); | ||
| 1449 | } | ||
| 1450 | |||
| 1451 | =head2 _new_empty_handle | ||
| 1452 | |||
| 1453 | Returns a new empty handle. | ||
| 1454 | |||
| 1455 | Empty handle can be used to hold result | ||
| 1456 | |||
| 1457 | Returns | ||
| 1458 | ------- | ||
| 1459 | a new empty ndarray handle | ||
| 1460 | =cut | ||
| 1461 | |||
| 1462 | sub _new_empty_handle | ||
| 1463 | { | ||
| 1464 | my $hdl = check_call(AI::MXNetCAPI::NDArrayCreateNone()); | ||
| 1465 | return $hdl; | ||
| 1466 | } | ||
| 1467 | |||
| 1468 | =head2 _new_alloc_handle | ||
| 1469 | |||
| 1470 | Returns a new handle with specified shape and context. | ||
| 1471 | |||
| 1472 | Empty handle is only used to hold results | ||
| 1473 | |||
| 1474 | Returns | ||
| 1475 | ------- | ||
| 1476 | a new empty ndarray handle | ||
| 1477 | =cut | ||
| 1478 | |||
| 1479 | func _new_alloc_handle($shape, $ctx, $delay_alloc, $dtype) | ||
| 1480 | { | ||
| 1481 | my $sub = AI::MXNet::RunTime->Features()->is_enabled('INT64_TENSOR_SIZE') | ||
| 1482 | ? \&AI::MXNetCAPI::NDArrayCreateEx64 | ||
| 1483 | : \&AI::MXNetCAPI::NDArrayCreateEx; | ||
| 1484 | my $hdl = check_call( | ||
| 1485 | $sub->( | ||
| 1486 | $shape, | ||
| 1487 | scalar(@$shape), | ||
| 1488 | $ctx->device_type_id, | ||
| 1489 | $ctx->device_id, | ||
| 1490 | $delay_alloc, | ||
| 1491 | $dtype | ||
| 1492 | ) | ||
| 1493 | ); | ||
| 1494 | return $hdl; | ||
| 1495 | } | ||
| 1496 | |||
| 1497 | method _new_from_shared_mem($shared_pid, $shared_id, $shape, $dtype) | ||
| 1498 | { | ||
| 1499 | my $hdl = check_call( | ||
| 1500 | AI::MXNetCAPI::NDArrayCreateFromSharedMemEx( | ||
| 1501 | $shared_pid, | ||
| 1502 | $shared_id, | ||
| 1503 | $shape, | ||
| 1504 | scalar(@$shape), | ||
| 1505 | DTYPE_STR_TO_MX->{$dtype} | ||
| 1506 | ) | ||
| 1507 | ); | ||
| 1508 | return $hdl; | ||
| 1509 | } | ||
| 1510 | |||
| 1511 | =head2 tostype | ||
| 1512 | |||
| 1513 | Return a copy of the array with chosen storage type. | ||
| 1514 | |||
| 1515 | Returns | ||
| 1516 | ------- | ||
| 1517 | AI::MXNet::NDArray or AI::MXNet::NDArray::CSR or AI::MXNet::NDArray::RowSparse | ||
| 1518 | A copy of the array with the chosen storage stype | ||
| 1519 | =cut | ||
| 1520 | |||
| 1521 | method tostype(Stype $stype) | ||
| 1522 | { | ||
| 1523 | return $self->cast_storage(stype => $stype); | ||
| 1524 | } | ||
| 1525 | |||
| 1526 | |||
| 1527 | =head2 waitall | ||
| 1528 | |||
| 1529 | Wait for all async operations to finish in MXNet. | ||
| 1530 | This function is used for benchmarks only. | ||
| 1531 | =cut | ||
| 1532 | |||
| 1533 | method waitall() | ||
| 1534 | { | ||
| 1535 | check_call(AI::MXNetCAPI::NDArrayWaitAll()); | ||
| 1536 | } | ||
| 1537 | |||
| 1538 | =head2 _fresh_grad | ||
| 1539 | |||
| 1540 | Parameters: | ||
| 1541 | ---------- | ||
| 1542 | Maybe[Bool] $state= | ||
| 1543 | |||
| 1544 | Whether this array's corresponding gradient array | ||
| 1545 | (registered via `autograd->mark_variables`) has been | ||
| 1546 | updated by `autograd->backward` since last reset. | ||
| 1547 | |||
| 1548 | `_fresh_grad` need to be manually set to False | ||
| 1549 | after consuming gradient (usually after updating this | ||
| 1550 | array). | ||
| 1551 | =cut | ||
| 1552 | |||
| 1553 | method _fresh_grad(Maybe[Bool] $state=) | ||
| 1554 | { | ||
| 1555 | if(defined $state) | ||
| 1556 | { | ||
| 1557 | check_call(AI::MXNetCAPI::NDArraySetGradState($self->handle, $state)); | ||
| 1558 | return $state; | ||
| 1559 | } | ||
| 1560 | else | ||
| 1561 | { | ||
| 1562 | return scalar(check_call(AI::MXNetCAPI::NDArrayGetGradState($self->handle))); | ||
| 1563 | } | ||
| 1564 | } | ||
| 1565 | |||
| 1566 | =head2 detach | ||
| 1567 | |||
| 1568 | Returns a new NDArray, detached from the current graph. | ||
| 1569 | =cut | ||
| 1570 | |||
| 1571 | method detach() | ||
| 1572 | { | ||
| 1573 | my $handle = check_call(AI::MXNetCAPI::NDArrayDetach($self->handle)); | ||
| 1574 | return __PACKAGE__->_ndarray_cls($handle); | ||
| 1575 | } | ||
| 1576 | |||
| 1577 | =head2 attach_grad | ||
| 1578 | |||
| 1579 | Attach a gradient buffer to this NDArray, so that `backward` | ||
| 1580 | can compute gradient with respect to it. | ||
| 1581 | |||
| 1582 | Parameters | ||
| 1583 | ---------- | ||
| 1584 | GradReq :$grad_req='write' : {'write', 'add', 'null'} | ||
| 1585 | How gradient will be accumulated. | ||
| 1586 | - 'write': gradient will be overwritten on every backward. | ||
| 1587 | - 'add': gradient will be added to existing value on every backward. | ||
| 1588 | - 'null': do not compute gradient for this NDArray. | ||
| 1589 | Maybe[Str] :$stype= : str, optional | ||
| 1590 | The storage type of the gradient array. Defaults to the same stype of this NDArray. | ||
| 1591 | =cut | ||
| 1592 | |||
| 1593 | method attach_grad(GradReq :$grad_req='write', Maybe[Str] :$stype=) | ||
| 1594 | { | ||
| 1595 | my $grad; | ||
| 1596 | if(defined $stype) | ||
| 1597 | { | ||
| 1598 | $grad = __PACKAGE__->zeros($self->shape, stype => $stype); | ||
| 1599 | } | ||
| 1600 | else | ||
| 1601 | { | ||
| 1602 | $grad = $self->zeros_like; | ||
| 1603 | } | ||
| 1604 | $grad_req = GRAD_REQ_MAP->{$grad_req}; | ||
| 1605 | check_call( | ||
| 1606 | AI::MXNetCAPI::AutogradMarkVariables( | ||
| 1607 | 1, | ||
| 1608 | [$self->handle], | ||
| 1609 | [$grad_req], | ||
| 1610 | [$grad->handle] | ||
| 1611 | ) | ||
| 1612 | ); | ||
| 1613 | } | ||
| 1614 | |||
| 1615 | =head2 grad | ||
| 1616 | |||
| 1617 | Returns gradient buffer attached to this NDArray. | ||
| 1618 | =cut | ||
| 1619 | |||
| 1620 | method grad() | ||
| 1621 | { | ||
| 1622 | my $handle = check_call(AI::MXNetCAPI::NDArrayGetGrad($self->handle)); | ||
| 1623 | return undef unless defined $handle; | ||
| 1624 | return __PACKAGE__->_ndarray_cls($handle); | ||
| 1625 | } | ||
| 1626 | |||
| 1627 | =head2 backward | ||
| 1628 | |||
| 1629 | Compute the gradients of this NDArray w.r.t variables. | ||
| 1630 | |||
| 1631 | Parameters | ||
| 1632 | ---------- | ||
| 1633 | :$out_grad= : NDArray, optional | ||
| 1634 | Gradient with respect to head. | ||
| 1635 | :$retain_graph=0 : bool, optional | ||
| 1636 | Whether to retain the computaion graph for another backward | ||
| 1637 | pass on the same graph. By default the computaion history | ||
| 1638 | is cleared. | ||
| 1639 | :$train_mode=1 : bool, optional | ||
| 1640 | Whether to compute gradient for training or inference. | ||
| 1641 | =cut | ||
| 1642 | |||
| 1643 | method backward(Maybe[AI::MXNet::NDArray] :$out_grad=, Bool :$retain_graph=0, Bool :$train_mode=1) | ||
| 1644 | { | ||
| 1645 | check_call( | ||
| 1646 | AI::MXNetCAPI::AutogradBackwardEx( | ||
| 1647 | 1, | ||
| 1648 | [$self->handle], | ||
| 1649 | [defined $out_grad ? $out_grad->handle : undef], | ||
| 1650 | 0, | ||
| 1651 | [], | ||
| 1652 | $retain_graph, | ||
| 1653 | 0, | ||
| 1654 | $train_mode | ||
| 1655 | ) | ||
| 1656 | ) | ||
| 1657 | } | ||
| 1658 | |||
| 1659 | method CachedOp(@args) { AI::MXNet::CachedOp->new(@args) } | ||
| 1660 | |||
| 1661 | method histogram(@args) { __PACKAGE__->_histogram(@args%2 ? ('data', @args) : @args) } | ||
| 1662 | |||
| 1663 | my $lvalue_methods = join "\n", map {"use attributes 'AI::MXNet::NDArray', \\&AI::MXNet::NDArray::$_, 'lvalue';"} | ||
| 1664 | qw/at slice aspdl asmpdl reshape copy sever T astype as_in_context copyto empty zero ones full | ||
| 1665 | array/; | ||
| 1666 | eval << "EOV" if ($^V and $^V >= 5.006007); | ||
| 1667 | { | ||
| 1668 | no warnings qw(misc); | ||
| 1669 | $lvalue_methods | ||
| 1670 | } | ||
| 1671 | EOV | ||
| 1672 | |||
| 1673 | sub contrib { 'AI::MXNet::Contrib::NDArray' } | ||
| 1674 | sub random { 'AI::MXNet::Random' } | ||
| 1675 | sub sparse { 'AI::MXNet::NDArray::Sparse' } | ||
| 1676 | sub linalg { 'AI::MXNet::LinAlg::NDArray' } | ||
| 1677 | sub image { 'AI::MXNet::Image::NDArray' } | ||
| 1678 | |||
| 1679 | __PACKAGE__->meta->make_immutable; |