| 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::Callback; | ||
| 19 | use strict; | ||
| 20 | use warnings; | ||
| 21 | use List::Util qw/max/; | ||
| 22 | use AI::MXNet::NS; | ||
| 23 | use AI::MXNet::Function::Parameters; | ||
| 24 | use Mouse; | ||
| 25 | use overload "&{}" => sub { my $self = shift; sub { $self->call(@_) } }; | ||
| 26 | |||
| 27 | =head1 NAME | ||
| 28 | |||
| 29 | AI::MXNet::Callback - A collection of predefined callback functions. | ||
| 30 | =cut | ||
| 31 | |||
| 32 | =head1 DESCRIPTION | ||
| 33 | |||
| 34 | A collection of predefined callback functions, mainly to be used in AI::MXNet::Module::Base::fit. | ||
| 35 | =cut | ||
| 36 | |||
| 37 | =head1 SYNOPSIS | ||
| 38 | |||
| 39 | my $model = mx->mod->Module( | ||
| 40 | symbol => $net, | ||
| 41 | context => $contexts | ||
| 42 | ); | ||
| 43 | $model->fit( | ||
| 44 | $data_iter, | ||
| 45 | eval_metric => mx->metric->Perplexity, | ||
| 46 | kvstore => $kv_store, | ||
| 47 | optimizer => $optimizer, | ||
| 48 | optimizer_params => { | ||
| 49 | learning_rate => $lr, | ||
| 50 | momentum => $mom, | ||
| 51 | wd => $wd, | ||
| 52 | clip_gradient => 5, | ||
| 53 | rescale_grad => 1/$batch_size, | ||
| 54 | lr_scheduler => AI::MXNet::FactorScheduler->new(step => 1000, factor => 0.99) | ||
| 55 | }, | ||
| 56 | initializer => mx->init->Xavier(factor_type => "in", magnitude => 2.34), | ||
| 57 | num_epoch => $num_epoch, | ||
| 58 | batch_end_callback => mx->callback->Speedometer($batch_size, $disp_batches), | ||
| 59 | ($chkp_epoch ? (epoch_end_callback => [mx->callback->module_checkpoint($model, $chkp_prefix, $chkp_epoch), \&sample]) : ()) | ||
| 60 | ); | ||
| 61 | =cut | ||
| 62 | |||
| 63 | =head2 module_checkpoint | ||
| 64 | |||
| 65 | Callback to save the module setup in the checkpoint files. | ||
| 66 | |||
| 67 | Parameters | ||
| 68 | ---------- | ||
| 69 | $mod : subclass of AI::MXNet::Module::Base | ||
| 70 | The module to checkpoint. | ||
| 71 | $prefix : Str | ||
| 72 | The file prefix to checkpoint to | ||
| 73 | $period=1 : Int | ||
| 74 | How many epochs to wait before checkpointing. Default is 1. | ||
| 75 | $save_optimizer_states=0 : Bool | ||
| 76 | Whether to save optimizer states for later training. | ||
| 77 | |||
| 78 | Returns | ||
| 79 | ------- | ||
| 80 | $callback : sub ref | ||
| 81 | The callback function that can be passed as iter_end_callback to fit. | ||
| 82 | =cut | ||
| 83 | |||
| 84 | method module_checkpoint( | ||
| 85 | AI::MXNet::Module::Base $mod, | ||
| 86 | Str $prefix, | ||
| 87 | Int $period=1, | ||
| 88 | Int $save_optimizer_states=0 | ||
| 89 | ) | ||
| 90 | { | ||
| 91 | $period = max(1, $period); | ||
| 92 | return sub { | ||
| 93 | my ($iter_no, $sym, $arg, $aux) = @_; | ||
| 94 | if(($iter_no + 1) % $period == 0) | ||
| 95 | { | ||
| 96 | $mod->save_checkpoint($prefix, $iter_no + 1, $save_optimizer_states); | ||
| 97 | } | ||
| 98 | } | ||
| 99 | } | ||
| 100 | |||
| 101 | =head2 log_train_metric | ||
| 102 | |||
| 103 | Callback to log the training evaluation result every period. | ||
| 104 | |||
| 105 | Parameters | ||
| 106 | ---------- | ||
| 107 | $period : Int | ||
| 108 | The number of batches after which to log the training evaluation metric. | ||
| 109 | $auto_reset : Bool | ||
| 110 | Whether to reset the metric after the logging. | ||
| 111 | |||
| 112 | Returns | ||
| 113 | ------- | ||
| 114 | $callback : sub ref | ||
| 115 | The callback function that can be passed as iter_epoch_callback to fit. | ||
| 116 | =cut | ||
| 117 | |||
| 118 | method log_train_metric(Int $period, Int $auto_reset=0) | ||
| 119 | { | ||
| 120 | return sub { | ||
| 121 | my ($param) = @_; | ||
| 122 | if($param->nbatch % $period == 0 and defined $param->eval_metric) | ||
| 123 | { | ||
| 124 | my $name_value = $param->eval_metric->get_name_value; | ||
| 125 | while(my ($name, $value) = each %{ $name_value }) | ||
| 126 | { | ||
| 127 | AI::MXNet::Logging->info( | ||
| 128 | "Iter[%d] Batch[%d] Train-%s=%f", | ||
| 129 | $param->epoch, $param->nbatch, $name, $value | ||
| 130 | ); | ||
| 131 | } | ||
| 132 | $param->eval_metric->reset if $auto_reset; | ||
| 133 | } | ||
| 134 | } | ||
| 135 | } | ||
| 136 | |||
| 137 | package AI::MXNet::Speedometer; | ||
| 138 | use Mouse; | ||
| 139 | use Time::HiRes qw/time/; | ||
| 140 | extends 'AI::MXNet::Callback'; | ||
| 141 | |||
| 142 | =head1 NAME | ||
| 143 | |||
| 144 | AI::MXNet::Speedometer - A callback that logs training speed | ||
| 145 | =cut | ||
| 146 | |||
| 147 | =head1 DESCRIPTION | ||
| 148 | |||
| 149 | Calculate and log training speed periodically. | ||
| 150 | |||
| 151 | Parameters | ||
| 152 | ---------- | ||
| 153 | batch_size: int | ||
| 154 | batch_size of data | ||
| 155 | frequent: int | ||
| 156 | How many batches between calculations. | ||
| 157 | Defaults to calculating & logging every 50 batches. | ||
| 158 | auto_reset: Bool | ||
| 159 | Reset the metric after each log, defaults to true. | ||
| 160 | =cut | ||
| 161 | |||
| 162 | has 'batch_size' => (is => 'ro', isa => 'Int', required => 1); | ||
| 163 | has 'frequent' => (is => 'ro', isa => 'Int', default => 50); | ||
| 164 | has 'init' => (is => 'rw', isa => 'Int', default => 0); | ||
| 165 | has 'tic' => (is => 'rw', isa => 'Num', default => 0); | ||
| 166 | has 'last_count' => (is => 'rw', isa => 'Int', default => 0); | ||
| 167 | has 'auto_reset' => (is => 'ro', isa => 'Bool', default => 1); | ||
| 168 | |||
| 169 | method call(AI::MXNet::BatchEndParam $param) | ||
| 170 | { | ||
| 171 | my $count = $param->nbatch; | ||
| 172 | if($self->last_count > $count) | ||
| 173 | { | ||
| 174 | $self->init(0); | ||
| 175 | } | ||
| 176 | $self->last_count($count); | ||
| 177 | |||
| 178 | if($self->init) | ||
| 179 | { | ||
| 180 | if(($count % $self->frequent) == 0) | ||
| 181 | { | ||
| 182 | my $speed = $self->frequent * $self->batch_size / (time - $self->tic); | ||
| 183 | if(defined $param->eval_metric) | ||
| 184 | { | ||
| 185 | my $name_value = $param->eval_metric->get_name_value; | ||
| 186 | $param->eval_metric->reset if $self->auto_reset; | ||
| 187 | while(my ($name, $value) = each %{ $name_value }) | ||
| 188 | { | ||
| 189 | AI::MXNet::Logging->info( | ||
| 190 | "Epoch[%d] Batch [%d]\tSpeed: %.2f samples/sec\tTrain-%s=%f", | ||
| 191 | $param->epoch, $count, $speed, $name, $value | ||
| 192 | ); | ||
| 193 | } | ||
| 194 | } | ||
| 195 | else | ||
| 196 | { | ||
| 197 | AI::MXNet::Logging->info( | ||
| 198 | "Iter[%d] Batch [%d]\tSpeed: %.2f samples/sec", | ||
| 199 | $param->epoch, $count, $speed | ||
| 200 | ); | ||
| 201 | } | ||
| 202 | $self->tic(time); | ||
| 203 | } | ||
| 204 | } | ||
| 205 | else | ||
| 206 | { | ||
| 207 | $self->init(1); | ||
| 208 | $self->tic(time); | ||
| 209 | } | ||
| 210 | } | ||
| 211 | |||
| 212 | *slice = \&call; | ||
| 213 | |||
| 214 | package AI::MXNet::ProgressBar; | ||
| 215 | use Mouse; | ||
| 216 | extends 'AI::MXNet::Callback'; | ||
| 217 | |||
| 218 | =head1 NAME | ||
| 219 | |||
| 220 | AI::MXNet::ProgressBar - A callback to show a progress bar. | ||
| 221 | |||
| 222 | =head1 DESCRIPTION | ||
| 223 | |||
| 224 | Shows a progress bar. | ||
| 225 | |||
| 226 | Parameters | ||
| 227 | ---------- | ||
| 228 | total: Int | ||
| 229 | batch size, default is 1 | ||
| 230 | length: Int | ||
| 231 | the length of the progress bar, default is 80 chars | ||
| 232 | =cut | ||
| 233 | |||
| 234 | has 'length' => (is => 'ro', isa => 'Int', default => 80); | ||
| 235 | has 'total' => (is => 'ro', isa => 'Int', required => 1); | ||
| 236 | |||
| 237 | method call(AI::MXNet::BatchEndParam $param) | ||
| 238 | { | ||
| 239 | my $count = $param->nbatch; | ||
| 240 | my $filled_len = int(0.5 + $self->length * $count / $self->total); | ||
| 241 | my $percents = int(100.0 * $count / $self->total) + 1; | ||
| 242 | my $prog_bar = ('=' x $filled_len) . ('-' x ($self->length - $filled_len)); | ||
| 243 | print "[$prog_bar] $percents%\r"; | ||
| 244 | } | ||
| 245 | |||
| 246 | *slice = \&call; | ||
| 247 | |||
| 248 | # Just logs the eval metrics at the end of an epoch. | ||
| 249 | package AI::MXNet::LogValidationMetricsCallback; | ||
| 250 | use Mouse; | ||
| 251 | extends 'AI::MXNet::Callback'; | ||
| 252 | |||
| 253 | =head1 NAME | ||
| 254 | |||
| 255 | AI::MXNet::LogValidationMetricsCallback - A callback to log the eval metrics at the end of an epoch. | ||
| 256 | =cut | ||
| 257 | |||
| 258 | method call(AI::MXNet::BatchEndParam $param) | ||
| 259 | { | ||
| 260 | return unless defined $param->eval_metric; | ||
| 261 | my $name_value = $param->eval_metric->get_name_value; | ||
| 262 | while(my ($name, $value) = each %{ $name_value }) | ||
| 263 | { | ||
| 264 | AI::MXNet::Logging->info( | ||
| 265 | "Epoch[%d] Validation-%s=%f", | ||
| 266 | $param->epoch, $name, $value | ||
| 267 | ); | ||
| 268 | } | ||
| 269 | } | ||
| 270 | |||
| 271 | package AI::MXNet::Callback; | ||
| 272 | |||
| 273 | method Speedometer(@args) | ||
| 274 | { | ||
| 275 | AI::MXNet::Speedometer->new( | ||
| 276 | @args == 3 ? | ||
| 277 | (batch_size => $args[0], frequent => $args[1], auto_reset => $args[2]) | ||
| 278 | : @args == 2 ? | ||
| 279 | (batch_size => $args[0], frequent => $args[1]) | ||
| 280 | : (batch_size => $args[0]) | ||
| 281 | ) | ||
| 282 | } | ||
| 283 | |||
| 284 | method ProgressBar(@args) | ||
| 285 | { | ||
| 286 | AI::MXNet::ProgressBar->new( | ||
| 287 | @args == 2 ? (total => $args[0], 'length' => $args[1]) : (total => $args[0]) | ||
| 288 | ) | ||
| 289 | } | ||
| 290 | |||
| 291 | method LogValidationMetricsCallback() | ||
| 292 | { | ||
| 293 | AI::MXNet::LogValidationMetricsCallback->new | ||
| 294 | } | ||
| 295 | |||
| 296 | 1; |