| 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::Sparse; | ||
| 19 | use strict; | ||
| 20 | use warnings; | ||
| 21 | use AI::MXNet::Base; | ||
| 22 | use AI::MXNet::Function::Parameters; | ||
| 23 | use AI::MXNet::RunTime; | ||
| 24 | use Mouse; | ||
| 25 | extends 'AI::MXNet::NDArray'; | ||
| 26 | |||
| 27 | =head1 NAME | ||
| 28 | |||
| 29 | AI::MXNet::NDArray::Sparse - Sparse NDArray API of MXNet | ||
| 30 | =cut | ||
| 31 | |||
| 32 | =head1 DESCRIPTION | ||
| 33 | |||
| 34 | The base class of an NDArray stored in a sparse storage format. | ||
| 35 | See AI::MXNet::NDArray::CSR and AI::MXNet::NDArray::RowSparse for more details. | ||
| 36 | =cut | ||
| 37 | |||
| 38 | method _new_alloc_handle( | ||
| 39 | Stype $stype, | ||
| 40 | Shape $shape, | ||
| 41 | AI::MXNet::Context $ctx, | ||
| 42 | Bool $delay_alloc, | ||
| 43 | Dtype $dtype, | ||
| 44 | AuxTypes $aux_types, | ||
| 45 | Maybe[ArrayRef[Shape]] $aux_shapes= | ||
| 46 | ) | ||
| 47 | { | ||
| 48 | confess("only int64 is supported for aux types") | ||
| 49 | if (grep { $_ ne 'int64' } @$aux_types); | ||
| 50 | my $aux_type_ids = [map { DTYPE_STR_TO_MX->{$_} } @$aux_types]; | ||
| 51 | $aux_shapes //= [map { [0] } @$aux_types]; | ||
| 52 | my $aux_shape_lens = [map { scalar(@$_) } @$aux_shapes]; | ||
| 53 | @$aux_shapes = map { @$_ } @$aux_shapes; | ||
| 54 | my $num_aux = @{ $aux_types }; | ||
| 55 | my $sub = AI::MXNet::RunTime->Features()->is_enabled('INT64_TENSOR_SIZE') | ||
| 56 | ? \&AI::MXNetCAPI::NDArrayCreateSparseEx64 | ||
| 57 | : \&AI::MXNetCAPI::NDArrayCreateSparseEx; | ||
| 58 | my $handle = check_call( | ||
| 59 | $sub->( | ||
| 60 | STORAGE_TYPE_STR_TO_ID->{$stype}, | ||
| 61 | $shape, | ||
| 62 | scalar(@$shape), | ||
| 63 | $ctx->device_type_id, | ||
| 64 | $ctx->device_id, | ||
| 65 | $delay_alloc, | ||
| 66 | DTYPE_STR_TO_MX->{$dtype}, | ||
| 67 | scalar(@$aux_types), | ||
| 68 | $aux_type_ids, | ||
| 69 | $aux_shape_lens, | ||
| 70 | $aux_shapes | ||
| 71 | ) | ||
| 72 | ); | ||
| 73 | } | ||
| 74 | |||
| 75 | method _class_name() | ||
| 76 | { | ||
| 77 | my $class = ref $self || $self; | ||
| 78 | $class; | ||
| 79 | } | ||
| 80 | |||
| 81 | sub not_implemented { confess "Not implemented" } | ||
| 82 | use overload '""' => sub { | ||
| 83 | my $self = shift; | ||
| 84 | my $shape_info = join('x', @{ $self->shape }); | ||
| 85 | sprintf("\n<%s, %s @%s>", $self->_class_name, $shape_info, $self->context); | ||
| 86 | }, | ||
| 87 | '+' => \&add, | ||
| 88 | '-' => \&subtract, | ||
| 89 | '*' => \&multiply, | ||
| 90 | '/' => \÷, | ||
| 91 | '+=' => \¬_implemented, | ||
| 92 | '-=' => \¬_implemented, | ||
| 93 | '*=' => \¬_implemented, | ||
| 94 | '/=' => \¬_implemented; | ||
| 95 | |||
| 96 | method add(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 97 | { | ||
| 98 | if(blessed $other and join(',', @{ $self->shape }) eq join(',', @{ $other->shape })) | ||
| 99 | { | ||
| 100 | return AI::MXNet::NDArray::_ufunc_helper( | ||
| 101 | $self, | ||
| 102 | $other, | ||
| 103 | qw/elemwise_add _plus_scalar/ | ||
| 104 | ); | ||
| 105 | } | ||
| 106 | else | ||
| 107 | { | ||
| 108 | return AI::MXNet::NDArray::_ufunc_helper( | ||
| 109 | $self, | ||
| 110 | $other, | ||
| 111 | qw/broadcast_add _plus_scalar/ | ||
| 112 | ); | ||
| 113 | } | ||
| 114 | } | ||
| 115 | |||
| 116 | |||
| 117 | method subtract(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 118 | { | ||
| 119 | if(blessed $other and join(',', @{ $self->shape }) eq join(',', @{ $other->shape })) | ||
| 120 | { | ||
| 121 | return AI::MXNet::NDArray::_ufunc_helper( | ||
| 122 | $self, | ||
| 123 | $other, | ||
| 124 | qw/elemwise_sub _minus_scalar _rminus_scalar/, | ||
| 125 | $reverse | ||
| 126 | ); | ||
| 127 | } | ||
| 128 | else | ||
| 129 | { | ||
| 130 | return AI::MXNet::NDArray::_ufunc_helper( | ||
| 131 | $self, | ||
| 132 | $other, | ||
| 133 | qw/broadcast_sub _minus_scalar _rminus_scalar/, | ||
| 134 | $reverse | ||
| 135 | ); | ||
| 136 | } | ||
| 137 | } | ||
| 138 | |||
| 139 | method multiply(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 140 | { | ||
| 141 | if(blessed $other and join(',', @{ $self->shape }) eq join(',', @{ $other->shape })) | ||
| 142 | { | ||
| 143 | return AI::MXNet::NDArray::_ufunc_helper( | ||
| 144 | $self, | ||
| 145 | $other, | ||
| 146 | qw/elemwise_mul _mul_scalar/, | ||
| 147 | ); | ||
| 148 | } | ||
| 149 | else | ||
| 150 | { | ||
| 151 | return AI::MXNet::NDArray::_ufunc_helper( | ||
| 152 | $self, | ||
| 153 | $other, | ||
| 154 | qw/broadcast_mul _mul_scalar/, | ||
| 155 | ); | ||
| 156 | } | ||
| 157 | } | ||
| 158 | |||
| 159 | method divide(AI::MXNet::NDArray|Num $other, $reverse=) | ||
| 160 | { | ||
| 161 | if(blessed $other and join(',', @{ $self->shape }) eq join(',', @{ $other->shape })) | ||
| 162 | { | ||
| 163 | return AI::MXNet::NDArray::_ufunc_helper( | ||
| 164 | $self, | ||
| 165 | $other, | ||
| 166 | qw/elemwise_div _div_scalar _rdiv_scalar/, | ||
| 167 | $reverse | ||
| 168 | ); | ||
| 169 | } | ||
| 170 | else | ||
| 171 | { | ||
| 172 | return AI::MXNet::NDArray::_ufunc_helper( | ||
| 173 | $self, | ||
| 174 | $other, | ||
| 175 | qw/broadcast_div _div_scalar _rdiv_scalar/, | ||
| 176 | $reverse | ||
| 177 | ); | ||
| 178 | } | ||
| 179 | } | ||
| 180 | |||
| 181 | { | ||
| 182 | no warnings 'redefine'; | ||
| 183 | *_sync_copyfrom = *_at = *_slice = *reshape = *size = \¬_implemented; | ||
| 184 | } | ||
| 185 | |||
| 186 | method _aux_type(Int $i) | ||
| 187 | { | ||
| 188 | return DTYPE_MX_TO_STR->{ | ||
| 189 | check_call( | ||
| 190 | AI::MXNetCAPI::NDArrayGetAuxType( | ||
| 191 | $self->handle, $i | ||
| 192 | ) | ||
| 193 | ) | ||
| 194 | } | ||
| 195 | } | ||
| 196 | |||
| 197 | method _num_aux() | ||
| 198 | { | ||
| 199 | return scalar(@{ STORAGE_AUX_TYPES->{ $self->stype } }); | ||
| 200 | } | ||
| 201 | |||
| 202 | method _aux_types() | ||
| 203 | { | ||
| 204 | [map { $self->_aux_type($_) } 0..$self->_num_aux-1]; | ||
| 205 | } | ||
| 206 | |||
| 207 | =head2 aspdl | ||
| 208 | |||
| 209 | Return a dense PDL object with value copied from this array | ||
| 210 | =cut | ||
| 211 | |||
| 212 | method aspdl() | ||
| 213 | { | ||
| 214 | return $self->tostype('default')->aspdl; | ||
| 215 | } | ||
| 216 | |||
| 217 | =head2 astype | ||
| 218 | |||
| 219 | Returns a copy of the array after casting to a specified type. | ||
| 220 | Parameters | ||
| 221 | ---------- | ||
| 222 | dtype : Dtype | ||
| 223 | The type of the returned array. | ||
| 224 | Examples | ||
| 225 | -------- | ||
| 226 | >>> $x = mx->nd->sparse->zeros('row_sparse', [2,3], dtype=>'float32') | ||
| 227 | >>> $y = $x->astype('int32') | ||
| 228 | >>> $y->dtype | ||
| 229 | <type 'int32'> | ||
| 230 | =cut | ||
| 231 | |||
| 232 | method astype(Dtype $dtype) | ||
| 233 | { | ||
| 234 | my $res = $self->zeros( | ||
| 235 | $self->stype, $self->shape, ctx => $self->context, | ||
| 236 | dtype => $dtype | ||
| 237 | ); | ||
| 238 | $self->copyto($res); | ||
| 239 | return $res; | ||
| 240 | } | ||
| 241 | |||
| 242 | =head2 copyto | ||
| 243 | |||
| 244 | Copies the value of this array to another array. | ||
| 245 | |||
| 246 | Parameters | ||
| 247 | ---------- | ||
| 248 | other : NDArray or NDArray::CSR or NDArray::RowSparse or Context | ||
| 249 | The destination array or context. | ||
| 250 | |||
| 251 | Returns | ||
| 252 | ------- | ||
| 253 | NDArray or CSRNDArray::CSR or NDArray::RowSparse | ||
| 254 | The copied array. | ||
| 255 | =cut | ||
| 256 | |||
| 257 | method copyto(AI::MXNet::NDArray|AI::MXNet::Context $other) | ||
| 258 | { | ||
| 259 | if($other->isa('AI::MXNet::NDArray')) | ||
| 260 | { | ||
| 261 | if($self->handle eq $other->handle) | ||
| 262 | { | ||
| 263 | Carp::cluck('You are attempting to copy an array to itself'); | ||
| 264 | return; | ||
| 265 | } | ||
| 266 | else | ||
| 267 | { | ||
| 268 | return __PACKAGE__->_copyto($self, out => $other); | ||
| 269 | } | ||
| 270 | } | ||
| 271 | elsif($other->isa('AI::MXNet::Context')) | ||
| 272 | { | ||
| 273 | my $hret = __PACKAGE__->_ndarray_cls( | ||
| 274 | __PACKAGE__->_new_alloc_handle( | ||
| 275 | $self->stype, $self->shape, $other, 1, $self->dtype, $self->_aux_types | ||
| 276 | ) | ||
| 277 | ); | ||
| 278 | return __PACKAGE__->_copyto($self, out=>$hret) | ||
| 279 | } | ||
| 280 | } | ||
| 281 | |||
| 282 | =head2 check_format | ||
| 283 | |||
| 284 | Check whether the NDArray format is valid. | ||
| 285 | |||
| 286 | Parameters | ||
| 287 | ---------- | ||
| 288 | full_check : bool, optional | ||
| 289 | If `True`, rigorous check, O(N) operations. Otherwise | ||
| 290 | basic check, O(1) operations (default True). | ||
| 291 | =cut | ||
| 292 | |||
| 293 | method check_format(Bool $full_check=1) | ||
| 294 | { | ||
| 295 | scalar(check_call(AI::MXNetCAPI::NDArraySyncCheckFormat($self->handle, $full_check))); | ||
| 296 | } | ||
| 297 | |||
| 298 | =head2 _data | ||
| 299 | |||
| 300 | A deep copy NDArray of the data array associated with the BaseSparseNDArray. | ||
| 301 | |||
| 302 | This function blocks. Do not use it in performance critical code. | ||
| 303 | =cut | ||
| 304 | |||
| 305 | method _data() | ||
| 306 | { | ||
| 307 | $self->wait_to_read; | ||
| 308 | my $handle = check_call(AI::MXNetCAPI::NDArrayGetDataNDArray($self->handle)); | ||
| 309 | return AI::MXNet::NDArray->new(handle => $handle); | ||
| 310 | } | ||
| 311 | |||
| 312 | =head2 _aux_data | ||
| 313 | |||
| 314 | Get a deep copy NDArray of the i-th aux data array associated with the | ||
| 315 | AI::MXNet::NDArray::Sparse | ||
| 316 | |||
| 317 | This function blocks. Do not use it in performance critical code. | ||
| 318 | =cut | ||
| 319 | |||
| 320 | method _aux_data(Int $i) | ||
| 321 | { | ||
| 322 | $self->wait_to_read; | ||
| 323 | my $handle = check_call(AI::MXNetCAPI::NDArrayGetAuxNDArray($self->handle, $i)); | ||
| 324 | return AI::MXNet::NDArray->new(handle => $handle); | ||
| 325 | } | ||
| 326 | |||
| 327 | package AI::MXNet::NDArray::CSR; | ||
| 328 | use AI::MXNet::Base; | ||
| 329 | use Mouse; | ||
| 330 | extends 'AI::MXNet::NDArray::Sparse'; | ||
| 331 | |||
| 332 | =head1 NAME | ||
| 333 | |||
| 334 | AI::MXNet::NDArray::CSR - A sparse representation of 2D NDArray in the Compressed Sparse Row format. | ||
| 335 | =cut | ||
| 336 | |||
| 337 | =head1 DESCRIPTION | ||
| 338 | |||
| 339 | A AI::MXNet::NDArray::CSR represents an AI::MXNet::NDArray as three separate arrays: `data`, | ||
| 340 | `indptr` and `indices`. It uses the CSR representation where the column indices for | ||
| 341 | row i are stored in ``indices[indptr[i]:indptr[i+1]]`` and their corresponding values are stored | ||
| 342 | in ``data[indptr[i]:indptr[i+1]]``. | ||
| 343 | |||
| 344 | The column indices for a given row are expected to be sorted in ascending order. | ||
| 345 | Duplicate column entries for the same row are not allowed. | ||
| 346 | |||
| 347 | Example | ||
| 348 | ------- | ||
| 349 | >>> $a = mx->nd->array([[0, 1, 0], [2, 0, 0], [0, 0, 0], [0, 0, 3]]); | ||
| 350 | >>> $a = $a->tostype('csr'); | ||
| 351 | >>> $a->data->aspdl; | ||
| 352 | [ 1 2 3] | ||
| 353 | >>> $a->indices->aspdl | ||
| 354 | [1 0 2] | ||
| 355 | >>> $a->indptr->aspdl | ||
| 356 | [0 1 2 2 3] | ||
| 357 | |||
| 358 | See Also | ||
| 359 | -------- | ||
| 360 | csr_matrix: Several ways to construct a CSRNDArray | ||
| 361 | =cut | ||
| 362 | |||
| 363 | use overload '+=' => sub { ($_[0] + $_[1])->copyto($_[0]) }, | ||
| 364 | '-=' => sub { ($_[0] - $_[1])->copyto($_[0]) }, | ||
| 365 | '*=' => sub { ($_[0] * $_[1])->copyto($_[0]) }, | ||
| 366 | '/=' => sub { ($_[0] / $_[1])->copyto($_[0]) }; | ||
| 367 | |||
| 368 | =head2 slice | ||
| 369 | |||
| 370 | Returns a newly created array based on the indexing key. | ||
| 371 | |||
| 372 | Parameters | ||
| 373 | ---------- | ||
| 374 | key : int or array ref | ||
| 375 | Indexing key. | ||
| 376 | |||
| 377 | Examples | ||
| 378 | -------- | ||
| 379 | >>> $indptr = [0, 2, 3, 6]; | ||
| 380 | >>> $indices = [0, 2, 2, 0, 1, 2]; | ||
| 381 | >>> $data = [1, 2, 3, 4, 5, 6]; | ||
| 382 | >>> $a = mx->nd->sparse->csr_matrix([$data, $indices, $indptr], shape=>[3, 3]) | ||
| 383 | >>> $a->aspdl | ||
| 384 | [[ 1 0 2] | ||
| 385 | [ 0 0 3] | ||
| 386 | [ 4 5 6]] | ||
| 387 | >>> $a->slice([1,2])->aspdl | ||
| 388 | [[ 0 0 3]] | ||
| 389 | >>> $a->slice(1)->aspdl | ||
| 390 | [[ 0 0 3]] | ||
| 391 | >>> $a->[-1]->aspdl | ||
| 392 | [[ 4 5 6]] | ||
| 393 | =cut | ||
| 394 | |||
| 395 | method slice(Slice|InternalSlice @slices) | ||
| 396 | { | ||
| 397 | if(grep { /^begin|end|slice$/ } @slices) | ||
| 398 | { | ||
| 399 | return $self->SUPER::slice(@slices); | ||
| 400 | } | ||
| 401 | my $slice = $slices[0]; | ||
| 402 | my ($begin, $end); | ||
| 403 | if(not ref $slice) | ||
| 404 | { | ||
| 405 | if($slice < 0) | ||
| 406 | { | ||
| 407 | $begin = $self->shape->[0] + $slice; | ||
| 408 | } | ||
| 409 | else | ||
| 410 | { | ||
| 411 | $begin = $slice; | ||
| 412 | } | ||
| 413 | $end = $begin; | ||
| 414 | } | ||
| 415 | else | ||
| 416 | { | ||
| 417 | ($begin, $end) = @{ $slice }; | ||
| 418 | $end //= $self->shape->[0] - 1; | ||
| 419 | if($begin < 0) | ||
| 420 | { | ||
| 421 | $begin += $self->shape->[0]; | ||
| 422 | } | ||
| 423 | if($end < 0) | ||
| 424 | { | ||
| 425 | $end += $self->shape->[0]; | ||
| 426 | } | ||
| 427 | } | ||
| 428 | return $self->SUPER::slice(begin => $begin, end => $end + 1); | ||
| 429 | } | ||
| 430 | |||
| 431 | |||
| 432 | =head2 set | ||
| 433 | |||
| 434 | Set self to value. Also usable as overloaded .= | ||
| 435 | |||
| 436 | Parameters | ||
| 437 | ---------- | ||
| 438 | value : AI::MXNet::NDArray or AI::MXNet::NDArray::CSR | ||
| 439 | or PDL/PDL::CCS::Nd/perl array ref in PDL constructor format | ||
| 440 | The value to set. | ||
| 441 | |||
| 442 | Examples | ||
| 443 | -------- | ||
| 444 | >>> $src = mx->nd->sparse->zeros('csr', [3,3]) | ||
| 445 | >>> $src->aspdl | ||
| 446 | [[ 0 0 0] | ||
| 447 | [ 0 0 0] | ||
| 448 | [ 0 0 0]] | ||
| 449 | >>> # AI::MXNet::NDArray::CSR with same storage type | ||
| 450 | >>> $x = mx->nd->ones('row_sparse', [3,3])->tostype('csr') | ||
| 451 | >>> $x .= $src | ||
| 452 | >>> $x->aspdl | ||
| 453 | [[ 1 1 1] | ||
| 454 | [ 1 1 1] | ||
| 455 | [ 1 1 1]] | ||
| 456 | >>> # assign NDArray to AI::MXNet::NDArray::CSR | ||
| 457 | >>> $x .= mx->nd->ones([3,3]) * 2 | ||
| 458 | >>> $x->aspdl | ||
| 459 | [[ 2 2 2] | ||
| 460 | [ 2 2 2] | ||
| 461 | [ 2 2 2]] | ||
| 462 | =cut | ||
| 463 | |||
| 464 | method set(AcceptableInput $other, $reverse=) | ||
| 465 | { | ||
| 466 | confess('Failed to assign to a readonly CSR') unless $self->writable; | ||
| 467 | if($other->isa('AI::MXNet::NDArray')) | ||
| 468 | { | ||
| 469 | if($self->handle ne $other->handle) | ||
| 470 | { | ||
| 471 | $other->copyto($self); | ||
| 472 | } | ||
| 473 | } | ||
| 474 | else | ||
| 475 | { | ||
| 476 | my $tmp = __PACKAGE__->array($other, ((not ref $other) ? ( pdl => $self->aspdl) : ())); | ||
| 477 | $tmp->copyto($self); | ||
| 478 | } | ||
| 479 | } | ||
| 480 | |||
| 481 | use overload '.=' => \&set; | ||
| 482 | |||
| 483 | =head2 indices | ||
| 484 | |||
| 485 | A deep copy NDArray of the indices array of the AI::MXNet::NDArray::CSR. | ||
| 486 | This generates a deep copy of the column indices of the current `csr` matrix. | ||
| 487 | |||
| 488 | Returns | ||
| 489 | ------- | ||
| 490 | NDArray | ||
| 491 | This AI::MXNet::NDArray::CSR indices array. | ||
| 492 | =cut | ||
| 493 | |||
| 494 | method indices() | ||
| 495 | { | ||
| 496 | return $self->_aux_data(1); | ||
| 497 | } | ||
| 498 | |||
| 499 | =head2 indptr | ||
| 500 | |||
| 501 | A deep copy NDArray of the inptr array of the AI::MXNet::NDArray::CSR. | ||
| 502 | This generates a deep copy of the indptr of the current `csr` matrix. | ||
| 503 | |||
| 504 | Returns | ||
| 505 | ------- | ||
| 506 | NDArray | ||
| 507 | This AI::MXNet::NDArray::CSR indptr array. | ||
| 508 | =cut | ||
| 509 | |||
| 510 | method indptr() | ||
| 511 | { | ||
| 512 | return $self->_aux_data(0); | ||
| 513 | } | ||
| 514 | |||
| 515 | =head2 data | ||
| 516 | |||
| 517 | A deep copy NDArray of the data array of the AI::MXNet::NDArray::CSR. | ||
| 518 | This generates a deep copy of the data of the current `csr` matrix. | ||
| 519 | |||
| 520 | Returns | ||
| 521 | ------- | ||
| 522 | NDArray | ||
| 523 | This AI::MXNet::NDArray::CSR data array. | ||
| 524 | =cut | ||
| 525 | |||
| 526 | method data() | ||
| 527 | { | ||
| 528 | return $self->_data; | ||
| 529 | } | ||
| 530 | |||
| 531 | =head2 tostype | ||
| 532 | |||
| 533 | Return a copy of the array with chosen storage type. | ||
| 534 | |||
| 535 | Returns | ||
| 536 | ------- | ||
| 537 | NDArray or AI::MXNet::NDArray::CSR | ||
| 538 | A copy of the array with the chosen storage stype | ||
| 539 | =cut | ||
| 540 | |||
| 541 | method tostype(Stype $stype) | ||
| 542 | { | ||
| 543 | if($stype eq 'row_sparse') | ||
| 544 | { | ||
| 545 | confess("cast_storage from csr to row_sparse is not supported"); | ||
| 546 | } | ||
| 547 | return $self->cast_storage(stype => $stype); | ||
| 548 | } | ||
| 549 | |||
| 550 | =head2 copyto | ||
| 551 | |||
| 552 | Copies the value of this array to another array. | ||
| 553 | |||
| 554 | If $other is a AI::MXNet::NDArray or AI::MXNet::NDArray::CSR object, then $other->shape and | ||
| 555 | $self->shape should be the same. This function copies the value from | ||
| 556 | $self to $other. | ||
| 557 | |||
| 558 | If $other is a context, a new AI::MXNet::NDArray::CSR will be first created on | ||
| 559 | the target context, and the value of $self is copied. | ||
| 560 | |||
| 561 | Parameters | ||
| 562 | ---------- | ||
| 563 | $other : AI::MXNet::NDArray or AI::MXNet::NDArray::CSR or AI::MXNet::Context | ||
| 564 | The destination array or context. | ||
| 565 | |||
| 566 | Returns | ||
| 567 | ------- | ||
| 568 | AI::MXNet::NDArray or AI::MXNet::NDArray::CSR | ||
| 569 | =cut | ||
| 570 | |||
| 571 | method copyto(AI::MXNet::Context|AI::MXNet::NDArray $other) | ||
| 572 | { | ||
| 573 | if($other->isa('AI::MXNet::Context')) | ||
| 574 | { | ||
| 575 | return $self->SUPER::copyto($other); | ||
| 576 | } | ||
| 577 | else | ||
| 578 | { | ||
| 579 | my $stype = $other->stype; | ||
| 580 | if($stype eq 'default' or $stype eq 'csr') | ||
| 581 | { | ||
| 582 | return return $self->SUPER::copyto($other); | ||
| 583 | } | ||
| 584 | else | ||
| 585 | { | ||
| 586 | confess("copyto does not support destination NDArray stype $stype"); | ||
| 587 | } | ||
| 588 | } | ||
| 589 | } | ||
| 590 | |||
| 591 | =head2 | ||
| 592 | |||
| 593 | Returns a PDL::CCS::Nd object with value copied from this array | ||
| 594 | =cut | ||
| 595 | |||
| 596 | method aspdlccs() | ||
| 597 | { | ||
| 598 | return ascsr($self->data->aspdl, $self->indptr->aspdl, $self->indices->aspdl, $self->shape); | ||
| 599 | } | ||
| 600 | |||
| 601 | package AI::MXNet::NDArray::RowSparse; | ||
| 602 | use Mouse; | ||
| 603 | extends 'AI::MXNet::NDArray::Sparse'; | ||
| 604 | |||
| 605 | =head1 NAME | ||
| 606 | |||
| 607 | AI::MXNet::NDArray::RowSparse - A sparse representation of a set of NDArray row slices at given indices. | ||
| 608 | =cut | ||
| 609 | |||
| 610 | =head1 DESCRIPTION | ||
| 611 | |||
| 612 | A AI::MXNet::NDArray::RowSparse represents a multidimensional NDArray using two separate arrays: `data` and | ||
| 613 | `indices`. The number of dimensions has to be at least 2. | ||
| 614 | |||
| 615 | - data: an NDArray of any dtype with shape [D0, D1, ..., Dn]. | ||
| 616 | - indices: a 1-D int64 NDArray with shape [D0] with values sorted in ascending order. | ||
| 617 | |||
| 618 | The `indices` stores the indices of the row slices with non-zeros, | ||
| 619 | while the values are stored in `data`. The corresponding NDArray ``dense`` | ||
| 620 | represented by AI::MXNet::NDArray::RowSparse ``rsp`` has | ||
| 621 | |||
| 622 | ``dense[rsp.indices[i], :, :, :, ...] = rsp.data[i, :, :, :, ...]`` | ||
| 623 | |||
| 624 | >>> $dense->aspdl | ||
| 625 | [[ 1 2 3 ] | ||
| 626 | [ 0 0 0 ] | ||
| 627 | [ 4 0 5 ] | ||
| 628 | [ 0 0 0 ] | ||
| 629 | [ 0 0 0 ]] | ||
| 630 | >>> $rsp = $dense->tostype('row_sparse'); | ||
| 631 | >>> $rsp->indices->aspdl | ||
| 632 | [ 0 2 ] | ||
| 633 | >>> $rsp->data->aspdl | ||
| 634 | [[ 1 2 3 ] | ||
| 635 | [ 4 0 5 ]] | ||
| 636 | |||
| 637 | A AI::MXNet::NDArray::RowSparse is typically used to represent non-zero row slices of a large NDArray | ||
| 638 | of shape [LARGE0, D1, .. , Dn] where LARGE0 >> D0 and most row slices are zeros. | ||
| 639 | |||
| 640 | AI::MXNet::NDArray::RowSparse is used principally in the definition of gradients for operations | ||
| 641 | that have sparse gradients (e.g. sparse dot and sparse embedding). | ||
| 642 | |||
| 643 | See Also | ||
| 644 | -------- | ||
| 645 | row_sparse_array: Several ways to construct a AI::MXNet::NDArray::RowSparse | ||
| 646 | =cut | ||
| 647 | |||
| 648 | use overload '+=' => sub { ($_[0] + $_[1])->copyto($_[0]) }, | ||
| 649 | '-=' => sub { ($_[0] - $_[1])->copyto($_[0]) }, | ||
| 650 | '*=' => sub { ($_[0] * $_[1])->copyto($_[0]) }, | ||
| 651 | '/=' => sub { ($_[0] / $_[1])->copyto($_[0]) }; | ||
| 652 | |||
| 653 | method slice(@args) { confess("not implemented") } | ||
| 654 | |||
| 655 | =head2 set | ||
| 656 | |||
| 657 | Set self to value. Also usable as overloaded .= | ||
| 658 | |||
| 659 | Parameters | ||
| 660 | ---------- | ||
| 661 | value : AI::MXNet::NDArray or AI::MXNet::NDArray::CSR | ||
| 662 | or PDL/PDL::CCS::Nd/perl array ref in PDL constructor format | ||
| 663 | The value to set. | ||
| 664 | |||
| 665 | Examples | ||
| 666 | -------- | ||
| 667 | >>> $src = mx->nd->sparse->zeros('raw_sparse', [3,3]) | ||
| 668 | >>> $src->aspdl | ||
| 669 | [[ 0 0 0] | ||
| 670 | [ 0 0 0] | ||
| 671 | [ 0 0 0]] | ||
| 672 | >>> # AI::MXNet::NDArray::RowSparse with same storage type | ||
| 673 | >>> $x = mx->nd->ones('row_sparse', [3,3]) | ||
| 674 | >>> $src .= $x | ||
| 675 | >>> $src->aspdl | ||
| 676 | [[ 1 1 1] | ||
| 677 | [ 1 1 1] | ||
| 678 | [ 1 1 1]] | ||
| 679 | >>> # assign NDArray to AI::MXNet::NDArray::RowSparse | ||
| 680 | >>> $x .= mx->nd->ones([3,3]) * 2 | ||
| 681 | >>> $x->aspdl | ||
| 682 | [[ 2 2 2] | ||
| 683 | [ 2 2 2] | ||
| 684 | [ 2 2 2]] | ||
| 685 | =cut | ||
| 686 | |||
| 687 | method set(AcceptableInput $other, $reverse=) | ||
| 688 | { | ||
| 689 | confess('Failed to assign to a readonly RowSparse') unless $self->writable; | ||
| 690 | if($other->isa('AI::MXNet::NDArray')) | ||
| 691 | { | ||
| 692 | if($self->handle ne $other->handle) | ||
| 693 | { | ||
| 694 | $other->copyto($self); | ||
| 695 | } | ||
| 696 | } | ||
| 697 | else | ||
| 698 | { | ||
| 699 | my $tmp = __PACKAGE__->array($other, ((not ref $other) ? ( pdl => $self->aspdl) : ())); | ||
| 700 | $tmp->copyto($self); | ||
| 701 | } | ||
| 702 | } | ||
| 703 | |||
| 704 | use overload '.=' => \&set; | ||
| 705 | |||
| 706 | =head2 data | ||
| 707 | |||
| 708 | A deep copy NDArray of the data array of the AI::MXNet::NDArray::RowSparse. | ||
| 709 | This generates a deep copy of the data of the current `row_sparse` matrix. | ||
| 710 | |||
| 711 | Returns | ||
| 712 | ------- | ||
| 713 | NDArray | ||
| 714 | This AI::MXNet::NDArray::RowSparse data array. | ||
| 715 | =cut | ||
| 716 | |||
| 717 | method data() | ||
| 718 | { | ||
| 719 | return $self->_data; | ||
| 720 | } | ||
| 721 | |||
| 722 | =head2 indices | ||
| 723 | |||
| 724 | A deep copy NDArray of the indices array of the AI::MXNet::NDArray::RowSparse. | ||
| 725 | This generates a deep copy of the column indices of the current `row_sparse` matrix. | ||
| 726 | |||
| 727 | Returns | ||
| 728 | ------- | ||
| 729 | NDArray | ||
| 730 | This AI::MXNet::NDArray::RowSparse indices array. | ||
| 731 | =cut | ||
| 732 | |||
| 733 | method indices() | ||
| 734 | { | ||
| 735 | return $self->_aux_data(0); | ||
| 736 | } | ||
| 737 | |||
| 738 | =head2 data | ||
| 739 | |||
| 740 | A deep copy NDArray of the data array of the AI::MXNet::NDArray::RowSparse. | ||
| 741 | This generates a deep copy of the data of the current `row_sparse` matrix. | ||
| 742 | |||
| 743 | Returns | ||
| 744 | ------- | ||
| 745 | NDArray | ||
| 746 | This AI::MXNet::NDArray::RowSparse data array. | ||
| 747 | =cut | ||
| 748 | |||
| 749 | =head2 tostype | ||
| 750 | |||
| 751 | Return a copy of the array with chosen storage type. | ||
| 752 | |||
| 753 | Returns | ||
| 754 | ------- | ||
| 755 | NDArray or RowSparseNDArray | ||
| 756 | A copy of the array with the chosen storage stype | ||
| 757 | =cut | ||
| 758 | |||
| 759 | method tostype(Stype $stype) | ||
| 760 | { | ||
| 761 | if($stype eq 'csr') | ||
| 762 | { | ||
| 763 | confess("cast_storage from row_sparse to csr is not supported"); | ||
| 764 | } | ||
| 765 | return $self->cast_storage(stype => $stype); | ||
| 766 | } | ||
| 767 | |||
| 768 | |||
| 769 | =head2 copyto | ||
| 770 | |||
| 771 | Copies the value of this array to another array. | ||
| 772 | |||
| 773 | If $other is a AI::MXNet::NDArray or AI::MXNet::NDArray::RawSparse object, then $other->shape and | ||
| 774 | $self->shape should be the same. This function copies the value from | ||
| 775 | $self to $other. | ||
| 776 | |||
| 777 | If $other is a context, a new AI::MXNet::NDArray::RawSparse will be first created on | ||
| 778 | the target context, and the value of $self is copied. | ||
| 779 | |||
| 780 | Parameters | ||
| 781 | ---------- | ||
| 782 | $other : AI::MXNet::NDArray or AI::MXNet::NDArray::RawSparse or AI::MXNet::Context | ||
| 783 | The destination array or context. | ||
| 784 | |||
| 785 | Returns | ||
| 786 | ------- | ||
| 787 | AI::MXNet::NDArray or AI::MXNet::NDArray::RawSparse | ||
| 788 | =cut | ||
| 789 | |||
| 790 | method copyto(AI::MXNet::Context|AI::MXNet::NDArray $other) | ||
| 791 | { | ||
| 792 | if($other->isa('AI::MXNet::Context')) | ||
| 793 | { | ||
| 794 | return $self->SUPER::copyto($other); | ||
| 795 | } | ||
| 796 | else | ||
| 797 | { | ||
| 798 | my $stype = $other->stype; | ||
| 799 | if($stype eq 'default' or $stype eq 'row_sparse') | ||
| 800 | { | ||
| 801 | return return $self->SUPER::copyto($other); | ||
| 802 | } | ||
| 803 | else | ||
| 804 | { | ||
| 805 | confess("copyto does not support destination NDArray stype $stype"); | ||
| 806 | } | ||
| 807 | } | ||
| 808 | } | ||
| 809 | |||
| 810 | package AI::MXNet::NDArray::Sparse; | ||
| 811 | |||
| 812 | # Prepare `source_array` so that it can be used to construct NDArray. | ||
| 813 | # `source_array` is converted to a `pdl` if it's neither an `NDArray` | ||
| 814 | # nor a `pdl`. | ||
| 815 | |||
| 816 | method _prepare_src_array($source_array, Dtype $dtype) | ||
| 817 | { | ||
| 818 | my $pdl_type = PDL::Type->new(DTYPE_MX_TO_PDL->{ $dtype }); | ||
| 819 | if(not blessed($source_array)) | ||
| 820 | { | ||
| 821 | $source_array = eval { | ||
| 822 | pdl($pdl_type, $source_array); | ||
| 823 | }; | ||
| 824 | confess($@) if $@; | ||
| 825 | } | ||
| 826 | elsif($source_array->isa('AI::MXNet::NDArray')) | ||
| 827 | { | ||
| 828 | return $source_array; | ||
| 829 | } | ||
| 830 | $source_array = pdl($pdl_type, [@{ $source_array->unpdl } ? $source_array->unpdl->[0] : 0 ]) unless @{ $source_array->shape->unpdl }; | ||
| 831 | return $source_array; | ||
| 832 | } | ||
| 833 | |||
| 834 | |||
| 835 | # Prepare the value of dtype if `dtype` is undef. If `src_array` is an NDArray, PDL | ||
| 836 | # or PDL::CCS::Ne, return src_array->dtype. float32 is returned otherwise. | ||
| 837 | |||
| 838 | method _prepare_default_dtype($src_array, $dtype) | ||
| 839 | { | ||
| 840 | if(not defined $dtype) | ||
| 841 | { | ||
| 842 | if(blessed $src_array) | ||
| 843 | { | ||
| 844 | $dtype = $src_array->dtype; | ||
| 845 | } | ||
| 846 | else | ||
| 847 | { | ||
| 848 | $dtype = 'float32'; | ||
| 849 | } | ||
| 850 | } | ||
| 851 | return $dtype; | ||
| 852 | } | ||
| 853 | |||
| 854 | use Data::Dumper; | ||
| 855 | method _check_shape($s1, $s2) | ||
| 856 | { | ||
| 857 | my ($ps1, $ps2) = map { (blessed($_) and $_->isa('AI::MXNet:NDArray')) ? pdl($_->shape) : blessed($_) ? $_ : pdl($_) } ($s1, $s2); | ||
| 858 | return 1 unless defined $s2; | ||
| 859 | ($ps1 == $ps2)->all | ||
| 860 | or | ||
| 861 | confess("Shape mismatch detected. " . Dumper(blessed ($s1) ? $s1->undpl : $s1 ) . " v.s. " . Dumper(blessed ($s2) ? $s2 : $s2)); | ||
| 862 | } | ||
| 863 | |||
| 864 | method coo_matrix(@args) | ||
| 865 | { | ||
| 866 | my ($data, $row, $col, $shape) = map { blessed $_ ? $_ : pdl($_) } @args; | ||
| 867 | my @which; | ||
| 868 | my $i = 0; | ||
| 869 | my $j = 0; | ||
| 870 | for (my $i = 0; $i < $row->nelem; $i++) | ||
| 871 | { | ||
| 872 | push @which, [$row->at($i), $col->at($i)]; | ||
| 873 | } | ||
| 874 | return PDL::CCS::Nd->newFromWhich( | ||
| 875 | pdl(\@which), $data, pdims => $shape | ||
| 876 | )->xchg(0, 1); | ||
| 877 | } | ||
| 878 | |||
| 879 | =head2 csr_matrix | ||
| 880 | |||
| 881 | Creates a AI::MXNet::NDArray::CSR, an 2D array with compressed sparse row (CSR) format. | ||
| 882 | |||
| 883 | The AI::MXNet::NDArray::CSR can be instantiated in several ways: | ||
| 884 | |||
| 885 | - csr_matrix($arg1, Maybe[AI::MXNet::Context] :$ctx=, Maybe[Shape] :$shape, Maybe [Dtype] :$dtype=) | ||
| 886 | $ctx, $shape, $dtype are optional | ||
| 887 | $arg1 can be given in following variants | ||
| 888 | |||
| 889 | - to construct a AI::MXNet::NDArray::CSR with a dense 2D array $arg1 | ||
| 890 | - $arg1 is in AI::MXNet::NDArray::array input format | ||
| 891 | |||
| 892 | - to construct a AI::MXNet::NDArray::CSR with a sparse 2D array $arg1 | ||
| 893 | $arg1 is AI::MXNet::NDArray::CSR or PDL::CCS::Nd - A sparse matrix. | ||
| 894 | PDL::CCS::Nd is expected to be converted internally into CSR format | ||
| 895 | AI::MXNet injects 'tocsr' method into PDL and PDL::CCS::Nd modules for this purpose. | ||
| 896 | |||
| 897 | - to construct an empty AI::MXNet::NDArray::CSR with shape $arg1 = [$M, $N] | ||
| 898 | - $M - Number of rows in the matrix | ||
| 899 | - $N - Number of columns in the matrix | ||
| 900 | |||
| 901 | - to construct a AI::MXNet::NDArray::CSR based on the definition of compressed sparse row format | ||
| 902 | using three separate arrays, | ||
| 903 | where the column indices for row i are stored in ``indices[indptr[i]:indptr[i+1]]`` | ||
| 904 | and their corresponding values are stored in ``data[indptr[i]:indptr[i+1]]``. | ||
| 905 | The column indices for a given row are expected to be **sorted in ascending order.** | ||
| 906 | Duplicate column entries for the same row are not allowed. | ||
| 907 | In this case $arg1 = [$data, $indices, $indptr] | ||
| 908 | $data, $indices, $indptr must be given in the AI::MXNet::NDArray::array input format | ||
| 909 | - $data - holds all the non-zero entries of the matrix in row-major order. | ||
| 910 | - $indices - stores the column index for each non-zero element in $data. | ||
| 911 | stores the column index for each non-zero element in $data. | ||
| 912 | - $indptr - stores the offset into $data of the first non-zero element number of each | ||
| 913 | row of the matrix. | ||
| 914 | |||
| 915 | to construct a AI::MXNet::NDArray::CSR based on the COOrdinate format | ||
| 916 | using three seperate arrays, | ||
| 917 | where ``row[i]`` is the row index of the element, | ||
| 918 | ``col[i]`` is the column index of the element | ||
| 919 | and ``data[i]`` is the data corresponding to the element. All the missing | ||
| 920 | elements in the input are taken to be zeroes. | ||
| 921 | In this case $arg1 = [$data, [$row, $col]] | ||
| 922 | $data, $row, $col must be given in the AI::MXNet::NDArray::array input format | ||
| 923 | $data - holds all the non-zero entries of the matrix in COO format. | ||
| 924 | $row - stores the row index for each non zero element in $data. | ||
| 925 | - **col** (*array_like*) - An object exposing the array interface, which | ||
| 926 | $col - stores the col index for each non zero element in $data. | ||
| 927 | |||
| 928 | Returns | ||
| 929 | ------- | ||
| 930 | AI::MXNet::NDArray::CSR | ||
| 931 | A AI::MXNet::NDArray::CSR with the 'csr' storage representation. | ||
| 932 | |||
| 933 | Example | ||
| 934 | ------- | ||
| 935 | >>> $a = mx->nd->sparse->csr_matrix([[1, 2, 3], [1, 0, 2], [0, 1, 2, 2, 3]], shape => [4, 3]) | ||
| 936 | >>> $a->aspdl | ||
| 937 | [[ 0 1 0] | ||
| 938 | [ 2 0 0] | ||
| 939 | [ 0 0 0] | ||
| 940 | [ 0 0 3]] | ||
| 941 | |||
| 942 | See Also | ||
| 943 | -------- | ||
| 944 | CSRNDArray : MXNet NDArray in compressed sparse row format. | ||
| 945 | =cut | ||
| 946 | method csr_matrix( | ||
| 947 | $arg1, | ||
| 948 | Maybe[Shape|PDL] :$shape=, | ||
| 949 | Maybe[AI::MXNet::Context] :$ctx=AI::MXNet::Context->current_ctx, | ||
| 950 | Maybe[Dtype] :$dtype= | ||
| 951 | ) | ||
| 952 | { | ||
| 953 | if(not defined $arg1) | ||
| 954 | { | ||
| 955 | return __PACKAGE__->empty('csr', $shape, ctx => $ctx, (defined $dtype ? (dtype => $dtype) : ())); | ||
| 956 | } | ||
| 957 | # construct a csr matrix from (M, N) or (data, indices, indptr) | ||
| 958 | if(ref $arg1 eq 'ARRAY') | ||
| 959 | { | ||
| 960 | my $arg_len = @{ $arg1 }; | ||
| 961 | if($arg_len == 2) | ||
| 962 | { | ||
| 963 | # construct a sparse csr matrix from | ||
| 964 | # scipy coo matrix if input format is coo | ||
| 965 | if(ref $arg1->[1] eq 'ARRAY' and @{ $arg1->[1] } == 2) | ||
| 966 | { | ||
| 967 | my $coo = __PACKAGE__->coo_matrix($arg1->[0], @{ $arg1->[1] }, $shape); | ||
| 968 | __PACKAGE__->_check_shape($coo->shape, $shape); | ||
| 969 | return __PACKAGE__->array($coo, ctx => $ctx, dtype => $dtype); | ||
| 970 | } | ||
| 971 | else | ||
| 972 | { | ||
| 973 | # empty matrix with shape | ||
| 974 | __PACKAGE__->_check_shape($arg1, $shape); | ||
| 975 | return __PACKAGE__->empty('csr', $arg1, ctx=>$ctx, dtype=>$dtype); | ||
| 976 | } | ||
| 977 | } | ||
| 978 | elsif($arg_len == 3) | ||
| 979 | { | ||
| 980 | # data, indices, indptr | ||
| 981 | return __PACKAGE__->_csr_matrix_from_definition( | ||
| 982 | @{ $arg1 }, shape => $shape, | ||
| 983 | ctx => $ctx, dtype => $dtype | ||
| 984 | ); | ||
| 985 | } | ||
| 986 | else | ||
| 987 | { | ||
| 988 | confess("Unexpected length of input array: " . Dumper($arg1)); | ||
| 989 | } | ||
| 990 | } | ||
| 991 | else | ||
| 992 | { | ||
| 993 | # construct a csr matrix from a sparse / dense one | ||
| 994 | if(blessed $arg1 and ($arg1->isa('AI::MXNet::NDArray::CSR') or $arg1->isa('PDL::CCS::Nd'))) | ||
| 995 | { | ||
| 996 | # construct a csr matrix from scipy or CSRNDArray | ||
| 997 | __PACKAGE__->_check_shape($arg1->shape, $shape); | ||
| 998 | return __PACKAGE__->array($arg1, ctx => $ctx, dtype => $dtype); | ||
| 999 | } | ||
| 1000 | elsif(blessed $arg1 and $arg1->isa('AI::MXNet::NDArray::RowSparse')) | ||
| 1001 | { | ||
| 1002 | confess("Unexpected input type: AI::MXNet::NDArray::RowSparse"); | ||
| 1003 | } | ||
| 1004 | else | ||
| 1005 | { | ||
| 1006 | # construct a csr matrix from a dense one | ||
| 1007 | # prepare default ctx and dtype since mx.nd.array doesn't use default values | ||
| 1008 | # based on source_array | ||
| 1009 | $dtype = __PACKAGE__->_prepare_default_dtype($arg1, $dtype); | ||
| 1010 | # create dns array with provided dtype. ctx is not passed since copy across | ||
| 1011 | # ctx requires dtype to be the same | ||
| 1012 | my $dns = __PACKAGE__->array($arg1, dtype=>$dtype); | ||
| 1013 | if(defined $ctx and $dns->context ne $ctx) | ||
| 1014 | { | ||
| 1015 | $dns = $dns->as_in_context($ctx); | ||
| 1016 | } | ||
| 1017 | __PACKAGE__->_check_shape($dns->shape, $shape); | ||
| 1018 | return $dns->tostype('csr'); | ||
| 1019 | } | ||
| 1020 | } | ||
| 1021 | } | ||
| 1022 | |||
| 1023 | # Create a AI::MXNet::NDarray::CSR based on data, indices and indptr | ||
| 1024 | method _csr_matrix_from_definition( | ||
| 1025 | $data, $indices, $indptr, | ||
| 1026 | Maybe[Shape|PDL] :$shape=, | ||
| 1027 | AI::MXNet::Context :$ctx=AI::MXNet::Context->current_ctx, | ||
| 1028 | Maybe[Dtype] :$dtype=, | ||
| 1029 | Maybe[Dtype] :$indices_type=STORAGE_AUX_TYPES->{'csr'}[0], | ||
| 1030 | Maybe[Dtype] :$indptr_type=STORAGE_AUX_TYPES->{'csr'}[1] | ||
| 1031 | ) | ||
| 1032 | { | ||
| 1033 | $dtype = __PACKAGE__->_prepare_default_dtype($data, $dtype); | ||
| 1034 | # prepare src array and types | ||
| 1035 | $data = __PACKAGE__->_prepare_src_array($data, $dtype); | ||
| 1036 | $indptr = __PACKAGE__->_prepare_src_array($indptr, $indptr_type); | ||
| 1037 | $indices = __PACKAGE__->_prepare_src_array($indices, $indices_type); | ||
| 1038 | |||
| 1039 | if(not (blessed $data and $data->isa('AI::MXNet::NDArray'))) | ||
| 1040 | { | ||
| 1041 | $data = __PACKAGE__->array($data, ctx => $ctx, dtype => $dtype); | ||
| 1042 | } | ||
| 1043 | if(not (blessed $indptr and $indptr->isa('AI::MXNet::NDArray'))) | ||
| 1044 | { | ||
| 1045 | $indptr = __PACKAGE__->array($indptr, ctx => $ctx, dtype => $indptr_type); | ||
| 1046 | } | ||
| 1047 | if(not (blessed $indices and $indices->isa('AI::MXNet::NDArray'))) | ||
| 1048 | { | ||
| 1049 | $indices = __PACKAGE__->array($indices, ctx => $ctx, dtype => $indices_type); | ||
| 1050 | } | ||
| 1051 | if(not defined $shape) | ||
| 1052 | { | ||
| 1053 | if($indices->shape->[0] == 0) | ||
| 1054 | { | ||
| 1055 | confess('invalid shape'); | ||
| 1056 | } | ||
| 1057 | $shape = [@{ $indptr } - 1, $indices->max->asscalar + 1]; | ||
| 1058 | } | ||
| 1059 | elsif(blessed $shape) | ||
| 1060 | { | ||
| 1061 | $shape = $shape->unpdl; | ||
| 1062 | } | ||
| 1063 | # verify shapes | ||
| 1064 | my $aux_shapes = [$indptr->shape, $indices->shape]; | ||
| 1065 | if($data->ndim != 1 or $indptr->ndim != 1 or $indices->ndim != 1 or $indptr->shape->[0] == 0 or @{ $shape } != 2) | ||
| 1066 | { | ||
| 1067 | confess('invalid shape'); | ||
| 1068 | } | ||
| 1069 | my $hdl = __PACKAGE__->_new_alloc_handle( | ||
| 1070 | 'csr', $shape, $ctx, 0, $dtype, | ||
| 1071 | [$indptr_type, $indices_type], $aux_shapes | ||
| 1072 | ); | ||
| 1073 | my $result = AI::MXNet::NDArray::CSR->new(handle => $hdl); | ||
| 1074 | check_call(AI::MXNetCAPI::NDArraySyncCopyFromNDArray($result->handle, $data->handle, -1)); | ||
| 1075 | check_call(AI::MXNetCAPI::NDArraySyncCopyFromNDArray($result->handle, $indptr->handle, 0)); | ||
| 1076 | check_call(AI::MXNetCAPI::NDArraySyncCopyFromNDArray($result->handle, $indices->handle, 1)); | ||
| 1077 | return $result; | ||
| 1078 | } | ||
| 1079 | |||
| 1080 | =head2 row_sparse_array | ||
| 1081 | |||
| 1082 | Creates a AI::MXNet::NDArray::RowSparse, a multidimensional row sparse array with a set of | ||
| 1083 | tensor slices at given indices. | ||
| 1084 | |||
| 1085 | The AI::MXNet::NDArray::RowSparse can be instantiated in several ways: | ||
| 1086 | |||
| 1087 | - row_sparse_array($arg1, Maybe[AI::MXNet::Context] :$ctx=, Maybe[Shape] :$shape, Maybe [Dtype] :$dtype=) | ||
| 1088 | $ctx, $shape, $dtype are optional | ||
| 1089 | $arg1 can be given in following variants | ||
| 1090 | |||
| 1091 | - to construct a AI::MXNet::NDArray::RowSparse with a dense array $arg1 | ||
| 1092 | - $arg1 is in AI::MXNet::NDArray::array input format | ||
| 1093 | |||
| 1094 | - to construct a AI::MXNet::NDArray::RowSparse with a sparse array $arg1 | ||
| 1095 | $arg1 is AI::MXNet::NDArray::RowSparse | ||
| 1096 | |||
| 1097 | - to construct an empty AI::MXNet::NDArray::RowSparse with shape $arg1 = [$D1, $D1, ...$DN] | ||
| 1098 | |||
| 1099 | - to construct a RowSparseNDArray based on the definition of row sparse format | ||
| 1100 | using two separate arrays, | ||
| 1101 | where the $indices stores the indices of the row slices with non-zeros, | ||
| 1102 | while the values are stored in $data. The corresponding NDArray dense | ||
| 1103 | represented by RowSparse rsp has | ||
| 1104 | dense[rsp.indices[i], :, :, :, ...] = rsp.data[i, :, :, :, ...] | ||
| 1105 | The row indices for are expected to be **sorted in ascending order. | ||
| 1106 | $arg1 = [$data, $indices] | ||
| 1107 | $data, $indices must be given in the AI::MXNet::NDArray::array input format | ||
| 1108 | |||
| 1109 | Returns | ||
| 1110 | ------- | ||
| 1111 | AI::MXNet::NDArray::RowSparse | ||
| 1112 | A AI::MXNet::NDArray::RowSparse with the 'row_sparse' storage representation. | ||
| 1113 | |||
| 1114 | Example | ||
| 1115 | ------- | ||
| 1116 | >>> $a = mx->nd->sparse->row_sparse_array([[[1, 2], [3, 4]], [1, 4]], shape=>[6, 2]) | ||
| 1117 | >>> $a->aspdl | ||
| 1118 | [[ 0 0] | ||
| 1119 | [ 1 2] | ||
| 1120 | [ 0 0] | ||
| 1121 | [ 0 0] | ||
| 1122 | [ 3 4] | ||
| 1123 | [ 0 0]] | ||
| 1124 | =cut | ||
| 1125 | |||
| 1126 | method row_sparse_array( | ||
| 1127 | $arg1, | ||
| 1128 | Maybe[Shape] :$shape=, | ||
| 1129 | Maybe[AI::MXNet::Context] :$ctx=AI::MXNet::Context->current_ctx, | ||
| 1130 | Maybe[Dtype] :$dtype= | ||
| 1131 | ) | ||
| 1132 | { | ||
| 1133 | if(not defined $arg1) | ||
| 1134 | { | ||
| 1135 | return __PACKAGE__->empty('row_sparse', $shape, ctx => $ctx, (defined $dtype ? (dtype => $dtype) : ())); | ||
| 1136 | } | ||
| 1137 | # construct a row sparse array from (D0, D1 ..) or (data, indices) | ||
| 1138 | if(ref $arg1 eq 'ARRAY') | ||
| 1139 | { | ||
| 1140 | my $arg_len = @{ $arg1 }; | ||
| 1141 | if($arg_len < 2) | ||
| 1142 | { | ||
| 1143 | confess("Unexpected length of input array: $arg_len "); | ||
| 1144 | } | ||
| 1145 | elsif($arg_len > 2) | ||
| 1146 | { | ||
| 1147 | # empty ndarray with shape | ||
| 1148 | __PACKAGE__->_check_shape($arg1, $shape); | ||
| 1149 | return __PACKAGE__->empty('row_sparse', $arg1, ctx => $ctx, dtype => $dtype); | ||
| 1150 | } | ||
| 1151 | else | ||
| 1152 | { | ||
| 1153 | # len(arg1) = 2, is either shape or (data, indices) | ||
| 1154 | if(not ref $arg1->[0] and not ref $arg1->[1]) | ||
| 1155 | { | ||
| 1156 | # empty ndarray with shape | ||
| 1157 | __PACKAGE__->_check_shape($arg1, $shape); | ||
| 1158 | return __PACKAGE__->empty('row_sparse', $arg1, ctx => $ctx, dtype => $dtype); | ||
| 1159 | } | ||
| 1160 | else | ||
| 1161 | { | ||
| 1162 | # data, indices, indptr | ||
| 1163 | return __PACKAGE__->_row_sparse_ndarray_from_definition( | ||
| 1164 | @{ $arg1 }, shape => $shape, ctx => $ctx, dtype => $dtype | ||
| 1165 | ); | ||
| 1166 | } | ||
| 1167 | } | ||
| 1168 | } | ||
| 1169 | else | ||
| 1170 | { | ||
| 1171 | # construct a row sparse ndarray from a dense / sparse array | ||
| 1172 | if(blessed $arg1 and $arg1->isa('AI::MXNet::NDArray::RowSparse')) | ||
| 1173 | { | ||
| 1174 | # construct a row sparse ndarray from RowSparseNDArray | ||
| 1175 | __PACKAGE__->_check_shape($arg1->shape, $shape); | ||
| 1176 | return __PACKAGE__->array($arg1, ctx => $ctx, dtype => $dtype); | ||
| 1177 | } | ||
| 1178 | elsif(blessed $arg1 and $arg1->isa('AI::MXNet::NDArray::CSR')) | ||
| 1179 | { | ||
| 1180 | confess("Unexpected input type: AI::MXNet::NDArray::CSR"); | ||
| 1181 | } | ||
| 1182 | else | ||
| 1183 | { | ||
| 1184 | # construct a csr matrix from a dense one | ||
| 1185 | # prepare default dtype since mx.nd.array doesn't use default values | ||
| 1186 | # based on source_array | ||
| 1187 | $dtype = __PACKAGE__->_prepare_default_dtype($arg1, $dtype); | ||
| 1188 | # create dns array with provided dtype. ctx is not passed since copy across | ||
| 1189 | # ctx requires dtype to be the same | ||
| 1190 | my $dns = __PACKAGE__->array($arg1, dtype => $dtype); | ||
| 1191 | if(defined $ctx and $dns->context ne $ctx) | ||
| 1192 | { | ||
| 1193 | $dns = $dns->as_in_context($ctx); | ||
| 1194 | } | ||
| 1195 | __PACKAGE__->_check_shape($dns->shape, $shape); | ||
| 1196 | return $dns->tostype('row_sparse'); | ||
| 1197 | } | ||
| 1198 | } | ||
| 1199 | } | ||
| 1200 | |||
| 1201 | # Create a AI::MXNet::NDArray::RowSparse based on data and indices | ||
| 1202 | method _row_sparse_ndarray_from_definition( | ||
| 1203 | $data, $indices, | ||
| 1204 | Maybe[Shape] :$shape=, | ||
| 1205 | AI::MXNet::Context :$ctx=AI::MXNet::Context->current_ctx, | ||
| 1206 | Maybe[Dtype] :$dtype=, | ||
| 1207 | Maybe[Dtype] :$indices_type=STORAGE_AUX_TYPES->{'row_sparse'}[0] | ||
| 1208 | ) | ||
| 1209 | { | ||
| 1210 | $dtype = __PACKAGE__->_prepare_default_dtype($data, $dtype); | ||
| 1211 | # prepare src array and types | ||
| 1212 | $data = __PACKAGE__->_prepare_src_array($data, $dtype); | ||
| 1213 | $indices = __PACKAGE__->_prepare_src_array($indices, $indices_type); | ||
| 1214 | |||
| 1215 | if(not (blessed $data and $data->isa('AI::MXNet::NDArray'))) | ||
| 1216 | { | ||
| 1217 | $data = __PACKAGE__->array($data, ctx => $ctx, dtype => $dtype); | ||
| 1218 | } | ||
| 1219 | if(not (blessed $indices and $indices->isa('AI::MXNet::NDArray'))) | ||
| 1220 | { | ||
| 1221 | $indices = __PACKAGE__->array($indices, ctx => $ctx, dtype => $indices_type); | ||
| 1222 | } | ||
| 1223 | if(not defined $shape) | ||
| 1224 | { | ||
| 1225 | my $num_indices = $indices->shape->[0]; | ||
| 1226 | if($num_indices == 0) | ||
| 1227 | { | ||
| 1228 | confess('invalid shape'); | ||
| 1229 | } | ||
| 1230 | my $dim0 = $indices->at($num_indices - 1)->asscalar + 1; | ||
| 1231 | $shape = [$dim0, @{ $data->shape } [1..@{ $data->shape } - 1]]; | ||
| 1232 | } | ||
| 1233 | # verify shapes | ||
| 1234 | if($data->ndim != @{ $shape } or $indices->ndim != 1 or product(@{ $shape } [1..@{ $shape } - 1]) == 0) | ||
| 1235 | { | ||
| 1236 | confess("invalid shape"); | ||
| 1237 | } | ||
| 1238 | my $handle = __PACKAGE__->_new_alloc_handle( | ||
| 1239 | 'row_sparse', $shape, $ctx, 0, $dtype, | ||
| 1240 | [$indices_type], [$indices->shape] | ||
| 1241 | ); | ||
| 1242 | my $result = AI::MXNet::NDArray::RowSparse->new(handle => $handle); | ||
| 1243 | check_call(AI::MXNetCAPI::NDArraySyncCopyFromNDArray($result->handle, $data->handle, -1)); | ||
| 1244 | check_call(AI::MXNetCAPI::NDArraySyncCopyFromNDArray($result->handle, $indices->handle, 0)); | ||
| 1245 | return $result | ||
| 1246 | } | ||
| 1247 | |||
| 1248 | =head2 zeros | ||
| 1249 | |||
| 1250 | Return a new array of given shape and type, filled with zeros. | ||
| 1251 | |||
| 1252 | Parameters | ||
| 1253 | ---------- | ||
| 1254 | $stype: string | ||
| 1255 | The storage type of the empty array, such as 'row_sparse', 'csr', etc | ||
| 1256 | shape : int or array ref of int | ||
| 1257 | The shape of the empty array | ||
| 1258 | :$ctx : AI::MXNet::Context, optional | ||
| 1259 | An optional device context (default is the current default context) | ||
| 1260 | :$dtype : Dtype, optional | ||
| 1261 | An optional value type (default is `float32`) | ||
| 1262 | |||
| 1263 | Returns | ||
| 1264 | ------- | ||
| 1265 | AI::MXNet::NDArray::RowSparse or AI::MXNet::NDArray::CSR | ||
| 1266 | A created array | ||
| 1267 | Examples | ||
| 1268 | -------- | ||
| 1269 | >>> mx->nd->sparse->zeros('csr', [1,2]) | ||
| 1270 | <AI::MXNet::NDArray::CSR 1x2 @cpu(0)> | ||
| 1271 | >>> mx->nd->sparse->zeros('row_sparse', [1,2], ctx=>mx->cpu(), dtype=>'float16')->aspdl | ||
| 1272 | [[ 0 0]] | ||
| 1273 | =cut | ||
| 1274 | |||
| 1275 | |||
| 1276 | method zeros( | ||
| 1277 | Stype $stype, | ||
| 1278 | Shape $shape, | ||
| 1279 | AI::MXNet::Context :$ctx=AI::MXNet::Context->current_ctx, | ||
| 1280 | Maybe[Dtype] :$dtype='float32', | ||
| 1281 | Maybe[AI::MXNet::NDArray] :$out=, | ||
| 1282 | Maybe[Str] :$name=, | ||
| 1283 | Maybe[Str] :$__layout__= | ||
| 1284 | ) | ||
| 1285 | { | ||
| 1286 | if($stype eq 'default') | ||
| 1287 | { | ||
| 1288 | return AI::MXNet::NDArray->zeros( | ||
| 1289 | $shape, ctx => $ctx, dtype => $dtype, out => $out, name => $name, __layout__ => $__layout__ | ||
| 1290 | ); | ||
| 1291 | } | ||
| 1292 | my $aux_types; | ||
| 1293 | if($stype eq 'row_sparse' or $stype or 'csr') | ||
| 1294 | { | ||
| 1295 | $aux_types = STORAGE_AUX_TYPES->{ $stype }; | ||
| 1296 | } | ||
| 1297 | else | ||
| 1298 | { | ||
| 1299 | confess("unknown storage type: $stype"); | ||
| 1300 | } | ||
| 1301 | $out //= __PACKAGE__->_ndarray_cls( | ||
| 1302 | __PACKAGE__->_new_alloc_handle( | ||
| 1303 | $stype, $shape, $ctx, 1, $dtype, $aux_types) | ||
| 1304 | ); | ||
| 1305 | return __PACKAGE__->_zeros( | ||
| 1306 | shape => $shape, ctx => $ctx, dtype => $dtype, out => $out, | ||
| 1307 | ($__layout__ ? (__layout__ => $__layout__) : ()) | ||
| 1308 | ); | ||
| 1309 | } | ||
| 1310 | |||
| 1311 | =head2 empty | ||
| 1312 | |||
| 1313 | Returns a new array of given shape and type, without initializing entries. | ||
| 1314 | |||
| 1315 | Parameters | ||
| 1316 | ---------- | ||
| 1317 | stype: string | ||
| 1318 | The storage type of the empty array, such as 'row_sparse', 'csr', etc | ||
| 1319 | shape : int or array ref of int | ||
| 1320 | The shape of the empty array. | ||
| 1321 | ctx : Context, optional | ||
| 1322 | An optional device context (default is the current default context). | ||
| 1323 | dtype : Dtype, optional | ||
| 1324 | An optional value type (default is `float32`). | ||
| 1325 | |||
| 1326 | Returns | ||
| 1327 | ------- | ||
| 1328 | AI::MXNet::NDArray::CSR or AI::MXNet::NDArray::RowSparse | ||
| 1329 | A created array. | ||
| 1330 | =cut | ||
| 1331 | |||
| 1332 | method empty( | ||
| 1333 | Stype $stype, | ||
| 1334 | Shape $shape, | ||
| 1335 | Maybe[AI::MXNet::Context] :$ctx=AI::MXNet::Context->current_ctx, | ||
| 1336 | Maybe[Dtype] :$dtype='float32' | ||
| 1337 | ) | ||
| 1338 | { | ||
| 1339 | assert(defined $stype); | ||
| 1340 | return __PACKAGE__->zeros($stype, $shape, ctx => $ctx, dtype => $dtype); | ||
| 1341 | } | ||
| 1342 | |||
| 1343 | =head2 array | ||
| 1344 | |||
| 1345 | Creates a sparse array from any object exposing the array interface. | ||
| 1346 | |||
| 1347 | Parameters | ||
| 1348 | ---------- | ||
| 1349 | $source_array : AI::MXNet::NDArray::RowSparse, AI::MXNet::NDArray::CSR or PDL::CCS::Nd | ||
| 1350 | The source sparse array | ||
| 1351 | :$ctx : Context, optional | ||
| 1352 | The default context is $source_array->context if $source_array is an NDArray. | ||
| 1353 | The current default context otherwise. | ||
| 1354 | :$dtype : Dtype, optional | ||
| 1355 | The data type of the output array. The default dtype is $source_array->dtype | ||
| 1356 | if $source_array is an AI::MXNet::NDArray, PDL or PDL::CCS::Nd | ||
| 1357 | 'float32' otherwise. | ||
| 1358 | |||
| 1359 | Returns | ||
| 1360 | ------- | ||
| 1361 | AI::MXNet::NDArray::RowSparse or AI::MXNet::NDArray::CSR | ||
| 1362 | An array with the same contents as the $source_array. | ||
| 1363 | |||
| 1364 | Examples | ||
| 1365 | -------- | ||
| 1366 | >>> use PDL; use PDL::CCS::Nd | ||
| 1367 | >>> $csr = zeros([100, 2])->tocsr | ||
| 1368 | >>> mx->nd->sparse->array($csr) | ||
| 1369 | <AI::MXNet::NDArray::CSR 2x100 @cpu(0)> | ||
| 1370 | >>> mx->nd->sparse->array(mx->nd->sparse->zeros('csr', [3, 2])) | ||
| 1371 | <AI::MXNet::NDArray::CSR 3x2 @cpu(0)> | ||
| 1372 | >>> mx->nd->sparse->array(mx->nd->sparse->zeros('row_sparse', [3, 2])) | ||
| 1373 | <AI::MXNet::NDArray::RowSparse 3x2 @cpu(0)> | ||
| 1374 | =cut | ||
| 1375 | |||
| 1376 | method array( | ||
| 1377 | AcceptableInput $source_array, | ||
| 1378 | Maybe[AI::MXNet::Context] :$ctx=AI::MXNet::Context->current_ctx, | ||
| 1379 | Maybe[Dtype] :$dtype='float32', | ||
| 1380 | Maybe[PDL] :$pdl= | ||
| 1381 | ) | ||
| 1382 | { | ||
| 1383 | if(not blessed $source_array or $source_array->isa('PDL') or ($source_array->isa('AI::MXNet::NDArray') and $source_array->stype eq 'default')) | ||
| 1384 | { | ||
| 1385 | if(not ref $source_array) | ||
| 1386 | { | ||
| 1387 | $pdl .= $source_array; | ||
| 1388 | $source_array = $pdl; | ||
| 1389 | } | ||
| 1390 | return __PACKAGE__->SUPER::array($source_array, ctx => $ctx, dtype => $dtype); | ||
| 1391 | } | ||
| 1392 | if($source_array->isa('AI::MXNet::NDArray')) | ||
| 1393 | { | ||
| 1394 | assert( | ||
| 1395 | ($source_array->stype ne 'default'), | ||
| 1396 | "Please use tostype to create AI::MXNet::NDarray::RowSparse or AI::MXNet::NDarray::CSR from an AI::MXNet::NDarray" | ||
| 1397 | ); | ||
| 1398 | # prepare dtype and ctx based on source_array, if not provided | ||
| 1399 | $dtype = __PACKAGE__->_prepare_default_dtype($source_array, $dtype); | ||
| 1400 | # if both dtype and ctx are different from source_array, we cannot copy directly | ||
| 1401 | my $arr; | ||
| 1402 | if($source_array->dtype ne $dtype and $source_array->context ne $ctx) | ||
| 1403 | { | ||
| 1404 | $arr = __PACKAGE__->empty($source_array->stype, $source_array->shape, dtype => $dtype); | ||
| 1405 | $arr .= $source_array; | ||
| 1406 | $arr = $arr->as_in_context($ctx); | ||
| 1407 | } | ||
| 1408 | else | ||
| 1409 | { | ||
| 1410 | $arr = __PACKAGE__->empty($source_array->stype, $source_array->shape, dtype => $dtype, ctx => $ctx); | ||
| 1411 | $arr .= $source_array; | ||
| 1412 | } | ||
| 1413 | return $arr; | ||
| 1414 | } | ||
| 1415 | elsif($source_array->isa('PDL::CCS::Nd')) | ||
| 1416 | { | ||
| 1417 | $dtype = __PACKAGE__->_prepare_default_dtype($source_array, $dtype); | ||
| 1418 | return __PACKAGE__->csr_matrix( | ||
| 1419 | [$source_array->data, $source_array->indices, $source_array->indptr], | ||
| 1420 | shape => $source_array->shape , dtype => $dtype, ctx => $ctx | ||
| 1421 | ); | ||
| 1422 | } | ||
| 1423 | } | ||
| 1424 | |||
| 1425 | sub AUTOLOAD { | ||
| 1426 | my $sub = $AI::MXNet::NDArray::Sparse::AUTOLOAD; | ||
| 1427 | $sub =~ s/.*:://; | ||
| 1428 | $sub = "_sparse_$sub"; | ||
| 1429 | shift; | ||
| 1430 | return AI::MXNet::NDArray->$sub(@_); | ||
| 1431 | } | ||
| 1432 | |||
| 1433 | 1; |