jwkirchenbauer commited on
Commit
b5b3015
1 Parent(s): 02d9c9c

a version with toggles

Browse files
Files changed (2) hide show
  1. app.py +3 -2
  2. demo_watermark.py +313 -210
app.py CHANGED
@@ -25,6 +25,7 @@ arg_dict = {
25
  'max_new_tokens': 200,
26
  'generation_seed': 123,
27
  'use_sampling': True,
 
28
  'sampling_temp': 0.7,
29
  'use_gpu': True,
30
  'seeding_scheme': 'markov_1',
@@ -33,11 +34,11 @@ arg_dict = {
33
  'normalizers': '',
34
  'ignore_repeated_bigrams': False,
35
  'detection_z_threshold': 4.0,
36
- 'select_green_tokens': True
 
37
  }
38
 
39
  args.__dict__.update(arg_dict)
40
- print(args)
41
 
42
  from demo_watermark import main
43
 
 
25
  'max_new_tokens': 200,
26
  'generation_seed': 123,
27
  'use_sampling': True,
28
+ 'n_beams': 1,
29
  'sampling_temp': 0.7,
30
  'use_gpu': True,
31
  'seeding_scheme': 'markov_1',
 
34
  'normalizers': '',
35
  'ignore_repeated_bigrams': False,
36
  'detection_z_threshold': 4.0,
37
+ 'select_green_tokens': True,
38
+ 'skip_model_load': False,
39
  }
40
 
41
  args.__dict__.update(arg_dict)
 
42
 
43
  from demo_watermark import main
44
 
demo_watermark.py CHANGED
@@ -16,9 +16,13 @@
16
 
17
  import os
18
  import argparse
 
19
  from pprint import pprint
20
  from functools import partial
21
 
 
 
 
22
  import torch
23
 
24
  from transformers import (AutoTokenizer,
@@ -45,8 +49,8 @@ def parse_args():
45
  parser.add_argument(
46
  "--run_gradio",
47
  type=str2bool,
48
- default=False,
49
- help="Whether to launch as a gradio demo.",
50
  )
51
  parser.add_argument(
52
  "--demo_public",
@@ -90,6 +94,12 @@ def parse_args():
90
  default=0.7,
91
  help="Sampling temperature to use when generating using multinomial sampling.",
92
  )
 
 
 
 
 
 
93
  parser.add_argument(
94
  "--use_gpu",
95
  type=str2bool,
@@ -138,17 +148,21 @@ def parse_args():
138
  default=True,
139
  help="How to treat the permuation when selecting the greenlist tokens at each step. Legacy is (False) to pick the complement/reds first.",
140
  )
 
 
 
 
 
 
141
  args = parser.parse_args()
142
  return args
143
 
144
-
145
- def main(args):
146
-
147
- is_seq2seq_model = any([(model_type in args.model_name_or_path) for model_type in ["t5","T0"]])
148
- is_decoder_only_model = any([(model_type in args.model_name_or_path) for model_type in ["gpt","opt","bloom"]])
149
- if is_seq2seq_model:
150
  model = AutoModelForSeq2SeqLM.from_pretrained(args.model_name_or_path)
151
- elif is_decoder_only_model:
152
  model = AutoModelForCausalLM.from_pretrained(args.model_name_or_path)
153
  else:
154
  raise ValueError(f"Unknown model type: {args.model_name_or_path}")
@@ -161,213 +175,302 @@ def main(args):
161
  model.eval()
162
 
163
  tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)
164
- vocabulary = list(tokenizer.get_vocab().values())
165
-
166
- def generate(prompt):
167
-
168
- watermark_processor = WatermarkLogitsProcessor(vocab=vocabulary,
169
- gamma=args.gamma,
170
- delta=args.delta,
171
- seeding_scheme=args.seeding_scheme,
172
- select_green_tokens=args.select_green_tokens)
173
-
174
- gen_kwargs = dict(max_new_tokens=args.max_new_tokens)
175
-
176
- if args.use_sampling:
177
- gen_kwargs.update(dict(
178
- do_sample=True,
179
- top_k=0,
180
- temperature=args.sampling_temp
181
- ))
182
- else:
183
- gen_kwargs.update(dict(
184
- num_beams=args.n_beams
185
- ))
186
-
187
- generate_without_watermark = partial(
188
- model.generate,
189
- **gen_kwargs
190
- )
191
- generate_with_watermark = partial(
192
- model.generate,
193
- logits_processor=LogitsProcessorList([watermark_processor]),
194
- **gen_kwargs
195
- )
196
- if args.prompt_max_length:
197
- pass
198
- elif hasattr(model.config,"max_position_embedding"):
199
- args.prompt_max_length = model.config.max_position_embeddings-args.max_new_tokens
200
- else:
201
- args.prompt_max_length = 2048-args.max_new_tokens
202
-
203
- tokd_input = tokenizer(prompt, return_tensors="pt", add_special_tokens=True, truncation=True, max_length=args.prompt_max_length).to(device)
204
- truncation_warning = True if tokd_input["input_ids"].shape[-1] == args.prompt_max_length else False
205
- redecoded_input = tokenizer.batch_decode(tokd_input["input_ids"], skip_special_tokens=True)[0]
206
-
207
- torch.manual_seed(args.generation_seed)
208
- output_without_watermark = generate_without_watermark(**tokd_input)
209
- # torch.manual_seed(seed) # optional, but will not be the same again generally, unless delta==0.0, no-op watermark
210
- output_with_watermark = generate_with_watermark(**tokd_input)
211
-
212
- if is_decoder_only_model:
213
- # need to isolate the newly generated tokens
214
- output_without_watermark = output_without_watermark[:,tokd_input["input_ids"].shape[-1]:]
215
- output_with_watermark = output_with_watermark[:,tokd_input["input_ids"].shape[-1]:]
216
-
217
- decoded_output_without_watermark = tokenizer.batch_decode(output_without_watermark, skip_special_tokens=True)[0]
218
- decoded_output_with_watermark = tokenizer.batch_decode(output_with_watermark, skip_special_tokens=True)[0]
219
-
220
- return (redecoded_input,
221
- int(truncation_warning),
222
- decoded_output_without_watermark,
223
- decoded_output_with_watermark)
224
- # decoded_output_with_watermark)
225
-
226
- def detect(input_text):
227
- watermark_detector = WatermarkDetector(vocab=list(tokenizer.get_vocab().values()),
228
- gamma=args.gamma,
229
- seeding_scheme=args.seeding_scheme,
230
- device=device,
231
- tokenizer=tokenizer,
232
- z_threshold=args.detection_z_threshold,
233
- normalizers=(args.normalizers.split(",") if args.normalizers else []),
234
- ignore_repeated_bigrams=args.ignore_repeated_bigrams,
235
- select_green_tokens=args.select_green_tokens)
236
- if len(input_text)-1 > watermark_detector.min_prefix_len:
237
- score_dict = watermark_detector.detect(input_text)
238
- output_str = (f"Detection result @ {watermark_detector.z_threshold}:\n"
239
- f"{score_dict}")
240
- else:
241
- output_str = (f"Error: string not long enough to compute watermark presence.")
242
- return output_str
243
 
244
- # Generate and detect, report to stdout
245
 
246
- # input_text = (
247
- # "The diamondback terrapin or simply terrapin (Malaclemys terrapin) is a "
248
- # "species of turtle native to the brackish coastal tidal marshes of the "
249
- # "Northeastern and southern United States, and in Bermuda.[6] It belongs "
250
- # "to the monotypic genus Malaclemys. It has one of the largest ranges of "
251
- # "all turtles in North America, stretching as far south as the Florida Keys "
252
- # "and as far north as Cape Cod.[7] The name 'terrapin' is derived from the "
253
- # "Algonquian word torope.[8] It applies to Malaclemys terrapin in both "
254
- # "British English and American English. The name originally was used by "
255
- # "early European settlers in North America to describe these brackish-water "
256
- # "turtles that inhabited neither freshwater habitats nor the sea. It retains "
257
- # "this primary meaning in American English.[8] In British English, however, "
258
- # "other semi-aquatic turtle species, such as the red-eared slider, might "
259
- # "also be called terrapins. The common name refers to the diamond pattern "
260
- # "on top of its shell (carapace), but the overall pattern and coloration "
261
- # "vary greatly. The shell is usually wider at the back than in the front, "
262
- # "and from above it appears wedge-shaped. The shell coloring can vary "
263
- # "from brown to grey, and its body color can be grey, brown, yellow, "
264
- # "or white. All have a unique pattern of wiggly, black markings or spots "
265
- # "on their body and head. The diamondback terrapin has large webbed "
266
- # "feet.[9] The species is"
267
- # )
268
-
269
- input_text = "In this work, we study watermarking of language model output. A watermark is a hidden pattern in text that is imperceptible to humans, while making the text algorithmically identifiable as synthetic. We propose an efficient watermark that makes synthetic text detectable from short spans of tokens (as few as 25 words), while false-positives (where human text is marked as machine-generated) are statistically improbable. The watermark detection algorithm can be made public, enabling third parties (e.g., social media platforms) to run it themselves, or it can be kept private and run behind an API. We seek a watermark with the following properties:\n"
270
-
271
-
272
- term_width = 80
273
- print("#"*term_width)
274
- print("Prompt:")
275
- print(input_text)
276
-
277
- _, _, decoded_output_without_watermark, decoded_output_with_watermark = generate(input_text)
278
- without_watermark_detection_result = detect(decoded_output_without_watermark)
279
- with_watermark_detection_result = detect(decoded_output_with_watermark)
280
-
281
- print("#"*term_width)
282
- print("Output without watermark:")
283
- print(decoded_output_without_watermark)
284
- print("-"*term_width)
285
- print(f"Detection result @ {args.detection_z_threshold}:")
286
- pprint(without_watermark_detection_result)
287
- print("-"*term_width)
288
-
289
- print("#"*term_width)
290
- print("Output with watermark:")
291
- print(decoded_output_with_watermark)
292
- print("-"*term_width)
293
- print(f"Detection result @ {args.detection_z_threshold}:")
294
- pprint(with_watermark_detection_result)
295
- print("-"*term_width)
296
 
297
- # Launch the app to generate and detect interactively (implements the hf space demo)
298
 
299
- if args.run_gradio:
300
- import gradio as gr
301
-
302
- with gr.Blocks() as demo:
303
- gr.Markdown("## Demo for ['A Watermark for Large Language Models'](https://arxiv.org/abs/2301.10226)")
304
- # gr.HTML("""
305
- # <p>For faster inference without waiting in queue, you may duplicate the space and upgrade to GPU in settings.
306
- # <br/>
307
- # <a href="https://huggingface.co/spaces/tomg-group-umd/pez-dispenser?duplicate=true">
308
- # <img style="margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>
309
- # <p/>
310
- # """)
311
- gr.Markdown(f"#### Generation and Watermarking Parameters:\n\n{args.__dict__}")
312
-
313
- with gr.Tab("Generation"):
314
- with gr.Row():
315
- prompt = gr.Textbox(label=f"Prompt (max {args.prompt_max_length} tokens)", interactive=True)
316
- with gr.Row():
317
- generate_btn = gr.Button("Generate")
318
- with gr.Row():
319
- with gr.Column(scale=2):
320
- output_without_watermark = gr.Textbox(label="Output Without Watermark", interactive=False)
321
- with gr.Column(scale=1):
322
- without_watermark_detection_result = gr.Textbox(label="Detection Result", interactive=False)
323
- with gr.Row():
324
- with gr.Column(scale=2):
325
- output_with_watermark = gr.Textbox(label="Output With Watermark", interactive=False)
326
- with gr.Column(scale=1):
327
- with_watermark_detection_result = gr.Textbox(label="Detection Result", interactive=False)
328
-
329
-
330
- redecoded_input = gr.Textbox(visible=False)
331
- truncation_warning = gr.Number(visible=False)
332
- def truncate_prompt(redecoded_input, truncation_warning, orig_prompt):
333
- if truncation_warning:
334
- return redecoded_input + f"\n\n[Prompt was truncated before generation due to length...]"
335
- else:
336
- return orig_prompt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
 
338
- generate_btn.click(fn=generate, inputs=[prompt], outputs=[redecoded_input, truncation_warning, output_without_watermark, output_with_watermark])
339
 
340
- # Show truncated version of prompt if truncation occurred
341
- redecoded_input.change(fn=truncate_prompt, inputs=[redecoded_input,truncation_warning,prompt], outputs=[prompt])
342
-
343
- # Call detection when the outputs of the generate function are updated.
344
- output_without_watermark.change(fn=detect, inputs=output_without_watermark, outputs=without_watermark_detection_result)
345
- output_with_watermark.change(fn=detect, inputs=output_with_watermark, outputs=with_watermark_detection_result)
346
-
347
- with gr.Tab("Detector Only"):
348
- with gr.Row():
349
- detection_input = gr.Textbox(label="Text to Analyze", interactive=True)
350
- with gr.Row():
351
- detect_btn = gr.Button("Detect")
352
- with gr.Row():
353
- detection_result = gr.Textbox(label="Detection Result", interactive=False)
354
- detect_btn.click(fn=detect, inputs=detection_input, outputs=detection_result)
355
-
356
- with gr.Accordion("A note on model capability",open=False):
357
- gr.Markdown(
358
- """
359
- The models that can be used in this demo are limited to those that are open source as well as fit on a single commodity GPU. In particular, there are few models above 10B parameters and way fewer trained using both Instruction finetuning or RLHF that are open source that we can use.
360
-
361
- Therefore, the model, in both it's un-watermarked (normal) and watermarked state, is not generally able to respond well to the kinds of prompts that a 100B+ Instruction and RLHF tuned model such as ChatGPT, Claude, or Bard is.
362
-
363
- We suggest you try prompts that give the model a few sentences and then allow it to 'continue' the prompt, as these weaker models are more capable in this simpler language modeling setting.
364
- """
365
- )
366
-
367
- if args.demo_public:
368
- demo.launch(share=True) # exposes app to the internet via randomly generated link
369
- else:
370
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371
 
372
  return
373
 
 
16
 
17
  import os
18
  import argparse
19
+ from argparse import Namespace
20
  from pprint import pprint
21
  from functools import partial
22
 
23
+ import numpy # for gradio hot reload
24
+ import gradio as gr
25
+
26
  import torch
27
 
28
  from transformers import (AutoTokenizer,
 
49
  parser.add_argument(
50
  "--run_gradio",
51
  type=str2bool,
52
+ default=True,
53
+ help="Whether to launch as a gradio demo. Set to False if not installed and want to just run the stdout version.",
54
  )
55
  parser.add_argument(
56
  "--demo_public",
 
94
  default=0.7,
95
  help="Sampling temperature to use when generating using multinomial sampling.",
96
  )
97
+ parser.add_argument(
98
+ "--n_beams",
99
+ type=int,
100
+ choices=[1,4,8],
101
+ help="Number of beams to use for beam search. 1 is normal greedy decoding",
102
+ )
103
  parser.add_argument(
104
  "--use_gpu",
105
  type=str2bool,
 
148
  default=True,
149
  help="How to treat the permuation when selecting the greenlist tokens at each step. Legacy is (False) to pick the complement/reds first.",
150
  )
151
+ parser.add_argument(
152
+ "--skip_model_load",
153
+ type=str2bool,
154
+ default=False,
155
+ help="Skip the model loading to debug the interface.",
156
+ )
157
  args = parser.parse_args()
158
  return args
159
 
160
+ def load_model():
161
+ args.is_seq2seq_model = any([(model_type in args.model_name_or_path) for model_type in ["t5","T0"]])
162
+ args.is_decoder_only_model = any([(model_type in args.model_name_or_path) for model_type in ["gpt","opt","bloom"]])
163
+ if args.is_seq2seq_model:
 
 
164
  model = AutoModelForSeq2SeqLM.from_pretrained(args.model_name_or_path)
165
+ elif args.is_decoder_only_model:
166
  model = AutoModelForCausalLM.from_pretrained(args.model_name_or_path)
167
  else:
168
  raise ValueError(f"Unknown model type: {args.model_name_or_path}")
 
175
  model.eval()
176
 
177
  tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
+ return model, tokenizer, device
180
 
181
+ def generate(prompt, args, model=None, tokenizer=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
 
183
+ print(f"Generating with {args}")
184
 
185
+ watermark_processor = WatermarkLogitsProcessor(vocab=list(tokenizer.get_vocab().values()),
186
+ gamma=args.gamma,
187
+ delta=args.delta,
188
+ seeding_scheme=args.seeding_scheme,
189
+ select_green_tokens=args.select_green_tokens)
190
+
191
+ gen_kwargs = dict(max_new_tokens=args.max_new_tokens)
192
+
193
+ if args.use_sampling:
194
+ gen_kwargs.update(dict(
195
+ do_sample=True,
196
+ top_k=0,
197
+ temperature=args.sampling_temp
198
+ ))
199
+ else:
200
+ gen_kwargs.update(dict(
201
+ num_beams=args.n_beams
202
+ ))
203
+
204
+ generate_without_watermark = partial(
205
+ model.generate,
206
+ **gen_kwargs
207
+ )
208
+ generate_with_watermark = partial(
209
+ model.generate,
210
+ logits_processor=LogitsProcessorList([watermark_processor]),
211
+ **gen_kwargs
212
+ )
213
+ if args.prompt_max_length:
214
+ pass
215
+ elif hasattr(model.config,"max_position_embedding"):
216
+ args.prompt_max_length = model.config.max_position_embeddings-args.max_new_tokens
217
+ else:
218
+ args.prompt_max_length = 2048-args.max_new_tokens
219
+
220
+ tokd_input = tokenizer(prompt, return_tensors="pt", add_special_tokens=True, truncation=True, max_length=args.prompt_max_length).to(device)
221
+ truncation_warning = True if tokd_input["input_ids"].shape[-1] == args.prompt_max_length else False
222
+ redecoded_input = tokenizer.batch_decode(tokd_input["input_ids"], skip_special_tokens=True)[0]
223
+
224
+ torch.manual_seed(args.generation_seed)
225
+ output_without_watermark = generate_without_watermark(**tokd_input)
226
+ # torch.manual_seed(seed) # optional, but will not be the same again generally, unless delta==0.0, no-op watermark
227
+ output_with_watermark = generate_with_watermark(**tokd_input)
228
+
229
+ if args.is_decoder_only_model:
230
+ # need to isolate the newly generated tokens
231
+ output_without_watermark = output_without_watermark[:,tokd_input["input_ids"].shape[-1]:]
232
+ output_with_watermark = output_with_watermark[:,tokd_input["input_ids"].shape[-1]:]
233
+
234
+ decoded_output_without_watermark = tokenizer.batch_decode(output_without_watermark, skip_special_tokens=True)[0]
235
+ decoded_output_with_watermark = tokenizer.batch_decode(output_with_watermark, skip_special_tokens=True)[0]
236
+
237
+ return (redecoded_input,
238
+ int(truncation_warning),
239
+ decoded_output_without_watermark,
240
+ decoded_output_with_watermark,
241
+ args)
242
+ # decoded_output_with_watermark)
243
+
244
+ def detect(input_text, args, device=None, tokenizer=None):
245
+ watermark_detector = WatermarkDetector(vocab=list(tokenizer.get_vocab().values()),
246
+ gamma=args.gamma,
247
+ seeding_scheme=args.seeding_scheme,
248
+ device=device,
249
+ tokenizer=tokenizer,
250
+ z_threshold=args.detection_z_threshold,
251
+ normalizers=args.normalizers,
252
+ ignore_repeated_bigrams=args.ignore_repeated_bigrams,
253
+ select_green_tokens=args.select_green_tokens)
254
+ if len(input_text)-1 > watermark_detector.min_prefix_len:
255
+ score_dict = watermark_detector.detect(input_text)
256
+ output_str = (f"Detection result @ {watermark_detector.z_threshold}:\n"
257
+ f"{score_dict}")
258
+ else:
259
+ output_str = (f"Error: string not long enough to compute watermark presence.")
260
+ return output_str, args
261
+
262
+ def run_gradio(args, model=None, device=None, tokenizer=None):
263
+
264
+ generate_partial = partial(generate, model=model, tokenizer=tokenizer)
265
+ detect_partial = partial(detect, device=device, tokenizer=tokenizer)
266
+
267
+ with gr.Blocks() as demo:
268
+
269
+ # Top section, greeting and instructions
270
+ gr.Markdown("## Demo for ['A Watermark for Large Language Models'](https://arxiv.org/abs/2301.10226)")
271
+ gr.HTML("""
272
+ <p>For faster inference without waiting in queue, you may duplicate the space and upgrade to GPU in settings.
273
+ <br/>
274
+ <a href="https://huggingface.co/spaces/tomg-group-umd/lm-watermarking?duplicate=true">
275
+ <img style="margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>
276
+ <p/>
277
+ """)
278
+
279
+ # Parameter selection group
280
+ with gr.Accordion("Advanced Settings",open=False):
281
+ with gr.Row():
282
+ with gr.Column(scale=1):
283
+ gr.Markdown(f"#### Generation Parameters")
284
+ with gr.Row():
285
+ decoding = gr.Radio(label="Decoding Method",choices=["multinomial", "greedy"], value=("multinomial" if args.use_sampling else "greedy"))
286
+ with gr.Row():
287
+ sampling_temp = gr.Slider(label="Sampling Temperature", minimum=0.1, maximum=1.0, step=0.1, value=args.sampling_temp, visible=True)
288
+ with gr.Row():
289
+ generation_seed = gr.Number(label="Generation Seed",value=args.generation_seed, interactive=True)
290
+ with gr.Row():
291
+ n_beams = gr.Dropdown(label="Number of Beams",choices=list(range(1,11,1)), value=args.n_beams, visible=(not args.use_sampling))
292
+
293
+ with gr.Column(scale=1):
294
+ gr.Markdown(f"#### Watermarking Parameters")
295
+ with gr.Row():
296
+ gamma = gr.Slider(label="gamma",minimum=0.1, maximum=0.9, step=0.1, value=args.gamma)
297
+ with gr.Row():
298
+ delta = gr.Slider(label="delta",minimum=0.0, maximum=10.0, step=0.1, value=args.delta)
299
+ with gr.Row():
300
+ ignore_repeated_bigrams = gr.Checkbox(label="Ignore Bigram Repeats")
301
+ with gr.Row():
302
+ normalizers = gr.CheckboxGroup(label="Normalizations", choices=["unicode", "homoglyphs", "truecase"], value=args.normalizers)
303
+
304
+ # State manager
305
+ # Construct state for parameters, define updates and toggles, and register event listeners
306
+ session_args = gr.State(value=args)
307
+
308
+ def update_sampling_temp(session_state, value): session_state.sampling_temp = float(value); return session_state
309
+ def update_generation_seed(session_state, value): session_state.generation_seed = int(value); return session_state
310
+ def update_gamma(session_state, value): session_state.gamma = float(value); return session_state
311
+ def update_delta(session_state, value): session_state.delta = float(value); return session_state
312
+ def update_decoding(session_state, value):
313
+ if value == "multinomial":
314
+ session_state.use_sampling = True
315
+ elif value == "greedy":
316
+ session_state.use_sampling = False
317
+ return session_state
318
+ def toggle_sampling_vis(value):
319
+ if value == "multinomial":
320
+ return gr.update(visible=True)
321
+ elif value == "greedy":
322
+ return gr.update(visible=False)
323
+ def toggle_sampling_vis_inv(value):
324
+ if value == "multinomial":
325
+ return gr.update(visible=False)
326
+ elif value == "greedy":
327
+ return gr.update(visible=True)
328
+ def update_n_beams(session_state, value): session_state.n_beams = int(value); return session_state
329
+ def update_ignore_repeated_bigrams(session_state, value): session_state.ignore_repeated_bigrams = value; return session_state
330
+ def update_normalizers(session_state, value): session_state.normalizers = value; return session_state
331
+
332
+ decoding.change(update_decoding,inputs=[session_args, decoding], outputs=[session_args])
333
+ decoding.change(toggle_sampling_vis,inputs=[decoding], outputs=[sampling_temp])
334
+ decoding.change(toggle_sampling_vis,inputs=[decoding], outputs=[generation_seed])
335
+ decoding.change(toggle_sampling_vis_inv,inputs=[decoding], outputs=[n_beams])
336
+
337
+ sampling_temp.change(update_sampling_temp,inputs=[session_args, sampling_temp], outputs=[session_args])
338
+ generation_seed.change(update_generation_seed,inputs=[session_args, generation_seed], outputs=[session_args])
339
+ n_beams.change(update_n_beams,inputs=[session_args, n_beams], outputs=[session_args])
340
+
341
+ gamma.change(update_gamma,inputs=[session_args, gamma], outputs=[session_args])
342
+ delta.change(update_delta,inputs=[session_args, delta], outputs=[session_args])
343
+ ignore_repeated_bigrams.change(update_ignore_repeated_bigrams,inputs=[session_args, ignore_repeated_bigrams], outputs=[session_args])
344
+ normalizers.change(update_normalizers,inputs=[session_args, normalizers], outputs=[session_args])
345
+
346
+ with gr.Tab("Generation"):
347
+
348
+ with gr.Row():
349
+ prompt = gr.Textbox(label=f"Prompt", interactive=True)
350
+ with gr.Row():
351
+ generate_btn = gr.Button("Generate")
352
+ with gr.Row():
353
+ with gr.Column(scale=2):
354
+ output_without_watermark = gr.Textbox(label="Output Without Watermark", interactive=False)
355
+ with gr.Column(scale=1):
356
+ without_watermark_detection_result = gr.Textbox(label="Detection Result", interactive=False)
357
+ with gr.Row():
358
+ with gr.Column(scale=2):
359
+ output_with_watermark = gr.Textbox(label="Output With Watermark", interactive=False)
360
+ with gr.Column(scale=1):
361
+ with_watermark_detection_result = gr.Textbox(label="Detection Result", interactive=False)
362
+
363
+
364
+ redecoded_input = gr.Textbox(visible=False)
365
+ truncation_warning = gr.Number(visible=False)
366
+ def truncate_prompt(redecoded_input, truncation_warning, orig_prompt, args):
367
+ if truncation_warning:
368
+ return redecoded_input + f"\n\n[Prompt was truncated before generation due to length...]"
369
+ else:
370
+ return orig_prompt, args
371
+
372
+ generate_btn.click(fn=generate_partial, inputs=[prompt,session_args], outputs=[redecoded_input, truncation_warning, output_without_watermark, output_with_watermark,session_args])
373
+
374
+ # Show truncated version of prompt if truncation occurred
375
+ redecoded_input.change(fn=truncate_prompt, inputs=[redecoded_input,truncation_warning,prompt,session_args], outputs=[prompt,session_args])
376
+
377
+ # Call detection when the outputs of the generate function are updated.
378
+ output_without_watermark.change(fn=detect_partial, inputs=[output_without_watermark,session_args], outputs=[without_watermark_detection_result,session_args])
379
+ output_with_watermark.change(fn=detect_partial, inputs=[output_with_watermark,session_args], outputs=[with_watermark_detection_result,session_args])
380
+
381
+ with gr.Tab("Detector Only"):
382
+ with gr.Row():
383
+ detection_input = gr.Textbox(label="Text to Analyze", interactive=True)
384
+ with gr.Row():
385
+ detect_btn = gr.Button("Detect")
386
+ with gr.Row():
387
+ detection_result = gr.Textbox(label="Detection Result", interactive=False)
388
+ detect_btn.click(fn=detect_partial, inputs=[detection_input,session_args], outputs=[detection_result, session_args])
389
+
390
+ with gr.Accordion("A note on model capability",open=False):
391
+ gr.Markdown(
392
+ """
393
+ The models that can be used in this demo are limited to those that are open source as well as fit on a single commodity GPU. In particular, there are few models above 10B parameters and way fewer trained using both Instruction finetuning or RLHF that are open source that we can use.
394
 
395
+ Therefore, the model, in both it's un-watermarked (normal) and watermarked state, is not generally able to respond well to the kinds of prompts that a 100B+ Instruction and RLHF tuned model such as ChatGPT, Claude, or Bard is.
396
 
397
+ We suggest you try prompts that give the model a few sentences and then allow it to 'continue' the prompt, as these weaker models are more capable in this simpler language modeling setting.
398
+ """
399
+ )
400
+
401
+ if args.demo_public:
402
+ demo.launch(share=True) # exposes app to the internet via randomly generated link
403
+ else:
404
+ demo.launch()
405
+
406
+ def main(args):
407
+
408
+ # Initial arg processing and log
409
+ args.normalizers = (args.normalizers.split(",") if args.normalizers else [])
410
+ print(args)
411
+
412
+ if not args.skip_model_load:
413
+ model, tokenizer, device = load_model(args)
414
+ else:
415
+ model, tokenizer, device = None, None, []
416
+
417
+ # Generate and detect, report to stdout
418
+ if not args.skip_model_load:
419
+ # input_text = (
420
+ # "The diamondback terrapin or simply terrapin (Malaclemys terrapin) is a "
421
+ # "species of turtle native to the brackish coastal tidal marshes of the "
422
+ # "Northeastern and southern United States, and in Bermuda.[6] It belongs "
423
+ # "to the monotypic genus Malaclemys. It has one of the largest ranges of "
424
+ # "all turtles in North America, stretching as far south as the Florida Keys "
425
+ # "and as far north as Cape Cod.[7] The name 'terrapin' is derived from the "
426
+ # "Algonquian word torope.[8] It applies to Malaclemys terrapin in both "
427
+ # "British English and American English. The name originally was used by "
428
+ # "early European settlers in North America to describe these brackish-water "
429
+ # "turtles that inhabited neither freshwater habitats nor the sea. It retains "
430
+ # "this primary meaning in American English.[8] In British English, however, "
431
+ # "other semi-aquatic turtle species, such as the red-eared slider, might "
432
+ # "also be called terrapins. The common name refers to the diamond pattern "
433
+ # "on top of its shell (carapace), but the overall pattern and coloration "
434
+ # "vary greatly. The shell is usually wider at the back than in the front, "
435
+ # "and from above it appears wedge-shaped. The shell coloring can vary "
436
+ # "from brown to grey, and its body color can be grey, brown, yellow, "
437
+ # "or white. All have a unique pattern of wiggly, black markings or spots "
438
+ # "on their body and head. The diamondback terrapin has large webbed "
439
+ # "feet.[9] The species is"
440
+ # )
441
+
442
+ input_text = "In this work, we study watermarking of language model output. A watermark is a hidden pattern in text that is imperceptible to humans, while making the text algorithmically identifiable as synthetic. We propose an efficient watermark that makes synthetic text detectable from short spans of tokens (as few as 25 words), while false-positives (where human text is marked as machine-generated) are statistically improbable. The watermark detection algorithm can be made public, enabling third parties (e.g., social media platforms) to run it themselves, or it can be kept private and run behind an API. We seek a watermark with the following properties:\n"
443
+
444
+
445
+ term_width = os.get_terminal_size()[0]
446
+ print("#"*term_width)
447
+ print("Prompt:")
448
+ print(input_text)
449
+
450
+ _, _, decoded_output_without_watermark, decoded_output_with_watermark, _ = generate(input_text, args)
451
+ without_watermark_detection_result = detect(decoded_output_without_watermark, args)
452
+ with_watermark_detection_result = detect(decoded_output_with_watermark, args)
453
+
454
+ print("#"*term_width)
455
+ print("Output without watermark:")
456
+ print(decoded_output_without_watermark)
457
+ print("-"*term_width)
458
+ print(f"Detection result @ {args.detection_z_threshold}:")
459
+ pprint(without_watermark_detection_result)
460
+ print("-"*term_width)
461
+
462
+ print("#"*term_width)
463
+ print("Output with watermark:")
464
+ print(decoded_output_with_watermark)
465
+ print("-"*term_width)
466
+ print(f"Detection result @ {args.detection_z_threshold}:")
467
+ pprint(with_watermark_detection_result)
468
+ print("-"*term_width)
469
+
470
+
471
+ # Launch the app to generate and detect interactively (implements the hf space demo)
472
+ if args.run_gradio:
473
+ run_gradio(args, model=model, tokenizer=tokenizer, device=device)
474
 
475
  return
476