页面简介
Learn how to process 2 billion images for Stable Diffusion model training using Ray Data. Build scalable, GPU-accelerated data pipelines for AI and ML workloads.
正文摘录
HomeBlogBlog DetailProcessing 2 Billion Images for Stable Diffusion Model Training - Definitive Guides with Ray SeriesBy Max Pumperla and Marwan Sarieddine | May 14, 2024This guide is the second in a series that will explore the challenges and solutions involved in training Stable Diffusion models at scale. Stable Diffusion models are a class of generative models that have shown promising results in generating high-quality images. However, training these models requires large amounts of data and computational resources, which can be challenging to manage. This guide will focus on the data processing aspect of training Stable Diffusion models, particularly the challenges involved in preparing training data at scale.In this guide, we will learn how to:💻 Develop an end-to-end data processing pipeline for Stable Diffusion model training.🚀 Build scalable data pipelines that you can apply to handle petabyte-scale datasets.💡 Familiarize yourself with Ray, an open-source tool for scalable computing.🔍 Dive deep into optimizing Ray Data for loading and processing large datasets efficiently.LinkOverviewDiffusion models like Stable Diffusion, Sora, and DALL-E excel in generating detailed, high-quality creative outputs. Notably, Stable Diffusion is open-source and crafts images from text descriptions, making it a pivotal tool in AI-driven art and design.Prompt: "Sunrise over a Scottish landscape". Figure 1: Example text-to-image output of a Stable Diffusion model.Sunrise over a Scottish landscapeStable Diffusion's openly available code and algorithms encourage enhancements through training on high-quality datasets. Such training can improve image quality and address commercial usage rights. Yet, building a diffusion model from scratch demands significant computing resources, potentially leading to lengthy and inefficient training periods without robust distributed computing systems.LinkGuide focusOur approach is practical and code-oriented rather than deeply mathematical. We aim to equip you with the intuitive understanding necessary to adapt our code for your projects. The guide specifically focuses on preparing data for the v2-base model of Stable Diffusion.LinkRequirementsYou don't need access to a distributed computing cluster to follow and run the code in this guide, as the same code is compatible on both single machines and clusters, thanks to Ray’s versatility. If you are looking to scale your code, try the reference implementation on the Anyscale platform. What you will get is a VSCode remote session running within a minimally sized cluster.LinkGuide progressionOn a high level, the progression of this guide mimics the following steps needed to prepare training data for a Stable Diffusion model, which we cover in much more detail later on:Download the right dataset: There are various interesting subsets of the so-called LAION dataset that is commonly used in Stable Diffusion training. The data consists of a collection of images and their text descriptions.Transform the data: Both the images and the text from the LAION data need to be processed for the Stable Diffusion training procedure. The first step is to crop and clean the images from the raw dataset and tokenize the text.Encode the data: Then both images and text need to be suitably encoded. We send the images through the encoding step of a variational autoencoder and the tokenized text through the encoding step of a Contrastive Language-Image Pretraining (CLIP) model.Let's download some data next to get started!LinkDownloading LAION datasetsThe Large-scale Artificial Intelligence Open Network (LAION) non-profit organization publishes models and datasets under a public license. LAION is particularly known for having provided the data underlying practically most Stable Diffusion models (see the v2-base model card for more details). The community sometimes colloquially refers to "the LAION dataset", but there are really a lot of datasets available.For this guide, we are primarily interested in the LAION Aesthetic dataset, which is a subset of the larger LAION 5B dataset selected for aesthetic images. It consists of image and text pairs. Here are a couple of examples:Cat images in the LAION Aesthetic datasetFigure 2: Cat images in the LAION Aesthetic dataset - picture taken from the LAION-datasets github repo.NOTE: Access to LAION datasets on HuggingFace has recently been disabled. This is due to an ongoing safety review of LAION 5B. If you would like to skip the download logic, you can move directly to the section titled "Processing Image and Text Data”. However, we recommend that you still go through the download code to get a better understanding of how to do so efficiently. In any case, we'll help you circumvent this temporary issue by providing S3 buckets for raw and processed data, so that you can run all other code in a frictionless manner. LinkDownloading the dataset with Ray DataThere are community-contributed command line tools like img2dataset that can help you download LAION data, too. In fact, it's the tool recommended by the LAION team on GitHub. However, img2dataset can only save files to a local machine. To store files on a remote storage like AWS S3, you will need to run a sync operation. Ray Data provides an efficient way to distribute download workloads across a Ray cluster. It can directly stream data to S3 without going through an intermediary file system; all operations are performed in the memory of the nodes within the cluster.Figure 3: Distributed downloading with img2dataset (shown as image2dataset) vs Ray Data. Distributed downloading with img2dataset vs Ray DataLinkArchitecture OverviewHere's a high-level overview of the download process that we would like to implement:Figure 4: Architecture overview of the download process.Architecture overview of the download processHere is a breakdown of the above processRay Data uses Ray tasks, distributed functions, to read parquet files from hugging face in parallel.Each read_parquet task reads one or more files and produces a stream of one or more output blocks.The output blocks are fed directly to the downstream transform.Ray Data maps the download_images transform to each output blockRay Data finally writes each transformed block to the specified cloud storage in parallel. LinkImplementationLink1. Reading parquet files from hugging faceThe LAION Aesthetic dataset can be acquired from HuggingFace, and can be downloaded as Parquet files. Ray Data has various efficient data loaders, in particular one for Parquet files, called read_parquet.With that in mind, let's define a get_input_dataset helper function that performs the following steps:Request from the Hugging Face Hub API the URLs of the LAION Aesthetics Parquet files.Load the Parquet files into a Ray Dataset using read_parquet. 1def get_parquet_urls(path: str, name: str, split: str) -> list[str]: 2 hf_api_url = f"https://huggingface.co/api/datasets/{path}/parquet" 3 hf_response = requests.get(hf_api_url) 4 hf_response.raise_for_status() 5 parquet_urls = hf_response.json()[name][split] 6 return parquet_urls 7 8def get_input_dataset(path: str, name: str, split: str) -> ray.data.dataset.Dataset: 9 parquet_urls = get_parquet_urls(path, name, split) 10 ds = ray.data.read_parquet(parquet_urls, columns=["URL", "caption"]) 11 return dsNote that Ray Data includes a handy from_huggingface method for loading data from the Hugging Face Hub. However, given that Parquet is a very common format, we chose to demonstrate the read_parquet method instead. This way, you’ll be well-equipped to handle datasets from a variety of sources.What does running the get_input_dataset helper function do?You might be wondering whether running get_input_dataset will initiate the download of the LAION Aesthetic dataset. The answer is no. get_input_dataset calls read_parquet which in turn will only read the metadata of the Parquet files and create a Ray Dataset object that represents the data. Ray Dataset creation and transformation APIs are lazy. This means that execution is only triggered by "sink" APIs, such as consuming or writing the dataset. This is a key feature of Ray Data that allows it to handle large datasets efficiently.A common pattern is to then apply transformations to the Ray Dataset, and finally consume it by writing the data to disk. Under the hood, Ray Data will build an execution plan that optimizes the computation and distributes it across the cluster. Optimizations include operator fusion, which combines multiple operations into a single operation to improve performance and memory stability.Link2. Downloading the image URLs in the parquet filesEach row in the LAION parquet file contains a URL and caption as we specified in get_input_dataset. Given this URL, we can use the requests library to download the corresponding image. We do so by implementing a simple download_image function.1def download_image(url: str) -> bytes: 2 try: 3 response = requests.get(url) 4 response.raise_for_status() 5 return response.content 6 except Exception: 7 return b""We now implement a download_images functionality that takes a batch of Parquet records and concurrently uses threads to call download_image. Some downloads might fail, e.g., due to corrupted files or wrong formatting, so we need to keep only the valid images.1def download_images(batch: dict[str, np.ndarray]) -> dict[str, np.ndarray]: 2 with ThreadPoolExecutor() as executor: 3 batch["image"] = list(executor.map(download_image, batch["URL"])) 4 del batch["URL"] 5 return keep_valid_images(batch)keep_valid_images is a helper function you should implement to run validation checks for your edge cases. For example, we check if the image is non-empty with a non-negligible size and a non-empty text description.Link3. Putting it all together into a convenient image downloading toolWith get_input_dataset and download_images utilities in place, let's write a download script that downloads the LAION Aesthetics dataset in one go