Skip to content

Conversation

@tchaton
Copy link
Contributor

@tchaton tchaton commented Sep 26, 2023

What does this PR do?

This PR introduces the Cache and CacheDataLoader object to optimise data fetching in the cloud.

Here are the different ways of using the Cache.

For beginners:

import os
import torch
from lightning.data.cache import CacheDataLoader
from lightning.pytorch.demos.boring_classes import RandomDataset

dataset = RandomDataset(64, 64)
dataloader = CacheDataLoader(dataset, cache_dir="./cache", chunk_bytes=2 << 12)
for batch in dataloader:
    # do your thing

print(sorted(os.listdir("./cache"))) # ['0.index.json', 'chunk-0-0.bin', 'chunk-0-1.bin', 'chunk-0-2.bin']. 
# Your dataset is optimised for the cloud

For advanced users:

import os
import numpy as np
import torch
from PIL import Image
from torchvision import transforms as T
from torch.utils.data import Dataset
from lightning import seed_everything
from lightning.data.cache import Cache, CacheDataLoader
from lightning.fabric import Fabric

class BoringImageDataset(Dataset):

    def __init__(self, cache, size=100, num_classes=10):
        self.cache = Cache("./cache", chunk_size=2 << 12)
        if not self.cache.filled:
            self.data = create_random_images(size, num_classes)
        self.transform = T.Compose([T.ToTensor()])

    def __len__(self):
        return len(self.cache) if self.cache.filled else len(self.data)

    def __getitem__(self, index):
        data = self.cache[index] if self.cache.filled else self.data[index]
        if not self.cache.filled: self.cache[index] = data
        data["image"] = self.transform(data["image"]).unsqueeze(0)
        data["class"] = torch.tensor([data["class"]])
        return data

def main(fabric):
    seed_everything(42)

    dataset = BoringImageDataset()
    dataloader = CacheDataLoader(dataset, num_workers=34, batch_size=4)

    model = fabric.setup(model)

    dataloader = fabric.setup_dataloader(dataloader) # to be added soon, but not needed as the CacheDataLoader handles distribution
    
    ...

    for epoch in range(10):
        for batch in dataloader:
            loss = model(batch)
            ...

if __name__ == "__main__":
    Fabric.launch(main, accelerator="auto", devices=2, strategy="ddp_spawn")

In the follow-ups PRs, I will investigate the followings:

  • Add more tests for the samplers, CacheDataLoader, etc...
  • Start benchmarking and optimising the Cache.
  • Add support for the IterableDataset
  • Add support for the LightningIterable
  • Optimise the index for very large dataset by dropping the offsets and mapping.
  • Add support for NLP (tensors) datasets
  • Add resumability
  • Prepare the MLPerf Dataset
  • Explore FFCV integration
  • ...

Fixes #<issue_number>

Before submitting
  • Was this discussed/agreed via a GitHub issue? (not for typos and docs)
  • Did you read the contributor guideline, Pull Request section?
  • Did you make sure your PR does only one thing, instead of bundling different changes together?
  • Did you make sure to update the documentation with your changes? (if necessary)
  • Did you write any new necessary tests? (not for typos and docs)
  • Did you verify new and existing tests pass locally with your changes?
  • Did you list all the breaking changes introduced by this pull request?
  • Did you update the CHANGELOG? (not for typos, docs, test updates, or minor internal changes/refactors)

PR review

Anyone in the community is welcome to review the PR.
Before you start reviewing, make sure you have read the review guidelines. In short, see the following bullet-list:

Reviewer checklist
  • Is this pull request ready for review? (if not, please submit in draft mode)
  • Check that all items from Before submitting are resolved
  • Make sure the title is self-explanatory and the description concisely explains the PR
  • Add labels and milestones (and optionally projects) to the PR so it can be classified

📚 Documentation preview 📚: https://pytorch-lightning--18642.org.readthedocs.build/en/18642/

cc @Borda

tchaton and others added 29 commits September 26, 2023 16:11
@tchaton tchaton changed the title Introduce Cache Introduce Cache 1/n Sep 28, 2023
@tchaton tchaton marked this pull request as ready for review October 6, 2023 16:36
@codecov
Copy link

codecov bot commented Oct 6, 2023

Codecov Report

Merging #18642 (0e5342c) into master (fdae213) will decrease coverage by 20%.
The diff coverage is 81%.

Additional details and impacted files
@@            Coverage Diff            @@
##           master   #18642     +/-   ##
=========================================
- Coverage      83%      64%    -20%     
=========================================
  Files         428      435      +7     
  Lines       33484    34530   +1046     
=========================================
- Hits        27904    21974   -5930     
- Misses       5580    12556   +6976     

Copy link
Member

@justusschock justusschock left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm, just some minor comments

@mergify mergify bot added the ready PRs ready to be merged label Oct 9, 2023
@Lightning-AI Lightning-AI deleted a comment from justusschock Oct 9, 2023
@tchaton tchaton requested a review from carmocca as a code owner October 9, 2023 11:37
@github-actions github-actions bot added the ci Continuous Integration label Oct 9, 2023
@github-actions github-actions bot added the dependencies Pull requests that update a dependency file label Oct 9, 2023
@github-actions github-actions bot removed the package label Oct 9, 2023
@tchaton tchaton merged commit 1d5851f into master Oct 9, 2023
@tchaton tchaton deleted the introduce_cache branch October 9, 2023 15:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continuous Integration dependencies Pull requests that update a dependency file ready PRs ready to be merged

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants