source
stringclasses 273
values | url
stringlengths 47
172
| file_type
stringclasses 1
value | chunk
stringlengths 1
512
| chunk_id
stringlengths 5
9
|
---|---|---|---|---|
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#qualitative-evaluation | .md | # prompts = load_dataset("nateraw/parti-prompts", split="train")
# prompts = prompts.shuffle()
# sample_prompts = [prompts[i]["Prompt"] for i in range(5)] | 42_3_5 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#qualitative-evaluation | .md | # Fixing these sample prompts in the interest of reproducibility.
sample_prompts = [
"a corgi",
"a hot air balloon with a yin-yang symbol, with the moon visible in the daytime sky",
"a car with no windows",
"a cube made of porcupine",
'The saying "BE EXCELLENT TO EACH OTHER" written on a red brick wall with a graffiti image of a green alien wearing a tuxedo. A yellow fire hydrant is on a sidewalk in the foreground.',
]
``` | 42_3_6 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#qualitative-evaluation | .md | ]
```
Now we can use these prompts to generate some images using Stable Diffusion ([v1-4 checkpoint](https://huggingface.co/CompVis/stable-diffusion-v1-4)):
```python
import torch | 42_3_7 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#qualitative-evaluation | .md | seed = 0
generator = torch.manual_seed(seed) | 42_3_8 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#qualitative-evaluation | .md | images = sd_pipeline(sample_prompts, num_images_per_prompt=1, generator=generator).images
```

We can also set `num_images_per_prompt` accordingly to compare different images for the same prompt. Running the same pipeline but with a different checkpoint ([v1-5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)), yields: | 42_3_9 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#qualitative-evaluation | .md | 
Once several images are generated from all the prompts using multiple models (under evaluation), these results are presented to human evaluators for scoring. For
more details on the DrawBench and PartiPrompts benchmarks, refer to their respective papers.
<Tip>
It is useful to look at some inference samples while a model is training to measure the | 42_3_10 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#qualitative-evaluation | .md | <Tip>
It is useful to look at some inference samples while a model is training to measure the
training progress. In our [training scripts](https://github.com/huggingface/diffusers/tree/main/examples/), we support this utility with additional support for
logging to TensorBoard and Weights & Biases.
</Tip> | 42_3_11 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#quantitative-evaluation | .md | In this section, we will walk you through how to evaluate three different diffusion pipelines using:
- CLIP score
- CLIP directional similarity
- FID | 42_4_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#text-guided-image-generation | .md | [CLIP score](https://arxiv.org/abs/2104.08718) measures the compatibility of image-caption pairs. Higher CLIP scores imply higher compatibility 🔼. The CLIP score is a quantitative measurement of the qualitative concept "compatibility". Image-caption pair compatibility can also be thought of as the semantic similarity between the image and the caption. CLIP score was found to have high correlation with human judgement.
Let's first load a [`StableDiffusionPipeline`]:
```python | 42_5_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#text-guided-image-generation | .md | Let's first load a [`StableDiffusionPipeline`]:
```python
from diffusers import StableDiffusionPipeline
import torch | 42_5_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#text-guided-image-generation | .md | model_ckpt = "CompVis/stable-diffusion-v1-4"
sd_pipeline = StableDiffusionPipeline.from_pretrained(model_ckpt, torch_dtype=torch.float16).to("cuda")
```
Generate some images with multiple prompts:
```python
prompts = [
"a photo of an astronaut riding a horse on mars",
"A high tech solarpunk utopia in the Amazon rainforest",
"A pikachu fine dining with a view to the Eiffel Tower",
"A mecha robot in a favela in expressionist style",
"an insect robot preparing a delicious meal", | 42_5_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#text-guided-image-generation | .md | "A mecha robot in a favela in expressionist style",
"an insect robot preparing a delicious meal",
"A small cabin on top of a snowy mountain in the style of Disney, artstation",
] | 42_5_3 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#text-guided-image-generation | .md | images = sd_pipeline(prompts, num_images_per_prompt=1, output_type="np").images
print(images.shape)
# (6, 512, 512, 3)
```
And then, we calculate the CLIP score.
```python
from torchmetrics.functional.multimodal import clip_score
from functools import partial
clip_score_fn = partial(clip_score, model_name_or_path="openai/clip-vit-base-patch16") | 42_5_4 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#text-guided-image-generation | .md | clip_score_fn = partial(clip_score, model_name_or_path="openai/clip-vit-base-patch16")
def calculate_clip_score(images, prompts):
images_int = (images * 255).astype("uint8")
clip_score = clip_score_fn(torch.from_numpy(images_int).permute(0, 3, 1, 2), prompts).detach()
return round(float(clip_score), 4) | 42_5_5 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#text-guided-image-generation | .md | sd_clip_score = calculate_clip_score(images, prompts)
print(f"CLIP score: {sd_clip_score}")
# CLIP score: 35.7038
```
In the above example, we generated one image per prompt. If we generated multiple images per prompt, we would have to take the average score from the generated images per prompt.
Now, if we wanted to compare two checkpoints compatible with the [`StableDiffusionPipeline`] we should pass a generator while calling the pipeline. First, we generate images with a | 42_5_6 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#text-guided-image-generation | .md | fixed seed with the [v1-4 Stable Diffusion checkpoint](https://huggingface.co/CompVis/stable-diffusion-v1-4):
```python
seed = 0
generator = torch.manual_seed(seed) | 42_5_7 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#text-guided-image-generation | .md | images = sd_pipeline(prompts, num_images_per_prompt=1, generator=generator, output_type="np").images
```
Then we load the [v1-5 checkpoint](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) to generate images:
```python
model_ckpt_1_5 = "stable-diffusion-v1-5/stable-diffusion-v1-5"
sd_pipeline_1_5 = StableDiffusionPipeline.from_pretrained(model_ckpt_1_5, torch_dtype=torch.float16).to("cuda") | 42_5_8 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#text-guided-image-generation | .md | images_1_5 = sd_pipeline_1_5(prompts, num_images_per_prompt=1, generator=generator, output_type="np").images
```
And finally, we compare their CLIP scores:
```python
sd_clip_score_1_4 = calculate_clip_score(images, prompts)
print(f"CLIP Score with v-1-4: {sd_clip_score_1_4}")
# CLIP Score with v-1-4: 34.9102 | 42_5_9 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#text-guided-image-generation | .md | sd_clip_score_1_5 = calculate_clip_score(images_1_5, prompts)
print(f"CLIP Score with v-1-5: {sd_clip_score_1_5}")
# CLIP Score with v-1-5: 36.2137
```
It seems like the [v1-5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) checkpoint performs better than its predecessor. Note, however, that the number of prompts we used to compute the CLIP scores is quite low. For a more practical evaluation, this number should be way higher, and the prompts should be diverse. | 42_5_10 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#text-guided-image-generation | .md | <Tip warning={true}>
By construction, there are some limitations in this score. The captions in the training dataset
were crawled from the web and extracted from `alt` and similar tags associated an image on the internet.
They are not necessarily representative of what a human being would use to describe an image. Hence we
had to "engineer" some prompts here.
</Tip> | 42_5_11 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | In this case, we condition the generation pipeline with an input image as well as a text prompt. Let's take the [`StableDiffusionInstructPix2PixPipeline`], as an example. It takes an edit instruction as an input prompt and an input image to be edited.
Here is one example:
 | 42_6_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | One strategy to evaluate such a model is to measure the consistency of the change between the two images (in [CLIP](https://huggingface.co/docs/transformers/model_doc/clip) space) with the change between the two image captions (as shown in [CLIP-Guided Domain Adaptation of Image Generators](https://arxiv.org/abs/2108.00946)). This is referred to as the "**CLIP directional similarity**".
- Caption 1 corresponds to the input image (image 1) that is to be edited. | 42_6_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | - Caption 1 corresponds to the input image (image 1) that is to be edited.
- Caption 2 corresponds to the edited image (image 2). It should reflect the edit instruction.
Following is a pictorial overview:

We have prepared a mini dataset to implement this metric. Let's first load the dataset.
```python
from datasets import load_dataset | 42_6_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | dataset = load_dataset("sayakpaul/instructpix2pix-demo", split="train")
dataset.features
```
```bash
{'input': Value(dtype='string', id=None),
'edit': Value(dtype='string', id=None),
'output': Value(dtype='string', id=None),
'image': Image(decode=True, id=None)}
```
Here we have:
- `input` is a caption corresponding to the `image`.
- `edit` denotes the edit instruction.
- `output` denotes the modified caption reflecting the `edit` instruction.
Let's take a look at a sample.
```python
idx = 0 | 42_6_3 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | - `output` denotes the modified caption reflecting the `edit` instruction.
Let's take a look at a sample.
```python
idx = 0
print(f"Original caption: {dataset[idx]['input']}")
print(f"Edit instruction: {dataset[idx]['edit']}")
print(f"Modified caption: {dataset[idx]['output']}")
```
```bash | 42_6_4 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | print(f"Edit instruction: {dataset[idx]['edit']}")
print(f"Modified caption: {dataset[idx]['output']}")
```
```bash
Original caption: 2. FAROE ISLANDS: An archipelago of 18 mountainous isles in the North Atlantic Ocean between Norway and Iceland, the Faroe Islands has 'everything you could hope for', according to Big 7 Travel. It boasts 'crystal clear waterfalls, rocky cliffs that seem to jut out of nowhere and velvety green hills'
Edit instruction: make the isles all white marble | 42_6_5 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | Edit instruction: make the isles all white marble
Modified caption: 2. WHITE MARBLE ISLANDS: An archipelago of 18 mountainous white marble isles in the North Atlantic Ocean between Norway and Iceland, the White Marble Islands has 'everything you could hope for', according to Big 7 Travel. It boasts 'crystal clear waterfalls, rocky cliffs that seem to jut out of nowhere and velvety green hills'
```
And here is the image:
```python
dataset[idx]["image"]
``` | 42_6_6 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | ```
And here is the image:
```python
dataset[idx]["image"]
```

We will first edit the images of our dataset with the edit instruction and compute the directional similarity.
Let's first load the [`StableDiffusionInstructPix2PixPipeline`]:
```python
from diffusers import StableDiffusionInstructPix2PixPipeline | 42_6_7 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | instruct_pix2pix_pipeline = StableDiffusionInstructPix2PixPipeline.from_pretrained(
"timbrooks/instruct-pix2pix", torch_dtype=torch.float16
).to("cuda")
```
Now, we perform the edits:
```python
import numpy as np
def edit_image(input_image, instruction):
image = instruct_pix2pix_pipeline(
instruction,
image=input_image,
output_type="np",
generator=generator,
).images[0]
return image
input_images = []
original_captions = []
modified_captions = []
edited_images = [] | 42_6_8 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | input_images = []
original_captions = []
modified_captions = []
edited_images = []
for idx in range(len(dataset)):
input_image = dataset[idx]["image"]
edit_instruction = dataset[idx]["edit"]
edited_image = edit_image(input_image, edit_instruction) | 42_6_9 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | input_images.append(np.array(input_image))
original_captions.append(dataset[idx]["input"])
modified_captions.append(dataset[idx]["output"])
edited_images.append(edited_image)
```
To measure the directional similarity, we first load CLIP's image and text encoders:
```python
from transformers import (
CLIPTokenizer,
CLIPTextModelWithProjection,
CLIPVisionModelWithProjection,
CLIPImageProcessor,
) | 42_6_10 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | clip_id = "openai/clip-vit-large-patch14"
tokenizer = CLIPTokenizer.from_pretrained(clip_id)
text_encoder = CLIPTextModelWithProjection.from_pretrained(clip_id).to("cuda")
image_processor = CLIPImageProcessor.from_pretrained(clip_id)
image_encoder = CLIPVisionModelWithProjection.from_pretrained(clip_id).to("cuda")
``` | 42_6_11 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | image_encoder = CLIPVisionModelWithProjection.from_pretrained(clip_id).to("cuda")
```
Notice that we are using a particular CLIP checkpoint, i.e.,`openai/clip-vit-large-patch14`. This is because the Stable Diffusion pre-training was performed with this CLIP variant. For more details, refer to the[documentation](https://huggingface.co/docs/transformers/model_doc/clip).
Next, we prepare a PyTorch`nn.Module`to compute directional similarity:
```python
import torch.nn as nn | 42_6_12 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | Next, we prepare a PyTorch`nn.Module`to compute directional similarity:
```python
import torch.nn as nn
import torch.nn.functional as F | 42_6_13 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | class DirectionalSimilarity(nn.Module):
def __init__(self, tokenizer, text_encoder, image_processor, image_encoder):
super().__init__()
self.tokenizer = tokenizer
self.text_encoder = text_encoder
self.image_processor = image_processor
self.image_encoder = image_encoder
def preprocess_image(self, image):
image = self.image_processor(image, return_tensors="pt")["pixel_values"]
return {"pixel_values": image.to("cuda")} | 42_6_14 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | def tokenize_text(self, text):
inputs = self.tokenizer(
text,
max_length=self.tokenizer.model_max_length,
padding="max_length",
truncation=True,
return_tensors="pt",
)
return {"input_ids": inputs.input_ids.to("cuda")}
def encode_image(self, image):
preprocessed_image = self.preprocess_image(image)
image_features = self.image_encoder(**preprocessed_image).image_embeds
image_features = image_features / image_features.norm(dim=1, keepdim=True)
return image_features | 42_6_15 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | def encode_text(self, text):
tokenized_text = self.tokenize_text(text)
text_features = self.text_encoder(**tokenized_text).text_embeds
text_features = text_features / text_features.norm(dim=1, keepdim=True)
return text_features
def compute_directional_similarity(self, img_feat_one, img_feat_two, text_feat_one, text_feat_two):
sim_direction = F.cosine_similarity(img_feat_two - img_feat_one, text_feat_two - text_feat_one)
return sim_direction | 42_6_16 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | def forward(self, image_one, image_two, caption_one, caption_two):
img_feat_one = self.encode_image(image_one)
img_feat_two = self.encode_image(image_two)
text_feat_one = self.encode_text(caption_one)
text_feat_two = self.encode_text(caption_two)
directional_similarity = self.compute_directional_similarity(
img_feat_one, img_feat_two, text_feat_one, text_feat_two
)
return directional_similarity
```
Let's put`DirectionalSimilarity`to use now.
```python | 42_6_17 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | )
return directional_similarity
```
Let's put`DirectionalSimilarity`to use now.
```python
dir_similarity = DirectionalSimilarity(tokenizer, text_encoder, image_processor, image_encoder)
scores = [] | 42_6_18 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | for i in range(len(input_images)):
original_image = input_images[i]
original_caption = original_captions[i]
edited_image = edited_images[i]
modified_caption = modified_captions[i]
similarity_score = dir_similarity(original_image, edited_image, original_caption, modified_caption)
scores.append(float(similarity_score.detach().cpu())) | 42_6_19 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | print(f"CLIP directional similarity: {np.mean(scores)}")
# CLIP directional similarity: 0.0797976553440094
```
Like the CLIP Score, the higher the CLIP directional similarity, the better it is. | 42_6_20 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | ```
Like the CLIP Score, the higher the CLIP directional similarity, the better it is.
It should be noted that the`StableDiffusionInstructPix2PixPipeline`exposes two arguments, namely,`image_guidance_scale`and`guidance_scale`that let you control the quality of the final edited image. We encourage you to experiment with these two arguments and see the impact of that on the directional similarity. | 42_6_21 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | We can extend the idea of this metric to measure how similar the original image and edited version are. To do that, we can just do`F.cosine_similarity(img_feat_two, img_feat_one)`. For these kinds of edits, we would still want the primary semantics of the images to be preserved as much as possible, i.e., a high similarity score. | 42_6_22 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | We can use these metrics for similar pipelines such as the [`StableDiffusionPix2PixZeroPipeline`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix_zero#diffusers.StableDiffusionPix2PixZeroPipeline).
<Tip>
Both CLIP score and CLIP direction similarity rely on the CLIP model, which can make the evaluations biased.
</Tip> | 42_6_23 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | ***Extending metrics like IS, FID (discussed later), or KID can be difficult*** when the model under evaluation was pre-trained on a large image-captioning dataset (such as the [LAION-5B dataset](https://laion.ai/blog/laion-5b/)). This is because underlying these metrics is an InceptionNet (pre-trained on the ImageNet-1k dataset) used for extracting intermediate image features. The pre-training dataset of Stable Diffusion may have limited overlap with the pre-training dataset of InceptionNet, so it is not | 42_6_24 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | pre-training dataset of Stable Diffusion may have limited overlap with the pre-training dataset of InceptionNet, so it is not a good candidate here for feature extraction. | 42_6_25 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#image-conditioned-text-to-image-generation | .md | ***Using the above metrics helps evaluate models that are class-conditioned. For example, [DiT](https://huggingface.co/docs/diffusers/main/en/api/pipelines/dit). It was pre-trained being conditioned on the ImageNet-1k classes.*** | 42_6_26 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#class-conditioned-image-generation | .md | Class-conditioned generative models are usually pre-trained on a class-labeled dataset such as [ImageNet-1k](https://huggingface.co/datasets/imagenet-1k). Popular metrics for evaluating these models include Fréchet Inception Distance (FID), Kernel Inception Distance (KID), and Inception Score (IS). In this document, we focus on FID ([Heusel et al.](https://arxiv.org/abs/1706.08500)). We show how to compute it with the [`DiTPipeline`](https://huggingface.co/docs/diffusers/api/pipelines/dit), which uses the | 42_7_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#class-conditioned-image-generation | .md | We show how to compute it with the [`DiTPipeline`](https://huggingface.co/docs/diffusers/api/pipelines/dit), which uses the [DiT model](https://arxiv.org/abs/2212.09748) under the hood. | 42_7_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#class-conditioned-image-generation | .md | FID aims to measure how similar are two datasets of images. As per [this resource](https://mmgeneration.readthedocs.io/en/latest/quick_run.html#fid): | 42_7_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#class-conditioned-image-generation | .md | > Fréchet Inception Distance is a measure of similarity between two datasets of images. It was shown to correlate well with the human judgment of visual quality and is most often used to evaluate the quality of samples of Generative Adversarial Networks. FID is calculated by computing the Fréchet distance between two Gaussians fitted to feature representations of the Inception network. | 42_7_3 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#class-conditioned-image-generation | .md | These two datasets are essentially the dataset of real images and the dataset of fake images (generated images in our case). FID is usually calculated with two large datasets. However, for this document, we will work with two mini datasets.
Let's first download a few images from the ImageNet-1k training set:
```python
from zipfile import ZipFile
import requests | 42_7_4 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#class-conditioned-image-generation | .md | def download(url, local_filepath):
r = requests.get(url)
with open(local_filepath, "wb") as f:
f.write(r.content)
return local_filepath
dummy_dataset_url = "https://hf.co/datasets/sayakpaul/sample-datasets/resolve/main/sample-imagenet-images.zip"
local_filepath = download(dummy_dataset_url, dummy_dataset_url.split("/")[-1])
with ZipFile(local_filepath, "r") as zipper:
zipper.extractall(".")
```
```python
from PIL import Image
import os
import numpy as np | 42_7_5 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#class-conditioned-image-generation | .md | dataset_path = "sample-imagenet-images"
image_paths = sorted([os.path.join(dataset_path, x) for x in os.listdir(dataset_path)]) | 42_7_6 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#class-conditioned-image-generation | .md | real_images = [np.array(Image.open(path).convert("RGB")) for path in image_paths]
```
These are 10 images from the following ImageNet-1k classes: "cassette_player", "chain_saw" (x2), "church", "gas_pump" (x3), "parachute" (x2), and "tench".
<p align="center">
<img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/real-images.png" alt="real-images"><br>
<em>Real images.</em>
</p> | 42_7_7 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#class-conditioned-image-generation | .md | <em>Real images.</em>
</p>
Now that the images are loaded, let's apply some lightweight pre-processing on them to use them for FID calculation.
```python
from torchvision.transforms import functional as F
import torch | 42_7_8 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#class-conditioned-image-generation | .md | def preprocess_image(image):
image = torch.tensor(image).unsqueeze(0)
image = image.permute(0, 3, 1, 2) / 255.0
return F.center_crop(image, (256, 256)) | 42_7_9 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#class-conditioned-image-generation | .md | real_images = torch.cat([preprocess_image(image) for image in real_images])
print(real_images.shape)
# torch.Size([10, 3, 256, 256])
```
We now load the[`DiTPipeline`](https://huggingface.co/docs/diffusers/api/pipelines/dit) to generate images conditioned on the above-mentioned classes.
```python
from diffusers import DiTPipeline, DPMSolverMultistepScheduler | 42_7_10 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#class-conditioned-image-generation | .md | dit_pipeline = DiTPipeline.from_pretrained("facebook/DiT-XL-2-256", torch_dtype=torch.float16)
dit_pipeline.scheduler = DPMSolverMultistepScheduler.from_config(dit_pipeline.scheduler.config)
dit_pipeline = dit_pipeline.to("cuda")
seed = 0
generator = torch.manual_seed(seed)
words = [
"cassette player",
"chainsaw",
"chainsaw",
"church",
"gas pump",
"gas pump",
"gas pump",
"parachute",
"parachute",
"tench",
] | 42_7_11 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#class-conditioned-image-generation | .md | class_ids = dit_pipeline.get_label_ids(words)
output = dit_pipeline(class_labels=class_ids, generator=generator, output_type="np")
fake_images = output.images
fake_images = torch.tensor(fake_images)
fake_images = fake_images.permute(0, 3, 1, 2)
print(fake_images.shape)
# torch.Size([10, 3, 256, 256])
```
Now, we can compute the FID using[`torchmetrics`](https://torchmetrics.readthedocs.io/).
```python
from torchmetrics.image.fid import FrechetInceptionDistance | 42_7_12 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#class-conditioned-image-generation | .md | fid = FrechetInceptionDistance(normalize=True)
fid.update(real_images, real=True)
fid.update(fake_images, real=False) | 42_7_13 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#class-conditioned-image-generation | .md | print(f"FID: {float(fid.compute())}")
# FID: 177.7147216796875
```
The lower the FID, the better it is. Several things can influence FID here:
- Number of images (both real and fake)
- Randomness induced in the diffusion process
- Number of inference steps in the diffusion process
- The scheduler being used in the diffusion process
For the last two points, it is, therefore, a good practice to run the evaluation across different seeds and inference steps, and then report an average result. | 42_7_14 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#class-conditioned-image-generation | .md | <Tip warning={true}>
FID results tend to be fragile as they depend on a lot of factors:
* The specific Inception model used during computation.
* The implementation accuracy of the computation.
* The image format (not the same if we start from PNGs vs JPGs).
Keeping that in mind, FID is often most useful when comparing similar runs, but it is
hard to reproduce paper results unless the authors carefully disclose the FID
measurement code. | 42_7_15 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/conceptual/evaluation.md | https://huggingface.co/docs/diffusers/en/conceptual/evaluation/#class-conditioned-image-generation | .md | hard to reproduce paper results unless the authors carefully disclose the FID
measurement code.
These points apply to other related metrics too, such as KID and IS.
</Tip>
As a final step, let's visually inspect the`fake_images`.
<p align="center">
<img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/fake-images.png" alt="fake-images"><br>
<em>Fake images.</em>
</p> | 42_7_16 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/ | .md | <!--Copyright 2024 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | 43_0_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/ | .md | an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
--> | 43_0_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | [bitsandbytes](https://huggingface.co/docs/bitsandbytes/index) is the easiest option for quantizing a model to 8 and 4-bit. 8-bit quantization multiplies outliers in fp16 with non-outliers in int8, converts the non-outlier values back to fp16, and then adds them together to return the weights in fp16. This reduces the degradative effect outlier values have on a model's performance. | 43_1_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | 4-bit quantization compresses a model even further, and it is commonly used with [QLoRA](https://hf.co/papers/2305.14314) to finetune quantized LLMs.
This guide demonstrates how quantization can enable running
[FLUX.1-dev](https://huggingface.co/black-forest-labs/FLUX.1-dev)
on less than 16GB of VRAM and even on a free Google
Colab instance.
 | 43_1_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | To use bitsandbytes, make sure you have the following libraries installed:
```bash
pip install diffusers transformers accelerate bitsandbytes -U
```
Now you can quantize a model by passing a [`BitsAndBytesConfig`] to [`~ModelMixin.from_pretrained`]. This works for any model in any modality, as long as it supports loading with [Accelerate](https://hf.co/docs/accelerate/index) and contains `torch.nn.Linear` layers.
<hfoptions id="bnb">
<hfoption id="8-bit"> | 43_1_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | <hfoptions id="bnb">
<hfoption id="8-bit">
Quantizing a model in 8-bit halves the memory-usage:
bitsandbytes is supported in both Transformers and Diffusers, so you can quantize both the
[`FluxTransformer2DModel`] and [`~transformers.T5EncoderModel`].
For Ada and higher-series GPUs. we recommend changing `torch_dtype` to `torch.bfloat16`.
> [!TIP] | 43_1_3 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | For Ada and higher-series GPUs. we recommend changing `torch_dtype` to `torch.bfloat16`.
> [!TIP]
> The [`CLIPTextModel`] and [`AutoencoderKL`] aren't quantized because they're already small in size and because [`AutoencoderKL`] only has a few `torch.nn.Linear` layers.
```py
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig
from transformers import BitsAndBytesConfig as TransformersBitsAndBytesConfig | 43_1_4 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | from diffusers import FluxTransformer2DModel
from transformers import T5EncoderModel
quant_config = TransformersBitsAndBytesConfig(load_in_8bit=True,)
text_encoder_2_8bit = T5EncoderModel.from_pretrained(
"black-forest-labs/FLUX.1-dev",
subfolder="text_encoder_2",
quantization_config=quant_config,
torch_dtype=torch.float16,
)
quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True,) | 43_1_5 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | transformer_8bit = FluxTransformer2DModel.from_pretrained(
"black-forest-labs/FLUX.1-dev",
subfolder="transformer",
quantization_config=quant_config,
torch_dtype=torch.float16,
)
```
By default, all the other modules such as `torch.nn.LayerNorm` are converted to `torch.float16`. You can change the data type of these modules with the `torch_dtype` parameter.
```diff
transformer_8bit = FluxTransformer2DModel.from_pretrained(
"black-forest-labs/FLUX.1-dev",
subfolder="transformer", | 43_1_6 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | ```diff
transformer_8bit = FluxTransformer2DModel.from_pretrained(
"black-forest-labs/FLUX.1-dev",
subfolder="transformer",
quantization_config=quant_config,
+ torch_dtype=torch.float32,
)
```
Let's generate an image using our quantized models.
Setting `device_map="auto"` automatically fills all available space on the GPU(s) first, then the
CPU, and finally, the hard drive (the absolute slowest option) if there is still not enough memory.
```py
pipe = FluxPipeline.from_pretrained( | 43_1_7 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | ```py
pipe = FluxPipeline.from_pretrained(
"black-forest-labs/FLUX.1-dev",
transformer=transformer_8bit,
text_encoder_2=text_encoder_2_8bit,
torch_dtype=torch.float16,
device_map="auto",
) | 43_1_8 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | pipe_kwargs = {
"prompt": "A cat holding a sign that says hello world",
"height": 1024,
"width": 1024,
"guidance_scale": 3.5,
"num_inference_steps": 50,
"max_sequence_length": 512,
} | 43_1_9 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | image = pipe(**pipe_kwargs, generator=torch.manual_seed(0),).images[0]
```
<div class="flex justify-center">
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/quant-bnb/8bit.png"/>
</div>
When there is enough memory, you can also directly move the pipeline to the GPU with `.to("cuda")` and apply [`~DiffusionPipeline.enable_model_cpu_offload`] to optimize GPU memory usage. | 43_1_10 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | Once a model is quantized, you can push the model to the Hub with the [`~ModelMixin.push_to_hub`] method. The quantization `config.json` file is pushed first, followed by the quantized model weights. You can also save the serialized 8-bit models locally with [`~ModelMixin.save_pretrained`].
</hfoption>
<hfoption id="4-bit">
Quantizing a model in 4-bit reduces your memory-usage by 4x:
bitsandbytes is supported in both Transformers and Diffusers, so you can can quantize both the | 43_1_11 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | bitsandbytes is supported in both Transformers and Diffusers, so you can can quantize both the
[`FluxTransformer2DModel`] and [`~transformers.T5EncoderModel`].
For Ada and higher-series GPUs. we recommend changing `torch_dtype` to `torch.bfloat16`.
> [!TIP]
> The [`CLIPTextModel`] and [`AutoencoderKL`] aren't quantized because they're already small in size and because [`AutoencoderKL`] only has a few `torch.nn.Linear` layers.
```py | 43_1_12 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | ```py
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig
from transformers import BitsAndBytesConfig as TransformersBitsAndBytesConfig | 43_1_13 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | from diffusers import FluxTransformer2DModel
from transformers import T5EncoderModel
quant_config = TransformersBitsAndBytesConfig(load_in_4bit=True,)
text_encoder_2_4bit = T5EncoderModel.from_pretrained(
"black-forest-labs/FLUX.1-dev",
subfolder="text_encoder_2",
quantization_config=quant_config,
torch_dtype=torch.float16,
)
quant_config = DiffusersBitsAndBytesConfig(load_in_4bit=True,) | 43_1_14 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | transformer_4bit = FluxTransformer2DModel.from_pretrained(
"black-forest-labs/FLUX.1-dev",
subfolder="transformer",
quantization_config=quant_config,
torch_dtype=torch.float16,
)
```
By default, all the other modules such as `torch.nn.LayerNorm` are converted to `torch.float16`. You can change the data type of these modules with the `torch_dtype` parameter.
```diff
transformer_4bit = FluxTransformer2DModel.from_pretrained(
"black-forest-labs/FLUX.1-dev",
subfolder="transformer", | 43_1_15 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | ```diff
transformer_4bit = FluxTransformer2DModel.from_pretrained(
"black-forest-labs/FLUX.1-dev",
subfolder="transformer",
quantization_config=quant_config,
+ torch_dtype=torch.float32,
)
```
Let's generate an image using our quantized models.
Setting `device_map="auto"` automatically fills all available space on the GPU(s) first, then the CPU, and finally, the hard drive (the absolute slowest option) if there is still not enough memory.
```py
pipe = FluxPipeline.from_pretrained( | 43_1_16 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | ```py
pipe = FluxPipeline.from_pretrained(
"black-forest-labs/FLUX.1-dev",
transformer=transformer_4bit,
text_encoder_2=text_encoder_2_4bit,
torch_dtype=torch.float16,
device_map="auto",
) | 43_1_17 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | pipe_kwargs = {
"prompt": "A cat holding a sign that says hello world",
"height": 1024,
"width": 1024,
"guidance_scale": 3.5,
"num_inference_steps": 50,
"max_sequence_length": 512,
} | 43_1_18 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | image = pipe(**pipe_kwargs, generator=torch.manual_seed(0),).images[0]
```
<div class="flex justify-center">
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/quant-bnb/4bit.png"/>
</div>
When there is enough memory, you can also directly move the pipeline to the GPU with `.to("cuda")` and apply [`~DiffusionPipeline.enable_model_cpu_offload`] to optimize GPU memory usage. | 43_1_19 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | Once a model is quantized, you can push the model to the Hub with the [`~ModelMixin.push_to_hub`] method. The quantization `config.json` file is pushed first, followed by the quantized model weights. You can also save the serialized 4-bit models locally with [`~ModelMixin.save_pretrained`].
</hfoption>
</hfoptions>
<Tip warning={true}>
Training with 8-bit and 4-bit weights are only supported for training *extra* parameters.
</Tip> | 43_1_20 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | <Tip warning={true}>
Training with 8-bit and 4-bit weights are only supported for training *extra* parameters.
</Tip>
Check your memory footprint with the `get_memory_footprint` method:
```py
print(model.get_memory_footprint())
```
Quantized models can be loaded from the [`~ModelMixin.from_pretrained`] method without needing to specify the `quantization_config` parameters:
```py
from diffusers import FluxTransformer2DModel, BitsAndBytesConfig | 43_1_21 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#bitsandbytes | .md | quantization_config = BitsAndBytesConfig(load_in_4bit=True)
model_4bit = FluxTransformer2DModel.from_pretrained(
"hf-internal-testing/flux.1-dev-nf4-pkg", subfolder="transformer"
)
``` | 43_1_22 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#8-bit-llmint8-algorithm | .md | <Tip>
Learn more about the details of 8-bit quantization in this [blog post](https://huggingface.co/blog/hf-bitsandbytes-integration)!
</Tip>
This section explores some of the specific features of 8-bit models, such as outlier thresholds and skipping module conversion. | 43_2_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#outlier-threshold | .md | An "outlier" is a hidden state value greater than a certain threshold, and these values are computed in fp16. While the values are usually normally distributed ([-3.5, 3.5]), this distribution can be very different for large models ([-60, 6] or [6, 60]). 8-bit quantization works well for values ~5, but beyond that, there is a significant performance penalty. A good default threshold value is 6, but a lower threshold may be needed for more unstable models (small models or finetuning). | 43_3_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#outlier-threshold | .md | To find the best threshold for your model, we recommend experimenting with the `llm_int8_threshold` parameter in [`BitsAndBytesConfig`]:
```py
from diffusers import FluxTransformer2DModel, BitsAndBytesConfig | 43_3_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#outlier-threshold | .md | quantization_config = BitsAndBytesConfig(
load_in_8bit=True, llm_int8_threshold=10,
)
model_8bit = FluxTransformer2DModel.from_pretrained(
"black-forest-labs/FLUX.1-dev",
subfolder="transformer",
quantization_config=quantization_config,
)
``` | 43_3_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#skip-module-conversion | .md | For some models, you don't need to quantize every module to 8-bit which can actually cause instability. For example, for diffusion models like [Stable Diffusion 3](../api/pipelines/stable_diffusion/stable_diffusion_3), the `proj_out` module can be skipped using the `llm_int8_skip_modules` parameter in [`BitsAndBytesConfig`]:
```py
from diffusers import SD3Transformer2DModel, BitsAndBytesConfig
quantization_config = BitsAndBytesConfig(
load_in_8bit=True, llm_int8_skip_modules=["proj_out"],
) | 43_4_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#skip-module-conversion | .md | quantization_config = BitsAndBytesConfig(
load_in_8bit=True, llm_int8_skip_modules=["proj_out"],
)
model_8bit = SD3Transformer2DModel.from_pretrained(
"stabilityai/stable-diffusion-3-medium-diffusers",
subfolder="transformer",
quantization_config=quantization_config,
)
``` | 43_4_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#4-bit-qlora-algorithm | .md | <Tip>
Learn more about its details in this [blog post](https://huggingface.co/blog/4bit-transformers-bitsandbytes).
</Tip>
This section explores some of the specific features of 4-bit models, such as changing the compute data type, using the Normal Float 4 (NF4) data type, and using nested quantization. | 43_5_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#compute-data-type | .md | To speedup computation, you can change the data type from float32 (the default value) to bf16 using the `bnb_4bit_compute_dtype` parameter in [`BitsAndBytesConfig`]:
```py
import torch
from diffusers import BitsAndBytesConfig
quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16)
``` | 43_6_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#normal-float-4-nf4 | .md | NF4 is a 4-bit data type from the [QLoRA](https://hf.co/papers/2305.14314) paper, adapted for weights initialized from a normal distribution. You should use NF4 for training 4-bit base models. This can be configured with the `bnb_4bit_quant_type` parameter in the [`BitsAndBytesConfig`]:
```py
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig
from transformers import BitsAndBytesConfig as TransformersBitsAndBytesConfig | 43_7_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#normal-float-4-nf4 | .md | from diffusers import FluxTransformer2DModel
from transformers import T5EncoderModel
quant_config = TransformersBitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
)
text_encoder_2_4bit = T5EncoderModel.from_pretrained(
"black-forest-labs/FLUX.1-dev",
subfolder="text_encoder_2",
quantization_config=quant_config,
torch_dtype=torch.float16,
)
quant_config = DiffusersBitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
) | 43_7_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/quantization/bitsandbytes.md | https://huggingface.co/docs/diffusers/en/quantization/bitsandbytes/#normal-float-4-nf4 | .md | quant_config = DiffusersBitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
)
transformer_4bit = FluxTransformer2DModel.from_pretrained(
"black-forest-labs/FLUX.1-dev",
subfolder="transformer",
quantization_config=quant_config,
torch_dtype=torch.float16,
)
```
For inference, the `bnb_4bit_quant_type` does not have a huge impact on performance. However, to remain consistent with the model weights, you should use the `bnb_4bit_compute_dtype` and `torch_dtype` values. | 43_7_2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.