data_pipeline.py 34.3 KB
Newer Older
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
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Asynchronous data producer for the NCF pipeline."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import atexit
import functools
import os
import sys
import tempfile
import threading
import time
import timeit
import traceback
Taylor Robie's avatar
Taylor Robie committed
30
import typing
31
32
33
34
35

import numpy as np
import six
from six.moves import queue
import tensorflow as tf
36
from absl import logging
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

from official.datasets import movielens
from official.recommendation import constants as rconst
from official.recommendation import popen_helper
from official.recommendation import stat_utils


SUMMARY_TEMPLATE = """General:
{spacer}Num users: {num_users}
{spacer}Num items: {num_items}

Training:
{spacer}Positive count:          {train_pos_ct}
{spacer}Batch size:              {train_batch_size} {multiplier}
{spacer}Batch count per epoch:   {train_batch_ct}

Eval:
{spacer}Positive count:          {eval_pos_ct}
{spacer}Batch size:              {eval_batch_size} {multiplier}
{spacer}Batch count per epoch:   {eval_batch_ct}"""


_TRAIN_FEATURE_MAP = {
60
61
62
63
    movielens.USER_COLUMN: tf.io.FixedLenFeature([], dtype=tf.string),
    movielens.ITEM_COLUMN: tf.io.FixedLenFeature([], dtype=tf.string),
    rconst.MASK_START_INDEX: tf.io.FixedLenFeature([1], dtype=tf.string),
    "labels": tf.io.FixedLenFeature([], dtype=tf.string),
64
65
66
67
}


_EVAL_FEATURE_MAP = {
68
69
70
    movielens.USER_COLUMN: tf.io.FixedLenFeature([], dtype=tf.string),
    movielens.ITEM_COLUMN: tf.io.FixedLenFeature([], dtype=tf.string),
    rconst.DUPLICATE_MASK: tf.io.FixedLenFeature([], dtype=tf.string)
71
72
73
74
75
76
77
78
79
80
81
}


class DatasetManager(object):
  """Helper class for handling TensorFlow specific data tasks.

  This class takes the (relatively) framework agnostic work done by the data
  constructor classes and handles the TensorFlow specific portions (TFRecord
  management, tf.Dataset creation, etc.).
  """
  def __init__(self, is_training, stream_files, batches_per_epoch,
82
83
               shard_root=None, deterministic=False):
    # type: (bool, bool, int, typing.Optional[str], bool) -> None
Taylor Robie's avatar
Taylor Robie committed
84
85
86
87
88
89
90
91
92
93
    """Constructs a `DatasetManager` instance.
    Args:
      is_training: Boolean of whether the data provided is training or
        evaluation data. This determines whether to reuse the data
        (if is_training=False) and the exact structure to use when storing and
        yielding data.
      stream_files: Boolean indicating whether data should be serialized and
        written to file shards.
      batches_per_epoch: The number of batches in a single epoch.
      shard_root: The base directory to be used when stream_files=True.
94
      deterministic: Forgo non-deterministic speedups. (i.e. sloppy=True)
Taylor Robie's avatar
Taylor Robie committed
95
    """
96
    self._is_training = is_training
97
    self._deterministic = deterministic
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
    self._stream_files = stream_files
    self._writers = []
    self._write_locks = [threading.RLock() for _ in
                         range(rconst.NUM_FILE_SHARDS)] if stream_files else []
    self._batches_per_epoch = batches_per_epoch
    self._epochs_completed = 0
    self._epochs_requested = 0
    self._shard_root = shard_root

    self._result_queue = queue.Queue()
    self._result_reuse = []

  @property
  def current_data_root(self):
    subdir = (rconst.TRAIN_FOLDER_TEMPLATE.format(self._epochs_completed)
              if self._is_training else rconst.EVAL_FOLDER)
    return os.path.join(self._shard_root, subdir)

  def buffer_reached(self):
    # Only applicable for training.
    return (self._epochs_completed - self._epochs_requested >=
            rconst.CYCLES_TO_BUFFER and self._is_training)

  @staticmethod
  def _serialize(data):
    """Convert NumPy arrays into a TFRecords entry."""

    feature_dict = {
        k: tf.train.Feature(bytes_list=tf.train.BytesList(
            value=[memoryview(v).tobytes()])) for k, v in data.items()}

    return tf.train.Example(
        features=tf.train.Features(feature=feature_dict)).SerializeToString()

  def _deserialize(self, serialized_data, batch_size):
    """Convert serialized TFRecords into tensors.

    Args:
      serialized_data: A tensor containing serialized records.
      batch_size: The data arrives pre-batched, so batch size is needed to
        deserialize the data.
    """
    feature_map = _TRAIN_FEATURE_MAP if self._is_training else _EVAL_FEATURE_MAP
    features = tf.parse_single_example(serialized_data, feature_map)

    users = tf.reshape(tf.decode_raw(
        features[movielens.USER_COLUMN], rconst.USER_DTYPE), (batch_size,))
    items = tf.reshape(tf.decode_raw(
        features[movielens.ITEM_COLUMN], rconst.ITEM_DTYPE), (batch_size,))

    def decode_binary(data_bytes):
      # tf.decode_raw does not support bool as a decode type. As a result it is
      # necessary to decode to int8 (7 of the bits will be ignored) and then
      # cast to bool.
      return tf.reshape(tf.cast(tf.decode_raw(data_bytes, tf.int8), tf.bool),
                        (batch_size,))

    if self._is_training:
      mask_start_index = tf.decode_raw(
          features[rconst.MASK_START_INDEX], tf.int32)[0]
      valid_point_mask = tf.less(tf.range(batch_size), mask_start_index)

      return {
          movielens.USER_COLUMN: users,
          movielens.ITEM_COLUMN: items,
          rconst.VALID_POINT_MASK: valid_point_mask,
      }, decode_binary(features["labels"])

    return {
        movielens.USER_COLUMN: users,
        movielens.ITEM_COLUMN: items,
        rconst.DUPLICATE_MASK: decode_binary(features[rconst.DUPLICATE_MASK]),
    }

  def put(self, index, data):
    # type: (int, dict) -> None
    """Store data for later consumption.

    Because there are several paths for storing and yielding data (queues,
    lists, files) the data producer simply provides the data in a standard
    format at which point the dataset manager handles storing it in the correct
    form.

    Args:
      index: Used to select shards when writing to files.
      data: A dict of the data to be stored. This method mutates data, and
        therefore expects to be the only consumer.
    """

    if self._stream_files:
      example_bytes = self._serialize(data)
      with self._write_locks[index % rconst.NUM_FILE_SHARDS]:
        self._writers[index % rconst.NUM_FILE_SHARDS].write(example_bytes)

    else:
      if self._is_training:
        mask_start_index = data.pop(rconst.MASK_START_INDEX)
        batch_size = data[movielens.ITEM_COLUMN].shape[0]
        data[rconst.VALID_POINT_MASK] = np.less(np.arange(batch_size),
                                                mask_start_index)
Taylor Robie's avatar
Taylor Robie committed
198
199
        data = (data, data.pop("labels"))
      self._result_queue.put(data)
200
201
202

  def start_construction(self):
    if self._stream_files:
203
      tf.io.gfile.makedirs(self.current_data_root)
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
      template = os.path.join(self.current_data_root, rconst.SHARD_TEMPLATE)
      self._writers = [tf.io.TFRecordWriter(template.format(i))
                       for i in range(rconst.NUM_FILE_SHARDS)]

  def end_construction(self):
    if self._stream_files:
      [writer.close() for writer in self._writers]
      self._writers = []
      self._result_queue.put(self.current_data_root)

    self._epochs_completed += 1

  def data_generator(self, epochs_between_evals):
    """Yields examples during local training."""
    assert not self._stream_files
Taylor Robie's avatar
Taylor Robie committed
219
    assert self._is_training or epochs_between_evals == 1
220
221
222
223
224
225

    if self._is_training:
      for _ in range(self._batches_per_epoch * epochs_between_evals):
        yield self._result_queue.get(timeout=300)

    else:
Taylor Robie's avatar
Taylor Robie committed
226
227
228
229
230
231
232
233
234
235
236
237
      if self._result_reuse:
        assert len(self._result_reuse) == self._batches_per_epoch

        for i in self._result_reuse:
          yield i
      else:
        # First epoch.
        for _ in range(self._batches_per_epoch * epochs_between_evals):
          result = self._result_queue.get(timeout=300)
          self._result_reuse.append(result)
          yield result

Shining Sun's avatar
Shining Sun committed
238
239
  def increment_request_epoch(self):
    self._epochs_requested += 1
240
241
242
243
244
245
246
247
248

  def get_dataset(self, batch_size, epochs_between_evals):
    """Construct the dataset to be used for training and eval.

    For local training, data is provided through Dataset.from_generator. For
    remote training (TPUs) the data is first serialized to files and then sent
    to the TPU through a StreamingFilesDataset.

    Args:
249
      batch_size: The per-replica batch size of the dataset.
250
251
252
      epochs_between_evals: How many epochs worth of data to yield.
        (Generator mode only.)
    """
Shining Sun's avatar
Shining Sun committed
253
    self.increment_request_epoch()
254
255
256
257
258
259
260
261
262
263
    if self._stream_files:
      if epochs_between_evals > 1:
        raise ValueError("epochs_between_evals > 1 not supported for file "
                         "based dataset.")
      epoch_data_dir = self._result_queue.get(timeout=300)
      if not self._is_training:
        self._result_queue.put(epoch_data_dir)  # Eval data is reused.

      file_pattern = os.path.join(
          epoch_data_dir, rconst.SHARD_TEMPLATE.format("*"))
Shining Sun's avatar
Shining Sun committed
264
      # TODO(seemuch): remove this contrib import
265
266
267
      # pylint: disable=line-too-long
      from tensorflow.contrib.tpu.python.tpu.datasets import StreamingFilesDataset
      # pylint: enable=line-too-long
268
      dataset = StreamingFilesDataset(
269
          files=file_pattern, worker_job=popen_helper.worker_job(),
270
271
          num_parallel_reads=rconst.NUM_FILE_SHARDS, num_epochs=1,
          sloppy=not self._deterministic)
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
      map_fn = functools.partial(self._deserialize, batch_size=batch_size)
      dataset = dataset.map(map_fn, num_parallel_calls=16)

    else:
      types = {movielens.USER_COLUMN: rconst.USER_DTYPE,
               movielens.ITEM_COLUMN: rconst.ITEM_DTYPE}
      shapes = {movielens.USER_COLUMN: tf.TensorShape([batch_size]),
                movielens.ITEM_COLUMN: tf.TensorShape([batch_size])}

      if self._is_training:
        types[rconst.VALID_POINT_MASK] = np.bool
        shapes[rconst.VALID_POINT_MASK] = tf.TensorShape([batch_size])

        types = (types, np.bool)
        shapes = (shapes, tf.TensorShape([batch_size]))

      else:
        types[rconst.DUPLICATE_MASK] = np.bool
        shapes[rconst.DUPLICATE_MASK] = tf.TensorShape([batch_size])

      data_generator = functools.partial(
          self.data_generator, epochs_between_evals=epochs_between_evals)
      dataset = tf.data.Dataset.from_generator(
          generator=data_generator, output_types=types,
          output_shapes=shapes)

    return dataset.prefetch(16)

  def make_input_fn(self, batch_size):
    """Create an input_fn which checks for batch size consistency."""

    def input_fn(params):
304
305
306
307
      """Returns batches for training."""

      # Estimator passes batch_size during training and eval_batch_size during
      # eval. TPUEstimator only passes batch_size.
308
      param_batch_size = (params["batch_size"] if self._is_training else
309
                          params.get("eval_batch_size") or params["batch_size"])
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
      if batch_size != param_batch_size:
        raise ValueError("producer batch size ({}) differs from params batch "
                         "size ({})".format(batch_size, param_batch_size))

      epochs_between_evals = (params.get("epochs_between_evals", 1)
                              if self._is_training else 1)
      return self.get_dataset(batch_size=batch_size,
                              epochs_between_evals=epochs_between_evals)

    return input_fn


class BaseDataConstructor(threading.Thread):
  """Data constructor base class.

  This class manages the control flow for constructing data. It is not meant
  to be used directly, but instead subclasses should implement the following
  two methods:

    self.construct_lookup_variables
    self.lookup_negative_items

  """
  def __init__(self,
               maximum_number_epochs,   # type: int
               num_users,               # type: int
               num_items,               # type: int
               user_map,                # type: dict
               item_map,                # type: dict
               train_pos_users,         # type: np.ndarray
               train_pos_items,         # type: np.ndarray
               train_batch_size,        # type: int
               batches_per_train_step,  # type: int
               num_train_negatives,     # type: int
               eval_pos_users,          # type: np.ndarray
               eval_pos_items,          # type: np.ndarray
               eval_batch_size,         # type: int
               batches_per_eval_step,   # type: int
348
               stream_files,            # type: bool
349
               deterministic=False,     # type: bool
350
               epoch_dir=None           # type: str
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
              ):
    # General constants
    self._maximum_number_epochs = maximum_number_epochs
    self._num_users = num_users
    self._num_items = num_items
    self.user_map = user_map
    self.item_map = item_map
    self._train_pos_users = train_pos_users
    self._train_pos_items = train_pos_items
    self.train_batch_size = train_batch_size
    self._num_train_negatives = num_train_negatives
    self._batches_per_train_step = batches_per_train_step
    self._eval_pos_users = eval_pos_users
    self._eval_pos_items = eval_pos_items
    self.eval_batch_size = eval_batch_size

    # Training
    if self._train_pos_users.shape != self._train_pos_items.shape:
      raise ValueError(
          "User positives ({}) is different from item positives ({})".format(
              self._train_pos_users.shape, self._train_pos_items.shape))

Taylor Robie's avatar
Taylor Robie committed
373
    (self._train_pos_count,) = self._train_pos_users.shape
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
    self._elements_in_epoch = (1 + num_train_negatives) * self._train_pos_count
    self.train_batches_per_epoch = self._count_batches(
        self._elements_in_epoch, train_batch_size, batches_per_train_step)

    # Evaluation
    if eval_batch_size % (1 + rconst.NUM_EVAL_NEGATIVES):
      raise ValueError("Eval batch size {} is not divisible by {}".format(
          eval_batch_size, 1 + rconst.NUM_EVAL_NEGATIVES))
    self._eval_users_per_batch = int(
        eval_batch_size // (1 + rconst.NUM_EVAL_NEGATIVES))
    self._eval_elements_in_epoch = num_users * (1 + rconst.NUM_EVAL_NEGATIVES)
    self.eval_batches_per_epoch = self._count_batches(
        self._eval_elements_in_epoch, eval_batch_size, batches_per_eval_step)

    # Intermediate artifacts
    self._current_epoch_order = np.empty(shape=(0,))
    self._shuffle_iterator = None

Taylor Robie's avatar
Taylor Robie committed
392
    self._shuffle_with_forkpool = not stream_files
393
    if stream_files:
394
      self._shard_root = epoch_dir or tempfile.mkdtemp(prefix="ncf_")
395
      atexit.register(tf.io.gfile.rmtree, dirname=self._shard_root)
396
397
398
399
    else:
      self._shard_root = None

    self._train_dataset = DatasetManager(
400
401
        True, stream_files, self.train_batches_per_epoch, self._shard_root,
        deterministic)
402
    self._eval_dataset = DatasetManager(
403
404
        False, stream_files, self.eval_batches_per_epoch, self._shard_root,
        deterministic)
405
406
407
408
409
410

    # Threading details
    super(BaseDataConstructor, self).__init__()
    self.daemon = True
    self._stop_loop = False
    self._fatal_exception = None
411
    self.deterministic = deterministic
412

Taylor Robie's avatar
Taylor Robie committed
413
  def __str__(self):
414
415
416
417
418
419
420
421
422
    multiplier = ("(x{} devices)".format(self._batches_per_train_step)
                  if self._batches_per_train_step > 1 else "")
    summary = SUMMARY_TEMPLATE.format(
        spacer="  ", num_users=self._num_users, num_items=self._num_items,
        train_pos_ct=self._train_pos_count,
        train_batch_size=self.train_batch_size,
        train_batch_ct=self.train_batches_per_epoch,
        eval_pos_ct=self._num_users, eval_batch_size=self.eval_batch_size,
        eval_batch_ct=self.eval_batches_per_epoch, multiplier=multiplier)
Taylor Robie's avatar
Taylor Robie committed
423
    return super(BaseDataConstructor, self).__str__() + "\n" + summary
424
425
426

  @staticmethod
  def _count_batches(example_count, batch_size, batches_per_step):
Taylor Robie's avatar
Taylor Robie committed
427
    """Determine the number of batches, rounding up to fill all devices."""
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
    x = (example_count + batch_size - 1) // batch_size
    return (x + batches_per_step - 1) // batches_per_step * batches_per_step

  def stop_loop(self):
    self._stop_loop = True

  def construct_lookup_variables(self):
    """Perform any one time pre-compute work."""
    raise NotImplementedError

  def lookup_negative_items(self, **kwargs):
    """Randomly sample negative items for given users."""
    raise NotImplementedError

  def _run(self):
    atexit.register(self.stop_loop)
    self._start_shuffle_iterator()
    self.construct_lookup_variables()
    self._construct_training_epoch()
    self._construct_eval_epoch()
    for _ in range(self._maximum_number_epochs - 1):
      self._construct_training_epoch()
450
    self.stop_loop()
451
452
453
454
455
456
457

  def run(self):
    try:
      self._run()
    except Exception as e:
      # The Thread base class swallows stack traces, so unfortunately it is
      # necessary to catch and re-raise to get debug output
Taylor Robie's avatar
Taylor Robie committed
458
      traceback.print_exc()
459
460
461
462
463
      self._fatal_exception = e
      sys.stderr.flush()
      raise

  def _start_shuffle_iterator(self):
464
465
466
467
    if self._shuffle_with_forkpool:
      pool = popen_helper.get_forkpool(3, closing=False)
    else:
      pool = popen_helper.get_threadpool(1, closing=False)
468
469
470
    atexit.register(pool.close)
    args = [(self._elements_in_epoch, stat_utils.random_int32())
            for _ in range(self._maximum_number_epochs)]
471
472
    imap = pool.imap if self.deterministic else pool.imap_unordered
    self._shuffle_iterator = imap(stat_utils.permutation, args)
473
474
475
476
477
478
479
480

  def _get_training_batch(self, i):
    """Construct a single batch of training data.

    Args:
      i: The index of the batch. This is used when stream_files=True to assign
        data to file shards.
    """
Taylor Robie's avatar
Taylor Robie committed
481
482
483
    batch_indices = self._current_epoch_order[i * self.train_batch_size:
                                              (i + 1) * self.train_batch_size]
    (mask_start_index,) = batch_indices.shape
484
485
486
487
488
489
490
491
492
493
494
495

    batch_ind_mod = np.mod(batch_indices, self._train_pos_count)
    users = self._train_pos_users[batch_ind_mod]

    negative_indices = np.greater_equal(batch_indices, self._train_pos_count)
    negative_users = users[negative_indices]

    negative_items = self.lookup_negative_items(negative_users=negative_users)

    items = self._train_pos_items[batch_ind_mod]
    items[negative_indices] = negative_items

Taylor Robie's avatar
Taylor Robie committed
496
    labels = np.logical_not(negative_indices)
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523

    # Pad last partial batch
    pad_length = self.train_batch_size - mask_start_index
    if pad_length:
      # We pad with arange rather than zeros because the network will still
      # compute logits for padded examples, and padding with zeros would create
      # a very "hot" embedding key which can have performance implications.
      user_pad = np.arange(pad_length, dtype=users.dtype) % self._num_users
      item_pad = np.arange(pad_length, dtype=items.dtype) % self._num_items
      label_pad = np.zeros(shape=(pad_length,), dtype=labels.dtype)
      users = np.concatenate([users, user_pad])
      items = np.concatenate([items, item_pad])
      labels = np.concatenate([labels, label_pad])

    self._train_dataset.put(i, {
        movielens.USER_COLUMN: users,
        movielens.ITEM_COLUMN: items,
        rconst.MASK_START_INDEX: np.array(mask_start_index, dtype=np.int32),
        "labels": labels,
    })

  def _wait_to_construct_train_epoch(self):
    count = 0
    while self._train_dataset.buffer_reached() and not self._stop_loop:
      time.sleep(0.01)
      count += 1
      if count >= 100 and np.log10(count) == np.round(np.log10(count)):
524
        logging.info(
525
526
527
528
529
530
531
532
533
534
535
            "Waited {} times for training data to be consumed".format(count))

  def _construct_training_epoch(self):
    """Loop to construct a batch of training data."""
    self._wait_to_construct_train_epoch()
    start_time = timeit.default_timer()
    if self._stop_loop:
      return

    self._train_dataset.start_construction()
    map_args = list(range(self.train_batches_per_epoch))
Taylor Robie's avatar
Taylor Robie committed
536
    self._current_epoch_order = next(self._shuffle_iterator)
537

538
539
540
    get_pool = (popen_helper.get_fauxpool if self.deterministic else
                popen_helper.get_threadpool)
    with get_pool(6) as pool:
541
542
543
      pool.map(self._get_training_batch, map_args)
    self._train_dataset.end_construction()

544
    logging.info("Epoch construction complete. Time: {:.1f} seconds".format(
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
        timeit.default_timer() - start_time))

  @staticmethod
  def _assemble_eval_batch(users, positive_items, negative_items,
                           users_per_batch):
    """Construct duplicate_mask and structure data accordingly.

    The positive items should be last so that they lose ties. However, they
    should not be masked out if the true eval positive happens to be
    selected as a negative. So instead, the positive is placed in the first
    position, and then switched with the last element after the duplicate
    mask has been computed.

    Args:
      users: An array of users in a batch. (should be identical along axis 1)
      positive_items: An array (batch_size x 1) of positive item indices.
      negative_items: An array of negative item indices.
      users_per_batch: How many users should be in the batch. This is passed
        as an argument so that ncf_test.py can use this method.

    Returns:
      User, item, and duplicate_mask arrays.
    """
    items = np.concatenate([positive_items, negative_items], axis=1)

    # We pad the users and items here so that the duplicate mask calculation
Taylor Robie's avatar
Taylor Robie committed
571
    # will include padding. The metric function relies on all padded elements
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
    # except the positive being marked as duplicate to mask out padded points.
    if users.shape[0] < users_per_batch:
      pad_rows = users_per_batch - users.shape[0]
      padding = np.zeros(shape=(pad_rows, users.shape[1]), dtype=np.int32)
      users = np.concatenate([users, padding.astype(users.dtype)], axis=0)
      items = np.concatenate([items, padding.astype(items.dtype)], axis=0)

    duplicate_mask = stat_utils.mask_duplicates(items, axis=1).astype(np.bool)

    items[:, (0, -1)] = items[:, (-1, 0)]
    duplicate_mask[:, (0, -1)] = duplicate_mask[:, (-1, 0)]

    assert users.shape == items.shape == duplicate_mask.shape
    return users, items, duplicate_mask

  def _get_eval_batch(self, i):
    """Construct a single batch of evaluation data.

    Args:
      i: The index of the batch.
    """
    low_index = i * self._eval_users_per_batch
    high_index = (i + 1) * self._eval_users_per_batch
    users = np.repeat(self._eval_pos_users[low_index:high_index, np.newaxis],
                      1 + rconst.NUM_EVAL_NEGATIVES, axis=1)
    positive_items = self._eval_pos_items[low_index:high_index, np.newaxis]
    negative_items = (self.lookup_negative_items(negative_users=users[:, :-1])
                      .reshape(-1, rconst.NUM_EVAL_NEGATIVES))

    users, items, duplicate_mask = self._assemble_eval_batch(
        users, positive_items, negative_items, self._eval_users_per_batch)

    self._eval_dataset.put(i, {
        movielens.USER_COLUMN: users.flatten(),
        movielens.ITEM_COLUMN: items.flatten(),
        rconst.DUPLICATE_MASK: duplicate_mask.flatten(),
    })

  def _construct_eval_epoch(self):
    """Loop to construct data for evaluation."""
    if self._stop_loop:
      return

    start_time = timeit.default_timer()

    self._eval_dataset.start_construction()
    map_args = [i for i in range(self.eval_batches_per_epoch)]
619
620
621
622

    get_pool = (popen_helper.get_fauxpool if self.deterministic else
                popen_helper.get_threadpool)
    with get_pool(6) as pool:
623
624
625
      pool.map(self._get_eval_batch, map_args)
    self._eval_dataset.end_construction()

626
    logging.info("Eval construction complete. Time: {:.1f} seconds".format(
627
628
629
        timeit.default_timer() - start_time))

  def make_input_fn(self, is_training):
Taylor Robie's avatar
Taylor Robie committed
630
631
    # It isn't feasible to provide a foolproof check, so this is designed to
    # catch most failures rather than provide an exhaustive guard.
632
633
634
635
636
637
638
639
    if self._fatal_exception is not None:
      raise ValueError("Fatal exception in the data production loop: {}"
                       .format(self._fatal_exception))

    return (
        self._train_dataset.make_input_fn(self.train_batch_size) if is_training
        else self._eval_dataset.make_input_fn(self.eval_batch_size))

Shining Sun's avatar
Shining Sun committed
640
641
642
  def increment_request_epoch(self):
    self._train_dataset.increment_request_epoch()

643
644
645

class DummyConstructor(threading.Thread):
  """Class for running with synthetic data."""
646

647
648
649
650
651
652
  def run(self):
    pass

  def stop_loop(self):
    pass

Shining Sun's avatar
Shining Sun committed
653
654
655
  def increment_request_epoch(self):
    pass

656
657
658
659
660
  @staticmethod
  def make_input_fn(is_training):
    """Construct training input_fn that uses synthetic data."""

    def input_fn(params):
661
662
663
664
      """Returns dummy input batches for training."""

      # Estimator passes batch_size during training and eval_batch_size during
      # eval. TPUEstimator only passes batch_size.
665
      batch_size = (params["batch_size"] if is_training else
666
                    params.get("eval_batch_size") or params["batch_size"])
667
668
669
      num_users = params["num_users"]
      num_items = params["num_items"]

670
      users = tf.random.uniform([batch_size], dtype=tf.int32, minval=0,
671
                                maxval=num_users)
672
      items = tf.random.uniform([batch_size], dtype=tf.int32, minval=0,
673
674
675
                                maxval=num_items)

      if is_training:
676
        valid_point_mask = tf.cast(tf.random.uniform(
677
            [batch_size], dtype=tf.int32, minval=0, maxval=2), tf.bool)
678
        labels = tf.cast(tf.random.uniform(
679
680
681
682
683
684
685
            [batch_size], dtype=tf.int32, minval=0, maxval=2), tf.bool)
        data = {
            movielens.USER_COLUMN: users,
            movielens.ITEM_COLUMN: items,
            rconst.VALID_POINT_MASK: valid_point_mask,
        }, labels
      else:
686
        dupe_mask = tf.cast(tf.random.uniform([batch_size], dtype=tf.int32,
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
                                              minval=0, maxval=2), tf.bool)
        data = {
            movielens.USER_COLUMN: users,
            movielens.ITEM_COLUMN: items,
            rconst.DUPLICATE_MASK: dupe_mask,
        }

      dataset = tf.data.Dataset.from_tensors(data).repeat(
          rconst.SYNTHETIC_BATCHES_PER_EPOCH * params["batches_per_step"])
      dataset = dataset.prefetch(32)
      return dataset

    return input_fn


class MaterializedDataConstructor(BaseDataConstructor):
  """Materialize a table of negative examples for fast negative generation.

  This class creates a table (num_users x num_items) containing all of the
  negative examples for each user. This table is conceptually ragged; that is to
Taylor Robie's avatar
Taylor Robie committed
707
  say the items dimension will have a number of unused elements at the end equal
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
  to the number of positive elements for a given user. For instance:

  num_users = 3
  num_items = 5
  positives = [[1, 3], [0], [1, 2, 3, 4]]

  will generate a negative table:
  [
    [0         2         4         int32max  int32max],
    [1         2         3         4         int32max],
    [0         int32max  int32max  int32max  int32max],
  ]

  and a vector of per-user negative counts, which in this case would be:
    [3, 4, 1]

  When sampling negatives, integers are (nearly) uniformly selected from the
  range [0, per_user_neg_count[user]) which gives a column_index, at which
  point the negative can be selected as:
    negative_table[user, column_index]

  This technique will not scale; however MovieLens is small enough that even
  a pre-compute which is quadratic in problem size will still fit in memory. A
  more scalable lookup method is in the works.
  """
  def __init__(self, *args, **kwargs):
    super(MaterializedDataConstructor, self).__init__(*args, **kwargs)
    self._negative_table = None
    self._per_user_neg_count = None

  def construct_lookup_variables(self):
    # Materialize negatives for fast lookup sampling.
    start_time = timeit.default_timer()
    inner_bounds = np.argwhere(self._train_pos_users[1:] -
                               self._train_pos_users[:-1])[:, 0] + 1
Taylor Robie's avatar
Taylor Robie committed
743
    (upper_bound,) = self._train_pos_users.shape
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
    index_bounds = [0] + inner_bounds.tolist() + [upper_bound]
    self._negative_table = np.zeros(shape=(self._num_users, self._num_items),
                                    dtype=rconst.ITEM_DTYPE)

    # Set the table to the max value to make sure the embedding lookup will fail
    # if we go out of bounds, rather than just overloading item zero.
    self._negative_table += np.iinfo(rconst.ITEM_DTYPE).max
    assert self._num_items < np.iinfo(rconst.ITEM_DTYPE).max

    # Reuse arange during generation. np.delete will make a copy.
    full_set = np.arange(self._num_items, dtype=rconst.ITEM_DTYPE)

    self._per_user_neg_count = np.zeros(
        shape=(self._num_users,), dtype=np.int32)

    # Threading does not improve this loop. For some reason, the np.delete
    # call does not parallelize well. Multiprocessing incurs too much
    # serialization overhead to be worthwhile.
    for i in range(self._num_users):
      positives = self._train_pos_items[index_bounds[i]:index_bounds[i+1]]
      negatives = np.delete(full_set, positives)
      self._per_user_neg_count[i] = self._num_items - positives.shape[0]
      self._negative_table[i, :self._per_user_neg_count[i]] = negatives

768
    logging.info("Negative sample table built. Time: {:.1f} seconds".format(
769
770
771
772
773
774
        timeit.default_timer() - start_time))

  def lookup_negative_items(self, negative_users, **kwargs):
    negative_item_choice = stat_utils.very_slightly_biased_randint(
        self._per_user_neg_count[negative_users])
    return self._negative_table[negative_users, negative_item_choice]
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820


class BisectionDataConstructor(BaseDataConstructor):
  """Use bisection to index within positive examples.

  This class tallies the number of negative items which appear before each
  positive item for a user. This means that in order to select the ith negative
  item for a user, it only needs to determine which two positive items bound
  it at which point the item id for the ith negative is a simply algebraic
  expression.
  """
  def __init__(self, *args, **kwargs):
    super(BisectionDataConstructor, self).__init__(*args, **kwargs)
    self.index_bounds = None
    self._sorted_train_pos_items = None
    self._total_negatives = None

  def _index_segment(self, user):
    lower, upper = self.index_bounds[user:user+2]
    items = self._sorted_train_pos_items[lower:upper]

    negatives_since_last_positive = np.concatenate(
        [items[0][np.newaxis], items[1:] - items[:-1] - 1])

    return np.cumsum(negatives_since_last_positive)

  def construct_lookup_variables(self):
    start_time = timeit.default_timer()
    inner_bounds = np.argwhere(self._train_pos_users[1:] -
                               self._train_pos_users[:-1])[:, 0] + 1
    (upper_bound,) = self._train_pos_users.shape
    self.index_bounds = np.array([0] + inner_bounds.tolist() + [upper_bound])

    # Later logic will assume that the users are in sequential ascending order.
    assert np.array_equal(self._train_pos_users[self.index_bounds[:-1]],
                          np.arange(self._num_users))

    self._sorted_train_pos_items = self._train_pos_items.copy()

    for i in range(self._num_users):
      lower, upper = self.index_bounds[i:i+2]
      self._sorted_train_pos_items[lower:upper].sort()

    self._total_negatives = np.concatenate([
        self._index_segment(i) for i in range(self._num_users)])

821
    logging.info("Negative total vector built. Time: {:.1f} seconds".format(
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
        timeit.default_timer() - start_time))

  def lookup_negative_items(self, negative_users, **kwargs):
    output = np.zeros(shape=negative_users.shape, dtype=rconst.ITEM_DTYPE) - 1

    left_index = self.index_bounds[negative_users]
    right_index = self.index_bounds[negative_users + 1] - 1

    num_positives = right_index - left_index + 1
    num_negatives = self._num_items - num_positives
    neg_item_choice = stat_utils.very_slightly_biased_randint(num_negatives)

    # Shortcuts:
    # For points where the negative is greater than or equal to the tally before
    # the last positive point there is no need to bisect. Instead the item id
    # corresponding to the negative item choice is simply:
    #   last_postive_index + 1 + (neg_choice - last_negative_tally)
    # Similarly, if the selection is less than the tally at the first positive
    # then the item_id is simply the selection.
    #
    # Because MovieLens organizes popular movies into low integers (which is
    # preserved through the preprocessing), the first shortcut is very
    # efficient, allowing ~60% of samples to bypass the bisection. For the same
    # reason, the second shortcut is rarely triggered (<0.02%) and is therefore
    # not worth implementing.
    use_shortcut = neg_item_choice >= self._total_negatives[right_index]
    output[use_shortcut] = (
        self._sorted_train_pos_items[right_index] + 1 +
        (neg_item_choice - self._total_negatives[right_index])
    )[use_shortcut]

853
854
855
856
    if np.all(use_shortcut):
      # The bisection code is ill-posed when there are no elements.
      return output

857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
    not_use_shortcut = np.logical_not(use_shortcut)
    left_index = left_index[not_use_shortcut]
    right_index = right_index[not_use_shortcut]
    neg_item_choice = neg_item_choice[not_use_shortcut]

    num_loops = np.max(
        np.ceil(np.log2(num_positives[not_use_shortcut])).astype(np.int32))

    for i in range(num_loops):
      mid_index = (left_index + right_index) // 2
      right_criteria = self._total_negatives[mid_index] > neg_item_choice
      left_criteria = np.logical_not(right_criteria)

      right_index[right_criteria] = mid_index[right_criteria]
      left_index[left_criteria] = mid_index[left_criteria]

    # Expected state after bisection pass:
    #   The right index is the smallest index whose tally is greater than the
    #   negative item choice index.

    assert np.all((right_index - left_index) <= 1)

    output[not_use_shortcut] = (
        self._sorted_train_pos_items[right_index] -
        (self._total_negatives[right_index] - neg_item_choice)
    )

    assert np.all(output >= 0)

    return output


def get_constructor(name):
  if name == "bisection":
    return BisectionDataConstructor
  if name == "materialized":
    return MaterializedDataConstructor
  raise ValueError("Unrecognized constructor: {}".format(name))