File size: 15,360 Bytes
6257003
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import gradio as gr
import json
import numpy as np
import pandas as pd
from datasets import load_from_disk
from itertools import chain
import operator

pd.options.plotting.backend = "plotly"


TITLE = "Identity Biases in Diffusion Models: Professions"

_INTRO = """
# Identity Biases in Diffusion Models: Professions
        
Explore profession-level social biases in the data from [DiffusionBiasExplorer](https://hf.co/spaces/tti-bias/DiffusionBiasExplorer)!
This demo leverages the gender and ethnicity representation clusters described in the [companion app](https://hf.co/spaces/tti-bias/DiffusionFaceClustering)
to analyze social trends in machine-generated visual representations of professions.
The **Professions Overview** tab lets you compare the distribution over
[identity clusters](https://hf.co/spaces/tti-bias/DiffusionFaceClustering "Identity clusters identify visual features in the systems' output space correlated with variation of gender and ethnicity in input prompts.")
across professions for Stable Diffusion and Dalle-2 systems (or aggregated for `All Models`).
The **Professions Focus** tab provides more details for each of the individual professions, including direct system comparisons and examples of profession images for each cluster.
This work was done in the scope of the [Stable Bias Project](https://hf.co/spaces/tti-bias/StableBias).
As you use this demo, please share findings and comments [in the discussions tab](https://hf.co/spaces/tti-bias/DiffusionClustering/discussions)!
"""

_ = """
 For example, you can use this tool to investigate:
 - How do each model's representation of professions correlate with the gender ratios reported by the [U.S. Bureau of Labor
Statistics](https://www.bls.gov/cps/cpsaat11.htm "The reported percentage of women in each profession in the US is indicated in the `Labor Women` column in the Professions Overview tab.")?
Are social trends reflected, are they exaggerated?
- Which professions have the starkest differences in how different models represent them?
"""

professions_dset = load_from_disk("professions")
professions_df = professions_dset.to_pandas()


clusters_dicts = dict(
    (num_cl, json.load(open(f"clusters/professions_to_clusters_{num_cl}.json")))
    for num_cl in [12, 24, 48]
)

cluster_summaries_by_size = json.load(open("clusters/cluster_summaries_by_size.json"))

prompts = pd.read_csv("promptsadjectives.csv")
professions = ["all professions"] + list(
#    sorted([p.lower() for p in prompts["Occupation-Noun"].tolist()])
    sorted([p for p in prompts["Occupation-Noun"].tolist()])
)
models = {
    "All": "All Models",
    "SD_14": "Stable Diffusion 1.4",
    "SD_2": "Stable Diffusion 2",
    "DallE": "Dall-E 2",
}

df_models = {
    "All Models": "All",
    "Stable Diffusion 1.4": "SD_14",
    "Stable Diffusion 2": "SD_2",
    "Dall-E 2": "DallE",
}


def describe_cluster(num_clusters, block="label"):
    cl_dict = clusters_dicts[num_clusters]
    labels_values = sorted(cl_dict.items(), key=operator.itemgetter(1))
    labels_values.reverse()
    total = float(sum(cl_dict.values()))
    lv_prcnt = list(
        (item[0], round(item[1] * 100 / total, 0)) for item in labels_values
    )
    top_label = lv_prcnt[0][0]
    description_string = (
        "<span>The most represented %s is <b>%s</b>, making up about <b>%d%%</b> of the cluster.</span>"
        % (to_string(block), to_string(top_label), lv_prcnt[0][1])
    )
    description_string += "<p>This is followed by: "
    for lv in lv_prcnt[1:]:
        description_string += "<BR/><b>%s:</b> %d%%" % (to_string(lv[0]), lv[1])
    description_string += "</p>"
    return description_string


def make_profession_plot(num_clusters, prof_name):
    sorted_cl_scores = [
        (k, v)
        for k, v in sorted(
            clusters_dicts[num_clusters]["All"][prof_name][
                "cluster_proportions"
            ].items(),
            key=lambda x: x[1],
            reverse=True,
        )
        if v > 0
    ]
    pre_pandas = dict(
        [
            (
                models[mod_name],
                dict(
                    (
                        f"Cluster {k}",
                        clusters_dicts[num_clusters][mod_name][prof_name][
                            "cluster_proportions"
                        ][k],
                    )
                    for k, _ in sorted_cl_scores
                ),
            )
            for mod_name in models
        ]
    )
    df = pd.DataFrame.from_dict(pre_pandas)
    prof_plot = df.plot(kind="bar", barmode="group")
    cl_summary_text = f"Profession '{prof_name}':\n"
    for cl_id, _ in sorted_cl_scores:
        cl_summary_text += f"- {cluster_summaries_by_size[str(num_clusters)][int(cl_id)].replace(' gender terms', '').replace('; ethnicity terms:', ',')} \n"
    return (
        prof_plot,
        gr.update(
            choices=[k for k, _ in sorted_cl_scores], value=sorted_cl_scores[0][0]
        ),
        gr.update(value=cl_summary_text),
    )


def make_profession_table(num_clusters, prof_names, mod_name, max_cols=8):
    professions_list_clusters = [
        (
            prof_name,
            clusters_dicts[num_clusters][df_models[mod_name]][prof_name][
                "cluster_proportions"
            ],
        )
        for prof_name in prof_names
    ]
    totals = sorted(
        [
            (
                k,
                sum(
                    prof_clusters[str(k)]
                    for _, prof_clusters in professions_list_clusters
                ),
            )
            for k in range(num_clusters)
        ],
        key=lambda x: x[1],
        reverse=True,
    )[:max_cols]
    prof_list_pre_pandas = [
        dict(
            [
                ("Profession", prof_name),
                (
                    "Entropy",
                    clusters_dicts[num_clusters][df_models[mod_name]][prof_name][
                        "entropy"
                    ],
                ),
                (
                    "Labor Women",
                    clusters_dicts[num_clusters][df_models[mod_name]][prof_name][
                        "labor_fm"
                    ][0],
                ),
                ("", ""),
            ]
            + [(f"Cluster {k}", prof_clusters[str(k)]) for k, v in totals if v > 0]
        )
        for prof_name, prof_clusters in professions_list_clusters
    ]
    clusters_df = pd.DataFrame.from_dict(prof_list_pre_pandas)
    cl_summary_text = ""
    for cl_id, _ in totals[:max_cols]:
        cl_summary_text += f"- {cluster_summaries_by_size[str(num_clusters)][cl_id].replace(' gender terms', '').replace('; ethnicity terms:', ',')} \n"
    return (
        [c[0] for c in totals],
        (
            clusters_df.style.background_gradient(
                axis=None, vmin=0, vmax=100, cmap="YlGnBu"
            )
            .format(precision=1)
            .to_html()
        ),
        gr.update(value=cl_summary_text),
    )


def get_image(model, fname, score):
    return (
        professions_dset.select(
            professions_df[
                (professions_df["image_path"] == fname)
                & (professions_df["model"] == model)
            ].index
        )["image"][0],
        " ".join(fname.split("/")[0].split("_")[4:])
        + f" | {score:.2f}"
        + f" | {models[model]}",
    )


def show_examplars(num_clusters, prof_name, cl_id, confidence_threshold=0.6):
    # only show images where the similarity to the centroid is > confidence_threshold
    examplars_dict = clusters_dicts[num_clusters]["All"][prof_name][
        "cluster_examplars"
    ][str(cl_id)]
    l = [
        tuple(img)
        for img in examplars_dict["close"]
        + examplars_dict["mid"][:2]
        + examplars_dict["far"]
    ]
    l = [
        img
        for i, img in enumerate(l)
        if img[0] > confidence_threshold and img not in l[:i]
    ]
    return (
        [get_image(model, fname, score) for score, model, fname in l],
        gr.update(
            label=f"Generations for profession ''{prof_name}'' assigned to cluster {cl_id} of {num_clusters}"
        ),
    )


with gr.Blocks(title=TITLE) as demo:
    gr.Markdown(_INTRO)
    gr.HTML(
        """<span style="color:red" font-size:smaller>⚠️ DISCLAIMER: the images displayed by this tool were generated by text-to-image systems and may depict offensive stereotypes or contain explicit content.</span>"""
    )
    with gr.Tab("Professions Overview"):
        gr.Markdown(
            """
            Select one or more professions and models from the dropdowns on the left to see which clusters are most representative for this combination.
            Try choosing different numbers of clusters to see if the results change, and then go to the 'Profession Focus' tab to go more in-depth into these results.
            The `Labor Women` column provided for comparison corresponds to the gender ratio reported by the
            [U.S. Bureau of Labor Statistics](https://www.bls.gov/cps/cpsaat11.htm) for each profession.
            """
        )
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("Select the parameters here:")
                num_clusters = gr.Radio(
                    [12, 24, 48],
                    value=12,
                    label="How many clusters do you want to use to represent identities?",
                )
                model_choices = gr.Dropdown(
                    [
                        "All Models",
                        "Stable Diffusion 1.4",
                        "Stable Diffusion 2",
                        "Dall-E 2",
                    ],
                    value="All Models",
                    label="Which models do you want to compare?",
                    interactive=True,
                )
                profession_choices_overview = gr.Dropdown(
                    professions,
                    value=[
                        "all professions",
                        "CEO",
                        "director",
                        "social assistant",
                        "social worker",
                    ],
                    label="Which professions do you want to compare?",
                    multiselect=True,
                    interactive=True,
                )
            with gr.Column(scale=3):
                with gr.Row():
                    table = gr.HTML(
                        label="Profession assignment per cluster", wrap=True
                    )
                with gr.Row():
                    # clusters = gr.Dataframe(type="array", visible=False, col_count=1)
                    clusters = gr.Textbox(label="clusters", visible=False)
                    gr.Markdown(
                        """
                        ##### What do the clusters mean?
                        Below is a summary of the identity cluster compositions.
                        For more details, see the [companion demo](https://huggingface.co/spaces/tti-bias/DiffusionFaceClustering):
                        """
                    )
                with gr.Row():
                    with gr.Accordion(label="Cluster summaries", open=True):
                        cluster_descriptions_table = gr.Text(
                            "TODO", label="Cluster summaries", show_label=False
                        )
    with gr.Tab("Profession Focus"):
        with gr.Row():
            with gr.Column():
                gr.Markdown(
                    "Select a profession to visualize and see which clusters and identity groups are most represented in the profession, as well as some examples of generated images below."
                )
                profession_choice_focus = gr.Dropdown(
                    choices=professions,
                    value="scientist",
                    label="Select profession:",
                )
                num_clusters_focus = gr.Radio(
                    [12, 24, 48],
                    value=12,
                    label="How many clusters do you want to use to represent identities?",
                )
            with gr.Column():
                plot = gr.Plot(
                    label=f"Makeup of the cluster assignments for profession {profession_choice_focus}"
                )
        with gr.Row():
            with gr.Column():
                gr.Markdown(
                    """
                    ##### What do the clusters mean?
                    Below is a summary of the identity cluster compositions.
                    For more details, see the [companion demo](https://huggingface.co/spaces/tti-bias/DiffusionFaceClustering):
                    """
                )
                with gr.Accordion(label="Cluster summaries", open=True):
                    cluster_descriptions = gr.Text(
                        "TODO", label="Cluster summaries", show_label=False
                    )
            with gr.Column():
                gr.Markdown(
                    """
                    ##### What's in the clusters?
                    You can show examples of profession images assigned to each identity cluster by selecting one here:
                    """
                )
                with gr.Accordion(label="Cluster selection", open=True):
                    cluster_id_focus = gr.Dropdown(
                        choices=[i for i in range(num_clusters_focus.value)],
                        value=0,
                        label="Select cluster to visualize:",
                    )
        with gr.Row():
            examplars_plot = gr.Gallery(
                label="Profession images assigned to the selected cluster."
            ).style(grid=4, height="auto", container=True)
    demo.load(
        make_profession_table,
        [num_clusters, profession_choices_overview, model_choices],
        [clusters, table, cluster_descriptions_table],
        queue=False,
    )
    demo.load(
        make_profession_plot,
        [num_clusters_focus, profession_choice_focus],
        [plot, cluster_id_focus, cluster_descriptions],
        queue=False,
    )
    demo.load(
        show_examplars,
        [
            num_clusters_focus,
            profession_choice_focus,
            cluster_id_focus,
        ],
        [examplars_plot, examplars_plot],
        queue=False,
    )
    for var in [num_clusters, model_choices, profession_choices_overview]:
        var.change(
            make_profession_table,
            [num_clusters, profession_choices_overview, model_choices],
            [clusters, table, cluster_descriptions_table],
            queue=False,
        )
    for var in [num_clusters_focus, profession_choice_focus]:
        var.change(
            make_profession_plot,
            [num_clusters_focus, profession_choice_focus],
            [plot, cluster_id_focus, cluster_descriptions],
            queue=False,
        )
    for var in [num_clusters_focus, profession_choice_focus, cluster_id_focus]:
        var.change(
            show_examplars,
            [
                num_clusters_focus,
                profession_choice_focus,
                cluster_id_focus,
            ],
            [examplars_plot, examplars_plot],
            queue=False,
        )


if __name__ == "__main__":
    demo.queue().launch(debug=True)