blib/lib/Algorithm/Classifier/IsolationForest/App/Command/bench.pm

filter: Statementstmt 90.1% 82 / 91 Branchbran 55.2% 21 / 38 Conditioncond 60.0% 3 / 5 MC/DCmcdc 33.3% 1 / 3 Subroutinesub 90.9% 20 / 22 Podpod 100% 5 / 5 totaltotal 80.4% 132 / 164 CC 25 SCAR 20.4
CC
25
Cov
79%
validate
21.3
execute
9.3
_read_csv
7.1
CRAP 7.7
« blib/lib/Algorithm/Classifier/IsolationForest/App/Command/pack.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest/App/Command.pm »
1 package Algorithm::Classifier::IsolationForest::App::Command::bench;
2  
3 86 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 86 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 86 ▶use Algorithm::Classifier::IsolationForest ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 86 ▶use Algorithm::Classifier::IsolationForest::App -command;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 86 ▶use File::Slurp qw(read_file);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 86 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 86 ▶use Time::HiRes qw(time);
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 1 ▶sub opt_spec {
Subroutine opt_spec: called CC=1 SCAR=0.0
Pod documented
12 return (
13 [
14 1 'm=s',
15 'Input model JSON file path/name.',
16 { 'default' => 'iforest_model.json', 'completion' => 'files' }
17 ],
18 [ 'i=s', 'Input CSV (rows of features to score).', { 'completion' => 'files' } ],
19 [ 'secs|s=f', 'Seconds per measurement (after a 0.3s warm-up).', { 'default' => 2 } ],
20 [ 't=f', 'Threshold to use for predict / score_predict_*.', { 'default' => 0.5 } ],
21 );
22 } ## end sub opt_spec
23  
24 0 ▶sub abstract { 'Measure scoring throughput of a saved model on a CSV dataset' }
Subroutine abstract: not called CC=1 SCAR=6.9
Pod documented
25  
26 0 ▶sub description {
Subroutine description: not called CC=1 SCAR=6.9
Pod documented
27 0 'Loads a model and a CSV dataset, then times each of the
28 public scoring methods over the configured wall-clock budget. Reports
29 ops-per-second for each.
30  
31 When the Inline::C backend is active the bench also runs pack_data once
32 up front and times the *_packed variants so users can see how much
33 pre-packing saves on their workload.
34  
35 Use this to answer:
36  
37 * is my Inline::C / OpenMP / SIMD build actually faster than the
38 pure-Perl fallback?
39 * how much does pack_data help on my data shape?
40 * what is the per-call throughput I can expect at production-typical
41 query-set sizes?
42 ';
43 } ## end sub description
44  
45 1 ▶sub validate {
Subroutine validate: called CC=9 SCAR=30.6
Pod documented
46 1 my ( $self, $opt, $args ) = @_;
47  
48 1 ▶ if ( !defined $opt->{'i'} ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opt->{'i'}) { } 0 1 1
elsif (not -f $opt->{'i'}) { } 0 1 1
elsif (not -r $opt->{'i'}) { } 0 1 1
49 0 $self->usage_error('-i has not been specified');
50 } elsif ( !-f $opt->{'i'} ) {
51 0 $self->usage_error( '-i, "' . $opt->{'i'} . '", is not a file or does not exist' );
52 } elsif ( !-r $opt->{'i'} ) {
53 0 $self->usage_error( '-i, "' . $opt->{'i'} . '", is not readable' );
54 }
55  
56 1 ▶ if ( !-f $opt->{'m'} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not -f $opt->{'m'}) { } 0 1 1
elsif (not -r $opt->{'m'}) { } 0 1 1
57 0 $self->usage_error( '-m, "' . $opt->{'m'} . '", is not a file or does not exist' );
58 } elsif ( !-r $opt->{'m'} ) {
59 0 $self->usage_error( '-m, "' . $opt->{'m'} . '", is not readable' );
60 }
61  
62 1 ▶ if ( $opt->{'secs'} <= 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"secs"} <= 0) 0 1 1
63 0 $self->usage_error('--secs must be > 0');
64 }
65  
66 1 ▶ if ( $opt->{'t'} <= 0 || $opt->{'t'} >= 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"t"} <= 0 or $opt->{"t"} >= 1) 0 1 1
Condition33%1/3
$opt->{"t"} <= 0 or $opt->{"t"} >= 1
l!l&&r!l&&!r
001
MC/DC0%0/2
$opt->{"t"} <= 0 or $opt->{"t"} >= 1
$opt->{"t"} <= 0 $opt->{"t"} >= 1
Truth table33%1/3
A or B
A= $opt->{"t"} <= 0B= $opt->{"t"} >= 1
ABresult
1X1
011
000
67 0 $self->usage_error('-t must satisfy 0 < t < 1');
68 }
69  
70 1 return 1;
71 } ## end sub validate
72  
73 # Standard bench helper: warm up briefly, then time exactly $secs of
74 # back-to-back calls. The warm-up matters here: the first scoring call
75 # on a model pays for lazy packing and cache misses that would otherwise
76 # be charged to the measurement.
77 #
78 # Args:
79 # $code :: the coderef to time. Called with no arguments, its return
80 # value discarded, so anything it needs must be closed over.
81 # $secs :: the measurement budget in seconds, on top of a fixed 0.3s
82 # warm-up.
83 #
84 # Returns: the throughput in calls per second, a float.
85 #
86 # Example:
87 # my $rate = _bench( sub { $model->score_samples($data) }, 2 );
88 # printf "%.1f ops/s\n", $rate;
89 8 ▶sub _bench {
Subroutine _bench: called CC=3 SCAR=11.0
90 8 my ( $code, $secs ) = @_;
91 8 my $t0 = time();
92 8 ▶ $code->() while time() - $t0 < 0.3;
Branch: 1 branch
BranchTrueFalseTotal
&Algorithm::Classifier::IsolationForest::App::Command::bench::time() - $t0 < "0.3" and do { &$code() } 9021 8 9029
93 8 $t0 = time();
94 8 my $n = 0;
95 8 ▶ $code->(), $n++ while time() - $t0 < $secs;
Branch: 1 branch
BranchTrueFalseTotal
&Algorithm::Classifier::IsolationForest::App::Command::bench::time() - $t0 < $secs and do { &$code(), ++$n } 8133 8 8141
96 8 return $n / ( time() - $t0 );
97 }
98  
99 # Slurp a CSV of feature rows into memory. The bench scores the same
100 # rows over and over, so it wants everything in RAM up front and every
101 # cell validated before timing starts -- a parse error surfacing mid-run
102 # would corrupt the measurement.
103 #
104 # Args:
105 # $path :: path to the CSV, which must be readable. Blank lines are
106 # skipped; there is no header handling, so a header line is a
107 # parse error.
108 #
109 # Returns: the two-element list ($data, $n_feats) -- an arrayref of
110 # feature-value arrayrefs, and the column count taken from the first data
111 # row. Dies naming the line on a ragged row or a non-numeric cell.
112 #
113 # Example:
114 # my ( $data, $cols ) = _read_csv('scores.csv');
115 # die "width mismatch\n" if $cols != $model->{n_features};
116 1 ▶sub _read_csv {
Subroutine _read_csv: called CC=7 SCAR=19.6
117 1 my ($path) = @_;
118 1 my @data;
119 my $expected;
120 1 my $line = 0;
121 1 for my $row ( read_file($path) ) {
122 7 $line++;
123 7 chomp $row;
124 7 ▶ next if $row =~ /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $row =~ /^\s*$/ 0 7 7
125 7 my @f = split /,/, $row, -1;
126 7 ▶ $expected //= scalar @f;
Condition100%2/2
$expected //= scalar @f
l!l
61
MC/DC100%1/1
$expected //= scalar @f
$expected
Truth table100%2/2
A
A= $expected
Aresult
11
00
127 7 ▶ die "line $line of '$path' has $row but expected $expected columns\n"
Branch: 1 branch
BranchTrueFalseTotal
if scalar @f != $expected 0 7 7
128 if scalar @f != $expected;
129 7 for my $v (@f) {
130 21 ▶ die "line $line of '$path' value '$v' is not numeric\n"
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($v) 0 21 21
131 unless looks_like_number($v);
132 }
133 7 push @data, \@f;
134 } ## end for my $row ( read_file($path) )
135 1 return ( \@data, $expected );
136 } ## end sub _read_csv
137  
138 1 ▶sub execute {
Subroutine execute: called CC=9 SCAR=22.3
Pod documented
139 1 my ( $self, $opt, $args ) = @_;
140  
141 1 my $model = Algorithm::Classifier::IsolationForest->load( $opt->{'m'} );
142  
143 1 my ( $data, $cols ) = _read_csv( $opt->{'i'} );
144 die "input CSV has $cols feature columns but model expects " . $model->{n_features} . "\n"
145 1 ▶ if $cols != $model->{n_features};
Branch: 1 branch
BranchTrueFalseTotal
if $cols != $model->{"n_features"} 0 1 1
146  
147 1 my $n_pts = scalar @$data;
148 1 my $secs = $opt->{'secs'};
149 1 my $thresh = $opt->{'t'};
150 1 ▶ my $has_c = $Algorithm::Classifier::IsolationForest::HAS_C ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$Algorithm::Classifier::IsolationForest::HAS_C ? : 1 0 1
151  
152 printf "Model: %s (n_trees=%d, mode=%s, n_features=%d)\n",
153 1 $opt->{'m'}, scalar @{ $model->{trees} },
154 1 $model->{mode}, $model->{n_features};
155 1 printf "Input: %s (%d rows)\n", $opt->{'i'}, $n_pts;
156 1 printf "Budget: %.1fs per measurement (0.3s warm-up)\n", $secs;
157 1 ▶ printf "Backend: HAS_C=%d HAS_OPENMP=%d HAS_SIMD=%d\n\n",
Branch: 2 branches
BranchTrueFalseTotal
$Algorithm::Classifier::IsolationForest::HAS_OPENMP ? : 1 0 1
$Algorithm::Classifier::IsolationForest::HAS_SIMD ? : 1 0 1
158 $has_c,
159 $Algorithm::Classifier::IsolationForest::HAS_OPENMP ? 1 : 0,
160 $Algorithm::Classifier::IsolationForest::HAS_SIMD ? 1 : 0;
161  
162 # Pre-pack once (when C is available) so the *_packed rows measure
163 # scoring in isolation, without the per-call pack_input_xs cost.
164 1 ▶ my $packed = $has_c ? $model->pack_data($data) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$has_c ? : 1 0 1
165  
166 my @bench = (
167 2309 ▶ [ 'score_samples' => sub { $model->score_samples($data) } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
168 2174 ▶ [ 'predict' => sub { $model->predict( $data, $thresh ) } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
169 1137 ▶ [ 'score_predict_samples' => sub { $model->score_predict_samples( $data, $thresh ) } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
170 1808 ▶ [ 'score_predict_split' => sub { my @r = $model->score_predict_split( $data, $thresh ); } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
171 1 ▶ [ 'path_lengths' => sub { $model->path_lengths($data) } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
172 );
173  
174 1 ▶ if ( defined $packed ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $packed) 1 0 1
175 push @bench,
176 (
177 2477 ▶ [ 'score_samples (packed)' => sub { $model->score_samples($packed) } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
178 2372 ▶ [ 'predict (packed)' => sub { $model->predict( $packed, $thresh ) } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
179 1 ▶ [ 'score_predict_split (packed)' => sub { my @r = $model->score_predict_split( $packed, $thresh ); } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
180 );
181 }
182  
183 1 printf " %-30s %14s %14s\n", 'method', 'ops/s', 'ms/call';
184 1 printf " %-30s %14s %14s\n", '-' x 30, '-' x 14, '-' x 14;
185 1 for my $row (@bench) {
186 8 my ( $label, $code ) = @$row;
187 8 my $rate = _bench( $code, $secs );
188 8 ▶ printf " %-30s %14.1f %14.2f\n", $label, $rate, $rate > 0 ? 1000 / $rate : 0;
Branch: 1 branch
BranchTrueFalseTotal
$rate > 0 ? : 8 0 8
189 }
190 1 return 1;
191 } ## end sub execute
192  
193 =head1 NAME
194  
195 Algorithm::Classifier::IsolationForest::App::Command::bench - Measure scoring throughput of a saved model on a CSV dataset
196  
197 =head1 DESCRIPTION
198  
199 Loads a model and a CSV dataset, then times each of the public scoring
200 methods over a wall-clock budget and reports calls per second and
201 milliseconds per call.
202  
203 When the Inline::C backend is active it also packs the dataset once up
204 front and times the packed variants, so the saving C<pack_data> gives on
205 your own data shape is visible rather than assumed.
206  
207 Run it as C<iforest bench>; C<iforest help bench> lists every option.
208  
209 =head1 METHODS
210  
211 L<App::Cmd> calls these while dispatching the subcommand. Nothing else
212 should.
213  
214 =head2 opt_spec
215  
216 Returns this command's option specifications, as the list of arrayrefs
217 L<Getopt::Long::Descriptive> expects.
218  
219 =head2 abstract
220  
221 Returns the one-line summary C<iforest commands> prints beside the
222 command name.
223  
224 =head2 description
225  
226 Returns the long help text C<iforest help bench> prints under the option
227 list.
228  
229 =head2 validate
230  
231 Checks the parsed options before anything is read or written, so a
232 mistake costs nothing.
233  
234 Checks that C<-i> and C<-m> name readable files, that C<--secs> is
235 positive, and that C<-t> satisfies 0 < t < 1.
236  
237 Takes the parsed options hashref and the arrayref of remaining
238 arguments. Calls C<usage_error>, which prints the usage and exits, on
239 the first problem it finds, and returns 1 when everything checks out.
240  
241 =head2 execute
242  
243 Reads the model and the CSV, refuses a dataset whose column count
244 disagrees with the model, and prints the timing table.
245  
246 Takes the parsed options hashref and the arrayref of remaining
247 arguments, and returns 1.
248  
249 =cut
250  
251 86 return 1;
« blib/lib/Algorithm/Classifier/IsolationForest/App/Command/pack.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest/App/Command.pm »