Spaces:
Runtime error
Runtime error
Commit
·
5943071
1
Parent(s):
d6ad933
Adding bert-like. Organizing description
Browse files
app.py
CHANGED
@@ -1,14 +1,16 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
import torch
|
3 |
from transformers import AutoModelForTokenClassification, AutoTokenizer
|
|
|
4 |
import pandas as pd
|
5 |
import numpy as np
|
6 |
|
7 |
|
8 |
-
|
9 |
# Play with me, consts
|
10 |
CONDITIONING_VARIABLES = ["none", "birth_place", "birth_date", "name"]
|
11 |
FEMALE_WEIGHTS = [1.5, 5] # About 5x more male than female tokens in dataset
|
|
|
12 |
|
13 |
# Internal consts
|
14 |
START_YEAR = 1800
|
@@ -44,6 +46,9 @@ for var in CONDITIONING_VARIABLES:
|
|
44 |
models[(var, f_weight)] = AutoModelForTokenClassification.from_pretrained(
|
45 |
models_paths[(var, f_weight)]
|
46 |
)
|
|
|
|
|
|
|
47 |
|
48 |
|
49 |
# Tokenizers same for each model, so just grabbing one of them
|
@@ -54,7 +59,7 @@ MASK_TOKEN_ID = tokenizer.mask_token_id
|
|
54 |
|
55 |
|
56 |
# more static stuff
|
57 |
-
gendered_lists = [
|
58 |
["he", "she"],
|
59 |
["him", "her"],
|
60 |
["his", "hers"],
|
@@ -63,15 +68,12 @@ gendered_lists = [
|
|
63 |
["men", "women"],
|
64 |
["husband", "wife"],
|
65 |
]
|
66 |
-
|
67 |
-
|
|
|
|
|
|
|
68 |
|
69 |
-
male_gendered_token_ids = tokenizer.convert_tokens_to_ids(
|
70 |
-
list(male_gendered_dict.keys())
|
71 |
-
)
|
72 |
-
female_gendered_token_ids = tokenizer.convert_tokens_to_ids(
|
73 |
-
list(female_gendered_dict.keys())
|
74 |
-
)
|
75 |
assert tokenizer.unk_token_id not in male_gendered_token_ids
|
76 |
assert tokenizer.unk_token_id not in female_gendered_token_ids
|
77 |
|
@@ -133,15 +135,30 @@ def tokenize_and_append_metadata(text, tokenizer):
|
|
133 |
|
134 |
# Run inference
|
135 |
def predict_gender_pronouns(
|
136 |
-
num_points, conditioning_variables, f_weights,
|
137 |
):
|
138 |
|
139 |
text_portions = input_text.split(SPLIT_KEY)
|
140 |
|
141 |
years = np.linspace(START_YEAR, STOP_YEAR, int(num_points)).astype(int)
|
|
|
142 |
|
143 |
dfs = []
|
144 |
dfs.append(pd.DataFrame({"year": years}))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
145 |
for f_weight in f_weights:
|
146 |
for var in conditioning_variables:
|
147 |
prefix = f"w{f_weight}_{var}"
|
@@ -149,17 +166,10 @@ def predict_gender_pronouns(
|
|
149 |
|
150 |
p_female = []
|
151 |
p_male = []
|
152 |
-
for
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
tokenizer=tokenizer,
|
157 |
-
)
|
158 |
-
|
159 |
-
ids = tokenized_sample["input_ids"]
|
160 |
-
atten_mask = torch.tensor(tokenized_sample["attention_mask"])
|
161 |
-
toks = tokenizer.convert_ids_to_tokens(ids)
|
162 |
-
labels = tokenized_sample["labels"]
|
163 |
|
164 |
with torch.no_grad():
|
165 |
outputs = model(ids.unsqueeze(dim=0), atten_mask.unsqueeze(dim=0))
|
@@ -167,13 +177,45 @@ def predict_gender_pronouns(
|
|
167 |
|
168 |
was_masked = labels.cpu() != -100
|
169 |
preds = torch.where(was_masked, preds, -100)
|
170 |
-
num_preds = torch.sum(was_masked).item()
|
171 |
|
172 |
-
|
173 |
-
|
|
|
|
|
|
|
174 |
|
175 |
dfs.append(pd.DataFrame({f"%f_{prefix}": p_female, f"%m_{prefix}": p_male}))
|
176 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
177 |
results = pd.concat(dfs, axis=1).set_index("year")
|
178 |
|
179 |
female_df = results.filter(regex=".*f_")
|
@@ -192,14 +234,21 @@ def predict_gender_pronouns(
|
|
192 |
female_df,
|
193 |
male_df_for_plot,
|
194 |
male_df,
|
195 |
-
)
|
196 |
|
197 |
|
198 |
title = "Changing Gender Pronouns"
|
199 |
-
description =
|
200 |
-
|
201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
202 |
|
|
|
203 |
In the DAG, we can see that `birth_place`, `birth_date` and `gender` are all independent elements that have no common cause with the other covariates in the DAG. However `birth_place`, `birth_date` and `gender` may all have a role in causing one's `access_to_resources`, with the general trend that `access_to_resources` has become less gender-dependent over time, but not in every `birth_place`, with recent events in Afghanistan providing a stark counterexample to this trend. `access_to_resources` further determines how or if at all, you may appear in the dataset’s `context_words`.
|
204 |
|
205 |
We also argue that although there are complex causal interactions between words in a segment, the `context_words` are more likely to cause the `gender_pronouns`, rather than vice versa. For example, if the subject is a famous doctor and the object is her wealthy father, these context words will determine which person is being referred to, and thus which gendered-pronoun to use.
|
@@ -212,9 +261,10 @@ In this graph, any pink path between `context_words` and `gender_pronouns` will
|
|
212 |
alt="DAG of possible data generating process for datasets used in training.">
|
213 |
</center>
|
214 |
|
215 |
-
Those familiar with causal DAGs may note when can simply condition on `gender` to block any confounding between the `context_words` and the `gender_pronouns`. However, this is not always possible, particularly in generative or mask-filling tasks, like those common in language models.
|
216 |
|
217 |
-
|
|
|
218 |
```
|
219 |
gendered_lists = [
|
220 |
['he', 'she'],
|
@@ -226,24 +276,25 @@ gendered_lists = [
|
|
226 |
["husband", "wife"],
|
227 |
]
|
228 |
```
|
229 |
-
|
230 |
-
In
|
231 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
232 |
- and our outcome: the predicted gender of pronouns in the text.
|
233 |
|
234 |
Specifically we are seeing if making larger magnitude intervention: an older `DATE` in the text will result in a larger magnitude effect in the outcome: higher percentage of predicted female pronouns.
|
235 |
-
|
236 |
-
In the demo below you can select among 4 different fine-tuning methods:
|
237 |
-
- which, if any, conditioning variable was appended to the text.
|
238 |
-
|
239 |
-
And two different weighting schemes that were used in the loss function to nudge more toward the minority class in the dataset:
|
240 |
-
- female pronouns.
|
241 |
-
|
242 |
-
|
243 |
-
One trend that appears is: conditioning on `birth_date` metadata in both training and inference text has the largest dose-response relationship. This seems reasonable, as the fine-tuned model is able to ‘stratify’ a learned relationship between gender pronouns and dates, when both are present in the text.
|
244 |
|
|
|
245 |
While conditioning on either no metadata or `birth_place` data training, have similar middle-ground effects for this inference task.
|
246 |
-
|
247 |
Finally, conditioning on `name` metadata in training, (while again conditioning on `date` in inference) has almost no dose-response relationship. It appears the learning of a `name —> gender pronouns` relationship was sufficiently successful to overwhelm any potential more nuanced learning, such as that driven by `birth_date` or `place`.
|
248 |
"""
|
249 |
|
@@ -255,24 +306,30 @@ gr.Interface(
|
|
255 |
fn=predict_gender_pronouns,
|
256 |
inputs=[
|
257 |
gr.inputs.Number(
|
258 |
-
default=
|
259 |
label="Number of points (years) plotted -- select fewer if slow.",
|
260 |
),
|
261 |
gr.inputs.CheckboxGroup(
|
262 |
CONDITIONING_VARIABLES,
|
263 |
default=["none", "birth_date"],
|
264 |
type="value",
|
265 |
-
label="Pick
|
266 |
),
|
267 |
gr.inputs.CheckboxGroup(
|
268 |
FEMALE_WEIGHTS,
|
269 |
default=[5],
|
270 |
type="value",
|
271 |
-
label="Pick
|
|
|
|
|
|
|
|
|
|
|
|
|
272 |
),
|
273 |
gr.inputs.Textbox(
|
274 |
lines=7,
|
275 |
-
label="Input Text. Include one of more instance of the word 'DATE' below, to be replace with a range of dates in demo.",
|
276 |
default="Born DATE, she was a computer scientist. Her work was greatly respected, and she was well-regarded in her field.",
|
277 |
),
|
278 |
],
|
@@ -295,7 +352,7 @@ gr.Interface(
|
|
295 |
label="Precent pred male pronoun vs year, per model trained with conditioning and with weight for female preds",
|
296 |
),
|
297 |
],
|
298 |
-
title
|
299 |
-
description
|
300 |
-
article
|
301 |
-
).launch()
|
|
|
1 |
+
from typing import Optional
|
2 |
import gradio as gr
|
3 |
import torch
|
4 |
from transformers import AutoModelForTokenClassification, AutoTokenizer
|
5 |
+
from transformers import pipeline
|
6 |
import pandas as pd
|
7 |
import numpy as np
|
8 |
|
9 |
|
|
|
10 |
# Play with me, consts
|
11 |
CONDITIONING_VARIABLES = ["none", "birth_place", "birth_date", "name"]
|
12 |
FEMALE_WEIGHTS = [1.5, 5] # About 5x more male than female tokens in dataset
|
13 |
+
BERT_LIKE_MODELS = ["bert", "distilbert"]
|
14 |
|
15 |
# Internal consts
|
16 |
START_YEAR = 1800
|
|
|
46 |
models[(var, f_weight)] = AutoModelForTokenClassification.from_pretrained(
|
47 |
models_paths[(var, f_weight)]
|
48 |
)
|
49 |
+
for bert_like in BERT_LIKE_MODELS:
|
50 |
+
models_paths[(bert_like,)] = f"{bert_like}-base-uncased"
|
51 |
+
models[(bert_like,)] = pipeline("fill-mask", model=models_paths[(bert_like,)])
|
52 |
|
53 |
|
54 |
# Tokenizers same for each model, so just grabbing one of them
|
|
|
59 |
|
60 |
|
61 |
# more static stuff
|
62 |
+
gendered_lists = [
|
63 |
["he", "she"],
|
64 |
["him", "her"],
|
65 |
["his", "hers"],
|
|
|
68 |
["men", "women"],
|
69 |
["husband", "wife"],
|
70 |
]
|
71 |
+
male_gendered_tokens = [list[0] for list in gendered_lists]
|
72 |
+
female_gendered_tokens = [list[1] for list in gendered_lists]
|
73 |
+
|
74 |
+
male_gendered_token_ids = tokenizer.convert_tokens_to_ids(male_gendered_tokens)
|
75 |
+
female_gendered_token_ids = tokenizer.convert_tokens_to_ids(female_gendered_tokens)
|
76 |
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
assert tokenizer.unk_token_id not in male_gendered_token_ids
|
78 |
assert tokenizer.unk_token_id not in female_gendered_token_ids
|
79 |
|
|
|
135 |
|
136 |
# Run inference
|
137 |
def predict_gender_pronouns(
|
138 |
+
num_points, conditioning_variables, f_weights, bert_like_models, input_text
|
139 |
):
|
140 |
|
141 |
text_portions = input_text.split(SPLIT_KEY)
|
142 |
|
143 |
years = np.linspace(START_YEAR, STOP_YEAR, int(num_points)).astype(int)
|
144 |
+
num_preds = None
|
145 |
|
146 |
dfs = []
|
147 |
dfs.append(pd.DataFrame({"year": years}))
|
148 |
+
|
149 |
+
tokenized = {'ids':[], 'atten_mask':[], 'toks':[], 'labels':[]}
|
150 |
+
for b_date in years:
|
151 |
+
target_text = f"{b_date}".join(text_portions)
|
152 |
+
tokenized_sample = tokenize_and_append_metadata(
|
153 |
+
target_text,
|
154 |
+
tokenizer=tokenizer,
|
155 |
+
)
|
156 |
+
|
157 |
+
tokenized['ids'].append(tokenized_sample["input_ids"])
|
158 |
+
tokenized['atten_mask'].append(torch.tensor(tokenized_sample["attention_mask"]))
|
159 |
+
tokenized['toks'].append(tokenizer.convert_ids_to_tokens(tokenized_sample["input_ids"]))
|
160 |
+
tokenized['labels'].append(tokenized_sample["labels"])
|
161 |
+
|
162 |
for f_weight in f_weights:
|
163 |
for var in conditioning_variables:
|
164 |
prefix = f"w{f_weight}_{var}"
|
|
|
166 |
|
167 |
p_female = []
|
168 |
p_male = []
|
169 |
+
for year_idx in range(len(tokenized['ids'])):
|
170 |
+
ids = tokenized["ids"][year_idx]
|
171 |
+
atten_mask = tokenized["atten_mask"][year_idx]
|
172 |
+
labels = tokenized["labels"][year_idx]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
173 |
|
174 |
with torch.no_grad():
|
175 |
outputs = model(ids.unsqueeze(dim=0), atten_mask.unsqueeze(dim=0))
|
|
|
177 |
|
178 |
was_masked = labels.cpu() != -100
|
179 |
preds = torch.where(was_masked, preds, -100)
|
|
|
180 |
|
181 |
+
if not num_preds:
|
182 |
+
num_preds = torch.sum(was_masked).item()
|
183 |
+
|
184 |
+
p_female.append(len(torch.where(preds == 0)[0]) / num_preds * 100)
|
185 |
+
p_male.append(len(torch.where(preds == 1)[0]) / num_preds * 100)
|
186 |
|
187 |
dfs.append(pd.DataFrame({f"%f_{prefix}": p_female, f"%m_{prefix}": p_male}))
|
188 |
|
189 |
+
|
190 |
+
for bert_like in bert_like_models:
|
191 |
+
|
192 |
+
p_female = []
|
193 |
+
p_male = []
|
194 |
+
for year_idx in range(len(tokenized['ids'])):
|
195 |
+
toks = tokenized["toks"][year_idx]
|
196 |
+
target_text_for_bert = ' '.join(toks[1:-1] ) # Removing [CLS] and [SEP]
|
197 |
+
|
198 |
+
prefix = bert_like
|
199 |
+
model = models[(bert_like,)]
|
200 |
+
|
201 |
+
|
202 |
+
mask_filled_text = model(target_text_for_bert)
|
203 |
+
|
204 |
+
female_pronouns = [
|
205 |
+
1 if pronoun[0]["token_str"] in female_gendered_tokens else 0
|
206 |
+
for pronoun in mask_filled_text
|
207 |
+
]
|
208 |
+
male_pronouns = [
|
209 |
+
1 if pronoun[0]["token_str"] in male_gendered_tokens else 0
|
210 |
+
for pronoun in mask_filled_text
|
211 |
+
]
|
212 |
+
|
213 |
+
p_female.append(sum(female_pronouns) / num_preds * 100)
|
214 |
+
p_male.append(sum(male_pronouns) / num_preds * 100)
|
215 |
+
|
216 |
+
dfs.append(pd.DataFrame({f"%f_{prefix}": p_female, f"%m_{prefix}": p_male}))
|
217 |
+
|
218 |
+
|
219 |
results = pd.concat(dfs, axis=1).set_index("year")
|
220 |
|
221 |
female_df = results.filter(regex=".*f_")
|
|
|
234 |
female_df,
|
235 |
male_df_for_plot,
|
236 |
male_df,
|
237 |
+
)
|
238 |
|
239 |
|
240 |
title = "Changing Gender Pronouns"
|
241 |
+
description = """
|
242 |
+
<h2> Intro </h2>
|
243 |
+
This is a demo for a project exploring possible spurious correlations in training datasets that can be exploited and manipulated to achieve alternative outcomes. In this case, a user can demo what context changes will cause predicted gender pronouns to change, in a range of models.
|
244 |
+
|
245 |
+
In a user provided sentence, with at least one reference to a `DATE` and one gender pronoun, we will see how sweeping through a range of `DATE` values can change the predicted pronouns.
|
246 |
+
|
247 |
+
We see this in both the BERT base model and a model fine-tuned with a specific pronoun predicting task on the [wiki-bio](https://huggingface.co/datasets/wiki_bio) dataset.
|
248 |
+
|
249 |
+
One way to explain this phenomena is by looking at a likely data generating process for biographical-like data in both the main BERT training dataset as well as the `wiki_bio` dataset, in the form of a causal DAG.
|
250 |
|
251 |
+
<h2> Causal DAG </h2>
|
252 |
In the DAG, we can see that `birth_place`, `birth_date` and `gender` are all independent elements that have no common cause with the other covariates in the DAG. However `birth_place`, `birth_date` and `gender` may all have a role in causing one's `access_to_resources`, with the general trend that `access_to_resources` has become less gender-dependent over time, but not in every `birth_place`, with recent events in Afghanistan providing a stark counterexample to this trend. `access_to_resources` further determines how or if at all, you may appear in the dataset’s `context_words`.
|
253 |
|
254 |
We also argue that although there are complex causal interactions between words in a segment, the `context_words` are more likely to cause the `gender_pronouns`, rather than vice versa. For example, if the subject is a famous doctor and the object is her wealthy father, these context words will determine which person is being referred to, and thus which gendered-pronoun to use.
|
|
|
261 |
alt="DAG of possible data generating process for datasets used in training.">
|
262 |
</center>
|
263 |
|
264 |
+
Those familiar with causal DAGs may note when can simply condition on `gender` to block any confounding between the `context_words` and the `gender_pronouns`. However, this is not always possible, particularly in generative or mask-filling tasks, like those common in language models and in the demo below.
|
265 |
|
266 |
+
<h2> How to use this demo </h2>
|
267 |
+
In this demo, a user can add any sentence that contains at least one gender pronoun and the capitalized word `DATE`. We then sweep through a range of `date` values in the place of `DATE`, while masking (for prediction) the gender pronouns (included in the list below).
|
268 |
```
|
269 |
gendered_lists = [
|
270 |
['he', 'she'],
|
|
|
276 |
["husband", "wife"],
|
277 |
]
|
278 |
```
|
279 |
+
|
280 |
+
In addition to chosing the test sentence, we ask that you pick how the fine-tuned model was trained:
|
281 |
+
- conditioning variable: which, if any, conditioning variable from the three noted above in the DAG, was included in the text at train time.
|
282 |
+
- loss function weight: weight assigned to the minority class (female pronouns in this fine-tuning dataset) that was included in the text at train time.
|
283 |
+
|
284 |
+
|
285 |
+
|
286 |
+
|
287 |
+
|
288 |
+
<h2> What are the results</h2>
|
289 |
+
|
290 |
+
In the resulting plots, we can look for a dose-response relationship between:
|
291 |
+
- our treatment: the sample text,
|
292 |
- and our outcome: the predicted gender of pronouns in the text.
|
293 |
|
294 |
Specifically we are seeing if making larger magnitude intervention: an older `DATE` in the text will result in a larger magnitude effect in the outcome: higher percentage of predicted female pronouns.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
295 |
|
296 |
+
One trend that appears is: conditioning on `birth_date` metadata in both training and inference text has the largest dose-response relationship. This seems reasonable, as the fine-tuned model is able to 'stratify' a learned relationship between gender pronouns and dates, when both are present in the text.
|
297 |
While conditioning on either no metadata or `birth_place` data training, have similar middle-ground effects for this inference task.
|
|
|
298 |
Finally, conditioning on `name` metadata in training, (while again conditioning on `date` in inference) has almost no dose-response relationship. It appears the learning of a `name —> gender pronouns` relationship was sufficiently successful to overwhelm any potential more nuanced learning, such as that driven by `birth_date` or `place`.
|
299 |
"""
|
300 |
|
|
|
306 |
fn=predict_gender_pronouns,
|
307 |
inputs=[
|
308 |
gr.inputs.Number(
|
309 |
+
default=15,
|
310 |
label="Number of points (years) plotted -- select fewer if slow.",
|
311 |
),
|
312 |
gr.inputs.CheckboxGroup(
|
313 |
CONDITIONING_VARIABLES,
|
314 |
default=["none", "birth_date"],
|
315 |
type="value",
|
316 |
+
label="Pick conditioning variable included in text during fine-tuning.",
|
317 |
),
|
318 |
gr.inputs.CheckboxGroup(
|
319 |
FEMALE_WEIGHTS,
|
320 |
default=[5],
|
321 |
type="value",
|
322 |
+
label="Pick loss function weight placed on female predictions during fine-tuning.",
|
323 |
+
),
|
324 |
+
gr.inputs.CheckboxGroup(
|
325 |
+
BERT_LIKE_MODELS,
|
326 |
+
default=["bert"],
|
327 |
+
type="value",
|
328 |
+
label="Pick optional bert-like base uncased model for comparison.",
|
329 |
),
|
330 |
gr.inputs.Textbox(
|
331 |
lines=7,
|
332 |
+
label="Input Text. Include one of more instance of the word 'DATE' below, to be replace with a range of dates in demo.",
|
333 |
default="Born DATE, she was a computer scientist. Her work was greatly respected, and she was well-regarded in her field.",
|
334 |
),
|
335 |
],
|
|
|
352 |
label="Precent pred male pronoun vs year, per model trained with conditioning and with weight for female preds",
|
353 |
),
|
354 |
],
|
355 |
+
title=title,
|
356 |
+
description=description,
|
357 |
+
article=article,
|
358 |
+
).launch()
|