emilylearning commited on
Commit
4946d79
1 Parent(s): 5df47ea

Bugfix masking uppercase pronouns. Update docs, examples. Parity with emilylearning

Browse files
Files changed (1) hide show
  1. app.py +47 -26
app.py CHANGED
@@ -153,7 +153,7 @@ def get_gendered_token_ids():
153
 
154
  def prepare_text_for_masking(input_text, mask_token, gendered_tokens, split_key):
155
  text_w_masks_list = [
156
- mask_token if word in gendered_tokens else word for word in input_text.split()]
157
  num_masks = len([m for m in text_w_masks_list if m == mask_token])
158
 
159
  text_portions = ' '.join(text_w_masks_list).split(split_key)
@@ -297,7 +297,7 @@ place_example = [
297
  'PLACE',
298
  "False",
299
  1,
300
- 'Born in PLACE, she was a teacher.'
301
  ]
302
 
303
  date_example = [
@@ -307,7 +307,7 @@ date_example = [
307
  'DATE',
308
  "False",
309
  3,
310
- 'Born in DATE, she was a doctor.'
311
  ]
312
 
313
 
@@ -317,8 +317,8 @@ subreddit_example = [
317
  ', '.join(SUBREDDITS),
318
  'SUBREDDIT',
319
  "False",
320
- 3,
321
- 'I saw in r/SUBREDDIT that she is a hacker.'
322
  ]
323
 
324
  own_model_example = [
@@ -354,10 +354,6 @@ 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("### Dose-response Relationship")
358
- 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).")
359
- 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.")
360
-
361
  gr.Markdown("## This Demo")
362
  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.")
363
  gr.Markdown("2) Check out the pre-populated fields as you scroll down to the ['Hit Submit...'] button!")
@@ -370,14 +366,14 @@ with demo:
370
  date_gen = gr.Button('Click for date example inputs')
371
 
372
  gr.Markdown(
373
- "X-axis sorted by bottom 10 and top 10 [Global Gender Gap](https://www3.weforum.org/docs/WEF_GGGR_2021.pdf) ranked countries by World Economic Forum in 2021:")
374
  place_gen = gr.Button('Click for country example inputs')
375
 
376
  gr.Markdown(
377
- "X-axis sorted in order of increasing self-identified female participation (see [bburky demo](http://bburky.com/subredditgenderratios/)): ")
378
  subreddit_gen = gr.Button('Click for Subreddit example inputs')
379
 
380
- gr.Markdown("Date example with your own model loaded! (We recommend you try after seeing how others work. It can take a while to load new model.)")
381
  your_gen = gr.Button('Click for your model example inputs')
382
 
383
  gr.Markdown("### Input fields")
@@ -391,8 +387,8 @@ with demo:
391
  )
392
 
393
 
394
- gr.Markdown(
395
- f"B) Pick a pre-loaded BERT-family model of interest on the right. C) Or select `{OWN_MODEL_NAME}`, then add the mame of any other Hugging Face model that supports the [fill-mask](https://huggingface.co/models?pipeline_tag=fill-mask) task on the right (note: this may take some time to load).")
396
 
397
  with gr.Row():
398
  model_name = gr.Radio(
@@ -404,10 +400,9 @@ with demo:
404
  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.",
405
  )
406
 
407
- gr.Markdown(
408
- "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)).")
409
- 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. D) Pick if you want to the predictions normalied to these gendered terms only.")
410
- 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, and F) the degree of polynomial fit used for high-lighting possible dose response trend ")
411
 
412
 
413
  with gr.Row():
@@ -470,25 +465,51 @@ with demo:
470
  outputs=[sample_text, female_fig, male_fig, df])
471
 
472
 
 
 
 
 
 
 
473
  gr.Markdown("### What is Causing these Spurious Correlations?")
474
 
475
  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.")
476
- gr.Markdown("Selection of samples into datasets is 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.")
 
 
 
 
 
477
 
478
  gr.Markdown("### Data Generating Process")
479
- gr.Markdown("To pick values below that are most likely to cause spurious correlations, it helps to make some assumptions about the training datasets' likely data generating process, and where selection bias may come in.")
 
 
 
 
 
 
 
 
480
 
481
- gr.Markdown("A plausible data generating processes for both Wikipedia and Reddit sourced data is shown as a DAG below. These DAGs are prone to collider bias when conditioning on `access`. In other words, although in real life `place`, `date`, (subreddit) `interest` and gender are all unconditionally independent, when we condition on their common effect, `access`, they become unconditionally dependent. Composing a dataset often requires the dataset maintainers to condition on `access`. Thus LLMs learn these dataset induced dependencies, appearing to us as spurious correlations.")
482
  gr.Markdown("""
 
 
 
 
 
 
483
  <center>
484
- <img src="https://www.dropbox.com/s/f0numpllywdd271/combo_dag_block_party.png?raw=1"
485
  alt="DAG of possible data generating process for datasets used in training some of our LLMs.">
486
  </center>
487
  """)
488
 
489
- gr.Markdown("There may be misassumptions in our DAG above, which you can explore above. Please contribute any corrections or new examples of interest!")
490
- gr.Markdown("You may also be interested in applying this demo to your own model of interest. This demo _should_ work with any Hugging Face model that supports the [fill-mask](https://huggingface.co/models?pipeline_tag=fill-mask) task.")
491
-
 
492
  demo.launch(debug=True)
493
 
494
- # %%
 
153
 
154
  def prepare_text_for_masking(input_text, mask_token, gendered_tokens, split_key):
155
  text_w_masks_list = [
156
+ mask_token if word.lower() in gendered_tokens else word for word in input_text.split()]
157
  num_masks = len([m for m in text_w_masks_list if m == mask_token])
158
 
159
  text_portions = ' '.join(text_w_masks_list).split(split_key)
297
  'PLACE',
298
  "False",
299
  1,
300
+ 'She was raised in PLACE.'
301
  ]
302
 
303
  date_example = [
307
  'DATE',
308
  "False",
309
  3,
310
+ 'She was a teenager in DATE.'
311
  ]
312
 
313
 
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 = [
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!")
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")
387
  )
388
 
389
 
390
+ gr.Markdown("B) Pick a pre-loaded BERT-family model of interest on the right.")
391
+ gr.Markdown(f"Or C) select `{OWN_MODEL_NAME}`, then add the mame of any other Hugging Face model that supports the [fill-mask](https://huggingface.co/models?pipeline_tag=fill-mask) task on the right (note: this may take some time to load).")
392
 
393
  with gr.Row():
394
  model_name = gr.Radio(
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():
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
+
515
+ # %%