Skip to content

tensor_stream

Tensor stream support.

This module implements a simple on-disk tensor storage format (a "tensor stream") which allows to append - possibly repeatedly - tensors to a data store, and then to read back the stored data in a random access fashion.

A tensor stream is stored inside a folder which contains one sub-folder per stream, each of them holding a sequence of .npy files (chunks) which are memory-mapped when accessed. Optionally, a state file can be stored in the tensor stream folder as well, so that arbitrary metadata - like the epoch at which the stream has been written - can be persisted along with the data.

Writing a tensor stream::

writer = Writer('/data/mystream') writer.write(feats, labels) # Writes one batch of samples. writer.write(feats, labels) # Writes another batch of samples. writer.flush(final=True) # Flushes pending data to disk and closes.

Reading a tensor stream::

reader = Reader('/data/mystream') feats = reader.get_slice(0, start=10, size=5)

Tensor streams can also be accessed as if they were numpy arrays (see StreamArray) or PyTorch datasets (see Dataset).

Writer

A tensor stream writer.

A writer accumulates tensors - one per stream - in memory, and flushes them to the tensor stream folder as chunk files whenever the amount of pending data reaches a given chunk size.

Example
writer = tensor_stream.Writer('/data/mystream')
writer.write(feats, labels)  # One tensor per stream.
writer.flush(final=True)     # Write the pending chunks and close.
Source code in py_misc_utils/tensor_stream.py
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
class Writer:
  """A tensor stream writer.

  A writer accumulates tensors - one per stream - in memory, and flushes
  them to the tensor stream folder as chunk files whenever the amount of
  pending data reaches a given chunk size.

  Example:
    writer = tensor_stream.Writer('/data/mystream')
    writer.write(feats, labels)  # One tensor per stream.
    writer.flush(final=True)     # Write the pending chunks and close.
  """

  def __init__(self, path, chunk_size=100 * 1024 * 1024):
    """Creates a tensor stream writer.

    Args:
      path: The tensor stream folder path. It must not already exist.
      chunk_size: The amount of data (in bytes) accumulated before a chunk
        is written to disk.

    Raises:
      RuntimeError: If the tensor stream folder already exists.
    """
    if os.path.exists(path):
      alog.xraise(RuntimeError, f'Tensor stream folder must not exist: {path}')
    os.mkdir(path)
    self._path = path
    self._chunk_size = chunk_size
    self._chunks = []
    self._shapes = []
    self._indices = []

  # Note that the tensors handed over to the write() API will become owned by
  # the Writer obect, and cannot be written over after the write operation.
  def write(self, *args):
    """Write a batch of tensors to the stream.

    The tensors handed over become owned by the Writer object, and cannot
    be written over after the write operation.

    Args:
      *args: The tensors to write - one per configured stream, aligned in
        the major dimension.

    Raises:
      RuntimeError: When the tensor counts or major dimensions mismatch
        the configured streams.
    """
    size = len(args[0]) if args else 0
    if not self._chunks:
      self._chunks = [_ChunkList(init=t) for t in args]
      self._shapes = [t.shape for t in args]
      self._indices = [0] * len(args)
      for i in range(len(args)):
        if size != len(args[i]):
          alog.xraise(
              RuntimeError,
              f'The major dimension of a write operation must match: {size} vs {len(args[i])}'
          )
        os.mkdir(os.path.join(self._path, str(i)))
    else:
      if len(args) != len(self._chunks):
        alog.xraise(
            RuntimeError,
            f'Written streams count must match: {len(args)} vs {len(self._chunks)}')
      for i, t in enumerate(args):
        if size != len(t):
          alog.xraise(
              RuntimeError,
              f'The major dimension of a write operation must match: {size} vs {len(t)}'
          )
        _check_shapes(self._shapes[i], t.shape)
        self._chunks[i].append(t)

    self.flush(final=False)

  def flush(self, final=True, state=None):
    """Flushes pending chunks of data to disk.

    Args:
      final: If True, all the non-empty pending chunks are written to disk.
        Otherwise only the chunks whose size reached the chunk size are
        written.
      state: An optional object to persist into the tensor stream state
        file - useful to store metadata (like epoch numbers) along the
        tensor stream data. When given, the state file is written (or
        overwritten), making is_stream_folder() report True for the
        stream folder.

    Example:
      writer = tensor_stream.Writer('/data/mystream')
      writer.write(feats, labels)
      writer.flush(final=True, state=dict(epoch=3))
    """
    for i, chunk in enumerate(self._chunks):
      if chunk is not None and chunk.size() > 0 and (final or
                                                     chunk.size() >= self._chunk_size):
        path = os.path.join(self._path, str(i), str(self._indices[i]) + '.npy')
        np.save(path, chunk.coalesce())

        self._indices[i] += 1
        self._chunks[i] = _ChunkList()

    if state is not None:
      with open(os.path.join(self._path, _STATE_FILE), mode='wb') as f:
        pickle.dump(state, f, protocol=ut.pickle_proto())

write(*args)

Write a batch of tensors to the stream.

The tensors handed over become owned by the Writer object, and cannot be written over after the write operation.

Parameters:

Name Type Description Default
*args

The tensors to write - one per configured stream, aligned in the major dimension.

()

Raises:

Type Description
RuntimeError

When the tensor counts or major dimensions mismatch the configured streams.

Source code in py_misc_utils/tensor_stream.py
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
def write(self, *args):
  """Write a batch of tensors to the stream.

  The tensors handed over become owned by the Writer object, and cannot
  be written over after the write operation.

  Args:
    *args: The tensors to write - one per configured stream, aligned in
      the major dimension.

  Raises:
    RuntimeError: When the tensor counts or major dimensions mismatch
      the configured streams.
  """
  size = len(args[0]) if args else 0
  if not self._chunks:
    self._chunks = [_ChunkList(init=t) for t in args]
    self._shapes = [t.shape for t in args]
    self._indices = [0] * len(args)
    for i in range(len(args)):
      if size != len(args[i]):
        alog.xraise(
            RuntimeError,
            f'The major dimension of a write operation must match: {size} vs {len(args[i])}'
        )
      os.mkdir(os.path.join(self._path, str(i)))
  else:
    if len(args) != len(self._chunks):
      alog.xraise(
          RuntimeError,
          f'Written streams count must match: {len(args)} vs {len(self._chunks)}')
    for i, t in enumerate(args):
      if size != len(t):
        alog.xraise(
            RuntimeError,
            f'The major dimension of a write operation must match: {size} vs {len(t)}'
        )
      _check_shapes(self._shapes[i], t.shape)
      self._chunks[i].append(t)

  self.flush(final=False)

flush(final=True, state=None)

Flushes pending chunks of data to disk.

Parameters:

Name Type Description Default
final

If True, all the non-empty pending chunks are written to disk. Otherwise only the chunks whose size reached the chunk size are written.

True
state

An optional object to persist into the tensor stream state file - useful to store metadata (like epoch numbers) along the tensor stream data. When given, the state file is written (or overwritten), making is_stream_folder() report True for the stream folder.

None
Example
writer = tensor_stream.Writer('/data/mystream')
writer.write(feats, labels)
writer.flush(final=True, state=dict(epoch=3))
Source code in py_misc_utils/tensor_stream.py
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
def flush(self, final=True, state=None):
  """Flushes pending chunks of data to disk.

  Args:
    final: If True, all the non-empty pending chunks are written to disk.
      Otherwise only the chunks whose size reached the chunk size are
      written.
    state: An optional object to persist into the tensor stream state
      file - useful to store metadata (like epoch numbers) along the
      tensor stream data. When given, the state file is written (or
      overwritten), making is_stream_folder() report True for the
      stream folder.

  Example:
    writer = tensor_stream.Writer('/data/mystream')
    writer.write(feats, labels)
    writer.flush(final=True, state=dict(epoch=3))
  """
  for i, chunk in enumerate(self._chunks):
    if chunk is not None and chunk.size() > 0 and (final or
                                                   chunk.size() >= self._chunk_size):
      path = os.path.join(self._path, str(i), str(self._indices[i]) + '.npy')
      np.save(path, chunk.coalesce())

      self._indices[i] += 1
      self._chunks[i] = _ChunkList()

  if state is not None:
    with open(os.path.join(self._path, _STATE_FILE), mode='wb') as f:
      pickle.dump(state, f, protocol=ut.pickle_proto())

Reader

A tensor stream reader.

A reader gives random access to the tensors stored in a tensor stream folder, optionally applying per-stream transformation functions to the data being read.

Example
reader = tensor_stream.Reader('/data/mystream')
reader.shape  # Per-stream shapes - e.g. ((5, 2), (5, 2)).
reader.get_slice(0, start=2, size=2)  # Rows 2:4 of stream 0.
reader.get_slices(2, size=1)  # Row 2 of every stream.
Source code in py_misc_utils/tensor_stream.py
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
class Reader:
  """A tensor stream reader.

  A reader gives random access to the tensors stored in a tensor stream
  folder, optionally applying per-stream transformation functions to the
  data being read.

  Example:
    reader = tensor_stream.Reader('/data/mystream')
    reader.shape  # Per-stream shapes - e.g. ((5, 2), (5, 2)).
    reader.get_slice(0, start=2, size=2)  # Rows 2:4 of stream 0.
    reader.get_slices(2, size=1)  # Row 2 of every stream.
  """

  def __init__(self, path, transforms=None):
    """Creates a tensor stream reader.

    Args:
      path: The tensor stream folder path.
      transforms: An optional list - one entry per stream - of functions
        taking a tensor and returning a transformed tensor, applied to the
        data before it is returned by the read operations.

    Raises:
      RuntimeError: If the tensor stream folder does not exist.
    """
    if not os.path.isdir(path):
      alog.xraise(RuntimeError, f'Tensor stream folder does not exist: {path}')
    self._path = path
    self._tensors = _load_tensors(path)
    self._sizes = _get_sizes(self._tensors)
    self.shape = _get_shapes(self._tensors)
    self.num_streams = len(self._tensors)
    self.state = dict()
    self._transforms = list(transforms) if transforms else None

    state_path = os.path.join(path, _STATE_FILE)
    if os.path.exists(state_path):
      with open(state_path, mode='rb') as f:
        self.state = pickle.load(f)

  @classmethod
  def is_stream_folder(cls, path):
    """Checks whether a folder holds a tensor stream with a state file.

    Note that a stream written without saving a state file does not
    count as a stream folder for this check.

    Args:
      path: The folder path to check.

    Returns:
      True if the folder contains a tensor stream state file.
    """
    state_path = os.path.join(path, _STATE_FILE)

    return os.path.exists(state_path)

  @property
  def dtype(self):
    """The dtype of each stream."""

    return tuple([self._tensors[n][0].dtype for n in range(self.num_streams)])

  def __len__(self):
    """Returns the number of samples stored in each stream."""

    lens = [self.shape[i][0] for i in range(self.num_streams)]
    tas.check(all(lens[0] == l for l in lens), msg=f'Mismatching sizes: {lens}')

    return lens[0] if lens else 0

  def tensor_sequence(self, streamno):
    """Returns the sequence of memory-mapped tensors of a stream.

    Args:
      streamno: The stream number.

    Returns:
      A tuple of memory-mapped tensors - one per chunk file of the stream.

    Raises:
      RuntimeError: If the stream number is out of range.
    """
    if streamno < 0 or streamno >= self.num_streams:
      alog.xraise(
          RuntimeError,
          f'Bad stream number {streamno}, must be >= 0 and < {self.num_streams}')

    return self._tensors[streamno]

  def get_slice(self, streamno, start, size=None):
    """Reads a slice of a stream.

    The slice may span multiple chunk files, in which case the chunks are
    transparently concatenated.

    Args:
      streamno: The stream number.
      start: The start index of the slice within the stream.
      size: The number of samples to read. If None, all the samples from
        start to the end of the stream are read.

    Returns:
      The sliced tensor, with its major dimension holding at most size
      elements, after having applied the stream transformation function -
      if any.

    Raises:
      RuntimeError: If the stream number is out of range.
      IndexError: If the slice start index is out of range.
    """
    if streamno < 0 or streamno >= self.num_streams:
      alog.xraise(
          RuntimeError,
          f'Bad stream number {streamno}, must be >= 0 and < {self.num_streams}')

    stream_tensors = self._tensors[streamno]
    stream_sizes = self._sizes[streamno]
    stream_shape = self.shape[streamno]

    if start < 0 or start >= stream_shape[0]:
      alog.xraise(
          IndexError,
          f'Invalid slice start index {start}, must be >= 0 and < {stream_shape[0]}')

    if size is None:
      size = stream_shape[0] - start
    else:
      size = min(size, stream_shape[0] - start)

    pos = bisect.bisect_right(stream_sizes, start) - 1
    tensor = stream_tensors[pos]
    tpos = start - stream_sizes[pos]
    tas.check_ge(tpos, 0)

    tsize = min(size, len(tensor) - tpos)
    slices = [tensor[tpos:tpos + tsize]]
    rsize = size - tsize
    while rsize > 0:
      pos += 1
      tensor = stream_tensors[pos]
      tsize = min(rsize, len(tensor))
      rsize -= tsize
      slices.append(tensor[:tsize])

    sliced_tensor = np.concatenate(slices) if len(slices) > 1 else slices[0]
    if self._transforms:
      sliced_tensor = self._transforms[streamno](sliced_tensor)

    return sliced_tensor

  def get_slices(self, start, size=None):
    """Reads a slice of each stream.

    Args:
      start: The start index of the slices within the streams.
      size: The number of samples to read from each stream. If None, all
        the samples from start to the end of the streams are read.

    Returns:
      A list of sliced tensors - one per stream.
    """
    return [self.get_slice(x, start, size=size) for x in range(self.num_streams)]

dtype property

The dtype of each stream.

is_stream_folder(path) classmethod

Checks whether a folder holds a tensor stream with a state file.

Note that a stream written without saving a state file does not count as a stream folder for this check.

Parameters:

Name Type Description Default
path

The folder path to check.

required

Returns:

Type Description

True if the folder contains a tensor stream state file.

Source code in py_misc_utils/tensor_stream.py
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
@classmethod
def is_stream_folder(cls, path):
  """Checks whether a folder holds a tensor stream with a state file.

  Note that a stream written without saving a state file does not
  count as a stream folder for this check.

  Args:
    path: The folder path to check.

  Returns:
    True if the folder contains a tensor stream state file.
  """
  state_path = os.path.join(path, _STATE_FILE)

  return os.path.exists(state_path)

tensor_sequence(streamno)

Returns the sequence of memory-mapped tensors of a stream.

Parameters:

Name Type Description Default
streamno

The stream number.

required

Returns:

Type Description

A tuple of memory-mapped tensors - one per chunk file of the stream.

Raises:

Type Description
RuntimeError

If the stream number is out of range.

Source code in py_misc_utils/tensor_stream.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
def tensor_sequence(self, streamno):
  """Returns the sequence of memory-mapped tensors of a stream.

  Args:
    streamno: The stream number.

  Returns:
    A tuple of memory-mapped tensors - one per chunk file of the stream.

  Raises:
    RuntimeError: If the stream number is out of range.
  """
  if streamno < 0 or streamno >= self.num_streams:
    alog.xraise(
        RuntimeError,
        f'Bad stream number {streamno}, must be >= 0 and < {self.num_streams}')

  return self._tensors[streamno]

get_slice(streamno, start, size=None)

Reads a slice of a stream.

The slice may span multiple chunk files, in which case the chunks are transparently concatenated.

Parameters:

Name Type Description Default
streamno

The stream number.

required
start

The start index of the slice within the stream.

required
size

The number of samples to read. If None, all the samples from start to the end of the stream are read.

None

Returns:

Type Description

The sliced tensor, with its major dimension holding at most size

elements, after having applied the stream transformation function -

if any.

Raises:

Type Description
RuntimeError

If the stream number is out of range.

IndexError

If the slice start index is out of range.

Source code in py_misc_utils/tensor_stream.py
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
def get_slice(self, streamno, start, size=None):
  """Reads a slice of a stream.

  The slice may span multiple chunk files, in which case the chunks are
  transparently concatenated.

  Args:
    streamno: The stream number.
    start: The start index of the slice within the stream.
    size: The number of samples to read. If None, all the samples from
      start to the end of the stream are read.

  Returns:
    The sliced tensor, with its major dimension holding at most size
    elements, after having applied the stream transformation function -
    if any.

  Raises:
    RuntimeError: If the stream number is out of range.
    IndexError: If the slice start index is out of range.
  """
  if streamno < 0 or streamno >= self.num_streams:
    alog.xraise(
        RuntimeError,
        f'Bad stream number {streamno}, must be >= 0 and < {self.num_streams}')

  stream_tensors = self._tensors[streamno]
  stream_sizes = self._sizes[streamno]
  stream_shape = self.shape[streamno]

  if start < 0 or start >= stream_shape[0]:
    alog.xraise(
        IndexError,
        f'Invalid slice start index {start}, must be >= 0 and < {stream_shape[0]}')

  if size is None:
    size = stream_shape[0] - start
  else:
    size = min(size, stream_shape[0] - start)

  pos = bisect.bisect_right(stream_sizes, start) - 1
  tensor = stream_tensors[pos]
  tpos = start - stream_sizes[pos]
  tas.check_ge(tpos, 0)

  tsize = min(size, len(tensor) - tpos)
  slices = [tensor[tpos:tpos + tsize]]
  rsize = size - tsize
  while rsize > 0:
    pos += 1
    tensor = stream_tensors[pos]
    tsize = min(rsize, len(tensor))
    rsize -= tsize
    slices.append(tensor[:tsize])

  sliced_tensor = np.concatenate(slices) if len(slices) > 1 else slices[0]
  if self._transforms:
    sliced_tensor = self._transforms[streamno](sliced_tensor)

  return sliced_tensor

get_slices(start, size=None)

Reads a slice of each stream.

Parameters:

Name Type Description Default
start

The start index of the slices within the streams.

required
size

The number of samples to read from each stream. If None, all the samples from start to the end of the streams are read.

None

Returns:

Type Description

A list of sliced tensors - one per stream.

Source code in py_misc_utils/tensor_stream.py
462
463
464
465
466
467
468
469
470
471
472
473
def get_slices(self, start, size=None):
  """Reads a slice of each stream.

  Args:
    start: The start index of the slices within the streams.
    size: The number of samples to read from each stream. If None, all
      the samples from start to the end of the streams are read.

  Returns:
    A list of sliced tensors - one per stream.
  """
  return [self.get_slice(x, start, size=size) for x in range(self.num_streams)]

StreamArray

Bases: Sequence

A stream seen as a 1-D sequence of numpy array samples.

StreamArray objects support indexing (both integer and slice indexing) and behave as if they were numpy arrays (via the array protocol).

Example
reader = tensor_stream.Reader('/data/mystream')
arr = tensor_stream.StreamArray(reader, 0)
arr[2]  # Sample 2 of stream 0.
arr[1:3]  # Samples 1:3 as a single numpy array.
numpy.asarray(arr)  # The whole stream as a numpy array.
Source code in py_misc_utils/tensor_stream.py
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
class StreamArray(collections.abc.Sequence):
  """A stream seen as a 1-D sequence of numpy array samples.

  StreamArray objects support indexing (both integer and slice indexing)
  and behave as if they were numpy arrays (via the __array__ protocol).

  Example:
    reader = tensor_stream.Reader('/data/mystream')
    arr = tensor_stream.StreamArray(reader, 0)
    arr[2]  # Sample 2 of stream 0.
    arr[1:3]  # Samples 1:3 as a single numpy array.
    numpy.asarray(arr)  # The whole stream as a numpy array.
  """

  def __init__(self, reader, streamno):
    """Creates a stream array.

    Args:
      reader: The Reader object holding the stream.
      streamno: The stream number.
    """
    super().__init__()
    self.reader = reader
    self.streamno = streamno
    self.shape = reader.shape[streamno]

  def __getitem__(self, i):
    """Reads one sample - or a slice of samples - of the stream.

    Args:
      i: An integer index, or a slice object.

    Returns:
      A numpy array holding the sample (dims: the stream shape without the
      major dimension) if i is an integer index, or a numpy array holding
      the requested samples if i is a slice.
    """
    if isinstance(i, slice):
      start, end, step = i.indices(len(self))
      if step != 1:
        parts = []
        for x in range(start, end, step):
          parts.append(self.reader.get_slice(self.streamno, x, size=1))
        return np.concatenate(parts)

      return self.reader.get_slice(self.streamno, start, size=end - start)

    return np.squeeze(self.reader.get_slice(self.streamno, i, size=1), axis=0)

  def __len__(self):
    """Returns the number of samples of the stream."""

    return self.shape[0]

  def to_numpy(self, dtype=None):
    """Reads the whole stream as a numpy array.

    Args:
      dtype: An optional numpy dtype the stream is casted to.

    Returns:
      The whole stream data as a numpy array.
    """
    npa = self.reader.get_slice(self.streamno, 0)

    return npa.astype(dtype) if dtype is not None else npa

  def __array__(self, dtype=None):
    """Returns the whole stream as a numpy array (numpy protocol)."""

    return self.to_numpy(dtype=dtype)

to_numpy(dtype=None)

Reads the whole stream as a numpy array.

Parameters:

Name Type Description Default
dtype

An optional numpy dtype the stream is casted to.

None

Returns:

Type Description

The whole stream data as a numpy array.

Source code in py_misc_utils/tensor_stream.py
530
531
532
533
534
535
536
537
538
539
540
541
def to_numpy(self, dtype=None):
  """Reads the whole stream as a numpy array.

  Args:
    dtype: An optional numpy dtype the stream is casted to.

  Returns:
    The whole stream data as a numpy array.
  """
  npa = self.reader.get_slice(self.streamno, 0)

  return npa.astype(dtype) if dtype is not None else npa

Dataset

Bases: Dataset

A tensor stream seen as a PyTorch dataset.

Each dataset item is a tuple of tensors - one per stream - holding the data of a single sample.

Example
ds = tensor_stream.Dataset('/data/mystream')
len(ds)  # The number of samples.
x0, x1 = ds[0]  # Torch tensors - one per stream.
Source code in py_misc_utils/tensor_stream.py
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
class Dataset(data_utils.Dataset):
  """A tensor stream seen as a PyTorch dataset.

  Each dataset item is a tuple of tensors - one per stream - holding the
  data of a single sample.

  Example:
    ds = tensor_stream.Dataset('/data/mystream')
    len(ds)  # The number of samples.
    x0, x1 = ds[0]  # Torch tensors - one per stream.
  """

  def __init__(self, path, transforms=None):
    """Creates a PyTorch dataset backed by a tensor stream.

    Args:
      path: The tensor stream folder path.
      transforms: An optional list - one entry per stream - of functions
        taking a tensor and returning a transformed tensor, applied to the
        data before it is returned by the read operations.
    """
    super().__init__()
    self.reader = Reader(path, transforms=transforms)

  def __len__(self):
    """Returns the number of samples held by the tensor stream."""

    shape = self.reader.shape
    return shape[0][0] if shape else 0

  def __getitem__(self, i):
    """Reads one sample of the tensor stream.

    Args:
      i: The index of the sample to read.

    Returns:
      A tuple of torch tensors - one per stream - holding the sample data.
    """
    return tuple([
        torch.from_numpy(np.array(x, copy=True))
        for x in self.reader.get_slices(i, size=1)
    ])