| 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::RNN::IO; | ||
| 19 | use strict; | ||
| 20 | use warnings; | ||
| 21 | use AI::MXNet::Base; | ||
| 22 | use AI::MXNet::Function::Parameters; | ||
| 23 | |||
| 24 | =encoding UTF-8 | ||
| 25 | |||
| 26 | =head1 NAME | ||
| 27 | |||
| 28 | AI::MXNet::RNN::IO - Functions for constructing recurrent neural networks. | ||
| 29 | =cut | ||
| 30 | |||
| 31 | =head1 DESCRIPTION | ||
| 32 | |||
| 33 | Functions for constructing recurrent neural networks. | ||
| 34 | =cut | ||
| 35 | |||
| 36 | =head2 encode_sentences | ||
| 37 | |||
| 38 | Encode sentences and (optionally) build a mapping | ||
| 39 | from string tokens to integer indices. Unknown keys | ||
| 40 | will be added to vocabulary. | ||
| 41 | |||
| 42 | Parameters | ||
| 43 | ---------- | ||
| 44 | $sentences : array ref of array refs of str | ||
| 45 | A array ref of sentences to encode. Each sentence | ||
| 46 | should be a array ref of string tokens. | ||
| 47 | :$vocab : undef or hash ref of str -> int | ||
| 48 | Optional input Vocabulary | ||
| 49 | :$invalid_label : int, default -1 | ||
| 50 | Index for invalid token, like <end-of-sentence> | ||
| 51 | :$invalid_key : str, default '\n' | ||
| 52 | Key for invalid token. Uses '\n' for end | ||
| 53 | of sentence by default. | ||
| 54 | :$start_label=0 : int | ||
| 55 | lowest index. | ||
| 56 | |||
| 57 | Returns | ||
| 58 | ------- | ||
| 59 | $result : array ref of array refs of int | ||
| 60 | encoded sentences | ||
| 61 | $vocab : hash ref of str -> int | ||
| 62 | result vocabulary | ||
| 63 | =cut | ||
| 64 | |||
| 65 | |||
| 66 | method encode_sentences( | ||
| 67 | ArrayRef[ArrayRef] $sentences, | ||
| 68 | Maybe[HashRef] :$vocab=, | ||
| 69 | Int :$invalid_label=-1, | ||
| 70 | Str :$invalid_key="\n", | ||
| 71 | Int :$start_label=0 | ||
| 72 | ) | ||
| 73 | { | ||
| 74 | my $idx = $start_label; | ||
| 75 | my $new_vocab; | ||
| 76 | if(not defined $vocab) | ||
| 77 | { | ||
| 78 | $vocab = { $invalid_key => $invalid_label }; | ||
| 79 | $new_vocab = 1; | ||
| 80 | } | ||
| 81 | else | ||
| 82 | { | ||
| 83 | $new_vocab = 0; | ||
| 84 | } | ||
| 85 | my @res; | ||
| 86 | for my $sent (@{ $sentences }) | ||
| 87 | { | ||
| 88 | my @coded; | ||
| 89 | for my $word (@{ $sent }) | ||
| 90 | { | ||
| 91 | if(not exists $vocab->{ $word }) | ||
| 92 | { | ||
| 93 | assert($new_vocab, "Unknown token: $word"); | ||
| 94 | if($idx == $invalid_label) | ||
| 95 | { | ||
| 96 | $idx += 1; | ||
| 97 | } | ||
| 98 | $vocab->{$word} = $idx; | ||
| 99 | $idx += 1; | ||
| 100 | } | ||
| 101 | push @coded, $vocab->{ $word }; | ||
| 102 | } | ||
| 103 | push @res, \@coded; | ||
| 104 | } | ||
| 105 | return (\@res, $vocab); | ||
| 106 | } | ||
| 107 | |||
| 108 | package AI::MXNet::BucketSentenceIter; | ||
| 109 | |||
| 110 | =encoding UTF-8 | ||
| 111 | |||
| 112 | =head1 NAME | ||
| 113 | |||
| 114 | AI::MXNet::BucketSentenceIter | ||
| 115 | =cut | ||
| 116 | |||
| 117 | =head1 DESCRIPTION | ||
| 118 | |||
| 119 | Simple bucketing iterator for language model. | ||
| 120 | Label for each step is constructed from data of | ||
| 121 | next step. | ||
| 122 | =cut | ||
| 123 | |||
| 124 | =head2 new | ||
| 125 | |||
| 126 | Parameters | ||
| 127 | ---------- | ||
| 128 | sentences : array ref of array refs of int | ||
| 129 | encoded sentences | ||
| 130 | batch_size : int | ||
| 131 | batch_size of data | ||
| 132 | invalid_label : int, default -1 | ||
| 133 | key for invalid label, e.g. <end-of-sentence> | ||
| 134 | dtype : str, default 'float32' | ||
| 135 | data type | ||
| 136 | buckets : array ref of int | ||
| 137 | size of data buckets. Automatically generated if undef. | ||
| 138 | data_name : str, default 'data' | ||
| 139 | name of data | ||
| 140 | label_name : str, default 'softmax_label' | ||
| 141 | name of label | ||
| 142 | layout : str | ||
| 143 | format of data and label. 'NT' means (batch_size, length) | ||
| 144 | and 'TN' means (length, batch_size). | ||
| 145 | =cut | ||
| 146 | |||
| 147 | use Mouse; | ||
| 148 | use AI::MXNet::Base; | ||
| 149 | use List::Util qw(shuffle max); | ||
| 150 | extends 'AI::MXNet::DataIter'; | ||
| 151 | has 'sentences' => (is => 'ro', isa => 'ArrayRef[ArrayRef]', required => 1); | ||
| 152 | has '+batch_size' => (is => 'ro', isa => 'Int', required => 1); | ||
| 153 | has 'invalid_label' => (is => 'ro', isa => 'Int', default => -1); | ||
| 154 | has 'data_name' => (is => 'ro', isa => 'Str', default => 'data'); | ||
| 155 | has 'label_name' => (is => 'ro', isa => 'Str', default => 'softmax_label'); | ||
| 156 | has 'dtype' => (is => 'ro', isa => 'Dtype', default => 'float32'); | ||
| 157 | has 'layout' => (is => 'ro', isa => 'Str', default => 'NT'); | ||
| 158 | has 'buckets' => (is => 'rw', isa => 'Maybe[ArrayRef[Int]]'); | ||
| 159 | has [qw/data nddata ndlabel | ||
| 160 | major_axis default_bucket_key | ||
| 161 | provide_data provide_label | ||
| 162 | idx curr_idx | ||
| 163 | /] => (is => 'rw', init_arg => undef); | ||
| 164 | |||
| 165 | sub BUILD | ||
| 166 | { | ||
| 167 | my $self = shift; | ||
| 168 | if(not defined $self->buckets) | ||
| 169 | { | ||
| 170 | my @buckets; | ||
| 171 | my $p = pdl([map { scalar(@$_) } @{ $self->sentences }]); | ||
| 172 | enumerate(sub { | ||
| 173 | my ($i, $j) = @_; | ||
| 174 | if($j >= $self->batch_size) | ||
| 175 | { | ||
| 176 | push @buckets, $i; | ||
| 177 | } | ||
| 178 | }, $p->histogram(1,0,$p->max+1)->unpdl); | ||
| 179 | $self->buckets(\@buckets); | ||
| 180 | } | ||
| 181 | @{ $self->buckets } = sort { $a <=> $b } @{ $self->buckets }; | ||
| 182 | my $ndiscard = 0; | ||
| 183 | $self->data([map { [] } 0..@{ $self->buckets }-1]); | ||
| 184 | for my $i (0..@{$self->sentences}-1) | ||
| 185 | { | ||
| 186 | my $buck = bisect_left($self->buckets, scalar(@{ $self->sentences->[$i] })); | ||
| 187 | if($buck == @{ $self->buckets }) | ||
| 188 | { | ||
| 189 | $ndiscard += 1; | ||
| 190 | next; | ||
| 191 | } | ||
| 192 | my $buff = AI::MXNet::NDArray->full( | ||
| 193 | [$self->buckets->[$buck]], | ||
| 194 | $self->invalid_label, | ||
| 195 | dtype => $self->dtype | ||
| 196 | )->aspdl; | ||
| 197 | $buff->slice([0, @{ $self->sentences->[$i] }-1]) .= pdl($self->sentences->[$i]); | ||
| 198 | push @{ $self->data->[$buck] }, $buff; | ||
| 199 | } | ||
| 200 | $self->data([map { pdl(PDL::Type->new(DTYPE_MX_TO_PDL->{$self->dtype}), $_) } @{$self->data}]); | ||
| 201 | AI::MXNet::Logging->warning("discarded $ndiscard sentences longer than the largest bucket.") | ||
| 202 | if $ndiscard; | ||
| 203 | $self->nddata([]); | ||
| 204 | $self->ndlabel([]); | ||
| 205 | $self->major_axis(index($self->layout, 'N')); | ||
| 206 | $self->default_bucket_key(max(@{ $self->buckets })); | ||
| 207 | my $shape; | ||
| 208 | if($self->major_axis == 0) | ||
| 209 | { | ||
| 210 | $shape = [$self->batch_size, $self->default_bucket_key]; | ||
| 211 | } | ||
| 212 | elsif($self->major_axis == 1) | ||
| 213 | { | ||
| 214 | $shape = [$self->default_bucket_key, $self->batch_size]; | ||
| 215 | } | ||
| 216 | else | ||
| 217 | { | ||
| 218 | confess("Invalid layout ${\ $self->layout }: Must by NT (batch major) or TN (time major)"); | ||
| 219 | } | ||
| 220 | $self->provide_data([ | ||
| 221 | AI::MXNet::DataDesc->new( | ||
| 222 | name => $self->data_name, | ||
| 223 | shape => $shape, | ||
| 224 | dtype => $self->dtype, | ||
| 225 | layout => $self->layout | ||
| 226 | ) | ||
| 227 | ]); | ||
| 228 | $self->provide_label([ | ||
| 229 | AI::MXNet::DataDesc->new( | ||
| 230 | name => $self->label_name, | ||
| 231 | shape => $shape, | ||
| 232 | dtype => $self->dtype, | ||
| 233 | layout => $self->layout | ||
| 234 | ) | ||
| 235 | ]); | ||
| 236 | $self->idx([]); | ||
| 237 | enumerate(sub { | ||
| 238 | my ($i, $buck) = @_; | ||
| 239 | my $buck_len = $buck->shape->at(-1); | ||
| 240 | for my $j (0..($buck_len - $self->batch_size)) | ||
| 241 | { | ||
| 242 | if(not $j%$self->batch_size) | ||
| 243 | { | ||
| 244 | push @{ $self->idx }, [$i, $j]; | ||
| 245 | } | ||
| 246 | } | ||
| 247 | }, $self->data); | ||
| 248 | $self->curr_idx(0); | ||
| 249 | $self->reset; | ||
| 250 | } | ||
| 251 | |||
| 252 | method reset() | ||
| 253 | { | ||
| 254 | $self->curr_idx(0); | ||
| 255 | @{ $self->idx } = shuffle(@{ $self->idx }); | ||
| 256 | $self->nddata([]); | ||
| 257 | $self->ndlabel([]); | ||
| 258 | for my $buck (@{ $self->data }) | ||
| 259 | { | ||
| 260 | $buck = pdl_shuffle($buck); | ||
| 261 | my $label = $buck->zeros; | ||
| 262 | $label->slice([0, -2], 'X') .= $buck->slice([1, -1], 'X'); | ||
| 263 | $label->slice([-1, -1], 'X') .= $self->invalid_label; | ||
| 264 | push @{ $self->nddata }, AI::MXNet::NDArray->array($buck, dtype => $self->dtype); | ||
| 265 | push @{ $self->ndlabel }, AI::MXNet::NDArray->array($label, dtype => $self->dtype); | ||
| 266 | } | ||
| 267 | } | ||
| 268 | |||
| 269 | method next() | ||
| 270 | { | ||
| 271 | return undef if($self->curr_idx == @{ $self->idx }); | ||
| 272 | my ($i, $j) = @{ $self->idx->[$self->curr_idx] }; | ||
| 273 | $self->curr_idx($self->curr_idx + 1); | ||
| 274 | my ($data, $label); | ||
| 275 | if($self->major_axis == 1) | ||
| 276 | { | ||
| 277 | $data = $self->nddata->[$i]->slice([$j, $j+$self->batch_size-1])->T; | ||
| 278 | $label = $self->ndlabel->[$i]->slice([$j, $j+$self->batch_size-1])->T; | ||
| 279 | } | ||
| 280 | else | ||
| 281 | { | ||
| 282 | $data = $self->nddata->[$i]->slice([$j, $j+$self->batch_size-1]); | ||
| 283 | $label = $self->ndlabel->[$i]->slice([$j, $j+$self->batch_size-1]); | ||
| 284 | } | ||
| 285 | return AI::MXNet::DataBatch->new( | ||
| 286 | data => [$data], | ||
| 287 | label => [$label], | ||
| 288 | bucket_key => $self->buckets->[$i], | ||
| 289 | pad => 0, | ||
| 290 | provide_data => [ | ||
| 291 | AI::MXNet::DataDesc->new( | ||
| 292 | name => $self->data_name, | ||
| 293 | shape => $data->shape, | ||
| 294 | dtype => $self->dtype, | ||
| 295 | layout => $self->layout | ||
| 296 | ) | ||
| 297 | ], | ||
| 298 | provide_label => [ | ||
| 299 | AI::MXNet::DataDesc->new( | ||
| 300 | name => $self->label_name, | ||
| 301 | shape => $label->shape, | ||
| 302 | dtype => $self->dtype, | ||
| 303 | layout => $self->layout | ||
| 304 | ) | ||
| 305 | ], | ||
| 306 | ); | ||
| 307 | } | ||
| 308 | |||
| 309 | 1; |