import numpy as np import torch import clip from PIL import Image from diffusers import StableDiffusionPipeline, EulerDiscreteScheduler import gradio as gr device = "cuda" if torch.cuda.is_available() else "cpu" model_id = "stabilityai/stable-diffusion-2-1-base" scheduler = EulerDiscreteScheduler.from_pretrained(model_id, subfolder="scheduler") # [FIX] half precision problem # pipe = StableDiffusionPipeline.from_pretrained(model_id, scheduler=scheduler, revision="fp16", torch_dtype=torch.float16) pipe = StableDiffusionPipeline.from_pretrained(model_id, scheduler=scheduler) pipe = pipe.to(device) model, preprocess = clip.load("ViT-B/32", device=device) def generate_image(text_prompt): images = pipe(text_prompt, num_images_per_prompt=4).images return images def build_generation_block(prompt): with gr.Row(variant="compact"): text = gr.Textbox( label=prompt, show_label=False, max_lines=1, placeholder=prompt, ).style( container=False, ) btn = gr.Button("Generate image").style(full_width=False) gallery = gr.Gallery( label="Generated images", show_label=False, elem_id="gallery" ).style(columns=[2], rows=[2], object_fit="contain", height="auto") btn.click(generate_image, text, gallery) return text, gallery def compute_association_score(image_null, image_pos, image_neg): def compute_score(images): # print(images[0]) features = [preprocess(Image.open(i['name'])) for i in images] features = torch.stack(features).to(device) with torch.no_grad(): image_features = model.encode_image(features) image_features /= image_features.norm(dim=-1, keepdim=True) return image_features.cpu().numpy() emb_null = compute_score(image_null) emb_pos = compute_score(image_pos) emb_neg = compute_score(image_neg) return np.mean(emb_pos @ emb_null.T) - np.mean(emb_neg @ emb_null.T) with gr.Blocks() as demo: with gr.Group(): gr.HTML("

T2IAT: Measuring Valence and Stereotypical Biases in Text-to-Image Generation") gr.HTML("

ACL 2023 (Findings)

") gr.HTML("

Jialu Wang, Xinyue Gabby Liu, Zonglin Di, Yang Liu, Xin Eric Wang

") gr.HTML("

University of California, Santa Cruz

") gr.HTML("""

Paper Code

""") gr.HTML("""

Abstract: In the last few years, text-to-image generative models have gained remarkable success in generating images with unprecedented quality accompanied by a breakthrough of inference speed. Despite their rapid progress, human biases that manifest in the training examples, particularly with regard to common stereotypical biases, like gender and skin tone, still have been found in these generative models. In this work, we seek to measure more complex human biases exist in the task of text-to-image generations. Inspired by the well-known Implicit Association Test (IAT) from social psychology, we propose a novel Text-to-Image Association Test (T2IAT) framework that quantifies the implicit stereotypes between concepts and valence, and those in the images. We replicate the previously documented bias tests on generative models, including morally neutral tests on flowers and insects as well as demographic stereotypical tests on diverse social attributes. The results of these experiments demonstrate the presence of complex stereotypical behaviors in image generations.

""") # gr.Image( # "images/Text2ImgAssocationTest.png" # ).style( # height=300, # weight=400 # ) with gr.Group(): gr.HTML("""

First step: generate images with neutral prompts

""") text_null, gallery_null = build_generation_block("Enter the neutral prompt.") with gr.Group(): gr.HTML("""

Second step: generate attribute-guided images by including the attributes into the prompts

""") text_pos, gallery_pos = build_generation_block("Enter your prompt with attribute A.") text_neg, gallery_neg = build_generation_block("Enter your prompt with attribute B.") with gr.Group(): gr.HTML("

Final step: compute the association score between your specified attributes!") with gr.Row(): score = gr.Number(label="association score") btn = gr.Button("Compute Association Score!") btn.click(compute_association_score, [gallery_null, gallery_pos, gallery_neg], score) gr.HTML("

The absolute value of the association score represents the strength of the bias between the compared attributes, A and B, subject to the concepts that users choose in image generation. The higher score, the stronger the association, and vice versa.

") if __name__ == "__main__": demo.queue(concurrency_count=3) demo.launch()