Giter Club home page Giter Club logo

Comments (6)

axkoenig avatar axkoenig commented on July 17, 2024 1

Attaching a minimal example of encoding a dataset of strings with FFCV. Please correct me if there is a nicer way to implement this. Note, the data items must be tuples. Also, Loader seems to automatically pad, so no need to pad manually as shown above.

import numpy as np

from ffcv.writer import DatasetWriter
from ffcv.fields import BytesField
from ffcv.loader import Loader

ENC = "utf-8"
DATA_PATH = "data.beton"


def encode(s: str):
    return np.frombuffer(s.encode(ENC), dtype="uint8")


data = [(encode("hello"),), (encode("world!!"),), (encode("how is life"),)]

writer = DatasetWriter(DATA_PATH, {"text": BytesField()})
writer.from_indexed_dataset(data)

loader = Loader(DATA_PATH, batch_size=1)

for item in loader:
    print("raw out\t", item)
    print("decoded\t", item[0].numpy().tobytes().decode(ENC))

Prints

raw out  (tensor([[104, 101, 108, 108, 111,   0,   0,   0,   0,   0,   0]], dtype=torch.uint8),)
decoded  hello
raw out  (tensor([[119, 111, 114, 108, 100,  33,  33,   0,   0,   0,   0]], dtype=torch.uint8),)
decoded  world!!
raw out  (tensor([[104, 111, 119,  32, 105, 115,  32, 108, 105, 102, 101]], dtype=torch.uint8),)
decoded  how is life

from ffcv.

BraSDon avatar BraSDon commented on July 17, 2024 1

@axkoenig I tried to use your script regarding a text dataset. However I seem to non-deterministicly fail decoding. I used the exact same code except for masking the CUDA_VISIBLE_DEVICES, as I have a CUDA device I wish not to use.

The decoding fails at a different point each time I execute it.

Examples:

raw out  (tensor([[104, 101, 108, 108, 111,   0,   0,   0, 113,   0,   0]],
       dtype=torch.uint8),)
decoded  helloq
raw out  (tensor([[119, 111, 114, 108, 100,  33,  33, 216,   7,   0,   0]],
       dtype=torch.uint8),)
Traceback (most recent call last):
  File "test.py", line 27, in <module>
    print("decoded\t", item[0].numpy().tobytes().decode(ENC))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd8 in position 7: invalid continuation byte
raw out  (tensor([[104, 101, 108, 108, 111, 127,   0,   0,  64, 172,  52]],
       dtype=torch.uint8),)
Traceback (most recent call last):
  File "test.py", line 27, in <module>
    print("decoded\t", item[0].numpy().tobytes().decode(ENC))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xac in position 9: invalid start byte

@andrewilyas @GuillaumeLeclerc Are you aware of any changes to the library that could cause the different behavior? Or is it likely to be a setup issue?

from ffcv.

andrewilyas avatar andrewilyas commented on July 17, 2024

Hi @shashankvasisht ! I'm not too familiar with the torchvision COCO dataset, do you think you could print the output of print(tr_dataset_func[0]), and also paste in what args is?

As for strings, here is a minimal example:

import numpy as np
from uuid import uuid4
from ffcv.writer import DatasetWriter
from ffcv.fields import NDArrayField
from ffcv.loader import Loader, OrderOption
from ffcv.fields.decoders import NDArrayDecoder
from tempfile import NamedTemporaryFile

MAX_STRING_SIZE = 100

class CaptionDataset:
    def __init__(self, N):
        self.captions = [str(uuid4())[:np.random.randint(50)] for _ in range(N)]

    def __getitem__(self, idx):
        padded_caption = (self.captions[idx] + (" " * MAX_STRING_SIZE))[:MAX_STRING_SIZE]
        return (np.frombuffer(padded_caption.encode('ascii'), dtype='uint8'),)

    def __len__(self):
        return len(self.captions)

dataset = CaptionDataset(100)

with NamedTemporaryFile() as handle:
    writer = DatasetWriter(handle.name, {
        'label': NDArrayField(np.dtype('uint8'), (MAX_STRING_SIZE,))
    }, num_workers=1)

    writer.from_indexed_dataset(dataset)

    loader = Loader(handle.name,
                batch_size=10,
                num_workers=2,
                order=OrderOption.RANDOM,
                pipelines={
                    'label': [NDArrayDecoder()]
                })

    for x, in loader:
        for cap in x:
            print(cap.tobytes().decode('ascii').strip())

from ffcv.

GuillaumeLeclerc avatar GuillaumeLeclerc commented on July 17, 2024

Hopefully this was helpful to you @shashankvasisht. If you have more questions feel free to reopen. I'll close in the meantime

from ffcv.

axkoenig avatar axkoenig commented on July 17, 2024

This is how to achieve the same with JSONField.

import numpy as np

from ffcv.writer import DatasetWriter
from ffcv.fields import JSONField
from ffcv.loader import Loader

ENC = "utf-8"
DATA_PATH = "data.beton"


def encode(s: str):
    return np.frombuffer(s.encode(ENC), dtype="uint8")


data = [("hello",), ("world",), ("how is life",)]

writer = DatasetWriter(DATA_PATH, {"text": JSONField()})
writer.from_indexed_dataset(data)

loader = Loader(DATA_PATH, batch_size=1)

for item in loader:
    print("raw out\t", item)
    print("decoded\n", JSONField.unpack(item[0])[0])

from ffcv.

JRopes avatar JRopes commented on July 17, 2024

I am also struggling with this original issue and it seems it was not really answered. For some reason I keep getting this "TypeError: Unsupported image type <class 'str'>" error despite me only saving images. Can anybody help me with this?

from ffcv.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.