Files changed (4) hide show
  1. README.md +37 -0
  2. app.py +113 -28
  3. collect.py +35 -19
  4. requirements.txt +6 -3
README.md CHANGED
@@ -11,3 +11,40 @@ license: bigscience-bloom-rail-1.0
11
  ---
12
 
13
  A basic example of dynamic adversarial data collection with a Gradio app.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  ---
12
 
13
  A basic example of dynamic adversarial data collection with a Gradio app.
14
+
15
+ **Instructions for someone to use for their own project:**
16
+
17
+ *Setting up the Space*
18
+ 1. Clone this repo and deploy it on your own Hugging Face space.
19
+ 2. Add one of your Hugging Face tokens to the secrets for your space, with the
20
+ name `HF_TOKEN`. Now, create an empty Hugging Face dataset on the hub. Put
21
+ the url of this dataset in the secrets for your space, with the name
22
+ `DATASET_REPO_URL`. It can be a private or public dataset. When you run this
23
+ space on mturk and when people visit your space on huggingface.co, the app
24
+ will use your token to automatically store new HITs in your dataset. NOTE:
25
+ if you push something to your dataset manually, you need to reboot your space
26
+ or it could get merge conflicts when trying to push HIT data.
27
+
28
+ *Running Data Collection*
29
+ 1. On your local repo that you pulled, create a copy of `config.py.example`,
30
+ just called `config.py`. Now, put keys from your AWS account in `config.py`.
31
+ These keys should be for an AWS account that has the
32
+ AmazonMechanicalTurkFullAccess permission. You also need to
33
+ create an mturk requestor account associated with your AWS account.
34
+ 2. Run `python collect.py` locally.
35
+
36
+ *Profit*
37
+ Now, you should be watching hits come into your Hugging Face dataset
38
+ automatically!
39
+
40
+ *Tips and Tricks*
41
+ - If you are developing and running this space locally to test it out, try
42
+ deleting the data directory that the app clones before running the app again.
43
+ Otherwise, the app could get merge conflicts when storing new HITs on the hub.
44
+ When you redeploy your app on Hugging Face spaces, the data directory is deleted
45
+ automatically.
46
+ - huggingface spaces have limited computational resources and memory. If you
47
+ run too many HITs and/or assignments at once, then you could encounter issues.
48
+ You could also encounter issues if you are trying to create a dataset that is
49
+ very large. Check the log of your space for any errors that could be happening.
50
+
app.py CHANGED
@@ -1,13 +1,30 @@
1
  # Basic example for doing model-in-the-loop dynamic adversarial data collection
2
  # using Gradio Blocks.
3
-
4
  import random
5
  from urllib.parse import parse_qs
6
 
7
  import gradio as gr
8
  import requests
9
  from transformers import pipeline
10
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  pipe = pipeline("sentiment-analysis")
12
 
13
  demo = gr.Blocks()
@@ -16,9 +33,9 @@ with demo:
16
  total_cnt = 2 # How many examples per HIT
17
  dummy = gr.Textbox(visible=False) # dummy for passing assignmentId
18
 
19
- # We keep track of state as a Variable
20
- state_dict = {"assignmentId": "", "cnt": 0, "fooled": 0, "data": [], "metadata": {}}
21
- state = gr.Variable(state_dict)
22
 
23
  gr.Markdown("# DADC in Gradio example")
24
  gr.Markdown("Try to fool the model and find an example where it predicts the wrong label!")
@@ -27,26 +44,41 @@ with demo:
27
 
28
  # Generate model prediction
29
  # Default model: distilbert-base-uncased-finetuned-sst-2-english
30
- def _predict(txt, tgt, state):
31
  pred = pipe(txt)[0]
32
  other_label = 'negative' if pred['label'].lower() == "positive" else "positive"
33
  pred_confidences = {pred['label'].lower(): pred['score'], other_label: 1 - pred['score']}
34
 
35
  pred["label"] = pred["label"].title()
36
  ret = f"Target: **{tgt}**. Model prediction: **{pred['label']}**\n\n"
37
- if pred["label"] != tgt:
38
- state["fooled"] += 1
 
39
  ret += " You fooled the model! Well done!"
40
  else:
41
  ret += " You did not fool the model! Too bad, try again!"
42
- state["data"].append(ret)
43
  state["cnt"] += 1
44
 
45
  done = state["cnt"] == total_cnt
46
- toggle_final_submit = gr.update(visible=done)
47
  toggle_example_submit = gr.update(visible=not done)
48
- new_state_md = f"State: {state['cnt']}/{total_cnt} ({state['fooled']} fooled)"
49
- return pred_confidences, ret, state, toggle_example_submit, toggle_final_submit, new_state_md
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
  # Input fields
52
  text_input = gr.Textbox(placeholder="Enter model-fooling statement", show_label=False)
@@ -59,28 +91,81 @@ with demo:
59
  submit_ex_button = gr.Button("Submit")
60
  with gr.Column(visible=False) as final_submit:
61
  submit_hit_button = gr.Button("Submit HIT")
62
-
63
- # Submit state to MTurk backend for ExternalQuestion
64
- # Update the URL below to switch from Sandbox to real data collection
65
- def _submit(state, dummy):
66
- query = parse_qs(dummy[1:])
67
- assert "assignmentId" in query, "No assignment ID provided, unable to submit"
68
- state["assignmentId"] = query["assignmentId"]
69
- url = "https://workersandbox.mturk.com/mturk/externalSubmit"
70
- return requests.post(url, data=state)
 
 
 
 
 
 
 
 
 
 
71
 
72
  # Button event handlers
 
 
 
 
 
 
73
  submit_ex_button.click(
74
  _predict,
75
- inputs=[text_input, label_input, state],
76
- outputs=[label_output, text_output, state, example_submit, final_submit, state_display],
 
77
  )
78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  submit_hit_button.click(
80
- _submit,
81
- inputs=[state, dummy],
82
- outputs=None,
83
- _js="function(state, dummy) { return [state, window.location.search]; }",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  )
85
 
86
- demo.launch(favicon_path="https://huggingface.co/favicon.ico")
 
1
  # Basic example for doing model-in-the-loop dynamic adversarial data collection
2
  # using Gradio Blocks.
3
+ import os
4
  import random
5
  from urllib.parse import parse_qs
6
 
7
  import gradio as gr
8
  import requests
9
  from transformers import pipeline
10
+ from huggingface_hub import Repository
11
+ from dotenv import load_dotenv
12
+ from pathlib import Path
13
+ import json
14
+ from filelock import FileLock
15
+
16
+ # These variables are for storing the mturk HITs in a Hugging Face dataset.
17
+ if Path(".env").is_file():
18
+ load_dotenv(".env")
19
+ DATASET_REPO_URL = os.getenv("DATASET_REPO_URL")
20
+ HF_TOKEN = os.getenv("HF_TOKEN")
21
+ DATA_FILENAME = "data.jsonl"
22
+ DATA_FILE = os.path.join("data", DATA_FILENAME)
23
+ repo = Repository(
24
+ local_dir="data", clone_from=DATASET_REPO_URL, use_auth_token=HF_TOKEN
25
+ )
26
+
27
+ # Now let's run the app!
28
  pipe = pipeline("sentiment-analysis")
29
 
30
  demo = gr.Blocks()
 
33
  total_cnt = 2 # How many examples per HIT
34
  dummy = gr.Textbox(visible=False) # dummy for passing assignmentId
35
 
36
+ # We keep track of state as a JSON
37
+ state_dict = {"assignmentId": "", "cnt": 0, "cnt_fooled": 0, "data": []}
38
+ state = gr.JSON(state_dict, visible=False)
39
 
40
  gr.Markdown("# DADC in Gradio example")
41
  gr.Markdown("Try to fool the model and find an example where it predicts the wrong label!")
 
44
 
45
  # Generate model prediction
46
  # Default model: distilbert-base-uncased-finetuned-sst-2-english
47
+ def _predict(txt, tgt, state, dummy):
48
  pred = pipe(txt)[0]
49
  other_label = 'negative' if pred['label'].lower() == "positive" else "positive"
50
  pred_confidences = {pred['label'].lower(): pred['score'], other_label: 1 - pred['score']}
51
 
52
  pred["label"] = pred["label"].title()
53
  ret = f"Target: **{tgt}**. Model prediction: **{pred['label']}**\n\n"
54
+ fooled = pred["label"] != tgt
55
+ if fooled:
56
+ state["cnt_fooled"] += 1
57
  ret += " You fooled the model! Well done!"
58
  else:
59
  ret += " You did not fool the model! Too bad, try again!"
 
60
  state["cnt"] += 1
61
 
62
  done = state["cnt"] == total_cnt
 
63
  toggle_example_submit = gr.update(visible=not done)
64
+ new_state_md = f"State: {state['cnt']}/{total_cnt} ({state['cnt_fooled']} fooled)"
65
+
66
+ state["data"].append({"cnt": state["cnt"], "text": txt, "target": tgt.lower(), "model_pred": pred["label"].lower(), "fooled": fooled})
67
+
68
+ query = parse_qs(dummy[1:])
69
+ if "assignmentId" in query and query["assignmentId"][0] != "ASSIGNMENT_ID_NOT_AVAILABLE":
70
+ # It seems that someone is using this app on mturk. We need to
71
+ # store the assignmentId in the state before submit_hit_button
72
+ # is clicked. We can do this here in _predict. We need to save the
73
+ # assignmentId so that the turker can get credit for their HIT.
74
+ state["assignmentId"] = query["assignmentId"][0]
75
+ toggle_final_submit = gr.update(visible=done)
76
+ toggle_final_submit_preview = gr.update(visible=False)
77
+ else:
78
+ toggle_final_submit_preview = gr.update(visible=done)
79
+ toggle_final_submit = gr.update(visible=False)
80
+
81
+ return pred_confidences, ret, state, toggle_example_submit, toggle_final_submit, toggle_final_submit_preview, new_state_md, dummy
82
 
83
  # Input fields
84
  text_input = gr.Textbox(placeholder="Enter model-fooling statement", show_label=False)
 
91
  submit_ex_button = gr.Button("Submit")
92
  with gr.Column(visible=False) as final_submit:
93
  submit_hit_button = gr.Button("Submit HIT")
94
+ with gr.Column(visible=False) as final_submit_preview:
95
+ submit_hit_button_preview = gr.Button("Submit Work (preview mode; no mturk HIT credit)")
96
+
97
+ # Store the HIT data into a Hugging Face dataset.
98
+ # The HIT is also stored and logged on mturk when post_hit_js is run below.
99
+ # This _store_in_huggingface_dataset function just demonstrates how easy it is
100
+ # to automatically create a Hugging Face dataset from mturk.
101
+ def _store_in_huggingface_dataset(state):
102
+ lock = FileLock(DATA_FILE + ".lock")
103
+ lock.acquire()
104
+ try:
105
+ with open(DATA_FILE, "a") as jsonlfile:
106
+ json_data_with_assignment_id =\
107
+ [json.dumps(dict({"assignmentId": state["assignmentId"]}, **datum)) for datum in state["data"]]
108
+ jsonlfile.write("\n".join(json_data_with_assignment_id) + "\n")
109
+ repo.push_to_hub()
110
+ finally:
111
+ lock.release()
112
+ return state
113
 
114
  # Button event handlers
115
+ get_window_location_search_js = """
116
+ function(text_input, label_input, state, dummy) {
117
+ return [text_input, label_input, state, window.location.search];
118
+ }
119
+ """
120
+
121
  submit_ex_button.click(
122
  _predict,
123
+ inputs=[text_input, label_input, state, dummy],
124
+ outputs=[label_output, text_output, state, example_submit, final_submit, final_submit_preview, state_display, dummy],
125
+ _js=get_window_location_search_js,
126
  )
127
 
128
+ post_hit_js = """
129
+ function(state) {
130
+ // If there is an assignmentId, then the submitter is on mturk
131
+ // and has accepted the HIT. So, we need to submit their HIT.
132
+ const form = document.createElement('form');
133
+ form.action = 'https://workersandbox.mturk.com/mturk/externalSubmit';
134
+ form.method = 'post';
135
+ for (const key in state) {
136
+ const hiddenField = document.createElement('input');
137
+ hiddenField.type = 'hidden';
138
+ hiddenField.name = key;
139
+ hiddenField.value = state[key];
140
+ form.appendChild(hiddenField);
141
+ };
142
+ document.body.appendChild(form);
143
+ form.submit();
144
+ return state;
145
+ }
146
+ """
147
+
148
  submit_hit_button.click(
149
+ _store_in_huggingface_dataset,
150
+ inputs=[state],
151
+ outputs=[state],
152
+ _js=post_hit_js,
153
+ )
154
+
155
+ refresh_app_js = """
156
+ function(state) {
157
+ // The following line here loads the app again so the user can
158
+ // enter in another preview-mode "HIT".
159
+ window.location.href = window.location.href;
160
+ return state;
161
+ }
162
+ """
163
+
164
+ submit_hit_button_preview.click(
165
+ _store_in_huggingface_dataset,
166
+ inputs=[state],
167
+ outputs=[state],
168
+ _js=refresh_app_js,
169
  )
170
 
171
+ demo.launch()
collect.py CHANGED
@@ -5,36 +5,52 @@ import boto3
5
  from boto.mturk.question import ExternalQuestion
6
 
7
  from config import MTURK_KEY, MTURK_SECRET
 
8
 
9
- MTURK_REGION = "us-east-1"
10
- MTURK_SANDBOX = "https://mturk-requester-sandbox.us-east-1.amazonaws.com"
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  mturk = boto3.client(
13
  "mturk",
14
  aws_access_key_id=MTURK_KEY,
15
  aws_secret_access_key=MTURK_SECRET,
16
- region_name=MTURK_REGION,
17
- endpoint_url=MTURK_SANDBOX,
18
  )
19
 
20
- # The + in the URL makes the Space easily embeddable in an iframe
21
- question = ExternalQuestion(
22
- "https://huggingface.co/spaces/douwekiela/dadc/+", frame_height=600
23
  )
24
 
25
- new_hit = mturk.create_hit(
26
- Title="DADC with Gradio",
27
- Description="Hello world",
28
- Keywords="fool the model",
29
- Reward="0.15",
30
- MaxAssignments=1,
31
- LifetimeInSeconds=172800,
32
- AssignmentDurationInSeconds=600,
33
- AutoApprovalDelayInSeconds=14400,
34
- Question=question.get_as_xml(),
35
- )
 
36
 
37
  print(
38
- "Sandbox link: https://workersandbox.mturk.com/mturk/preview?groupId="
39
  + new_hit["HIT"]["HITGroupId"]
40
  )
 
 
5
  from boto.mturk.question import ExternalQuestion
6
 
7
  from config import MTURK_KEY, MTURK_SECRET
8
+ import argparse
9
 
10
+ parser = argparse.ArgumentParser()
11
+ parser.add_argument("--mturk_region", default="us-east-1", help="The region for mturk (default: us-east-1)")
12
+ parser.add_argument("--space_name", default="Tristan/dadc", help="Name of the accompanying Hugging Face space (default: Tristan/dadc)")
13
+ parser.add_argument("--num_hits", type=int, default=5, help="The number of HITs.")
14
+ parser.add_argument("--num_assignments", type=int, default=1, help="The number of times that the HIT can be accepted and completed.")
15
+ parser.add_argument("--live_mode", action="store_true", help="""
16
+ Whether to run in live mode with real turkers. This will charge your account money.
17
+ If you don't use this flag, the HITs will be deployed on the sandbox version of mturk,
18
+ which will not charge your account money.
19
+ """
20
+ )
21
+
22
+ args = parser.parse_args()
23
+
24
+ MTURK_URL = f"https://mturk-requester{'' if args.live_mode else '-sandbox'}.{args.mturk_region}.amazonaws.com"
25
 
26
  mturk = boto3.client(
27
  "mturk",
28
  aws_access_key_id=MTURK_KEY,
29
  aws_secret_access_key=MTURK_SECRET,
30
+ region_name=args.mturk_region,
31
+ endpoint_url=MTURK_URL,
32
  )
33
 
34
+ # This is the URL that makes the space embeddable in an mturk iframe
35
+ question = ExternalQuestion(f"https://hf.space/embed/{args.space_name}/+?__theme=light",
36
+ frame_height=600
37
  )
38
 
39
+ for i in range(args.num_hits):
40
+ new_hit = mturk.create_hit(
41
+ Title="Beat the AI",
42
+ Description="Try to fool an AI by creating examples that it gets wrong",
43
+ Keywords="fool the model",
44
+ Reward="0.15",
45
+ MaxAssignments=args.num_assignments,
46
+ LifetimeInSeconds=172800,
47
+ AssignmentDurationInSeconds=600,
48
+ AutoApprovalDelayInSeconds=14400,
49
+ Question=question.get_as_xml(),
50
+ )
51
 
52
  print(
53
+ f"HIT Group Link: https://worker{'' if args.live_mode else 'sandbox'}.mturk.com/mturk/preview?groupId="
54
  + new_hit["HIT"]["HITGroupId"]
55
  )
56
+
requirements.txt CHANGED
@@ -1,3 +1,6 @@
1
- requests
2
- torch
3
- transformers
 
 
 
 
1
+ torch==1.12.0
2
+ transformers==4.20.1
3
+ gradio==3.0.26
4
+ boto3==1.24.32
5
+ huggingface_hub==0.8.1
6
+ python-dotenv==0.20.0