{"id":13472041,"url":"https://github.com/facebookresearch/DiT","last_synced_at":"2025-03-26T15:31:15.900Z","repository":{"id":64974775,"uuid":"578825599","full_name":"facebookresearch/DiT","owner":"facebookresearch","description":"Official PyTorch Implementation of \"Scalable Diffusion Models with Transformers\"","archived":false,"fork":false,"pushed_at":"2024-05-31T13:04:15.000Z","size":6487,"stargazers_count":6225,"open_issues_count":62,"forks_count":553,"subscribers_count":44,"default_branch":"main","last_synced_at":"2024-10-29T14:57:24.188Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/facebookresearch.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.txt","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2022-12-16T01:00:34.000Z","updated_at":"2024-10-29T14:55:57.000Z","dependencies_parsed_at":"2024-01-16T07:22:09.008Z","dependency_job_id":"8c07156f-3aa5-4418-9ccc-95d193de269e","html_url":"https://github.com/facebookresearch/DiT","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/facebookresearch%2FDiT","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/facebookresearch%2FDiT/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/facebookresearch%2FDiT/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/facebookresearch%2FDiT/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/facebookresearch","download_url":"https://codeload.github.com/facebookresearch/DiT/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":222151628,"owners_count":16939423,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T16:00:51.347Z","updated_at":"2024-10-30T02:31:21.252Z","avatar_url":"https://github.com/facebookresearch.png","language":"Python","funding_links":[],"categories":["Python","Image Generation","其他_机器视觉","Repos"],"sub_categories":["Diffusion Paradigm","网络服务_其他"],"readme":"## Scalable Diffusion Models with Transformers (DiT)\u003cbr\u003e\u003csub\u003eOfficial PyTorch Implementation\u003c/sub\u003e\n\n### [Paper](http://arxiv.org/abs/2212.09748) | [Project Page](https://www.wpeebles.com/DiT) | Run DiT-XL/2 [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/wpeebles/DiT) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](http://colab.research.google.com/github/facebookresearch/DiT/blob/main/run_DiT.ipynb) \u003ca href=\"https://replicate.com/arielreplicate/scalable_diffusion_with_transformers\"\u003e\u003cimg src=\"https://replicate.com/arielreplicate/scalable_diffusion_with_transformers/badge\"\u003e\u003c/a\u003e\n\n![DiT samples](visuals/sample_grid_0.png)\n\nThis repo contains PyTorch model definitions, pre-trained weights and training/sampling code for our paper exploring \ndiffusion models with transformers (DiTs). You can find more visualizations on our [project page](https://www.wpeebles.com/DiT).\n\n\u003e [**Scalable Diffusion Models with Transformers**](https://www.wpeebles.com/DiT)\u003cbr\u003e\n\u003e [William Peebles](https://www.wpeebles.com), [Saining Xie](https://www.sainingxie.com)\n\u003e \u003cbr\u003eUC Berkeley, New York University\u003cbr\u003e\n\nWe train latent diffusion models, replacing the commonly-used U-Net backbone with a transformer that operates on \nlatent patches. We analyze the scalability of our Diffusion Transformers (DiTs) through the lens of forward pass \ncomplexity as measured by Gflops. We find that DiTs with higher Gflops---through increased transformer depth/width or\nincreased number of input tokens---consistently have lower FID. In addition to good scalability properties, our \nDiT-XL/2 models outperform all prior diffusion models on the class-conditional ImageNet 512×512 and 256×256 benchmarks, \nachieving a state-of-the-art FID of 2.27 on the latter.\n\nThis repository contains:\n\n* 🪐 A simple PyTorch [implementation](models.py) of DiT\n* ⚡️ Pre-trained class-conditional DiT models trained on ImageNet (512x512 and 256x256)\n* 💥 A self-contained [Hugging Face Space](https://huggingface.co/spaces/wpeebles/DiT) and [Colab notebook](http://colab.research.google.com/github/facebookresearch/DiT/blob/main/run_DiT.ipynb) for running pre-trained DiT-XL/2 models\n* 🛸 A DiT [training script](train.py) using PyTorch DDP\n\nAn implementation of DiT directly in Hugging Face `diffusers` can also be found [here](https://github.com/huggingface/diffusers/blob/main/docs/source/en/api/pipelines/dit.mdx).\n\n\n## Setup\n\nFirst, download and set up the repo:\n\n```bash\ngit clone https://github.com/facebookresearch/DiT.git\ncd DiT\n```\n\nWe provide an [`environment.yml`](environment.yml) file that can be used to create a Conda environment. If you only want \nto run pre-trained models locally on CPU, you can remove the `cudatoolkit` and `pytorch-cuda` requirements from the file.\n\n```bash\nconda env create -f environment.yml\nconda activate DiT\n```\n\n\n## Sampling [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/wpeebles/DiT) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](http://colab.research.google.com/github/facebookresearch/DiT/blob/main/run_DiT.ipynb)\n![More DiT samples](visuals/sample_grid_1.png)\n\n**Pre-trained DiT checkpoints.** You can sample from our pre-trained DiT models with [`sample.py`](sample.py). Weights for our pre-trained DiT model will be \nautomatically downloaded depending on the model you use. The script has various arguments to switch between the 256x256\nand 512x512 models, adjust sampling steps, change the classifier-free guidance scale, etc. For example, to sample from\nour 512x512 DiT-XL/2 model, you can use:\n\n```bash\npython sample.py --image-size 512 --seed 1\n```\n\nFor convenience, our pre-trained DiT models can be downloaded directly here as well:\n\n| DiT Model     | Image Resolution | FID-50K | Inception Score | Gflops | \n|---------------|------------------|---------|-----------------|--------|\n| [XL/2](https://dl.fbaipublicfiles.com/DiT/models/DiT-XL-2-256x256.pt) | 256x256          | 2.27    | 278.24          | 119    |\n| [XL/2](https://dl.fbaipublicfiles.com/DiT/models/DiT-XL-2-512x512.pt) | 512x512          | 3.04    | 240.82          | 525    |\n\n\n**Custom DiT checkpoints.** If you've trained a new DiT model with [`train.py`](train.py) (see [below](#training-dit)), you can add the `--ckpt`\nargument to use your own checkpoint instead. For example, to sample from the EMA weights of a custom \n256x256 DiT-L/4 model, run:\n\n```bash\npython sample.py --model DiT-L/4 --image-size 256 --ckpt /path/to/model.pt\n```\n\n\n## Training DiT\n\nWe provide a training script for DiT in [`train.py`](train.py). This script can be used to train class-conditional \nDiT models, but it can be easily modified to support other types of conditioning. To launch DiT-XL/2 (256x256) training with `N` GPUs on \none node:\n\n```bash\ntorchrun --nnodes=1 --nproc_per_node=N train.py --model DiT-XL/2 --data-path /path/to/imagenet/train\n```\n\n### PyTorch Training Results\n\nWe've trained DiT-XL/2 and DiT-B/4 models from scratch with the PyTorch training script\nto verify that it reproduces the original JAX results up to several hundred thousand training iterations. Across our experiments, the PyTorch-trained models give \nsimilar (and sometimes slightly better) results compared to the JAX-trained models up to reasonable random variation. Some data points:\n\n| DiT Model  | Train Steps | FID-50K\u003cbr\u003e (JAX Training) | FID-50K\u003cbr\u003e (PyTorch Training) | PyTorch Global Training Seed |\n|------------|-------------|----------------------------|--------------------------------|------------------------------|\n| XL/2       | 400K        | 19.5                       | **18.1**                       | 42                           |\n| B/4        | 400K        | **68.4**                   | 68.9                           | 42                           |\n| B/4        | 400K        | 68.4                       | **68.3**                       | 100                          |\n\nThese models were trained at 256x256 resolution; we used 8x A100s to train XL/2 and 4x A100s to train B/4. Note that FID \nhere is computed with 250 DDPM sampling steps, with the `mse` VAE decoder and without guidance (`cfg-scale=1`). \n\n**TF32 Note (important for A100 users).** When we ran the above tests, TF32 matmuls were disabled per PyTorch's defaults. \nWe've enabled them at the top of `train.py` and `sample.py` because it makes training and sampling way way way faster on \nA100s (and should for other Ampere GPUs too), but note that the use of TF32 may lead to some differences compared to \nthe above results.\n\n### Enhancements\nTraining (and sampling) could likely be sped-up significantly by:\n- [ ] using [Flash Attention](https://github.com/HazyResearch/flash-attention) in the DiT model\n- [ ] using `torch.compile` in PyTorch 2.0\n\nBasic features that would be nice to add:\n- [ ] Monitor FID and other metrics\n- [ ] Generate and save samples from the EMA model periodically\n- [ ] Resume training from a checkpoint\n- [ ] AMP/bfloat16 support\n\n**🔥 Feature Update** Check out this repository at https://github.com/chuanyangjin/fast-DiT to preview a selection of training speed acceleration and memory saving features including gradient checkpointing, mixed precision training and pre-extrated VAE features. With these advancements, we have achieved a training speed of 0.84 steps/sec for DiT-XL/2 using just a single A100 GPU.\n\n## Evaluation (FID, Inception Score, etc.)\n\nWe include a [`sample_ddp.py`](sample_ddp.py) script which samples a large number of images from a DiT model in parallel. This script \ngenerates a folder of samples as well as a `.npz` file which can be directly used with [ADM's TensorFlow\nevaluation suite](https://github.com/openai/guided-diffusion/tree/main/evaluations) to compute FID, Inception Score and\nother metrics. For example, to sample 50K images from our pre-trained DiT-XL/2 model over `N` GPUs, run:\n\n```bash\ntorchrun --nnodes=1 --nproc_per_node=N sample_ddp.py --model DiT-XL/2 --num-fid-samples 50000\n```\n\nThere are several additional options; see [`sample_ddp.py`](sample_ddp.py) for details. \n\n\n## Differences from JAX\n\nOur models were originally trained in JAX on TPUs. The weights in this repo are ported directly from the JAX models. \nThere may be minor differences in results stemming from sampling with different floating point precisions. We re-evaluated \nour ported PyTorch weights at FP32, and they actually perform marginally better than sampling in JAX (2.21 FID \nversus 2.27 in the paper).\n\n\n## BibTeX\n\n```bibtex\n@article{Peebles2022DiT,\n  title={Scalable Diffusion Models with Transformers},\n  author={William Peebles and Saining Xie},\n  year={2022},\n  journal={arXiv preprint arXiv:2212.09748},\n}\n```\n\n\n## Acknowledgments\nWe thank Kaiming He, Ronghang Hu, Alexander Berg, Shoubhik Debnath, Tim Brooks, Ilija Radosavovic and Tete Xiao for helpful discussions. \nWilliam Peebles is supported by the NSF Graduate Research Fellowship.\n\nThis codebase borrows from OpenAI's diffusion repos, most notably [ADM](https://github.com/openai/guided-diffusion).\n\n\n## License\nThe code and model weights are licensed under CC-BY-NC. See [`LICENSE.txt`](LICENSE.txt) for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffacebookresearch%2FDiT","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffacebookresearch%2FDiT","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffacebookresearch%2FDiT/lists"}