MXNet/Gluon/Utils.pm untested

filter: Statementstmt 0.0% 0 / 134 Branchbran 0.0% 0 / 36 Conditioncond 0.0% 0 / 27 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 12 Podpod n/a totaltotal 0.0% 0 / 209 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
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::Gluon::Utils;
19 use strict;
20 use warnings;
21 use AI::MXNet::Base;
22 use AI::MXNet::Function::Parameters;
23 use Digest::SHA qw(sha1_hex);
24 use File::Path qw(make_path);
25 use HTTP::Tiny;
26 use Exporter;
27 use base qw(Exporter);
28 our @EXPORT_OK = qw(download check_sha1);
29  
30 =head1 NAME
31  
32 AI::MXNet::Gluon::Utils
33 =cut
34  
35 =head1 DESCRIPTION
36  
37 Miscellaneous utilities.
38 =cut
39  
40 =head2 split_data
41  
42 Splits an NDArray into `num_slice` slices along `batch_axis`.
43 Usually used for data parallelism where each slices is sent
44 to one device (i.e. GPU).
45  
46 Parameters
47 ----------
48 $data : NDArray
49 A batch of data.
50 $num_slice : int
51 Number of desired slices.
52 $batch_axis=0 : int, default 0
53 The axis along which to slice.
54 :$even_split=1 : bool, default True
55 Whether to force all slices to have the same number of elements.
56 If `True`, an error will be raised when `num_slice` does not evenly
57 divide `data.shape[batch_axis]`.
58  
59 Returns
60 -------
61 array ref of NDArray
62 Return value is a array ref even if `num_slice` is 1.
63 =cut
64  
65  
66 method split_data(AI::MXNet::NDArray $data, Int $num_slice, Int $batch_axis=0, Bool :$even_split=1)
67 {
68 my $size = $data->shape->[$batch_axis];
69 if($size < $num_slice)
70 {
71 Carp::confess(
72 sprintf(
73 "Too many slices for data with shape (%s). Arguments are ".
74 "num_slice=%d and batch_axis=%d.",
75 join(',', @{ $data->shape }), $num_slice, $batch_axis
76 )
77 );
78 }
79 if($even_split and $size % $num_slice != 0)
80 {
81 Carp::confess(
82 sprintf(
83 "data with shape %s cannot be evenly split into %d slices along axis %d. ".
84 "Use a batch size that's multiple of %d or set even_split=False to allow ".
85 "uneven partitioning of data.",
86 join(',', @{ $data->shape }), $num_slice, $batch_axis, $num_slice
87 )
88 );
89 }
90 my $step = int($size/$num_slice);
91 my $slices = [];
92 if($batch_axis == 0)
93 {
94 for my $i (0 .. $num_slice-1)
95 {
96 if($i < $num_slice-1)
97 {
98 push @$slices, $data->slice([$i*$step, ($i+1)*$step-1]);
99 }
100 else
101 {
102 push @$slices, $data->slice([$i*$step, $size-1]);
103 }
104 }
105 }
106 elsif($even_split)
107 {
108 $slices = AI::MXNet::NDArray->split($data, num_outputs => $num_slice, axis => $batch_axis);
109 }
110 else
111 {
112 for my $i (0 .. $num_slice-1)
113 {
114 if($i < $num_slice-1)
115 {
116 push @$slices, $data->slice_axis($batch_axis, $i*$step, ($i+1)*$step);
117 }
118 else
119 {
120 push @$slices, $data->slice_axis($batch_axis, $i*$step, $size);
121 }
122 }
123 }
124 return $slices;
125 }
126  
127 =head2 split_and_load
128  
129 Splits an NDArray into `len(ctx_list)` slices along `batch_axis` and loads
130 each slice to one context in `ctx_list`.
131  
132 Parameters
133 ----------
134 $data : AcceptableInput
135 A batch of data.
136 :$ctx_list : list of Context
137 A list of Contexts.
138 :$batch_axis : int, default 0
139 The axis along which to slice.
140 :$even_split : bool, default True
141 Whether to force all slices to have the same number of elements.
142  
143 Returns
144 -------
145 list of NDArray
146 Each corresponds to a context in `ctx_list`.
147 =cut
148  
149 method split_and_load(
150 PDL|PDL::Matrix|ArrayRef|AI::MXNet::NDArray $data,
151 ArrayRef[AI::MXNet::Context] :$ctx_list,
152 Int :$batch_axis=0,
153 Bool :$even_split=1
154 )
155 {
156 if(not (blessed $data and $data->isa('AI::MXNet::NDArray')))
157 {
158 $data = AI::MXNet::NDArray->array($data, ctx => $ctx_list->[0])
159 }
160 if(@{ $ctx_list } == 1)
161 {
162 return [$data->as_in_context($ctx_list->[0])];
163 }
164 my $slices = __PACKAGE__->split_data($data, scalar(@$ctx_list), $batch_axis, even_split => $even_split);
165 my @ret;
166 for(zip($slices, $ctx_list)) {
167 my ($i, $ctx) = @$_;
168 push @ret, $i->as_in_context($ctx);
169 }
170 return \@ret;
171 }
172  
173 =head2 clip_global_norm
174  
175 Rescales NDArrays so that the sum of their 2-norm is smaller than `max_norm`.
176 =cut
177  
178 method clip_global_norm(ArrayRef[AI::MXNet::NDArray] $arrays, Num $max_norm)
179 {
180 my $_norm = sub { my ($array) = @_;
181 if($array->stype eq 'default')
182 {
183 my $x = $array->reshape([-1]);
184 return AI::MXNet::NDArray->dot($x, $x);
185 }
186 return $array->norm->square;
187 };
188 assert(@$arrays > 0);
189 my $ctx = $arrays->[0]->context;
190 my $total_norm = AI::MXNet::NDArray->add_n(map { $_norm->($_)->as_in_context($ctx) } @$arrays);
191 $total_norm = $total_norm->sqrt->asscalar;
192 if(lc($total_norm) eq 'nan' or $total_norm =~ /inf/i)
193 {
194 AI::MXNet::Logging->warning('nan or inf is detected. Clipping results will be undefined.');
195 }
196 my $scale = $max_norm / ($total_norm + 1e-8);
197 if($scale < 1.0)
198 {
199 for my $arr (@$arrays)
200 {
201 $arr *= $scale;
202 }
203 }
204 return $total_norm;
205 }
206  
207 =head2 check_sha1
208  
209 Check whether the sha1 hash of the file content matches the expected hash.
210  
211 Parameters
212 ----------
213 filename : str
214 Path to the file.
215 sha1_hash : str
216 Expected sha1 hash in hexadecimal digits.
217  
218 Returns
219 -------
220 bool
221 Whether the file content matches the expected hash.
222 =cut
223  
224 func check_sha1(Str $filename, Str $sha1_hash)
225 {
226 local($/) = undef;
227 open(F, $filename) or Carp::confess("can't open $filename $!");
228 my $data = <F>;
229 close(F);
230 return sha1_hex($data) eq $sha1_hash;
231 }
232  
233 =head2 download
234  
235 Download an given URL
236  
237 Parameters
238 ----------
239 $url : str
240 URL to download
241 :$path : str, optional
242 Destination path to store downloaded file. By default stores to the
243 current directory with same name as in url.
244 :$overwrite : bool, optional
245 Whether to overwrite destination file if already exists.
246 :$sha1_hash : str, optional
247 Expected sha1 hash in hexadecimal digits. Will ignore existing file when hash is specified
248 but doesn't match.
249 Returns
250 -------
251 str
252 The file path of the downloaded file.
253 =cut
254  
255 func download(Str $url, Maybe[Str] :$path=, Bool :$overwrite=0, Maybe[Str] :$sha1_hash=)
256 {
257 my $fname;
258 $path =~ s/~/$ENV{HOME}/ if defined $path;
259 if(not defined $path)
260 {
261 $fname = (split(m[/], $url))[-1];
262 }
263 elsif(-d $path)
264 {
265 $fname = join('/', $path, (split(m[/], $url))[-1]);
266 }
267 else
268 {
269 $fname = $path;
270 }
271 if($overwrite or not -f $fname or ($sha1_hash and not check_sha1($fname, $sha1_hash)))
272 {
273 $fname =~ s/~/$ENV{HOME}/;
274 my $dirname = $fname;
275 $dirname =~ s/[^\/]+$//;
276 if(not -d $dirname)
277 {
278 make_path($dirname);
279 }
280 warn "Downloading $fname from $url ...\n";
281 my $response = HTTP::Tiny->new->get($url);
282 Carp::confess("download of url failed! ($response->{status} $response->{reason})\n")
283 unless $response->{success};
284 open(F, ">$fname") or Carp::confess("can't open $fname: $!");
285 print F $response->{content};
286 close(F);
287 }
288 return $fname
289 }
290  
291 package AI::MXNet::Gluon::Utils::HookHandle;
292 use Mouse;
293 use AI::MXNet::Base;
294 use Scalar::Util qw(refaddr);
295 has [qw/_hooks_dict_ref/] => (is => 'rw', init_arg => undef, weak_ref => 1);
296 has [qw/_id/] => (is => 'rw', init_arg => undef);
297  
298 method attach(Hash::Ordered $hooks_dict, $hook)
299 {
300 assert((not $self->_hooks_dict_ref), 'The same handle cannot be attached twice.');
301 $self->_id(refaddr($hook));
302 $hooks_dict->set($self->_id, $hook);
303 $self->_hooks_dict_ref($hooks_dict);
304 }
305  
306 method detach()
307 {
308 my $hooks_dict = $self->_hooks_dict_ref;
309 if($hooks_dict and $hooks_dict->exists($self->_id))
310 {
311 $hooks_dict->delete($self->_id);
312 }
313 }
314  
315 1;