| 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::Executor::Group; | ||
| 19 | use strict; | ||
| 20 | use warnings; | ||
| 21 | use Scalar::Util qw(blessed); | ||
| 22 | use List::Util qw(sum min); | ||
| 23 | use AI::MXNet::Base; | ||
| 24 | use AI::MXNet::Function::Parameters; | ||
| 25 | |||
| 26 | =head1 NAME | ||
| 27 | |||
| 28 | AI::MXNet::Executor::Group - Manager for a group of executors working in different contexts. | ||
| 29 | =cut | ||
| 30 | |||
| 31 | func _split_input_slice($batch_size, $work_load_list) | ||
| 32 | { | ||
| 33 | my $total_work_load = sum(@{ $work_load_list }); | ||
| 34 | my @batch_num_list = map { # perl does not have builtin round | ||
| 35 | int(($_ * $batch_size / $total_work_load) + 0.5) | ||
| 36 | } @{ $work_load_list }; | ||
| 37 | my $batch_num_sum = sum(@batch_num_list); | ||
| 38 | my @slices; | ||
| 39 | if($batch_num_sum < $batch_size) | ||
| 40 | { | ||
| 41 | $batch_num_list[-1] += $batch_size - $batch_num_sum; | ||
| 42 | } | ||
| 43 | my $end = 0; | ||
| 44 | for my $batch_num (@batch_num_list) | ||
| 45 | { | ||
| 46 | my $begin = int(min($end, $batch_size)); | ||
| 47 | $end = int(min($begin + $batch_num, $batch_size)); | ||
| 48 | if($begin >= $end) | ||
| 49 | { | ||
| 50 | Carp::confess('Too many slices such that some splits are empty'); | ||
| 51 | } | ||
| 52 | push @slices, [$begin, $end]; | ||
| 53 | } | ||
| 54 | return \@slices; | ||
| 55 | } | ||
| 56 | |||
| 57 | # Load a array ref of arrays into a array ref of arrays specified by slices | ||
| 58 | func _load_general($data, $targets, $major_axis) | ||
| 59 | { | ||
| 60 | for(zip($data, $targets, $major_axis)) { | ||
| 61 | my ($d_src, $d_targets, $axis) = @$_; | ||
| 62 | if(blessed($d_targets) and $d_targets->isa('AI::MXNet::NDarray')) | ||
| 63 | { | ||
| 64 | $d_src->copyto($d_targets); | ||
| 65 | } | ||
| 66 | elsif(ref $d_targets eq 'ARRAY' and blessed $d_targets->[0]) | ||
| 67 | { | ||
| 68 | for(zip($d_src, $d_targets)) { | ||
| 69 | my ($src, $dst) = @$_; | ||
| 70 | $src->copyto($dst); | ||
| 71 | } | ||
| 72 | } | ||
| 73 | else | ||
| 74 | { | ||
| 75 | for my $d (@{ $d_targets }) | ||
| 76 | { | ||
| 77 | my ($slice_idx, $d_dst) = @{ $d }; | ||
| 78 | if($axis >= 0) | ||
| 79 | { | ||
| 80 | my $shape = $d_src->shape; | ||
| 81 | my $do_crop = ($slice_idx->[0] != 0 or $shape->[$axis] != $slice_idx->[1]); | ||
| 82 | if($do_crop) | ||
| 83 | { | ||
| 84 | if($axis == 0) | ||
| 85 | { | ||
| 86 | $d_src->slice([$slice_idx->[0], $slice_idx->[1] - 1])->copyto($d_dst); | ||
| 87 | } | ||
| 88 | else | ||
| 89 | { | ||
| 90 | if($d_src->context == $d_dst->context) | ||
| 91 | { | ||
| 92 | AI::MXNet::NDArray->slice_axis( | ||
| 93 | $d_src, | ||
| 94 | { | ||
| 95 | axis => $axis, | ||
| 96 | begin => $slice_idx->[0], | ||
| 97 | end => $slice_idx->[1], | ||
| 98 | out => $d_dst | ||
| 99 | } | ||
| 100 | ); | ||
| 101 | } | ||
| 102 | else | ||
| 103 | { | ||
| 104 | my $d_dst_copy = AI::MXNet::NDArray->slice_axis( | ||
| 105 | $d_src, | ||
| 106 | { | ||
| 107 | axis => $axis, | ||
| 108 | begin => $slice_idx->[0], | ||
| 109 | end => $slice_idx->[1] | ||
| 110 | } | ||
| 111 | ); | ||
| 112 | $d_dst_copy->copyto($d_dst); | ||
| 113 | } | ||
| 114 | } | ||
| 115 | } | ||
| 116 | else | ||
| 117 | { | ||
| 118 | $d_src->copyto($d_dst); | ||
| 119 | } | ||
| 120 | } | ||
| 121 | else | ||
| 122 | { | ||
| 123 | $d_src->copyto($d_dst); | ||
| 124 | } | ||
| 125 | } | ||
| 126 | } | ||
| 127 | } | ||
| 128 | } | ||
| 129 | |||
| 130 | # Load data into sliced arrays | ||
| 131 | func _load_data($batch, $targets, $major_axis) | ||
| 132 | { | ||
| 133 | _load_general($batch->data, $targets, $major_axis); | ||
| 134 | } | ||
| 135 | |||
| 136 | # Load label into sliced arrays | ||
| 137 | func _load_label($batch, $targets, $major_axis) | ||
| 138 | { | ||
| 139 | _load_general($batch->label, $targets, $major_axis); | ||
| 140 | } | ||
| 141 | |||
| 142 | # Merge outputs that live on multiple context into one, so that they look | ||
| 143 | # like living on one context. | ||
| 144 | func _merge_multi_context($outputs, $major_axis) | ||
| 145 | { | ||
| 146 | my @rets; | ||
| 147 | for(zip($outputs, $major_axis)) { | ||
| 148 | my ($tensors, $axis) = @$_; | ||
| 149 | if($axis >= 0) | ||
| 150 | { | ||
| 151 | if(@$tensors == 1) | ||
| 152 | { | ||
| 153 | push @rets, $tensors->[0]; | ||
| 154 | } | ||
| 155 | else | ||
| 156 | { | ||
| 157 | my $ctx = $tensors->[0]->context; | ||
| 158 | push @rets, AI::MXNet::NDArray->concat((map { $_->as_in_context($ctx) } @$tensors), { dim => $axis }); | ||
| 159 | } | ||
| 160 | } | ||
| 161 | else | ||
| 162 | { | ||
| 163 | # negative axis means the there is no batch_size axis, and all the | ||
| 164 | # results should be the same on each device. We simply take the | ||
| 165 | # first one, without checking they are actually the same | ||
| 166 | push @rets, $tensors->[0]; | ||
| 167 | } | ||
| 168 | } | ||
| 169 | return \@rets; | ||
| 170 | } | ||
| 171 | |||
| 172 | ## TODO | ||
| 173 | ## this class is here because of https://github.com/gfx/p5-Mouse/pull/67 | ||
| 174 | ## once 2.4.7 version of Mouse in Ubuntu for affected Perl version | ||
| 175 | ## these accessors should be merged into main class | ||
| 176 | package AI::MXNet::DataParallelExecutorGroup::_private; | ||
| 177 | use Mouse; | ||
| 178 | has [qw/output_layouts label_layouts arg_names aux_names | ||
| 179 | batch_size slices execs data_arrays | ||
| 180 | label_arrays param_arrays grad_arrays aux_arrays | ||
| 181 | data_layouts shared_data_arrays input_grad_arrays | ||
| 182 | _default_execs state_arrays/ | ||
| 183 | ] => (is => 'rw', init_arg => undef); | ||
| 184 | |||
| 185 | package AI::MXNet::DataParallelExecutorGroup; | ||
| 186 | use Mouse; | ||
| 187 | use AI::MXNet::Base; | ||
| 188 | use List::Util qw(sum); | ||
| 189 | |||
| 190 | =head1 DESCRIPTION | ||
| 191 | |||
| 192 | DataParallelExecutorGroup is a group of executors that lives on a group of devices. | ||
| 193 | This is a helper class used to implement data parallelization. Each mini-batch will | ||
| 194 | be split and run on the devices. | ||
| 195 | |||
| 196 | Parameters for constructor | ||
| 197 | ---------- | ||
| 198 | symbol : AI::MXNet::Symbol | ||
| 199 | The common symbolic computation graph for all executors. | ||
| 200 | contexts : ArrayRef[AI::MXNet::Context] | ||
| 201 | A array ref of contexts. | ||
| 202 | workload : ArrayRef[Num] | ||
| 203 | If not undef, could be an array ref of numbers that specify the workload to be assigned | ||
| 204 | to different context. Larger number indicate heavier workload. | ||
| 205 | data_shapes : ArrayRef[NameShape|AI::MXNet::DataDesc] | ||
| 206 | Should be a array ref of [name, shape] array refs, for the shapes of data. Note the order is | ||
| 207 | important and should be the same as the order that the `DataIter` provide the data. | ||
| 208 | label_shapes : Maybe[ArrayRef[NameShape|AI::MXNet::DataDesc]] | ||
| 209 | Should be a array ref of [$name, $shape] array refs, for the shapes of label. Note the order is | ||
| 210 | important and should be the same as the order that the `DataIter` provide the label. | ||
| 211 | param_names : ArrayRef[Str] | ||
| 212 | A array ref of strings, indicating the names of parameters (e.g. weights, filters, etc.) | ||
| 213 | in the computation graph. | ||
| 214 | for_training : Bool | ||
| 215 | Indicate whether the executors should be bind for training. When not doing training, | ||
| 216 | the memory for gradients will not be allocated. | ||
| 217 | inputs_need_grad : Bool | ||
| 218 | Indicate whether the gradients for the input data should be computed. This is currently | ||
| 219 | not used. It will be useful for implementing composition of modules. | ||
| 220 | shared_group : AI::MXNet::DataParallelExecutorGroup | ||
| 221 | Default is undef. This is used in bucketing. When not undef, it should be a executor | ||
| 222 | group corresponding to a different bucket. In other words, it will correspond to a different | ||
| 223 | symbol with the same set of parameters (e.g. unrolled RNNs with different lengths). | ||
| 224 | In this case the memory regions of the parameters will be shared. | ||
| 225 | logger : Logger | ||
| 226 | Default is AI::MXNet::Logging->get_logger. | ||
| 227 | fixed_param_names: Maybe[ArrayRef[Str]] | ||
| 228 | Indicate parameters to be fixed during training. Parameters in this array ref will not allocate | ||
| 229 | space for gradient, nor do gradient calculation. | ||
| 230 | grad_req : ArrayRef[GradReq]|HashRef[GradReq]|GradReq | ||
| 231 | Requirement for gradient accumulation. Can be 'write', 'add', or 'null' | ||
| 232 | (default to 'write'). | ||
| 233 | Can be specified globally (str) or for each argument (array ref, hash ref). | ||
| 234 | state_names: Maybe[ArrayRef[Str]] | ||
| 235 | =cut | ||
| 236 | |||
| 237 | has 'symbol' => (is => 'ro', isa => 'AI::MXNet::Symbol', required => 1); | ||
| 238 | has 'contexts' => (is => 'ro', isa => 'ArrayRef[AI::MXNet::Context]', required => 1); | ||
| 239 | has 'workload' => (is => 'ro', isa => 'ArrayRef[Num]', default => sub { [] }); | ||
| 240 | has 'data_shapes' => (is => 'rw', isa => 'ArrayRef[NameShape|AI::MXNet::DataDesc]', required => 1); | ||
| 241 | has 'label_shapes' => (is => 'rw', isa => 'Maybe[ArrayRef[NameShape|AI::MXNet::DataDesc]]'); | ||
| 242 | has 'param_names' => (is => 'ro', isa => 'ArrayRef[Str]', required => 1); | ||
| 243 | has 'for_training' => (is => 'ro', isa => 'Bool', required => 1); | ||
| 244 | has 'inputs_need_grad' => (is => 'ro', isa => 'Bool', default => 0); | ||
| 245 | has 'shared_group' => (is => 'ro', isa => 'Maybe[AI::MXNet::DataParallelExecutorGroup]'); | ||
| 246 | has 'logger' => (is => 'ro', default => sub { AI::MXNet::Logging->get_logger }); | ||
| 247 | has 'fixed_param_names' => (is => 'rw', isa => 'Maybe[ArrayRef[Str]]'); | ||
| 248 | has 'state_names' => (is => 'rw', isa => 'Maybe[ArrayRef[Str]]'); | ||
| 249 | has 'grad_req' => (is => 'rw', isa => 'ArrayRef[GradReq]|HashRef[GradReq]|GradReq', default=>'write'); | ||
| 250 | has '_p' => (is => 'rw', init_arg => undef); | ||
| 251 | sub BUILD | ||
| 252 | { | ||
| 253 | my $self = shift; | ||
| 254 | my $p = AI::MXNet::DataParallelExecutorGroup::_private->new; | ||
| 255 | $p->arg_names($self->symbol->list_arguments); | ||
| 256 | $p->aux_names($self->symbol->list_auxiliary_states); | ||
| 257 | $p->execs([]); | ||
| 258 | $self->_p($p); | ||
| 259 | $self->grad_req('null') if not $self->for_training; | ||
| 260 | $self->fixed_param_names([]) unless defined $self->fixed_param_names; | ||
| 261 | $self->state_names([]) unless defined $self->state_names; | ||
| 262 | my $data_shapes = []; | ||
| 263 | for my $d (@{ $self->data_shapes }) | ||
| 264 | { | ||
| 265 | $d = AI::MXNet::DataDesc->new(name => $d->[0], shape => $d->[1]) | ||
| 266 | unless blessed $d; | ||
| 267 | push @{ $data_shapes }, $d; | ||
| 268 | } | ||
| 269 | $self->data_shapes($data_shapes); | ||
| 270 | if(defined $self->label_shapes) | ||
| 271 | { | ||
| 272 | my $label_shapes = []; | ||
| 273 | for my $l (@{ $self->label_shapes }) | ||
| 274 | { | ||
| 275 | $l = AI::MXNet::DataDesc->new(name => $l->[0], shape => $l->[1]) | ||
| 276 | unless blessed $l; | ||
| 277 | push @{ $label_shapes }, $l; | ||
| 278 | } | ||
| 279 | $self->label_shapes($label_shapes); | ||
| 280 | } | ||
| 281 | my %data_names = map { $_->name => 1 } @{ $self->data_shapes }; | ||
| 282 | my %param_names = map { $_ => 1 } @{ $self->param_names }; | ||
| 283 | my %fixed_param_names = map { $_ => 1 } @{ $self->fixed_param_names }; | ||
| 284 | my %grad_req; | ||
| 285 | if(not ref $self->grad_req) | ||
| 286 | { | ||
| 287 | for my $k (@{ $self->_p->arg_names }) | ||
| 288 | { | ||
| 289 | if(exists $param_names{ $k }) | ||
| 290 | { | ||
| 291 | $grad_req{$k} = exists $fixed_param_names{ $k } ? 'null' : $self->grad_req; | ||
| 292 | } | ||
| 293 | elsif(exists $data_names{ $k }) | ||
| 294 | { | ||
| 295 | $grad_req{$k} = $self->inputs_need_grad ? $self->grad_req : 'null'; | ||
| 296 | } | ||
| 297 | else | ||
| 298 | { | ||
| 299 | $grad_req{$k} = 'null'; | ||
| 300 | } | ||
| 301 | } | ||
| 302 | } | ||
| 303 | elsif(ref $self->grad_req eq 'ARRAY') | ||
| 304 | { | ||
| 305 | @grad_req{ @{ $self->_p->arg_names } } = @{ $self->grad_req }; | ||
| 306 | } | ||
| 307 | else | ||
| 308 | { | ||
| 309 | for my $k (@{ $self->_p->arg_names }) | ||
| 310 | { | ||
| 311 | if(exists $param_names{ $k }) | ||
| 312 | { | ||
| 313 | $grad_req{$k} = exists $fixed_param_names{ $k } ? 'null' : 'write'; | ||
| 314 | } | ||
| 315 | elsif(exists $data_names{ $k }) | ||
| 316 | { | ||
| 317 | $grad_req{$k} = $self->inputs_need_grad ? 'write' : 'null'; | ||
| 318 | } | ||
| 319 | else | ||
| 320 | { | ||
| 321 | $grad_req{$k} = 'null'; | ||
| 322 | } | ||
| 323 | } | ||
| 324 | %grad_req = (%grad_req, %{ $self->grad_req }); | ||
| 325 | } | ||
| 326 | $self->grad_req(\%grad_req); | ||
| 327 | if(defined $self->shared_group) | ||
| 328 | { | ||
| 329 | $self->_p->shared_data_arrays($self->shared_group->_p->shared_data_arrays); | ||
| 330 | } | ||
| 331 | else | ||
| 332 | { | ||
| 333 | $self->_p->shared_data_arrays([map { +{} } 0..@{ $self->contexts }-1]); | ||
| 334 | } | ||
| 335 | $self->_p->output_layouts([ | ||
| 336 | map { | ||
| 337 | AI::MXNet::DataDesc->get_batch_axis($self->symbol->slice($_)->attr('__layout__')) | ||
| 338 | } @{ $self->symbol->list_outputs } | ||
| 339 | ]); | ||
| 340 | $self->bind_exec($self->data_shapes, $self->label_shapes, $self->shared_group); | ||
| 341 | } | ||
| 342 | |||
| 343 | =head2 decide_slices | ||
| 344 | |||
| 345 | Decide the slices for each context according to the workload. | ||
| 346 | |||
| 347 | Parameters | ||
| 348 | ---------- | ||
| 349 | $data_shapes : ArrayRef[AI::MXNet::DataDesc] | ||
| 350 | =cut | ||
| 351 | |||
| 352 | method decide_slices(ArrayRef[AI::MXNet::DataDesc] $data_shapes) | ||
| 353 | { | ||
| 354 | confess("empty data_shapes array") unless @{ $data_shapes } > 0; | ||
| 355 | my $major_axis = [map { AI::MXNet::DataDesc->get_batch_axis($_->layout) } @{ $data_shapes }]; | ||
| 356 | for(zip($data_shapes, $major_axis)) { | ||
| 357 | my ($desc, $axis) = @$_; | ||
| 358 | next if($axis == -1); | ||
| 359 | my $batch_size = $desc->shape->[$axis]; | ||
| 360 | if(defined $self->_p->batch_size) | ||
| 361 | { | ||
| 362 | confess( | ||
| 363 | "all data must have the same batch size: " | ||
| 364 | . sprintf("batch_size = %d, but ", $self->_p->batch_size) | ||
| 365 | . sprintf("%s has shape %s", $desc->name, '('. join(',', @{ $desc->shape }) . ')') | ||
| 366 | ) unless $batch_size == $self->_p->batch_size; | ||
| 367 | } | ||
| 368 | else | ||
| 369 | { | ||
| 370 | $self->_p->batch_size($batch_size); | ||
| 371 | $self->_p->slices(AI::MXNet::Executor::Group::_split_input_slice($self->_p->batch_size, $self->workload)); | ||
| 372 | } | ||
| 373 | } | ||
| 374 | return $major_axis; | ||
| 375 | } | ||
| 376 | |||
| 377 | # Collect internal arrays from executors. | ||
| 378 | method _collect_arrays() | ||
| 379 | { | ||
| 380 | # convenient data structures | ||
| 381 | $self->_p->data_arrays([]); | ||
| 382 | for my $d (@{ $self->data_shapes }) | ||
| 383 | { | ||
| 384 | my $name = $d->name; | ||
| 385 | my @tmp; | ||
| 386 | for my $i (0..@{ $self->_p->execs }-1) | ||
| 387 | { | ||
| 388 | push @tmp, [ $self->_p->slices->[$i], $self->_p->execs->[$i]->arg_dict->{$name} ]; | ||
| 389 | } | ||
| 390 | push @{ $self->_p->data_arrays }, \@tmp; | ||
| 391 | } | ||
| 392 | if(defined $self->label_shapes) | ||
| 393 | { | ||
| 394 | $self->_p->label_arrays([]); | ||
| 395 | for my $l (@{ $self->label_shapes }) | ||
| 396 | { | ||
| 397 | my $name = $l->name; | ||
| 398 | my @tmp; | ||
| 399 | for my $i (0..@{ $self->_p->execs }-1) | ||
| 400 | { | ||
| 401 | push @tmp, [ $self->_p->slices->[$i], $self->_p->execs->[$i]->arg_dict->{$name} ]; | ||
| 402 | } | ||
| 403 | push @{ $self->_p->label_arrays }, \@tmp; | ||
| 404 | } | ||
| 405 | } | ||
| 406 | $self->_p->param_arrays([]); | ||
| 407 | my %param_names = map { $_ => 1 } @{ $self->param_names }; | ||
| 408 | for my $i (0..@{ $self->_p->arg_names }-1) | ||
| 409 | { | ||
| 410 | my $name = $self->_p->arg_names->[$i]; | ||
| 411 | if(exists $param_names{$name}) | ||
| 412 | { | ||
| 413 | my @tmp; | ||
| 414 | for my $exec (@{ $self->_p->execs }) | ||
| 415 | { | ||
| 416 | push @tmp, $exec->arg_arrays->[$i]; | ||
| 417 | } | ||
| 418 | push @{ $self->_p->param_arrays }, \@tmp; | ||
| 419 | } | ||
| 420 | } | ||
| 421 | $self->_p->state_arrays([]); | ||
| 422 | for my $i (0..@{ $self->state_names }-1) | ||
| 423 | { | ||
| 424 | my $name = $self->state_names->[$i]; | ||
| 425 | my @tmp; | ||
| 426 | for my $exec (@{ $self->_p->execs }) | ||
| 427 | { | ||
| 428 | push @tmp, $exec->arg_dict->{$name}; | ||
| 429 | } | ||
| 430 | push @{ $self->_p->state_arrays }, \@tmp; | ||
| 431 | } | ||
| 432 | if($self->for_training) | ||
| 433 | { | ||
| 434 | $self->_p->grad_arrays([]); | ||
| 435 | for my $i (0..@{ $self->_p->arg_names }-1) | ||
| 436 | { | ||
| 437 | my $name = $self->_p->arg_names->[$i]; | ||
| 438 | if(exists $param_names{$name}) | ||
| 439 | { | ||
| 440 | my @tmp; | ||
| 441 | for my $exec (@{ $self->_p->execs }) | ||
| 442 | { | ||
| 443 | push @tmp, $exec->grad_arrays->[$i]; | ||
| 444 | } | ||
| 445 | push @{ $self->_p->grad_arrays }, \@tmp; | ||
| 446 | } | ||
| 447 | } | ||
| 448 | } | ||
| 449 | my @data_names = map { $_->name } @{ $self->data_shapes }; | ||
| 450 | my $j = 0; my %arg_names = map { $_ => $j++ } @{ $self->_p->arg_names }; | ||
| 451 | if($self->inputs_need_grad) | ||
| 452 | { | ||
| 453 | $self->_p->input_grad_arrays([]); | ||
| 454 | for my $name (@data_names) | ||
| 455 | { | ||
| 456 | next unless exists $arg_names{$name}; | ||
| 457 | my @tmp; | ||
| 458 | for my $exec (@{ $self->_p->execs }) | ||
| 459 | { | ||
| 460 | push @tmp, $exec->grad_arrays->[$arg_names{$name}]; | ||
| 461 | } | ||
| 462 | push @{ $self->_p->input_grad_arrays }, \@tmp; | ||
| 463 | } | ||
| 464 | } | ||
| 465 | $self->_p->aux_arrays([]); | ||
| 466 | for my $i (0..@{ $self->_p->aux_names }-1) | ||
| 467 | { | ||
| 468 | my @tmp; | ||
| 469 | for my $exec (@{ $self->_p->execs }) | ||
| 470 | { | ||
| 471 | push @tmp, $exec->aux_arrays->[$i]; | ||
| 472 | } | ||
| 473 | push @{ $self->_p->aux_arrays }, \@tmp; | ||
| 474 | } | ||
| 475 | } | ||
| 476 | |||
| 477 | =head2 bind_exec | ||
| 478 | |||
| 479 | Bind executors on their respective devices. | ||
| 480 | |||
| 481 | Parameters | ||
| 482 | ---------- | ||
| 483 | $data_shapes : ArrayRef[AI::MXNet::DataDesc] | ||
| 484 | $label_shapes : Maybe[ArrayRef[AI::MXNet::DataDesc]] | ||
| 485 | $shared_group : Maybe[AI::MXNet::DataParallelExecutorGroup] | ||
| 486 | $reshape : Bool | ||
| 487 | =cut | ||
| 488 | |||
| 489 | method bind_exec( | ||
| 490 | ArrayRef[AI::MXNet::DataDesc] $data_shapes, | ||
| 491 | Maybe[ArrayRef[AI::MXNet::DataDesc]] $label_shapes=, | ||
| 492 | Maybe[AI::MXNet::DataParallelExecutorGroup] $shared_group=, | ||
| 493 | Bool $reshape=0 | ||
| 494 | ) | ||
| 495 | { | ||
| 496 | assert($reshape or not @{ $self->_p->execs }); | ||
| 497 | $self->_p->batch_size(undef); | ||
| 498 | |||
| 499 | # calculate workload and bind executors | ||
| 500 | $self->_p->data_layouts($self->decide_slices($data_shapes)); | ||
| 501 | # call it to make sure labels has the same batch size as data | ||
| 502 | if(defined $label_shapes) | ||
| 503 | { | ||
| 504 | $self->_p->label_layouts($self->decide_slices($label_shapes)); | ||
| 505 | } | ||
| 506 | |||
| 507 | for my $i (0..@{ $self->contexts }-1) | ||
| 508 | { | ||
| 509 | my $data_shapes_i = $self->_sliced_shape($data_shapes, $i, $self->_p->data_layouts); | ||
| 510 | my $label_shapes_i = []; | ||
| 511 | if(defined $label_shapes) | ||
| 512 | { | ||
| 513 | $label_shapes_i = $self->_sliced_shape($label_shapes, $i, $self->_p->label_layouts); | ||
| 514 | } | ||
| 515 | if($reshape) | ||
| 516 | { | ||
| 517 | my %combined_hash = map { $_->name => $_->shape } (@{ $data_shapes_i }, @{ $label_shapes_i }); | ||
| 518 | $self->_p->execs->[$i] = $self->_p->_default_execs->[$i]->reshape( | ||
| 519 | \%combined_hash, | ||
| 520 | allow_up_sizing => 1, | ||
| 521 | ); | ||
| 522 | } | ||
| 523 | else | ||
| 524 | { | ||
| 525 | push @{ $self->_p->execs }, $self->_bind_ith_exec($i, $data_shapes_i, $label_shapes_i, $shared_group); | ||
| 526 | } | ||
| 527 | } | ||
| 528 | $self->data_shapes($data_shapes); | ||
| 529 | $self->label_shapes($label_shapes); | ||
| 530 | $self->_collect_arrays; | ||
| 531 | } | ||
| 532 | |||
| 533 | =head2 reshape | ||
| 534 | |||
| 535 | Reshape executors. | ||
| 536 | |||
| 537 | Parameters | ||
| 538 | ---------- | ||
| 539 | $data_shapes : ArrayRef[AI::MXNet::DataDesc] | ||
| 540 | $label_shapes : Maybe[ArrayRef[AI::MXNet::DataDesc]] | ||
| 541 | =cut | ||
| 542 | |||
| 543 | |||
| 544 | method reshape( | ||
| 545 | ArrayRef[AI::MXNet::DataDesc] $data_shapes, | ||
| 546 | Maybe[ArrayRef[AI::MXNet::DataDesc]] $label_shapes= | ||
| 547 | ) | ||
| 548 | { | ||
| 549 | return if($data_shapes eq $self->data_shapes and $label_shapes eq $self->label_shapes); | ||
| 550 | if (not defined $self->_p->_default_execs) | ||
| 551 | { | ||
| 552 | $self->_p->_default_execs([@{ $self->_p->execs }]); | ||
| 553 | } | ||
| 554 | $self->bind_exec($data_shapes, $label_shapes, undef, 1); | ||
| 555 | } | ||
| 556 | |||
| 557 | =head2 set_params | ||
| 558 | |||
| 559 | Assign, i.e. copy parameters to all the executors. | ||
| 560 | |||
| 561 | Parameters | ||
| 562 | ---------- | ||
| 563 | $arg_params : HashRef[AI::MXNet::NDArray] | ||
| 564 | A dictionary of name to AI::MXNet::NDArray parameter mapping. | ||
| 565 | $aux_params : HashRef[AI::MXNet::NDArray] | ||
| 566 | A dictionary of name to AI::MXNet::NDArray auxiliary variable mapping. | ||
| 567 | =cut | ||
| 568 | |||
| 569 | method set_params(HashRef[AI::MXNet::NDArray] $arg_params, HashRef[AI::MXNet::NDArray] $aux_params, Bool $allow_extra=0) | ||
| 570 | { | ||
| 571 | $_->copy_params_from($arg_params, $aux_params, $allow_extra) for @{ $self->_p->execs }; | ||
| 572 | } | ||
| 573 | |||
| 574 | =head2 get_params | ||
| 575 | |||
| 576 | Copy data from each executor to arg_params and aux_params. | ||
| 577 | |||
| 578 | Parameters | ||
| 579 | ---------- | ||
| 580 | $arg_params : HashRef[AI::MXNet::NDArray] | ||
| 581 | target parameter arrays | ||
| 582 | $aux_params : HashRef[AI::MXNet::NDArray] | ||
| 583 | target aux arrays | ||
| 584 | |||
| 585 | Notes | ||
| 586 | ----- | ||
| 587 | - This function will inplace update the NDArrays in arg_params and aux_params. | ||
| 588 | =cut | ||
| 589 | |||
| 590 | method get_params(HashRef[AI::MXNet::NDArray] $arg_params, HashRef[AI::MXNet::NDArray] $aux_params) | ||
| 591 | { | ||
| 592 | my $weight = 0; | ||
| 593 | for(zip($self->param_names, $self->_p->param_arrays)) { | ||
| 594 | my ($name, $block) = @$_; | ||
| 595 | my $weight = sum(map { $_->copyto(AI::MXNet::Context->cpu) } @{ $block }) / @{ $block }; | ||
| 596 | $weight->astype($arg_params->{$name}->dtype)->copyto($arg_params->{$name}); | ||
| 597 | } | ||
| 598 | for(zip($self->_p->aux_names, $self->_p->aux_arrays)) { | ||
| 599 | my ($name, $block) = @$_; | ||
| 600 | my $weight = sum(map { $_->copyto(AI::MXNet::Context->cpu) } @{ $block }) / @{ $block }; | ||
| 601 | $weight->astype($aux_params->{$name}->dtype)->copyto($aux_params->{$name}); | ||
| 602 | } | ||
| 603 | } | ||
| 604 | |||
| 605 | |||
| 606 | |||
| 607 | method get_states($merge_multi_context=1) | ||
| 608 | { | ||
| 609 | assert((not $merge_multi_context), "merge_multi_context=True is not supported for get_states yet."); | ||
| 610 | return $self->_p->state_arrays; | ||
| 611 | } | ||
| 612 | |||
| 613 | method set_states($states, $value) | ||
| 614 | { | ||
| 615 | if(defined $states) | ||
| 616 | { | ||
| 617 | assert((not defined $value), "Only one of states & value can be specified."); | ||
| 618 | AI::MXNet::Executor::Group::_load_general($states, $self->_p->state_arrays, [(0)x@{ $states }]); | ||
| 619 | } | ||
| 620 | else | ||
| 621 | { | ||
| 622 | assert((defined $value), "At least one of states & value must be specified."); | ||
| 623 | assert((not defined $states), "Only one of states & value can be specified."); | ||
| 624 | for my $d_dst (@{ $self->_p->state_arrays }) | ||
| 625 | { | ||
| 626 | for my $dst (@{ $d_dst }) | ||
| 627 | { | ||
| 628 | $dst .= $value; | ||
| 629 | } | ||
| 630 | } | ||
| 631 | } | ||
| 632 | } | ||
| 633 | |||
| 634 | =head2 forward | ||
| 635 | |||
| 636 | Split the data_batch according to a workload and run forward on each devices. | ||
| 637 | |||
| 638 | Parameters | ||
| 639 | ---------- | ||
| 640 | data_batch : AI::MXNet::DataBatch | ||
| 641 | Or could be any object implementing similar interface. | ||
| 642 | |||
| 643 | is_train : bool | ||
| 644 | The hint for the backend, indicating whether we are during training phase. | ||
| 645 | Default is undef, then the value $self->for_training will be used. | ||
| 646 | =cut | ||
| 647 | |||
| 648 | |||
| 649 | method forward(AI::MXNet::DataBatch $data_batch, Maybe[Bool] $is_train=) | ||
| 650 | { | ||
| 651 | AI::MXNet::Executor::Group::_load_data($data_batch, $self->_p->data_arrays, $self->_p->data_layouts); | ||
| 652 | $is_train //= $self->for_training; | ||
| 653 | if(defined $self->_p->label_arrays) | ||
| 654 | { | ||
| 655 | confess("assert not is_train or data_batch.label") | ||
| 656 | unless (not $is_train or $data_batch->label); | ||
| 657 | if($data_batch->label) | ||
| 658 | { | ||
| 659 | AI::MXNet::Executor::Group::_load_label($data_batch, $self->_p->label_arrays, $self->_p->label_layouts); | ||
| 660 | } | ||
| 661 | } | ||
| 662 | $_->forward($is_train) for @{ $self->_p->execs }; | ||
| 663 | } | ||
| 664 | |||
| 665 | # Get the shapes of the outputs | ||
| 666 | |||
| 667 | method get_output_shapes() | ||
| 668 | { | ||
| 669 | my @shapes = map { $_->shape } @{ $self->execs->[0]->outputs }; | ||
| 670 | my @concat_shapes; | ||
| 671 | for(zip($self->symbol->list_outputs, \@shapes, $self->_p->output_layouts)) { | ||
| 672 | my ($key, $shape, $axis) = @$_; | ||
| 673 | my @the_shape = @{ $shape }; | ||
| 674 | if($axis >= 0) | ||
| 675 | { | ||
| 676 | $the_shape[$axis] = $self->_p->batch_size; | ||
| 677 | } | ||
| 678 | push @concat_shapes, AI::MXNet::DataDesc->new(name => $key, shape => \@the_shape); | ||
| 679 | } | ||
| 680 | return \@concat_shapes; | ||
| 681 | } | ||
| 682 | |||
| 683 | =head2 get_outputs | ||
| 684 | |||
| 685 | Gets outputs of the previous forward computation. | ||
| 686 | |||
| 687 | Parameters | ||
| 688 | ---------- | ||
| 689 | merge_multi_context : bool | ||
| 690 | Default is 1. In the case when data-parallelism is used, the outputs | ||
| 691 | will be collected from multiple devices. A 1 value indicates that we | ||
| 692 | should merge the collected results so that they look like from a single | ||
| 693 | executor. | ||
| 694 | |||
| 695 | Returns | ||
| 696 | ------- | ||
| 697 | If merge_multi_context is 1, it is [$out1, $out2]. Otherwise, it | ||
| 698 | is [[$out1_dev1, $out1_dev2], [$out2_dev1, $out2_dev2]]. All the output | ||
| 699 | elements are `AI::MXNet::NDArray`. | ||
| 700 | =cut | ||
| 701 | |||
| 702 | method get_outputs(Bool $merge_multi_context=1) | ||
| 703 | { | ||
| 704 | my $outputs; | ||
| 705 | for my $i (0..@{ $self->_p->execs->[0]->outputs }-1) | ||
| 706 | { | ||
| 707 | my @tmp; | ||
| 708 | for my $exec (@{ $self->_p->execs }) | ||
| 709 | { | ||
| 710 | push @tmp, $exec->outputs->[$i]; | ||
| 711 | } | ||
| 712 | push @$outputs, \@tmp; | ||
| 713 | } | ||
| 714 | if($merge_multi_context) | ||
| 715 | { | ||
| 716 | $outputs = AI::MXNet::Executor::Group::_merge_multi_context($outputs, $self->_p->output_layouts); | ||
| 717 | } | ||
| 718 | return $outputs; | ||
| 719 | } | ||
| 720 | |||
| 721 | =head2 get_input_grads | ||
| 722 | |||
| 723 | Get the gradients with respect to the inputs of the module. | ||
| 724 | |||
| 725 | Parameters | ||
| 726 | ---------- | ||
| 727 | merge_multi_context : bool | ||
| 728 | Default is 1. In the case when data-parallelism is used, the outputs | ||
| 729 | will be collected from multiple devices. A 1 value indicates that we | ||
| 730 | should merge the collected results so that they look like from a single | ||
| 731 | executor. | ||
| 732 | |||
| 733 | Returns | ||
| 734 | ------- | ||
| 735 | If merge_multi_context is 1, it is [$grad1, $grad2]. Otherwise, it | ||
| 736 | is [[$grad1_dev1, $grad1_dev2], [$grad2_dev1, $grad2_dev2]]. All the output | ||
| 737 | elements are AI::MXNet::NDArray. | ||
| 738 | =cut | ||
| 739 | |||
| 740 | method get_input_grads(Bool $merge_multi_context=1) | ||
| 741 | { | ||
| 742 | confess("assert \$self->inputs_need_grad") unless $self->inputs_need_grad; | ||
| 743 | if($merge_multi_context) | ||
| 744 | { | ||
| 745 | return AI::MXNet::Executor::Group::_merge_multi_context($self->_p->input_grad_arrays, $self->_p->data_layouts); | ||
| 746 | } | ||
| 747 | return $self->_p->input_grad_arrays; | ||
| 748 | } | ||
| 749 | |||
| 750 | =head2 backward | ||
| 751 | |||
| 752 | Run backward on all devices. A backward should be called after | ||
| 753 | a call to the forward function. Backward cannot be called unless | ||
| 754 | $self->for_training is 1. | ||
| 755 | |||
| 756 | Parameters | ||
| 757 | ---------- | ||
| 758 | out_grads : NDArray or array ref of NDArray, optional | ||
| 759 | Gradient on the outputs to be propagated back. | ||
| 760 | This parameter is only needed when bind is called | ||
| 761 | on outputs that are not a loss function. | ||
| 762 | =cut | ||
| 763 | |||
| 764 | method backward(Maybe[AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]] $out_grads=) | ||
| 765 | { | ||
| 766 | confess('re-bind with for_training=1 to run backward') unless $self->for_training; | ||
| 767 | $out_grads //= []; | ||
| 768 | for(zip([0..@{ $self->_p->execs }-1], $self->_p->execs, $self->_p->slices)) { | ||
| 769 | my ($i, $exec, $islice) = @$_; | ||
| 770 | my @out_grads_slice; | ||
| 771 | for(zip($out_grads, $self->_p->output_layouts)) { | ||
| 772 | my ($grad, $axis) = @$_; | ||
| 773 | if($axis >= 0) | ||
| 774 | { | ||
| 775 | my $og_my_slice = $grad->slice_axis({ | ||
| 776 | axis => $axis, | ||
| 777 | begin => $islice->[0], | ||
| 778 | end => $islice->[1] | ||
| 779 | }); | ||
| 780 | push @out_grads_slice, $og_my_slice->as_in_context($self->contexts->[$i]); | ||
| 781 | } | ||
| 782 | else | ||
| 783 | { | ||
| 784 | push @out_grads_slice, $grad->copyto($self->contexts->[$i]); | ||
| 785 | } | ||
| 786 | } | ||
| 787 | $exec->backward(\@out_grads_slice); | ||
| 788 | } | ||
| 789 | } | ||
| 790 | |||
| 791 | =head2 update_metric | ||
| 792 | |||
| 793 | Accumulate the performance according to eval_metric on all devices. | ||
| 794 | |||
| 795 | Parameters | ||
| 796 | ---------- | ||
| 797 | eval_metric : AI::MXNet::EvalMetric | ||
| 798 | The metric used for evaluation. | ||
| 799 | labels : array ref of NDArray | ||
| 800 | Typically comes from label of AI::MXNet::DataBatch. | ||
| 801 | =cut | ||
| 802 | |||
| 803 | method update_metric(AI::MXNet::EvalMetric $eval_metric, ArrayRef[AI::MXNet::NDArray] $labels) | ||
| 804 | { | ||
| 805 | for(zip($self->_p->execs, $self->_p->slices)) { | ||
| 806 | my ($texec, $islice) = @$_; | ||
| 807 | my @labels_slice; | ||
| 808 | for(zip($labels, $self->_p->label_layouts)) { | ||
| 809 | my ($label, $axis) = @$_; | ||
| 810 | if($axis == 0) | ||
| 811 | { | ||
| 812 | # slicing NDArray along axis 0 can avoid copying | ||
| 813 | push @labels_slice, $label->slice([$islice->[0], $islice->[1]-1]); | ||
| 814 | } | ||
| 815 | elsif($axis > 0) | ||
| 816 | { | ||
| 817 | my $label_my_slice = $label->slice_axis({ | ||
| 818 | axis => $axis, | ||
| 819 | begin => $islice->[0], | ||
| 820 | end => $islice->[1] | ||
| 821 | })->as_in_context($label->context); | ||
| 822 | push @labels_slice, $label_my_slice; | ||
| 823 | } | ||
| 824 | else | ||
| 825 | { | ||
| 826 | push @labels_slice, $label; | ||
| 827 | } | ||
| 828 | } | ||
| 829 | $eval_metric->update(\@labels_slice, $texec->outputs); | ||
| 830 | } | ||
| 831 | } | ||
| 832 | |||
| 833 | method _bind_ith_exec( | ||
| 834 | Int $i, | ||
| 835 | ArrayRef[AI::MXNet::DataDesc] $data_shapes, | ||
| 836 | Maybe[ArrayRef[AI::MXNet::DataDesc]] $label_shapes, | ||
| 837 | Maybe[AI::MXNet::DataParallelExecutorGroup] $shared_group | ||
| 838 | ) | ||
| 839 | { | ||
| 840 | my $shared_exec = $shared_group ? $shared_group->_p->execs->[$i] : undef; | ||
| 841 | my $context = $self->contexts->[$i]; | ||
| 842 | my $shared_data_arrays = $self->_p->shared_data_arrays->[$i]; | ||
| 843 | my %input_shapes = map { $_->name => $_->shape } @{ $data_shapes }; | ||
| 844 | my %input_types = map { $_->name => $_->dtype } @{ $data_shapes }; | ||
| 845 | if(defined $label_shapes) | ||
| 846 | { | ||
| 847 | %input_shapes = (%input_shapes, map { $_->name => $_->shape } @{ $label_shapes }); | ||
| 848 | %input_types = (%input_types, map { $_->name => $_->dtype } @{ $label_shapes }); | ||
| 849 | } | ||
| 850 | my $executor = $self->symbol->simple_bind( | ||
| 851 | ctx => $context, | ||
| 852 | grad_req => $self->grad_req, | ||
| 853 | type_dict => \%input_types, | ||
| 854 | shared_arg_names => $self->param_names, | ||
| 855 | shared_exec => $shared_exec, | ||
| 856 | shared_buffer => $shared_data_arrays, | ||
| 857 | shapes => \%input_shapes | ||
| 858 | ); | ||
| 859 | return $executor; | ||
| 860 | } | ||
| 861 | |||
| 862 | =head2 _sliced_shape | ||
| 863 | |||
| 864 | Get the sliced shapes for the i-th executor. | ||
| 865 | |||
| 866 | Parameters | ||
| 867 | ---------- | ||
| 868 | shapes : array ref of (str, array ref) | ||
| 869 | The original (name, shape) pairs. | ||
| 870 | i : int | ||
| 871 | Which executor we are dealing with. | ||
| 872 | =cut | ||
| 873 | |||
| 874 | method _sliced_shape(ArrayRef[AI::MXNet::DataDesc] $shapes, Int $i, ArrayRef[Int] $major_axis) | ||
| 875 | { | ||
| 876 | my @sliced_shapes; | ||
| 877 | for(zip($shapes, $major_axis)) { | ||
| 878 | my ($desc, $axis) = @$_; | ||
| 879 | my @shape = @{ $desc->shape }; | ||
| 880 | if($axis >= 0) | ||
| 881 | { | ||
| 882 | $shape[$axis] = $self->_p->slices->[$i]->[1] - $self->_p->slices->[$i]->[0]; | ||
| 883 | } | ||
| 884 | push @sliced_shapes, AI::MXNet::DataDesc->new( | ||
| 885 | name => $desc->name, | ||
| 886 | shape => \@shape, | ||
| 887 | dtype => $desc->dtype, | ||
| 888 | layout => $desc->layout | ||
| 889 | ); | ||
| 890 | } | ||
| 891 | return \@sliced_shapes; | ||
| 892 | } | ||
| 893 | |||
| 894 | =head2 install_monitor | ||
| 895 | |||
| 896 | Install monitor on all executors | ||
| 897 | |||
| 898 | Parameters | ||
| 899 | ---------- | ||
| 900 | $mon : AI::MXNet::Monitor | ||
| 901 | =cut | ||
| 902 | |||
| 903 | method install_monitor(AI::MXNet::Monitor $mon) | ||
| 904 | { | ||
| 905 | $mon->install($_) for @{ $self->_p->execs }; | ||
| 906 | } | ||
| 907 | |||
| 908 | method shared_data_arrays() | ||
| 909 | { | ||
| 910 | $self->_p->shared_data_arrays; | ||
| 911 | } | ||
| 912 | |||
| 913 | method execs() | ||
| 914 | { | ||
| 915 | $self->_p->execs; | ||
| 916 | } | ||
| 917 | |||
| 918 | 1; |