tfrecord

repository·main·Indexed 21 days ago

https://github.com/vahidk/tfrecord

A Python library for reading and writing TFRecord files, supporting uncompressed and gzip-compressed formats. It provides specialized PyTorch IterableDataset implementations, including TFRecordDataset and MultiTFRecordDataset, for integration into deep learning pipelines. The library supports tf.Example and tf.train.SequenceExample records, offering tools for creating index files (*.tfindex) to prevent duplicate records when using multiple workers.

Tokens
2.4K
Snippets
11
Records
11
Agent score
25%

What's inside tfrecord

  1. Configure dataset finiteness and shuffling in PyTorch

    main

    When using MultiTFRecordDataset or TFRecordDataset in PyTorch, you can control the following behaviors:

    • Finiteness: By default, MultiTFRecordDataset is infinite. Set infinite=False to make it finite.
    • Shuffling: Both datasets automatically shuffle data if you provide a shuffle_queue_size argument.
    # Finite dataset
    dataset = MultiTFRecordDataset(..., infinite=False)
    
    # Shuffled dataset
    dataset = TFRecordDataset(..., shuffle_queue_size=1024)
  2. Read SequenceExamples in PyTorch

    main

    When reading SequenceExample records in PyTorch using TFRecordDataset, you must provide both context_description and sequence_description.

    Because sequence features are often variable-length, you should use the transform argument to pad sequences or implement a custom collate_fn in the DataLoader to handle dynamic padding during batch assembly.

    import torch
    import numpy as np
    from tfrecord.torch.dataset import TFRecordDataset
    
    # Example using transform for padding
    PAD_WIDTH = 5
    def pad_sequence_feats(data):
        context, features = data
        for k, v in features.items():
            features[k] = np.pad(v, ((0, PAD_WIDTH - len(v)), (0, 0)), 'constant')
        return (context, features)
    
    context_description = {"length": "int", "label": "int"}
    sequence_description = {"tokens": "int", "seq_labels": "int"}
    
    dataset = TFRecordDataset("/tmp/data.tfrecord",
                              index_path=None,
                              description=context_description,
                              transform=pad_sequence_feats,
                              sequence_description=sequence_description)
    
    loader = torch.utils.data.DataLoader(dataset, batch_size=32)
  3. Transform input data in TFRecord datasets

    main

    You can pass a transform function to TFRecordDataset to perform post-processing (like image decoding or normalization) on features before they are returned. This is useful for converting raw bytes into usable tensors or arrays.

    import tfrecord
    import cv2
    
    def decode_image(features):
        # get BGR image from bytes
        features["image"] = cv2.imdecode(features["image"], -1)
        return features
    
    description = {
        "image": "bytes",
    }
    
    dataset = tfrecord.torch.TFRecordDataset("/tmp/data.tfrecord",
                                             index_path=None,
                                             description=description,
                                             transform=decode_image)
    
    data = next(iter(dataset))
    print(data)
  4. Create index files for TFRecord datasets

    main

    It is highly recommended to create an index file (*.tfindex) for each TFRecord file. Providing an index file is required when using multiple workers to prevent the loader from returning duplicate records.

    To create an index file for a single TFRecord file:

    python3 -m tfrecord.tools.tfrecord2idx <tfrecord path> <index path>

    To create index files for all *.tfrecord files in a directory:

    tfrecord2idx <data dir>
  5. Read tf.train.SequenceExample records in Python

    main

    To read SequenceExample records, use tfrecord.tfrecord_loader and provide both context_description and sequence_description. The loader will yield a tuple of (context_features, sequence_features).

    import tfrecord
    
    context_description = {"length": "int", "label": "int"}
    sequence_description = {"tokens": "int", "seq_labels": "int"}
    loader = tfrecord.tfrecord_loader("/tmp/data.tfrecord", None,
                                      context_description,
                                      sequence_description=sequence_description)
    
    for context, sequence_feats in loader:
        print(context["label"])
        print(sequence_feats["seq_labels"])
  6. Read multiple TFRecord files in PyTorch using MultiTFRecordDataset

    main

    Use MultiTFRecordDataset to sample from multiple TFRecord files based on provided probabilities. This class accepts patterns for both the TFRecord files and their corresponding index files.

    import torch
    from tfrecord.torch.dataset import MultiTFRecordDataset
    
    tfrecord_pattern = "/tmp/{}.tfrecord"
    index_pattern = "/tmp/{}.index"
    splits = {
        "dataset1": 0.8,
        "dataset2": 0.2,
    }
    description = {"image": "byte", "label": "int"}
    
    dataset = MultiTFRecordDataset(tfrecord_pattern, index_pattern, splits, description)
    loader = torch.utils.data.DataLoader(dataset, batch_size=32)
    
    data = next(iter(loader))
    print(data)
  7. Write tf.train.SequenceExample records in Python

    main

    To write SequenceExample records, use tfrecord.TFRecordWriter.write with two dictionaries: the first for context features and the second for sequence features. Sequence features should be provided as lists/sequences.

    import tfrecord
    
    writer = tfrecord.TFRecordWriter("/tmp/data.tfrecord")
    # First dict is context, second dict is sequence
    writer.write({'length': (3, 'int'), 'label': (1, 'int')},
                 {'tokens': ([[0, 0, 1], [0, 1, 0], [1, 0, 0]], 'int'), 'seq_labels': ([0, 1, 1], 'int')})
    writer.close()
  8. Read TFRecord files in PyTorch using TFRecordDataset

    main

    Use TFRecordDataset to create a PyTorch-compatible dataset from a single TFRecord file. You must provide a description dictionary mapping feature names to types (e.g., "byte", "float", "int").

    import torch
    from tfrecord.torch.dataset import TFRecordDataset
    
    tfrecord_path = "/tmp/data.tfrecord"
    index_path = None
    description = {"image": "byte", "label": "float"}
    
    dataset = TFRecordDataset(tfrecord_path, index_path, description)
    loader = torch.utils.data.DataLoader(dataset, batch_size=32)
    
    data = next(iter(loader))
    print(data)
  9. Write tf.Example records in Python

    main

    Use tfrecord.TFRecordWriter to create TFRecord files. When writing, provide a dictionary where values are tuples containing the data and its type (e.g., (value, "type")).

    import tfrecord
    
    writer = tfrecord.TFRecordWriter("/tmp/data.tfrecord")
    writer.write({
        "image": (image_bytes, "byte"),
        "label": (label, "float"),
        "index": (index, "int")
    })
    writer.close()
  10. Read tf.Example records in Python

    main

    Use tfrecord.tfrecord_loader to iterate over records in a TFRecord file. It requires the file path, an optional index path, and a description dictionary.

    import tfrecord
    
    loader = tfrecord.tfrecord_loader("/tmp/data.tfrecord", None, {
        "image": "byte",
        "label": "float",
        "index": "int"
    })
    for record in loader:
        print(record["label"])