| 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 | use strict; | ||
| 19 | use warnings; | ||
| 20 | use Hash::Ordered; | ||
| 21 | package AI::MXNet::Gluon::Parameter; | ||
| 22 | use AI::MXNet::NS; | ||
| 23 | use AI::MXNet::Function::Parameters; | ||
| 24 | |||
| 25 | =head1 NAME | ||
| 26 | |||
| 27 | AI::MXNet::Gluon::Parameter - A Container holding parameters (weights) of AI::MXNEt::Gluon::Block(s). | ||
| 28 | =cut | ||
| 29 | |||
| 30 | =head1 DESCRIPTION | ||
| 31 | |||
| 32 | AI::MXNet::Gluon::Parameter holds a copy of the parameter on each AI::MXNet::Context after | ||
| 33 | it is initialized with AI::MXNet::Gluon::Parameter->initialize(...)`. If grad_req is | ||
| 34 | not 'null', it will also hold a gradient array on each AI::MXNet::Context | ||
| 35 | |||
| 36 | $ctx = mx->gpu(0); | ||
| 37 | $x = mx->nd->zeros([16, 100], ctx=>$ctx); | ||
| 38 | $w = mx->gluon->Parameter('fc_weight', shape=>[64, 100], init=>mx->init->Xavier()); | ||
| 39 | $b = mx->gluon->Parameter('fc_bias', shape=>[64], init=>mx->init->Zero()); | ||
| 40 | $w->initialize(ctx=>$ctx); | ||
| 41 | $b->initialize(ctx=>ctx); | ||
| 42 | $out = mx->nd->FullyConnected($x, $w->data($ctx), $b->data($ctx), num_hidden=>64); | ||
| 43 | |||
| 44 | Parameters | ||
| 45 | ---------- | ||
| 46 | name : str | ||
| 47 | Name of this parameter. | ||
| 48 | grad_req : {'write', 'add', 'null'}, default 'write' | ||
| 49 | Specifies how to update gradient to grad arrays. | ||
| 50 | |||
| 51 | - 'write' means everytime gradient is written to grad NDArray. | ||
| 52 | - 'add' means everytime gradient is added to the grad NDArray. You need | ||
| 53 | to manually call zero_grad() to clear the gradient buffer before each | ||
| 54 | iteration when using this option. | ||
| 55 | - 'null' means gradient is not requested for this parameter. gradient arrays | ||
| 56 | will not be allocated. | ||
| 57 | shape : array ref of int or int, default undef | ||
| 58 | Shape of this parameter. By default shape is not specified. Parameter with | ||
| 59 | unknown shape can be used for `Symbol` API, but `init` will throw an error | ||
| 60 | when using `NDArray` API. | ||
| 61 | dtype : Dtype, default 'float32' | ||
| 62 | Data type of this parameter. For example, 'float64'. | ||
| 63 | lr_mult : float, default 1.0 | ||
| 64 | Learning rate multiplier. Learning rate will be multiplied by lr_mult | ||
| 65 | when updating this parameter with optimizer. | ||
| 66 | wd_mult : float, default 1.0 | ||
| 67 | Weight decay multiplier (L2 regularizer coefficient). Works similar to lr_mult. | ||
| 68 | init : Initializer, default None | ||
| 69 | Initializer of this parameter. Will use the global initializer by default. | ||
| 70 | stype: {'default', 'row_sparse', 'csr'}, defaults to 'default'. | ||
| 71 | The storage type of the parameter. | ||
| 72 | grad_stype: {'default', 'row_sparse', 'csr'}, defaults to 'default'. | ||
| 73 | The storage type of the parameter's gradient. | ||
| 74 | |||
| 75 | |||
| 76 | Attributes | ||
| 77 | ---------- | ||
| 78 | grad_req : {'write', 'add', 'null'} | ||
| 79 | This can be set before or after initialization. Setting grad_req to null | ||
| 80 | with $x->grad_req = 'null' saves memory and computation when you don't | ||
| 81 | need gradient w.r.t x. | ||
| 82 | =cut | ||
| 83 | |||
| 84 | use Mouse; | ||
| 85 | use AI::MXNet::Base; | ||
| 86 | use overload '""' => sub { | ||
| 87 | my $self = shift; | ||
| 88 | "Parameter " . $self->name. | ||
| 89 | " (shape=(" . join(', ', @{ $self->shape//[] }) .")". | ||
| 90 | ", dtype=" . $self->dtype. | ||
| 91 | ", stype=" . $self->stype.")" | ||
| 92 | }, | ||
| 93 | fallback => 1; | ||
| 94 | |||
| 95 | around BUILDARGS => sub { | ||
| 96 | my $orig = shift; | ||
| 97 | my $class = shift; | ||
| 98 | if(@_ % 2) | ||
| 99 | { | ||
| 100 | my $name = shift; | ||
| 101 | return $class->$orig(name => $name, @_); | ||
| 102 | } | ||
| 103 | else | ||
| 104 | { | ||
| 105 | return $class->$orig(@_); | ||
| 106 | } | ||
| 107 | }; | ||
| 108 | |||
| 109 | sub BUILD | ||
| 110 | { | ||
| 111 | my $self = shift; | ||
| 112 | $self->grad_req($self->_grad_req); | ||
| 113 | $self->_shape([$self->_shape]) if defined $self->_shape and not ref $self->_shape; | ||
| 114 | $self->_deferred_init([]); | ||
| 115 | } | ||
| 116 | |||
| 117 | has 'name' => (is => 'ro', isa => 'Str', required => 1); | ||
| 118 | has '_grad_req' => (is => 'rw', isa => 'GradReq', init_arg => 'grad_req', default => 'write'); | ||
| 119 | has '_shape' => (is => 'rw', isa => 'Maybe[Shape|Int]', init_arg => 'shape'); | ||
| 120 | has 'dtype' => (is => 'rw', isa => 'Dtype', default => 'float32'); | ||
| 121 | has ['stype', | ||
| 122 | 'grad_stype'] => (is => 'rw', isa => 'Stype', default => 'default'); | ||
| 123 | has [qw/lr_mult wd_mult/] => (is => 'rw', isa => 'Num', default => 1); | ||
| 124 | has 'init' => (is => 'rw', isa => 'Maybe[Initializer]'); | ||
| 125 | has 'allow_deferred_init' => (is => 'rw', isa => 'Bool', default => 0); | ||
| 126 | has 'differentiable' => (is => 'rw', isa => 'Bool', default => 1); | ||
| 127 | has [qw/_var _data _grad | ||
| 128 | _deferred_init _trainer | ||
| 129 | _ctx_list _ctx_map/] => (is => 'rw', init_arg => undef); | ||
| 130 | |||
| 131 | method grad_req(Maybe[GradReq] $req=) | ||
| 132 | { | ||
| 133 | return $self->_grad_req unless defined $req; | ||
| 134 | if(not $self->differentiable) | ||
| 135 | { | ||
| 136 | $req = 'null'; | ||
| 137 | } | ||
| 138 | return if $self->_grad_req eq $req; | ||
| 139 | $self->_grad_req($req); | ||
| 140 | if($req eq 'null' and defined $self->_grad) | ||
| 141 | { | ||
| 142 | $self->_grad(undef); | ||
| 143 | $self->_data([map { $_->detach } @{ $self->_data }]); | ||
| 144 | } | ||
| 145 | elsif(defined $self->_data) | ||
| 146 | { | ||
| 147 | $self->_init_grad(); | ||
| 148 | } | ||
| 149 | } | ||
| 150 | |||
| 151 | method shape(@args) | ||
| 152 | { | ||
| 153 | return $self->_shape unless @args; | ||
| 154 | if(not defined $args[0]) | ||
| 155 | { | ||
| 156 | $self->_shape(undef); | ||
| 157 | return undef; | ||
| 158 | } | ||
| 159 | if(not defined $self->_shape and defined $args[0]) | ||
| 160 | { | ||
| 161 | $self->_shape(ref $args[0] ? $args[0] : [$args[0]]); | ||
| 162 | return $self->_shape; | ||
| 163 | } | ||
| 164 | my $new_shape = ref $args[0] ? $args[0] : [$args[0]]; | ||
| 165 | my $shape_validated = 0; | ||
| 166 | if(@{ $self->_shape } == @{ $new_shape }) | ||
| 167 | { | ||
| 168 | $shape_validated = 1; | ||
| 169 | zip(sub { | ||
| 170 | my ($i, $j) = @_; | ||
| 171 | return unless $i; | ||
| 172 | return if $i == $j; | ||
| 173 | $shape_validated = 0; | ||
| 174 | }, $self->_shape, $new_shape); | ||
| 175 | } | ||
| 176 | assert($shape_validated, 'Expected shape is incompatible with given shape'); | ||
| 177 | $self->_shape($new_shape); | ||
| 178 | return $self->_shape; | ||
| 179 | } | ||
| 180 | |||
| 181 | method _set_trainer($trainer) | ||
| 182 | { | ||
| 183 | if($self->stype ne 'default' and $self->_trainer and $trainer and Scalar::Util::refaddr($self->_trainer) ne Scalar::Util::refaddr($trainer)) | ||
| 184 | { | ||
| 185 | confess( | ||
| 186 | "Failed to set the trainer for Parameter '${\ $self->name }' because it was already set. ". | ||
| 187 | "More than one trainers for a ${\ $self->stype } Parameter is not supported." | ||
| 188 | ); | ||
| 189 | } | ||
| 190 | $self->_trainer($trainer); | ||
| 191 | } | ||
| 192 | |||
| 193 | method _get_row_sparse($arr_list, $ctx, AI::MXNet::NDArray $row_id) | ||
| 194 | { | ||
| 195 | if(not $self->_trainer) | ||
| 196 | { | ||
| 197 | confess( | ||
| 198 | "Cannot get row_sparse data for Parameter '${\ $self->name }' when no ". | ||
| 199 | "Trainer is created with it." | ||
| 200 | ); | ||
| 201 | } | ||
| 202 | my $results = $self->_check_and_get($arr_list, $ctx); | ||
| 203 | |||
| 204 | # fetch row sparse params from the trainer | ||
| 205 | $self->_trainer->_row_sparse_pull($self, $results, $row_id); | ||
| 206 | return $results; | ||
| 207 | } | ||
| 208 | |||
| 209 | method _check_and_get($arr_list, $ctx) | ||
| 210 | { | ||
| 211 | if(defined $arr_list) | ||
| 212 | { | ||
| 213 | if(ref $ctx eq 'ARRAY') | ||
| 214 | { | ||
| 215 | return $arr_list; | ||
| 216 | } | ||
| 217 | if(not defined $ctx) | ||
| 218 | { | ||
| 219 | if(@{ $arr_list } == 1) | ||
| 220 | { | ||
| 221 | return $arr_list->[0]; | ||
| 222 | } | ||
| 223 | else | ||
| 224 | { | ||
| 225 | $ctx = AI::MXNet::Context->current_ctx; | ||
| 226 | } | ||
| 227 | } | ||
| 228 | my $ctx_list = $self->_ctx_map->[$ctx->device_type_id&1]; | ||
| 229 | if($ctx->device_id < @{ $ctx_list }) | ||
| 230 | { | ||
| 231 | my $idx = $ctx_list->[$ctx->device_id]; | ||
| 232 | if(defined $idx) | ||
| 233 | { | ||
| 234 | return $arr_list->[$idx]; | ||
| 235 | } | ||
| 236 | } | ||
| 237 | confess( | ||
| 238 | "Parameter '${\ $self->name }' was not initialized on context $ctx. ". | ||
| 239 | "It was only initialized on @{ $self->_ctx_list }." | ||
| 240 | ); | ||
| 241 | } | ||
| 242 | if(@{ $self->_deferred_init }) | ||
| 243 | { | ||
| 244 | confess("DeferredInitializationError: ". | ||
| 245 | "Parameter '${\ $self->name }' has not been initialized yet because initialization was ". | ||
| 246 | "deferred. Actual initialization happens during the first forward pass. ". | ||
| 247 | "Please pass one batch of data through the network before accessing Parameters. ". | ||
| 248 | "You can also avoid deferred initialization by specifying in_units, ". | ||
| 249 | "num_features, etc., for network layers."); | ||
| 250 | } | ||
| 251 | confess( | ||
| 252 | "Parameter '${\ $self->name }' has not been initialized. Note that ". | ||
| 253 | "you should initialize parameters and create Trainer ". | ||
| 254 | "with Block.collect_params() instead of Block.params ". | ||
| 255 | "because the later does not include Parameters of ". | ||
| 256 | "nested child Blocks" | ||
| 257 | ); | ||
| 258 | } | ||
| 259 | |||
| 260 | |||
| 261 | # (Re)initializes by loading from data. | ||
| 262 | method _load_init($data, $ctx) | ||
| 263 | { | ||
| 264 | if($self->shape) | ||
| 265 | { | ||
| 266 | for(zip($self->shape, $data->shape)) { | ||
| 267 | my ($self_dim, $data_dim) = @$_; | ||
| 268 | assert( | ||
| 269 | ($self_dim == 0 or $self_dim == $data_dim), | ||
| 270 | sprintf( | ||
| 271 | "Failed loading Parameter '%s' from saved params: ". | ||
| 272 | "shape incompatible expected (%s) vs saved (%s)", | ||
| 273 | $self->name, "@{$self->shape}", "@{$data->shape}" | ||
| 274 | ) | ||
| 275 | ); | ||
| 276 | } | ||
| 277 | $self->shape([map { $_->[0] ? $_->[0] : $_->[1] } zip($self->shape, $data->shape)]); | ||
| 278 | } | ||
| 279 | if($self->dtype) | ||
| 280 | { | ||
| 281 | assert( | ||
| 282 | ($self->dtype eq $data->dtype), | ||
| 283 | sprintf( | ||
| 284 | "Failed loading Parameter '%s' from saved params: ". | ||
| 285 | "dtype incompatible expected %s vs saved %s", | ||
| 286 | $self->name, $self->dtype, $data->dtype | ||
| 287 | ) | ||
| 288 | ); | ||
| 289 | } | ||
| 290 | if($self->stype ne $data->stype) | ||
| 291 | { | ||
| 292 | $data = $data->tostype($self->stype); | ||
| 293 | } | ||
| 294 | |||
| 295 | if(blessed ($ctx) and $ctx->isa('AI::MXNet::Context')) | ||
| 296 | { | ||
| 297 | $ctx = [$ctx]; | ||
| 298 | } | ||
| 299 | if(not defined $self->_data) | ||
| 300 | { | ||
| 301 | if(@{ $self->_deferred_init }) | ||
| 302 | { | ||
| 303 | assert( | ||
| 304 | (not defined $ctx or join('', @{ $ctx }) eq join('', @{ $self->_deferred_init->[1] })), | ||
| 305 | sprintf( | ||
| 306 | "Failed to load Parameter '%s' on %s because it was ". | ||
| 307 | "previously initialized on %s.", | ||
| 308 | $self->name, $ctx, $self->list_ctx | ||
| 309 | ) | ||
| 310 | ); | ||
| 311 | $ctx = $self->_deferred_init->[1]; | ||
| 312 | } | ||
| 313 | elsif(not defined $ctx) | ||
| 314 | { | ||
| 315 | $ctx = [AI::MXNet::Context->cpu]; | ||
| 316 | } | ||
| 317 | $self->_init_impl($data, $ctx); | ||
| 318 | } | ||
| 319 | else | ||
| 320 | { | ||
| 321 | assert( | ||
| 322 | (not defined $ctx or join('', @{ $ctx }) eq join('', @{ $self->list_ctx })), | ||
| 323 | sprintf( | ||
| 324 | "Failed to load Parameter '%s' on %s because it was ". | ||
| 325 | "previously initialized on %s.", | ||
| 326 | $self->name, "@$ctx", "@{$self->list_ctx}" | ||
| 327 | ) | ||
| 328 | ); | ||
| 329 | $self->set_data($data); | ||
| 330 | } | ||
| 331 | $self->_deferred_init([]); | ||
| 332 | } | ||
| 333 | |||
| 334 | # Finishes deferred initialization. | ||
| 335 | method _finish_deferred_init() | ||
| 336 | { | ||
| 337 | return unless @{ $self->_deferred_init }; | ||
| 338 | my ($init, $ctx, $default_init, $data) = @{ $self->_deferred_init }; | ||
| 339 | $self->_deferred_init([]); | ||
| 340 | assert( | ||
| 341 | (defined($self->shape) and product(@{ $self->shape }) > 0), | ||
| 342 | sprintf( | ||
| 343 | "Cannot initialize Parameter '%s' because it has ". | ||
| 344 | "invalid shape: %s. Please specify in_units, ". | ||
| 345 | "in_channels, etc for `Block`s.", | ||
| 346 | $self->name, $self->shape | ||
| 347 | ) | ||
| 348 | ); | ||
| 349 | AI::MXNet::AutoGrad->pause(sub { | ||
| 350 | if(not defined $data) | ||
| 351 | { | ||
| 352 | $data = AI::MXNet::NDArray->zeros( | ||
| 353 | $self->shape, | ||
| 354 | dtype => $self->dtype, | ||
| 355 | ctx => AI::MXNet::Context->cpu, | ||
| 356 | stype => $self->stype | ||
| 357 | ); | ||
| 358 | AI::MXNet::Initializer->new->( | ||
| 359 | AI::MXNet::InitDesc->new( | ||
| 360 | name => $self->name, | ||
| 361 | attrs => { __init__ => defined $init ? "$init" : "$default_init" } | ||
| 362 | ), | ||
| 363 | $data | ||
| 364 | ); | ||
| 365 | } | ||
| 366 | $self->_init_impl($data, $ctx); | ||
| 367 | }); | ||
| 368 | } | ||
| 369 | |||
| 370 | # Sets data and grad. | ||
| 371 | method _init_impl($data, $ctx_list) | ||
| 372 | { | ||
| 373 | $self->_ctx_list([@{ $ctx_list }]); | ||
| 374 | $self->_ctx_map([[], []]); | ||
| 375 | enumerate(sub { | ||
| 376 | my ($i, $ctx) = @_; | ||
| 377 | my $dev_list = $self->_ctx_map->[$ctx->device_type_id&1]; | ||
| 378 | while(@{ $dev_list } <= $ctx->device_id) | ||
| 379 | { | ||
| 380 | push @{ $dev_list }, undef; | ||
| 381 | } | ||
| 382 | $dev_list->[$ctx->device_id] = $i; | ||
| 383 | }, $self->_ctx_list); | ||
| 384 | $self->_data([map { $data->copyto($_) } @{ $self->_ctx_list }]); | ||
| 385 | $self->_init_grad; | ||
| 386 | } | ||
| 387 | |||
| 388 | # Initialize grad buffers. | ||
| 389 | method _init_grad() | ||
| 390 | { | ||
| 391 | if($self->grad_req eq 'null') | ||
| 392 | { | ||
| 393 | $self->_grad(undef); | ||
| 394 | return; | ||
| 395 | } | ||
| 396 | $self->_grad([ | ||
| 397 | map { | ||
| 398 | AI::MXNet::NDArray->zeros( | ||
| 399 | $_->shape, dtype => $_->dtype, | ||
| 400 | ctx => $_->context, stype => $self->grad_stype | ||
| 401 | ) | ||
| 402 | } @{ $self->_data } | ||
| 403 | ]); | ||
| 404 | AI::MXNet::AutoGrad->mark_variables( | ||
| 405 | $self->_check_and_get($self->_data, []), | ||
| 406 | $self->_grad, | ||
| 407 | grad_reqs => $self->grad_req | ||
| 408 | ); | ||
| 409 | } | ||
| 410 | |||
| 411 | # Reduce data from multiple contexts to cpu. | ||
| 412 | method _reduce() | ||
| 413 | { | ||
| 414 | my $data; | ||
| 415 | my $ctx = AI::MXNet::Context->cpu; | ||
| 416 | if($self->stype eq 'default') | ||
| 417 | { | ||
| 418 | my $block = $self->list_data; | ||
| 419 | $data = AI::MXNet::NDArray->add_n(map { $_->copyto($ctx) } @{ $block }) / @{ $block }; | ||
| 420 | } | ||
| 421 | else | ||
| 422 | { | ||
| 423 | my $all_row_ids = AI::MXNet::NDArray->arange(stop => $self->shape->[0], dtype=>'int64', ctx=>$ctx); | ||
| 424 | $data = AI::MXNet::NDArray->zeros($self->shape, stype=>'row_sparse', ctx=>$ctx); | ||
| 425 | $self->_trainer->_row_sparse_pull($self, $data, $all_row_ids, 1); | ||
| 426 | } | ||
| 427 | return $data; | ||
| 428 | } | ||
| 429 | |||
| 430 | =head2 initialize | ||
| 431 | |||
| 432 | Initializes parameter and gradient arrays. Only used for `NDArray` API. | ||
| 433 | |||
| 434 | Parameters | ||
| 435 | ---------- | ||
| 436 | :$init : Initializer | ||
| 437 | The initializer to use. Overrides AI::MXNet::Gluon::Parameter->init and default_init. | ||
| 438 | :$ctx : AI::MXNet::Context or array ref of AI::MXNet::Context, defaults to AI::MXNet::Context->current_ctx(). | ||
| 439 | Initialize Parameter on given context. If ctx is a list of Context, a | ||
| 440 | copy will be made for each context. | ||
| 441 | Copies are independent arrays. User is responsible for keeping | ||
| 442 | their values consistent when updating. Normally gluon->Trainer does this for you. | ||
| 443 | :$default_init : Initializer | ||
| 444 | Default initializer is used when both 'init' and AI::MXNet::Gluon::Parameter->init are undefined. | ||
| 445 | :$force_reinit : bool, default False | ||
| 446 | Whether to force re-initialization if parameter is already initialized. | ||
| 447 | |||
| 448 | Examples | ||
| 449 | -------- | ||
| 450 | >>> $weight = mx->gluon->Parameter('weight', shape=>[2, 2]); | ||
| 451 | >>> $weight->initialize(ctx=>mx->cpu(0)); | ||
| 452 | >>> print $weight->data | ||
| 453 | [[-0.01068833 0.01729892] | ||
| 454 | [ 0.02042518 -0.01618656]] | ||
| 455 | <NDArray 2x2 @cpu(0)> | ||
| 456 | >>> print $weight->grad() | ||
| 457 | [[ 0. 0.] | ||
| 458 | [ 0. 0.]] | ||
| 459 | <NDArray 2x2 @cpu(0)> | ||
| 460 | >>> $weight->initialize(ctx=>[mx->gpu(0), mx->gpu(1)]); | ||
| 461 | >>> print $weight->data(mx->gpu(0)); | ||
| 462 | [[-0.00873779 -0.02834515] | ||
| 463 | [ 0.05484822 -0.06206018]] | ||
| 464 | <NDArray 2x2 @gpu(0)> | ||
| 465 | >>> print $weight->data(mx->gpu(1)) | ||
| 466 | [[-0.00873779 -0.02834515] | ||
| 467 | [ 0.05484822 -0.06206018]] | ||
| 468 | <NDArray 2x2 @gpu(1)> | ||
| 469 | =cut | ||
| 470 | |||
| 471 | method initialize( | ||
| 472 | Maybe[Initializer] :$init=, | ||
| 473 | Maybe[AI::MXNet::Context|ArrayRef[AI::MXNet::Context]] :$ctx=AI::MXNet::Context->current_ctx, | ||
| 474 | Initializer :$default_init=AI::MXNet::Initializer->Uniform, | ||
| 475 | Bool :$force_reinit=0 | ||
| 476 | ) | ||
| 477 | { | ||
| 478 | $ctx //=AI::MXNet::Context->current_ctx; | ||
| 479 | if(defined $self->_data and not $force_reinit) | ||
| 480 | { | ||
| 481 | AI::MXNet::Logging->warning( | ||
| 482 | "Parameter '%s' is already initialized, ignoring. ". | ||
| 483 | "Set force_reinit=True to re-initialize.", $self->name | ||
| 484 | ); | ||
| 485 | return; | ||
| 486 | } | ||
| 487 | $self->_data(undef); | ||
| 488 | $self->_grad(undef); | ||
| 489 | if(blessed($ctx) and $ctx->isa('AI::MXNet::Context')) | ||
| 490 | { | ||
| 491 | $ctx = [$ctx]; | ||
| 492 | } | ||
| 493 | if(not defined $init) | ||
| 494 | { | ||
| 495 | if(defined $self->init) | ||
| 496 | { | ||
| 497 | $init = $self->init; | ||
| 498 | } | ||
| 499 | else | ||
| 500 | { | ||
| 501 | $init = $default_init; | ||
| 502 | } | ||
| 503 | } | ||
| 504 | if(not defined $self->shape or not @{ $self->shape } or product(@{ $self->shape }) <= 0) | ||
| 505 | { | ||
| 506 | if($self->allow_deferred_init) | ||
| 507 | { | ||
| 508 | $self->_deferred_init([$init, $ctx, $default_init, undef]); | ||
| 509 | return; | ||
| 510 | } | ||
| 511 | confess("Cannot initialize Parameter '${\ $self->name }' because it has ". | ||
| 512 | "invalid shape: @{$self->shape//[]}."); | ||
| 513 | } | ||
| 514 | $self->_deferred_init([$init, $ctx, $default_init, undef]); | ||
| 515 | $self->_finish_deferred_init; | ||
| 516 | } | ||
| 517 | |||
| 518 | =head2 reset_ctx | ||
| 519 | |||
| 520 | Re-assign Parameter to other contexts. | ||
| 521 | |||
| 522 | :$ctx : AI::MXNet::Context or array ref of AI::MXNet::Context, default AI::MXNet::Context->current_ctx. | ||
| 523 | Assign Parameter to given context. If ctx is a list of Context, a | ||
| 524 | copy will be made for each context. | ||
| 525 | =cut | ||
| 526 | |||
| 527 | method reset_ctx(Maybe[AI::MXNet::Context|ArrayRef[AI::MXNet::Context]] :$ctx=AI::MXNet::Context->current_ctx) | ||
| 528 | { | ||
| 529 | if(blessed($ctx) and $ctx->isa('AI::MXNet::Context')) | ||
| 530 | { | ||
| 531 | $ctx = [$ctx]; | ||
| 532 | } | ||
| 533 | if(defined $self->_data) | ||
| 534 | { | ||
| 535 | my $data = $self->_reduce; | ||
| 536 | AI::MXNet::AutoGrad->pause(sub { | ||
| 537 | $self->_init_impl($data, $ctx); | ||
| 538 | }); | ||
| 539 | } | ||
| 540 | elsif(@{ $self->_deferred_init }) | ||
| 541 | { | ||
| 542 | my ($init, undef, $default_init, $data) = @{ $self->_deferred_init }; | ||
| 543 | $self->_deferred_init([$init, $ctx, $default_init, $data]); | ||
| 544 | } | ||
| 545 | else | ||
| 546 | { | ||
| 547 | confess("Cannot reset context for Parameter '${ \ $self->name }' because it ". | ||
| 548 | "has not been initialized."); | ||
| 549 | } | ||
| 550 | } | ||
| 551 | |||
| 552 | =head2 set_data | ||
| 553 | |||
| 554 | Sets this parameter's value on all contexts to data. | ||
| 555 | =cut | ||
| 556 | |||
| 557 | method set_data($data) | ||
| 558 | { | ||
| 559 | $self->shape($data->shape); | ||
| 560 | if(not defined $self->_data) | ||
| 561 | { | ||
| 562 | assert( | ||
| 563 | (@{ $self->_deferred_init }), | ||
| 564 | "Parameter '${\ $self->name }' has not been initialized" | ||
| 565 | ); | ||
| 566 | $self->_deferred_init->[3] = $data; | ||
| 567 | return; | ||
| 568 | } | ||
| 569 | |||
| 570 | # if update_on_kvstore, we need to make sure the copy stored in kvstore is in sync | ||
| 571 | if($self->_trainer and $self->_trainer->_kv_initialized and $self->_trainer->update_on_kvstore) | ||
| 572 | { | ||
| 573 | if(!grep { Scalar::Util::refaddr($self) == Scalar::Util::refaddr($_) } @{ $self->_trainer->_params_to_init }) | ||
| 574 | { | ||
| 575 | $self->_trainer->_reset_kvstore(); | ||
| 576 | } | ||
| 577 | } | ||
| 578 | for my $arr (@{ $self->_check_and_get($self->_data, []) }) | ||
| 579 | { | ||
| 580 | $arr .= $data; | ||
| 581 | } | ||
| 582 | } | ||
| 583 | |||
| 584 | =head2 row_sparse_data | ||
| 585 | |||
| 586 | Returns a copy of the 'row_sparse' parameter on the same context as row_id's. | ||
| 587 | The copy only retains rows whose ids occur in provided row ids. | ||
| 588 | The parameter must have been initialized on this context before. | ||
| 589 | |||
| 590 | Parameters | ||
| 591 | ---------- | ||
| 592 | $row_id: AI::MXNet::NDArray | ||
| 593 | Row ids to retain for the 'row_sparse' parameter. | ||
| 594 | |||
| 595 | Returns | ||
| 596 | ------- | ||
| 597 | AI::MXNet::NDArray on row_id's context | ||
| 598 | =cut | ||
| 599 | |||
| 600 | method row_sparse_data(AI::MXNet::NDArray $row_id) | ||
| 601 | { | ||
| 602 | if($self->stype ne 'row_sparse') | ||
| 603 | { | ||
| 604 | confess( | ||
| 605 | "Cannot return a copy of Parameter ${\ $self->name } via row_sparse_data() ". | ||
| 606 | "because its storage type is ${\ $self->stype }. Please use data() instead." | ||
| 607 | ); | ||
| 608 | } | ||
| 609 | return $self->_get_row_sparse($self->_data, $row_id->context, $row_id); | ||
| 610 | } | ||
| 611 | |||
| 612 | =head2 list_row_sparse_data | ||
| 613 | |||
| 614 | Returns copies of the 'row_sparse' parameter on all contexts, in the same order | ||
| 615 | as creation. The copy only retains rows whose ids occur in provided row ids. | ||
| 616 | The parameter must have been initialized before. | ||
| 617 | |||
| 618 | Parameters | ||
| 619 | ---------- | ||
| 620 | $row_id: AI::MXNet::NDArray | ||
| 621 | Row ids to retain for the 'row_sparse' parameter. | ||
| 622 | |||
| 623 | Returns | ||
| 624 | ------- | ||
| 625 | array ref of AI::MXNet::NDArrays | ||
| 626 | =cut | ||
| 627 | |||
| 628 | method list_row_sparse_data(AI::MXNet::NDArray $row_id) | ||
| 629 | { | ||
| 630 | if($self->stype ne 'row_sparse') | ||
| 631 | { | ||
| 632 | confess( | ||
| 633 | "Cannot return copies of Parameter '${\ $self->name }' on all contexts via ". | ||
| 634 | "list_row_sparse_data() because its storage type is ${\ $self->stype }. Please ". | ||
| 635 | "use data() instead." | ||
| 636 | ); | ||
| 637 | } | ||
| 638 | return $self->_get_row_sparse($self->_data, [], $row_id); | ||
| 639 | } | ||
| 640 | |||
| 641 | =head2 data | ||
| 642 | |||
| 643 | Returns a copy of this parameter on one context. Must have been | ||
| 644 | initialized on this context before. For sparse parameters, use | ||
| 645 | row_sparse_data instead. | ||
| 646 | |||
| 647 | Parameters | ||
| 648 | ---------- | ||
| 649 | ctx : Context | ||
| 650 | Desired context. | ||
| 651 | |||
| 652 | Returns | ||
| 653 | ------- | ||
| 654 | NDArray on ctx | ||
| 655 | =cut | ||
| 656 | |||
| 657 | method data(Maybe[AI::MXNet::Context] $ctx=) | ||
| 658 | { | ||
| 659 | if($self->stype ne 'default') | ||
| 660 | { | ||
| 661 | $ctx //= AI::MXNet::Context->current_ctx; | ||
| 662 | confess( | ||
| 663 | "Cannot return a copy of Parameter '${\ $self->name }' on ctx $ctx via data() ". | ||
| 664 | "because its storage type is ${\ $self->stype }. Please use row_sparse_data() ". | ||
| 665 | "instead." | ||
| 666 | ); | ||
| 667 | } | ||
| 668 | return $self->_check_and_get($self->_data, $ctx); | ||
| 669 | } | ||
| 670 | |||
| 671 | =head2 list_data | ||
| 672 | |||
| 673 | Returns copies of this parameter on all contexts, in the same order | ||
| 674 | as creation. For sparse parameters, use list_row_sparse_data | ||
| 675 | instead. | ||
| 676 | =cut | ||
| 677 | |||
| 678 | method list_data() | ||
| 679 | { | ||
| 680 | if($self->stype ne 'default') | ||
| 681 | { | ||
| 682 | confess( | ||
| 683 | "Cannot return a copies of Parameter '${\ $self->data }' on all contexts via list_data() ". | ||
| 684 | "because its storage type is ${\ $self->stype }. Please use row_sparse_data() ". | ||
| 685 | "instead." | ||
| 686 | ); | ||
| 687 | } | ||
| 688 | return $self->_check_and_get($self->_data, []) | ||
| 689 | } | ||
| 690 | |||
| 691 | =head2 grad | ||
| 692 | |||
| 693 | Returns a gradient buffer for this parameter on one context. | ||
| 694 | |||
| 695 | Parameters | ||
| 696 | ---------- | ||
| 697 | ctx : Context | ||
| 698 | Desired context. | ||
| 699 | =cut | ||
| 700 | |||
| 701 | method grad(Maybe [AI::MXNet::Context] $ctx=) | ||
| 702 | { | ||
| 703 | if(defined $self->_data and not defined $self->_grad) | ||
| 704 | { | ||
| 705 | confess( | ||
| 706 | "Cannot get gradient array for Parameter ${\ $self->name } ". | ||
| 707 | "because grad_req='null'" | ||
| 708 | ); | ||
| 709 | } | ||
| 710 | return $self->_check_and_get($self->_grad, $ctx); | ||
| 711 | } | ||
| 712 | |||
| 713 | =head2 list_grad | ||
| 714 | |||
| 715 | Returns gradient buffers on all contexts, in the same order | ||
| 716 | as 'values'. | ||
| 717 | =cut | ||
| 718 | |||
| 719 | method list_grad() | ||
| 720 | { | ||
| 721 | if(defined $self->_data and not defined $self->_grad) | ||
| 722 | { | ||
| 723 | confess( | ||
| 724 | "Cannot get gradient array for Parameter ${\ $self->name } ". | ||
| 725 | "because grad_req='null'" | ||
| 726 | ); | ||
| 727 | } | ||
| 728 | return $self->_check_and_get($self->_grad, []); | ||
| 729 | } | ||
| 730 | |||
| 731 | =head2 list_ctx | ||
| 732 | |||
| 733 | Returns a list of contexts this parameter is initialized on. | ||
| 734 | =cut | ||
| 735 | |||
| 736 | method list_ctx() | ||
| 737 | { | ||
| 738 | if(not defined $self->_data) | ||
| 739 | { | ||
| 740 | if(@{ $self->_deferred_init }) | ||
| 741 | { | ||
| 742 | return $self->_deferred_init->[1]; | ||
| 743 | } | ||
| 744 | confess("Parameter ${\ $self->name } has not been initialized"); | ||
| 745 | } | ||
| 746 | return $self->_ctx_list; | ||
| 747 | } | ||
| 748 | |||
| 749 | =head2 zero_grad | ||
| 750 | |||
| 751 | Sets gradient buffer on all contexts to 0. No action is taken if | ||
| 752 | parameter is uninitialized or doesn't require gradient. | ||
| 753 | =cut | ||
| 754 | |||
| 755 | method zero_grad() | ||
| 756 | { | ||
| 757 | return unless defined $self->_grad; | ||
| 758 | AI::MXNet::NDArray->zeros_like($_, { out => $_ }) for @{ $self->_grad }; | ||
| 759 | } | ||
| 760 | |||
| 761 | =head2 var | ||
| 762 | |||
| 763 | Returns a symbol representing this parameter. | ||
| 764 | =cut | ||
| 765 | |||
| 766 | method var() | ||
| 767 | { | ||
| 768 | if(not defined $self->_var) | ||
| 769 | { | ||
| 770 | $self->_var( | ||
| 771 | AI::MXNet::Symbol->var( | ||
| 772 | $self->name, shape => $self->shape, dtype => $self->dtype, | ||
| 773 | lr_mult => $self->lr_mult, wd_mult => $self->wd_mult, | ||
| 774 | init => $self->init, stype => $self->stype | ||
| 775 | ) | ||
| 776 | ); | ||
| 777 | } | ||
| 778 | return $self->_var; | ||
| 779 | } | ||
| 780 | |||
| 781 | =head2 cast | ||
| 782 | |||
| 783 | Cast data and gradient of this Parameter to a new data type. | ||
| 784 | |||
| 785 | Parameters | ||
| 786 | ---------- | ||
| 787 | $dtype : Dtype | ||
| 788 | The new data type. | ||
| 789 | =cut | ||
| 790 | |||
| 791 | method cast(Dtype $dtype) | ||
| 792 | { | ||
| 793 | $self->dtype($dtype); | ||
| 794 | return unless defined $self->_data; | ||
| 795 | AI::MXNet::AutoGrad->pause(sub { | ||
| 796 | $self->_data([map { $_->astype($dtype) } @{ $self->_data }]); | ||
| 797 | return unless defined $self->_grad; | ||
| 798 | $self->_grad([map { $_->astype($dtype) } @{ $self->_grad }]); | ||
| 799 | AI::MXNet::AutoGrad->mark_variables($self->_data, $self->_grad, grad_reqs => $self->grad_req); | ||
| 800 | }); | ||
| 801 | } | ||
| 802 | |||
| 803 | __PACKAGE__->AI::MXNet::NS::register('AI::MXNet::Gluon'); | ||
| 804 | |||
| 805 | package AI::MXNet::Gluon::Constant; | ||
| 806 | use strict; | ||
| 807 | use warnings; | ||
| 808 | use Mouse; | ||
| 809 | extends 'AI::MXNet::Gluon::Parameter'; | ||
| 810 | |||
| 811 | =head1 NAME | ||
| 812 | |||
| 813 | AI::MXNet::Gluon::Constant - A constant parameter for holding immutable tensors. | ||
| 814 | =cut | ||
| 815 | |||
| 816 | =head1 DESCRIPTION | ||
| 817 | |||
| 818 | A constant parameter for holding immutable tensors. | ||
| 819 | Constants are ignored by autograd and Trainer, thus their values | ||
| 820 | will not change during training. But you can still update their values | ||
| 821 | manually with the set_data method. | ||
| 822 | |||
| 823 | Constants can be created with either | ||
| 824 | |||
| 825 | $const = mx->gluon->Constant('const', [[1,2],[3,4]]); | ||
| 826 | |||
| 827 | or | ||
| 828 | |||
| 829 | package Block; | ||
| 830 | use AI::MXNet::Gluon::Mouse; | ||
| 831 | extends 'AI::MXNet::Gluon::Block'; | ||
| 832 | sub BUILD | ||
| 833 | { | ||
| 834 | $self->const($self->params->get_constant('const', [[1,2],[3,4]])); | ||
| 835 | } | ||
| 836 | |||
| 837 | Constructor Attributes | ||
| 838 | ---------- | ||
| 839 | name : str | ||
| 840 | Name of the parameter. | ||
| 841 | value : AcceptableInput (perl array, pdl, ndarray, etc) | ||
| 842 | Initial value for the constant. | ||
| 843 | =cut | ||
| 844 | |||
| 845 | use Mouse; | ||
| 846 | use AI::MXNet::Base; | ||
| 847 | use Scalar::Util qw(refaddr); | ||
| 848 | around BUILDARGS => \&AI::MXNet::Base::process_arguments; | ||
| 849 | method python_constructor_arguments() { ['name', 'value'] } | ||
| 850 | has 'value' => (is => 'rw', isa => 'AcceptableInput'); | ||
| 851 | has '+_grad_req' => (is => 'rw', default => 'null'); | ||
| 852 | use overload '""' => sub { | ||
| 853 | my $self = shift; | ||
| 854 | "Constant " . $self->name. | ||
| 855 | " (shape=(" . join(', ', @{ $self->shape//[] }) .")". | ||
| 856 | ", dtype=" . $self->dtype. | ||
| 857 | ", stype=" . $self->stype.")" | ||
| 858 | }, | ||
| 859 | fallback => 1; | ||
| 860 | |||
| 861 | |||
| 862 | sub BUILD | ||
| 863 | { | ||
| 864 | my $self = shift; | ||
| 865 | if(not (blessed $self->value and $self->value->isa('AI::MXNet::NDArray'))) | ||
| 866 | { | ||
| 867 | $self->value(AI::MXNet::NDArray->array($self->value, dtype => $self->dtype)); | ||
| 868 | } | ||
| 869 | $self->shape($self->value->shape); | ||
| 870 | my $init = "AI::MXNet::Gluon::Constant::Init_${\ $self->name }_${\ refaddr($self) }"; | ||
| 871 | my $tmp =<<"EOP"; | ||
| 872 | package $init; | ||
| 873 | use Mouse; | ||
| 874 | extends 'AI::MXNet::Initializer'; | ||
| 875 | sub _init_weight | ||
| 876 | { | ||
| 877 | \$self->value->copyto(\$_[2]); | ||
| 878 | } | ||
| 879 | $init->register; | ||
| 880 | 1; | ||
| 881 | EOP | ||
| 882 | eval $tmp; | ||
| 883 | $self->init($init->new); | ||
| 884 | } | ||
| 885 | |||
| 886 | method grad_req($req=) | ||
| 887 | { | ||
| 888 | if(defined $req and $req ne 'null') | ||
| 889 | { | ||
| 890 | AI::MXNet::Logging->warning( | ||
| 891 | 'Constant parameter "%s" does not support '. | ||
| 892 | 'grad_req other than "null", and new value "%s" '. | ||
| 893 | 'is ignored.', | ||
| 894 | $self->name, $req | ||
| 895 | ); | ||
| 896 | } | ||
| 897 | return 'null'; | ||
| 898 | } | ||
| 899 | |||
| 900 | package AI::MXNet::Gluon::ParameterDict; | ||
| 901 | use AI::MXNet::Base; | ||
| 902 | =head1 NAME | ||
| 903 | |||
| 904 | AI::MXNet::Gluon::ParameterDict - A dictionary managing a set of parameters. | ||
| 905 | =cut | ||
| 906 | |||
| 907 | =head1 DESCRIPTION | ||
| 908 | |||
| 909 | Parameters | ||
| 910 | ---------- | ||
| 911 | prefix : str, default '' | ||
| 912 | The prefix to be prepended to all Parameters' names created by this dict. | ||
| 913 | shared : ParameterDict or undef | ||
| 914 | If not undef, when this dict's `get` method creates a new parameter, will | ||
| 915 | first try to retrieve it from `shared` dict. Usually used for sharing | ||
| 916 | parameters with another `Block`. | ||
| 917 | =cut | ||
| 918 | |||
| 919 | use Mouse; | ||
| 920 | has _prefix => (is => 'ro', isa => 'Str', init_arg => 'prefix', default => ''); | ||
| 921 | has _shared => (is => 'rw', isa => 'Maybe[AI::MXNet::Gluon::ParameterDict]', init_arg => 'shared'); | ||
| 922 | has _params => (is => 'rw', init_arg => undef); | ||
| 923 | |||
| 924 | around BUILDARGS => \&AI::MXNet::Base::process_arguments; | ||
| 925 | method python_constructor_arguments() { [qw/prefix shared/] } | ||
| 926 | |||
| 927 | sub BUILD | ||
| 928 | { | ||
| 929 | my $self = shift; | ||
| 930 | $self->_params(Hash::Ordered->new); | ||
| 931 | } | ||
| 932 | |||
| 933 | use overload | ||
| 934 | '""' => sub { | ||
| 935 | my $self = shift; | ||
| 936 | my $name = $self->_prefix ? $self->_prefix." " : ''; | ||
| 937 | my $content = join("\n", map { AI::MXNet::Base::_indent(" $_", 2) } $self->values); | ||
| 938 | return "$name(\n$content\n)"; | ||
| 939 | }, | ||
| 940 | '@{}' => sub { my @tmp = shift->_params->as_list; \@tmp }, | ||
| 941 | fallback => 1; | ||
| 942 | |||
| 943 | method items() | ||
| 944 | { | ||
| 945 | return @{$self}; | ||
| 946 | } | ||
| 947 | |||
| 948 | method keys() | ||
| 949 | { | ||
| 950 | return $self->_params->keys; | ||
| 951 | } | ||
| 952 | |||
| 953 | method values() | ||
| 954 | { | ||
| 955 | return $self->_params->values; | ||
| 956 | } | ||
| 957 | |||
| 958 | method prefix() | ||
| 959 | { | ||
| 960 | $self->_prefix; | ||
| 961 | } | ||
| 962 | |||
| 963 | method params() | ||
| 964 | { | ||
| 965 | $self->_params; | ||
| 966 | } | ||
| 967 | |||
| 968 | method _get_impl($name) | ||
| 969 | { | ||
| 970 | if($self->_params->exists($name)) | ||
| 971 | { | ||
| 972 | return $self->_params->get($name); | ||
| 973 | } | ||
| 974 | if(defined $self->_shared and $self->_shared->_params->exists($name)) | ||
| 975 | { | ||
| 976 | $self->_params->set($name => $self->_shared->_params->get($name)); | ||
| 977 | return $self->_params->get($name); | ||
| 978 | } | ||
| 979 | return undef; | ||
| 980 | } | ||
| 981 | |||
| 982 | =head2 get | ||
| 983 | |||
| 984 | Retrieves a 'AI::MXNet::Gluon::Parameter' with name '$self->prefix.$name'. If not found, | ||
| 985 | 'get' will first try to retrieve it from 'shared' dict. If still not | ||
| 986 | found, 'get' will create a new 'AI::MXNet::Gluon::Parameter' with key-word arguments and | ||
| 987 | insert it to self. | ||
| 988 | |||
| 989 | Parameters | ||
| 990 | ---------- | ||
| 991 | name : str | ||
| 992 | Name of the desired Parameter. It will be prepended with this dictionary's | ||
| 993 | prefix. | ||
| 994 | %kwargs : hash | ||
| 995 | The rest of key-word arguments for the created `Parameter`. | ||
| 996 | |||
| 997 | Returns | ||
| 998 | ------- | ||
| 999 | Parameter | ||
| 1000 | The created or retrieved `Parameter`. | ||
| 1001 | =cut | ||
| 1002 | |||
| 1003 | use Data::Dumper; | ||
| 1004 | method get(Str $name, %kwargs) | ||
| 1005 | { | ||
| 1006 | $name = $self->prefix . $name; | ||
| 1007 | my $param = $self->_get_impl($name); | ||
| 1008 | if(not defined $param) | ||
| 1009 | { | ||
| 1010 | $param = AI::MXNet::Gluon::Parameter->new($name, %kwargs); | ||
| 1011 | $self->_params->set($name => $param); | ||
| 1012 | } | ||
| 1013 | else | ||
| 1014 | { | ||
| 1015 | while(my ($k, $v) = each %kwargs) | ||
| 1016 | { | ||
| 1017 | if($param->can($k)) | ||
| 1018 | { | ||
| 1019 | if(defined $param->$k) | ||
| 1020 | { | ||
| 1021 | my $existing = $param->$k; | ||
| 1022 | if($k eq 'shape' and @{$v} == @{$existing}) | ||
| 1023 | { | ||
| 1024 | my @inferred_shape; | ||
| 1025 | my $matched = 1; | ||
| 1026 | for(zip($v, $existing)) | ||
| 1027 | { | ||
| 1028 | my ($dim1, $dim2) = @$_; | ||
| 1029 | if($dim1 != $dim2 and $dim1 * $dim2 != 0) | ||
| 1030 | { | ||
| 1031 | $matched = 0; | ||
| 1032 | last; | ||
| 1033 | } | ||
| 1034 | elsif($dim1 == $dim2) | ||
| 1035 | { | ||
| 1036 | push @inferred_shape, $dim1; | ||
| 1037 | } | ||
| 1038 | elsif($dim1 == 0) | ||
| 1039 | { | ||
| 1040 | push @inferred_shape, $dim2; | ||
| 1041 | } | ||
| 1042 | else | ||
| 1043 | { | ||
| 1044 | push @inferred_shape, $dim1; | ||
| 1045 | } | ||
| 1046 | } | ||
| 1047 | if($matched) | ||
| 1048 | { | ||
| 1049 | $param->_shape(\@inferred_shape); | ||
| 1050 | next; | ||
| 1051 | } | ||
| 1052 | } | ||
| 1053 | elsif($k eq 'dtype' and ($v//'') eq ($existing//'')) | ||
| 1054 | { | ||
| 1055 | next; | ||
| 1056 | } | ||
| 1057 | assert( | ||
| 1058 | (not defined $v or Dumper($v) eq Dumper($param->$k)), | ||
| 1059 | "Cannot retrieve Parameter $name because desired attribute ". | ||
| 1060 | "does not match with stored for attribute $k: ". | ||
| 1061 | "desired ".Dumper($v)." vs stored ". Dumper($param->$k) | ||
| 1062 | ); | ||
| 1063 | } | ||
| 1064 | else | ||
| 1065 | { | ||
| 1066 | $param->$k($v); | ||
| 1067 | } | ||
| 1068 | } | ||
| 1069 | else | ||
| 1070 | { | ||
| 1071 | confess("unknown param $k, $v"); | ||
| 1072 | } | ||
| 1073 | } | ||
| 1074 | } | ||
| 1075 | return $param; | ||
| 1076 | } | ||
| 1077 | |||
| 1078 | =head2 update | ||
| 1079 | |||
| 1080 | Copies all Parameters in $other to self. | ||
| 1081 | =cut | ||
| 1082 | |||
| 1083 | method update($other, Maybe[Str] $select=) | ||
| 1084 | { | ||
| 1085 | my @keys = $other->keys; | ||
| 1086 | for my $k (grep { not defined $select or /$select/ } @keys) | ||
| 1087 | { | ||
| 1088 | if($self->_params->exists($k)) | ||
| 1089 | { | ||
| 1090 | assert( | ||
| 1091 | ($self->_params->get($k) eq $other->_params->get($k)), | ||
| 1092 | "Cannot update self with other because they have different ". | ||
| 1093 | "Parameters with the same name $k" | ||
| 1094 | ); | ||
| 1095 | } | ||
| 1096 | else | ||
| 1097 | { | ||
| 1098 | $self->_params->set($k => $other->_params->get($k)); | ||
| 1099 | } | ||
| 1100 | } | ||
| 1101 | } | ||
| 1102 | |||
| 1103 | =head2 get_constant | ||
| 1104 | |||
| 1105 | Retrieves AI::MXNet::Gluon::Constant with name $self->prefix.$name. If not found, | ||
| 1106 | 'get' will first try to retrieve it from "shared" dictionary. If still not | ||
| 1107 | found, 'get' will create a new Constant with key-word | ||
| 1108 | arguments and insert it to self. | ||
| 1109 | |||
| 1110 | Parameters | ||
| 1111 | ---------- | ||
| 1112 | name : str | ||
| 1113 | Name of the desired Constant. It will be prepended with this dictionary's | ||
| 1114 | prefix. | ||
| 1115 | value : array-like | ||
| 1116 | Initial value of constant. | ||
| 1117 | |||
| 1118 | Returns | ||
| 1119 | ------- | ||
| 1120 | Constant | ||
| 1121 | The created or retrieved Constant. | ||
| 1122 | =cut | ||
| 1123 | |||
| 1124 | method get_constant(Str $name, Maybe[AcceptableInput] $value=) | ||
| 1125 | { | ||
| 1126 | $name = $self->prefix . $name; | ||
| 1127 | my $param = $self->_get_impl($name); | ||
| 1128 | if(not defined $param) | ||
| 1129 | { | ||
| 1130 | if(not defined $value) | ||
| 1131 | { | ||
| 1132 | confess( | ||
| 1133 | "No constant named '$name'. Please specify value ". | ||
| 1134 | "if you want to create a new constant." | ||
| 1135 | ); | ||
| 1136 | } | ||
| 1137 | $param = AI::MXNet::Gluon::Constant->new($name, $value); | ||
| 1138 | $self->_params->set($name, $param); | ||
| 1139 | } | ||
| 1140 | elsif(defined $value) | ||
| 1141 | { | ||
| 1142 | confess("reinit of Constant $name is not allowed"); | ||
| 1143 | } | ||
| 1144 | return $param; | ||
| 1145 | } | ||
| 1146 | |||
| 1147 | =head2 initialize | ||
| 1148 | |||
| 1149 | Initializes all Parameters managed by this dictionary to be used for 'NDArray' | ||
| 1150 | API. It has no effect when using 'Symbol' API. | ||
| 1151 | |||
| 1152 | Parameters | ||
| 1153 | ---------- | ||
| 1154 | :$init : Initializer | ||
| 1155 | Global default Initializer to be used when AI::MXNet::Gluon::Parameter->init is undef. | ||
| 1156 | Otherwise, AI::MXNet::Gluon::Parameter->init takes precedence. | ||
| 1157 | :$ctx : AI::MXNet::Context or array ref of AI::MXNet::Context objects | ||
| 1158 | Keeps a copy of Parameters on one or many context(s). | ||
| 1159 | :$force_reinit : bool, default False | ||
| 1160 | Whether to force re-initialization if parameter is already initialized. | ||
| 1161 | :$verbose : bool, default False | ||
| 1162 | Whether to force re-initialization if parameter is already initialized. | ||
| 1163 | =cut | ||
| 1164 | |||
| 1165 | method initialize( | ||
| 1166 | Initializer :$init=AI::MXNet::Initializer->Uniform(), | ||
| 1167 | Maybe[AI::MXNet::Context|ArrayRef[AI::MXNet::Context]] :$ctx=, | ||
| 1168 | Bool :$verbose=0, | ||
| 1169 | Bool :$force_reinit=0 | ||
| 1170 | ) | ||
| 1171 | { | ||
| 1172 | if($verbose) | ||
| 1173 | { | ||
| 1174 | $init->set_verbosity(verbose=>$verbose); | ||
| 1175 | } | ||
| 1176 | $_->initialize(ctx => $ctx, default_init => $init, force_reinit => $force_reinit) for $self->values; | ||
| 1177 | } | ||
| 1178 | |||
| 1179 | =head2 zero_grad | ||
| 1180 | |||
| 1181 | Sets all Parameters' gradient buffer to 0. | ||
| 1182 | =cut | ||
| 1183 | |||
| 1184 | method zero_grad() | ||
| 1185 | { | ||
| 1186 | $_->zero_grad for $self->values; | ||
| 1187 | } | ||
| 1188 | |||
| 1189 | =head2 reset_ctx | ||
| 1190 | |||
| 1191 | Re-assign all Parameters to other contexts. | ||
| 1192 | |||
| 1193 | $ctx : AI::MXNet::Context or array ref of AI::MXNet::Context objects, defaults to AI::MXNet::Context->current_ctx(). | ||
| 1194 | Assign Parameter to given context. If $ctx is an array ref of AI::MXNet::Context objects, a | ||
| 1195 | copy will be made for each context. | ||
| 1196 | =cut | ||
| 1197 | |||
| 1198 | method reset_ctx(AI::MXNet::Context|ArrayRef[AI::MXNet::Conetxt] $ctx=AI::MXNet::Context->current_ctx) | ||
| 1199 | { | ||
| 1200 | $_->reset_ctx($ctx) for $self->values; | ||
| 1201 | } | ||
| 1202 | |||
| 1203 | =head2 setattr | ||
| 1204 | |||
| 1205 | Set an attribute to a new value for all Parameters. | ||
| 1206 | |||
| 1207 | For example, set grad_req to null if you don't need gradient w.r.t a | ||
| 1208 | model's Parameters:: | ||
| 1209 | |||
| 1210 | $model->collect_params()->setattr(grad_req => 'null'); | ||
| 1211 | |||
| 1212 | or change the learning rate multiplier:: | ||
| 1213 | |||
| 1214 | $model->collect_params()->setattr(lr_mult => 0.5); | ||
| 1215 | |||
| 1216 | Parameters | ||
| 1217 | ---------- | ||
| 1218 | $name : str | ||
| 1219 | Name of the attribute. | ||
| 1220 | $value : valid type for attribute name | ||
| 1221 | The new value for the attribute. | ||
| 1222 | =cut | ||
| 1223 | |||
| 1224 | method setattr($name, $value) | ||
| 1225 | { | ||
| 1226 | $_->$name($value) for $self->values; | ||
| 1227 | } | ||
| 1228 | |||
| 1229 | |||
| 1230 | =head2 save | ||
| 1231 | |||
| 1232 | Save parameters to file. | ||
| 1233 | |||
| 1234 | $filename : str | ||
| 1235 | Path to parameter file. | ||
| 1236 | $strip_prefix : str, default '' | ||
| 1237 | Strip prefix from parameter names before saving. | ||
| 1238 | =cut | ||
| 1239 | |||
| 1240 | method save(Str $filename, Str $strip_prefix='') | ||
| 1241 | { | ||
| 1242 | my %arg_dict = (); | ||
| 1243 | for my $param ($self->values()) | ||
| 1244 | { | ||
| 1245 | my $weight = $param->_reduce(); | ||
| 1246 | if(not $param->name =~ /^$strip_prefix/) | ||
| 1247 | { | ||
| 1248 | confess( | ||
| 1249 | "Prefix $strip_prefix is to be striped before saving, but Parameter ". | ||
| 1250 | "${\ $param->name } does not start with $strip_prefix. If you are using Block.save_params, ". | ||
| 1251 | "This may be due to your Block shares parameters from other ". | ||
| 1252 | "Blocks or you forgot to use `with name_scope()`` during init. ". | ||
| 1253 | "Consider switching to Block.collect_params.save and ". | ||
| 1254 | "Block.collect_params.load instead." | ||
| 1255 | ); | ||
| 1256 | } | ||
| 1257 | $arg_dict{ substr($param->name, length $strip_prefix) } = $weight; | ||
| 1258 | } | ||
| 1259 | AI::MXNet::NDArray->save($filename, \%arg_dict); | ||
| 1260 | } | ||
| 1261 | |||
| 1262 | =head2 | ||
| 1263 | |||
| 1264 | Load parameters from file. | ||
| 1265 | |||
| 1266 | $filename : str | ||
| 1267 | Path to parameter file. | ||
| 1268 | :$ctx : AI::MXNet::Context or array ref of AI::MXNet::Context objects | ||
| 1269 | Context(s) initialize loaded parameters on. | ||
| 1270 | :$allow_missing : bool, default False | ||
| 1271 | Whether to silently skip loading parameters not represents in the file. | ||
| 1272 | :$ignore_extra : bool, default False | ||
| 1273 | Whether to silently ignore parameters from the file that are not | ||
| 1274 | present in this ParameterDict. | ||
| 1275 | :$restore_prefix : str, default '' | ||
| 1276 | prepend prefix to names of stored parameters before loading. | ||
| 1277 | =cut | ||
| 1278 | |||
| 1279 | method load( | ||
| 1280 | Str $filename, | ||
| 1281 | AI::MXNet::Context|ArrayRef[AI::MXNet::Context] :$ctx=AI::MXNet::Context->current_ctx, | ||
| 1282 | Bool :$allow_missing=0, | ||
| 1283 | Bool :$ignore_extra=0, | ||
| 1284 | Str :$restore_prefix='' | ||
| 1285 | ) | ||
| 1286 | { | ||
| 1287 | if($restore_prefix) | ||
| 1288 | { | ||
| 1289 | for my $name ($self->keys()) | ||
| 1290 | { | ||
| 1291 | assert( | ||
| 1292 | ($name =~ /^$restore_prefix/), | ||
| 1293 | "restore_prefix is $restore_prefix but Parameters name $name does not start ". | ||
| 1294 | "with $restore_prefix" | ||
| 1295 | ); | ||
| 1296 | } | ||
| 1297 | } | ||
| 1298 | my $lprefix = length $restore_prefix; | ||
| 1299 | my %orig_load = %{ AI::MXNet::NDArray->load($filename) }; | ||
| 1300 | my %arg_dict = map { my $k = $_; s/^(?:arg|aux)://; ($restore_prefix.$_, $orig_load{$k}) } keys %orig_load; | ||
| 1301 | if(not $allow_missing) | ||
| 1302 | { | ||
| 1303 | for my $name ($self->keys()) | ||
| 1304 | { | ||
| 1305 | assert( | ||
| 1306 | (exists $arg_dict{ $name }), | ||
| 1307 | sprintf("Parameter %s is missing in file %s", substr($name, $lprefix), $filename) | ||
| 1308 | ); | ||
| 1309 | } | ||
| 1310 | } | ||
| 1311 | for my $name (keys %arg_dict) | ||
| 1312 | { | ||
| 1313 | if(not $self->_params->exists($name)) | ||
| 1314 | { | ||
| 1315 | assert( | ||
| 1316 | $ignore_extra, | ||
| 1317 | sprintf( | ||
| 1318 | "Parameter %s loaded from file %s is not present in ParameterDict", | ||
| 1319 | substr($name, $lprefix), | ||
| 1320 | $filename | ||
| 1321 | ) | ||
| 1322 | ); | ||
| 1323 | next; | ||
| 1324 | } | ||
| 1325 | $self->_params->get($name)->_load_init($arg_dict{$name}, $ctx); | ||
| 1326 | } | ||
| 1327 | } | ||
| 1328 | |||
| 1329 | __PACKAGE__->AI::MXNet::NS::register('AI::MXNet::Gluon'); | ||
| 1330 | |||
| 1331 | 1; |