| 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::TestUtils; | ||
| 19 | use strict; | ||
| 20 | use warnings; | ||
| 21 | use AI::MXNet 'mx'; | ||
| 22 | use PDL; | ||
| 23 | use Carp qw(confess); | ||
| 24 | use Scalar::Util qw(blessed); | ||
| 25 | use List::Util qw(shuffle); | ||
| 26 | use AI::MXNet::Function::Parameters; | ||
| 27 | use AI::MXNet::Base; | ||
| 28 | use Exporter; | ||
| 29 | use base qw(Exporter); | ||
| 30 | our @EXPORT_OK = qw(same reldiff almost_equal GetMNIST_ubyte | ||
| 31 | GetCifar10 pdl_maximum pdl_minimum mlp2 conv dies_ok | ||
| 32 | check_consistency zip assert enumerate same_array dies_like allclose rand_shape_2d | ||
| 33 | rand_shape_3d rand_sparse_ndarray random_arrays rand_ndarray randint pdl); | ||
| 34 | use constant default_numerical_threshold => 1e-6; | ||
| 35 | =head1 NAME | ||
| 36 | |||
| 37 | AI::MXNet::TestUtils - Convenience subs used in tests. | ||
| 38 | |||
| 39 | =head2 same | ||
| 40 | |||
| 41 | Test if two pdl arrays are the same | ||
| 42 | |||
| 43 | Parameters | ||
| 44 | ---------- | ||
| 45 | a : pdl | ||
| 46 | b : pdl | ||
| 47 | =cut | ||
| 48 | |||
| 49 | func isNaN(PDL $a) | ||
| 50 | { | ||
| 51 | # Only NaN is not greater, equal to, or less than zero. | ||
| 52 | return !(($a > 0) + ($a <= 0)); | ||
| 53 | } | ||
| 54 | |||
| 55 | func same(PDL $a, PDL $b) | ||
| 56 | { | ||
| 57 | my $rv = ($a != $b) - isNaN($a) * isNaN($b); | ||
| 58 | return $rv->sum == 0; | ||
| 59 | } | ||
| 60 | |||
| 61 | =head2 allclose | ||
| 62 | |||
| 63 | Test if all elements of two pdl arrays are almost equal | ||
| 64 | |||
| 65 | Parameters | ||
| 66 | ---------- | ||
| 67 | a : pdl | ||
| 68 | b : pdl | ||
| 69 | =cut | ||
| 70 | |||
| 71 | func allclose(PDL $a, PDL $b, Maybe[Num] $threshold=) | ||
| 72 | { | ||
| 73 | return (($a - $b)->abs <= ($threshold//default_numerical_threshold))->all; | ||
| 74 | } | ||
| 75 | |||
| 76 | =head2 reldiff | ||
| 77 | |||
| 78 | Calculate the relative difference between two input arrays | ||
| 79 | |||
| 80 | Calculated by :math:`\\frac{|a-b|_1}{|a|_1 + |b|_1}` | ||
| 81 | |||
| 82 | Parameters | ||
| 83 | ---------- | ||
| 84 | a : pdl | ||
| 85 | b : pdl | ||
| 86 | =cut | ||
| 87 | |||
| 88 | func reldiff(PDL $a, PDL $b) | ||
| 89 | { | ||
| 90 | my $diff = sum(abs($a - $b)); | ||
| 91 | my $norm = sum(abs($a)) + sum(abs($b)); | ||
| 92 | if($diff == 0) | ||
| 93 | { | ||
| 94 | return 0; | ||
| 95 | } | ||
| 96 | my $ret = $diff / $norm; | ||
| 97 | return $ret; | ||
| 98 | } | ||
| 99 | |||
| 100 | =head2 almost_equal | ||
| 101 | |||
| 102 | Test if two pdl arrays are almost equal. | ||
| 103 | =cut | ||
| 104 | |||
| 105 | func almost_equal(PDL $a, PDL $b, Maybe[Num] $threshold=) | ||
| 106 | { | ||
| 107 | $threshold //= default_numerical_threshold; | ||
| 108 | my $rel = reldiff($a, $b); | ||
| 109 | return $rel <= $threshold; | ||
| 110 | } | ||
| 111 | |||
| 112 | func GetMNIST_ubyte() | ||
| 113 | { | ||
| 114 | if(not -d "data") | ||
| 115 | { | ||
| 116 | mkdir "data"; | ||
| 117 | } | ||
| 118 | if ( | ||
| 119 | not -f 'data/train-images-idx3-ubyte' | ||
| 120 | or | ||
| 121 | not -f 'data/train-labels-idx1-ubyte' | ||
| 122 | or | ||
| 123 | not -f 'data/t10k-images-idx3-ubyte' | ||
| 124 | or | ||
| 125 | not -f 'data/t10k-labels-idx1-ubyte' | ||
| 126 | ) | ||
| 127 | { | ||
| 128 | `wget http://data.mxnet.io/mxnet/data/mnist.zip -P data`; | ||
| 129 | chdir 'data'; | ||
| 130 | `unzip -u mnist.zip`; | ||
| 131 | chdir '..'; | ||
| 132 | } | ||
| 133 | } | ||
| 134 | |||
| 135 | func GetCifar10() | ||
| 136 | { | ||
| 137 | if(not -d "data") | ||
| 138 | { | ||
| 139 | mkdir "data"; | ||
| 140 | } | ||
| 141 | if (not -f 'data/cifar10.zip') | ||
| 142 | { | ||
| 143 | `wget http://data.mxnet.io/mxnet/data/cifar10.zip -P data`; | ||
| 144 | chdir 'data'; | ||
| 145 | `unzip -u cifar10.zip`; | ||
| 146 | chdir '..'; | ||
| 147 | } | ||
| 148 | } | ||
| 149 | |||
| 150 | func _pdl_compare(PDL $a, PDL|Num $b, Str $criteria) | ||
| 151 | { | ||
| 152 | if(not blessed $b) | ||
| 153 | { | ||
| 154 | my $tmp = $b; | ||
| 155 | $b = $a->copy; | ||
| 156 | $b .= $tmp; | ||
| 157 | } | ||
| 158 | my $mask = { | ||
| 159 | 'max' => sub { $_[0] < $_[1] }, | ||
| 160 | 'min' => sub { $_[0] > $_[1] }, | ||
| 161 | }->{$criteria}->($a, $b); | ||
| 162 | my $c = $a->copy; | ||
| 163 | $c->where($mask) .= $b->where($mask); | ||
| 164 | $c; | ||
| 165 | } | ||
| 166 | |||
| 167 | func pdl_maximum(PDL $a, PDL|Num $b) | ||
| 168 | { | ||
| 169 | _pdl_compare($a, $b, 'max'); | ||
| 170 | } | ||
| 171 | |||
| 172 | func pdl_minimum(PDL $a, PDL|Num $b) | ||
| 173 | { | ||
| 174 | _pdl_compare($a, $b, 'min'); | ||
| 175 | } | ||
| 176 | |||
| 177 | func mlp2() | ||
| 178 | { | ||
| 179 | my $data = AI::MXNet::Symbol->Variable('data'); | ||
| 180 | my $out = AI::MXNet::Symbol->FullyConnected(data=>$data, name=>'fc1', num_hidden=>1000); | ||
| 181 | $out = AI::MXNet::Symbol->Activation(data=>$out, act_type=>'relu'); | ||
| 182 | $out = AI::MXNet::Symbol->FullyConnected(data=>$out, name=>'fc2', num_hidden=>10); | ||
| 183 | return $out; | ||
| 184 | } | ||
| 185 | |||
| 186 | func conv() | ||
| 187 | { | ||
| 188 | my $data = AI::MXNet::Symbol->Variable('data'); | ||
| 189 | my $conv1 = AI::MXNet::Symbol->Convolution(data => $data, name=>'conv1', num_filter=>32, kernel=>[3,3], stride=>[2,2]); | ||
| 190 | my $bn1 = AI::MXNet::Symbol->BatchNorm(data => $conv1, name=>"bn1"); | ||
| 191 | my $act1 = AI::MXNet::Symbol->Activation(data => $bn1, name=>'relu1', act_type=>"relu"); | ||
| 192 | my $mp1 = AI::MXNet::Symbol->Pooling(data => $act1, name => 'mp1', kernel=>[2,2], stride=>[2,2], pool_type=>'max'); | ||
| 193 | |||
| 194 | my $conv2 = AI::MXNet::Symbol->Convolution(data => $mp1, name=>'conv2', num_filter=>32, kernel=>[3,3], stride=>[2,2]); | ||
| 195 | my $bn2 = AI::MXNet::Symbol->BatchNorm(data => $conv2, name=>"bn2"); | ||
| 196 | my $act2 = AI::MXNet::Symbol->Activation(data => $bn2, name=>'relu2', act_type=>"relu"); | ||
| 197 | my $mp2 = AI::MXNet::Symbol->Pooling(data => $act2, name => 'mp2', kernel=>[2,2], stride=>[2,2], pool_type=>'max'); | ||
| 198 | |||
| 199 | my $fl = AI::MXNet::Symbol->Flatten(data => $mp2, name=>"flatten"); | ||
| 200 | my $fc2 = AI::MXNet::Symbol->FullyConnected(data => $fl, name=>'fc2', num_hidden=>10); | ||
| 201 | my $softmax = AI::MXNet::Symbol->SoftmaxOutput(data => $fc2, name => 'sm'); | ||
| 202 | return $softmax; | ||
| 203 | } | ||
| 204 | |||
| 205 | =head2 check_consistency | ||
| 206 | |||
| 207 | Check symbol gives the same output for different running context | ||
| 208 | |||
| 209 | Parameters | ||
| 210 | ---------- | ||
| 211 | sym : Symbol or list of Symbols | ||
| 212 | symbol(s) to run the consistency test | ||
| 213 | ctx_list : list | ||
| 214 | running context. See example for more detail. | ||
| 215 | scale : float, optional | ||
| 216 | standard deviation of the inner normal distribution. Used in initialization | ||
| 217 | grad_req : str or list of str or dict of str to str | ||
| 218 | gradient requirement. | ||
| 219 | =cut | ||
| 220 | |||
| 221 | my %dtypes = ( | ||
| 222 | float32 => 0, | ||
| 223 | float64 => 1, | ||
| 224 | float16 => 2, | ||
| 225 | uint8 => 3, | ||
| 226 | int32 => 4 | ||
| 227 | ); | ||
| 228 | |||
| 229 | func check_consistency( | ||
| 230 | SymbolOrArrayOfSymbols :$sym, | ||
| 231 | ArrayRef :$ctx_list, | ||
| 232 | Num :$scale=1, | ||
| 233 | Str|ArrayRef[Str]|HashRef[Str] :$grad_req='write', | ||
| 234 | Maybe[HashRef[AI::MXNet::NDArray]] :$arg_params=, | ||
| 235 | Maybe[HashRef[AI::MXNet::NDArray]] :$aux_params=, | ||
| 236 | Maybe[HashRef[Num]|Num] :$tol=, | ||
| 237 | Bool :$raise_on_err=1, | ||
| 238 | Maybe[AI::MXNer::NDArray] :$ground_truth= | ||
| 239 | ) | ||
| 240 | { | ||
| 241 | $tol //= { | ||
| 242 | float16 => 1e-1, | ||
| 243 | float32 => 1e-3, | ||
| 244 | float64 => 1e-5, | ||
| 245 | uint8 => 0, | ||
| 246 | int32 => 0 | ||
| 247 | }; | ||
| 248 | $tol = { | ||
| 249 | float16 => $tol, | ||
| 250 | float32 => $tol, | ||
| 251 | float64 => $tol, | ||
| 252 | uint8 => $tol, | ||
| 253 | int32 => $tol | ||
| 254 | } unless ref $tol; | ||
| 255 | |||
| 256 | Test::More::ok(@$ctx_list > 1); | ||
| 257 | if(blessed $sym) | ||
| 258 | { | ||
| 259 | $sym = [($sym)x@$ctx_list]; | ||
| 260 | } | ||
| 261 | else | ||
| 262 | { | ||
| 263 | Test::More::ok(@$sym == @$ctx_list); | ||
| 264 | } | ||
| 265 | my $output_names = $sym->[0]->list_outputs; | ||
| 266 | my $arg_names = $sym->[0]->list_arguments; | ||
| 267 | my @exe_list; | ||
| 268 | zip(sub { | ||
| 269 | my ($s, $ctx) = @_; | ||
| 270 | Test::More::is_deeply($s->list_arguments, $arg_names); | ||
| 271 | Test::More::is_deeply($s->list_outputs, $output_names); | ||
| 272 | push @exe_list, $s->simple_bind(grad_req=>$grad_req, %$ctx); | ||
| 273 | }, $sym, $ctx_list); | ||
| 274 | $arg_params //= {}; | ||
| 275 | $aux_params //= {}; | ||
| 276 | my %arg_dict = %{ $exe_list[0]->arg_dict }; | ||
| 277 | while(my ($n, $arr) = each %arg_dict) | ||
| 278 | { | ||
| 279 | if(not exists $arg_params->{$n}) | ||
| 280 | { | ||
| 281 | $arg_params->{$n} = random(reverse @{ $arr->shape })*$scale; | ||
| 282 | } | ||
| 283 | } | ||
| 284 | my %aux_dict = %{ $exe_list[0]->aux_dict }; | ||
| 285 | while(my ($n, $arr) = each %aux_dict) | ||
| 286 | { | ||
| 287 | if(not exists $aux_params->{$n}) | ||
| 288 | { | ||
| 289 | $aux_params->{$n} = 0; | ||
| 290 | } | ||
| 291 | } | ||
| 292 | for my $exe(@exe_list) | ||
| 293 | { | ||
| 294 | %arg_dict = %{ $exe->arg_dict }; | ||
| 295 | while(my ($name, $arr) = each %arg_dict) | ||
| 296 | { | ||
| 297 | $arr .= $arg_params->{$name}; | ||
| 298 | } | ||
| 299 | %aux_dict = %{ $exe->aux_dict }; | ||
| 300 | while(my ($name, $arr) = each %aux_dict) | ||
| 301 | { | ||
| 302 | $arr .= $aux_params->{$name}; | ||
| 303 | } | ||
| 304 | } | ||
| 305 | my @dtypes = map { $_->outputs->[0]->dtype } @exe_list; | ||
| 306 | my $max_idx = pdl(map { $dtypes{$_} } @dtypes)->maximum_ind; | ||
| 307 | my $gt = $ground_truth; | ||
| 308 | if(not defined $gt) | ||
| 309 | { | ||
| 310 | $gt = { %{ $exe_list[$max_idx]->output_dict } }; | ||
| 311 | if($grad_req ne 'null') | ||
| 312 | { | ||
| 313 | %{$gt} = (%{$gt}, %{ $exe_list[$max_idx]->grad_dict }); | ||
| 314 | } | ||
| 315 | } | ||
| 316 | |||
| 317 | # test | ||
| 318 | for my $exe (@exe_list) | ||
| 319 | { | ||
| 320 | $exe->forward(0); | ||
| 321 | } | ||
| 322 | enumerate(sub { | ||
| 323 | my ($i, $exe) = @_; | ||
| 324 | if($i == $max_idx) | ||
| 325 | { | ||
| 326 | return; | ||
| 327 | } | ||
| 328 | zip(sub { | ||
| 329 | my ($name, $arr) = @_; | ||
| 330 | my $gtarr = $gt->{$name}->astype($dtypes[$i])->aspdl; | ||
| 331 | $arr = $arr->aspdl; | ||
| 332 | Test::More::ok( | ||
| 333 | almost_equal( | ||
| 334 | $arr, $gtarr, | ||
| 335 | $tol->{$dtypes[$i]} | ||
| 336 | ) | ||
| 337 | ); | ||
| 338 | }, $output_names, $exe->outputs); | ||
| 339 | }, \@exe_list); | ||
| 340 | |||
| 341 | # train | ||
| 342 | if ($grad_req ne 'null') | ||
| 343 | { | ||
| 344 | for my $exe (@exe_list) | ||
| 345 | { | ||
| 346 | $exe->forward(1); | ||
| 347 | $exe->backward($exe->outputs); | ||
| 348 | } | ||
| 349 | enumerate(sub { | ||
| 350 | my ($i, $exe) = @_; | ||
| 351 | return if($i == $max_idx); | ||
| 352 | zip(sub { | ||
| 353 | my ($name, $arr) = @_; | ||
| 354 | if (not defined $gt->{$name}) | ||
| 355 | { | ||
| 356 | Test::More::ok(not defined $arr); | ||
| 357 | return; | ||
| 358 | } | ||
| 359 | my $gtarr = $gt->{$name}->astype($dtypes[$i])->aspdl; | ||
| 360 | $arr = $arr->aspdl; | ||
| 361 | Test::More::ok( | ||
| 362 | almost_equal( | ||
| 363 | $arr, $gtarr, | ||
| 364 | $tol->{$dtypes[$i]} | ||
| 365 | ) | ||
| 366 | ); | ||
| 367 | }, [@$output_names, @$arg_names], [@{ $exe->outputs }, @{ $exe->grad_arrays }]); | ||
| 368 | }, \@exe_list); | ||
| 369 | } | ||
| 370 | return $gt; | ||
| 371 | } | ||
| 372 | |||
| 373 | =head2 same_array | ||
| 374 | |||
| 375 | Check whether two NDArrays sharing the same memory block | ||
| 376 | |||
| 377 | Parameters | ||
| 378 | ---------- | ||
| 379 | |||
| 380 | array1 : NDArray | ||
| 381 | First NDArray to be checked | ||
| 382 | array2 : NDArray | ||
| 383 | Second NDArray to be checked | ||
| 384 | |||
| 385 | Returns | ||
| 386 | ------- | ||
| 387 | bool | ||
| 388 | Whether two NDArrays share the same memory | ||
| 389 | =cut | ||
| 390 | |||
| 391 | func same_array( | ||
| 392 | AI::MXNet::NDArray $array1, | ||
| 393 | AI::MXNet::NDArray $array2 | ||
| 394 | ) | ||
| 395 | { | ||
| 396 | $array1 += 1; | ||
| 397 | if(not same($array1->aspdl, $array2->aspdl)) | ||
| 398 | { | ||
| 399 | $array1 -= 1; | ||
| 400 | return 0 | ||
| 401 | } | ||
| 402 | $array1 -= 1; | ||
| 403 | return same($array1->aspdl, $array2->aspdl); | ||
| 404 | } | ||
| 405 | |||
| 406 | func dies_like($code, $regexp) | ||
| 407 | { | ||
| 408 | eval { $code->() }; | ||
| 409 | if($@ =~ $regexp) | ||
| 410 | { | ||
| 411 | return 1; | ||
| 412 | } | ||
| 413 | else | ||
| 414 | { | ||
| 415 | warn $@; | ||
| 416 | return 0; | ||
| 417 | } | ||
| 418 | } | ||
| 419 | |||
| 420 | func random_arrays(@shapes) | ||
| 421 | { | ||
| 422 | my @arrays = map { random(reverse(@$_))->float } @shapes; | ||
| 423 | if(@arrays > 1) | ||
| 424 | { | ||
| 425 | return @arrays; | ||
| 426 | } | ||
| 427 | else | ||
| 428 | { | ||
| 429 | return $arrays[0]; | ||
| 430 | } | ||
| 431 | } | ||
| 432 | |||
| 433 | |||
| 434 | func _validate_csr_generation_inputs( | ||
| 435 | $num_rows, $num_cols, $density, | ||
| 436 | $distribution="uniform" | ||
| 437 | ) | ||
| 438 | { | ||
| 439 | my $total_nnz = int($num_rows * $num_cols * $density); | ||
| 440 | if($density < 0 or $density > 1) | ||
| 441 | { | ||
| 442 | confess("density has to be between 0 and 1"); | ||
| 443 | } | ||
| 444 | if($num_rows <= 0 or $num_cols <= 0) | ||
| 445 | { | ||
| 446 | confess("num_rows or num_cols should be greater than 0"); | ||
| 447 | } | ||
| 448 | if($distribution eq "powerlaw") | ||
| 449 | { | ||
| 450 | if($total_nnz < 2 * $num_rows) | ||
| 451 | { | ||
| 452 | confess( | ||
| 453 | "not supported for this density: $density" | ||
| 454 | ." for this shape ($num_rows, $num_cols)" | ||
| 455 | ." Please keep :" | ||
| 456 | ." num_rows * num_cols * density >= 2 * num_rows" | ||
| 457 | ); | ||
| 458 | } | ||
| 459 | } | ||
| 460 | } | ||
| 461 | |||
| 462 | # Shuffle CSR column indices per row | ||
| 463 | # This allows validation of unordered column indices, which is not a requirement | ||
| 464 | # for a valid CSR matrix | ||
| 465 | |||
| 466 | func shuffle_csr_column_indices($csr) | ||
| 467 | { | ||
| 468 | my $row_count = @{ $csr->indptr } - 1; | ||
| 469 | for my $i (0..$row_count-1) | ||
| 470 | { | ||
| 471 | my $start_index = $csr->indptr->[$i]; | ||
| 472 | my $end_index = $csr->indptr->[$i + 1]; | ||
| 473 | my @sublist = @{$csr->indices}[$start_index .. $end_index]; | ||
| 474 | @sublist = shuffle(@sublist); | ||
| 475 | @{$csr->indices}[$start_index .. $end_index] = @sublist; | ||
| 476 | } | ||
| 477 | } | ||
| 478 | |||
| 479 | |||
| 480 | func _get_uniform_dataset_csr( | ||
| 481 | $num_rows, $num_cols, $density=0.1, $dtype='float32', | ||
| 482 | $data_init=, $shuffle_csr_indices=0) | ||
| 483 | { | ||
| 484 | # Returns CSRNDArray with uniform distribution | ||
| 485 | # This generates a csr matrix with totalnnz unique randomly chosen numbers | ||
| 486 | # from num_rows*num_cols and arranges them in the 2d array in the | ||
| 487 | # following way: | ||
| 488 | # row_index = (random_number_generated / num_rows) | ||
| 489 | # col_index = random_number_generated - row_index * num_cols | ||
| 490 | |||
| 491 | _validate_csr_generation_inputs( | ||
| 492 | $num_rows, $num_cols, $density, | ||
| 493 | "uniform" | ||
| 494 | ); | ||
| 495 | my $csr = rand_sparse($num_rows, $num_cols, $density, $dtype, "csr"); | ||
| 496 | if(defined $data_init) | ||
| 497 | { | ||
| 498 | $csr->data->fill($data_init); | ||
| 499 | } | ||
| 500 | if($shuffle_csr_indices) | ||
| 501 | { | ||
| 502 | shuffle_csr_column_indices($csr); | ||
| 503 | } | ||
| 504 | return mx->nd->sparse->csr_matrix( | ||
| 505 | [$csr->data, $csr->indices, $csr->indptr], | ||
| 506 | shape => [$num_rows, $num_cols], dtype => $dtype | ||
| 507 | ); | ||
| 508 | } | ||
| 509 | |||
| 510 | func _get_powerlaw_dataset_csr($num_rows, $num_cols, $density=0.1, $dtype='float32') | ||
| 511 | { | ||
| 512 | # Returns CSRNDArray with powerlaw distribution | ||
| 513 | # with exponentially increasing number of non zeros in each row. | ||
| 514 | # Not supported for cases where total_nnz < 2*num_rows. This is because | ||
| 515 | # the algorithm first tries to ensure that there are rows with no zeros by | ||
| 516 | # putting non zeros at beginning of each row. | ||
| 517 | |||
| 518 | _validate_csr_generation_inputs($num_rows, $num_cols, $density, | ||
| 519 | "powerlaw"); | ||
| 520 | |||
| 521 | my $total_nnz = int($num_rows * $num_cols * $density); | ||
| 522 | |||
| 523 | my $unused_nnz = $total_nnz; | ||
| 524 | my $output_arr = zeros($num_cols, $num_rows); | ||
| 525 | # Start with ones on each row so that no row is empty | ||
| 526 | for my $row (0..$num_rows-1) | ||
| 527 | { | ||
| 528 | $output_arr->slice(0, $row) .= 1 + rand(2); | ||
| 529 | $unused_nnz--; | ||
| 530 | if($unused_nnz <= 0) | ||
| 531 | { | ||
| 532 | return mx->nd->array($output_arr)->tostype("csr"); | ||
| 533 | } | ||
| 534 | } | ||
| 535 | # Populate rest of matrix with 2^i items in ith row. | ||
| 536 | # if we have used all total nnz return the sparse matrix | ||
| 537 | # else if we reached max column size then fill up full columns until we use all nnz | ||
| 538 | my $col_max = 2; | ||
| 539 | for my $row (0..$num_rows-1) | ||
| 540 | { | ||
| 541 | my $col_limit = List::Util::min($num_cols, $col_max); | ||
| 542 | # In case col_limit reached assign same value to all elements, which is much faster | ||
| 543 | if($col_limit == $num_cols and $unused_nnz > $col_limit) | ||
| 544 | { | ||
| 545 | $output_arr->slice('X', $row) .= 1 + rand(2); | ||
| 546 | $unused_nnz = $unused_nnz - $col_limit + 1; | ||
| 547 | if($unused_nnz <= 0) | ||
| 548 | { | ||
| 549 | return mx->nd->array($output_arr)->tostype("csr"); | ||
| 550 | } | ||
| 551 | } | ||
| 552 | else | ||
| 553 | { | ||
| 554 | for my $col_index (1..$col_limit-1) | ||
| 555 | { | ||
| 556 | $output_arr->slice($col_index, $row) .= 1 + rand(2); | ||
| 557 | $unused_nnz--; | ||
| 558 | if($unused_nnz <= 0) | ||
| 559 | { | ||
| 560 | return mx->nd->array($output_arr)->tostype("csr"); | ||
| 561 | } | ||
| 562 | } | ||
| 563 | $col_max *= 2; | ||
| 564 | } | ||
| 565 | } | ||
| 566 | |||
| 567 | if($unused_nnz > 0) | ||
| 568 | { | ||
| 569 | warn $unused_nnz; | ||
| 570 | confess( | ||
| 571 | "not supported for this density: $density" | ||
| 572 | ." for this shape ($num_rows,$num_cols)" | ||
| 573 | ); | ||
| 574 | } | ||
| 575 | else | ||
| 576 | { | ||
| 577 | return mx->nd->array($output_arr)->tostype("csr"); | ||
| 578 | } | ||
| 579 | } | ||
| 580 | |||
| 581 | |||
| 582 | func assign_each($input, $function=) | ||
| 583 | { | ||
| 584 | my $res = pdl($input); | ||
| 585 | if(defined $function) | ||
| 586 | { | ||
| 587 | return $function->($res); | ||
| 588 | } | ||
| 589 | return $res; | ||
| 590 | } | ||
| 591 | |||
| 592 | func assign_each2($input1, $input2, $function=) | ||
| 593 | { | ||
| 594 | my $res = pdl($input1); | ||
| 595 | if(defined $function) | ||
| 596 | { | ||
| 597 | return $function->($res, pdl($input2)); | ||
| 598 | } | ||
| 599 | return $res; | ||
| 600 | } | ||
| 601 | |||
| 602 | =head2 rand_sparse_ndarray | ||
| 603 | |||
| 604 | Generate a random sparse ndarray. Returns the ndarray, value(np) and indices(np) | ||
| 605 | |||
| 606 | Parameters | ||
| 607 | ---------- | ||
| 608 | shape: list or tuple | ||
| 609 | stype: str, valid values: "csr" or "row_sparse" | ||
| 610 | density, optional: float, should be between 0 and 1 | ||
| 611 | distribution, optional: str, valid values: "uniform" or "powerlaw" | ||
| 612 | dtype, optional: numpy.dtype, default value is None | ||
| 613 | |||
| 614 | Returns | ||
| 615 | ------- | ||
| 616 | Result of type CSRNDArray or RowSparseNDArray | ||
| 617 | |||
| 618 | Examples | ||
| 619 | -------- | ||
| 620 | Below is an example of the powerlaw distribution with csr as the stype. | ||
| 621 | It calculates the nnz using the shape and density. | ||
| 622 | It fills up the ndarray with exponentially increasing number of elements. | ||
| 623 | If there are enough unused_nnzs, n+1th row will have twice more nnzs compared to nth row. | ||
| 624 | else, remaining unused_nnzs will be used in n+1th row | ||
| 625 | If number of cols is too small and we have already reached column size it will fill up | ||
| 626 | all following columns in all followings rows until we reach the required density. | ||
| 627 | |||
| 628 | >>> csr_arr, _ = rand_sparse_ndarray(shape=(5, 16), stype="csr", | ||
| 629 | density=0.50, distribution="powerlaw") | ||
| 630 | >>> indptr = csr_arr.indptr.asnumpy() | ||
| 631 | >>> indices = csr_arr.indices.asnumpy() | ||
| 632 | >>> data = csr_arr.data.asnumpy() | ||
| 633 | >>> row2nnz = len(data[indptr[1]:indptr[2]]) | ||
| 634 | >>> row3nnz = len(data[indptr[2]:indptr[3]]) | ||
| 635 | >>> assert(row3nnz == 2*row2nnz) | ||
| 636 | >>> row4nnz = len(data[indptr[3]:indptr[4]]) | ||
| 637 | >>> assert(row4nnz == 2*row3nnz) | ||
| 638 | =cut | ||
| 639 | |||
| 640 | func rand_sparse_ndarray( | ||
| 641 | $shape, $stype, :$density=rand, :$dtype='float32', :$distribution='uniform', | ||
| 642 | :$data_init=, :$rsp_indices=, :$modifier_func=, | ||
| 643 | :$shuffle_csr_indices=0 | ||
| 644 | ) | ||
| 645 | { | ||
| 646 | if($stype eq 'row_sparse') | ||
| 647 | { | ||
| 648 | assert ( | ||
| 649 | ($distribution eq "uniform"), | ||
| 650 | "Distribution $distribution not supported for row_sparse" | ||
| 651 | ); | ||
| 652 | # sample index | ||
| 653 | my $indices; | ||
| 654 | if(defined $rsp_indices) | ||
| 655 | { | ||
| 656 | $indices = $rsp_indices; | ||
| 657 | assert($indices->nelem <= $shape->[0]); | ||
| 658 | } | ||
| 659 | else | ||
| 660 | { | ||
| 661 | my $idx_sample = random($shape->[0]); | ||
| 662 | $indices = which($idx_sample < $density); | ||
| 663 | } | ||
| 664 | if($indices->shape(-1)->at(0) == 0) | ||
| 665 | { | ||
| 666 | my $result = mx->nd->zeros($shape, stype=>'row_sparse', dtype=>$dtype); | ||
| 667 | return ($result, [pdl([]), pdl([])]); | ||
| 668 | } | ||
| 669 | # generate random values | ||
| 670 | my $val = random(PDL::Type->new(DTYPE_MX_TO_PDL->{ $dtype }), reverse($indices->shape(-1)->at(0), @{ $shape }[1..@{ $shape }-1])); | ||
| 671 | |||
| 672 | # Allow caller to override or adjust random values | ||
| 673 | if(defined $data_init) | ||
| 674 | { | ||
| 675 | $val .= $data_init; | ||
| 676 | } | ||
| 677 | if(defined $modifier_func) | ||
| 678 | { | ||
| 679 | $val = assign_each($val, $modifier_func); | ||
| 680 | } | ||
| 681 | my $arr = mx->nd->sparse->row_sparse_array([$val, $indices], shape=>$shape, dtype=>$dtype); | ||
| 682 | return ($arr, [$val, $indices]); | ||
| 683 | } | ||
| 684 | elsif($stype eq 'csr') | ||
| 685 | { | ||
| 686 | assert(@{ $shape } == 2); | ||
| 687 | my $csr; | ||
| 688 | if($distribution eq "uniform") | ||
| 689 | { | ||
| 690 | $csr = _get_uniform_dataset_csr( | ||
| 691 | @{ $shape }, $density, $dtype, | ||
| 692 | $data_init, $shuffle_csr_indices | ||
| 693 | ); | ||
| 694 | return ($csr, [$csr->indptr, $csr->indices, $csr->data]); | ||
| 695 | } | ||
| 696 | elsif($distribution eq "powerlaw") | ||
| 697 | { | ||
| 698 | $csr = _get_powerlaw_dataset_csr(@{ $shape }, $density, $dtype); | ||
| 699 | return ($csr, [$csr->indptr, $csr->indices, $csr->data]); | ||
| 700 | } | ||
| 701 | else | ||
| 702 | { | ||
| 703 | confess("Distribution not supported: $distribution"); | ||
| 704 | } | ||
| 705 | } | ||
| 706 | else | ||
| 707 | { | ||
| 708 | confess("unknown storage type"); | ||
| 709 | } | ||
| 710 | } | ||
| 711 | |||
| 712 | func rand_ndarray( | ||
| 713 | $shape, $stype, $density=rand, $dtype='float32', | ||
| 714 | $modifier_func=, $shuffle_csr_indices=0, $distribution='uniform' | ||
| 715 | ) | ||
| 716 | { | ||
| 717 | my $arr; | ||
| 718 | if($stype eq 'default') | ||
| 719 | { | ||
| 720 | $arr = mx->nd->array(random_arrays($shape), dtype=>$dtype); | ||
| 721 | } | ||
| 722 | else | ||
| 723 | { | ||
| 724 | ($arr) = rand_sparse_ndarray( | ||
| 725 | $shape, $stype, density => $density, dtype => $dtype, | ||
| 726 | modifier_func => $modifier_func, | ||
| 727 | shuffle_csr_indices => $shuffle_csr_indices, distribution => $distribution | ||
| 728 | ); | ||
| 729 | } | ||
| 730 | return $arr; | ||
| 731 | } | ||
| 732 | |||
| 733 | |||
| 734 | func create_sparse_array( | ||
| 735 | $shape, $stype, $data_init=, $rsp_indices=, | ||
| 736 | $dtype=, $modifier_func=, $density=0.5, | ||
| 737 | $shuffle_csr_indices=0 | ||
| 738 | ) | ||
| 739 | { | ||
| 740 | my $arr_data; | ||
| 741 | if($stype eq 'row_sparse') | ||
| 742 | { | ||
| 743 | my $arr_indices; | ||
| 744 | if(defined $rsp_indices) | ||
| 745 | { | ||
| 746 | $arr_indices = pdl($rsp_indices); | ||
| 747 | $arr_indices->inplace->qsort; | ||
| 748 | } | ||
| 749 | ($arr_data) = rand_sparse_ndarray( | ||
| 750 | $shape, $stype, | ||
| 751 | $density, $dtype, | ||
| 752 | $data_init, | ||
| 753 | $arr_indices, | ||
| 754 | $modifier_func | ||
| 755 | ); | ||
| 756 | } | ||
| 757 | elsif($stype eq 'csr') | ||
| 758 | { | ||
| 759 | ($arr_data) = rand_sparse_ndarray( | ||
| 760 | $shape, | ||
| 761 | $stype, | ||
| 762 | $density, $dtype, | ||
| 763 | $data_init, | ||
| 764 | $modifier_func, | ||
| 765 | $shuffle_csr_indices | ||
| 766 | ); | ||
| 767 | } | ||
| 768 | else | ||
| 769 | { | ||
| 770 | confess("Unknown storage type: $stype"); | ||
| 771 | } | ||
| 772 | return $arr_data; | ||
| 773 | } | ||
| 774 | |||
| 775 | |||
| 776 | func create_sparse_array_zd( | ||
| 777 | $shape, $stype, $density, $data_init=, | ||
| 778 | $rsp_indices=, $dtype=, $modifier_func=, | ||
| 779 | $shuffle_csr_indices=0 | ||
| 780 | ) | ||
| 781 | { | ||
| 782 | if($stype eq 'row_sparse') | ||
| 783 | { | ||
| 784 | $density = 0; | ||
| 785 | if(defined $rsp_indices) | ||
| 786 | { | ||
| 787 | assert($rsp_indices->len <= $shape->[0]); | ||
| 788 | } | ||
| 789 | } | ||
| 790 | return create_sparse_array( | ||
| 791 | $shape, $stype, | ||
| 792 | $data_init, | ||
| 793 | $rsp_indices, | ||
| 794 | $dtype, | ||
| 795 | $modifier_func, | ||
| 796 | $density, | ||
| 797 | $shuffle_csr_indices | ||
| 798 | ); | ||
| 799 | } | ||
| 800 | |||
| 801 | func rand_shape_2d($dim0=10, $dim1=10) | ||
| 802 | { | ||
| 803 | [int(rand($dim0)+1), int(rand($dim1)+1)]; | ||
| 804 | } | ||
| 805 | |||
| 806 | |||
| 807 | func rand_shape_3d($dim0=10, $dim1=10, $dim2=10) | ||
| 808 | { | ||
| 809 | [int(rand($dim0)+1), int(rand($dim1)+1), int(rand($dim1)+1)]; | ||
| 810 | } | ||
| 811 | |||
| 812 | |||
| 813 | func rand_shape_nd($num_dim, $dim=10) | ||
| 814 | { | ||
| 815 | (random($num_dim)*$dim+1)->floor->unpdl; | ||
| 816 | } | ||
| 817 | |||
| 818 | func randint($low=0, $high=10) | ||
| 819 | { | ||
| 820 | my $value = int(rand($high)); | ||
| 821 | return $value < $low ? $low : $value; | ||
| 822 | } | ||
| 823 | |||
| 824 | sub dies_ok | ||
| 825 | { | ||
| 826 | my $sub = shift; | ||
| 827 | eval { $sub->() }; | ||
| 828 | if($@) | ||
| 829 | { | ||
| 830 | Test::More::ok(1); | ||
| 831 | } | ||
| 832 | else | ||
| 833 | { | ||
| 834 | Test::More::ok(0); | ||
| 835 | } | ||
| 836 | } | ||
| 837 | |||
| 838 | 1; |