---
title: LitData
description: Stream and process datasets at scale.
canonical: 'https://lightning.ai/docs/litdata'
---
# LitData {#litdata}

**Transform datasets at scale.**

Optimize data for fast AI model training.

Stream and process datasets at scale into your training and
inference jobs. Speed up training by 20x by streaming optimized
datasets directly from cloud storage; parallelize data
processing across many machines; combine, encrypt, and version
datasets without local downloads.

Install: `pip install litdata`

- Parallelize data processing
- Accelerate training 20x
- Multi-machine streaming
- Combine and split datasets
- Run distributed inference

---

**Parallelize data processing**

Walk through resizing a folder of images in parallel with LitData's `map` function.

[Open in Studio](https://lightning.ai/lightning-ai/templates/litdata-parallelize-data-processing)

```python
from PIL import Image
import litdata as ld

# use a local or S3 folder
input_dir = "my_large_images"     # or "s3://my-bucket/my_large_images"
output_dir = "my_resized_images"  # or "s3://my-bucket/my_resized_images"

inputs = [os.path.join(input_dir, f) for f in os.listdir(input_dir)]

# resize the input image
def resize_image(image_path, output_dir):
    output_image_path = os.path.join(output_dir, os.path.basename(image_path))
    Image.open(image_path).resize((224, 224)).save(output_image_path)

ld.map(
    fn=resize_image,
    inputs=inputs,
    output_dir="output_dir",
)
```

- **Imports** (lines 1–2): Pull in PIL and LitData.
- **Define I/O** (lines 4–8): Set the input and output directories and list the input images.
- **The work function** (lines 10–13): Read each image, resize it, and write to the output directory.
- **Run with map** (lines 15–19): Hand the function and input list to `ld.map`. LitData parallelises the work for you.
- **Control workers** (line 19): Add `num_workers=N` to control concurrency on a single machine.

```python
from PIL import Image
import litdata as ld

# use a local or S3 folder
input_dir = "my_large_images"     # or "s3://my-bucket/my_large_images"
output_dir = "my_resized_images"  # or "s3://my-bucket/my_resized_images"

inputs = [os.path.join(input_dir, f) for f in os.listdir(input_dir)]

# resize the input image
def resize_image(image_path, output_dir):
    output_image_path = os.path.join(output_dir, os.path.basename(image_path))
    Image.open(image_path).resize((224, 224)).save(output_image_path)

ld.map(
    fn=resize_image,
    inputs=inputs,
    output_dir="output_dir",
    num_workers=8,
)
```

- **Scale across machines** (lines 2, 20–21): Add `machine` and `num_nodes` to scale across multiple machines.

```python
from PIL import Image
import litdata as ld, Machine

# use a local or S3 folder
input_dir = "my_large_images"     # or "s3://my-bucket/my_large_images"
output_dir = "my_resized_images"  # or "s3://my-bucket/my_resized_images"

inputs = [os.path.join(input_dir, f) for f in os.listdir(input_dir)]

# resize the input image
def resize_image(image_path, output_dir):
    output_image_path = os.path.join(output_dir, os.path.basename(image_path))
    Image.open(image_path).resize((224, 224)).save(output_image_path)

ld.map(
    fn=resize_image,
    inputs=inputs,
    output_dir="output_dir",
    machine=Machine.DATA_PREP,
    num_nodes=4,
)
```


**Accelerate training by 20x**

Walk through optimising a dataset into LitData's chunked binary format and streaming it back from cloud storage with the StreamingDataLoader.

[Open in Studio](https://lightning.ai/lightning-ai/templates/litdata-accelerate-training-by-20x)

```python
import numpy as np
from PIL import Image
import litdata as ld

def random_images(index):
    fake_images = Image.fromarray(np.random.randint(0, 256, (32, 32, 3), dtype=np.uint8))
    fake_labels = np.random.randint(10)
    return {"index": index, "image": fake_images, "class": fake_labels}

if __name__ == "__main__":
    ld.optimize(
        fn=random_images,                       # The function applied to each input
        inputs=list(range(1000)),               # The inputs to the function (here it's a list of numbers)
        output_dir="s3://my-bucket/fast_data",  # Optimized data is stored here
        num_workers=4,                          # The number of workers on the same machine
        chunk_bytes="64MB"                      # Size of each chunk
    )

    train_dataset = ld.StreamingDataset('s3://my-bucket/fast_data', shuffle=True, drop_last=True)
    train_dataloader = ld.StreamingDataLoader(train_dataset)
    for sample in train_dataloader:
        img, cls = sample['image'], sample['class']
```

- **Imports** (lines 1–3): Imports LitData, PIL and numpy for image processing.
- **Function to generate sample data** (lines 4–8): In real world use cases, return your own data samples. Here, we generate fake images and labels.
- **Support any format of data** (lines 8–9): You can simply return any format of data and LitData will handle the rest.
- **Use LitData optimize function to optimize the data in faster data format** (lines 10–17): Optimize converts the data into 64MB chunks and stores them in S3.
- **Use LitData StreamingDataset to load the optimized data from S3** (lines 18–22): The StreamingDataset and StreamingDataLoader will load the optimized data from S3.

**Hugging Face**

Point the StreamingDataset at a Hugging Face URL and iterate the data with no local download.

[Open in Studio](https://lightning.ai/lightning-ai/templates/litdata-hugging-face)

```python
import litdata as ld

hf_uri = "hf://datasets/open-thoughts/OpenThoughts-114k/data"

dataset = ld.StreamingDataset(hf_uri)

for batch in dataset:
    print(f"{batch=}")
```

- **Imports** (line 1): Import LitData.
- **HF dataset URL** (line 3): Pick the parquet dataset you want from huggingface.co/datasets and copy its URL.
- **Wrap with StreamingDataset** (line 5): Hand the URL to StreamingDataset — it streams the data on demand.
- **Iterate** (lines 7–8): Iterate the dataset like any PyTorch dataset.

**Run distributed inference**

Embed the entire English Wikipedia in parallel by running a transformer model with LitData map.

[Open in Studio](https://lightning.ai/lightning-ai/templates/litdata-distributed-inference)

```python
import datasets, torch, os, warnings
from transformers import pipeline
from litdata import map, Machine

wikipedia = datasets.load_dataset("wikipedia", "20220301.en", cache_dir="data", trust_remote_code=True)['train']

class TextEmbedder:
    def __init__(self):
        self.model = None

    def __call__(self, index, output_dir, device):
        if self.model is None:
            self.model = pipeline("feature-extraction", model="BAAI/bge-small-en-v1.5", device=device)

        article = wikipedia[index]
        for block_start in range(0, len(article['text']), 512):
            article_block = article['text'][block_start: block_start + 512]
            embeddings = self.model(article_block)
            torch.save(embeddings, os.path.join(output_dir, f"{index}_{block_start}.pt"))

map(
    fn=TextEmbedder(),
    inputs=list(range(len(wikipedia))),
    output_dir="s3://my-bucket/wikipedia_embeddings",
)
```

- **Imports** (lines 1–3): Pull in datasets, torch, os, warnings, transformers, and LitData.
- **Load the dataset** (line 5): All articles from the English Wikipedia.
- **TextEmbedder class** (lines 7, 11): A lazy embedder — model loaded once per worker, on the GPU device LitData provides.
- **Instantiate on GPU** (lines 11–14): First call inflates the model on the worker's device.
- **Inference loop** (lines 15–19): Block the article, run inference, save the embeddings to the output dir.
- **Apply LitData map** (lines 20–24): LitData runs the embedder over the full dataset in parallel and writes results to the output dir.

---

**Navigation**

- Parent: [Documentation](/docs.md)
- Children:
  - [LitData](/docs/litdata.md)
  - [Install](/docs/litdata/install.md)
  - [Get started](/docs/litdata/quick-start.md)
  - [Features](/docs/litdata/features.md)
  - [Benchmarks](/docs/litdata/benchmarks.md)
  - [Examples](/docs/litdata/examples.md)
