devingulliver commited on
Commit
689b9f0
·
verified ·
1 Parent(s): e7c9c2f

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -9
app.py CHANGED
@@ -1,12 +1,151 @@
 
 
 
 
 
1
  import torch
2
- from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
 
 
 
3
 
4
- quant_config = BitsAndBytesConfig(load_in_8bit=True, llm_int8_skip_modules=["temporal_block"])
5
- tokenizer = AutoTokenizer.from_pretrained("alpindale/recurrentgemma-9b-it")
6
- model = AutoModelForCausalLM.from_pretrained(
7
- "alpindale/recurrentgemma-9b-it",
8
- device_map="auto", torch_dtype=torch.float16,
9
- quantization_config=quant_config
10
- )
11
 
12
- model.push_to_hub("recurrentgemma-9b-it-8bit")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import all the libraries
2
+ import math
3
+ import numpy as np
4
+ import scipy
5
+ from PIL import Image
6
  import torch
7
+ import torchvision.transforms as tforms
8
+ from diffusers import DiffusionPipeline, UNet2DConditionModel, DDIMScheduler, DDIMInverseScheduler
9
+ from diffusers.models import AutoencoderKL
10
+ import gradio as gr
11
 
12
+ # load SDXL pipeline
13
+ vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
14
+ unet = UNet2DConditionModel.from_pretrained("mhdang/dpo-sdxl-text2image-v1", subfolder="unet", torch_dtype=torch.float16)
15
+ pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", unet=unet, vae=vae, torch_dtype=torch.float16)
16
+ pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
17
+ pipe = pipe.to("cuda")
 
18
 
19
+ # watermarking helper functions. paraphrased from the reference impl of arXiv:2305.20030
20
+
21
+ def circle_mask(size=128, r=16, x_offset=0, y_offset=0):
22
+ x0 = y0 = size // 2
23
+ x0 += x_offset
24
+ y0 += y_offset
25
+ y, x = np.ogrid[:size, :size]
26
+ y = y[::-1]
27
+ return ((x - x0)**2 + (y-y0)**2)<= r**2
28
+
29
+ def get_pattern(shape, w_seed=999999):
30
+ g = torch.Generator(device=pipe.device)
31
+ g.manual_seed(w_seed)
32
+ gt_init = pipe.prepare_latents(1, pipe.unet.in_channels,
33
+ 1024, 1024,
34
+ pipe.unet.dtype, pipe.device, g)
35
+ gt_patch = torch.fft.fftshift(torch.fft.fft2(gt_init), dim=(-1, -2))
36
+ # ring pattern. paper found this to be effective
37
+ gt_patch_tmp = gt_patch.clone().detach()
38
+ for i in range(shape[-1] // 2, 0, -1):
39
+ tmp_mask = circle_mask(gt_init.shape[-1], r=i)
40
+ tmp_mask = torch.tensor(tmp_mask)
41
+ for j in range(gt_patch.shape[1]):
42
+ gt_patch[:, j, tmp_mask] = gt_patch_tmp[0, j, 0, i].item()
43
+
44
+ return gt_patch
45
+
46
+ def transform_img(image):
47
+ tform = tforms.Compose([tforms.Resize(1024),tforms.CenterCrop(1024),tforms.ToTensor()])
48
+ image = tform(image)
49
+ return 2.0 * image - 1.0
50
+
51
+ # hyperparameters
52
+ shape = (1, 4, 128, 128)
53
+ w_seed = 7433 # TREE :)
54
+ w_channel = 0
55
+ w_radius = 16 # the suggested r from section 4.4 of paper
56
+
57
+ # get w_key and w_mask
58
+ np_mask = circle_mask(shape[-1], r=w_radius)
59
+ torch_mask = torch.tensor(np_mask).to(pipe.device)
60
+ w_mask = torch.zeros(shape, dtype=torch.bool).to(pipe.device)
61
+ w_mask[:, w_channel] = torch_mask
62
+ w_key = get_pattern(shape, w_seed=w_seed).to(pipe.device)
63
+
64
+
65
+ def get_noise():
66
+ # moved w_key and w_mask to globals
67
+
68
+ # inject watermark
69
+ init_latents = pipe.prepare_latents(1, pipe.unet.in_channels,
70
+ 1024, 1024,
71
+ pipe.unet.dtype, pipe.device, None)
72
+ init_latents_fft = torch.fft.fftshift(torch.fft.fft2(init_latents), dim=(-1, -2))
73
+ init_latents_fft[w_mask] = w_key[w_mask].clone()
74
+ init_latents = torch.fft.ifft2(torch.fft.ifftshift(init_latents_fft, dim=(-1, -2))).real
75
+ # hot fix to prevent out of bounds values. will "properly" fix this later
76
+ init_latents[init_latents == float("Inf")] = 4
77
+ init_latents[init_latents == float("-Inf")] = -4
78
+
79
+ return init_latents
80
+
81
+ def detect(image):
82
+ # invert scheduler
83
+ curr_scheduler = pipe.scheduler
84
+ pipe.scheduler = DDIMInverseScheduler.from_config(pipe.scheduler.config)
85
+
86
+ # ddim inversion
87
+ img = transform_img(image).unsqueeze(0).to(pipe.unet.dtype).to(pipe.device)
88
+ image_latents = pipe.vae.encode(img).latent_dist.mode() * 0.13025
89
+ inverted_latents = pipe(prompt="", latents=image_latents, guidance_scale=1, num_inference_steps=50, output_type="latent")
90
+ inverted_latents = inverted_latents.images
91
+
92
+ # calculate p-value instead of detection threshold. more rigorous, plus we can do a non-boolean output
93
+ inverted_latents_fft = torch.fft.fftshift(torch.fft.fft2(inverted_latents), dim=(-1, -2))[w_mask].flatten()
94
+ target = w_key[w_mask].flatten()
95
+ inverted_latents_fft = torch.concatenate([inverted_latents_fft.real, inverted_latents_fft.imag])
96
+ target = torch.concatenate([target.real, target.imag])
97
+
98
+ sigma = inverted_latents_fft.std()
99
+ lamda = (target ** 2 / sigma ** 2).sum().item()
100
+ x = (((inverted_latents_fft - target) / sigma) ** 2).sum().item()
101
+ p_value = scipy.stats.ncx2.cdf(x=x, df=len(target), nc=lamda)
102
+
103
+ # revert scheduler
104
+ pipe.scheduler = curr_scheduler
105
+
106
+ if p_value == 0:
107
+ return 1.0
108
+ else:
109
+ return max(0.0, 1-1/math.log(5/p_value,10))
110
+
111
+ def generate(prompt):
112
+ return pipe(prompt=prompt, negative_prompt="monochrome", num_inference_steps=50, latents=get_noise()).images[0]
113
+
114
+ # optimize for speed
115
+ pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
116
+ print(detect(generate("an astronaut riding a green horse"))) # warmup after jit
117
+
118
+ # actual gradio demo
119
+
120
+ def manager(input, progress=gr.Progress(track_tqdm=True)): # to prevent the queue from overloading
121
+ if type(input) == str:
122
+ return generate(input)
123
+ elif type(input) == np.ndarray:
124
+ image = Image.fromarray(input)
125
+ percent = detect(image)
126
+ return {"watermarked": percent, "not_watermarked": 1.0-percent}
127
+
128
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="green",secondary_hue="green", font=gr.themes.GoogleFont("Fira Sans"))) as app:
129
+ with gr.Row():
130
+ gr.HTML('<center><p>Bad actors are using generative AI to destroy the livelihoods of real artists. We need transparency now.</p><h1><span style="font-size:1.5em">Introducing Dendrokronos 🌳</span></h1></center>')
131
+ with gr.Row():
132
+ with gr.Column():
133
+ gr.Markdown("# Generate\nType a prompt and hit Go. Dendrokronos will generate an invisibly-watermarked image. \nYou can click the download button to save the finished image. Try it with the detector.")
134
+ with gr.Group():
135
+ with gr.Row():
136
+ gen_in = gr.Textbox(max_lines=1, placeholder='try "a majestic tree at sunset, oil painting"', show_label=False, scale=4)
137
+ gen_btn = gr.Button("Go", variant="primary", scale=0)
138
+ gen_out = gr.Image(interactive=False, show_label=False)
139
+ gen_btn.click(fn=manager, inputs=gen_in, outputs=gen_out)
140
+ with gr.Column():
141
+ gr.Markdown("# Detect\nUpload an image and hit Detect. Dendrokronos will predict the probability it was watermarked. \nNote: Dendrokronos can only detect its own watermark. It won't detect other AIs, such as DALL-E.")
142
+ det_out = gr.Label(show_label=False)
143
+ with gr.Group():
144
+ det_btn = gr.Button("Detect", variant="primary")
145
+ det_in = gr.Image(interactive=True, sources=["upload","clipboard"], show_label=False)
146
+ det_btn.click(fn=manager, inputs=det_in, outputs=det_out)
147
+ with gr.Row():
148
+ gr.HTML('<center><h1>&nbsp;</h1>Acknowledgements: Dendrokronos uses <a href="https://huggingface.co/mhdang/dpo-sdxl-text2image-v1">SDXL DPO 1.0</a> for the underlying image generation and <a href="https://arxiv.org/abs/2305.20030">an algorithm by UMD researchers</a> for the watermark technology.<br />Dendrokronos is a project by Devin Gulliver.</center>')
149
+
150
+ app.queue()
151
+ app.launch(show_api=False)