| 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::AutoGrad; | ||
| 19 | use strict; | ||
| 20 | use warnings; | ||
| 21 | use AI::MXNet::NS 'global'; | ||
| 22 | use AI::MXNet::Base; | ||
| 23 | use AI::MXNet::Function::Parameters; | ||
| 24 | use Scalar::Util qw(blessed); | ||
| 25 | use Carp qw(confess); | ||
| 26 | |||
| 27 | =head1 NAME | ||
| 28 | |||
| 29 | AI::MXNet::AutoGrad - Autograd for NDArray. | ||
| 30 | =cut | ||
| 31 | |||
| 32 | =head1 DESCRIPTION | ||
| 33 | |||
| 34 | Auto gradients differentiation for dynamic graphs, primarily used with Gluon. | ||
| 35 | |||
| 36 | =cut | ||
| 37 | |||
| 38 | =head1 SYNOPSIS | ||
| 39 | |||
| 40 | use AI::MXNet qw(mx); | ||
| 41 | my $x = mx->nd->ones([1]); | ||
| 42 | $x->attach_grad; | ||
| 43 | my $z; | ||
| 44 | mx->autograd->record(sub { | ||
| 45 | $z = mx->nd->elemwise_add($x->exp, $x); | ||
| 46 | }); | ||
| 47 | my $dx = mx->autograd->grad($z, $x, create_graph=>1); | ||
| 48 | ok(abs($dx->asscalar - 3.71828175) < 1e-7); | ||
| 49 | $dx->backward; | ||
| 50 | ok(abs($x->grad->asscalar - 2.71828175) < 1e-7); | ||
| 51 | |||
| 52 | =cut | ||
| 53 | |||
| 54 | =head2 set_is_training | ||
| 55 | |||
| 56 | Set status to training/not training. When training, graph will be constructed | ||
| 57 | for gradient computation. Operators will also run with $is_train=1. For example, | ||
| 58 | Dropout will drop inputs randomly when is_train=True while simply passing through | ||
| 59 | if $is_train=0. | ||
| 60 | |||
| 61 | Parameters | ||
| 62 | ---------- | ||
| 63 | $is_train: Bool | ||
| 64 | |||
| 65 | Returns | ||
| 66 | ------- | ||
| 67 | previous state before this set. | ||
| 68 | =cut | ||
| 69 | |||
| 70 | |||
| 71 | method set_is_training(Bool $is_train) | ||
| 72 | { | ||
| 73 | return scalar(check_call(AI::MXNetCAPI::AutogradSetIsTraining($is_train))); | ||
| 74 | } | ||
| 75 | |||
| 76 | =head2 set_is_recording | ||
| 77 | |||
| 78 | Set status to recording/not recording. When recording, graph will be constructed | ||
| 79 | for gradient computation. | ||
| 80 | |||
| 81 | Parameters | ||
| 82 | ---------- | ||
| 83 | $is_recoding: Bool | ||
| 84 | |||
| 85 | Returns | ||
| 86 | ------- | ||
| 87 | previous state before this set. | ||
| 88 | =cut | ||
| 89 | |||
| 90 | method set_is_recording(Bool $is_recording) | ||
| 91 | { | ||
| 92 | return scalar(check_call(AI::MXNetCAPI::AutogradSetIsRecording($is_recording))); | ||
| 93 | } | ||
| 94 | |||
| 95 | =head2 is_recording | ||
| 96 | |||
| 97 | Get status on recording/not recording. | ||
| 98 | |||
| 99 | Returns | ||
| 100 | ------- | ||
| 101 | Current state of recording. | ||
| 102 | =cut | ||
| 103 | |||
| 104 | method is_recording() | ||
| 105 | { | ||
| 106 | return scalar(check_call(AI::MXNetCAPI::AutogradIsRecording())); | ||
| 107 | } | ||
| 108 | |||
| 109 | =head2 is_training | ||
| 110 | |||
| 111 | Get status on training/predicting. | ||
| 112 | |||
| 113 | Returns | ||
| 114 | ------- | ||
| 115 | Current state of training/predicting. | ||
| 116 | =cut | ||
| 117 | |||
| 118 | method is_training() | ||
| 119 | { | ||
| 120 | return scalar(check_call(AI::MXNetCAPI::AutogradIsTraining())); | ||
| 121 | } | ||
| 122 | |||
| 123 | =head2 mark_variables | ||
| 124 | |||
| 125 | Mark AI::MXNet::NDArrays as variables to compute gradient for autograd. | ||
| 126 | |||
| 127 | Parameters | ||
| 128 | ---------- | ||
| 129 | ArrayRef[AI::MXNet::NDArray] $variables | ||
| 130 | ArrayRef[AI::MXNet::NDArray] $gradients | ||
| 131 | GradReq|ArrayRef[GradReq] :$grad_reqs='write' | ||
| 132 | =cut | ||
| 133 | |||
| 134 | method mark_variables( | ||
| 135 | ArrayRef[AI::MXNet::NDArray] $variables, | ||
| 136 | ArrayRef[AI::MXNet::NDArray] $gradients, | ||
| 137 | GradReq|ArrayRef[GradReq] :$grad_reqs='write' | ||
| 138 | ) | ||
| 139 | { | ||
| 140 | my @variable_handles = map { $_->handle } @{ $variables }; | ||
| 141 | my @gradient_handles = map { $_->handle } @{ $gradients }; | ||
| 142 | my @grad_reqs; | ||
| 143 | if(not ref $grad_reqs) | ||
| 144 | { | ||
| 145 | @grad_reqs = (GRAD_REQ_MAP->{ $grad_reqs }) x scalar(@variable_handles); | ||
| 146 | } | ||
| 147 | else | ||
| 148 | { | ||
| 149 | @grad_reqs = map { GRAD_REQ_MAP->{ $_ } } @{ $grad_reqs }; | ||
| 150 | } | ||
| 151 | check_call( | ||
| 152 | AI::MXNetCAPI::AutogradMarkVariables( | ||
| 153 | scalar(@variable_handles), | ||
| 154 | \@variable_handles, | ||
| 155 | \@grad_reqs, | ||
| 156 | \@gradient_handles | ||
| 157 | ) | ||
| 158 | ); | ||
| 159 | } | ||
| 160 | |||
| 161 | =head2 backward | ||
| 162 | |||
| 163 | Compute the gradients of heads w.r.t previously marked variables. | ||
| 164 | |||
| 165 | Parameters | ||
| 166 | ---------- | ||
| 167 | $heads: ArrayRef[AI::MXNet::NDArray] | ||
| 168 | Output NDArray(s) | ||
| 169 | :$head_grads=: Maybe[AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray|Undef]] | ||
| 170 | Gradients with respect to heads. | ||
| 171 | :$retain_graph=0: Bool, optional | ||
| 172 | Whether to retain graph. | ||
| 173 | :$train_mode=1: Bool, optional | ||
| 174 | Whether to do backward for training or predicting. | ||
| 175 | =cut | ||
| 176 | method backward( | ||
| 177 | AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray] $heads, | ||
| 178 | Maybe[AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray|Undef]] :$head_grads=, | ||
| 179 | Bool :$retain_graph=0, | ||
| 180 | Bool :$train_mode=1 | ||
| 181 | ) | ||
| 182 | { | ||
| 183 | my ($head_handles, $hgrad_handles) = _parse_head($heads, $head_grads); | ||
| 184 | check_call( | ||
| 185 | AI::MXNetCAPI::AutogradBackwardEx( | ||
| 186 | scalar(@{ $head_handles }), | ||
| 187 | $head_handles, | ||
| 188 | $hgrad_handles, | ||
| 189 | 0, | ||
| 190 | [], | ||
| 191 | $retain_graph, | ||
| 192 | 0, | ||
| 193 | $train_mode | ||
| 194 | ) | ||
| 195 | ); | ||
| 196 | } | ||
| 197 | |||
| 198 | =head2 compute_gradient | ||
| 199 | |||
| 200 | Compute the gradients of outputs w.r.t variables. | ||
| 201 | |||
| 202 | Parameters | ||
| 203 | ---------- | ||
| 204 | outputs: ArrayRef[AI::MXNet::NDArray] | ||
| 205 | |||
| 206 | Returns | ||
| 207 | ------- | ||
| 208 | gradients: ArrayRef[AI::MXNet::NDArray] | ||
| 209 | =cut | ||
| 210 | |||
| 211 | |||
| 212 | method compute_gradient(ArrayRef[AI::MXNet::NDArray] $outputs) | ||
| 213 | { | ||
| 214 | __PACKAGE__->backward($outputs); | ||
| 215 | } | ||
| 216 | |||
| 217 | =head2 grad_and_loss | ||
| 218 | |||
| 219 | Return function that computes both gradient of arguments and loss value. | ||
| 220 | |||
| 221 | Parameters | ||
| 222 | ---------- | ||
| 223 | $func: CodeRef | ||
| 224 | The forward (loss) function. | ||
| 225 | $argnum: Maybe[Int|ArrayRef[Int]] | ||
| 226 | The index of argument to calculate gradient for. | ||
| 227 | |||
| 228 | Returns | ||
| 229 | ------- | ||
| 230 | grad_and_loss_func: CodeRef | ||
| 231 | A function that would compute both the gradient of arguments and loss value. | ||
| 232 | =cut | ||
| 233 | |||
| 234 | method grad_and_loss(CodeRef $func, Maybe[Int|ArrayRef[Int]] $argnum=) | ||
| 235 | { | ||
| 236 | return sub { | ||
| 237 | my @args = @_; | ||
| 238 | my @variables = @_; | ||
| 239 | if(defined $argnum) | ||
| 240 | { | ||
| 241 | my @argnum = ref $argnum ? @$argnum : ($argnum); | ||
| 242 | @variables = map { $args[$_] } @argnum; | ||
| 243 | } | ||
| 244 | map { | ||
| 245 | assert( | ||
| 246 | (blessed($_) and $_->isa('AI::MXNet::NDArray')), | ||
| 247 | "type of autograd input should NDArray") | ||
| 248 | } @variables; | ||
| 249 | my @grads = map { $_->zeros_like } @variables; | ||
| 250 | __PACKAGE__->mark_variables(\@variables, \@grads); | ||
| 251 | my $outputs; | ||
| 252 | __PACKAGE__->record(sub { $outputs = $func->(@args) }); | ||
| 253 | __PACKAGE__->backward(ref $outputs eq 'ARRAY' ? $outputs : [$outputs]); | ||
| 254 | return (\@grads, $outputs); | ||
| 255 | }; | ||
| 256 | } | ||
| 257 | |||
| 258 | =head2 grad | ||
| 259 | |||
| 260 | Compute the gradients of heads w.r.t variables. Gradients will be | ||
| 261 | returned as new NDArrays instead of stored into `variable.grad`. | ||
| 262 | Supports recording gradient graph for computing higher order gradients. | ||
| 263 | |||
| 264 | Note: Currently only a very limited set of operators support higher order | ||
| 265 | gradients. | ||
| 266 | |||
| 267 | Parameters | ||
| 268 | ---------- | ||
| 269 | $heads: AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray] | ||
| 270 | Output NDArray(s) | ||
| 271 | $variables: AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray] | ||
| 272 | Input variables to compute gradients for. | ||
| 273 | :$head_grads=: Maybe[AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray|Undef]] | ||
| 274 | Gradients with respect to heads. | ||
| 275 | :$retain_graph=: Bool | ||
| 276 | Whether to keep computation graph to differentiate again, instead | ||
| 277 | of clearing history and release memory. Defaults to the same value | ||
| 278 | as create_graph. | ||
| 279 | :$create_graph=0: Bool | ||
| 280 | Whether to record gradient graph for computing of higher order gradients. | ||
| 281 | $train_mode=1: Bool, optional | ||
| 282 | Whether to do backward for training or prediction. | ||
| 283 | |||
| 284 | Returns | ||
| 285 | ------- | ||
| 286 | AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]: | ||
| 287 | Gradients with respect to variables. | ||
| 288 | |||
| 289 | Examples | ||
| 290 | -------- | ||
| 291 | >>> $x = mx->nd->ones([1]); | ||
| 292 | >>> $x->attach_grad(); | ||
| 293 | >>> mx->autograd->record(sub { | ||
| 294 | $z = mx->nd->elemwise_add(mx->nd->exp($x), $x); | ||
| 295 | }); | ||
| 296 | >>> $dx = mx->autograd->grad($z, [$x], create_graph=>1) | ||
| 297 | >>> $dx->backward(); | ||
| 298 | >>> print($dx->grad->aspdl) | ||
| 299 | [3.71828175] | ||
| 300 | =cut | ||
| 301 | |||
| 302 | method grad( | ||
| 303 | AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray] $heads, | ||
| 304 | AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray] $variables, | ||
| 305 | Maybe[AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray|Undef]] :$head_grads=, | ||
| 306 | Bool :$retain_graph=, | ||
| 307 | Bool :$create_graph=0, | ||
| 308 | Bool :$train_mode=1 | ||
| 309 | ) | ||
| 310 | { | ||
| 311 | my ($head_handles, $hgrad_handles) = _parse_head($heads, $head_grads); | ||
| 312 | my @var_handles; | ||
| 313 | if(blessed $variables) | ||
| 314 | { | ||
| 315 | @var_handles = ($variables->handle); | ||
| 316 | } | ||
| 317 | else | ||
| 318 | { | ||
| 319 | assert(scalar(@{ $variables }), "variables cannot be an empty array."); | ||
| 320 | @var_handles = map { $_->handle } @{ $variables }; | ||
| 321 | } | ||
| 322 | |||
| 323 | $retain_graph //= $create_graph; | ||
| 324 | |||
| 325 | my ($grad_vars, $grad_stypes) | ||
| 326 | = | ||
| 327 | check_call( | ||
| 328 | AI::MXNetCAPI::AutogradBackwardEx( | ||
| 329 | scalar(@{ $head_handles }), | ||
| 330 | $head_handles, | ||
| 331 | $hgrad_handles, | ||
| 332 | scalar(@var_handles), | ||
| 333 | \@var_handles, | ||
| 334 | $retain_graph, | ||
| 335 | $create_graph, | ||
| 336 | $train_mode | ||
| 337 | ) | ||
| 338 | ); | ||
| 339 | |||
| 340 | my @ret; | ||
| 341 | for(zip($grad_vars, $grad_stypes)) { | ||
| 342 | my ($handle, $stype) = @$_; | ||
| 343 | push @ret, AI::MXNet::NDArray->_ndarray_cls($handle, 1, $stype); | ||
| 344 | } | ||
| 345 | if(blessed $variables) | ||
| 346 | { | ||
| 347 | return $ret[0]; | ||
| 348 | } | ||
| 349 | return \@ret; | ||
| 350 | } | ||
| 351 | |||
| 352 | =head2 train_mode | ||
| 353 | |||
| 354 | Executes $sub within an autograd training scope context. | ||
| 355 | Parameters | ||
| 356 | ---------- | ||
| 357 | $sub: CodeRef | ||
| 358 | =cut | ||
| 359 | |||
| 360 | method train_mode(CodeRef $sub) | ||
| 361 | { | ||
| 362 | my $prev = __PACKAGE__->set_is_training(1); | ||
| 363 | eval { $sub->(); }; | ||
| 364 | __PACKAGE__->set_is_training(0) unless $prev; | ||
| 365 | confess($@) if $@; | ||
| 366 | } | ||
| 367 | |||
| 368 | =head2 predict_mode | ||
| 369 | |||
| 370 | Executes $sub within an autograd predicting scope context. | ||
| 371 | Parameters | ||
| 372 | ---------- | ||
| 373 | $sub: CodeRef | ||
| 374 | =cut | ||
| 375 | |||
| 376 | method predict_mode(CodeRef $sub) | ||
| 377 | { | ||
| 378 | my $prev = __PACKAGE__->set_is_training(0); | ||
| 379 | eval { $sub->(); }; | ||
| 380 | __PACKAGE__->set_is_training(1) if $prev; | ||
| 381 | confess($@) if $@; | ||
| 382 | } | ||
| 383 | |||
| 384 | =head2 record | ||
| 385 | |||
| 386 | Executes $sub within an autograd recording scope context | ||
| 387 | and captures code that needs gradients to be calculated. | ||
| 388 | Parameters | ||
| 389 | ---------- | ||
| 390 | $sub: CodeRef | ||
| 391 | :$train_mode=1 : Maybe[Bool] | ||
| 392 | =cut | ||
| 393 | |||
| 394 | method record(CodeRef $sub, Maybe[Bool] :$train_mode=1) | ||
| 395 | { | ||
| 396 | my $prev_train; | ||
| 397 | if(defined $train_mode) | ||
| 398 | { | ||
| 399 | $prev_train = __PACKAGE__->set_is_training($train_mode); | ||
| 400 | } | ||
| 401 | my $prev_recording = __PACKAGE__->set_is_recording(1); | ||
| 402 | eval { $sub->(); }; | ||
| 403 | if(defined $train_mode) | ||
| 404 | { | ||
| 405 | $prev_train = __PACKAGE__->set_is_training($prev_train) if not $prev_train == $train_mode; | ||
| 406 | } | ||
| 407 | __PACKAGE__->set_is_recording(0) unless $prev_recording; | ||
| 408 | confess($@) if $@; | ||
| 409 | } | ||
| 410 | |||
| 411 | =head2 pause | ||
| 412 | |||
| 413 | Executes $sub within an autograd recording scope context | ||
| 414 | and captures code that needs gradients to be calculated. | ||
| 415 | Parameters | ||
| 416 | ---------- | ||
| 417 | $sub: CodeRef | ||
| 418 | :$train_mode=0 : Maybe[Bool] | ||
| 419 | =cut | ||
| 420 | |||
| 421 | method pause(CodeRef $sub, Maybe[Bool] :$train_mode=0) | ||
| 422 | { | ||
| 423 | my $prev_train; | ||
| 424 | if(defined $train_mode) | ||
| 425 | { | ||
| 426 | $prev_train = __PACKAGE__->set_is_training($train_mode); | ||
| 427 | } | ||
| 428 | my $prev_recording = __PACKAGE__->set_is_recording(0); | ||
| 429 | eval { $sub->(); }; | ||
| 430 | if(defined $train_mode) | ||
| 431 | { | ||
| 432 | $prev_train = __PACKAGE__->set_is_training($prev_train) if not $prev_train == $train_mode; | ||
| 433 | } | ||
| 434 | __PACKAGE__->set_is_recording(1) if $prev_recording; | ||
| 435 | confess($@) if $@; | ||
| 436 | } | ||
| 437 | |||
| 438 | =head2 get_symbol | ||
| 439 | |||
| 440 | Retrieve recorded computation history as `Symbol`. | ||
| 441 | |||
| 442 | Parameters | ||
| 443 | ---------- | ||
| 444 | $x : AI::MXNet::NDArray | ||
| 445 | AI::MXNet::NDArray representing the head of computation graph. | ||
| 446 | Returns | ||
| 447 | ------- | ||
| 448 | AI::MXNet::Symbol | ||
| 449 | The retrieved Symbol. | ||
| 450 | =cut | ||
| 451 | |||
| 452 | method get_symbol(AI::MXNet::NDArray $x) | ||
| 453 | { | ||
| 454 | my $handle = scalar(check_call(AI::MXNetCAPI::AutogradGetSymbol($x->handle))); | ||
| 455 | return AI::MXNet::Symbol->new(handle => $handle); | ||
| 456 | } | ||
| 457 | |||
| 458 | # parse head gradient for backward and grad. | ||
| 459 | func _parse_head($heads, $head_grads) | ||
| 460 | { | ||
| 461 | if(blessed $heads) | ||
| 462 | { | ||
| 463 | $heads = [$heads]; | ||
| 464 | } | ||
| 465 | if(blessed $head_grads) | ||
| 466 | { | ||
| 467 | $head_grads = [$head_grads]; | ||
| 468 | } | ||
| 469 | my @head_handles = map { $_->handle } @{ $heads }; | ||
| 470 | my @hgrad_handles; | ||
| 471 | if(defined $head_grads) | ||
| 472 | { | ||
| 473 | assert( | ||
| 474 | (@{ $heads } == @{ $head_grads }), | ||
| 475 | "heads and head_grads must be lists of the same length" | ||
| 476 | ); | ||
| 477 | @hgrad_handles = map { defined($_) ? $_->handle : undef } @{ $head_grads }; | ||
| 478 | } | ||
| 479 | return (\@head_handles, \@hgrad_handles); | ||
| 480 | } | ||
| 481 | |||
| 482 | 1; |