| 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::Visualization; | ||
| 19 | use strict; | ||
| 20 | use warnings; | ||
| 21 | use AI::MXNet::NS; | ||
| 22 | use AI::MXNet::Base; | ||
| 23 | use AI::MXNet::Function::Parameters; | ||
| 24 | use JSON::PP; | ||
| 25 | |||
| 26 | =encoding UTF-8 | ||
| 27 | |||
| 28 | =head1 NAME | ||
| 29 | |||
| 30 | AI::MXNet::Vizualization - Vizualization support for Perl interface to MXNet machine learning library | ||
| 31 | |||
| 32 | =head1 SYNOPSIS | ||
| 33 | |||
| 34 | use strict; | ||
| 35 | use warnings; | ||
| 36 | use AI::MXNet qw(mx); | ||
| 37 | |||
| 38 | ### model | ||
| 39 | my $data = mx->symbol->Variable('data'); | ||
| 40 | my $conv1= mx->symbol->Convolution(data => $data, name => 'conv1', num_filter => 32, kernel => [3,3], stride => [2,2]); | ||
| 41 | my $bn1 = mx->symbol->BatchNorm(data => $conv1, name => "bn1"); | ||
| 42 | my $act1 = mx->symbol->Activation(data => $bn1, name => 'relu1', act_type => "relu"); | ||
| 43 | my $mp1 = mx->symbol->Pooling(data => $act1, name => 'mp1', kernel => [2,2], stride =>[2,2], pool_type=>'max'); | ||
| 44 | |||
| 45 | my $conv2= mx->symbol->Convolution(data => $mp1, name => 'conv2', num_filter => 32, kernel=>[3,3], stride=>[2,2]); | ||
| 46 | my $bn2 = mx->symbol->BatchNorm(data => $conv2, name=>"bn2"); | ||
| 47 | my $act2 = mx->symbol->Activation(data => $bn2, name=>'relu2', act_type=>"relu"); | ||
| 48 | my $mp2 = mx->symbol->Pooling(data => $act2, name => 'mp2', kernel=>[2,2], stride=>[2,2], pool_type=>'max'); | ||
| 49 | |||
| 50 | |||
| 51 | my $fl = mx->symbol->Flatten(data => $mp2, name=>"flatten"); | ||
| 52 | my $fc1 = mx->symbol->FullyConnected(data => $fl, name=>"fc1", num_hidden=>30); | ||
| 53 | my $act3 = mx->symbol->Activation(data => $fc1, name=>'relu3', act_type=>"relu"); | ||
| 54 | my $fc2 = mx->symbol->FullyConnected(data => $act3, name=>'fc2', num_hidden=>10); | ||
| 55 | my $softmax = mx->symbol->SoftmaxOutput(data => $fc2, name => 'softmax'); | ||
| 56 | |||
| 57 | ## creates the image file working directory | ||
| 58 | mx->viz->plot_network($softmax, save_format => 'png')->render("network.png"); | ||
| 59 | |||
| 60 | =head1 DESCRIPTION | ||
| 61 | |||
| 62 | Vizualization support for Perl interface to MXNet machine learning library | ||
| 63 | |||
| 64 | =head1 Class methods | ||
| 65 | |||
| 66 | =head2 print_summary | ||
| 67 | |||
| 68 | convert symbol for detail information | ||
| 69 | |||
| 70 | Parameters | ||
| 71 | ---------- | ||
| 72 | symbol: AI::MXNet::Symbol | ||
| 73 | symbol to be visualized | ||
| 74 | shape: hashref | ||
| 75 | hashref of shapes, str->shape (arrayref[int]), given input shapes | ||
| 76 | line_length: int | ||
| 77 | total length of printed lines | ||
| 78 | positions: arrayref[float] | ||
| 79 | relative or absolute positions of log elements in each line | ||
| 80 | Returns | ||
| 81 | ------ | ||
| 82 | nothing | ||
| 83 | =cut | ||
| 84 | |||
| 85 | method print_summary( | ||
| 86 | AI::MXNet::Symbol $symbol, | ||
| 87 | Maybe[HashRef[Shape]] $shape=, | ||
| 88 | Int $line_length=120, | ||
| 89 | ArrayRef[Num] $positions=[.44, .64, .74, 1] | ||
| 90 | ) | ||
| 91 | { | ||
| 92 | my $show_shape; | ||
| 93 | my %shape_dict; | ||
| 94 | if(defined $shape) | ||
| 95 | { | ||
| 96 | $show_shape = 1; | ||
| 97 | my $interals = $symbol->get_internals; | ||
| 98 | my (undef, $out_shapes, undef) = $interals->infer_shape(%{ $shape }); | ||
| 99 | Carp::confess("Input shape is incomplete") | ||
| 100 | unless defined $out_shapes; | ||
| 101 | @shape_dict{ @{ $interals->list_outputs } } = @{ $out_shapes }; | ||
| 102 | } | ||
| 103 | my $conf = decode_json($symbol->tojson); | ||
| 104 | my $nodes = $conf->{nodes}; | ||
| 105 | my %heads = map { $_ => 1 } @{ $conf->{heads}[0] }; | ||
| 106 | if($positions->[-1] <= 1) | ||
| 107 | { | ||
| 108 | $positions = [map { int($line_length * $_) } @{ $positions }]; | ||
| 109 | } | ||
| 110 | # header names for the different log elements | ||
| 111 | my $to_display = ['Layer (type)', 'Output Shape', 'Param #', 'Previous Layer']; | ||
| 112 | my $print_row = sub { my ($fields, $positions) = @_; | ||
| 113 | my $line = ''; | ||
| 114 | enumerate(sub { | ||
| 115 | my ($i, $field) = @_; | ||
| 116 | $line .= $field//''; | ||
| 117 | $line = substr($line, 0, $positions->[$i]); | ||
| 118 | $line .= ' ' x ($positions->[$i] - length($line)); | ||
| 119 | |||
| 120 | }, $fields); | ||
| 121 | print $line,"\n"; | ||
| 122 | }; | ||
| 123 | print('_' x $line_length,"\n"); | ||
| 124 | $print_row->($to_display, $positions); | ||
| 125 | print('=' x $line_length,"\n"); | ||
| 126 | my $print_layer_summary = sub { my ($node, $out_shape) = @_; | ||
| 127 | my $op = $node->{op}; | ||
| 128 | my $pre_node = []; | ||
| 129 | my $pre_filter = 0; | ||
| 130 | if($op ne 'null') | ||
| 131 | { | ||
| 132 | my $inputs = $node->{inputs}; | ||
| 133 | for my $item (@{ $inputs }) | ||
| 134 | { | ||
| 135 | my $input_node = $nodes->[$item->[0]]; | ||
| 136 | my $input_name = $input_node->{name}; | ||
| 137 | if($input_node->{op} ne 'null' or exists $heads{ $item->[0] }) | ||
| 138 | { | ||
| 139 | push @{ $pre_node }, $input_name; | ||
| 140 | if($show_shape) | ||
| 141 | { | ||
| 142 | my $key = $input_name; | ||
| 143 | $key .= '_output' if $input_node->{op} ne 'null'; | ||
| 144 | if(exists $shape_dict{ $key }) | ||
| 145 | { | ||
| 146 | $pre_filter = $pre_filter + int($shape_dict{$key}[1]//0); | ||
| 147 | } | ||
| 148 | } | ||
| 149 | } | ||
| 150 | } | ||
| 151 | } | ||
| 152 | my $cur_param = 0; | ||
| 153 | if($op eq 'Convolution') | ||
| 154 | { | ||
| 155 | my $num_filter = $node->{attrs}{num_filter}; | ||
| 156 | $cur_param = $pre_filter * $num_filter; | ||
| 157 | while($node->{attrs}{kernel} =~ /(\d+)/g) | ||
| 158 | { | ||
| 159 | $cur_param *= $1; | ||
| 160 | } | ||
| 161 | $cur_param += $num_filter; | ||
| 162 | } | ||
| 163 | elsif($op eq 'FullyConnected') | ||
| 164 | { | ||
| 165 | $cur_param = $pre_filter * ($node->{attrs}{num_hidden} + 1); | ||
| 166 | } | ||
| 167 | elsif($op eq 'BatchNorm') | ||
| 168 | { | ||
| 169 | my $key = "$node->{name}_output"; | ||
| 170 | if($show_shape) | ||
| 171 | { | ||
| 172 | my $num_filter = $shape_dict{$key}[1]; | ||
| 173 | $cur_param = $num_filter * 2; | ||
| 174 | } | ||
| 175 | } | ||
| 176 | elsif($op eq 'Embedding') | ||
| 177 | { | ||
| 178 | $cur_param = $node->{attrs}{input_dim} * $node->{attrs}{output_dim}; | ||
| 179 | } | ||
| 180 | my $first_connection; | ||
| 181 | if(not $pre_node) | ||
| 182 | { | ||
| 183 | $first_connection = ''; | ||
| 184 | } | ||
| 185 | else | ||
| 186 | { | ||
| 187 | $first_connection = $pre_node->[0]; | ||
| 188 | } | ||
| 189 | my $fields = [ | ||
| 190 | $node->{name} . '(' . $op . ')', | ||
| 191 | join('x', @{ $out_shape }), | ||
| 192 | $cur_param, | ||
| 193 | $first_connection | ||
| 194 | ]; | ||
| 195 | $print_row->($fields, $positions); | ||
| 196 | if(@{ $pre_node } > 1) | ||
| 197 | { | ||
| 198 | for my $i (1..@{ $pre_node }-1) | ||
| 199 | { | ||
| 200 | $fields = ['', '', '', $pre_node->[$i]]; | ||
| 201 | $print_row->($fields, $positions); | ||
| 202 | } | ||
| 203 | } | ||
| 204 | return $cur_param; | ||
| 205 | }; | ||
| 206 | my $total_params = 0; | ||
| 207 | enumerate(sub { | ||
| 208 | my ($i, $node) = @_; | ||
| 209 | my $out_shape = []; | ||
| 210 | my $op = $node->{op}; | ||
| 211 | return if($op eq 'null' and $i > 0); | ||
| 212 | if($op ne 'null' or exists $heads{$i}) | ||
| 213 | { | ||
| 214 | if($show_shape) | ||
| 215 | { | ||
| 216 | my $key = $node->{name}; | ||
| 217 | $key .= '_output' if $op ne 'null'; | ||
| 218 | if(exists $shape_dict{ $key }) | ||
| 219 | { | ||
| 220 | my $end = @{ $shape_dict{ $key } }; | ||
| 221 | @{ $out_shape } = @{ $shape_dict{ $key } }[1..$end-1]; | ||
| 222 | } | ||
| 223 | } | ||
| 224 | } | ||
| 225 | $total_params += $print_layer_summary->($nodes->[$i], $out_shape); | ||
| 226 | if($i == @{ $nodes } - 1) | ||
| 227 | { | ||
| 228 | print('=' x $line_length, "\n"); | ||
| 229 | } | ||
| 230 | else | ||
| 231 | { | ||
| 232 | print('_' x $line_length, "\n"); | ||
| 233 | } | ||
| 234 | }, $nodes); | ||
| 235 | print("Total params: $total_params\n"); | ||
| 236 | print('_' x $line_length, "\n"); | ||
| 237 | } | ||
| 238 | |||
| 239 | =head2 plot_network | ||
| 240 | |||
| 241 | convert symbol to dot object for visualization | ||
| 242 | |||
| 243 | Parameters | ||
| 244 | ---------- | ||
| 245 | title: str | ||
| 246 | title of the dot graph | ||
| 247 | symbol: AI::MXNet::Symbol | ||
| 248 | symbol to be visualized | ||
| 249 | shape: HashRef[Shape] | ||
| 250 | If supplied, the visualization will include the shape | ||
| 251 | of each tensor on the edges between nodes. | ||
| 252 | node_attrs: HashRef of node's attributes | ||
| 253 | for example: | ||
| 254 | {shape => "oval",fixedsize => "false"} | ||
| 255 | means to plot the network in "oval" | ||
| 256 | hide_weights: Bool | ||
| 257 | if True (default) then inputs with names like `*_weight` | ||
| 258 | or `*_bias` will be hidden | ||
| 259 | |||
| 260 | Returns | ||
| 261 | ------ | ||
| 262 | dot: Diagraph | ||
| 263 | dot object of symbol | ||
| 264 | =cut | ||
| 265 | |||
| 266 | method plot_network( | ||
| 267 | AI::MXNet::Symbol $symbol, | ||
| 268 | Str :$title='plot', | ||
| 269 | Str :$save_format='ps', | ||
| 270 | Maybe[HashRef[Shape]] :$shape=, | ||
| 271 | HashRef[Str] :$node_attrs={}, | ||
| 272 | Bool :$hide_weights=1 | ||
| 273 | ) | ||
| 274 | { | ||
| 275 | eval { require GraphViz; }; | ||
| 276 | Carp::confess("plot_network requires GraphViz module") if $@; | ||
| 277 | my $draw_shape; | ||
| 278 | my %shape_dict; | ||
| 279 | if(defined $shape) | ||
| 280 | { | ||
| 281 | $draw_shape = 1; | ||
| 282 | my $interals = $symbol->get_internals; | ||
| 283 | my (undef, $out_shapes, undef) = $interals->infer_shape(%{ $shape }); | ||
| 284 | Carp::confess("Input shape is incomplete") | ||
| 285 | unless defined $out_shapes; | ||
| 286 | @shape_dict{ @{ $interals->list_outputs } } = @{ $out_shapes }; | ||
| 287 | } | ||
| 288 | my $conf = decode_json($symbol->tojson); | ||
| 289 | my $nodes = $conf->{nodes}; | ||
| 290 | my %node_attr = ( | ||
| 291 | qw/ shape box fixedsize true | ||
| 292 | width 1.3 height 0.8034 style filled/, | ||
| 293 | %{ $node_attrs } | ||
| 294 | ); | ||
| 295 | my $dot = AI::MXNet::Visualization::PythonGraphviz->new( | ||
| 296 | graph => GraphViz->new(name => $title), | ||
| 297 | format => $save_format, | ||
| 298 | ); | ||
| 299 | # color map | ||
| 300 | my @cm = ( | ||
| 301 | "#8dd3c7", "#fb8072", "#ffffb3", "#bebada", "#80b1d3", | ||
| 302 | "#fdb462", "#b3de69", "#fccde5" | ||
| 303 | ); | ||
| 304 | # make nodes | ||
| 305 | my %hidden_nodes; | ||
| 306 | for my $node (@{ $nodes }) | ||
| 307 | { | ||
| 308 | my $op = $node->{op}; | ||
| 309 | my $name = $node->{name}; | ||
| 310 | # input data | ||
| 311 | my %attr = %node_attr; | ||
| 312 | my $label = $name; | ||
| 313 | if($op eq 'null') | ||
| 314 | { | ||
| 315 | if($name =~ /(?:_weight|_bias|_beta|_gamma|_moving_var|_moving_mean|running_var|running_mean)$/) | ||
| 316 | { | ||
| 317 | if($hide_weights) | ||
| 318 | { | ||
| 319 | $hidden_nodes{$name} = 1; | ||
| 320 | } | ||
| 321 | # else we don't render a node, but | ||
| 322 | # don't add it to the hidden_nodes set | ||
| 323 | # so it gets rendered as an empty oval | ||
| 324 | next; | ||
| 325 | } | ||
| 326 | $attr{shape} = 'ellipse'; # inputs get their own shape | ||
| 327 | $label = $name; | ||
| 328 | $label = 'plus' if $label =~ /plus\d+$/; | ||
| 329 | $attr{fillcolor} = $cm[0]; | ||
| 330 | } | ||
| 331 | elsif($op eq 'Convolution') | ||
| 332 | { | ||
| 333 | my @k = $node->{attrs}{kernel} =~ /(\d+)/g; | ||
| 334 | my @stride = ($node->{attrs}{stride}//'') =~ /(\d+)/g; | ||
| 335 | $stride[0] //= 1; | ||
| 336 | $label = "Convolution\n".join('x',@k).'/'.join('x',@stride).", $node->{attrs}{num_filter}"; | ||
| 337 | $attr{fillcolor} = $cm[1]; | ||
| 338 | } | ||
| 339 | elsif($op eq 'FullyConnected') | ||
| 340 | { | ||
| 341 | $label = "FullyConnected\n$node->{attrs}{num_hidden}"; | ||
| 342 | $attr{fillcolor} = $cm[1]; | ||
| 343 | } | ||
| 344 | elsif($op eq 'BatchNorm') | ||
| 345 | { | ||
| 346 | $attr{fillcolor} = $cm[3]; | ||
| 347 | $label = $op; | ||
| 348 | } | ||
| 349 | elsif($op eq 'Flatten') | ||
| 350 | { | ||
| 351 | $label = $op; | ||
| 352 | $attr{fillcolor} = $cm[5]; | ||
| 353 | } | ||
| 354 | elsif($op eq 'elemwise_add' or $op eq 'clip' or $op eq 'Concat') | ||
| 355 | { | ||
| 356 | $label = $op; | ||
| 357 | $attr{fillcolor} = $cm[5]; | ||
| 358 | } | ||
| 359 | elsif($op eq 'Dropout') | ||
| 360 | { | ||
| 361 | $label = "$op ($node->{attrs}{p})"; | ||
| 362 | } | ||
| 363 | elsif($op eq 'Reshape') | ||
| 364 | { | ||
| 365 | $label = "$op $node->{attrs}{shape}"; | ||
| 366 | $attr{fillcolor} = $cm[5]; | ||
| 367 | } | ||
| 368 | elsif($op eq 'Activation' or $op eq 'LeakyReLU') | ||
| 369 | { | ||
| 370 | $label = "$op\n$node->{attrs}{act_type}"; | ||
| 371 | $attr{fillcolor} = $cm[2]; | ||
| 372 | } | ||
| 373 | elsif($op eq 'Pooling') | ||
| 374 | { | ||
| 375 | my @k = $node->{attrs}{kernel} =~ /(\d+)/g; | ||
| 376 | my @stride = ($node->{attrs}{stride}//'') =~ /(\d+)/g; | ||
| 377 | $stride[0] //= 1; | ||
| 378 | $label = "Pooling\n$node->{attrs}{pool_type}, ".join('x',@k).'/'.join('x',@stride); | ||
| 379 | $attr{fillcolor} = $cm[4]; | ||
| 380 | } | ||
| 381 | elsif($op eq 'Softmax') | ||
| 382 | { | ||
| 383 | $attr{fillcolor} = $cm[6]; | ||
| 384 | } | ||
| 385 | else | ||
| 386 | { | ||
| 387 | $attr{fillcolor} = $cm[7]; | ||
| 388 | if($op eq 'Custom') | ||
| 389 | { | ||
| 390 | $label = $node->{attrs}{op_type}; | ||
| 391 | } | ||
| 392 | } | ||
| 393 | $dot->graph->add_node($name, label => $label, %attr); | ||
| 394 | }; | ||
| 395 | |||
| 396 | # add edges | ||
| 397 | for my $node (@{ $nodes }) | ||
| 398 | { | ||
| 399 | my $op = $node->{op}; | ||
| 400 | my $name = $node->{name}; | ||
| 401 | if($op eq 'null') | ||
| 402 | { | ||
| 403 | next; | ||
| 404 | } | ||
| 405 | else | ||
| 406 | { | ||
| 407 | my $inputs = $node->{inputs}; | ||
| 408 | for my $item (@{ $inputs }) | ||
| 409 | { | ||
| 410 | my $input_node = $nodes->[$item->[0]]; | ||
| 411 | my $input_name = $input_node->{name}; | ||
| 412 | if(not exists $hidden_nodes{ $input_name }) | ||
| 413 | { | ||
| 414 | my %attr = qw/dir back arrowtail normal/; | ||
| 415 | # add shapes | ||
| 416 | if($draw_shape) | ||
| 417 | { | ||
| 418 | my $key = $input_name; | ||
| 419 | $key .= '_output' if $input_node->{op} ne 'null'; | ||
| 420 | if($input_node->{op} ne 'null' and exists $input_node->{attrs}) | ||
| 421 | { | ||
| 422 | if(ref $input_node->{attrs} eq 'HASH' and exists $input_node->{attrs}{num_outputs}) | ||
| 423 | { | ||
| 424 | $key .= ($input_node->{attrs}{num_outputs} - 1); | ||
| 425 | } | ||
| 426 | } | ||
| 427 | my $end = @{ $shape_dict{$key} }; | ||
| 428 | $attr{label} = join('x', @{ $shape_dict{$key} }[1..$end-1]); | ||
| 429 | } | ||
| 430 | $dot->graph->add_edge($name => $input_name, %attr); | ||
| 431 | } | ||
| 432 | } | ||
| 433 | } | ||
| 434 | } | ||
| 435 | return $dot; | ||
| 436 | } | ||
| 437 | |||
| 438 | package AI::MXNet::Visualization::PythonGraphviz; | ||
| 439 | use Mouse; | ||
| 440 | use AI::MXNet::Types; | ||
| 441 | has 'format' => ( | ||
| 442 | is => 'ro', | ||
| 443 | isa => enum([qw/debug canon text ps hpgl pcl mif | ||
| 444 | pic gd gd2 gif jpeg png wbmp cmapx | ||
| 445 | imap vdx vrml vtx mp fig svg svgz | ||
| 446 | plain/] | ||
| 447 | ) | ||
| 448 | ); | ||
| 449 | has 'graph' => (is => 'ro', isa => 'GraphViz'); | ||
| 450 | |||
| 451 | method render($output=) | ||
| 452 | { | ||
| 453 | my $method = 'as_' . $self->format; | ||
| 454 | return $self->graph->$method($output); | ||
| 455 | } | ||
| 456 | |||
| 457 | 1; |