-
Notifications
You must be signed in to change notification settings - Fork 7
/
examples.go
441 lines (372 loc) · 10.4 KB
/
examples.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
package lukai
import (
"bytes"
"compress/gzip"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"os"
"path"
"sort"
"time"
"github.com/gogo/protobuf/proto"
"github.com/pkg/errors"
tensorflow "github.com/tensorflow/tensorflow/tensorflow/go"
"github.com/luk-ai/lukai/protobuf/clientpb"
"github.com/luk-ai/lukai/tf"
"github.com/luk-ai/lukai/units"
)
var (
// MaxFileSize is the target size an example file will be.
MaxFileSize = 1 * units.MB
// MaxFileRetention is the duration worth of examples kept.
MaxFileRetention = 14 * units.Day
// MaxDiskUsage is the number of bytes that will used for examples.
MaxDiskUsage = 50 * units.MB
// MaxFileDuration is the duration worth of examples that will be stored in
// one file.
MaxFileDuration = 1 * units.Day
// IndexFileName is the name of the examples index file.
IndexFileName = "index.pb"
// FilePerm is the file permission all the example files use.
FilePerm os.FileMode = tf.FilePerm
DirPerm os.FileMode = 0700
// GCEvery controls how often the examples garbage collector runs.
GCEvery = 1 * time.Hour
)
type example struct {
feeds map[string]*tensorflow.Tensor
fetches []string
targets []string
}
type writeCounter struct {
n int
target io.Writer
}
func (c *writeCounter) Write(p []byte) (int, error) {
n, err := c.target.Write(p)
if err != nil {
return 0, err
}
c.n += n
return n, nil
}
func (ex example) writeTo(w io.Writer) (int, error) {
c := writeCounter{target: w}
gzw := gzip.NewWriter(&c)
defer gzw.Close()
if err := tf.EncodeTensorMap(gzw, ex.feeds); err != nil {
return 0, err
}
if err := tf.EncodeStringArray(gzw, ex.fetches); err != nil {
return 0, err
}
if err := tf.EncodeStringArray(gzw, ex.targets); err != nil {
return 0, err
}
if err := gzw.Close(); err != nil {
return 0, err
}
return c.n, nil
}
type readCounter struct {
n int
target io.Reader
}
func (c *readCounter) Read(p []byte) (int, error) {
n, err := c.target.Read(p)
if err != nil {
return 0, err
}
c.n += n
return n, nil
}
func (ex *example) readFrom(r io.Reader) (int, error) {
*ex = example{}
c := readCounter{target: r}
gzr, err := gzip.NewReader(&c)
if err != nil {
return 0, err
}
defer gzr.Close()
// This is required since there's some strange error occuring without it that
// causes an EOF.
// TODO(d4l3k): Fix this.
var buf bytes.Buffer
if _, err := buf.ReadFrom(gzr); err != nil {
return 0, err
}
ex.feeds, err = tf.DecodeTensorMap(&buf)
if err != nil {
return 0, errors.Wrap(err, "feeds")
}
ex.fetches, err = tf.DecodeStringArray(&buf)
if err != nil {
return 0, errors.Wrap(err, "fetches")
}
ex.targets, err = tf.DecodeStringArray(&buf)
if err != nil {
return 0, errors.Wrap(err, "targets")
}
return c.n, nil
}
// TotalExamples returns the number of examples that are currently saved
// locally.
func (mt *ModelType) TotalExamples() int64 {
mt.examplesMeta.Lock()
defer mt.examplesMeta.Unlock()
return mt.examplesMeta.index.TotalExamples
}
// TotalSize returns the file size of examples that are currently saved
// locally.
func (mt *ModelType) TotalSize() int64 {
mt.examplesMeta.Lock()
defer mt.examplesMeta.Unlock()
return mt.examplesMeta.index.TotalSize
}
// Log records model input->output pairs for later use in training. This data is
// saved locally only.
// - feeds key is the tensorflow output and should be in the form "name:output#".
// - targets is the name of the tensorflow target and should be in the form "name".
func (mt *ModelType) Log(feeds map[string]*tensorflow.Tensor, targets []string) error {
mt.examplesMeta.Lock()
defer mt.examplesMeta.Unlock()
mt.ensureFilePresentLocked()
mt.examplesMeta.index.TotalExamples += 1
file := &mt.examplesMeta.index.Files[len(mt.examplesMeta.index.Files)-1]
filePath := mt.filePath(file.Name)
f, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, FilePerm)
if err != nil {
return err
}
defer f.Close()
ex := example{
feeds: feeds,
targets: targets,
}
n, err := ex.writeTo(f)
if err != nil {
return err
}
file.Positions = append(file.Positions, int32(file.TotalSize))
file.TotalSize += int64(n)
mt.examplesMeta.index.TotalSize += int64(n)
mt.examplesMeta.saveIndex()
return nil
}
// ensureFilePresentLocked checks if there is a valid index entry, and if not,
// creates one.
func (mt *ModelType) ensureFilePresentLocked() {
numFiles := len(mt.examplesMeta.index.Files)
if numFiles > 0 {
lastFile := &mt.examplesMeta.index.Files[numFiles-1]
// Create a new file if the file is too old.
outdatedFile := lastFile.Created.Before(time.Now().Add(-MaxFileDuration))
// Create a new file if the last one is over the maximum file size.
largeFile := lastFile.TotalSize >= int64(MaxFileSize)
if !outdatedFile && !largeFile {
return
}
}
now := time.Now()
file := clientpb.ExampleFile{
Name: fmt.Sprintf("examples-%s", now.Format(time.RFC3339Nano)),
Created: now,
}
mt.examplesMeta.index.Files = append(mt.examplesMeta.index.Files, file)
}
// saveExamplesMeta saves the examples index.
func (mt *ModelType) saveExamplesMeta() error {
mt.examplesMeta.RLock()
defer mt.examplesMeta.RUnlock()
return mt.saveExamplesMetaLocked()
}
func (mt *ModelType) saveExamplesMetaLocked() error {
bytes, err := proto.Marshal(&mt.examplesMeta.index)
if err != nil {
return err
}
if err := ioutil.WriteFile(mt.filePath(IndexFileName), bytes, FilePerm); err != nil {
return err
}
return nil
}
// loadExamplesMeta loads the examples index.
func (mt *ModelType) loadExamplesMeta() error {
mt.examplesMeta.Lock()
defer mt.examplesMeta.Unlock()
bytes, err := ioutil.ReadFile(mt.filePath(IndexFileName))
if os.IsNotExist(err) {
return nil
} else if err != nil {
return err
}
if err := proto.Unmarshal(bytes, &mt.examplesMeta.index); err != nil {
return err
}
return nil
}
func (mt *ModelType) filePath(file string) string {
return path.Join(mt.DataDir, file)
}
// int64Slice attaches the methods of Interface to []int64, sorting in increasing order.
type int64Slice []int64
func (p int64Slice) Len() int { return len(p) }
func (p int64Slice) Less(i, j int) bool { return p[i] < p[j] }
func (p int64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (mt *ModelType) getNExamples(n int64) ([]example, error) {
mt.examplesMeta.RLock()
defer mt.examplesMeta.RUnlock()
fileReads := map[string][]int64{}
for i := int64(0); i < n; i++ {
totalExamples := mt.examplesMeta.index.TotalExamples
if totalExamples == 0 {
break
}
exampleIndex := rand.Int63n(totalExamples)
seenCount := int64(0)
for _, file := range mt.examplesMeta.index.Files {
seenSoFar := seenCount + int64(len(file.Positions))
if exampleIndex < seenSoFar {
fileReads[file.Name] = append(fileReads[file.Name], int64(file.Positions[exampleIndex-seenCount]))
break
}
seenCount = seenSoFar
}
if seenCount == mt.examplesMeta.index.TotalExamples {
return nil, errors.Errorf("failed to find file for example index %d", exampleIndex)
}
}
examples := make([]example, n)
i := 0
for filename, offsets := range fileReads {
// Sort the offsets to improve disk read performance.
sort.Sort(int64Slice(offsets))
f, err := os.OpenFile(mt.filePath(filename), os.O_RDONLY, FilePerm)
if err != nil {
return nil, err
}
defer f.Close()
for _, offset := range offsets {
if _, err := f.Seek(offset, 0); err != nil {
return nil, err
}
if _, err := examples[i].readFrom(f); err != nil {
return nil, errors.Wrapf(err, "failed to read from %q, offset %d", filename, offset)
}
i++
}
}
return examples, nil
}
// getExampleBatch returns a batched set of n examples.
func (mt *ModelType) getExampleBatch(
batchers batcherCache, cache tfOpCache, n int64,
) ([]example, error) {
examples, err := mt.getNExamples(n)
if err != nil {
return nil, err
}
if n == 1 {
return examples, nil
}
if int64(len(examples)) < n {
log.Printf("don't have enough examples for batching; need %d; have %d", n, len(examples))
return examples, nil
}
ex := example{
feeds: map[string]*tensorflow.Tensor{},
}
values := map[string][]*tensorflow.Tensor{}
for _, example := range examples {
for name, val := range example.feeds {
_, ok := batchers[name]
if !ok {
feed, err := cache.resolveFeed(name)
if err != nil {
return nil, err
}
shape, err := feed.Shape().ToSlice()
if err != nil {
return nil, err
}
batchers[name], err = tf.NewTensorBatcher(int(n), val.DataType(), shape)
if err != nil {
return nil, errors.Wrapf(err, "feed name %q", name)
}
}
values[name] = append(values[name], val)
}
ex.fetches = example.fetches
ex.targets = example.targets
}
for feed, values := range values {
batcher := batchers[feed]
out, err := batcher.Batch(values)
if err != nil {
return nil, errors.Wrapf(err, "feed %q", feed)
}
ex.feeds[feed] = out
}
return []example{ex}, nil
}
type batcherCache map[string]*tf.Batcher
func (c batcherCache) Close() error {
for _, batcher := range c {
if batcher == nil {
continue
}
if err := batcher.Close(); err != nil {
return err
}
}
return nil
}
func (mt *ModelType) gcLoop() {
for {
if err := mt.GCExamples(); err != nil {
log.Printf("GC error: %+v", err)
}
select {
case <-mt.ctx.Done():
return
case <-time.After(GCEvery):
}
}
}
// GCExamples scans through the example files and deletes any that violate the
// retention or max file size policies.
func (mt *ModelType) GCExamples() error {
mt.examplesMeta.Lock()
defer mt.examplesMeta.Unlock()
examples := mt.examplesMeta.index.TotalExamples
size := mt.examplesMeta.index.TotalSize
var toDelete []clientpb.ExampleFile
var toKeep []clientpb.ExampleFile
for _, f := range mt.examplesMeta.index.Files {
if mt.examplesMeta.index.TotalSize > int64(MaxDiskUsage) || time.Now().Add(-MaxFileRetention).After(f.Created) {
toDelete = append(toDelete, f)
mt.examplesMeta.index.TotalExamples -= int64(len(f.Positions))
mt.examplesMeta.index.TotalSize -= f.TotalSize
} else {
toKeep = append(toKeep, f)
}
}
log.Printf("GC: new %dB/%dB, %d/%d examples; removed %d files", mt.examplesMeta.index.TotalSize, size, mt.examplesMeta.index.TotalExamples, examples, len(toDelete))
if len(toDelete) == 0 {
return nil
}
mt.examplesMeta.index.Files = toKeep
if err := mt.saveExamplesMetaLocked(); err != nil {
return err
}
var errFinal error
for _, f := range toDelete {
if err := os.Remove(mt.filePath(f.Name)); err != nil {
errFinal = errors.Wrapf(err, "GCing file")
}
}
return errFinal
}