Emily McMilin commited on
Commit
eef17b3
1 Parent(s): c8a64af

updated for parity with ICML version

Browse files
Files changed (1) hide show
  1. app.py +47 -87
app.py CHANGED
@@ -7,9 +7,8 @@ import random
7
  from matplotlib.ticker import MaxNLocator
8
  from transformers import pipeline
9
 
10
- MODEL_NAMES = ["bert-base-uncased",
11
- "distilbert-base-uncased", "xlm-roberta-base", "roberta-base"]
12
- OWN_MODEL_NAME = 'add-your-own'
13
 
14
  DECIMAL_PLACES = 1
15
  EPS = 1e-5 # to avoid /0 errors
@@ -290,45 +289,47 @@ description = """
290
 
291
  """
292
 
293
- place_example = [
294
- MODEL_NAMES[0],
 
295
  '',
296
- ', '.join(PLACES),
297
- 'PLACE',
298
  "False",
299
  1,
300
- 'She was raised in PLACE.'
301
  ]
302
 
303
- date_example = [
 
304
  MODEL_NAMES[0],
305
  '',
306
- ', '.join(DATES),
307
- 'DATE',
308
  "False",
309
- 3,
310
- 'She was a teenager in DATE.'
311
  ]
312
 
313
 
314
  subreddit_example = [
315
- MODEL_NAMES[2],
316
  '',
317
  ', '.join(SUBREDDITS),
318
  'SUBREDDIT',
319
  "False",
320
  1,
321
- 'I saw in r/SUBREDDIT that she was born in 1911.'
322
  ]
323
 
324
  own_model_example = [
325
  OWN_MODEL_NAME,
326
- 'lordtt13/COVID-SciBERT',
327
  ', '.join(DATES),
328
  'DATE',
329
  "False",
330
- 3,
331
- 'Ending her professorship in DATE, she was instrumental in developing the COVID vaccine.'
332
  ]
333
 
334
 
@@ -351,39 +352,42 @@ def your_fn():
351
  # %%
352
  demo = gr.Blocks()
353
  with demo:
354
- gr.Markdown("## Spurious Correlation Evaluation for Pre-trained and Fine-tuned LLMs")
355
- gr.Markdown("Although genders are relatively evenly distributed across time, place and interests, there are also known gender disparities in terms of access to resources. Here we demonstrate that this access disparity can result in dataset selection bias, causing models to learn a surprising range of spurious associations.")
356
-
357
- gr.Markdown("## This Demo")
358
- gr.Markdown("1) Click on one of the examples below (where we sweep through a spectrum of `places`, `date` and `subreddit` interest) to pre-populate the input fields.")
 
 
 
359
  gr.Markdown("2) Check out the pre-populated fields as you scroll down to the ['Hit Submit...'] button!")
360
  gr.Markdown("3) Repeat steps (1) and (2) with more pre-populated inputs or with your own values in the input fields!")
361
 
362
- gr.Markdown("### Example inputs")
363
  gr.Markdown("Click a button below to pre-populate input fields with example values. Then scroll down to Hit Submit to generate predictions.")
364
  with gr.Row():
365
- gr.Markdown("X-axis sorted by older to more recent dates:")
366
  date_gen = gr.Button('Click for date example inputs')
 
367
 
368
- gr.Markdown(
369
- "X-axis sorted by bottom 10 and top 10 [Global Gender Gap](https://www3.weforum.org/docs/WEF_GGGR_2021.pdf) ranked countries:")
370
  place_gen = gr.Button('Click for country example inputs')
371
-
372
  gr.Markdown(
373
- "X-axis sorted in order of increasing self-identified female participation (see [bburky](http://bburky.com/subredditgenderratios/)): ")
 
374
  subreddit_gen = gr.Button('Click for Subreddit example inputs')
 
 
375
 
376
- gr.Markdown("Date example with your own model loaded! (If first time, try another example, it can take a while to load new model.)")
377
- your_gen = gr.Button('Click for your model example inputs')
378
 
379
- gr.Markdown("### Input fields")
380
  gr.Markdown(
381
- f"A) Pick a spectrum of comma separated values for text injection and x-axis, described above in the Dose-response Relationship section.")
382
 
383
  with gr.Row():
384
  x_axis = gr.Textbox(
385
- lines=5,
386
- label="A) Pick a spectrum of comma separated values for text injection and x-axis",
387
  )
388
 
389
 
@@ -394,15 +398,15 @@ with demo:
394
  model_name = gr.Radio(
395
  MODEL_NAMES + [OWN_MODEL_NAME],
396
  type="value",
397
- label="B) Pick a BERT-like model.",
398
  )
399
  own_model_name = gr.Textbox(
400
- label="C) If you selected an 'add-your-own' model, put your models Hugging Face pipeline name here. We think it should work with any model that supports the fill-mask task.",
401
  )
402
 
403
  gr.Markdown("D) Pick if you want to the predictions normalied to these gendered terms only.")
404
  gr.Markdown("E) Also tell the demo what special token you will use in your input text, that you would like replaced with the spectrum of values you listed above.")
405
- gr.Markdown("And F) the degree of polynomial fit used for high-lighting possible dose response trend.")
406
 
407
 
408
  with gr.Row():
@@ -412,11 +416,11 @@ with demo:
412
  type="index",
413
  )
414
  place_holder = gr.Textbox(
415
- label="E) Special token place-holder that used in input text that will be replaced with the above spectrum of values.",
416
  )
417
  n_fit = gr.Dropdown(
418
  list(range(1, 5)),
419
- label="F) Degree of polynomial fit for high-lighting possible dose response trend",
420
  type="value",
421
  )
422
 
@@ -425,11 +429,11 @@ with demo:
425
 
426
  with gr.Row():
427
  input_text = gr.Textbox(
428
- lines=3,
429
- label="G) Input text that includes gendered pronouns and your place-holder token specified above.",
430
  )
431
 
432
- gr.Markdown("### Outputs!")
433
  #gr.Markdown("Scroll down and 'Hit Submit'!")
434
  with gr.Row():
435
  btn = gr.Button("Hit submit to generate predictions!")
@@ -465,50 +469,6 @@ with demo:
465
  outputs=[sample_text, female_fig, male_fig, df])
466
 
467
 
468
- gr.Markdown("### How does this work?")
469
- gr.Markdown("We are able to test the pre-trained LLMs without any modification to the models, as the gender-pronoun prediction task is simply a special case of the masked language modeling (MLM) task, with which all these models were pre-trained. Rather than random masking, the gender-pronoun prediction task masks only non-gender-neutral terms (listed in prior [Space](https://huggingface.co/spaces/emilylearning/causing_gender_pronouns_two)).")
470
- gr.Markdown("For the pre-trained LLMs the final prediction is a softmax over the entire tokenizer's vocabulary, from which we sum up the portion of the probability mass from the top five prediction words that are gendered terms (and normalize or not, based on selected preference above.")
471
-
472
-
473
-
474
- gr.Markdown("### What is Causing these Spurious Correlations?")
475
-
476
- gr.Markdown("Spurious correlations are often considered undesirable, as they do not match our intuition about the real-world domain from which we derive samples for inference-time prediction.")
477
- gr.Markdown("Selection of samples into datasets can be a zero-sum-game, with even our high quality datasets forced to trade off one for another, thus inducing selection bias into the learned associations of the model.")
478
-
479
- gr.Markdown("### Dose-response Relationship")
480
- gr.Markdown("One intuitive way to see the impact that changing one variable may have upon another is to look for a dose-response relationship, in which a larger intervention in the treatment (the value in text form injected in the otherwise unchanged text sample) produces a larger response in the output (the softmax probability of a gendered pronoun).")
481
- gr.Markdown("This dose-response plot requires a range of values along which we may see a spectrum of gender representation (or misrepresentation) in our datasets.")
482
-
483
-
484
- gr.Markdown("### Data Generating Process")
485
- gr.Markdown("To pick values below that are most likely to cause spurious correlations, it helps to make some assumptions about the training dataset's likely data generating process, and where selection bias may come in.")
486
-
487
- gr.Markdown("A plausible data generating processes for Wiki-Bio and Reddit datasets is shown as a DAG below. The variables `W` : birth place, birth date or subreddit interest, and `G`: gender, are both independent variables that have no ancestral variables. However, `W` and `G` may have a role in causing one's access, `Z`. In the case of Wiki-Bio a functional form of `Z` may capture the general trend that access has become less gender-dependent over time, but not in every place. In the case of Reddit TLDR, `Z` may capture that despite some subreddits having gender-neutral topics, the specific style of moderation and community in the subreddit may reduce access to some genders.")
488
-
489
- gr.Markdown("This DAG structure is prone to collider bias between `W` and `G` when conditioning on access, `Z`. In other words, although in real life *place*, *date*, and (subreddit) *interest* vs *gender* are unconditionally independent, when we condition on their common effect, *access*, they become unconditionally dependent.")
490
-
491
- gr.Markdown("The obvious solution to not condition on access is unavailable to us, as we are required to in order to represent the process of selection into the dataset. Thus, a statistical relationship between `W` and `G` can be induced by the dataset formation, leading to possible spurious correlations, as shown here.")
492
-
493
-
494
-
495
- gr.Markdown("""
496
- <style>
497
- img {
498
- width: 30%;
499
- max-width: 600px;
500
- }
501
- </style>
502
- <center>
503
- <img src="https://www.dropbox.com/s/4f07djirinl2qvy/show_g_crop.png?raw=1"
504
- alt="DAG of possible data generating process for datasets used in training some of our LLMs.">
505
- </center>
506
- """)
507
-
508
- gr.Markdown("### I Don't Buy It")
509
- gr.Markdown("See something wrong above? Do you think we cherry picked our examples? Try your own, including your own x-axis. Think we cherry picked LLMs? Try the `add-your-own` model option. This demo _should_ work with any Hugging Face model that supports the [fill-mask](https://huggingface.co/models?pipeline_tag=fill-mask) task.")
510
- gr.Markdown("Think our data generating process is wrong, or found an interesting spurious correlation you'd like to set as a default example? Use the community tab to discuss or pull request your fix.")
511
-
512
  demo.launch(debug=True)
513
 
514
 
 
7
  from matplotlib.ticker import MaxNLocator
8
  from transformers import pipeline
9
 
10
+ MODEL_NAMES = ["bert-base-uncased", "roberta-base", "bert-large-uncased", "roberta-large"]
11
+ OWN_MODEL_NAME = 'add-a-model'
 
12
 
13
  DECIMAL_PLACES = 1
14
  EPS = 1e-5 # to avoid /0 errors
 
289
 
290
  """
291
 
292
+
293
+ date_example = [
294
+ MODEL_NAMES[1],
295
  '',
296
+ ', '.join(DATES),
297
+ 'DATE',
298
  "False",
299
  1,
300
+ 'She was a teenager in DATE.'
301
  ]
302
 
303
+
304
+ place_example = [
305
  MODEL_NAMES[0],
306
  '',
307
+ ', '.join(PLACES),
308
+ 'PLACE',
309
  "False",
310
+ 1,
311
+ 'She became an adult in PLACE.'
312
  ]
313
 
314
 
315
  subreddit_example = [
316
+ MODEL_NAMES[3],
317
  '',
318
  ', '.join(SUBREDDITS),
319
  'SUBREDDIT',
320
  "False",
321
  1,
322
+ 'She was a kid. SUBREDDIT.'
323
  ]
324
 
325
  own_model_example = [
326
  OWN_MODEL_NAME,
327
+ 'emilyalsentzer/Bio_ClinicalBERT',
328
  ', '.join(DATES),
329
  'DATE',
330
  "False",
331
+ 1,
332
+ 'She was exposed to the virus in DATE.'
333
  ]
334
 
335
 
 
352
  # %%
353
  demo = gr.Blocks()
354
  with demo:
355
+ gr.Markdown("# Spurious Correlation Evaluation for Pre-trained LLMs")
356
+ gr.Markdown("Find spurious correlations between seemingly independent variables (for example between `gender` and `time`) in almost any BERT-like LLM on Hugging Face, below.")
357
+
358
+ gr.Markdown("See why this happens how in our paper, [Selection Bias Induced Spurious Correlations in Large Language Models](https://arxiv.org/pdf/2207.08982.pdf), presented at [ICML 2022 Workshop on Spurious Correlations, Invariance, and Stability](https://sites.google.com/view/scis-workshop/home).")
359
+
360
+
361
+ gr.Markdown("## Instructions for this Demo")
362
+ gr.Markdown("1) Click on one of the examples below (where we sweep through a spectrum of `places`, `dates` and `subreddits`) to pre-populate the input fields.")
363
  gr.Markdown("2) Check out the pre-populated fields as you scroll down to the ['Hit Submit...'] button!")
364
  gr.Markdown("3) Repeat steps (1) and (2) with more pre-populated inputs or with your own values in the input fields!")
365
 
366
+ gr.Markdown("## Example inputs")
367
  gr.Markdown("Click a button below to pre-populate input fields with example values. Then scroll down to Hit Submit to generate predictions.")
368
  with gr.Row():
 
369
  date_gen = gr.Button('Click for date example inputs')
370
+ gr.Markdown("<-- x-axis sorted by older to more recent dates:")
371
 
 
 
372
  place_gen = gr.Button('Click for country example inputs')
 
373
  gr.Markdown(
374
+ "<-- x-axis sorted by bottom 10 and top 10 [Global Gender Gap](https://www3.weforum.org/docs/WEF_GGGR_2021.pdf) ranked countries:")
375
+
376
  subreddit_gen = gr.Button('Click for Subreddit example inputs')
377
+ gr.Markdown(
378
+ "<-- x-axis sorted in order of increasing self-identified female participation (see [bburky](http://bburky.com/subredditgenderratios/)): ")
379
 
380
+ your_gen = gr.Button('Add-a-model example inputs')
381
+ gr.Markdown("<-- x-axis dates, with your own model loaded! (If first time, try another example, it can take a while to load new model.)")
382
 
383
+ gr.Markdown("## Input fields")
384
  gr.Markdown(
385
+ f"A) Pick a spectrum of comma separated values for text injection and x-axis.")
386
 
387
  with gr.Row():
388
  x_axis = gr.Textbox(
389
+ lines=3,
390
+ label="A) Comma separated values for text injection and x-axis",
391
  )
392
 
393
 
 
398
  model_name = gr.Radio(
399
  MODEL_NAMES + [OWN_MODEL_NAME],
400
  type="value",
401
+ label="B) BERT-like model.",
402
  )
403
  own_model_name = gr.Textbox(
404
+ label="C) If you selected an 'add-a-model' model, put any Hugging Face pipeline model name (that supports the fill-mask task) here.",
405
  )
406
 
407
  gr.Markdown("D) Pick if you want to the predictions normalied to these gendered terms only.")
408
  gr.Markdown("E) Also tell the demo what special token you will use in your input text, that you would like replaced with the spectrum of values you listed above.")
409
+ gr.Markdown("And F) the degree of polynomial fit used for high-lighting potential spurious association.")
410
 
411
 
412
  with gr.Row():
 
416
  type="index",
417
  )
418
  place_holder = gr.Textbox(
419
+ label="E) Special token place-holder",
420
  )
421
  n_fit = gr.Dropdown(
422
  list(range(1, 5)),
423
+ label="F) Degree of polynomial fit",
424
  type="value",
425
  )
426
 
 
429
 
430
  with gr.Row():
431
  input_text = gr.Textbox(
432
+ lines=2,
433
+ label="G) Input text with pronouns and place-holder token",
434
  )
435
 
436
+ gr.Markdown("## Outputs!")
437
  #gr.Markdown("Scroll down and 'Hit Submit'!")
438
  with gr.Row():
439
  btn = gr.Button("Hit submit to generate predictions!")
 
469
  outputs=[sample_text, female_fig, male_fig, df])
470
 
471
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
472
  demo.launch(debug=True)
473
 
474