Adityadn commited on
Commit
617d388
1 Parent(s): 6f14d9a

Upload 524 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +54 -0
  2. aiDescTerminal.py +90 -0
  3. aiDescUI.py +688 -0
  4. app.html +6 -0
  5. app.py +67 -0
  6. args_manager.py +55 -0
  7. auth-example.json +6 -0
  8. auth.json +6 -0
  9. build_launcher.py +26 -0
  10. config.txt +16 -0
  11. config_modification_tutorial.txt +123 -0
  12. css/style.css +220 -0
  13. entry_with_update.py +46 -0
  14. entrypoint.sh +33 -0
  15. environment.yaml +7 -0
  16. experiments_expansion.py +8 -0
  17. experiments_face.py +7 -0
  18. experiments_interrogate.py +205 -0
  19. extras/BLIP/configs/bert_config.json +21 -0
  20. extras/BLIP/configs/caption_coco.yaml +33 -0
  21. extras/BLIP/configs/med_config.json +21 -0
  22. extras/BLIP/configs/nlvr.yaml +21 -0
  23. extras/BLIP/configs/nocaps.yaml +15 -0
  24. extras/BLIP/configs/pretrain.yaml +27 -0
  25. extras/BLIP/configs/retrieval_coco.yaml +34 -0
  26. extras/BLIP/configs/retrieval_flickr.yaml +34 -0
  27. extras/BLIP/configs/retrieval_msrvtt.yaml +12 -0
  28. extras/BLIP/configs/vqa.yaml +25 -0
  29. extras/BLIP/models/__pycache__/blip.cpython-310.pyc +0 -0
  30. extras/BLIP/models/__pycache__/med.cpython-310.pyc +0 -0
  31. extras/BLIP/models/__pycache__/vit.cpython-310.pyc +0 -0
  32. extras/BLIP/models/bert_tokenizer/config.json +23 -0
  33. extras/BLIP/models/bert_tokenizer/tokenizer.json +0 -0
  34. extras/BLIP/models/bert_tokenizer/tokenizer_config.json +3 -0
  35. extras/BLIP/models/bert_tokenizer/vocab.txt +0 -0
  36. extras/BLIP/models/blip.py +239 -0
  37. extras/BLIP/models/blip_itm.py +76 -0
  38. extras/BLIP/models/blip_nlvr.py +105 -0
  39. extras/BLIP/models/blip_pretrain.py +339 -0
  40. extras/BLIP/models/blip_retrieval.py +319 -0
  41. extras/BLIP/models/blip_vqa.py +186 -0
  42. extras/BLIP/models/med.py +955 -0
  43. extras/BLIP/models/nlvr_encoder.py +843 -0
  44. extras/BLIP/models/vit.py +308 -0
  45. extras/__pycache__/expansion.cpython-310.pyc +0 -0
  46. extras/__pycache__/face_crop.cpython-310.pyc +0 -0
  47. extras/__pycache__/interrogate.cpython-310.pyc +0 -0
  48. extras/__pycache__/ip_adapter.cpython-310.pyc +0 -0
  49. extras/__pycache__/preprocessors.cpython-310.pyc +0 -0
  50. extras/__pycache__/resampler.cpython-310.pyc +0 -0
.gitignore ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ *.ckpt
3
+ *.safetensors
4
+ *.pth
5
+ *.pt
6
+ *.bin
7
+ *.patch
8
+ *.backup
9
+ *.corrupted
10
+ *.partial
11
+ *.onnx
12
+ sorted_styles.json
13
+ /input
14
+ /cache
15
+ /language/default.json
16
+ /test_imgs
17
+ config.txt
18
+ config_modification_tutorial.txt
19
+ user_path_config.txt
20
+ user_path_config-deprecated.txt
21
+ /modules/*.png
22
+ /repositories
23
+ /fooocus_env
24
+ /venv
25
+ /tmp
26
+ /ui-config.json
27
+ /outputs
28
+ /config.json
29
+ /log
30
+ /webui.settings.bat
31
+ /embeddings
32
+ /styles.csv
33
+ /params.txt
34
+ /styles.csv.bak
35
+ /webui-user.bat
36
+ /webui-user.sh
37
+ /interrogate
38
+ /user.css
39
+ /.idea
40
+ /notification.ogg
41
+ /notification.mp3
42
+ /SwinIR
43
+ /textual_inversion
44
+ .vscode
45
+ /extensions
46
+ /test/stdout.txt
47
+ /test/stderr.txt
48
+ /cache.json*
49
+ /config_states/
50
+ /node_modules
51
+ /package-lock.json
52
+ /.coverage*
53
+ /auth.json
54
+ .DS_Store
aiDescTerminal.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import numpy as np
4
+ from PIL import Image
5
+ import requests
6
+ from io import BytesIO
7
+
8
+ root = os.path.dirname(os.path.abspath(__file__))
9
+ sys.path.append(root)
10
+ os.chdir(root)
11
+
12
+ import modules.config
13
+ import modules.html
14
+ import modules.flags as flags
15
+ import modules.meta_parser
16
+
17
+ def download_image(url):
18
+ response = requests.get(url)
19
+ img = Image.open(BytesIO(response.content)).convert("RGB")
20
+ return img
21
+
22
+ def trigger_describe(mode, img_path):
23
+ print("Running")
24
+ print("Press Ctrl+C for Stop ")
25
+ if mode == flags.desc_type_photo:
26
+ from extras.interrogate import default_interrogator as default_interrogator_photo
27
+ if img_path.startswith('http'):
28
+ img = download_image(img_path)
29
+ else:
30
+ img = Image.open(img_path).convert("RGB")
31
+ return default_interrogator_photo(img), ["Fooocus V2", "Fooocus Enhance", "Fooocus Sharp"]
32
+ elif mode == flags.desc_type_anime:
33
+ from extras.wd14tagger import default_interrogator as default_interrogator_anime
34
+ if img_path.startswith('http'):
35
+ img = download_image(img_path)
36
+ elif isinstance(img_path, str):
37
+ # Load the image if the input is a path
38
+ img = Image.open(img_path).convert("RGB")
39
+ elif isinstance(img_path, np.ndarray):
40
+ # Use the provided NumPy array directly
41
+ img = Image.fromarray(img_path).convert("RGB")
42
+ else:
43
+ raise ValueError("Invalid image format. Please provide a valid path or NumPy array.")
44
+
45
+ # Convert the image to a NumPy array
46
+ img_array = np.array(img)
47
+
48
+ return default_interrogator_anime(img_array), ["Fooocus V2", "Fooocus Masterpiece"]
49
+ return mode, ["Fooocus V2"]
50
+
51
+ style_selections = modules.config.default_styles
52
+
53
+ def run_describe(image_path, content_type):
54
+ desc_input_image = image_path
55
+ desc_method = content_type
56
+
57
+ result, style_selections = None, None
58
+
59
+ if desc_method in ["Photograph", "1", ""]:
60
+ desc_method = "Photograph (1)"
61
+ result, style_selections = trigger_describe(flags.desc_type_photo, desc_input_image)
62
+ elif desc_method in ["Art/Anime", "2"]:
63
+ desc_method = "Art/Anime (2)"
64
+ result, style_selections = trigger_describe(flags.desc_type_anime, desc_input_image)
65
+ else:
66
+ print("ERROR!")
67
+
68
+ if result or style_selections != "":
69
+ style_selections = ""
70
+ print("Result:", result)
71
+ # print("Style Selections:", style_selections)
72
+ quit()
73
+
74
+ if __name__ == "__main__":
75
+ desc_input_image = input("Path to Image (local path or URL): ")
76
+
77
+ if desc_input_image == "":
78
+ desc_input_image = "./imgs/Gambar1.jpg"
79
+
80
+ print(f"You use: {desc_input_image}")
81
+
82
+ desc_method = input(
83
+ """
84
+ Select Content Type:
85
+ Photograph (1)
86
+ Art/Anime (2)
87
+ """
88
+ )
89
+
90
+ run_describe(desc_input_image, desc_method)
aiDescUI.py ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import random
3
+ import os
4
+ # import json
5
+ import time
6
+ import shared
7
+ import modules.config
8
+ # import fooocus_version
9
+ import modules.html
10
+ import modules.async_worker as worker
11
+ import modules.constants as constants
12
+ import modules.flags as flags
13
+ import modules.gradio_hijack as grh
14
+ import modules.style_sorter as style_sorter
15
+ import modules.meta_parser
16
+ import args_manager
17
+ import copy
18
+
19
+ from modules.sdxl_styles import legal_style_names
20
+ from modules.private_logger import get_current_html_path
21
+ from modules.ui_gradio_extensions import reload_javascript
22
+ from modules.auth import auth_enabled, check_auth
23
+ # from modules.util import is_json
24
+
25
+ # def get_task(*args):
26
+ # args = list(args)
27
+ # args.pop(0)
28
+
29
+ # return worker.AsyncTask(args=args)
30
+
31
+ # def generate_clicked(task):
32
+ # import ldm_patched.modules.model_management as model_management
33
+
34
+ # with model_management.interrupt_processing_mutex:
35
+ # model_management.interrupt_processing = False
36
+ # # outputs=[progress_html, progress_window, progress_gallery, gallery]
37
+ # execution_start_time = time.perf_counter()
38
+ # finished = False
39
+
40
+ # yield gr.update(visible=True, value=modules.html.make_progress_html(1, 'Waiting for task to start ...')), \
41
+ # gr.update(visible=True, value=None), \
42
+ # gr.update(visible=False, value=None), \
43
+ # gr.update(visible=False)
44
+
45
+ # worker.async_tasks.append(task)
46
+
47
+ # while not finished:
48
+ # time.sleep(0.01)
49
+ # if len(task.yields) > 0:
50
+ # flag, product = task.yields.pop(0)
51
+ # if flag == 'preview':
52
+
53
+ # # help bad internet connection by skipping duplicated preview
54
+ # if len(task.yields) > 0: # if we have the next item
55
+ # if task.yields[0][0] == 'preview': # if the next item is also a preview
56
+ # # print('Skipped one preview for better internet connection.')
57
+ # continue
58
+
59
+ # percentage, title, image = product
60
+ # yield gr.update(visible=True, value=modules.html.make_progress_html(percentage, title)), \
61
+ # gr.update(visible=True, value=image) if image is not None else gr.update(), \
62
+ # gr.update(), \
63
+ # gr.update(visible=False)
64
+ # if flag == 'results':
65
+ # yield gr.update(visible=True), \
66
+ # gr.update(visible=True), \
67
+ # gr.update(visible=True, value=product), \
68
+ # gr.update(visible=False)
69
+ # if flag == 'finish':
70
+ # yield gr.update(visible=False), \
71
+ # gr.update(visible=False), \
72
+ # gr.update(visible=False), \
73
+ # gr.update(visible=True, value=product)
74
+ # finished = True
75
+
76
+ # # delete Fooocus temp images, only keep gradio temp images
77
+ # if args_manager.args.disable_image_log:
78
+ # for filepath in product:
79
+ # if isinstance(filepath, str) and os.path.exists(filepath):
80
+ # os.remove(filepath)
81
+
82
+ # execution_time = time.perf_counter() - execution_start_time
83
+ # print(f'Total time: {execution_time:.2f} seconds')
84
+ # return
85
+
86
+
87
+ reload_javascript()
88
+
89
+ title = 'AI Describe Image'
90
+
91
+ if isinstance(args_manager.args.preset, str):
92
+ title += ' ' + args_manager.args.preset
93
+
94
+ shared.gradio_root = gr.Blocks(
95
+ title=title,
96
+ css=modules.html.css).queue()
97
+
98
+ with shared.gradio_root:
99
+ # currentTask = gr.State(worker.AsyncTask(args=[]))
100
+ with gr.Row():
101
+ with gr.Column(scale=2):
102
+ # with gr.Row():
103
+ # progress_window = grh.Image(label='Preview', show_label=True, visible=False, height=768,
104
+ # elem_classes=['main_view'])
105
+ # progress_gallery = gr.Gallery(label='Finished Images', show_label=True, object_fit='contain',
106
+ # height=768, visible=False, elem_classes=['main_view', 'image_gallery'])
107
+ # progress_html = gr.HTML(value=modules.html.make_progress_html(32, 'Progress 32%'), visible=False,
108
+ # elem_id='progress-bar', elem_classes='progress-bar')
109
+ # gallery = gr.Gallery(label='Gallery', show_label=False, object_fit='contain', visible=True, height=768,
110
+ # elem_classes=['resizable_area', 'main_view', 'final_gallery', 'image_gallery'],
111
+ # elem_id='final_gallery')
112
+ with gr.Row(visible=True) as image_input_panel:
113
+ with gr.Tabs():
114
+ # with gr.TabItem(label='Upscale or Variation') as uov_tab:
115
+ # with gr.Row():
116
+ # with gr.Column():
117
+ # uov_input_image = grh.Image(label='Drag above image to here', source='upload', type='numpy')
118
+ # with gr.Column():
119
+ # uov_method = gr.Radio(label='Upscale or Variation:', choices=flags.uov_list, value=flags.disabled)
120
+ # gr.HTML('<a href="https://github.com/lllyasviel/Fooocus/discussions/390" target="_blank">\U0001F4D4 Document</a>')
121
+ # with gr.TabItem(label='Image Prompt') as ip_tab:
122
+ # with gr.Row():
123
+ # ip_images = []
124
+ # ip_types = []
125
+ # ip_stops = []
126
+ # ip_weights = []
127
+ # ip_ctrls = []
128
+ # ip_ad_cols = []
129
+ # for _ in range(flags.controlnet_image_count):
130
+ # with gr.Column():
131
+ # ip_image = grh.Image(label='Image', source='upload', type='numpy', show_label=False, height=300)
132
+ # ip_images.append(ip_image)
133
+ # ip_ctrls.append(ip_image)
134
+ # with gr.Column(visible=False) as ad_col:
135
+ # with gr.Row():
136
+ # default_end, default_weight = flags.default_parameters[flags.default_ip]
137
+
138
+ # ip_stop = gr.Slider(label='Stop At', minimum=0.0, maximum=1.0, step=0.001, value=default_end)
139
+ # ip_stops.append(ip_stop)
140
+ # ip_ctrls.append(ip_stop)
141
+
142
+ # ip_weight = gr.Slider(label='Weight', minimum=0.0, maximum=2.0, step=0.001, value=default_weight)
143
+ # ip_weights.append(ip_weight)
144
+ # ip_ctrls.append(ip_weight)
145
+
146
+ # ip_type = gr.Radio(label='Type', choices=flags.ip_list, value=flags.default_ip, container=False)
147
+ # ip_types.append(ip_type)
148
+ # ip_ctrls.append(ip_type)
149
+
150
+ # ip_type.change(lambda x: flags.default_parameters[x], inputs=[ip_type], outputs=[ip_stop, ip_weight], queue=False, show_progress=False)
151
+ # ip_ad_cols.append(ad_col)
152
+ # ip_advanced = gr.Checkbox(label='Advanced', value=False, container=False)
153
+ # gr.HTML('* \"Image Prompt\" is powered by Fooocus Image Mixture Engine (v1.0.1). <a href="https://github.com/lllyasviel/Fooocus/discussions/557" target="_blank">\U0001F4D4 Document</a>')
154
+
155
+ # def ip_advance_checked(x):
156
+ # return [gr.update(visible=x)] * len(ip_ad_cols) + \
157
+ # [flags.default_ip] * len(ip_types) + \
158
+ # [flags.default_parameters[flags.default_ip][0]] * len(ip_stops) + \
159
+ # [flags.default_parameters[flags.default_ip][1]] * len(ip_weights)
160
+
161
+ # ip_advanced.change(ip_advance_checked, inputs=ip_advanced,
162
+ # outputs=ip_ad_cols + ip_types + ip_stops + ip_weights,
163
+ # queue=False, show_progress=False)
164
+ # with gr.TabItem(label='Inpaint or Outpaint') as inpaint_tab:
165
+ # with gr.Row():
166
+ # inpaint_input_image = grh.Image(label='Drag inpaint or outpaint image to here', source='upload', type='numpy', tool='sketch', height=500, brush_color="#FFFFFF", elem_id='inpaint_canvas')
167
+ # inpaint_mask_image = grh.Image(label='Mask Upload', source='upload', type='numpy', height=500, visible=False)
168
+
169
+ # with gr.Row():
170
+ # inpaint_additional_prompt = gr.Textbox(placeholder="Describe what you want to inpaint.", elem_id='inpaint_additional_prompt', label='Inpaint Additional Prompt', visible=False)
171
+ # outpaint_selections = gr.CheckboxGroup(choices=['Left', 'Right', 'Top', 'Bottom'], value=[], label='Outpaint Direction')
172
+ # inpaint_mode = gr.Dropdown(choices=modules.flags.inpaint_options, value=modules.flags.inpaint_option_default, label='Method')
173
+ # example_inpaint_prompts = gr.Dataset(samples=modules.config.example_inpaint_prompts, label='Additional Prompt Quick List', components=[inpaint_additional_prompt], visible=False)
174
+ # gr.HTML('* Powered by Fooocus Inpaint Engine <a href="https://github.com/lllyasviel/Fooocus/discussions/414" target="_blank">\U0001F4D4 Document</a>')
175
+ # example_inpaint_prompts.click(lambda x: x[0], inputs=example_inpaint_prompts, outputs=inpaint_additional_prompt, show_progress=False, queue=False)
176
+ with gr.TabItem(label='Describe') as desc_tab:
177
+ with gr.Row():
178
+ with gr.Column():
179
+ desc_input_image = grh.Image(label='Drag any image to here', source='upload', type='numpy')
180
+ with gr.Column():
181
+ # with gr.Row(elem_classes='type_row'):
182
+ with gr.Row():
183
+ prompt = gr.Textbox(label="Output", show_label=True, elem_id='positive_prompt', container=True, autofocus=True, show_copy_button=True, interactive=True)
184
+
185
+ default_prompt = modules.config.default_prompt
186
+ if isinstance(default_prompt, str) and default_prompt != '':
187
+ shared.gradio_root.load(lambda: default_prompt, outputs=prompt)
188
+
189
+ # with gr.Column(scale=3, min_width=0):
190
+ # generate_button = gr.Button(label="Generate", value="Generate", elem_classes='type_row', elem_id='generate_button', visible=True)
191
+ # load_parameter_button = gr.Button(label="Load Parameters", value="Load Parameters", elem_classes='type_row', elem_id='load_parameter_button', visible=False)
192
+ # skip_button = gr.Button(label="Skip", value="Skip", elem_classes='type_row_half', visible=False)
193
+ # stop_button = gr.Button(label="Stop", value="Stop", elem_classes='type_row_half', elem_id='stop_button', visible=False)
194
+
195
+ # def stop_clicked(currentTask):
196
+ # import ldm_patched.modules.model_management as model_management
197
+ # currentTask.last_stop = 'stop'
198
+ # if (currentTask.processing):
199
+ # model_management.interrupt_current_processing()
200
+ # return currentTask
201
+
202
+ # def skip_clicked(currentTask):
203
+ # import ldm_patched.modules.model_management as model_management
204
+ # currentTask.last_stop = 'skip'
205
+ # if (currentTask.processing):
206
+ # model_management.interrupt_current_processing()
207
+ # return currentTask
208
+
209
+ # stop_button.click(stop_clicked, inputs=currentTask, outputs=currentTask, queue=False, show_progress=False, _js='cancelGenerateForever')
210
+ # skip_button.click(skip_clicked, inputs=currentTask, outputs=currentTask, queue=False, show_progress=False)
211
+ # with gr.Row(elem_classes='advanced_check_row'):
212
+ # # input_image_checkbox = gr.Checkbox(label='Input Image', value=False, container=False, elem_classes='min_check')
213
+ # advanced_checkbox = gr.Checkbox(label='Advanced', value=modules.config.default_advanced_checkbox, container=False, elem_classes='min_check')
214
+ with gr.Row():
215
+ desc_method = gr.Radio(
216
+ label='Content Type',
217
+ choices=[flags.desc_type_photo, flags.desc_type_anime],
218
+ value=flags.desc_type_photo)
219
+ desc_btn = gr.Button(value='Describe this Image into Prompt')
220
+ # gr.HTML('<a href="https://github.com/lllyasviel/Fooocus/discussions/1363" target="_blank">\U0001F4D4 Document</a>')
221
+ # with gr.TabItem(label='Metadata') as load_tab:
222
+ # with gr.Column():
223
+ # metadata_input_image = grh.Image(label='Drag any image generated by Fooocus here', source='upload', type='filepath')
224
+ # metadata_json = gr.JSON(label='Metadata')
225
+ # metadata_import_button = gr.Button(value='Apply Metadata')
226
+
227
+ # def trigger_metadata_preview(filepath):
228
+ # parameters, metadata_scheme = modules.meta_parser.read_info_from_image(filepath)
229
+
230
+ # results = {}
231
+ # if parameters is not None:
232
+ # results['parameters'] = parameters
233
+
234
+ # if isinstance(metadata_scheme, flags.MetadataScheme):
235
+ # results['metadata_scheme'] = metadata_scheme.value
236
+
237
+ # return results
238
+
239
+ # metadata_input_image.upload(trigger_metadata_preview, inputs=metadata_input_image,
240
+ # outputs=metadata_json, queue=False, show_progress=True)
241
+
242
+ switch_js = "(x) => {if(x){viewer_to_bottom(100);viewer_to_bottom(500);}else{viewer_to_top();} return x;}"
243
+ down_js = "() => {viewer_to_bottom();}"
244
+
245
+ # input_image_checkbox.change(lambda x: gr.update(visible=x), inputs=input_image_checkbox,
246
+ # outputs=image_input_panel, queue=False, show_progress=False, _js=switch_js)
247
+ # ip_advanced.change(lambda: None, queue=False, show_progress=False, _js=down_js)
248
+
249
+ # current_tab = gr.Textbox(value='desc', visible=False)
250
+ # # uov_tab.select(lambda: 'uov', outputs=current_tab, queue=False, _js=down_js, show_progress=False)
251
+ # # inpaint_tab.select(lambda: 'inpaint', outputs=current_tab, queue=False, _js=down_js, show_progress=False)
252
+ # # ip_tab.select(lambda: 'ip', outputs=current_tab, queue=False, _js=down_js, show_progress=False)
253
+ # desc_tab.select(lambda: 'desc', outputs=current_tab, queue=False, _js=down_js, show_progress=False)
254
+
255
+ # with gr.Column(scale=1, visible=modules.config.default_advanced_checkbox) as advanced_column:
256
+ # with gr.Tab(label='Setting'):
257
+ # performance_selection = gr.Radio(label='Performance',
258
+ # choices=modules.flags.performance_selections,
259
+ # value=modules.config.default_performance)
260
+ # aspect_ratios_selection = gr.Radio(label='Aspect Ratios', choices=modules.config.available_aspect_ratios,
261
+ # value=modules.config.default_aspect_ratio, info='width × height',
262
+ # elem_classes='aspect_ratios')
263
+ # image_number = gr.Slider(label='Image Number', minimum=1, maximum=modules.config.default_max_image_number, step=1, value=modules.config.default_image_number)
264
+
265
+ # output_format = gr.Radio(label='Output Format',
266
+ # choices=modules.flags.output_formats,
267
+ # value=modules.config.default_output_format)
268
+
269
+ # negative_prompt = gr.Textbox(label='Negative Prompt', show_label=True, placeholder="Type prompt here.",
270
+ # info='Describing what you do not want to see.', lines=2,
271
+ # elem_id='negative_prompt',
272
+ # value=modules.config.default_prompt_negative)
273
+ # seed_random = gr.Checkbox(label='Random', value=True)
274
+ # image_seed = gr.Textbox(label='Seed', value=0, max_lines=1, visible=False) # workaround for https://github.com/gradio-app/gradio/issues/5354
275
+
276
+ # def random_checked(r):
277
+ # return gr.update(visible=not r)
278
+
279
+ # def refresh_seed(r, seed_string):
280
+ # if r:
281
+ # return random.randint(constants.MIN_SEED, constants.MAX_SEED)
282
+ # else:
283
+ # try:
284
+ # seed_value = int(seed_string)
285
+ # if constants.MIN_SEED <= seed_value <= constants.MAX_SEED:
286
+ # return seed_value
287
+ # except ValueError:
288
+ # pass
289
+ # return random.randint(constants.MIN_SEED, constants.MAX_SEED)
290
+
291
+ # seed_random.change(random_checked, inputs=[seed_random], outputs=[image_seed],
292
+ # queue=False, show_progress=False)
293
+
294
+ # def update_history_link():
295
+ # if args_manager.args.disable_image_log:
296
+ # return gr.update(value='')
297
+
298
+ # return gr.update(value=f'<a href="file={get_current_html_path(output_format)}" target="_blank">\U0001F4DA History Log</a>')
299
+
300
+ # history_link = gr.HTML()
301
+ # shared.gradio_root.load(update_history_link, outputs=history_link, queue=False, show_progress=False)
302
+
303
+ # with gr.Tab(label='Style'):
304
+ # style_sorter.try_load_sorted_styles(
305
+ # style_names=legal_style_names,
306
+ # default_selected=modules.config.default_styles)
307
+
308
+ # style_search_bar = gr.Textbox(show_label=False, container=False,
309
+ # placeholder="\U0001F50E Type here to search styles ...",
310
+ # value="",
311
+ # label='Search Styles')
312
+ # style_selections = gr.CheckboxGroup(show_label=False, container=False,
313
+ # choices=copy.deepcopy(style_sorter.all_styles),
314
+ # value=copy.deepcopy(modules.config.default_styles),
315
+ # label='Selected Styles',
316
+ # elem_classes=['style_selections'])
317
+ # gradio_receiver_style_selections = gr.Textbox(elem_id='gradio_receiver_style_selections', visible=False)
318
+
319
+ # shared.gradio_root.load(lambda: gr.update(choices=copy.deepcopy(style_sorter.all_styles)),
320
+ # outputs=style_selections)
321
+
322
+ # style_search_bar.change(style_sorter.search_styles,
323
+ # inputs=[style_selections, style_search_bar],
324
+ # outputs=style_selections,
325
+ # queue=False,
326
+ # show_progress=False).then(
327
+ # lambda: None, _js='()=>{refresh_style_localization();}')
328
+
329
+ # gradio_receiver_style_selections.input(style_sorter.sort_styles,
330
+ # inputs=style_selections,
331
+ # outputs=style_selections,
332
+ # queue=False,
333
+ # show_progress=False).then(
334
+ # lambda: None, _js='()=>{refresh_style_localization();}')
335
+
336
+ # with gr.Tab(label='Model'):
337
+ # with gr.Group():
338
+ # with gr.Row():
339
+ # base_model = gr.Dropdown(label='Base Model (SDXL only)', choices=modules.config.model_filenames, value=modules.config.default_base_model_name, show_label=True)
340
+ # refiner_model = gr.Dropdown(label='Refiner (SDXL or SD 1.5)', choices=['None'] + modules.config.model_filenames, value=modules.config.default_refiner_model_name, show_label=True)
341
+
342
+ # refiner_switch = gr.Slider(label='Refiner Switch At', minimum=0.1, maximum=1.0, step=0.0001,
343
+ # info='Use 0.4 for SD1.5 realistic models; '
344
+ # 'or 0.667 for SD1.5 anime models; '
345
+ # 'or 0.8 for XL-refiners; '
346
+ # 'or any value for switching two SDXL models.',
347
+ # value=modules.config.default_refiner_switch,
348
+ # visible=modules.config.default_refiner_model_name != 'None')
349
+
350
+ # refiner_model.change(lambda x: gr.update(visible=x != 'None'),
351
+ # inputs=refiner_model, outputs=refiner_switch, show_progress=False, queue=False)
352
+
353
+ # with gr.Group():
354
+ # lora_ctrls = []
355
+
356
+ # for i, (n, v) in enumerate(modules.config.default_loras):
357
+ # with gr.Row():
358
+ # lora_enabled = gr.Checkbox(label='Enable', value=True,
359
+ # elem_classes=['lora_enable', 'min_check'], scale=1)
360
+ # lora_model = gr.Dropdown(label=f'LoRA {i + 1}',
361
+ # choices=['None'] + modules.config.lora_filenames, value=n,
362
+ # elem_classes='lora_model', scale=5)
363
+ # lora_weight = gr.Slider(label='Weight', minimum=modules.config.default_loras_min_weight,
364
+ # maximum=modules.config.default_loras_max_weight, step=0.01, value=v,
365
+ # elem_classes='lora_weight', scale=5)
366
+ # lora_ctrls += [lora_enabled, lora_model, lora_weight]
367
+
368
+ # with gr.Row():
369
+ # model_refresh = gr.Button(label='Refresh', value='\U0001f504 Refresh All Files', variant='secondary', elem_classes='refresh_button')
370
+ # with gr.Tab(label='Advanced'):
371
+ # guidance_scale = gr.Slider(label='Guidance Scale', minimum=1.0, maximum=30.0, step=0.01,
372
+ # value=modules.config.default_cfg_scale,
373
+ # info='Higher value means style is cleaner, vivider, and more artistic.')
374
+ # sharpness = gr.Slider(label='Image Sharpness', minimum=0.0, maximum=30.0, step=0.001,
375
+ # value=modules.config.default_sample_sharpness,
376
+ # info='Higher value means image and texture are sharper.')
377
+ # gr.HTML('<a href="https://github.com/lllyasviel/Fooocus/discussions/117" target="_blank">\U0001F4D4 Document</a>')
378
+ # dev_mode = gr.Checkbox(label='Developer Debug Mode', value=False, container=False)
379
+
380
+ # with gr.Column(visible=False) as dev_tools:
381
+ # with gr.Tab(label='Debug Tools'):
382
+ # adm_scaler_positive = gr.Slider(label='Positive ADM Guidance Scaler', minimum=0.1, maximum=3.0,
383
+ # step=0.001, value=1.5, info='The scaler multiplied to positive ADM (use 1.0 to disable). ')
384
+ # adm_scaler_negative = gr.Slider(label='Negative ADM Guidance Scaler', minimum=0.1, maximum=3.0,
385
+ # step=0.001, value=0.8, info='The scaler multiplied to negative ADM (use 1.0 to disable). ')
386
+ # adm_scaler_end = gr.Slider(label='ADM Guidance End At Step', minimum=0.0, maximum=1.0,
387
+ # step=0.001, value=0.3,
388
+ # info='When to end the guidance from positive/negative ADM. ')
389
+
390
+ # refiner_swap_method = gr.Dropdown(label='Refiner swap method', value=flags.refiner_swap_method,
391
+ # choices=['joint', 'separate', 'vae'])
392
+
393
+ # adaptive_cfg = gr.Slider(label='CFG Mimicking from TSNR', minimum=1.0, maximum=30.0, step=0.01,
394
+ # value=modules.config.default_cfg_tsnr,
395
+ # info='Enabling Fooocus\'s implementation of CFG mimicking for TSNR '
396
+ # '(effective when real CFG > mimicked CFG).')
397
+ # sampler_name = gr.Dropdown(label='Sampler', choices=flags.sampler_list,
398
+ # value=modules.config.default_sampler)
399
+ # scheduler_name = gr.Dropdown(label='Scheduler', choices=flags.scheduler_list,
400
+ # value=modules.config.default_scheduler)
401
+
402
+ # generate_image_grid = gr.Checkbox(label='Generate Image Grid for Each Batch',
403
+ # info='(Experimental) This may cause performance problems on some computers and certain internet conditions.',
404
+ # value=False)
405
+
406
+ # overwrite_step = gr.Slider(label='Forced Overwrite of Sampling Step',
407
+ # minimum=-1, maximum=200, step=1,
408
+ # value=modules.config.default_overwrite_step,
409
+ # info='Set as -1 to disable. For developer debugging.')
410
+ # overwrite_switch = gr.Slider(label='Forced Overwrite of Refiner Switch Step',
411
+ # minimum=-1, maximum=200, step=1,
412
+ # value=modules.config.default_overwrite_switch,
413
+ # info='Set as -1 to disable. For developer debugging.')
414
+ # overwrite_width = gr.Slider(label='Forced Overwrite of Generating Width',
415
+ # minimum=-1, maximum=2048, step=1, value=-1,
416
+ # info='Set as -1 to disable. For developer debugging. '
417
+ # 'Results will be worse for non-standard numbers that SDXL is not trained on.')
418
+ # overwrite_height = gr.Slider(label='Forced Overwrite of Generating Height',
419
+ # minimum=-1, maximum=2048, step=1, value=-1,
420
+ # info='Set as -1 to disable. For developer debugging. '
421
+ # 'Results will be worse for non-standard numbers that SDXL is not trained on.')
422
+ # overwrite_vary_strength = gr.Slider(label='Forced Overwrite of Denoising Strength of "Vary"',
423
+ # minimum=-1, maximum=1.0, step=0.001, value=-1,
424
+ # info='Set as negative number to disable. For developer debugging.')
425
+ # overwrite_upscale_strength = gr.Slider(label='Forced Overwrite of Denoising Strength of "Upscale"',
426
+ # minimum=-1, maximum=1.0, step=0.001, value=-1,
427
+ # info='Set as negative number to disable. For developer debugging.')
428
+ # disable_preview = gr.Checkbox(label='Disable Preview', value=False,
429
+ # info='Disable preview during generation.')
430
+ # disable_intermediate_results = gr.Checkbox(label='Disable Intermediate Results',
431
+ # value=modules.config.default_performance == 'Extreme Speed',
432
+ # interactive=modules.config.default_performance != 'Extreme Speed',
433
+ # info='Disable intermediate results during generation, only show final gallery.')
434
+ # disable_seed_increment = gr.Checkbox(label='Disable seed increment',
435
+ # info='Disable automatic seed increment when image number is > 1.',
436
+ # value=False)
437
+
438
+ # # if not args_manager.args.disable_metadata:
439
+ # # save_metadata_to_images = gr.Checkbox(label='Save Metadata to Images', value=modules.config.default_save_metadata_to_images,
440
+ # # info='Adds parameters to generated images allowing manual regeneration.')
441
+ # # metadata_scheme = gr.Radio(label='Metadata Scheme', choices=flags.metadata_scheme, value=modules.config.default_metadata_scheme,
442
+ # # info='Image Prompt parameters are not included. Use png and a1111 for compatibility with Civitai.',
443
+ # # visible=modules.config.default_save_metadata_to_images)
444
+
445
+ # # save_metadata_to_images.change(lambda x: gr.update(visible=x), inputs=[save_metadata_to_images], outputs=[metadata_scheme],
446
+ # # queue=False, show_progress=False)
447
+
448
+ # # with gr.Tab(label='Control'):
449
+ # # debugging_cn_preprocessor = gr.Checkbox(label='Debug Preprocessors', value=False,
450
+ # # info='See the results from preprocessors.')
451
+ # # skipping_cn_preprocessor = gr.Checkbox(label='Skip Preprocessors', value=False,
452
+ # # info='Do not preprocess images. (Inputs are already canny/depth/cropped-face/etc.)')
453
+
454
+ # # mixing_image_prompt_and_vary_upscale = gr.Checkbox(label='Mixing Image Prompt and Vary/Upscale',
455
+ # # value=False)
456
+ # # mixing_image_prompt_and_inpaint = gr.Checkbox(label='Mixing Image Prompt and Inpaint',
457
+ # # value=False)
458
+
459
+ # # controlnet_softness = gr.Slider(label='Softness of ControlNet', minimum=0.0, maximum=1.0,
460
+ # # step=0.001, value=0.25,
461
+ # # info='Similar to the Control Mode in A1111 (use 0.0 to disable). ')
462
+
463
+ # # with gr.Tab(label='Canny'):
464
+ # # canny_low_threshold = gr.Slider(label='Canny Low Threshold', minimum=1, maximum=255,
465
+ # # step=1, value=64)
466
+ # # canny_high_threshold = gr.Slider(label='Canny High Threshold', minimum=1, maximum=255,
467
+ # # step=1, value=128)
468
+
469
+ # # with gr.Tab(label='Inpaint'):
470
+ # # debugging_inpaint_preprocessor = gr.Checkbox(label='Debug Inpaint Preprocessing', value=False)
471
+ # # inpaint_disable_initial_latent = gr.Checkbox(label='Disable initial latent in inpaint', value=False)
472
+ # # inpaint_engine = gr.Dropdown(label='Inpaint Engine',
473
+ # # value=modules.config.default_inpaint_engine_version,
474
+ # # choices=flags.inpaint_engine_versions,
475
+ # # info='Version of Fooocus inpaint model')
476
+ # # inpaint_strength = gr.Slider(label='Inpaint Denoising Strength',
477
+ # # minimum=0.0, maximum=1.0, step=0.001, value=1.0,
478
+ # # info='Same as the denoising strength in A1111 inpaint. '
479
+ # # 'Only used in inpaint, not used in outpaint. '
480
+ # # '(Outpaint always use 1.0)')
481
+ # # inpaint_respective_field = gr.Slider(label='Inpaint Respective Field',
482
+ # # minimum=0.0, maximum=1.0, step=0.001, value=0.618,
483
+ # # info='The area to inpaint. '
484
+ # # 'Value 0 is same as "Only Masked" in A1111. '
485
+ # # 'Value 1 is same as "Whole Image" in A1111. '
486
+ # # 'Only used in inpaint, not used in outpaint. '
487
+ # # '(Outpaint always use 1.0)')
488
+ # # inpaint_erode_or_dilate = gr.Slider(label='Mask Erode or Dilate',
489
+ # # minimum=-64, maximum=64, step=1, value=0,
490
+ # # info='Positive value will make white area in the mask larger, '
491
+ # # 'negative value will make white area smaller.'
492
+ # # '(default is 0, always process before any mask invert)')
493
+ # # inpaint_mask_upload_checkbox = gr.Checkbox(label='Enable Mask Upload', value=False)
494
+ # # invert_mask_checkbox = gr.Checkbox(label='Invert Mask', value=False)
495
+
496
+ # # inpaint_ctrls = [debugging_inpaint_preprocessor, inpaint_disable_initial_latent, inpaint_engine,
497
+ # # inpaint_strength, inpaint_respective_field,
498
+ # # inpaint_mask_upload_checkbox, invert_mask_checkbox, inpaint_erode_or_dilate]
499
+
500
+ # # inpaint_mask_upload_checkbox.change(lambda x: gr.update(visible=x),
501
+ # # inputs=inpaint_mask_upload_checkbox,
502
+ # # outputs=inpaint_mask_image, queue=False, show_progress=False)
503
+
504
+ # with gr.Tab(label='FreeU'):
505
+ # freeu_enabled = gr.Checkbox(label='Enabled', value=False)
506
+ # freeu_b1 = gr.Slider(label='B1', minimum=0, maximum=2, step=0.01, value=1.01)
507
+ # freeu_b2 = gr.Slider(label='B2', minimum=0, maximum=2, step=0.01, value=1.02)
508
+ # freeu_s1 = gr.Slider(label='S1', minimum=0, maximum=4, step=0.01, value=0.99)
509
+ # freeu_s2 = gr.Slider(label='S2', minimum=0, maximum=4, step=0.01, value=0.95)
510
+ # freeu_ctrls = [freeu_enabled, freeu_b1, freeu_b2, freeu_s1, freeu_s2]
511
+
512
+ # def dev_mode_checked(r):
513
+ # return gr.update(visible=r)
514
+
515
+
516
+ # dev_mode.change(dev_mode_checked, inputs=[dev_mode], outputs=[dev_tools],
517
+ # queue=False, show_progress=False)
518
+
519
+ # def model_refresh_clicked():
520
+ # modules.config.update_all_model_names()
521
+ # results = [gr.update(choices=modules.config.model_filenames)]
522
+ # results += [gr.update(choices=['None'] + modules.config.model_filenames)]
523
+ # for i in range(modules.config.default_max_lora_number):
524
+ # results += [gr.update(interactive=True), gr.update(choices=['None'] + modules.config.lora_filenames), gr.update()]
525
+ # return results
526
+
527
+ # model_refresh.click(model_refresh_clicked, [], [base_model, refiner_model] + lora_ctrls,
528
+ # queue=False, show_progress=False)
529
+
530
+ # performance_selection.change(lambda x: [gr.update(interactive=x != 'Extreme Speed')] * 11 +
531
+ # [gr.update(visible=x != 'Extreme Speed')] * 1 +
532
+ # [gr.update(interactive=x != 'Extreme Speed', value=x == 'Extreme Speed', )] * 1,
533
+ # inputs=performance_selection,
534
+ # outputs=[
535
+ # guidance_scale, sharpness, adm_scaler_end, adm_scaler_positive,
536
+ # adm_scaler_negative, refiner_switch, refiner_model, sampler_name,
537
+ # scheduler_name, adaptive_cfg, refiner_swap_method, negative_prompt, disable_intermediate_results
538
+ # ], queue=False, show_progress=False)
539
+
540
+ # output_format.input(lambda x: gr.update(output_format=x), inputs=output_format)
541
+
542
+ # advanced_checkbox.change(lambda x: gr.update(visible=x), advanced_checkbox, advanced_column,
543
+ # queue=False, show_progress=False) \
544
+ # .then(fn=lambda: None, _js='refresh_grid_delayed', queue=False, show_progress=False)
545
+
546
+ # def inpaint_mode_change(mode):
547
+ # assert mode in modules.flags.inpaint_options
548
+
549
+ # # inpaint_additional_prompt, outpaint_selections, example_inpaint_prompts,
550
+ # # inpaint_disable_initial_latent, inpaint_engine,
551
+ # # inpaint_strength, inpaint_respective_field
552
+
553
+ # if mode == modules.flags.inpaint_option_detail:
554
+ # return [
555
+ # gr.update(visible=True), gr.update(visible=False, value=[]),
556
+ # gr.Dataset.update(visible=True, samples=modules.config.example_inpaint_prompts),
557
+ # False, 'None', 0.5, 0.0
558
+ # ]
559
+
560
+ # if mode == modules.flags.inpaint_option_modify:
561
+ # return [
562
+ # gr.update(visible=True), gr.update(visible=False, value=[]),
563
+ # gr.Dataset.update(visible=False, samples=modules.config.example_inpaint_prompts),
564
+ # True, modules.config.default_inpaint_engine_version, 1.0, 0.0
565
+ # ]
566
+
567
+ # return [
568
+ # gr.update(visible=False, value=''), gr.update(visible=True),
569
+ # gr.Dataset.update(visible=False, samples=modules.config.example_inpaint_prompts),
570
+ # False, modules.config.default_inpaint_engine_version, 1.0, 0.618
571
+ # ]
572
+
573
+ # inpaint_mode.input(inpaint_mode_change, inputs=inpaint_mode, outputs=[
574
+ # inpaint_additional_prompt, outpaint_selections, example_inpaint_prompts,
575
+ # inpaint_disable_initial_latent, inpaint_engine,
576
+ # inpaint_strength, inpaint_respective_field
577
+ # ], show_progress=False, queue=False)
578
+
579
+ # ctrls = [currentTask, generate_image_grid]
580
+ # ctrls += [
581
+ # prompt, negative_prompt, style_selections,
582
+ # performance_selection, aspect_ratios_selection, image_number, output_format, image_seed, sharpness, guidance_scale
583
+ # ]
584
+
585
+ # ctrls += [base_model, refiner_model, refiner_switch] + lora_ctrls
586
+ # # ctrls += [input_image_checkbox, current_tab]
587
+ # # ctrls += [uov_method, uov_input_image]
588
+ # # ctrls += [outpaint_selections, inpaint_input_image, inpaint_additional_prompt, inpaint_mask_image]
589
+ # ctrls += [disable_preview, disable_intermediate_results, disable_seed_increment]
590
+ # ctrls += [adm_scaler_positive, adm_scaler_negative, adm_scaler_end, adaptive_cfg]
591
+ # ctrls += [sampler_name, scheduler_name]
592
+ # ctrls += [overwrite_step, overwrite_switch, overwrite_width, overwrite_height, overwrite_vary_strength]
593
+ # ctrls += [overwrite_upscale_strength, mixing_image_prompt_and_vary_upscale, mixing_image_prompt_and_inpaint]
594
+ # ctrls += [debugging_cn_preprocessor, skipping_cn_preprocessor, canny_low_threshold, canny_high_threshold]
595
+ # ctrls += [refiner_swap_method, controlnet_softness]
596
+ # ctrls += freeu_ctrls
597
+ # ctrls += inpaint_ctrls
598
+
599
+ # if not args_manager.args.disable_metadata:
600
+ # ctrls += [save_metadata_to_images, metadata_scheme]
601
+
602
+ # ctrls += ip_ctrls
603
+
604
+ # state_is_generating = gr.State(False)
605
+
606
+ # def parse_meta(raw_prompt_txt, is_generating):
607
+ # loaded_json = None
608
+ # if is_json(raw_prompt_txt):
609
+ # loaded_json = json.loads(raw_prompt_txt)
610
+
611
+ # if loaded_json is None:
612
+ # if is_generating:
613
+ # return gr.update(), gr.update(), gr.update()
614
+ # else:
615
+ # return gr.update(), gr.update(visible=True), gr.update(visible=False)
616
+
617
+ # return json.dumps(loaded_json), gr.update(visible=False), gr.update(visible=True)
618
+
619
+ # prompt.input(parse_meta, inputs=[prompt, state_is_generating], outputs=[prompt, generate_button, load_parameter_button], queue=False, show_progress=False)
620
+
621
+ # load_data_outputs = [advanced_checkbox, image_number, prompt, negative_prompt, style_selections,
622
+ # performance_selection, overwrite_step, overwrite_switch, aspect_ratios_selection,
623
+ # overwrite_width, overwrite_height, guidance_scale, sharpness, adm_scaler_positive,
624
+ # adm_scaler_negative, adm_scaler_end, refiner_swap_method, adaptive_cfg, base_model,
625
+ # refiner_model, refiner_switch, sampler_name, scheduler_name, seed_random, image_seed,
626
+ # generate_button, load_parameter_button] + freeu_ctrls + lora_ctrls
627
+
628
+ # load_parameter_button.click(modules.meta_parser.load_parameter_button_click, inputs=[prompt, state_is_generating], outputs=load_data_outputs, queue=False, show_progress=False)
629
+
630
+ # # def trigger_metadata_import(filepath, state_is_generating):
631
+ # # parameters, metadata_scheme = modules.meta_parser.read_info_from_image(filepath)
632
+ # # if parameters is None:
633
+ # # print('Could not find metadata in the image!')
634
+ # # parsed_parameters = {}
635
+ # # else:
636
+ # # metadata_parser = modules.meta_parser.get_metadata_parser(metadata_scheme)
637
+ # # parsed_parameters = metadata_parser.parse_json(parameters)
638
+
639
+ # # return modules.meta_parser.load_parameter_button_click(parsed_parameters, state_is_generating)
640
+
641
+
642
+ # # metadata_import_button.click(trigger_metadata_import, inputs=[metadata_input_image, state_is_generating], outputs=load_data_outputs, queue=False, show_progress=True) \
643
+ # # .then(style_sorter.sort_styles, inputs=style_selections, outputs=style_selections, queue=False, show_progress=False)
644
+
645
+ # generate_button.click(lambda: (gr.update(visible=True, interactive=True), gr.update(visible=True, interactive=True), gr.update(visible=False, interactive=False), [], True),
646
+ # outputs=[stop_button, skip_button, generate_button, gallery, state_is_generating]) \
647
+ # .then(fn=refresh_seed, inputs=[seed_random, image_seed], outputs=image_seed) \
648
+ # .then(fn=get_task, inputs=ctrls, outputs=currentTask) \
649
+ # .then(fn=generate_clicked, inputs=currentTask, outputs=[progress_html, progress_window, progress_gallery, gallery]) \
650
+ # .then(lambda: (gr.update(visible=True, interactive=True), gr.update(visible=False, interactive=False), gr.update(visible=False, interactive=False), False),
651
+ # outputs=[generate_button, stop_button, skip_button, state_is_generating]) \
652
+ # .then(fn=update_history_link, outputs=history_link) \
653
+ # .then(fn=lambda: None, _js='playNotification').then(fn=lambda: None, _js='refresh_grid_delayed')
654
+
655
+ for notification_file in ['notification.ogg', 'notification.mp3']:
656
+ if os.path.exists(notification_file):
657
+ gr.Audio(interactive=False, value=notification_file, elem_id='audio_notification', visible=False)
658
+ break
659
+
660
+ def trigger_describe(mode, img):
661
+ if mode == flags.desc_type_photo:
662
+ from extras.interrogate import default_interrogator as default_interrogator_photo
663
+ return default_interrogator_photo(img), ["Fooocus V2", "Fooocus Enhance", "Fooocus Sharp"]
664
+ if mode == flags.desc_type_anime:
665
+ from extras.wd14tagger import default_interrogator as default_interrogator_anime
666
+ return default_interrogator_anime(img), ["Fooocus V2", "Fooocus Masterpiece"]
667
+ return mode, ["Fooocus V2"]
668
+
669
+ desc_btn.click(trigger_describe, inputs=[desc_method, desc_input_image],
670
+ outputs=prompt, show_progress=True, queue=True)
671
+
672
+
673
+ def dump_default_english_config():
674
+ from modules.localization import dump_english_config
675
+ dump_english_config(grh.all_components)
676
+
677
+
678
+ # dump_default_english_config()
679
+
680
+ shared.gradio_root.launch(
681
+ inbrowser=args_manager.args.in_browser,
682
+ server_name=args_manager.args.listen,
683
+ server_port=args_manager.args.port,
684
+ share=args_manager.args.share,
685
+ auth=check_auth if (args_manager.args.share or args_manager.args.listen) and auth_enabled else None,
686
+ allowed_paths=[modules.config.path_outputs],
687
+ blocked_paths=[constants.AUTH_FILENAME]
688
+ )
app.html ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <script
2
+ type="module"
3
+ src="https://gradio.s3-us-west-2.amazonaws.com/4.21.0/gradio.js"
4
+ ></script>
5
+
6
+ <gradio-app src="https://Adityadn-test.hf.space"></gradio-app>
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ print("Wait..")
2
+
3
+ def test():
4
+ import gradio as gr
5
+
6
+ def analyze_text(text):
7
+ # Lakukan analisis atau pemrosesan teks di sini
8
+ result = f"Anda memasukkan teks: {text}"
9
+ return result
10
+
11
+ iface = gr.Interface(
12
+ fn=analyze_text,
13
+ inputs=gr.Textbox(), # Menggunakan input textbox
14
+ outputs="text" # Menetapkan output ke tipe teks
15
+ )
16
+
17
+ iface.launch()
18
+
19
+ def process():
20
+ import subprocess
21
+
22
+ def uninstall_and_install_gradio(version):
23
+ # Uninstall current Gradio
24
+ uninstall_command = ["pip", "uninstall", "gradio", "-y"]
25
+ subprocess.run(uninstall_command)
26
+
27
+ # Install specific version of Gradio
28
+ install_command = ["pip", "install", f"gradio=={version}"]
29
+ subprocess.run(install_command)
30
+
31
+ # Gantilah "3.41.2" dengan versi Gradio yang diinginkan
32
+ desired_version = "3.41.2"
33
+
34
+ # Periksa versi Gradio yang terinstal
35
+ current_version_command = ["pip", "show", "gradio"]
36
+ result = subprocess.run(current_version_command, capture_output=True, text=True)
37
+ current_version = None
38
+
39
+ if "Version" in result.stdout:
40
+ current_version = result.stdout.split("Version:")[1].strip()
41
+
42
+ # Cek dan lakukan uninstall dan install jika versi tidak sesuai
43
+ if current_version != desired_version:
44
+ uninstall_and_install_gradio(desired_version)
45
+ print(f"Gradio has been updated to version {desired_version}")
46
+ else:
47
+ print(f"Gradio is already at version {desired_version}")
48
+
49
+ python_script = "entry_with_update.py"
50
+
51
+ # Argument yang ingin Anda tambahkan
52
+ # additional_arguments = ["--in-browser", "--all-in-fp32", "--directml", "--debug-mode", "--multi-user", "--always-cpu", "--is-windows-embedded-python"]
53
+ additional_arguments = ["--always-cpu"]
54
+
55
+ # Gabungkan semua argumen
56
+ PIP = ["pip", "install", "-r", "requirements.txt"]
57
+ command = ["python", python_script] + additional_arguments
58
+
59
+ # Jalankan skrip menggunakan subprocess
60
+ subprocess.run(PIP)
61
+ print("Installing..")
62
+
63
+ subprocess.run(command)# Menjalankan file batch
64
+ print("Running..")
65
+ # subprocess.run([batch_file_path], shell=True)
66
+
67
+ process()
args_manager.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ldm_patched.modules.args_parser as args_parser
2
+ import os
3
+
4
+ from tempfile import gettempdir
5
+
6
+ args_parser.parser.add_argument("--share", action='store_true', help="Set whether to share on Gradio.")
7
+ args_parser.parser.add_argument("--preset", type=str, default=None, help="Apply specified UI preset.")
8
+
9
+ args_parser.parser.add_argument("--language", type=str, default='default',
10
+ help="Translate UI using json files in [language] folder. "
11
+ "For example, [--language example] will use [language/example.json] for translation.")
12
+
13
+ # For example, https://github.com/lllyasviel/Fooocus/issues/849
14
+ args_parser.parser.add_argument("--disable-offload-from-vram", action="store_true",
15
+ help="Force loading models to vram when the unload can be avoided. "
16
+ "Some Mac users may need this.")
17
+
18
+ args_parser.parser.add_argument("--theme", type=str, help="launches the UI with light or dark theme", default=None)
19
+ args_parser.parser.add_argument("--disable-image-log", action='store_true',
20
+ help="Prevent writing images and logs to hard drive.")
21
+
22
+ args_parser.parser.add_argument("--disable-analytics", action='store_true',
23
+ help="Disables analytics for Gradio.")
24
+
25
+ args_parser.parser.add_argument("--disable-metadata", action='store_true',
26
+ help="Disables saving metadata to images.")
27
+
28
+ args_parser.parser.add_argument("--disable-preset-download", action='store_true',
29
+ help="Disables downloading models for presets", default=False)
30
+
31
+ args_parser.parser.add_argument("--always-download-new-model", action='store_true',
32
+ help="Always download newer models ", default=False)
33
+
34
+ args_parser.parser.set_defaults(
35
+ disable_cuda_malloc=True,
36
+ in_browser=True,
37
+ port=None
38
+ )
39
+
40
+ args_parser.args = args_parser.parser.parse_args()
41
+
42
+ # (Disable by default because of issues like https://github.com/lllyasviel/Fooocus/issues/724)
43
+ args_parser.args.always_offload_from_vram = not args_parser.args.disable_offload_from_vram
44
+
45
+ if args_parser.args.disable_analytics:
46
+ import os
47
+ os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
48
+
49
+ if args_parser.args.disable_in_browser:
50
+ args_parser.args.in_browser = False
51
+
52
+ if args_parser.args.temp_path is None:
53
+ args_parser.args.temp_path = os.path.join(gettempdir(), 'Fooocus')
54
+
55
+ args = args_parser.args
auth-example.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "user": "sitting-duck-1",
4
+ "pass": "very-bad-publicly-known-password-change-it"
5
+ }
6
+ ]
auth.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "user": "user123",
4
+ "pass": "pass123"
5
+ }
6
+ ]
build_launcher.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ win32_root = os.path.dirname(os.path.dirname(__file__))
4
+ python_embeded_path = os.path.join(win32_root, 'python_embeded')
5
+
6
+ is_win32_standalone_build = os.path.exists(python_embeded_path) and os.path.isdir(python_embeded_path)
7
+
8
+ win32_cmd = '''
9
+ .\python_embeded\python.exe -s Fooocus\entry_with_update.py {cmds} %*
10
+ pause
11
+ '''
12
+
13
+
14
+ def build_launcher():
15
+ if not is_win32_standalone_build:
16
+ return
17
+
18
+ presets = [None, 'anime', 'realistic']
19
+
20
+ for preset in presets:
21
+ win32_cmd_preset = win32_cmd.replace('{cmds}', '' if preset is None else f'--preset {preset}')
22
+ bat_path = os.path.join(win32_root, 'run.bat' if preset is None else f'run_{preset}.bat')
23
+ if not os.path.exists(bat_path):
24
+ with open(bat_path, "w", encoding="utf-8") as f:
25
+ f.write(win32_cmd_preset)
26
+ return
config.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "path_checkpoints": [
3
+ "models\\checkpoints"
4
+ ],
5
+ "path_loras": [
6
+ "models\\loras"
7
+ ],
8
+ "path_embeddings": "models\\embeddings",
9
+ "path_vae_approx": "models\\vae_approx",
10
+ "path_upscale_models": "models\\upscale_models",
11
+ "path_inpaint": "models\\inpaint",
12
+ "path_controlnet": "models\\controlnet",
13
+ "path_clip_vision": "models\\clip_vision",
14
+ "path_fooocus_expansion": "models\\prompt_expansion\\fooocus_expansion",
15
+ "path_outputs": "outputs"
16
+ }
config_modification_tutorial.txt ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You can modify your "D:\\ADITYA FILE\\Developer\\MICROSOFT\\Microsoft Visual Studio Code\\Project\\Application Website\\Nyxel\\Flowly AI\\My Project\\AI Image\\config.txt" using the below keys, formats, and examples.
2
+ Do not modify this file. Modifications in this file will not take effect.
3
+ This file is a tutorial and example. Please edit "D:\\ADITYA FILE\\Developer\\MICROSOFT\\Microsoft Visual Studio Code\\Project\\Application Website\\Nyxel\\Flowly AI\\My Project\\AI Image\\config.txt" to really change any settings.
4
+ Remember to split the paths with "\\" rather than "\", and there is no "," before the last "}".
5
+
6
+
7
+ {
8
+ "path_checkpoints": [
9
+ "models\\checkpoints"
10
+ ],
11
+ "path_loras": [
12
+ "models\\loras"
13
+ ],
14
+ "path_embeddings": "models\\embeddings",
15
+ "path_vae_approx": "models\\vae_approx",
16
+ "path_upscale_models": "models\\upscale_models",
17
+ "path_inpaint": "models\\inpaint",
18
+ "path_controlnet": "models\\controlnet",
19
+ "path_clip_vision": "models\\clip_vision",
20
+ "path_fooocus_expansion": "models\\prompt_expansion\\fooocus_expansion",
21
+ "path_outputs": "outputs",
22
+ "default_model": "juggernautXL_v8Rundiffusion.safetensors",
23
+ "previous_default_models": [
24
+ "juggernautXL_version8Rundiffusion.safetensors",
25
+ "juggernautXL_version7Rundiffusion.safetensors",
26
+ "juggernautXL_v7Rundiffusion.safetensors",
27
+ "juggernautXL_version6Rundiffusion.safetensors",
28
+ "juggernautXL_v6Rundiffusion.safetensors"
29
+ ],
30
+ "default_refiner": "None",
31
+ "default_refiner_switch": 0.5,
32
+ "default_loras_min_weight": -2,
33
+ "default_loras_max_weight": 2,
34
+ "default_loras": [
35
+ [
36
+ "sd_xl_offset_example-lora_1.0.safetensors",
37
+ 0.1
38
+ ],
39
+ [
40
+ "None",
41
+ 1.0
42
+ ],
43
+ [
44
+ "None",
45
+ 1.0
46
+ ],
47
+ [
48
+ "None",
49
+ 1.0
50
+ ],
51
+ [
52
+ "None",
53
+ 1.0
54
+ ]
55
+ ],
56
+ "default_max_lora_number": 5,
57
+ "default_cfg_scale": 4.0,
58
+ "default_sample_sharpness": 2.0,
59
+ "default_sampler": "dpmpp_2m_sde_gpu",
60
+ "default_scheduler": "karras",
61
+ "default_styles": [
62
+ "Fooocus V2",
63
+ "Fooocus Enhance",
64
+ "Fooocus Sharp"
65
+ ],
66
+ "default_prompt_negative": "",
67
+ "default_prompt": "",
68
+ "default_performance": "Speed",
69
+ "default_advanced_checkbox": false,
70
+ "default_max_image_number": 32,
71
+ "default_output_format": "png",
72
+ "default_image_number": 2,
73
+ "checkpoint_downloads": {
74
+ "juggernautXL_v8Rundiffusion.safetensors": "https://huggingface.co/lllyasviel/fav_models/resolve/main/fav/juggernautXL_v8Rundiffusion.safetensors"
75
+ },
76
+ "lora_downloads": {
77
+ "sd_xl_offset_example-lora_1.0.safetensors": "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_offset_example-lora_1.0.safetensors"
78
+ },
79
+ "embeddings_downloads": {},
80
+ "available_aspect_ratios": [
81
+ "704*1408",
82
+ "704*1344",
83
+ "768*1344",
84
+ "768*1280",
85
+ "832*1216",
86
+ "832*1152",
87
+ "896*1152",
88
+ "896*1088",
89
+ "960*1088",
90
+ "960*1024",
91
+ "1024*1024",
92
+ "1024*960",
93
+ "1088*960",
94
+ "1088*896",
95
+ "1152*896",
96
+ "1152*832",
97
+ "1216*832",
98
+ "1280*768",
99
+ "1344*768",
100
+ "1344*704",
101
+ "1408*704",
102
+ "1472*704",
103
+ "1536*640",
104
+ "1600*640",
105
+ "1664*576",
106
+ "1728*576"
107
+ ],
108
+ "default_aspect_ratio": "1152*896",
109
+ "default_inpaint_engine_version": "v2.6",
110
+ "default_cfg_tsnr": 7.0,
111
+ "default_overwrite_step": -1,
112
+ "default_overwrite_switch": -1,
113
+ "example_inpaint_prompts": [
114
+ "highly detailed face",
115
+ "detailed girl face",
116
+ "detailed man face",
117
+ "detailed hand",
118
+ "beautiful eyes"
119
+ ],
120
+ "default_save_metadata_to_images": true,
121
+ "default_metadata_scheme": "fooocus",
122
+ "metadata_created_by": ""
123
+ }
css/style.css ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* based on https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/v1.6.0/style.css */
2
+
3
+ #context-menu{
4
+ z-index:9999;
5
+ position:absolute;
6
+ display:block;
7
+ padding:0px 0;
8
+ border:2px solid #a55000;
9
+ border-radius:8px;
10
+ box-shadow:1px 1px 2px #CE6400;
11
+ width: 200px;
12
+ }
13
+
14
+ .context-menu-items{
15
+ list-style: none;
16
+ margin: 0;
17
+ padding: 0;
18
+ }
19
+
20
+ .context-menu-items a{
21
+ display:block;
22
+ padding:5px;
23
+ cursor:pointer;
24
+ }
25
+
26
+ .context-menu-items a:hover{
27
+ background: #a55000;
28
+ }
29
+
30
+ .canvas-tooltip-info {
31
+ position: absolute;
32
+ top: 28px;
33
+ left: 2px;
34
+ cursor: help;
35
+ background-color: rgba(0, 0, 0, 0.3);
36
+ width: 20px;
37
+ height: 20px;
38
+ border-radius: 50%;
39
+ display: flex;
40
+ align-items: center;
41
+ justify-content: center;
42
+ flex-direction: column;
43
+
44
+ z-index: 100;
45
+ }
46
+
47
+ .canvas-tooltip-info::after {
48
+ content: '';
49
+ display: block;
50
+ width: 2px;
51
+ height: 7px;
52
+ background-color: white;
53
+ margin-top: 2px;
54
+ }
55
+
56
+ .canvas-tooltip-info::before {
57
+ content: '';
58
+ display: block;
59
+ width: 2px;
60
+ height: 2px;
61
+ background-color: white;
62
+ }
63
+
64
+ .canvas-tooltip-content {
65
+ display: none;
66
+ background-color: #f9f9f9;
67
+ color: #333;
68
+ border: 1px solid #ddd;
69
+ padding: 15px;
70
+ position: absolute;
71
+ top: 40px;
72
+ left: 10px;
73
+ width: 250px;
74
+ font-size: 16px;
75
+ opacity: 0;
76
+ border-radius: 8px;
77
+ box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
78
+
79
+ z-index: 100;
80
+ }
81
+
82
+ .canvas-tooltip:hover .canvas-tooltip-content {
83
+ display: block;
84
+ animation: fadeIn 0.5s;
85
+ opacity: 1;
86
+ }
87
+
88
+ @keyframes fadeIn {
89
+ from {opacity: 0;}
90
+ to {opacity: 1;}
91
+ }
92
+
93
+ .styler {
94
+ overflow:inherit !important;
95
+ }
96
+
97
+ .gradio-container{
98
+ overflow: visible;
99
+ }
100
+
101
+ /* fullpage image viewer */
102
+
103
+ #lightboxModal{
104
+ display: none;
105
+ position: fixed;
106
+ z-index: 1001;
107
+ left: 0;
108
+ top: 0;
109
+ width: 100%;
110
+ height: 100%;
111
+ overflow: auto;
112
+ background-color: rgba(20, 20, 20, 0.95);
113
+ user-select: none;
114
+ -webkit-user-select: none;
115
+ flex-direction: column;
116
+ }
117
+
118
+ .modalControls {
119
+ display: flex;
120
+ position: absolute;
121
+ right: 0px;
122
+ left: 0px;
123
+ gap: 1em;
124
+ padding: 1em;
125
+ background-color:rgba(0,0,0,0);
126
+ z-index: 1;
127
+ transition: 0.2s ease background-color;
128
+ }
129
+ .modalControls:hover {
130
+ background-color:rgba(0,0,0,0.9);
131
+ }
132
+ .modalClose {
133
+ margin-left: auto;
134
+ }
135
+ .modalControls span{
136
+ color: white;
137
+ text-shadow: 0px 0px 0.25em black;
138
+ font-size: 35px;
139
+ font-weight: bold;
140
+ cursor: pointer;
141
+ width: 1em;
142
+ }
143
+
144
+ .modalControls span:hover, .modalControls span:focus{
145
+ color: #999;
146
+ text-decoration: none;
147
+ }
148
+
149
+ #lightboxModal > img {
150
+ display: block;
151
+ margin: auto;
152
+ width: auto;
153
+ }
154
+
155
+ #lightboxModal > img.modalImageFullscreen{
156
+ object-fit: contain;
157
+ height: 100%;
158
+ width: 100%;
159
+ min-height: 0;
160
+ }
161
+
162
+ .modalPrev,
163
+ .modalNext {
164
+ cursor: pointer;
165
+ position: absolute;
166
+ top: 50%;
167
+ width: auto;
168
+ padding: 16px;
169
+ margin-top: -50px;
170
+ color: white;
171
+ font-weight: bold;
172
+ font-size: 20px;
173
+ transition: 0.6s ease;
174
+ border-radius: 0 3px 3px 0;
175
+ user-select: none;
176
+ -webkit-user-select: none;
177
+ }
178
+
179
+ .modalNext {
180
+ right: 0;
181
+ border-radius: 3px 0 0 3px;
182
+ }
183
+
184
+ .modalPrev:hover,
185
+ .modalNext:hover {
186
+ background-color: rgba(0, 0, 0, 0.8);
187
+ }
188
+
189
+ #imageARPreview {
190
+ position: absolute;
191
+ top: 0px;
192
+ left: 0px;
193
+ border: 2px solid red;
194
+ background: rgba(255, 0, 0, 0.3);
195
+ z-index: 900;
196
+ pointer-events: none;
197
+ display: none;
198
+ }
199
+
200
+ #stylePreviewOverlay {
201
+ opacity: 0;
202
+ pointer-events: none;
203
+ width: 128px;
204
+ height: 128px;
205
+ position: fixed;
206
+ top: 0px;
207
+ left: 0px;
208
+ border: solid 1px lightgrey;
209
+ transform: translate(-140px, 20px);
210
+ background-size: cover;
211
+ background-position: center;
212
+ background-color: rgba(0, 0, 0, 0.3);
213
+ border-radius: 5px;
214
+ z-index: 100;
215
+ transition: transform 0.1s ease, opacity 0.3s ease;
216
+ }
217
+
218
+ #stylePreviewOverlay.lower-half {
219
+ transform: translate(-140px, -140px);
220
+ }
entry_with_update.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+
5
+ root = os.path.dirname(os.path.abspath(__file__))
6
+ sys.path.append(root)
7
+ os.chdir(root)
8
+
9
+
10
+ try:
11
+ import pygit2
12
+ pygit2.option(pygit2.GIT_OPT_SET_OWNER_VALIDATION, 0)
13
+
14
+ repo = pygit2.Repository(os.path.abspath(os.path.dirname(__file__)))
15
+
16
+ branch_name = repo.head.shorthand
17
+
18
+ remote_name = 'origin'
19
+ remote = repo.remotes[remote_name]
20
+
21
+ remote.fetch()
22
+
23
+ local_branch_ref = f'refs/heads/{branch_name}'
24
+ local_branch = repo.lookup_reference(local_branch_ref)
25
+
26
+ remote_reference = f'refs/remotes/{remote_name}/{branch_name}'
27
+ remote_commit = repo.revparse_single(remote_reference)
28
+
29
+ merge_result, _ = repo.merge_analysis(remote_commit.id)
30
+
31
+ if merge_result & pygit2.GIT_MERGE_ANALYSIS_UP_TO_DATE:
32
+ print("Already up-to-date")
33
+ elif merge_result & pygit2.GIT_MERGE_ANALYSIS_FASTFORWARD:
34
+ local_branch.set_target(remote_commit.id)
35
+ repo.head.set_target(remote_commit.id)
36
+ repo.checkout_tree(repo.get(remote_commit.id))
37
+ repo.reset(local_branch.target, pygit2.GIT_RESET_HARD)
38
+ print("Fast-forward merge")
39
+ elif merge_result & pygit2.GIT_MERGE_ANALYSIS_NORMAL:
40
+ print("Update failed - Did you modify any file?")
41
+ except Exception as e:
42
+ print('Update failed.')
43
+ print(str(e))
44
+
45
+ print('Update succeeded.')
46
+ from launch import *
entrypoint.sh ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ ORIGINALDIR=/content/app
4
+ # Use predefined DATADIR if it is defined
5
+ [[ x"${DATADIR}" == "x" ]] && DATADIR=/content/data
6
+
7
+ # Make persistent dir from original dir
8
+ function mklink () {
9
+ mkdir -p $DATADIR/$1
10
+ ln -s $DATADIR/$1 $ORIGINALDIR
11
+ }
12
+
13
+ # Copy old files from import dir
14
+ function import () {
15
+ (test -d /import/$1 && cd /import/$1 && cp -Rpn . $DATADIR/$1/)
16
+ }
17
+
18
+ cd $ORIGINALDIR
19
+
20
+ # models
21
+ mklink models
22
+ # Copy original files
23
+ (cd $ORIGINALDIR/models.org && cp -Rpn . $ORIGINALDIR/models/)
24
+ # Import old files
25
+ import models
26
+
27
+ # outputs
28
+ mklink outputs
29
+ # Import old files
30
+ import outputs
31
+
32
+ # Start application
33
+ python launch.py $*
environment.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ name: fooocus
2
+ channels:
3
+ - defaults
4
+ dependencies:
5
+ - python=3.10
6
+ - pip=23.0
7
+ - packaging
experiments_expansion.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from modules.expansion import FooocusExpansion
2
+
3
+ expansion = FooocusExpansion()
4
+
5
+ text = 'a handsome man'
6
+
7
+ for i in range(64):
8
+ print(expansion(text, seed=i))
experiments_face.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import extras.face_crop as cropper
3
+
4
+
5
+ img = cv2.imread('lena.png')
6
+ result = cropper.crop_image(img)
7
+ cv2.imwrite('lena_result.png', result)
experiments_interrogate.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+
5
+ root = os.path.dirname(os.path.abspath(__file__))
6
+ sys.path.append(root)
7
+ os.chdir(root)
8
+
9
+
10
+ try:
11
+ import pygit2
12
+ pygit2.option(pygit2.GIT_OPT_SET_OWNER_VALIDATION, 0)
13
+
14
+ repo = pygit2.Repository(os.path.abspath(os.path.dirname(__file__)))
15
+
16
+ branch_name = repo.head.shorthand
17
+
18
+ remote_name = 'origin'
19
+ remote = repo.remotes[remote_name]
20
+
21
+ remote.fetch()
22
+
23
+ local_branch_ref = f'refs/heads/{branch_name}'
24
+ local_branch = repo.lookup_reference(local_branch_ref)
25
+
26
+ remote_reference = f'refs/remotes/{remote_name}/{branch_name}'
27
+ remote_commit = repo.revparse_single(remote_reference)
28
+
29
+ merge_result, _ = repo.merge_analysis(remote_commit.id)
30
+
31
+ if merge_result & pygit2.GIT_MERGE_ANALYSIS_UP_TO_DATE:
32
+ print("Already up-to-date")
33
+ elif merge_result & pygit2.GIT_MERGE_ANALYSIS_FASTFORWARD:
34
+ local_branch.set_target(remote_commit.id)
35
+ repo.head.set_target(remote_commit.id)
36
+ repo.checkout_tree(repo.get(remote_commit.id))
37
+ repo.reset(local_branch.target, pygit2.GIT_RESET_HARD)
38
+ print("Fast-forward merge")
39
+ elif merge_result & pygit2.GIT_MERGE_ANALYSIS_NORMAL:
40
+ print("Update failed - Did you modify any file?")
41
+ except Exception as e:
42
+ print('Update failed.')
43
+ print(str(e))
44
+
45
+ import os
46
+ import sys
47
+ import ssl
48
+
49
+ print('[System ARGV] ' + str(sys.argv))
50
+
51
+ root = os.path.dirname(os.path.abspath(__file__))
52
+ sys.path.append(root)
53
+ os.chdir(root)
54
+
55
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
56
+ os.environ["PYTORCH_MPS_HIGH_WATERMARK_RATIO"] = "0.0"
57
+ if "GRADIO_SERVER_PORT" not in os.environ:
58
+ os.environ["GRADIO_SERVER_PORT"] = "7865"
59
+
60
+ ssl._create_default_https_context = ssl._create_unverified_context
61
+
62
+
63
+ import platform
64
+ import fooocus_version
65
+
66
+ from build_launcher import build_launcher
67
+ from modules.launch_util import is_installed, run, python, run_pip, requirements_met
68
+ from modules.model_loader import load_file_from_url
69
+
70
+
71
+ REINSTALL_ALL = False
72
+ TRY_INSTALL_XFORMERS = False
73
+
74
+
75
+ def prepare_environment():
76
+ torch_index_url = os.environ.get('TORCH_INDEX_URL', "https://download.pytorch.org/whl/cu121")
77
+ torch_command = os.environ.get('TORCH_COMMAND',
78
+ f"pip install torch==2.1.0 torchvision==0.16.0 --extra-index-url {torch_index_url}")
79
+ requirements_file = os.environ.get('REQS_FILE', "requirements_versions.txt")
80
+
81
+ print(f"Python {sys.version}")
82
+ print(f"Fooocus version: {fooocus_version.version}")
83
+
84
+ if REINSTALL_ALL or not is_installed("torch") or not is_installed("torchvision"):
85
+ run(f'"{python}" -m {torch_command}', "Installing torch and torchvision", "Couldn't install torch", live=True)
86
+
87
+ if TRY_INSTALL_XFORMERS:
88
+ if REINSTALL_ALL or not is_installed("xformers"):
89
+ xformers_package = os.environ.get('XFORMERS_PACKAGE', 'xformers==0.0.23')
90
+ if platform.system() == "Windows":
91
+ if platform.python_version().startswith("3.10"):
92
+ run_pip(f"install -U -I --no-deps {xformers_package}", "xformers", live=True)
93
+ else:
94
+ print("Installation of xformers is not supported in this version of Python.")
95
+ print(
96
+ "You can also check this and build manually: https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Xformers#building-xformers-on-windows-by-duckness")
97
+ if not is_installed("xformers"):
98
+ exit(0)
99
+ elif platform.system() == "Linux":
100
+ run_pip(f"install -U -I --no-deps {xformers_package}", "xformers")
101
+
102
+ if REINSTALL_ALL or not requirements_met(requirements_file):
103
+ run_pip(f"install -r \"{requirements_file}\"", "requirements")
104
+
105
+ return
106
+
107
+
108
+ vae_approx_filenames = [
109
+ ('xlvaeapp.pth', 'https://huggingface.co/lllyasviel/misc/resolve/main/xlvaeapp.pth'),
110
+ ('vaeapp_sd15.pth', 'https://huggingface.co/lllyasviel/misc/resolve/main/vaeapp_sd15.pt'),
111
+ ('xl-to-v1_interposer-v3.1.safetensors',
112
+ 'https://huggingface.co/lllyasviel/misc/resolve/main/xl-to-v1_interposer-v3.1.safetensors')
113
+ ]
114
+
115
+ def ini_args():
116
+ from args_manager import args
117
+ return args
118
+
119
+
120
+ prepare_environment()
121
+ build_launcher()
122
+ args = ini_args()
123
+
124
+
125
+ if args.gpu_device_id is not None:
126
+ os.environ['CUDA_VISIBLE_DEVICES'] = str(args.gpu_device_id)
127
+ print("Set device to:", args.gpu_device_id)
128
+
129
+
130
+ from modules import config
131
+
132
+ def download_models():
133
+ for file_name, url in vae_approx_filenames:
134
+ load_file_from_url(url=url, model_dir=config.path_vae_approx, file_name=file_name)
135
+
136
+ load_file_from_url(
137
+ url='https://huggingface.co/lllyasviel/misc/resolve/main/fooocus_expansion.bin',
138
+ model_dir=config.path_fooocus_expansion,
139
+ file_name='pytorch_model.bin'
140
+ )
141
+
142
+ if args.disable_preset_download:
143
+ print('Skipped model download.')
144
+ return
145
+
146
+ if not args.always_download_new_model:
147
+ if not os.path.exists(os.path.join(config.paths_checkpoints[0], config.default_base_model_name)):
148
+ for alternative_model_name in config.previous_default_models:
149
+ if os.path.exists(os.path.join(config.paths_checkpoints[0], alternative_model_name)):
150
+ print(f'You do not have [{config.default_base_model_name}] but you have [{alternative_model_name}].')
151
+ print(f'Fooocus will use [{alternative_model_name}] to avoid downloading new models, '
152
+ f'but you are not using latest models.')
153
+ print('Use --always-download-new-model to avoid fallback and always get new models.')
154
+ config.checkpoint_downloads = {}
155
+ config.default_base_model_name = alternative_model_name
156
+ break
157
+
158
+ for file_name, url in config.checkpoint_downloads.items():
159
+ load_file_from_url(url=url, model_dir=config.paths_checkpoints[0], file_name=file_name)
160
+ for file_name, url in config.embeddings_downloads.items():
161
+ load_file_from_url(url=url, model_dir=config.path_embeddings, file_name=file_name)
162
+ for file_name, url in config.lora_downloads.items():
163
+ load_file_from_url(url=url, model_dir=config.paths_loras[0], file_name=file_name)
164
+
165
+ return
166
+
167
+
168
+ download_models()
169
+
170
+ import gradio as gr
171
+ import modules.gradio_hijack as grh
172
+ from extras.interrogate import default_interrogator as default_interrogator_photo
173
+ from extras.wd14tagger import default_interrogator as default_interrogator_anime
174
+ import modules.flags as flags
175
+
176
+ def interrogatorFunction(img, value):
177
+ if value == flags.desc_type_photo: # Menggunakan operator perbandingan '==' untuk memeriksa kesamaan
178
+ output = default_interrogator_photo(img)
179
+ print(output)
180
+ else:
181
+ output = default_interrogator_anime(img)
182
+ print(output)
183
+ return output
184
+
185
+ describe = gr.Blocks(title="AI Describe Image", css="#component-3, #component-5 {display: grid; align-content: center;}")
186
+
187
+ with describe:
188
+ describe_tab = gr.TabItem(label='Describe')
189
+ with describe_tab:
190
+ input_column = gr.Row()
191
+ with input_column:
192
+ with gr.Column():
193
+ input_image = grh.Image(label='Input', source='upload', type='numpy')
194
+ with gr.Column():
195
+ content_type = gr.Radio(
196
+ label='Content Type',
197
+ choices=[flags.desc_type_photo, flags.desc_type_anime],
198
+ value=flags.desc_type_photo
199
+ )
200
+ desc_btn = gr.Button(value='Describe this Image into Prompt')
201
+ outputs=gr.Textbox(type="text", label="Output", show_copy_button=True)
202
+
203
+ desc_btn.click(interrogatorFunction, inputs=[input_image, content_type], outputs=[outputs])
204
+
205
+ describe.launch()
extras/BLIP/configs/bert_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertModel"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "hidden_act": "gelu",
7
+ "hidden_dropout_prob": 0.1,
8
+ "hidden_size": 768,
9
+ "initializer_range": 0.02,
10
+ "intermediate_size": 3072,
11
+ "layer_norm_eps": 1e-12,
12
+ "max_position_embeddings": 512,
13
+ "model_type": "bert",
14
+ "num_attention_heads": 12,
15
+ "num_hidden_layers": 12,
16
+ "pad_token_id": 0,
17
+ "type_vocab_size": 2,
18
+ "vocab_size": 30522,
19
+ "encoder_width": 768,
20
+ "add_cross_attention": true
21
+ }
extras/BLIP/configs/caption_coco.yaml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ image_root: '/export/share/datasets/vision/coco/images/'
2
+ ann_root: 'annotation'
3
+ coco_gt_root: 'annotation/coco_gt'
4
+
5
+ # set pretrained as a file path or an url
6
+ pretrained: 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_caption_capfilt_large.pth'
7
+
8
+ # size of vit model; base or large
9
+ vit: 'base'
10
+ vit_grad_ckpt: False
11
+ vit_ckpt_layer: 0
12
+ batch_size: 32
13
+ init_lr: 1e-5
14
+
15
+ # vit: 'large'
16
+ # vit_grad_ckpt: True
17
+ # vit_ckpt_layer: 5
18
+ # batch_size: 16
19
+ # init_lr: 2e-6
20
+
21
+ image_size: 384
22
+
23
+ # generation configs
24
+ max_length: 20
25
+ min_length: 5
26
+ num_beams: 3
27
+ prompt: 'a picture of '
28
+
29
+ # optimizer
30
+ weight_decay: 0.05
31
+ min_lr: 0
32
+ max_epoch: 5
33
+
extras/BLIP/configs/med_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertModel"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "hidden_act": "gelu",
7
+ "hidden_dropout_prob": 0.1,
8
+ "hidden_size": 768,
9
+ "initializer_range": 0.02,
10
+ "intermediate_size": 3072,
11
+ "layer_norm_eps": 1e-12,
12
+ "max_position_embeddings": 512,
13
+ "model_type": "bert",
14
+ "num_attention_heads": 12,
15
+ "num_hidden_layers": 12,
16
+ "pad_token_id": 0,
17
+ "type_vocab_size": 2,
18
+ "vocab_size": 30524,
19
+ "encoder_width": 768,
20
+ "add_cross_attention": true
21
+ }
extras/BLIP/configs/nlvr.yaml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ image_root: '/export/share/datasets/vision/NLVR2/'
2
+ ann_root: 'annotation'
3
+
4
+ # set pretrained as a file path or an url
5
+ pretrained: 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_nlvr.pth'
6
+
7
+ #size of vit model; base or large
8
+ vit: 'base'
9
+ batch_size_train: 16
10
+ batch_size_test: 64
11
+ vit_grad_ckpt: False
12
+ vit_ckpt_layer: 0
13
+ max_epoch: 15
14
+
15
+ image_size: 384
16
+
17
+ # optimizer
18
+ weight_decay: 0.05
19
+ init_lr: 3e-5
20
+ min_lr: 0
21
+
extras/BLIP/configs/nocaps.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ image_root: '/export/share/datasets/vision/nocaps/'
2
+ ann_root: 'annotation'
3
+
4
+ # set pretrained as a file path or an url
5
+ pretrained: 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_caption_capfilt_large.pth'
6
+
7
+ vit: 'base'
8
+ batch_size: 32
9
+
10
+ image_size: 384
11
+
12
+ max_length: 20
13
+ min_length: 5
14
+ num_beams: 3
15
+ prompt: 'a picture of '
extras/BLIP/configs/pretrain.yaml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ train_file: ['/export/share/junnan-li/VL_pretrain/annotation/coco_karpathy_train.json',
2
+ '/export/share/junnan-li/VL_pretrain/annotation/vg_caption.json',
3
+ ]
4
+ laion_path: ''
5
+
6
+ # size of vit model; base or large
7
+ vit: 'base'
8
+ vit_grad_ckpt: False
9
+ vit_ckpt_layer: 0
10
+
11
+ image_size: 224
12
+ batch_size: 75
13
+
14
+ queue_size: 57600
15
+ alpha: 0.4
16
+
17
+ # optimizer
18
+ weight_decay: 0.05
19
+ init_lr: 3e-4
20
+ min_lr: 1e-6
21
+ warmup_lr: 1e-6
22
+ lr_decay_rate: 0.9
23
+ max_epoch: 20
24
+ warmup_steps: 3000
25
+
26
+
27
+
extras/BLIP/configs/retrieval_coco.yaml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ image_root: '/export/share/datasets/vision/coco/images/'
2
+ ann_root: 'annotation'
3
+ dataset: 'coco'
4
+
5
+ # set pretrained as a file path or an url
6
+ pretrained: 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth'
7
+
8
+ # size of vit model; base or large
9
+
10
+ vit: 'base'
11
+ batch_size_train: 32
12
+ batch_size_test: 64
13
+ vit_grad_ckpt: True
14
+ vit_ckpt_layer: 4
15
+ init_lr: 1e-5
16
+
17
+ # vit: 'large'
18
+ # batch_size_train: 16
19
+ # batch_size_test: 32
20
+ # vit_grad_ckpt: True
21
+ # vit_ckpt_layer: 12
22
+ # init_lr: 5e-6
23
+
24
+ image_size: 384
25
+ queue_size: 57600
26
+ alpha: 0.4
27
+ k_test: 256
28
+ negative_all_rank: True
29
+
30
+ # optimizer
31
+ weight_decay: 0.05
32
+ min_lr: 0
33
+ max_epoch: 6
34
+
extras/BLIP/configs/retrieval_flickr.yaml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ image_root: '/export/share/datasets/vision/flickr30k/'
2
+ ann_root: 'annotation'
3
+ dataset: 'flickr'
4
+
5
+ # set pretrained as a file path or an url
6
+ pretrained: 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_flickr.pth'
7
+
8
+ # size of vit model; base or large
9
+
10
+ vit: 'base'
11
+ batch_size_train: 32
12
+ batch_size_test: 64
13
+ vit_grad_ckpt: True
14
+ vit_ckpt_layer: 4
15
+ init_lr: 1e-5
16
+
17
+ # vit: 'large'
18
+ # batch_size_train: 16
19
+ # batch_size_test: 32
20
+ # vit_grad_ckpt: True
21
+ # vit_ckpt_layer: 10
22
+ # init_lr: 5e-6
23
+
24
+ image_size: 384
25
+ queue_size: 57600
26
+ alpha: 0.4
27
+ k_test: 128
28
+ negative_all_rank: False
29
+
30
+ # optimizer
31
+ weight_decay: 0.05
32
+ min_lr: 0
33
+ max_epoch: 6
34
+
extras/BLIP/configs/retrieval_msrvtt.yaml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ video_root: '/export/share/dongxuli/data/msrvtt_retrieval/videos'
2
+ ann_root: 'annotation'
3
+
4
+ # set pretrained as a file path or an url
5
+ pretrained: 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth'
6
+
7
+ # size of vit model; base or large
8
+ vit: 'base'
9
+ batch_size: 64
10
+ k_test: 128
11
+ image_size: 384
12
+ num_frm_test: 8
extras/BLIP/configs/vqa.yaml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ vqa_root: '/export/share/datasets/vision/VQA/Images/mscoco/' #followed by train2014/
2
+ vg_root: '/export/share/datasets/vision/visual-genome/' #followed by image/
3
+ train_files: ['vqa_train','vqa_val','vg_qa']
4
+ ann_root: 'annotation'
5
+
6
+ # set pretrained as a file path or an url
7
+ pretrained: 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth'
8
+
9
+ # size of vit model; base or large
10
+ vit: 'base'
11
+ batch_size_train: 16
12
+ batch_size_test: 32
13
+ vit_grad_ckpt: False
14
+ vit_ckpt_layer: 0
15
+ init_lr: 2e-5
16
+
17
+ image_size: 480
18
+
19
+ k_test: 128
20
+ inference: 'rank'
21
+
22
+ # optimizer
23
+ weight_decay: 0.05
24
+ min_lr: 0
25
+ max_epoch: 10
extras/BLIP/models/__pycache__/blip.cpython-310.pyc ADDED
Binary file (7.1 kB). View file
 
extras/BLIP/models/__pycache__/med.cpython-310.pyc ADDED
Binary file (28 kB). View file
 
extras/BLIP/models/__pycache__/vit.cpython-310.pyc ADDED
Binary file (12.5 kB). View file
 
extras/BLIP/models/bert_tokenizer/config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertForMaskedLM"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "gradient_checkpointing": false,
7
+ "hidden_act": "gelu",
8
+ "hidden_dropout_prob": 0.1,
9
+ "hidden_size": 768,
10
+ "initializer_range": 0.02,
11
+ "intermediate_size": 3072,
12
+ "layer_norm_eps": 1e-12,
13
+ "max_position_embeddings": 512,
14
+ "model_type": "bert",
15
+ "num_attention_heads": 12,
16
+ "num_hidden_layers": 12,
17
+ "pad_token_id": 0,
18
+ "position_embedding_type": "absolute",
19
+ "transformers_version": "4.6.0.dev0",
20
+ "type_vocab_size": 2,
21
+ "use_cache": true,
22
+ "vocab_size": 30522
23
+ }
extras/BLIP/models/bert_tokenizer/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
extras/BLIP/models/bert_tokenizer/tokenizer_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "do_lower_case": true
3
+ }
extras/BLIP/models/bert_tokenizer/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
extras/BLIP/models/blip.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ * Copyright (c) 2022, salesforce.com, inc.
3
+ * All rights reserved.
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
6
+ * By Junnan Li
7
+ '''
8
+ import warnings
9
+ warnings.filterwarnings("ignore")
10
+
11
+ from extras.BLIP.models.vit import VisionTransformer, interpolate_pos_embed
12
+ from extras.BLIP.models.med import BertConfig, BertModel, BertLMHeadModel
13
+ from transformers import BertTokenizer
14
+
15
+ import torch
16
+ from torch import nn
17
+ import torch.nn.functional as F
18
+
19
+ import os
20
+ from urllib.parse import urlparse
21
+ from timm.models.hub import download_cached_file
22
+
23
+ class BLIP_Base(nn.Module):
24
+ def __init__(self,
25
+ med_config = 'configs/med_config.json',
26
+ image_size = 224,
27
+ vit = 'base',
28
+ vit_grad_ckpt = False,
29
+ vit_ckpt_layer = 0,
30
+ ):
31
+ """
32
+ Args:
33
+ med_config (str): path for the mixture of encoder-decoder model's configuration file
34
+ image_size (int): input image size
35
+ vit (str): model size of vision transformer
36
+ """
37
+ super().__init__()
38
+
39
+ self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer)
40
+ self.tokenizer = init_tokenizer()
41
+ med_config = BertConfig.from_json_file(med_config)
42
+ med_config.encoder_width = vision_width
43
+ self.text_encoder = BertModel(config=med_config, add_pooling_layer=False)
44
+
45
+
46
+ def forward(self, image, caption, mode):
47
+
48
+ assert mode in ['image', 'text', 'multimodal'], "mode parameter must be image, text, or multimodal"
49
+ text = self.tokenizer(caption, return_tensors="pt").to(image.device)
50
+
51
+ if mode=='image':
52
+ # return image features
53
+ image_embeds = self.visual_encoder(image)
54
+ return image_embeds
55
+
56
+ elif mode=='text':
57
+ # return text features
58
+ text_output = self.text_encoder(text.input_ids, attention_mask = text.attention_mask,
59
+ return_dict = True, mode = 'text')
60
+ return text_output.last_hidden_state
61
+
62
+ elif mode=='multimodal':
63
+ # return multimodel features
64
+ image_embeds = self.visual_encoder(image)
65
+ image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
66
+
67
+ text.input_ids[:,0] = self.tokenizer.enc_token_id
68
+ output = self.text_encoder(text.input_ids,
69
+ attention_mask = text.attention_mask,
70
+ encoder_hidden_states = image_embeds,
71
+ encoder_attention_mask = image_atts,
72
+ return_dict = True,
73
+ )
74
+ return output.last_hidden_state
75
+
76
+
77
+
78
+ class BLIP_Decoder(nn.Module):
79
+ def __init__(self,
80
+ med_config = 'configs/med_config.json',
81
+ image_size = 384,
82
+ vit = 'base',
83
+ vit_grad_ckpt = False,
84
+ vit_ckpt_layer = 0,
85
+ prompt = 'a picture of ',
86
+ ):
87
+ """
88
+ Args:
89
+ med_config (str): path for the mixture of encoder-decoder model's configuration file
90
+ image_size (int): input image size
91
+ vit (str): model size of vision transformer
92
+ """
93
+ super().__init__()
94
+
95
+ self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer)
96
+ self.tokenizer = init_tokenizer()
97
+ med_config = BertConfig.from_json_file(med_config)
98
+ med_config.encoder_width = vision_width
99
+ self.text_decoder = BertLMHeadModel(config=med_config)
100
+
101
+ self.prompt = prompt
102
+ self.prompt_length = len(self.tokenizer(self.prompt).input_ids)-1
103
+
104
+
105
+ def forward(self, image, caption):
106
+
107
+ image_embeds = self.visual_encoder(image)
108
+ image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
109
+
110
+ text = self.tokenizer(caption, padding='longest', truncation=True, max_length=40, return_tensors="pt").to(image.device)
111
+
112
+ text.input_ids[:,0] = self.tokenizer.bos_token_id
113
+
114
+ decoder_targets = text.input_ids.masked_fill(text.input_ids == self.tokenizer.pad_token_id, -100)
115
+ decoder_targets[:,:self.prompt_length] = -100
116
+
117
+ decoder_output = self.text_decoder(text.input_ids,
118
+ attention_mask = text.attention_mask,
119
+ encoder_hidden_states = image_embeds,
120
+ encoder_attention_mask = image_atts,
121
+ labels = decoder_targets,
122
+ return_dict = True,
123
+ )
124
+ loss_lm = decoder_output.loss
125
+
126
+ return loss_lm
127
+
128
+ def generate(self, image, sample=False, num_beams=3, max_length=30, min_length=10, top_p=0.9, repetition_penalty=1.0):
129
+ image_embeds = self.visual_encoder(image)
130
+
131
+ if not sample:
132
+ image_embeds = image_embeds.repeat_interleave(num_beams,dim=0)
133
+
134
+ image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
135
+ model_kwargs = {"encoder_hidden_states": image_embeds, "encoder_attention_mask":image_atts}
136
+
137
+ prompt = [self.prompt] * image.size(0)
138
+ input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids.to(image.device)
139
+ input_ids[:,0] = self.tokenizer.bos_token_id
140
+ input_ids = input_ids[:, :-1]
141
+
142
+ if sample:
143
+ #nucleus sampling
144
+ outputs = self.text_decoder.generate(input_ids=input_ids,
145
+ max_length=max_length,
146
+ min_length=min_length,
147
+ do_sample=True,
148
+ top_p=top_p,
149
+ num_return_sequences=1,
150
+ eos_token_id=self.tokenizer.sep_token_id,
151
+ pad_token_id=self.tokenizer.pad_token_id,
152
+ repetition_penalty=1.1,
153
+ **model_kwargs)
154
+ else:
155
+ #beam search
156
+ outputs = self.text_decoder.generate(input_ids=input_ids,
157
+ max_length=max_length,
158
+ min_length=min_length,
159
+ num_beams=num_beams,
160
+ eos_token_id=self.tokenizer.sep_token_id,
161
+ pad_token_id=self.tokenizer.pad_token_id,
162
+ repetition_penalty=repetition_penalty,
163
+ **model_kwargs)
164
+
165
+ captions = []
166
+ for output in outputs:
167
+ caption = self.tokenizer.decode(output, skip_special_tokens=True)
168
+ captions.append(caption[len(self.prompt):])
169
+ return captions
170
+
171
+
172
+ def blip_decoder(pretrained='',**kwargs):
173
+ model = BLIP_Decoder(**kwargs)
174
+ if pretrained:
175
+ model,msg = load_checkpoint(model,pretrained)
176
+ assert(len(msg.missing_keys)==0)
177
+ return model
178
+
179
+ def blip_feature_extractor(pretrained='',**kwargs):
180
+ model = BLIP_Base(**kwargs)
181
+ if pretrained:
182
+ model,msg = load_checkpoint(model,pretrained)
183
+ assert(len(msg.missing_keys)==0)
184
+ return model
185
+
186
+ def init_tokenizer():
187
+ tokenizer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "bert_tokenizer")
188
+ tokenizer = BertTokenizer.from_pretrained(tokenizer_path)
189
+ tokenizer.add_special_tokens({'bos_token':'[DEC]'})
190
+ tokenizer.add_special_tokens({'additional_special_tokens':['[ENC]']})
191
+ tokenizer.enc_token_id = tokenizer.additional_special_tokens_ids[0]
192
+ return tokenizer
193
+
194
+
195
+ def create_vit(vit, image_size, use_grad_checkpointing=False, ckpt_layer=0, drop_path_rate=0):
196
+
197
+ assert vit in ['base', 'large'], "vit parameter must be base or large"
198
+ if vit=='base':
199
+ vision_width = 768
200
+ visual_encoder = VisionTransformer(img_size=image_size, patch_size=16, embed_dim=vision_width, depth=12,
201
+ num_heads=12, use_grad_checkpointing=use_grad_checkpointing, ckpt_layer=ckpt_layer,
202
+ drop_path_rate=0 or drop_path_rate
203
+ )
204
+ elif vit=='large':
205
+ vision_width = 1024
206
+ visual_encoder = VisionTransformer(img_size=image_size, patch_size=16, embed_dim=vision_width, depth=24,
207
+ num_heads=16, use_grad_checkpointing=use_grad_checkpointing, ckpt_layer=ckpt_layer,
208
+ drop_path_rate=0.1 or drop_path_rate
209
+ )
210
+ return visual_encoder, vision_width
211
+
212
+ def is_url(url_or_filename):
213
+ parsed = urlparse(url_or_filename)
214
+ return parsed.scheme in ("http", "https")
215
+
216
+ def load_checkpoint(model,url_or_filename):
217
+ if is_url(url_or_filename):
218
+ cached_file = download_cached_file(url_or_filename, check_hash=False, progress=True)
219
+ checkpoint = torch.load(cached_file, map_location='cpu')
220
+ elif os.path.isfile(url_or_filename):
221
+ checkpoint = torch.load(url_or_filename, map_location='cpu')
222
+ else:
223
+ raise RuntimeError('checkpoint url or path is invalid')
224
+
225
+ state_dict = checkpoint['model']
226
+
227
+ state_dict['visual_encoder.pos_embed'] = interpolate_pos_embed(state_dict['visual_encoder.pos_embed'],model.visual_encoder)
228
+ if 'visual_encoder_m.pos_embed' in model.state_dict().keys():
229
+ state_dict['visual_encoder_m.pos_embed'] = interpolate_pos_embed(state_dict['visual_encoder_m.pos_embed'],
230
+ model.visual_encoder_m)
231
+ for key in model.state_dict().keys():
232
+ if key in state_dict.keys():
233
+ if state_dict[key].shape!=model.state_dict()[key].shape:
234
+ del state_dict[key]
235
+
236
+ msg = model.load_state_dict(state_dict,strict=False)
237
+ print('load checkpoint from %s'%url_or_filename)
238
+ return model,msg
239
+
extras/BLIP/models/blip_itm.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from extras.BLIP.models.med import BertConfig, BertModel
2
+ from transformers import BertTokenizer
3
+
4
+ import torch
5
+ from torch import nn
6
+ import torch.nn.functional as F
7
+
8
+ from extras.BLIP.models.blip import create_vit, init_tokenizer, load_checkpoint
9
+
10
+ class BLIP_ITM(nn.Module):
11
+ def __init__(self,
12
+ med_config = 'configs/med_config.json',
13
+ image_size = 384,
14
+ vit = 'base',
15
+ vit_grad_ckpt = False,
16
+ vit_ckpt_layer = 0,
17
+ embed_dim = 256,
18
+ ):
19
+ """
20
+ Args:
21
+ med_config (str): path for the mixture of encoder-decoder model's configuration file
22
+ image_size (int): input image size
23
+ vit (str): model size of vision transformer
24
+ """
25
+ super().__init__()
26
+
27
+ self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer)
28
+ self.tokenizer = init_tokenizer()
29
+ med_config = BertConfig.from_json_file(med_config)
30
+ med_config.encoder_width = vision_width
31
+ self.text_encoder = BertModel(config=med_config, add_pooling_layer=False)
32
+
33
+ text_width = self.text_encoder.config.hidden_size
34
+
35
+ self.vision_proj = nn.Linear(vision_width, embed_dim)
36
+ self.text_proj = nn.Linear(text_width, embed_dim)
37
+
38
+ self.itm_head = nn.Linear(text_width, 2)
39
+
40
+
41
+ def forward(self, image, caption, match_head='itm'):
42
+
43
+ image_embeds = self.visual_encoder(image)
44
+ image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
45
+
46
+ text = self.tokenizer(caption, padding='max_length', truncation=True, max_length=35,
47
+ return_tensors="pt").to(image.device)
48
+
49
+
50
+ if match_head=='itm':
51
+ output = self.text_encoder(text.input_ids,
52
+ attention_mask = text.attention_mask,
53
+ encoder_hidden_states = image_embeds,
54
+ encoder_attention_mask = image_atts,
55
+ return_dict = True,
56
+ )
57
+ itm_output = self.itm_head(output.last_hidden_state[:,0,:])
58
+ return itm_output
59
+
60
+ elif match_head=='itc':
61
+ text_output = self.text_encoder(text.input_ids, attention_mask = text.attention_mask,
62
+ return_dict = True, mode = 'text')
63
+ image_feat = F.normalize(self.vision_proj(image_embeds[:,0,:]),dim=-1)
64
+ text_feat = F.normalize(self.text_proj(text_output.last_hidden_state[:,0,:]),dim=-1)
65
+
66
+ sim = image_feat @ text_feat.t()
67
+ return sim
68
+
69
+
70
+ def blip_itm(pretrained='',**kwargs):
71
+ model = BLIP_ITM(**kwargs)
72
+ if pretrained:
73
+ model,msg = load_checkpoint(model,pretrained)
74
+ assert(len(msg.missing_keys)==0)
75
+ return model
76
+
extras/BLIP/models/blip_nlvr.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from extras.BLIP.models.med import BertConfig
2
+ from extras.BLIP.models.nlvr_encoder import BertModel
3
+ from extras.BLIP.models.vit import interpolate_pos_embed
4
+ from extras.BLIP.models.blip import create_vit, init_tokenizer, is_url
5
+
6
+ from timm.models.hub import download_cached_file
7
+
8
+ import torch
9
+ from torch import nn
10
+ import torch.nn.functional as F
11
+ from transformers import BertTokenizer
12
+ import numpy as np
13
+ import os
14
+
15
+
16
+ class BLIP_NLVR(nn.Module):
17
+ def __init__(self,
18
+ med_config = 'configs/med_config.json',
19
+ image_size = 480,
20
+ vit = 'base',
21
+ vit_grad_ckpt = False,
22
+ vit_ckpt_layer = 0,
23
+ ):
24
+ """
25
+ Args:
26
+ med_config (str): path for the mixture of encoder-decoder model's configuration file
27
+ image_size (int): input image size
28
+ vit (str): model size of vision transformer
29
+ """
30
+ super().__init__()
31
+
32
+ self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer, drop_path_rate=0.1)
33
+ self.tokenizer = init_tokenizer()
34
+ med_config = BertConfig.from_json_file(med_config)
35
+ med_config.encoder_width = vision_width
36
+ self.text_encoder = BertModel(config=med_config, add_pooling_layer=False)
37
+
38
+ self.cls_head = nn.Sequential(
39
+ nn.Linear(self.text_encoder.config.hidden_size, self.text_encoder.config.hidden_size),
40
+ nn.ReLU(),
41
+ nn.Linear(self.text_encoder.config.hidden_size, 2)
42
+ )
43
+
44
+ def forward(self, image, text, targets, train=True):
45
+
46
+ image_embeds = self.visual_encoder(image)
47
+ image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
48
+ image0_embeds, image1_embeds = torch.split(image_embeds,targets.size(0))
49
+
50
+ text = self.tokenizer(text, padding='longest', return_tensors="pt").to(image.device)
51
+ text.input_ids[:,0] = self.tokenizer.enc_token_id
52
+
53
+ output = self.text_encoder(text.input_ids,
54
+ attention_mask = text.attention_mask,
55
+ encoder_hidden_states = [image0_embeds,image1_embeds],
56
+ encoder_attention_mask = [image_atts[:image0_embeds.size(0)],
57
+ image_atts[image0_embeds.size(0):]],
58
+ return_dict = True,
59
+ )
60
+ hidden_state = output.last_hidden_state[:,0,:]
61
+ prediction = self.cls_head(hidden_state)
62
+
63
+ if train:
64
+ loss = F.cross_entropy(prediction, targets)
65
+ return loss
66
+ else:
67
+ return prediction
68
+
69
+ def blip_nlvr(pretrained='',**kwargs):
70
+ model = BLIP_NLVR(**kwargs)
71
+ if pretrained:
72
+ model,msg = load_checkpoint(model,pretrained)
73
+ print("missing keys:")
74
+ print(msg.missing_keys)
75
+ return model
76
+
77
+
78
+ def load_checkpoint(model,url_or_filename):
79
+ if is_url(url_or_filename):
80
+ cached_file = download_cached_file(url_or_filename, check_hash=False, progress=True)
81
+ checkpoint = torch.load(cached_file, map_location='cpu')
82
+ elif os.path.isfile(url_or_filename):
83
+ checkpoint = torch.load(url_or_filename, map_location='cpu')
84
+ else:
85
+ raise RuntimeError('checkpoint url or path is invalid')
86
+ state_dict = checkpoint['model']
87
+
88
+ state_dict['visual_encoder.pos_embed'] = interpolate_pos_embed(state_dict['visual_encoder.pos_embed'],model.visual_encoder)
89
+
90
+ for key in list(state_dict.keys()):
91
+ if 'crossattention.self.' in key:
92
+ new_key0 = key.replace('self','self0')
93
+ new_key1 = key.replace('self','self1')
94
+ state_dict[new_key0] = state_dict[key]
95
+ state_dict[new_key1] = state_dict[key]
96
+ elif 'crossattention.output.dense.' in key:
97
+ new_key0 = key.replace('dense','dense0')
98
+ new_key1 = key.replace('dense','dense1')
99
+ state_dict[new_key0] = state_dict[key]
100
+ state_dict[new_key1] = state_dict[key]
101
+
102
+ msg = model.load_state_dict(state_dict,strict=False)
103
+ print('load checkpoint from %s'%url_or_filename)
104
+ return model,msg
105
+
extras/BLIP/models/blip_pretrain.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ * Copyright (c) 2022, salesforce.com, inc.
3
+ * All rights reserved.
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
6
+ * By Junnan Li
7
+ '''
8
+ from extras.BLIP.models.med import BertConfig, BertModel, BertLMHeadModel
9
+ from transformers import BertTokenizer
10
+ import transformers
11
+ transformers.logging.set_verbosity_error()
12
+
13
+ import torch
14
+ from torch import nn
15
+ import torch.nn.functional as F
16
+
17
+ from extras.BLIP.models.blip import create_vit, init_tokenizer, load_checkpoint
18
+
19
+ class BLIP_Pretrain(nn.Module):
20
+ def __init__(self,
21
+ med_config = 'configs/bert_config.json',
22
+ image_size = 224,
23
+ vit = 'base',
24
+ vit_grad_ckpt = False,
25
+ vit_ckpt_layer = 0,
26
+ embed_dim = 256,
27
+ queue_size = 57600,
28
+ momentum = 0.995,
29
+ ):
30
+ """
31
+ Args:
32
+ med_config (str): path for the mixture of encoder-decoder model's configuration file
33
+ image_size (int): input image size
34
+ vit (str): model size of vision transformer
35
+ """
36
+ super().__init__()
37
+
38
+ self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer, 0)
39
+
40
+ if vit=='base':
41
+ checkpoint = torch.hub.load_state_dict_from_url(
42
+ url="https://dl.fbaipublicfiles.com/deit/deit_base_patch16_224-b5f2ef4d.pth",
43
+ map_location="cpu", check_hash=True)
44
+ state_dict = checkpoint["model"]
45
+ msg = self.visual_encoder.load_state_dict(state_dict,strict=False)
46
+ elif vit=='large':
47
+ from timm.models.helpers import load_custom_pretrained
48
+ from timm.models.vision_transformer import default_cfgs
49
+ load_custom_pretrained(self.visual_encoder,default_cfgs['vit_large_patch16_224_in21k'])
50
+
51
+ self.tokenizer = init_tokenizer()
52
+ encoder_config = BertConfig.from_json_file(med_config)
53
+ encoder_config.encoder_width = vision_width
54
+ self.text_encoder = BertModel.from_pretrained('bert-base-uncased',config=encoder_config, add_pooling_layer=False)
55
+ self.text_encoder.resize_token_embeddings(len(self.tokenizer))
56
+
57
+ text_width = self.text_encoder.config.hidden_size
58
+
59
+ self.vision_proj = nn.Linear(vision_width, embed_dim)
60
+ self.text_proj = nn.Linear(text_width, embed_dim)
61
+
62
+ self.itm_head = nn.Linear(text_width, 2)
63
+
64
+ # create momentum encoders
65
+ self.visual_encoder_m, vision_width = create_vit(vit,image_size)
66
+ self.vision_proj_m = nn.Linear(vision_width, embed_dim)
67
+ self.text_encoder_m = BertModel(config=encoder_config, add_pooling_layer=False)
68
+ self.text_proj_m = nn.Linear(text_width, embed_dim)
69
+
70
+ self.model_pairs = [[self.visual_encoder,self.visual_encoder_m],
71
+ [self.vision_proj,self.vision_proj_m],
72
+ [self.text_encoder,self.text_encoder_m],
73
+ [self.text_proj,self.text_proj_m],
74
+ ]
75
+ self.copy_params()
76
+
77
+ # create the queue
78
+ self.register_buffer("image_queue", torch.randn(embed_dim, queue_size))
79
+ self.register_buffer("text_queue", torch.randn(embed_dim, queue_size))
80
+ self.register_buffer("queue_ptr", torch.zeros(1, dtype=torch.long))
81
+
82
+ self.image_queue = nn.functional.normalize(self.image_queue, dim=0)
83
+ self.text_queue = nn.functional.normalize(self.text_queue, dim=0)
84
+
85
+ self.queue_size = queue_size
86
+ self.momentum = momentum
87
+ self.temp = nn.Parameter(0.07*torch.ones([]))
88
+
89
+ # create the decoder
90
+ decoder_config = BertConfig.from_json_file(med_config)
91
+ decoder_config.encoder_width = vision_width
92
+ self.text_decoder = BertLMHeadModel.from_pretrained('bert-base-uncased',config=decoder_config)
93
+ self.text_decoder.resize_token_embeddings(len(self.tokenizer))
94
+ tie_encoder_decoder_weights(self.text_encoder,self.text_decoder.bert,'','/attention')
95
+
96
+
97
+ def forward(self, image, caption, alpha):
98
+ with torch.no_grad():
99
+ self.temp.clamp_(0.001,0.5)
100
+
101
+ image_embeds = self.visual_encoder(image)
102
+ image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
103
+ image_feat = F.normalize(self.vision_proj(image_embeds[:,0,:]),dim=-1)
104
+
105
+ text = self.tokenizer(caption, padding='max_length', truncation=True, max_length=30,
106
+ return_tensors="pt").to(image.device)
107
+ text_output = self.text_encoder(text.input_ids, attention_mask = text.attention_mask,
108
+ return_dict = True, mode = 'text')
109
+ text_feat = F.normalize(self.text_proj(text_output.last_hidden_state[:,0,:]),dim=-1)
110
+
111
+ # get momentum features
112
+ with torch.no_grad():
113
+ self._momentum_update()
114
+ image_embeds_m = self.visual_encoder_m(image)
115
+ image_feat_m = F.normalize(self.vision_proj_m(image_embeds_m[:,0,:]),dim=-1)
116
+ image_feat_all = torch.cat([image_feat_m.t(),self.image_queue.clone().detach()],dim=1)
117
+
118
+ text_output_m = self.text_encoder_m(text.input_ids, attention_mask = text.attention_mask,
119
+ return_dict = True, mode = 'text')
120
+ text_feat_m = F.normalize(self.text_proj_m(text_output_m.last_hidden_state[:,0,:]),dim=-1)
121
+ text_feat_all = torch.cat([text_feat_m.t(),self.text_queue.clone().detach()],dim=1)
122
+
123
+ sim_i2t_m = image_feat_m @ text_feat_all / self.temp
124
+ sim_t2i_m = text_feat_m @ image_feat_all / self.temp
125
+
126
+ sim_targets = torch.zeros(sim_i2t_m.size()).to(image.device)
127
+ sim_targets.fill_diagonal_(1)
128
+
129
+ sim_i2t_targets = alpha * F.softmax(sim_i2t_m, dim=1) + (1 - alpha) * sim_targets
130
+ sim_t2i_targets = alpha * F.softmax(sim_t2i_m, dim=1) + (1 - alpha) * sim_targets
131
+
132
+ sim_i2t = image_feat @ text_feat_all / self.temp
133
+ sim_t2i = text_feat @ image_feat_all / self.temp
134
+
135
+ loss_i2t = -torch.sum(F.log_softmax(sim_i2t, dim=1)*sim_i2t_targets,dim=1).mean()
136
+ loss_t2i = -torch.sum(F.log_softmax(sim_t2i, dim=1)*sim_t2i_targets,dim=1).mean()
137
+
138
+ loss_ita = (loss_i2t+loss_t2i)/2
139
+
140
+ self._dequeue_and_enqueue(image_feat_m, text_feat_m)
141
+
142
+ ###============== Image-text Matching ===================###
143
+ encoder_input_ids = text.input_ids.clone()
144
+ encoder_input_ids[:,0] = self.tokenizer.enc_token_id
145
+
146
+ # forward the positve image-text pair
147
+ bs = image.size(0)
148
+ output_pos = self.text_encoder(encoder_input_ids,
149
+ attention_mask = text.attention_mask,
150
+ encoder_hidden_states = image_embeds,
151
+ encoder_attention_mask = image_atts,
152
+ return_dict = True,
153
+ )
154
+ with torch.no_grad():
155
+ weights_t2i = F.softmax(sim_t2i[:,:bs],dim=1)+1e-4
156
+ weights_t2i.fill_diagonal_(0)
157
+ weights_i2t = F.softmax(sim_i2t[:,:bs],dim=1)+1e-4
158
+ weights_i2t.fill_diagonal_(0)
159
+
160
+ # select a negative image for each text
161
+ image_embeds_neg = []
162
+ for b in range(bs):
163
+ neg_idx = torch.multinomial(weights_t2i[b], 1).item()
164
+ image_embeds_neg.append(image_embeds[neg_idx])
165
+ image_embeds_neg = torch.stack(image_embeds_neg,dim=0)
166
+
167
+ # select a negative text for each image
168
+ text_ids_neg = []
169
+ text_atts_neg = []
170
+ for b in range(bs):
171
+ neg_idx = torch.multinomial(weights_i2t[b], 1).item()
172
+ text_ids_neg.append(encoder_input_ids[neg_idx])
173
+ text_atts_neg.append(text.attention_mask[neg_idx])
174
+
175
+ text_ids_neg = torch.stack(text_ids_neg,dim=0)
176
+ text_atts_neg = torch.stack(text_atts_neg,dim=0)
177
+
178
+ text_ids_all = torch.cat([encoder_input_ids, text_ids_neg],dim=0)
179
+ text_atts_all = torch.cat([text.attention_mask, text_atts_neg],dim=0)
180
+
181
+ image_embeds_all = torch.cat([image_embeds_neg,image_embeds],dim=0)
182
+ image_atts_all = torch.cat([image_atts,image_atts],dim=0)
183
+
184
+ output_neg = self.text_encoder(text_ids_all,
185
+ attention_mask = text_atts_all,
186
+ encoder_hidden_states = image_embeds_all,
187
+ encoder_attention_mask = image_atts_all,
188
+ return_dict = True,
189
+ )
190
+
191
+ vl_embeddings = torch.cat([output_pos.last_hidden_state[:,0,:], output_neg.last_hidden_state[:,0,:]],dim=0)
192
+ vl_output = self.itm_head(vl_embeddings)
193
+
194
+ itm_labels = torch.cat([torch.ones(bs,dtype=torch.long),torch.zeros(2*bs,dtype=torch.long)],
195
+ dim=0).to(image.device)
196
+ loss_itm = F.cross_entropy(vl_output, itm_labels)
197
+
198
+ ##================= LM ========================##
199
+ decoder_input_ids = text.input_ids.clone()
200
+ decoder_input_ids[:,0] = self.tokenizer.bos_token_id
201
+ decoder_targets = decoder_input_ids.masked_fill(decoder_input_ids == self.tokenizer.pad_token_id, -100)
202
+
203
+ decoder_output = self.text_decoder(decoder_input_ids,
204
+ attention_mask = text.attention_mask,
205
+ encoder_hidden_states = image_embeds,
206
+ encoder_attention_mask = image_atts,
207
+ labels = decoder_targets,
208
+ return_dict = True,
209
+ )
210
+
211
+ loss_lm = decoder_output.loss
212
+ return loss_ita, loss_itm, loss_lm
213
+
214
+
215
+
216
+ @torch.no_grad()
217
+ def copy_params(self):
218
+ for model_pair in self.model_pairs:
219
+ for param, param_m in zip(model_pair[0].parameters(), model_pair[1].parameters()):
220
+ param_m.data.copy_(param.data) # initialize
221
+ param_m.requires_grad = False # not update by gradient
222
+
223
+
224
+ @torch.no_grad()
225
+ def _momentum_update(self):
226
+ for model_pair in self.model_pairs:
227
+ for param, param_m in zip(model_pair[0].parameters(), model_pair[1].parameters()):
228
+ param_m.data = param_m.data * self.momentum + param.data * (1. - self.momentum)
229
+
230
+
231
+ @torch.no_grad()
232
+ def _dequeue_and_enqueue(self, image_feat, text_feat):
233
+ # gather keys before updating queue
234
+ image_feats = concat_all_gather(image_feat)
235
+ text_feats = concat_all_gather(text_feat)
236
+
237
+ batch_size = image_feats.shape[0]
238
+
239
+ ptr = int(self.queue_ptr)
240
+ assert self.queue_size % batch_size == 0 # for simplicity
241
+
242
+ # replace the keys at ptr (dequeue and enqueue)
243
+ self.image_queue[:, ptr:ptr + batch_size] = image_feats.T
244
+ self.text_queue[:, ptr:ptr + batch_size] = text_feats.T
245
+ ptr = (ptr + batch_size) % self.queue_size # move pointer
246
+
247
+ self.queue_ptr[0] = ptr
248
+
249
+
250
+ def blip_pretrain(**kwargs):
251
+ model = BLIP_Pretrain(**kwargs)
252
+ return model
253
+
254
+
255
+ @torch.no_grad()
256
+ def concat_all_gather(tensor):
257
+ """
258
+ Performs all_gather operation on the provided tensors.
259
+ *** Warning ***: torch.distributed.all_gather has no gradient.
260
+ """
261
+ tensors_gather = [torch.ones_like(tensor)
262
+ for _ in range(torch.distributed.get_world_size())]
263
+ torch.distributed.all_gather(tensors_gather, tensor, async_op=False)
264
+
265
+ output = torch.cat(tensors_gather, dim=0)
266
+ return output
267
+
268
+
269
+ from typing import List
270
+ def tie_encoder_decoder_weights(encoder: nn.Module, decoder: nn.Module, base_model_prefix: str, skip_key:str):
271
+ uninitialized_encoder_weights: List[str] = []
272
+ if decoder.__class__ != encoder.__class__:
273
+ print(
274
+ f"{decoder.__class__} and {encoder.__class__} are not equal. In this case make sure that all encoder weights are correctly initialized."
275
+ )
276
+
277
+ def tie_encoder_to_decoder_recursively(
278
+ decoder_pointer: nn.Module,
279
+ encoder_pointer: nn.Module,
280
+ module_name: str,
281
+ uninitialized_encoder_weights: List[str],
282
+ skip_key: str,
283
+ depth=0,
284
+ ):
285
+ assert isinstance(decoder_pointer, nn.Module) and isinstance(
286
+ encoder_pointer, nn.Module
287
+ ), f"{decoder_pointer} and {encoder_pointer} have to be of type torch.nn.Module"
288
+ if hasattr(decoder_pointer, "weight") and skip_key not in module_name:
289
+ assert hasattr(encoder_pointer, "weight")
290
+ encoder_pointer.weight = decoder_pointer.weight
291
+ if hasattr(decoder_pointer, "bias"):
292
+ assert hasattr(encoder_pointer, "bias")
293
+ encoder_pointer.bias = decoder_pointer.bias
294
+ print(module_name+' is tied')
295
+ return
296
+
297
+ encoder_modules = encoder_pointer._modules
298
+ decoder_modules = decoder_pointer._modules
299
+ if len(decoder_modules) > 0:
300
+ assert (
301
+ len(encoder_modules) > 0
302
+ ), f"Encoder module {encoder_pointer} does not match decoder module {decoder_pointer}"
303
+
304
+ all_encoder_weights = set([module_name + "/" + sub_name for sub_name in encoder_modules.keys()])
305
+ encoder_layer_pos = 0
306
+ for name, module in decoder_modules.items():
307
+ if name.isdigit():
308
+ encoder_name = str(int(name) + encoder_layer_pos)
309
+ decoder_name = name
310
+ if not isinstance(decoder_modules[decoder_name], type(encoder_modules[encoder_name])) and len(
311
+ encoder_modules
312
+ ) != len(decoder_modules):
313
+ # this can happen if the name corresponds to the position in a list module list of layers
314
+ # in this case the decoder has added a cross-attention that the encoder does not have
315
+ # thus skip this step and subtract one layer pos from encoder
316
+ encoder_layer_pos -= 1
317
+ continue
318
+ elif name not in encoder_modules:
319
+ continue
320
+ elif depth > 500:
321
+ raise ValueError(
322
+ "Max depth of recursive function `tie_encoder_to_decoder` reached. It seems that there is a circular dependency between two or more `nn.Modules` of your model."
323
+ )
324
+ else:
325
+ decoder_name = encoder_name = name
326
+ tie_encoder_to_decoder_recursively(
327
+ decoder_modules[decoder_name],
328
+ encoder_modules[encoder_name],
329
+ module_name + "/" + name,
330
+ uninitialized_encoder_weights,
331
+ skip_key,
332
+ depth=depth + 1,
333
+ )
334
+ all_encoder_weights.remove(module_name + "/" + encoder_name)
335
+
336
+ uninitialized_encoder_weights += list(all_encoder_weights)
337
+
338
+ # tie weights recursively
339
+ tie_encoder_to_decoder_recursively(decoder, encoder, base_model_prefix, uninitialized_encoder_weights, skip_key)
extras/BLIP/models/blip_retrieval.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from extras.BLIP.models.med import BertConfig, BertModel
2
+ from transformers import BertTokenizer
3
+
4
+ import torch
5
+ from torch import nn
6
+ import torch.nn.functional as F
7
+
8
+ from extras.BLIP.models.blip import create_vit, init_tokenizer, load_checkpoint
9
+
10
+ class BLIP_Retrieval(nn.Module):
11
+ def __init__(self,
12
+ med_config = 'configs/med_config.json',
13
+ image_size = 384,
14
+ vit = 'base',
15
+ vit_grad_ckpt = False,
16
+ vit_ckpt_layer = 0,
17
+ embed_dim = 256,
18
+ queue_size = 57600,
19
+ momentum = 0.995,
20
+ negative_all_rank = False,
21
+ ):
22
+ """
23
+ Args:
24
+ med_config (str): path for the mixture of encoder-decoder model's configuration file
25
+ image_size (int): input image size
26
+ vit (str): model size of vision transformer
27
+ """
28
+ super().__init__()
29
+
30
+ self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer)
31
+ self.tokenizer = init_tokenizer()
32
+ med_config = BertConfig.from_json_file(med_config)
33
+ med_config.encoder_width = vision_width
34
+ self.text_encoder = BertModel(config=med_config, add_pooling_layer=False)
35
+
36
+ text_width = self.text_encoder.config.hidden_size
37
+
38
+ self.vision_proj = nn.Linear(vision_width, embed_dim)
39
+ self.text_proj = nn.Linear(text_width, embed_dim)
40
+
41
+ self.itm_head = nn.Linear(text_width, 2)
42
+
43
+ # create momentum encoders
44
+ self.visual_encoder_m, vision_width = create_vit(vit,image_size)
45
+ self.vision_proj_m = nn.Linear(vision_width, embed_dim)
46
+ self.text_encoder_m = BertModel(config=med_config, add_pooling_layer=False)
47
+ self.text_proj_m = nn.Linear(text_width, embed_dim)
48
+
49
+ self.model_pairs = [[self.visual_encoder,self.visual_encoder_m],
50
+ [self.vision_proj,self.vision_proj_m],
51
+ [self.text_encoder,self.text_encoder_m],
52
+ [self.text_proj,self.text_proj_m],
53
+ ]
54
+ self.copy_params()
55
+
56
+ # create the queue
57
+ self.register_buffer("image_queue", torch.randn(embed_dim, queue_size))
58
+ self.register_buffer("text_queue", torch.randn(embed_dim, queue_size))
59
+ self.register_buffer("idx_queue", torch.full((1,queue_size),-100))
60
+ self.register_buffer("ptr_queue", torch.zeros(1, dtype=torch.long))
61
+
62
+ self.image_queue = nn.functional.normalize(self.image_queue, dim=0)
63
+ self.text_queue = nn.functional.normalize(self.text_queue, dim=0)
64
+
65
+ self.queue_size = queue_size
66
+ self.momentum = momentum
67
+ self.temp = nn.Parameter(0.07*torch.ones([]))
68
+
69
+ self.negative_all_rank = negative_all_rank
70
+
71
+
72
+ def forward(self, image, caption, alpha, idx):
73
+ with torch.no_grad():
74
+ self.temp.clamp_(0.001,0.5)
75
+
76
+ image_embeds = self.visual_encoder(image)
77
+ image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
78
+ image_feat = F.normalize(self.vision_proj(image_embeds[:,0,:]),dim=-1)
79
+
80
+ text = self.tokenizer(caption, padding='max_length', truncation=True, max_length=35,
81
+ return_tensors="pt").to(image.device)
82
+
83
+ text_output = self.text_encoder(text.input_ids, attention_mask = text.attention_mask,
84
+ return_dict = True, mode = 'text')
85
+ text_feat = F.normalize(self.text_proj(text_output.last_hidden_state[:,0,:]),dim=-1)
86
+
87
+ ###============== Image-text Contrastive Learning ===================###
88
+ idx = idx.view(-1,1)
89
+ idx_all = torch.cat([idx.t(), self.idx_queue.clone().detach()],dim=1)
90
+ pos_idx = torch.eq(idx, idx_all).float()
91
+ sim_targets = pos_idx / pos_idx.sum(1,keepdim=True)
92
+
93
+ # get momentum features
94
+ with torch.no_grad():
95
+ self._momentum_update()
96
+ image_embeds_m = self.visual_encoder_m(image)
97
+ image_feat_m = F.normalize(self.vision_proj_m(image_embeds_m[:,0,:]),dim=-1)
98
+ image_feat_m_all = torch.cat([image_feat_m.t(),self.image_queue.clone().detach()],dim=1)
99
+
100
+ text_output_m = self.text_encoder_m(text.input_ids, attention_mask = text.attention_mask,
101
+ return_dict = True, mode = 'text')
102
+ text_feat_m = F.normalize(self.text_proj_m(text_output_m.last_hidden_state[:,0,:]),dim=-1)
103
+ text_feat_m_all = torch.cat([text_feat_m.t(),self.text_queue.clone().detach()],dim=1)
104
+
105
+ sim_i2t_m = image_feat_m @ text_feat_m_all / self.temp
106
+ sim_t2i_m = text_feat_m @ image_feat_m_all / self.temp
107
+
108
+ sim_i2t_targets = alpha * F.softmax(sim_i2t_m, dim=1) + (1 - alpha) * sim_targets
109
+ sim_t2i_targets = alpha * F.softmax(sim_t2i_m, dim=1) + (1 - alpha) * sim_targets
110
+
111
+ sim_i2t = image_feat @ text_feat_m_all / self.temp
112
+ sim_t2i = text_feat @ image_feat_m_all / self.temp
113
+
114
+ loss_i2t = -torch.sum(F.log_softmax(sim_i2t, dim=1)*sim_i2t_targets,dim=1).mean()
115
+ loss_t2i = -torch.sum(F.log_softmax(sim_t2i, dim=1)*sim_t2i_targets,dim=1).mean()
116
+
117
+ loss_ita = (loss_i2t+loss_t2i)/2
118
+
119
+ idxs = concat_all_gather(idx)
120
+ self._dequeue_and_enqueue(image_feat_m, text_feat_m, idxs)
121
+
122
+ ###============== Image-text Matching ===================###
123
+ encoder_input_ids = text.input_ids.clone()
124
+ encoder_input_ids[:,0] = self.tokenizer.enc_token_id
125
+
126
+ # forward the positve image-text pair
127
+ bs = image.size(0)
128
+ output_pos = self.text_encoder(encoder_input_ids,
129
+ attention_mask = text.attention_mask,
130
+ encoder_hidden_states = image_embeds,
131
+ encoder_attention_mask = image_atts,
132
+ return_dict = True,
133
+ )
134
+
135
+
136
+ if self.negative_all_rank:
137
+ # compute sample similarity
138
+ with torch.no_grad():
139
+ mask = torch.eq(idx, idxs.t())
140
+
141
+ image_feat_world = concat_all_gather(image_feat)
142
+ text_feat_world = concat_all_gather(text_feat)
143
+
144
+ sim_i2t = image_feat @ text_feat_world.t() / self.temp
145
+ sim_t2i = text_feat @ image_feat_world.t() / self.temp
146
+
147
+ weights_i2t = F.softmax(sim_i2t,dim=1)
148
+ weights_i2t.masked_fill_(mask, 0)
149
+
150
+ weights_t2i = F.softmax(sim_t2i,dim=1)
151
+ weights_t2i.masked_fill_(mask, 0)
152
+
153
+ image_embeds_world = all_gather_with_grad(image_embeds)
154
+
155
+ # select a negative image (from all ranks) for each text
156
+ image_embeds_neg = []
157
+ for b in range(bs):
158
+ neg_idx = torch.multinomial(weights_t2i[b], 1).item()
159
+ image_embeds_neg.append(image_embeds_world[neg_idx])
160
+ image_embeds_neg = torch.stack(image_embeds_neg,dim=0)
161
+
162
+ # select a negative text (from all ranks) for each image
163
+ input_ids_world = concat_all_gather(encoder_input_ids)
164
+ att_mask_world = concat_all_gather(text.attention_mask)
165
+
166
+ text_ids_neg = []
167
+ text_atts_neg = []
168
+ for b in range(bs):
169
+ neg_idx = torch.multinomial(weights_i2t[b], 1).item()
170
+ text_ids_neg.append(input_ids_world[neg_idx])
171
+ text_atts_neg.append(att_mask_world[neg_idx])
172
+
173
+ else:
174
+ with torch.no_grad():
175
+ mask = torch.eq(idx, idx.t())
176
+
177
+ sim_i2t = image_feat @ text_feat.t() / self.temp
178
+ sim_t2i = text_feat @ image_feat.t() / self.temp
179
+
180
+ weights_i2t = F.softmax(sim_i2t,dim=1)
181
+ weights_i2t.masked_fill_(mask, 0)
182
+
183
+ weights_t2i = F.softmax(sim_t2i,dim=1)
184
+ weights_t2i.masked_fill_(mask, 0)
185
+
186
+ # select a negative image (from same rank) for each text
187
+ image_embeds_neg = []
188
+ for b in range(bs):
189
+ neg_idx = torch.multinomial(weights_t2i[b], 1).item()
190
+ image_embeds_neg.append(image_embeds[neg_idx])
191
+ image_embeds_neg = torch.stack(image_embeds_neg,dim=0)
192
+
193
+ # select a negative text (from same rank) for each image
194
+ text_ids_neg = []
195
+ text_atts_neg = []
196
+ for b in range(bs):
197
+ neg_idx = torch.multinomial(weights_i2t[b], 1).item()
198
+ text_ids_neg.append(encoder_input_ids[neg_idx])
199
+ text_atts_neg.append(text.attention_mask[neg_idx])
200
+
201
+ text_ids_neg = torch.stack(text_ids_neg,dim=0)
202
+ text_atts_neg = torch.stack(text_atts_neg,dim=0)
203
+
204
+ text_ids_all = torch.cat([encoder_input_ids, text_ids_neg],dim=0)
205
+ text_atts_all = torch.cat([text.attention_mask, text_atts_neg],dim=0)
206
+
207
+ image_embeds_all = torch.cat([image_embeds_neg,image_embeds],dim=0)
208
+ image_atts_all = torch.cat([image_atts,image_atts],dim=0)
209
+
210
+ output_neg = self.text_encoder(text_ids_all,
211
+ attention_mask = text_atts_all,
212
+ encoder_hidden_states = image_embeds_all,
213
+ encoder_attention_mask = image_atts_all,
214
+ return_dict = True,
215
+ )
216
+
217
+
218
+ vl_embeddings = torch.cat([output_pos.last_hidden_state[:,0,:], output_neg.last_hidden_state[:,0,:]],dim=0)
219
+ vl_output = self.itm_head(vl_embeddings)
220
+
221
+ itm_labels = torch.cat([torch.ones(bs,dtype=torch.long),torch.zeros(2*bs,dtype=torch.long)],
222
+ dim=0).to(image.device)
223
+ loss_itm = F.cross_entropy(vl_output, itm_labels)
224
+
225
+ return loss_ita, loss_itm
226
+
227
+
228
+ @torch.no_grad()
229
+ def copy_params(self):
230
+ for model_pair in self.model_pairs:
231
+ for param, param_m in zip(model_pair[0].parameters(), model_pair[1].parameters()):
232
+ param_m.data.copy_(param.data) # initialize
233
+ param_m.requires_grad = False # not update by gradient
234
+
235
+
236
+ @torch.no_grad()
237
+ def _momentum_update(self):
238
+ for model_pair in self.model_pairs:
239
+ for param, param_m in zip(model_pair[0].parameters(), model_pair[1].parameters()):
240
+ param_m.data = param_m.data * self.momentum + param.data * (1. - self.momentum)
241
+
242
+
243
+ @torch.no_grad()
244
+ def _dequeue_and_enqueue(self, image_feat, text_feat, idxs):
245
+ # gather keys before updating queue
246
+ image_feats = concat_all_gather(image_feat)
247
+ text_feats = concat_all_gather(text_feat)
248
+
249
+
250
+ batch_size = image_feats.shape[0]
251
+
252
+ ptr = int(self.ptr_queue)
253
+ assert self.queue_size % batch_size == 0 # for simplicity
254
+
255
+ # replace the keys at ptr (dequeue and enqueue)
256
+ self.image_queue[:, ptr:ptr + batch_size] = image_feats.T
257
+ self.text_queue[:, ptr:ptr + batch_size] = text_feats.T
258
+ self.idx_queue[:, ptr:ptr + batch_size] = idxs.T
259
+ ptr = (ptr + batch_size) % self.queue_size # move pointer
260
+
261
+ self.ptr_queue[0] = ptr
262
+
263
+
264
+ def blip_retrieval(pretrained='',**kwargs):
265
+ model = BLIP_Retrieval(**kwargs)
266
+ if pretrained:
267
+ model,msg = load_checkpoint(model,pretrained)
268
+ print("missing keys:")
269
+ print(msg.missing_keys)
270
+ return model
271
+
272
+
273
+ @torch.no_grad()
274
+ def concat_all_gather(tensor):
275
+ """
276
+ Performs all_gather operation on the provided tensors.
277
+ *** Warning ***: torch.distributed.all_gather has no gradient.
278
+ """
279
+ tensors_gather = [torch.ones_like(tensor)
280
+ for _ in range(torch.distributed.get_world_size())]
281
+ torch.distributed.all_gather(tensors_gather, tensor, async_op=False)
282
+
283
+ output = torch.cat(tensors_gather, dim=0)
284
+ return output
285
+
286
+
287
+ class GatherLayer(torch.autograd.Function):
288
+ """
289
+ Gather tensors from all workers with support for backward propagation:
290
+ This implementation does not cut the gradients as torch.distributed.all_gather does.
291
+ """
292
+
293
+ @staticmethod
294
+ def forward(ctx, x):
295
+ output = [torch.zeros_like(x) for _ in range(torch.distributed.get_world_size())]
296
+ torch.distributed.all_gather(output, x)
297
+ return tuple(output)
298
+
299
+ @staticmethod
300
+ def backward(ctx, *grads):
301
+ all_gradients = torch.stack(grads)
302
+ torch.distributed.all_reduce(all_gradients)
303
+ return all_gradients[torch.distributed.get_rank()]
304
+
305
+
306
+ def all_gather_with_grad(tensors):
307
+ """
308
+ Performs all_gather operation on the provided tensors.
309
+ Graph remains connected for backward grad computation.
310
+ """
311
+ # Queue the gathered tensors
312
+ world_size = torch.distributed.get_world_size()
313
+ # There is no need for reduction in the single-proc case
314
+ if world_size == 1:
315
+ return tensors
316
+
317
+ tensor_all = GatherLayer.apply(tensors)
318
+
319
+ return torch.cat(tensor_all, dim=0)
extras/BLIP/models/blip_vqa.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from extras.BLIP.models.med import BertConfig, BertModel, BertLMHeadModel
2
+ from extras.BLIP.models.blip import create_vit, init_tokenizer, load_checkpoint
3
+
4
+ import torch
5
+ from torch import nn
6
+ import torch.nn.functional as F
7
+ from transformers import BertTokenizer
8
+ import numpy as np
9
+
10
+ class BLIP_VQA(nn.Module):
11
+ def __init__(self,
12
+ med_config = 'configs/med_config.json',
13
+ image_size = 480,
14
+ vit = 'base',
15
+ vit_grad_ckpt = False,
16
+ vit_ckpt_layer = 0,
17
+ ):
18
+ """
19
+ Args:
20
+ med_config (str): path for the mixture of encoder-decoder model's configuration file
21
+ image_size (int): input image size
22
+ vit (str): model size of vision transformer
23
+ """
24
+ super().__init__()
25
+
26
+ self.visual_encoder, vision_width = create_vit(vit, image_size, vit_grad_ckpt, vit_ckpt_layer, drop_path_rate=0.1)
27
+ self.tokenizer = init_tokenizer()
28
+
29
+ encoder_config = BertConfig.from_json_file(med_config)
30
+ encoder_config.encoder_width = vision_width
31
+ self.text_encoder = BertModel(config=encoder_config, add_pooling_layer=False)
32
+
33
+ decoder_config = BertConfig.from_json_file(med_config)
34
+ self.text_decoder = BertLMHeadModel(config=decoder_config)
35
+
36
+
37
+ def forward(self, image, question, answer=None, n=None, weights=None, train=True, inference='rank', k_test=128):
38
+
39
+ image_embeds = self.visual_encoder(image)
40
+ image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
41
+
42
+ question = self.tokenizer(question, padding='longest', truncation=True, max_length=35,
43
+ return_tensors="pt").to(image.device)
44
+ question.input_ids[:,0] = self.tokenizer.enc_token_id
45
+
46
+ if train:
47
+ '''
48
+ n: number of answers for each question
49
+ weights: weight for each answer
50
+ '''
51
+ answer = self.tokenizer(answer, padding='longest', return_tensors="pt").to(image.device)
52
+ answer.input_ids[:,0] = self.tokenizer.bos_token_id
53
+ answer_targets = answer.input_ids.masked_fill(answer.input_ids == self.tokenizer.pad_token_id, -100)
54
+
55
+ question_output = self.text_encoder(question.input_ids,
56
+ attention_mask = question.attention_mask,
57
+ encoder_hidden_states = image_embeds,
58
+ encoder_attention_mask = image_atts,
59
+ return_dict = True)
60
+
61
+ question_states = []
62
+ question_atts = []
63
+ for b, n in enumerate(n):
64
+ question_states += [question_output.last_hidden_state[b]]*n
65
+ question_atts += [question.attention_mask[b]]*n
66
+ question_states = torch.stack(question_states,0)
67
+ question_atts = torch.stack(question_atts,0)
68
+
69
+ answer_output = self.text_decoder(answer.input_ids,
70
+ attention_mask = answer.attention_mask,
71
+ encoder_hidden_states = question_states,
72
+ encoder_attention_mask = question_atts,
73
+ labels = answer_targets,
74
+ return_dict = True,
75
+ reduction = 'none',
76
+ )
77
+
78
+ loss = weights * answer_output.loss
79
+ loss = loss.sum()/image.size(0)
80
+
81
+ return loss
82
+
83
+
84
+ else:
85
+ question_output = self.text_encoder(question.input_ids,
86
+ attention_mask = question.attention_mask,
87
+ encoder_hidden_states = image_embeds,
88
+ encoder_attention_mask = image_atts,
89
+ return_dict = True)
90
+
91
+ if inference=='generate':
92
+ num_beams = 3
93
+ question_states = question_output.last_hidden_state.repeat_interleave(num_beams,dim=0)
94
+ question_atts = torch.ones(question_states.size()[:-1],dtype=torch.long).to(question_states.device)
95
+ model_kwargs = {"encoder_hidden_states": question_states, "encoder_attention_mask":question_atts}
96
+
97
+ bos_ids = torch.full((image.size(0),1),fill_value=self.tokenizer.bos_token_id,device=image.device)
98
+
99
+ outputs = self.text_decoder.generate(input_ids=bos_ids,
100
+ max_length=10,
101
+ min_length=1,
102
+ num_beams=num_beams,
103
+ eos_token_id=self.tokenizer.sep_token_id,
104
+ pad_token_id=self.tokenizer.pad_token_id,
105
+ **model_kwargs)
106
+
107
+ answers = []
108
+ for output in outputs:
109
+ answer = self.tokenizer.decode(output, skip_special_tokens=True)
110
+ answers.append(answer)
111
+ return answers
112
+
113
+ elif inference=='rank':
114
+ max_ids = self.rank_answer(question_output.last_hidden_state, question.attention_mask,
115
+ answer.input_ids, answer.attention_mask, k_test)
116
+ return max_ids
117
+
118
+
119
+
120
+ def rank_answer(self, question_states, question_atts, answer_ids, answer_atts, k):
121
+
122
+ num_ques = question_states.size(0)
123
+ start_ids = answer_ids[0,0].repeat(num_ques,1) # bos token
124
+
125
+ start_output = self.text_decoder(start_ids,
126
+ encoder_hidden_states = question_states,
127
+ encoder_attention_mask = question_atts,
128
+ return_dict = True,
129
+ reduction = 'none')
130
+ logits = start_output.logits[:,0,:] # first token's logit
131
+
132
+ # topk_probs: top-k probability
133
+ # topk_ids: [num_question, k]
134
+ answer_first_token = answer_ids[:,1]
135
+ prob_first_token = F.softmax(logits,dim=1).index_select(dim=1, index=answer_first_token)
136
+ topk_probs, topk_ids = prob_first_token.topk(k,dim=1)
137
+
138
+ # answer input: [num_question*k, answer_len]
139
+ input_ids = []
140
+ input_atts = []
141
+ for b, topk_id in enumerate(topk_ids):
142
+ input_ids.append(answer_ids.index_select(dim=0, index=topk_id))
143
+ input_atts.append(answer_atts.index_select(dim=0, index=topk_id))
144
+ input_ids = torch.cat(input_ids,dim=0)
145
+ input_atts = torch.cat(input_atts,dim=0)
146
+
147
+ targets_ids = input_ids.masked_fill(input_ids == self.tokenizer.pad_token_id, -100)
148
+
149
+ # repeat encoder's output for top-k answers
150
+ question_states = tile(question_states, 0, k)
151
+ question_atts = tile(question_atts, 0, k)
152
+
153
+ output = self.text_decoder(input_ids,
154
+ attention_mask = input_atts,
155
+ encoder_hidden_states = question_states,
156
+ encoder_attention_mask = question_atts,
157
+ labels = targets_ids,
158
+ return_dict = True,
159
+ reduction = 'none')
160
+
161
+ log_probs_sum = -output.loss
162
+ log_probs_sum = log_probs_sum.view(num_ques,k)
163
+
164
+ max_topk_ids = log_probs_sum.argmax(dim=1)
165
+ max_ids = topk_ids[max_topk_ids>=0,max_topk_ids]
166
+
167
+ return max_ids
168
+
169
+
170
+ def blip_vqa(pretrained='',**kwargs):
171
+ model = BLIP_VQA(**kwargs)
172
+ if pretrained:
173
+ model,msg = load_checkpoint(model,pretrained)
174
+ # assert(len(msg.missing_keys)==0)
175
+ return model
176
+
177
+
178
+ def tile(x, dim, n_tile):
179
+ init_dim = x.size(dim)
180
+ repeat_idx = [1] * x.dim()
181
+ repeat_idx[dim] = n_tile
182
+ x = x.repeat(*(repeat_idx))
183
+ order_index = torch.LongTensor(np.concatenate([init_dim * np.arange(n_tile) + i for i in range(init_dim)]))
184
+ return torch.index_select(x, dim, order_index.to(x.device))
185
+
186
+
extras/BLIP/models/med.py ADDED
@@ -0,0 +1,955 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ * Copyright (c) 2022, salesforce.com, inc.
3
+ * All rights reserved.
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
6
+ * By Junnan Li
7
+ * Based on huggingface code base
8
+ * https://github.com/huggingface/transformers/blob/v4.15.0/src/transformers/models/bert
9
+ '''
10
+
11
+ import math
12
+ import os
13
+ import warnings
14
+ from dataclasses import dataclass
15
+ from typing import Optional, Tuple
16
+
17
+ import torch
18
+ from torch import Tensor, device, dtype, nn
19
+ import torch.utils.checkpoint
20
+ from torch import nn
21
+ from torch.nn import CrossEntropyLoss
22
+ import torch.nn.functional as F
23
+
24
+ from transformers.activations import ACT2FN
25
+ from transformers.file_utils import (
26
+ ModelOutput,
27
+ )
28
+ from transformers.modeling_outputs import (
29
+ BaseModelOutputWithPastAndCrossAttentions,
30
+ BaseModelOutputWithPoolingAndCrossAttentions,
31
+ CausalLMOutputWithCrossAttentions,
32
+ MaskedLMOutput,
33
+ MultipleChoiceModelOutput,
34
+ NextSentencePredictorOutput,
35
+ QuestionAnsweringModelOutput,
36
+ SequenceClassifierOutput,
37
+ TokenClassifierOutput,
38
+ )
39
+ from transformers.modeling_utils import (
40
+ PreTrainedModel,
41
+ apply_chunking_to_forward,
42
+ find_pruneable_heads_and_indices,
43
+ prune_linear_layer,
44
+ )
45
+ from transformers.utils import logging
46
+ from transformers.models.bert.configuration_bert import BertConfig
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+
52
+ class BertEmbeddings(nn.Module):
53
+ """Construct the embeddings from word and position embeddings."""
54
+
55
+ def __init__(self, config):
56
+ super().__init__()
57
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
58
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
59
+
60
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
61
+ # any TensorFlow checkpoint file
62
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
63
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
64
+
65
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
66
+ self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
67
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
68
+
69
+ self.config = config
70
+
71
+ def forward(
72
+ self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
73
+ ):
74
+ if input_ids is not None:
75
+ input_shape = input_ids.size()
76
+ else:
77
+ input_shape = inputs_embeds.size()[:-1]
78
+
79
+ seq_length = input_shape[1]
80
+
81
+ if position_ids is None:
82
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
83
+
84
+ if inputs_embeds is None:
85
+ inputs_embeds = self.word_embeddings(input_ids)
86
+
87
+ embeddings = inputs_embeds
88
+
89
+ if self.position_embedding_type == "absolute":
90
+ position_embeddings = self.position_embeddings(position_ids)
91
+ embeddings += position_embeddings
92
+ embeddings = self.LayerNorm(embeddings)
93
+ embeddings = self.dropout(embeddings)
94
+ return embeddings
95
+
96
+
97
+ class BertSelfAttention(nn.Module):
98
+ def __init__(self, config, is_cross_attention):
99
+ super().__init__()
100
+ self.config = config
101
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
102
+ raise ValueError(
103
+ "The hidden size (%d) is not a multiple of the number of attention "
104
+ "heads (%d)" % (config.hidden_size, config.num_attention_heads)
105
+ )
106
+
107
+ self.num_attention_heads = config.num_attention_heads
108
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
109
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
110
+
111
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
112
+ if is_cross_attention:
113
+ self.key = nn.Linear(config.encoder_width, self.all_head_size)
114
+ self.value = nn.Linear(config.encoder_width, self.all_head_size)
115
+ else:
116
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
117
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
118
+
119
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
120
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
121
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
122
+ self.max_position_embeddings = config.max_position_embeddings
123
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
124
+ self.save_attention = False
125
+
126
+ def save_attn_gradients(self, attn_gradients):
127
+ self.attn_gradients = attn_gradients
128
+
129
+ def get_attn_gradients(self):
130
+ return self.attn_gradients
131
+
132
+ def save_attention_map(self, attention_map):
133
+ self.attention_map = attention_map
134
+
135
+ def get_attention_map(self):
136
+ return self.attention_map
137
+
138
+ def transpose_for_scores(self, x):
139
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
140
+ x = x.view(*new_x_shape)
141
+ return x.permute(0, 2, 1, 3)
142
+
143
+ def forward(
144
+ self,
145
+ hidden_states,
146
+ attention_mask=None,
147
+ head_mask=None,
148
+ encoder_hidden_states=None,
149
+ encoder_attention_mask=None,
150
+ past_key_value=None,
151
+ output_attentions=False,
152
+ ):
153
+ mixed_query_layer = self.query(hidden_states)
154
+
155
+ # If this is instantiated as a cross-attention module, the keys
156
+ # and values come from an encoder; the attention mask needs to be
157
+ # such that the encoder's padding tokens are not attended to.
158
+ is_cross_attention = encoder_hidden_states is not None
159
+
160
+ if is_cross_attention:
161
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
162
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
163
+ attention_mask = encoder_attention_mask
164
+ elif past_key_value is not None:
165
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
166
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
167
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
168
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
169
+ else:
170
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
171
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
172
+
173
+ query_layer = self.transpose_for_scores(mixed_query_layer)
174
+
175
+ past_key_value = (key_layer, value_layer)
176
+
177
+ # Take the dot product between "query" and "key" to get the raw attention scores.
178
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
179
+
180
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
181
+ seq_length = hidden_states.size()[1]
182
+ position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
183
+ position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
184
+ distance = position_ids_l - position_ids_r
185
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
186
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
187
+
188
+ if self.position_embedding_type == "relative_key":
189
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
190
+ attention_scores = attention_scores + relative_position_scores
191
+ elif self.position_embedding_type == "relative_key_query":
192
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
193
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
194
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
195
+
196
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
197
+ if attention_mask is not None:
198
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
199
+ attention_scores = attention_scores + attention_mask
200
+
201
+ # Normalize the attention scores to probabilities.
202
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
203
+
204
+ if is_cross_attention and self.save_attention:
205
+ self.save_attention_map(attention_probs)
206
+ attention_probs.register_hook(self.save_attn_gradients)
207
+
208
+ # This is actually dropping out entire tokens to attend to, which might
209
+ # seem a bit unusual, but is taken from the original Transformer paper.
210
+ attention_probs_dropped = self.dropout(attention_probs)
211
+
212
+ # Mask heads if we want to
213
+ if head_mask is not None:
214
+ attention_probs_dropped = attention_probs_dropped * head_mask
215
+
216
+ context_layer = torch.matmul(attention_probs_dropped, value_layer)
217
+
218
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
219
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
220
+ context_layer = context_layer.view(*new_context_layer_shape)
221
+
222
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
223
+
224
+ outputs = outputs + (past_key_value,)
225
+ return outputs
226
+
227
+
228
+ class BertSelfOutput(nn.Module):
229
+ def __init__(self, config):
230
+ super().__init__()
231
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
232
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
233
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
234
+
235
+ def forward(self, hidden_states, input_tensor):
236
+ hidden_states = self.dense(hidden_states)
237
+ hidden_states = self.dropout(hidden_states)
238
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
239
+ return hidden_states
240
+
241
+
242
+ class BertAttention(nn.Module):
243
+ def __init__(self, config, is_cross_attention=False):
244
+ super().__init__()
245
+ self.self = BertSelfAttention(config, is_cross_attention)
246
+ self.output = BertSelfOutput(config)
247
+ self.pruned_heads = set()
248
+
249
+ def prune_heads(self, heads):
250
+ if len(heads) == 0:
251
+ return
252
+ heads, index = find_pruneable_heads_and_indices(
253
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
254
+ )
255
+
256
+ # Prune linear layers
257
+ self.self.query = prune_linear_layer(self.self.query, index)
258
+ self.self.key = prune_linear_layer(self.self.key, index)
259
+ self.self.value = prune_linear_layer(self.self.value, index)
260
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
261
+
262
+ # Update hyper params and store pruned heads
263
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
264
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
265
+ self.pruned_heads = self.pruned_heads.union(heads)
266
+
267
+ def forward(
268
+ self,
269
+ hidden_states,
270
+ attention_mask=None,
271
+ head_mask=None,
272
+ encoder_hidden_states=None,
273
+ encoder_attention_mask=None,
274
+ past_key_value=None,
275
+ output_attentions=False,
276
+ ):
277
+ self_outputs = self.self(
278
+ hidden_states,
279
+ attention_mask,
280
+ head_mask,
281
+ encoder_hidden_states,
282
+ encoder_attention_mask,
283
+ past_key_value,
284
+ output_attentions,
285
+ )
286
+ attention_output = self.output(self_outputs[0], hidden_states)
287
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
288
+ return outputs
289
+
290
+
291
+ class BertIntermediate(nn.Module):
292
+ def __init__(self, config):
293
+ super().__init__()
294
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
295
+ if isinstance(config.hidden_act, str):
296
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
297
+ else:
298
+ self.intermediate_act_fn = config.hidden_act
299
+
300
+ def forward(self, hidden_states):
301
+ hidden_states = self.dense(hidden_states)
302
+ hidden_states = self.intermediate_act_fn(hidden_states)
303
+ return hidden_states
304
+
305
+
306
+ class BertOutput(nn.Module):
307
+ def __init__(self, config):
308
+ super().__init__()
309
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
310
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
311
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
312
+
313
+ def forward(self, hidden_states, input_tensor):
314
+ hidden_states = self.dense(hidden_states)
315
+ hidden_states = self.dropout(hidden_states)
316
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
317
+ return hidden_states
318
+
319
+
320
+ class BertLayer(nn.Module):
321
+ def __init__(self, config, layer_num):
322
+ super().__init__()
323
+ self.config = config
324
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
325
+ self.seq_len_dim = 1
326
+ self.attention = BertAttention(config)
327
+ self.layer_num = layer_num
328
+ if self.config.add_cross_attention:
329
+ self.crossattention = BertAttention(config, is_cross_attention=self.config.add_cross_attention)
330
+ self.intermediate = BertIntermediate(config)
331
+ self.output = BertOutput(config)
332
+
333
+ def forward(
334
+ self,
335
+ hidden_states,
336
+ attention_mask=None,
337
+ head_mask=None,
338
+ encoder_hidden_states=None,
339
+ encoder_attention_mask=None,
340
+ past_key_value=None,
341
+ output_attentions=False,
342
+ mode=None,
343
+ ):
344
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
345
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
346
+ self_attention_outputs = self.attention(
347
+ hidden_states,
348
+ attention_mask,
349
+ head_mask,
350
+ output_attentions=output_attentions,
351
+ past_key_value=self_attn_past_key_value,
352
+ )
353
+ attention_output = self_attention_outputs[0]
354
+
355
+ outputs = self_attention_outputs[1:-1]
356
+ present_key_value = self_attention_outputs[-1]
357
+
358
+ if mode=='multimodal':
359
+ assert encoder_hidden_states is not None, "encoder_hidden_states must be given for cross-attention layers"
360
+
361
+ cross_attention_outputs = self.crossattention(
362
+ attention_output,
363
+ attention_mask,
364
+ head_mask,
365
+ encoder_hidden_states,
366
+ encoder_attention_mask,
367
+ output_attentions=output_attentions,
368
+ )
369
+ attention_output = cross_attention_outputs[0]
370
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
371
+ layer_output = apply_chunking_to_forward(
372
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
373
+ )
374
+ outputs = (layer_output,) + outputs
375
+
376
+ outputs = outputs + (present_key_value,)
377
+
378
+ return outputs
379
+
380
+ def feed_forward_chunk(self, attention_output):
381
+ intermediate_output = self.intermediate(attention_output)
382
+ layer_output = self.output(intermediate_output, attention_output)
383
+ return layer_output
384
+
385
+
386
+ class BertEncoder(nn.Module):
387
+ def __init__(self, config):
388
+ super().__init__()
389
+ self.config = config
390
+ self.layer = nn.ModuleList([BertLayer(config,i) for i in range(config.num_hidden_layers)])
391
+ self.gradient_checkpointing = False
392
+
393
+ def forward(
394
+ self,
395
+ hidden_states,
396
+ attention_mask=None,
397
+ head_mask=None,
398
+ encoder_hidden_states=None,
399
+ encoder_attention_mask=None,
400
+ past_key_values=None,
401
+ use_cache=None,
402
+ output_attentions=False,
403
+ output_hidden_states=False,
404
+ return_dict=True,
405
+ mode='multimodal',
406
+ ):
407
+ all_hidden_states = () if output_hidden_states else None
408
+ all_self_attentions = () if output_attentions else None
409
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
410
+
411
+ next_decoder_cache = () if use_cache else None
412
+
413
+ for i in range(self.config.num_hidden_layers):
414
+ layer_module = self.layer[i]
415
+ if output_hidden_states:
416
+ all_hidden_states = all_hidden_states + (hidden_states,)
417
+
418
+ layer_head_mask = head_mask[i] if head_mask is not None else None
419
+ past_key_value = past_key_values[i] if past_key_values is not None else None
420
+
421
+ if self.gradient_checkpointing and self.training:
422
+
423
+ if use_cache:
424
+ logger.warn(
425
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
426
+ )
427
+ use_cache = False
428
+
429
+ def create_custom_forward(module):
430
+ def custom_forward(*inputs):
431
+ return module(*inputs, past_key_value, output_attentions)
432
+
433
+ return custom_forward
434
+
435
+ layer_outputs = torch.utils.checkpoint.checkpoint(
436
+ create_custom_forward(layer_module),
437
+ hidden_states,
438
+ attention_mask,
439
+ layer_head_mask,
440
+ encoder_hidden_states,
441
+ encoder_attention_mask,
442
+ mode=mode,
443
+ )
444
+ else:
445
+ layer_outputs = layer_module(
446
+ hidden_states,
447
+ attention_mask,
448
+ layer_head_mask,
449
+ encoder_hidden_states,
450
+ encoder_attention_mask,
451
+ past_key_value,
452
+ output_attentions,
453
+ mode=mode,
454
+ )
455
+
456
+ hidden_states = layer_outputs[0]
457
+ if use_cache:
458
+ next_decoder_cache += (layer_outputs[-1],)
459
+ if output_attentions:
460
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
461
+
462
+ if output_hidden_states:
463
+ all_hidden_states = all_hidden_states + (hidden_states,)
464
+
465
+ if not return_dict:
466
+ return tuple(
467
+ v
468
+ for v in [
469
+ hidden_states,
470
+ next_decoder_cache,
471
+ all_hidden_states,
472
+ all_self_attentions,
473
+ all_cross_attentions,
474
+ ]
475
+ if v is not None
476
+ )
477
+ return BaseModelOutputWithPastAndCrossAttentions(
478
+ last_hidden_state=hidden_states,
479
+ past_key_values=next_decoder_cache,
480
+ hidden_states=all_hidden_states,
481
+ attentions=all_self_attentions,
482
+ cross_attentions=all_cross_attentions,
483
+ )
484
+
485
+
486
+ class BertPooler(nn.Module):
487
+ def __init__(self, config):
488
+ super().__init__()
489
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
490
+ self.activation = nn.Tanh()
491
+
492
+ def forward(self, hidden_states):
493
+ # We "pool" the model by simply taking the hidden state corresponding
494
+ # to the first token.
495
+ first_token_tensor = hidden_states[:, 0]
496
+ pooled_output = self.dense(first_token_tensor)
497
+ pooled_output = self.activation(pooled_output)
498
+ return pooled_output
499
+
500
+
501
+ class BertPredictionHeadTransform(nn.Module):
502
+ def __init__(self, config):
503
+ super().__init__()
504
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
505
+ if isinstance(config.hidden_act, str):
506
+ self.transform_act_fn = ACT2FN[config.hidden_act]
507
+ else:
508
+ self.transform_act_fn = config.hidden_act
509
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
510
+
511
+ def forward(self, hidden_states):
512
+ hidden_states = self.dense(hidden_states)
513
+ hidden_states = self.transform_act_fn(hidden_states)
514
+ hidden_states = self.LayerNorm(hidden_states)
515
+ return hidden_states
516
+
517
+
518
+ class BertLMPredictionHead(nn.Module):
519
+ def __init__(self, config):
520
+ super().__init__()
521
+ self.transform = BertPredictionHeadTransform(config)
522
+
523
+ # The output weights are the same as the input embeddings, but there is
524
+ # an output-only bias for each token.
525
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
526
+
527
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
528
+
529
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
530
+ self.decoder.bias = self.bias
531
+
532
+ def forward(self, hidden_states):
533
+ hidden_states = self.transform(hidden_states)
534
+ hidden_states = self.decoder(hidden_states)
535
+ return hidden_states
536
+
537
+
538
+ class BertOnlyMLMHead(nn.Module):
539
+ def __init__(self, config):
540
+ super().__init__()
541
+ self.predictions = BertLMPredictionHead(config)
542
+
543
+ def forward(self, sequence_output):
544
+ prediction_scores = self.predictions(sequence_output)
545
+ return prediction_scores
546
+
547
+
548
+ class BertPreTrainedModel(PreTrainedModel):
549
+ """
550
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
551
+ models.
552
+ """
553
+
554
+ config_class = BertConfig
555
+ base_model_prefix = "bert"
556
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
557
+
558
+ def _init_weights(self, module):
559
+ """ Initialize the weights """
560
+ if isinstance(module, (nn.Linear, nn.Embedding)):
561
+ # Slightly different from the TF version which uses truncated_normal for initialization
562
+ # cf https://github.com/pytorch/pytorch/pull/5617
563
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
564
+ elif isinstance(module, nn.LayerNorm):
565
+ module.bias.data.zero_()
566
+ module.weight.data.fill_(1.0)
567
+ if isinstance(module, nn.Linear) and module.bias is not None:
568
+ module.bias.data.zero_()
569
+
570
+
571
+ class BertModel(BertPreTrainedModel):
572
+ """
573
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
574
+ cross-attention is added between the self-attention layers, following the architecture described in `Attention is
575
+ all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
576
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
577
+ argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
578
+ input to the forward pass.
579
+ """
580
+
581
+ def __init__(self, config, add_pooling_layer=True):
582
+ super().__init__(config)
583
+ self.config = config
584
+
585
+ self.embeddings = BertEmbeddings(config)
586
+
587
+ self.encoder = BertEncoder(config)
588
+
589
+ self.pooler = BertPooler(config) if add_pooling_layer else None
590
+
591
+ self.init_weights()
592
+
593
+
594
+ def get_input_embeddings(self):
595
+ return self.embeddings.word_embeddings
596
+
597
+ def set_input_embeddings(self, value):
598
+ self.embeddings.word_embeddings = value
599
+
600
+ def _prune_heads(self, heads_to_prune):
601
+ """
602
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
603
+ class PreTrainedModel
604
+ """
605
+ for layer, heads in heads_to_prune.items():
606
+ self.encoder.layer[layer].attention.prune_heads(heads)
607
+
608
+
609
+ def get_extended_attention_mask(self, attention_mask: Tensor, input_shape: Tuple[int], device: device, is_decoder: bool) -> Tensor:
610
+ """
611
+ Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
612
+
613
+ Arguments:
614
+ attention_mask (:obj:`torch.Tensor`):
615
+ Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
616
+ input_shape (:obj:`Tuple[int]`):
617
+ The shape of the input to the model.
618
+ device: (:obj:`torch.device`):
619
+ The device of the input to the model.
620
+
621
+ Returns:
622
+ :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`.
623
+ """
624
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
625
+ # ourselves in which case we just need to make it broadcastable to all heads.
626
+ if attention_mask.dim() == 3:
627
+ extended_attention_mask = attention_mask[:, None, :, :]
628
+ elif attention_mask.dim() == 2:
629
+ # Provided a padding mask of dimensions [batch_size, seq_length]
630
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
631
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
632
+ if is_decoder:
633
+ batch_size, seq_length = input_shape
634
+
635
+ seq_ids = torch.arange(seq_length, device=device)
636
+ causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None]
637
+ # in case past_key_values are used we need to add a prefix ones mask to the causal mask
638
+ # causal and attention masks must have same type with pytorch version < 1.3
639
+ causal_mask = causal_mask.to(attention_mask.dtype)
640
+
641
+ if causal_mask.shape[1] < attention_mask.shape[1]:
642
+ prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
643
+ causal_mask = torch.cat(
644
+ [
645
+ torch.ones((batch_size, seq_length, prefix_seq_len), device=device, dtype=causal_mask.dtype),
646
+ causal_mask,
647
+ ],
648
+ axis=-1,
649
+ )
650
+
651
+ extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
652
+ else:
653
+ extended_attention_mask = attention_mask[:, None, None, :]
654
+ else:
655
+ raise ValueError(
656
+ "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
657
+ input_shape, attention_mask.shape
658
+ )
659
+ )
660
+
661
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
662
+ # masked positions, this operation will create a tensor which is 0.0 for
663
+ # positions we want to attend and -10000.0 for masked positions.
664
+ # Since we are adding it to the raw scores before the softmax, this is
665
+ # effectively the same as removing these entirely.
666
+ extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
667
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
668
+ return extended_attention_mask
669
+
670
+ def forward(
671
+ self,
672
+ input_ids=None,
673
+ attention_mask=None,
674
+ position_ids=None,
675
+ head_mask=None,
676
+ inputs_embeds=None,
677
+ encoder_embeds=None,
678
+ encoder_hidden_states=None,
679
+ encoder_attention_mask=None,
680
+ past_key_values=None,
681
+ use_cache=None,
682
+ output_attentions=None,
683
+ output_hidden_states=None,
684
+ return_dict=None,
685
+ is_decoder=False,
686
+ mode='multimodal',
687
+ ):
688
+ r"""
689
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
690
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
691
+ the model is configured as a decoder.
692
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
693
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
694
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
695
+ - 1 for tokens that are **not masked**,
696
+ - 0 for tokens that are **masked**.
697
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
698
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
699
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
700
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
701
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
702
+ use_cache (:obj:`bool`, `optional`):
703
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
704
+ decoding (see :obj:`past_key_values`).
705
+ """
706
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
707
+ output_hidden_states = (
708
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
709
+ )
710
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
711
+
712
+ if is_decoder:
713
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
714
+ else:
715
+ use_cache = False
716
+
717
+ if input_ids is not None and inputs_embeds is not None:
718
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
719
+ elif input_ids is not None:
720
+ input_shape = input_ids.size()
721
+ batch_size, seq_length = input_shape
722
+ device = input_ids.device
723
+ elif inputs_embeds is not None:
724
+ input_shape = inputs_embeds.size()[:-1]
725
+ batch_size, seq_length = input_shape
726
+ device = inputs_embeds.device
727
+ elif encoder_embeds is not None:
728
+ input_shape = encoder_embeds.size()[:-1]
729
+ batch_size, seq_length = input_shape
730
+ device = encoder_embeds.device
731
+ else:
732
+ raise ValueError("You have to specify either input_ids or inputs_embeds or encoder_embeds")
733
+
734
+ # past_key_values_length
735
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
736
+
737
+ if attention_mask is None:
738
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
739
+
740
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
741
+ # ourselves in which case we just need to make it broadcastable to all heads.
742
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape,
743
+ device, is_decoder)
744
+
745
+ # If a 2D or 3D attention mask is provided for the cross-attention
746
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
747
+ if encoder_hidden_states is not None:
748
+ if type(encoder_hidden_states) == list:
749
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size()
750
+ else:
751
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
752
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
753
+
754
+ if type(encoder_attention_mask) == list:
755
+ encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask]
756
+ elif encoder_attention_mask is None:
757
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
758
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
759
+ else:
760
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
761
+ else:
762
+ encoder_extended_attention_mask = None
763
+
764
+ # Prepare head mask if needed
765
+ # 1.0 in head_mask indicate we keep the head
766
+ # attention_probs has shape bsz x n_heads x N x N
767
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
768
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
769
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
770
+
771
+ if encoder_embeds is None:
772
+ embedding_output = self.embeddings(
773
+ input_ids=input_ids,
774
+ position_ids=position_ids,
775
+ inputs_embeds=inputs_embeds,
776
+ past_key_values_length=past_key_values_length,
777
+ )
778
+ else:
779
+ embedding_output = encoder_embeds
780
+
781
+ encoder_outputs = self.encoder(
782
+ embedding_output,
783
+ attention_mask=extended_attention_mask,
784
+ head_mask=head_mask,
785
+ encoder_hidden_states=encoder_hidden_states,
786
+ encoder_attention_mask=encoder_extended_attention_mask,
787
+ past_key_values=past_key_values,
788
+ use_cache=use_cache,
789
+ output_attentions=output_attentions,
790
+ output_hidden_states=output_hidden_states,
791
+ return_dict=return_dict,
792
+ mode=mode,
793
+ )
794
+ sequence_output = encoder_outputs[0]
795
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
796
+
797
+ if not return_dict:
798
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
799
+
800
+ return BaseModelOutputWithPoolingAndCrossAttentions(
801
+ last_hidden_state=sequence_output,
802
+ pooler_output=pooled_output,
803
+ past_key_values=encoder_outputs.past_key_values,
804
+ hidden_states=encoder_outputs.hidden_states,
805
+ attentions=encoder_outputs.attentions,
806
+ cross_attentions=encoder_outputs.cross_attentions,
807
+ )
808
+
809
+
810
+
811
+ class BertLMHeadModel(BertPreTrainedModel):
812
+
813
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
814
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
815
+
816
+ def __init__(self, config):
817
+ super().__init__(config)
818
+
819
+ self.bert = BertModel(config, add_pooling_layer=False)
820
+ self.cls = BertOnlyMLMHead(config)
821
+
822
+ self.init_weights()
823
+
824
+ def get_output_embeddings(self):
825
+ return self.cls.predictions.decoder
826
+
827
+ def set_output_embeddings(self, new_embeddings):
828
+ self.cls.predictions.decoder = new_embeddings
829
+
830
+ def forward(
831
+ self,
832
+ input_ids=None,
833
+ attention_mask=None,
834
+ position_ids=None,
835
+ head_mask=None,
836
+ inputs_embeds=None,
837
+ encoder_hidden_states=None,
838
+ encoder_attention_mask=None,
839
+ labels=None,
840
+ past_key_values=None,
841
+ use_cache=None,
842
+ output_attentions=None,
843
+ output_hidden_states=None,
844
+ return_dict=None,
845
+ return_logits=False,
846
+ is_decoder=True,
847
+ reduction='mean',
848
+ mode='multimodal',
849
+ ):
850
+ r"""
851
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
852
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
853
+ the model is configured as a decoder.
854
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
855
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
856
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
857
+ - 1 for tokens that are **not masked**,
858
+ - 0 for tokens that are **masked**.
859
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
860
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
861
+ ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are
862
+ ignored (masked), the loss is only computed for the tokens with labels n ``[0, ..., config.vocab_size]``
863
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
864
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
865
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
866
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
867
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
868
+ use_cache (:obj:`bool`, `optional`):
869
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
870
+ decoding (see :obj:`past_key_values`).
871
+ Returns:
872
+ Example::
873
+ >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig
874
+ >>> import torch
875
+ >>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
876
+ >>> config = BertConfig.from_pretrained("bert-base-cased")
877
+ >>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config)
878
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
879
+ >>> outputs = model(**inputs)
880
+ >>> prediction_logits = outputs.logits
881
+ """
882
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
883
+ if labels is not None:
884
+ use_cache = False
885
+
886
+ outputs = self.bert(
887
+ input_ids,
888
+ attention_mask=attention_mask,
889
+ position_ids=position_ids,
890
+ head_mask=head_mask,
891
+ inputs_embeds=inputs_embeds,
892
+ encoder_hidden_states=encoder_hidden_states,
893
+ encoder_attention_mask=encoder_attention_mask,
894
+ past_key_values=past_key_values,
895
+ use_cache=use_cache,
896
+ output_attentions=output_attentions,
897
+ output_hidden_states=output_hidden_states,
898
+ return_dict=return_dict,
899
+ is_decoder=is_decoder,
900
+ mode=mode,
901
+ )
902
+
903
+ sequence_output = outputs[0]
904
+ prediction_scores = self.cls(sequence_output)
905
+
906
+ if return_logits:
907
+ return prediction_scores[:, :-1, :].contiguous()
908
+
909
+ lm_loss = None
910
+ if labels is not None:
911
+ # we are doing next-token prediction; shift prediction scores and input ids by one
912
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
913
+ labels = labels[:, 1:].contiguous()
914
+ loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=0.1)
915
+ lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
916
+ if reduction=='none':
917
+ lm_loss = lm_loss.view(prediction_scores.size(0),-1).sum(1)
918
+
919
+ if not return_dict:
920
+ output = (prediction_scores,) + outputs[2:]
921
+ return ((lm_loss,) + output) if lm_loss is not None else output
922
+
923
+ return CausalLMOutputWithCrossAttentions(
924
+ loss=lm_loss,
925
+ logits=prediction_scores,
926
+ past_key_values=outputs.past_key_values,
927
+ hidden_states=outputs.hidden_states,
928
+ attentions=outputs.attentions,
929
+ cross_attentions=outputs.cross_attentions,
930
+ )
931
+
932
+ def prepare_inputs_for_generation(self, input_ids, past=None, attention_mask=None, **model_kwargs):
933
+ input_shape = input_ids.shape
934
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
935
+ if attention_mask is None:
936
+ attention_mask = input_ids.new_ones(input_shape)
937
+
938
+ # cut decoder_input_ids if past is used
939
+ if past is not None:
940
+ input_ids = input_ids[:, -1:]
941
+
942
+ return {
943
+ "input_ids": input_ids,
944
+ "attention_mask": attention_mask,
945
+ "past_key_values": past,
946
+ "encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None),
947
+ "encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None),
948
+ "is_decoder": True,
949
+ }
950
+
951
+ def _reorder_cache(self, past, beam_idx):
952
+ reordered_past = ()
953
+ for layer_past in past:
954
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
955
+ return reordered_past
extras/BLIP/models/nlvr_encoder.py ADDED
@@ -0,0 +1,843 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import warnings
4
+ from dataclasses import dataclass
5
+ from typing import Optional, Tuple
6
+
7
+ import torch
8
+ from torch import Tensor, device, dtype, nn
9
+ import torch.utils.checkpoint
10
+ from torch import nn
11
+ from torch.nn import CrossEntropyLoss
12
+ import torch.nn.functional as F
13
+
14
+ from transformers.activations import ACT2FN
15
+ from transformers.file_utils import (
16
+ ModelOutput,
17
+ )
18
+ from transformers.modeling_outputs import (
19
+ BaseModelOutputWithPastAndCrossAttentions,
20
+ BaseModelOutputWithPoolingAndCrossAttentions,
21
+ CausalLMOutputWithCrossAttentions,
22
+ MaskedLMOutput,
23
+ MultipleChoiceModelOutput,
24
+ NextSentencePredictorOutput,
25
+ QuestionAnsweringModelOutput,
26
+ SequenceClassifierOutput,
27
+ TokenClassifierOutput,
28
+ )
29
+ from transformers.modeling_utils import (
30
+ PreTrainedModel,
31
+ apply_chunking_to_forward,
32
+ find_pruneable_heads_and_indices,
33
+ prune_linear_layer,
34
+ )
35
+ from transformers.utils import logging
36
+ from transformers.models.bert.configuration_bert import BertConfig
37
+
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+
42
+ class BertEmbeddings(nn.Module):
43
+ """Construct the embeddings from word and position embeddings."""
44
+
45
+ def __init__(self, config):
46
+ super().__init__()
47
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
48
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
49
+
50
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
51
+ # any TensorFlow checkpoint file
52
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
53
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
54
+
55
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
56
+ self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
57
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
58
+
59
+ self.config = config
60
+
61
+ def forward(
62
+ self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
63
+ ):
64
+ if input_ids is not None:
65
+ input_shape = input_ids.size()
66
+ else:
67
+ input_shape = inputs_embeds.size()[:-1]
68
+
69
+ seq_length = input_shape[1]
70
+
71
+ if position_ids is None:
72
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
73
+
74
+ if inputs_embeds is None:
75
+ inputs_embeds = self.word_embeddings(input_ids)
76
+
77
+ embeddings = inputs_embeds
78
+
79
+ if self.position_embedding_type == "absolute":
80
+ position_embeddings = self.position_embeddings(position_ids)
81
+ embeddings += position_embeddings
82
+ embeddings = self.LayerNorm(embeddings)
83
+ embeddings = self.dropout(embeddings)
84
+ return embeddings
85
+
86
+
87
+ class BertSelfAttention(nn.Module):
88
+ def __init__(self, config, is_cross_attention):
89
+ super().__init__()
90
+ self.config = config
91
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
92
+ raise ValueError(
93
+ "The hidden size (%d) is not a multiple of the number of attention "
94
+ "heads (%d)" % (config.hidden_size, config.num_attention_heads)
95
+ )
96
+
97
+ self.num_attention_heads = config.num_attention_heads
98
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
99
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
100
+
101
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
102
+ if is_cross_attention:
103
+ self.key = nn.Linear(config.encoder_width, self.all_head_size)
104
+ self.value = nn.Linear(config.encoder_width, self.all_head_size)
105
+ else:
106
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
107
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
108
+
109
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
110
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
111
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
112
+ self.max_position_embeddings = config.max_position_embeddings
113
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
114
+ self.save_attention = False
115
+
116
+ def save_attn_gradients(self, attn_gradients):
117
+ self.attn_gradients = attn_gradients
118
+
119
+ def get_attn_gradients(self):
120
+ return self.attn_gradients
121
+
122
+ def save_attention_map(self, attention_map):
123
+ self.attention_map = attention_map
124
+
125
+ def get_attention_map(self):
126
+ return self.attention_map
127
+
128
+ def transpose_for_scores(self, x):
129
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
130
+ x = x.view(*new_x_shape)
131
+ return x.permute(0, 2, 1, 3)
132
+
133
+ def forward(
134
+ self,
135
+ hidden_states,
136
+ attention_mask=None,
137
+ head_mask=None,
138
+ encoder_hidden_states=None,
139
+ encoder_attention_mask=None,
140
+ past_key_value=None,
141
+ output_attentions=False,
142
+ ):
143
+ mixed_query_layer = self.query(hidden_states)
144
+
145
+ # If this is instantiated as a cross-attention module, the keys
146
+ # and values come from an encoder; the attention mask needs to be
147
+ # such that the encoder's padding tokens are not attended to.
148
+ is_cross_attention = encoder_hidden_states is not None
149
+
150
+ if is_cross_attention:
151
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
152
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
153
+ attention_mask = encoder_attention_mask
154
+ elif past_key_value is not None:
155
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
156
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
157
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
158
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
159
+ else:
160
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
161
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
162
+
163
+ query_layer = self.transpose_for_scores(mixed_query_layer)
164
+
165
+ past_key_value = (key_layer, value_layer)
166
+
167
+ # Take the dot product between "query" and "key" to get the raw attention scores.
168
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
169
+
170
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
171
+ seq_length = hidden_states.size()[1]
172
+ position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
173
+ position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
174
+ distance = position_ids_l - position_ids_r
175
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
176
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
177
+
178
+ if self.position_embedding_type == "relative_key":
179
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
180
+ attention_scores = attention_scores + relative_position_scores
181
+ elif self.position_embedding_type == "relative_key_query":
182
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
183
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
184
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
185
+
186
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
187
+ if attention_mask is not None:
188
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
189
+ attention_scores = attention_scores + attention_mask
190
+
191
+ # Normalize the attention scores to probabilities.
192
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
193
+
194
+ if is_cross_attention and self.save_attention:
195
+ self.save_attention_map(attention_probs)
196
+ attention_probs.register_hook(self.save_attn_gradients)
197
+
198
+ # This is actually dropping out entire tokens to attend to, which might
199
+ # seem a bit unusual, but is taken from the original Transformer paper.
200
+ attention_probs_dropped = self.dropout(attention_probs)
201
+
202
+ # Mask heads if we want to
203
+ if head_mask is not None:
204
+ attention_probs_dropped = attention_probs_dropped * head_mask
205
+
206
+ context_layer = torch.matmul(attention_probs_dropped, value_layer)
207
+
208
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
209
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
210
+ context_layer = context_layer.view(*new_context_layer_shape)
211
+
212
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
213
+
214
+ outputs = outputs + (past_key_value,)
215
+ return outputs
216
+
217
+
218
+ class BertSelfOutput(nn.Module):
219
+ def __init__(self, config, twin=False, merge=False):
220
+ super().__init__()
221
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
222
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
223
+ if twin:
224
+ self.dense0 = nn.Linear(config.hidden_size, config.hidden_size)
225
+ self.dense1 = nn.Linear(config.hidden_size, config.hidden_size)
226
+ else:
227
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
228
+ if merge:
229
+ self.act = ACT2FN[config.hidden_act]
230
+ self.merge_layer = nn.Linear(config.hidden_size * 2, config.hidden_size)
231
+ self.merge = True
232
+ else:
233
+ self.merge = False
234
+
235
+ def forward(self, hidden_states, input_tensor):
236
+ if type(hidden_states) == list:
237
+ hidden_states0 = self.dense0(hidden_states[0])
238
+ hidden_states1 = self.dense1(hidden_states[1])
239
+ if self.merge:
240
+ #hidden_states = self.merge_layer(self.act(torch.cat([hidden_states0,hidden_states1],dim=-1)))
241
+ hidden_states = self.merge_layer(torch.cat([hidden_states0,hidden_states1],dim=-1))
242
+ else:
243
+ hidden_states = (hidden_states0+hidden_states1)/2
244
+ else:
245
+ hidden_states = self.dense(hidden_states)
246
+ hidden_states = self.dropout(hidden_states)
247
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
248
+ return hidden_states
249
+
250
+
251
+ class BertAttention(nn.Module):
252
+ def __init__(self, config, is_cross_attention=False, layer_num=-1):
253
+ super().__init__()
254
+ if is_cross_attention:
255
+ self.self0 = BertSelfAttention(config, is_cross_attention)
256
+ self.self1 = BertSelfAttention(config, is_cross_attention)
257
+ else:
258
+ self.self = BertSelfAttention(config, is_cross_attention)
259
+ self.output = BertSelfOutput(config, twin=is_cross_attention, merge=(is_cross_attention and layer_num>=6))
260
+ self.pruned_heads = set()
261
+
262
+ def prune_heads(self, heads):
263
+ if len(heads) == 0:
264
+ return
265
+ heads, index = find_pruneable_heads_and_indices(
266
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
267
+ )
268
+
269
+ # Prune linear layers
270
+ self.self.query = prune_linear_layer(self.self.query, index)
271
+ self.self.key = prune_linear_layer(self.self.key, index)
272
+ self.self.value = prune_linear_layer(self.self.value, index)
273
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
274
+
275
+ # Update hyper params and store pruned heads
276
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
277
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
278
+ self.pruned_heads = self.pruned_heads.union(heads)
279
+
280
+ def forward(
281
+ self,
282
+ hidden_states,
283
+ attention_mask=None,
284
+ head_mask=None,
285
+ encoder_hidden_states=None,
286
+ encoder_attention_mask=None,
287
+ past_key_value=None,
288
+ output_attentions=False,
289
+ ):
290
+ if type(encoder_hidden_states)==list:
291
+ self_outputs0 = self.self0(
292
+ hidden_states,
293
+ attention_mask,
294
+ head_mask,
295
+ encoder_hidden_states[0],
296
+ encoder_attention_mask[0],
297
+ past_key_value,
298
+ output_attentions,
299
+ )
300
+ self_outputs1 = self.self1(
301
+ hidden_states,
302
+ attention_mask,
303
+ head_mask,
304
+ encoder_hidden_states[1],
305
+ encoder_attention_mask[1],
306
+ past_key_value,
307
+ output_attentions,
308
+ )
309
+ attention_output = self.output([self_outputs0[0],self_outputs1[0]], hidden_states)
310
+
311
+ outputs = (attention_output,) + self_outputs0[1:] # add attentions if we output them
312
+ else:
313
+ self_outputs = self.self(
314
+ hidden_states,
315
+ attention_mask,
316
+ head_mask,
317
+ encoder_hidden_states,
318
+ encoder_attention_mask,
319
+ past_key_value,
320
+ output_attentions,
321
+ )
322
+ attention_output = self.output(self_outputs[0], hidden_states)
323
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
324
+ return outputs
325
+
326
+
327
+ class BertIntermediate(nn.Module):
328
+ def __init__(self, config):
329
+ super().__init__()
330
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
331
+ if isinstance(config.hidden_act, str):
332
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
333
+ else:
334
+ self.intermediate_act_fn = config.hidden_act
335
+
336
+ def forward(self, hidden_states):
337
+ hidden_states = self.dense(hidden_states)
338
+ hidden_states = self.intermediate_act_fn(hidden_states)
339
+ return hidden_states
340
+
341
+
342
+ class BertOutput(nn.Module):
343
+ def __init__(self, config):
344
+ super().__init__()
345
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
346
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
347
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
348
+
349
+ def forward(self, hidden_states, input_tensor):
350
+ hidden_states = self.dense(hidden_states)
351
+ hidden_states = self.dropout(hidden_states)
352
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
353
+ return hidden_states
354
+
355
+
356
+ class BertLayer(nn.Module):
357
+ def __init__(self, config, layer_num):
358
+ super().__init__()
359
+ self.config = config
360
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
361
+ self.seq_len_dim = 1
362
+ self.attention = BertAttention(config)
363
+ self.layer_num = layer_num
364
+ if self.config.add_cross_attention:
365
+ self.crossattention = BertAttention(config, is_cross_attention=self.config.add_cross_attention, layer_num=layer_num)
366
+ self.intermediate = BertIntermediate(config)
367
+ self.output = BertOutput(config)
368
+
369
+ def forward(
370
+ self,
371
+ hidden_states,
372
+ attention_mask=None,
373
+ head_mask=None,
374
+ encoder_hidden_states=None,
375
+ encoder_attention_mask=None,
376
+ past_key_value=None,
377
+ output_attentions=False,
378
+ mode=None,
379
+ ):
380
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
381
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
382
+ self_attention_outputs = self.attention(
383
+ hidden_states,
384
+ attention_mask,
385
+ head_mask,
386
+ output_attentions=output_attentions,
387
+ past_key_value=self_attn_past_key_value,
388
+ )
389
+ attention_output = self_attention_outputs[0]
390
+
391
+ outputs = self_attention_outputs[1:-1]
392
+ present_key_value = self_attention_outputs[-1]
393
+
394
+ if mode=='multimodal':
395
+ assert encoder_hidden_states is not None, "encoder_hidden_states must be given for cross-attention layers"
396
+ cross_attention_outputs = self.crossattention(
397
+ attention_output,
398
+ attention_mask,
399
+ head_mask,
400
+ encoder_hidden_states,
401
+ encoder_attention_mask,
402
+ output_attentions=output_attentions,
403
+ )
404
+ attention_output = cross_attention_outputs[0]
405
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
406
+ layer_output = apply_chunking_to_forward(
407
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
408
+ )
409
+ outputs = (layer_output,) + outputs
410
+
411
+ outputs = outputs + (present_key_value,)
412
+
413
+ return outputs
414
+
415
+ def feed_forward_chunk(self, attention_output):
416
+ intermediate_output = self.intermediate(attention_output)
417
+ layer_output = self.output(intermediate_output, attention_output)
418
+ return layer_output
419
+
420
+
421
+ class BertEncoder(nn.Module):
422
+ def __init__(self, config):
423
+ super().__init__()
424
+ self.config = config
425
+ self.layer = nn.ModuleList([BertLayer(config,i) for i in range(config.num_hidden_layers)])
426
+ self.gradient_checkpointing = False
427
+
428
+ def forward(
429
+ self,
430
+ hidden_states,
431
+ attention_mask=None,
432
+ head_mask=None,
433
+ encoder_hidden_states=None,
434
+ encoder_attention_mask=None,
435
+ past_key_values=None,
436
+ use_cache=None,
437
+ output_attentions=False,
438
+ output_hidden_states=False,
439
+ return_dict=True,
440
+ mode='multimodal',
441
+ ):
442
+ all_hidden_states = () if output_hidden_states else None
443
+ all_self_attentions = () if output_attentions else None
444
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
445
+
446
+ next_decoder_cache = () if use_cache else None
447
+
448
+ for i in range(self.config.num_hidden_layers):
449
+ layer_module = self.layer[i]
450
+ if output_hidden_states:
451
+ all_hidden_states = all_hidden_states + (hidden_states,)
452
+
453
+ layer_head_mask = head_mask[i] if head_mask is not None else None
454
+ past_key_value = past_key_values[i] if past_key_values is not None else None
455
+
456
+ if self.gradient_checkpointing and self.training:
457
+
458
+ if use_cache:
459
+ logger.warn(
460
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
461
+ )
462
+ use_cache = False
463
+
464
+ def create_custom_forward(module):
465
+ def custom_forward(*inputs):
466
+ return module(*inputs, past_key_value, output_attentions)
467
+
468
+ return custom_forward
469
+
470
+ layer_outputs = torch.utils.checkpoint.checkpoint(
471
+ create_custom_forward(layer_module),
472
+ hidden_states,
473
+ attention_mask,
474
+ layer_head_mask,
475
+ encoder_hidden_states,
476
+ encoder_attention_mask,
477
+ mode=mode,
478
+ )
479
+ else:
480
+ layer_outputs = layer_module(
481
+ hidden_states,
482
+ attention_mask,
483
+ layer_head_mask,
484
+ encoder_hidden_states,
485
+ encoder_attention_mask,
486
+ past_key_value,
487
+ output_attentions,
488
+ mode=mode,
489
+ )
490
+
491
+ hidden_states = layer_outputs[0]
492
+ if use_cache:
493
+ next_decoder_cache += (layer_outputs[-1],)
494
+ if output_attentions:
495
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
496
+
497
+ if output_hidden_states:
498
+ all_hidden_states = all_hidden_states + (hidden_states,)
499
+
500
+ if not return_dict:
501
+ return tuple(
502
+ v
503
+ for v in [
504
+ hidden_states,
505
+ next_decoder_cache,
506
+ all_hidden_states,
507
+ all_self_attentions,
508
+ all_cross_attentions,
509
+ ]
510
+ if v is not None
511
+ )
512
+ return BaseModelOutputWithPastAndCrossAttentions(
513
+ last_hidden_state=hidden_states,
514
+ past_key_values=next_decoder_cache,
515
+ hidden_states=all_hidden_states,
516
+ attentions=all_self_attentions,
517
+ cross_attentions=all_cross_attentions,
518
+ )
519
+
520
+
521
+ class BertPooler(nn.Module):
522
+ def __init__(self, config):
523
+ super().__init__()
524
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
525
+ self.activation = nn.Tanh()
526
+
527
+ def forward(self, hidden_states):
528
+ # We "pool" the model by simply taking the hidden state corresponding
529
+ # to the first token.
530
+ first_token_tensor = hidden_states[:, 0]
531
+ pooled_output = self.dense(first_token_tensor)
532
+ pooled_output = self.activation(pooled_output)
533
+ return pooled_output
534
+
535
+
536
+ class BertPredictionHeadTransform(nn.Module):
537
+ def __init__(self, config):
538
+ super().__init__()
539
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
540
+ if isinstance(config.hidden_act, str):
541
+ self.transform_act_fn = ACT2FN[config.hidden_act]
542
+ else:
543
+ self.transform_act_fn = config.hidden_act
544
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
545
+
546
+ def forward(self, hidden_states):
547
+ hidden_states = self.dense(hidden_states)
548
+ hidden_states = self.transform_act_fn(hidden_states)
549
+ hidden_states = self.LayerNorm(hidden_states)
550
+ return hidden_states
551
+
552
+
553
+ class BertLMPredictionHead(nn.Module):
554
+ def __init__(self, config):
555
+ super().__init__()
556
+ self.transform = BertPredictionHeadTransform(config)
557
+
558
+ # The output weights are the same as the input embeddings, but there is
559
+ # an output-only bias for each token.
560
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
561
+
562
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
563
+
564
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
565
+ self.decoder.bias = self.bias
566
+
567
+ def forward(self, hidden_states):
568
+ hidden_states = self.transform(hidden_states)
569
+ hidden_states = self.decoder(hidden_states)
570
+ return hidden_states
571
+
572
+
573
+ class BertOnlyMLMHead(nn.Module):
574
+ def __init__(self, config):
575
+ super().__init__()
576
+ self.predictions = BertLMPredictionHead(config)
577
+
578
+ def forward(self, sequence_output):
579
+ prediction_scores = self.predictions(sequence_output)
580
+ return prediction_scores
581
+
582
+
583
+ class BertPreTrainedModel(PreTrainedModel):
584
+ """
585
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
586
+ models.
587
+ """
588
+
589
+ config_class = BertConfig
590
+ base_model_prefix = "bert"
591
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
592
+
593
+ def _init_weights(self, module):
594
+ """ Initialize the weights """
595
+ if isinstance(module, (nn.Linear, nn.Embedding)):
596
+ # Slightly different from the TF version which uses truncated_normal for initialization
597
+ # cf https://github.com/pytorch/pytorch/pull/5617
598
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
599
+ elif isinstance(module, nn.LayerNorm):
600
+ module.bias.data.zero_()
601
+ module.weight.data.fill_(1.0)
602
+ if isinstance(module, nn.Linear) and module.bias is not None:
603
+ module.bias.data.zero_()
604
+
605
+
606
+ class BertModel(BertPreTrainedModel):
607
+ """
608
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
609
+ cross-attention is added between the self-attention layers, following the architecture described in `Attention is
610
+ all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
611
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
612
+ argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
613
+ input to the forward pass.
614
+ """
615
+
616
+ def __init__(self, config, add_pooling_layer=True):
617
+ super().__init__(config)
618
+ self.config = config
619
+
620
+ self.embeddings = BertEmbeddings(config)
621
+
622
+ self.encoder = BertEncoder(config)
623
+
624
+ self.pooler = BertPooler(config) if add_pooling_layer else None
625
+
626
+ self.init_weights()
627
+
628
+
629
+ def get_input_embeddings(self):
630
+ return self.embeddings.word_embeddings
631
+
632
+ def set_input_embeddings(self, value):
633
+ self.embeddings.word_embeddings = value
634
+
635
+ def _prune_heads(self, heads_to_prune):
636
+ """
637
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
638
+ class PreTrainedModel
639
+ """
640
+ for layer, heads in heads_to_prune.items():
641
+ self.encoder.layer[layer].attention.prune_heads(heads)
642
+
643
+
644
+ def get_extended_attention_mask(self, attention_mask: Tensor, input_shape: Tuple[int], device: device, is_decoder: bool) -> Tensor:
645
+ """
646
+ Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
647
+
648
+ Arguments:
649
+ attention_mask (:obj:`torch.Tensor`):
650
+ Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
651
+ input_shape (:obj:`Tuple[int]`):
652
+ The shape of the input to the model.
653
+ device: (:obj:`torch.device`):
654
+ The device of the input to the model.
655
+
656
+ Returns:
657
+ :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`.
658
+ """
659
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
660
+ # ourselves in which case we just need to make it broadcastable to all heads.
661
+ if attention_mask.dim() == 3:
662
+ extended_attention_mask = attention_mask[:, None, :, :]
663
+ elif attention_mask.dim() == 2:
664
+ # Provided a padding mask of dimensions [batch_size, seq_length]
665
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
666
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
667
+ if is_decoder:
668
+ batch_size, seq_length = input_shape
669
+
670
+ seq_ids = torch.arange(seq_length, device=device)
671
+ causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None]
672
+ # in case past_key_values are used we need to add a prefix ones mask to the causal mask
673
+ # causal and attention masks must have same type with pytorch version < 1.3
674
+ causal_mask = causal_mask.to(attention_mask.dtype)
675
+
676
+ if causal_mask.shape[1] < attention_mask.shape[1]:
677
+ prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
678
+ causal_mask = torch.cat(
679
+ [
680
+ torch.ones((batch_size, seq_length, prefix_seq_len), device=device, dtype=causal_mask.dtype),
681
+ causal_mask,
682
+ ],
683
+ axis=-1,
684
+ )
685
+
686
+ extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
687
+ else:
688
+ extended_attention_mask = attention_mask[:, None, None, :]
689
+ else:
690
+ raise ValueError(
691
+ "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
692
+ input_shape, attention_mask.shape
693
+ )
694
+ )
695
+
696
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
697
+ # masked positions, this operation will create a tensor which is 0.0 for
698
+ # positions we want to attend and -10000.0 for masked positions.
699
+ # Since we are adding it to the raw scores before the softmax, this is
700
+ # effectively the same as removing these entirely.
701
+ extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
702
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
703
+ return extended_attention_mask
704
+
705
+ def forward(
706
+ self,
707
+ input_ids=None,
708
+ attention_mask=None,
709
+ position_ids=None,
710
+ head_mask=None,
711
+ inputs_embeds=None,
712
+ encoder_embeds=None,
713
+ encoder_hidden_states=None,
714
+ encoder_attention_mask=None,
715
+ past_key_values=None,
716
+ use_cache=None,
717
+ output_attentions=None,
718
+ output_hidden_states=None,
719
+ return_dict=None,
720
+ is_decoder=False,
721
+ mode='multimodal',
722
+ ):
723
+ r"""
724
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
725
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
726
+ the model is configured as a decoder.
727
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
728
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
729
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
730
+ - 1 for tokens that are **not masked**,
731
+ - 0 for tokens that are **masked**.
732
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
733
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
734
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
735
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
736
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
737
+ use_cache (:obj:`bool`, `optional`):
738
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
739
+ decoding (see :obj:`past_key_values`).
740
+ """
741
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
742
+ output_hidden_states = (
743
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
744
+ )
745
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
746
+
747
+ if is_decoder:
748
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
749
+ else:
750
+ use_cache = False
751
+
752
+ if input_ids is not None and inputs_embeds is not None:
753
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
754
+ elif input_ids is not None:
755
+ input_shape = input_ids.size()
756
+ batch_size, seq_length = input_shape
757
+ device = input_ids.device
758
+ elif inputs_embeds is not None:
759
+ input_shape = inputs_embeds.size()[:-1]
760
+ batch_size, seq_length = input_shape
761
+ device = inputs_embeds.device
762
+ elif encoder_embeds is not None:
763
+ input_shape = encoder_embeds.size()[:-1]
764
+ batch_size, seq_length = input_shape
765
+ device = encoder_embeds.device
766
+ else:
767
+ raise ValueError("You have to specify either input_ids or inputs_embeds or encoder_embeds")
768
+
769
+ # past_key_values_length
770
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
771
+
772
+ if attention_mask is None:
773
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
774
+
775
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
776
+ # ourselves in which case we just need to make it broadcastable to all heads.
777
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape,
778
+ device, is_decoder)
779
+
780
+ # If a 2D or 3D attention mask is provided for the cross-attention
781
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
782
+ if encoder_hidden_states is not None:
783
+ if type(encoder_hidden_states) == list:
784
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size()
785
+ else:
786
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
787
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
788
+
789
+ if type(encoder_attention_mask) == list:
790
+ encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask]
791
+ elif encoder_attention_mask is None:
792
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
793
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
794
+ else:
795
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
796
+ else:
797
+ encoder_extended_attention_mask = None
798
+
799
+ # Prepare head mask if needed
800
+ # 1.0 in head_mask indicate we keep the head
801
+ # attention_probs has shape bsz x n_heads x N x N
802
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
803
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
804
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
805
+
806
+ if encoder_embeds is None:
807
+ embedding_output = self.embeddings(
808
+ input_ids=input_ids,
809
+ position_ids=position_ids,
810
+ inputs_embeds=inputs_embeds,
811
+ past_key_values_length=past_key_values_length,
812
+ )
813
+ else:
814
+ embedding_output = encoder_embeds
815
+
816
+ encoder_outputs = self.encoder(
817
+ embedding_output,
818
+ attention_mask=extended_attention_mask,
819
+ head_mask=head_mask,
820
+ encoder_hidden_states=encoder_hidden_states,
821
+ encoder_attention_mask=encoder_extended_attention_mask,
822
+ past_key_values=past_key_values,
823
+ use_cache=use_cache,
824
+ output_attentions=output_attentions,
825
+ output_hidden_states=output_hidden_states,
826
+ return_dict=return_dict,
827
+ mode=mode,
828
+ )
829
+ sequence_output = encoder_outputs[0]
830
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
831
+
832
+ if not return_dict:
833
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
834
+
835
+ return BaseModelOutputWithPoolingAndCrossAttentions(
836
+ last_hidden_state=sequence_output,
837
+ pooler_output=pooled_output,
838
+ past_key_values=encoder_outputs.past_key_values,
839
+ hidden_states=encoder_outputs.hidden_states,
840
+ attentions=encoder_outputs.attentions,
841
+ cross_attentions=encoder_outputs.cross_attentions,
842
+ )
843
+
extras/BLIP/models/vit.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ * Copyright (c) 2022, salesforce.com, inc.
3
+ * All rights reserved.
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
6
+ * By Junnan Li
7
+ * Based on timm code base
8
+ * https://github.com/rwightman/pytorch-image-models/tree/master/timm
9
+ '''
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+ from functools import partial
15
+
16
+ from timm.models.vision_transformer import _cfg, PatchEmbed
17
+ from timm.models.registry import register_model
18
+ from timm.models.layers import trunc_normal_, DropPath
19
+ from timm.models.helpers import named_apply, adapt_input_conv
20
+
21
+
22
+ def checkpoint_wrapper(x):
23
+ return x
24
+
25
+
26
+ class Mlp(nn.Module):
27
+ """ MLP as used in Vision Transformer, MLP-Mixer and related networks
28
+ """
29
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
30
+ super().__init__()
31
+ out_features = out_features or in_features
32
+ hidden_features = hidden_features or in_features
33
+ self.fc1 = nn.Linear(in_features, hidden_features)
34
+ self.act = act_layer()
35
+ self.fc2 = nn.Linear(hidden_features, out_features)
36
+ self.drop = nn.Dropout(drop)
37
+
38
+ def forward(self, x):
39
+ x = self.fc1(x)
40
+ x = self.act(x)
41
+ x = self.drop(x)
42
+ x = self.fc2(x)
43
+ x = self.drop(x)
44
+ return x
45
+
46
+
47
+ class Attention(nn.Module):
48
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
49
+ super().__init__()
50
+ self.num_heads = num_heads
51
+ head_dim = dim // num_heads
52
+ # NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights
53
+ self.scale = qk_scale or head_dim ** -0.5
54
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
55
+ self.attn_drop = nn.Dropout(attn_drop)
56
+ self.proj = nn.Linear(dim, dim)
57
+ self.proj_drop = nn.Dropout(proj_drop)
58
+ self.attn_gradients = None
59
+ self.attention_map = None
60
+
61
+ def save_attn_gradients(self, attn_gradients):
62
+ self.attn_gradients = attn_gradients
63
+
64
+ def get_attn_gradients(self):
65
+ return self.attn_gradients
66
+
67
+ def save_attention_map(self, attention_map):
68
+ self.attention_map = attention_map
69
+
70
+ def get_attention_map(self):
71
+ return self.attention_map
72
+
73
+ def forward(self, x, register_hook=False):
74
+ B, N, C = x.shape
75
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
76
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
77
+
78
+ attn = (q @ k.transpose(-2, -1)) * self.scale
79
+ attn = attn.softmax(dim=-1)
80
+ attn = self.attn_drop(attn)
81
+
82
+ if register_hook:
83
+ self.save_attention_map(attn)
84
+ attn.register_hook(self.save_attn_gradients)
85
+
86
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
87
+ x = self.proj(x)
88
+ x = self.proj_drop(x)
89
+ return x
90
+
91
+
92
+ class Block(nn.Module):
93
+
94
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
95
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, use_grad_checkpointing=False):
96
+ super().__init__()
97
+ self.norm1 = norm_layer(dim)
98
+ self.attn = Attention(
99
+ dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
100
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
101
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
102
+ self.norm2 = norm_layer(dim)
103
+ mlp_hidden_dim = int(dim * mlp_ratio)
104
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
105
+
106
+ if use_grad_checkpointing:
107
+ self.attn = checkpoint_wrapper(self.attn)
108
+ self.mlp = checkpoint_wrapper(self.mlp)
109
+
110
+ def forward(self, x, register_hook=False):
111
+ x = x + self.drop_path(self.attn(self.norm1(x), register_hook=register_hook))
112
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
113
+ return x
114
+
115
+
116
+ class VisionTransformer(nn.Module):
117
+ """ Vision Transformer
118
+ A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` -
119
+ https://arxiv.org/abs/2010.11929
120
+ """
121
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12,
122
+ num_heads=12, mlp_ratio=4., qkv_bias=True, qk_scale=None, representation_size=None,
123
+ drop_rate=0., attn_drop_rate=0., drop_path_rate=0., norm_layer=None,
124
+ use_grad_checkpointing=False, ckpt_layer=0):
125
+ """
126
+ Args:
127
+ img_size (int, tuple): input image size
128
+ patch_size (int, tuple): patch size
129
+ in_chans (int): number of input channels
130
+ num_classes (int): number of classes for classification head
131
+ embed_dim (int): embedding dimension
132
+ depth (int): depth of transformer
133
+ num_heads (int): number of attention heads
134
+ mlp_ratio (int): ratio of mlp hidden dim to embedding dim
135
+ qkv_bias (bool): enable bias for qkv if True
136
+ qk_scale (float): override default qk scale of head_dim ** -0.5 if set
137
+ representation_size (Optional[int]): enable and set representation layer (pre-logits) to this value if set
138
+ drop_rate (float): dropout rate
139
+ attn_drop_rate (float): attention dropout rate
140
+ drop_path_rate (float): stochastic depth rate
141
+ norm_layer: (nn.Module): normalization layer
142
+ """
143
+ super().__init__()
144
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
145
+ norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6)
146
+
147
+ self.patch_embed = PatchEmbed(
148
+ img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
149
+
150
+ num_patches = self.patch_embed.num_patches
151
+
152
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
153
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
154
+ self.pos_drop = nn.Dropout(p=drop_rate)
155
+
156
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
157
+ self.blocks = nn.ModuleList([
158
+ Block(
159
+ dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
160
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer,
161
+ use_grad_checkpointing=(use_grad_checkpointing and i>=depth-ckpt_layer)
162
+ )
163
+ for i in range(depth)])
164
+ self.norm = norm_layer(embed_dim)
165
+
166
+ trunc_normal_(self.pos_embed, std=.02)
167
+ trunc_normal_(self.cls_token, std=.02)
168
+ self.apply(self._init_weights)
169
+
170
+ def _init_weights(self, m):
171
+ if isinstance(m, nn.Linear):
172
+ trunc_normal_(m.weight, std=.02)
173
+ if isinstance(m, nn.Linear) and m.bias is not None:
174
+ nn.init.constant_(m.bias, 0)
175
+ elif isinstance(m, nn.LayerNorm):
176
+ nn.init.constant_(m.bias, 0)
177
+ nn.init.constant_(m.weight, 1.0)
178
+
179
+ @torch.jit.ignore
180
+ def no_weight_decay(self):
181
+ return {'pos_embed', 'cls_token'}
182
+
183
+ def forward(self, x, register_blk=-1):
184
+ B = x.shape[0]
185
+ x = self.patch_embed(x)
186
+
187
+ cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
188
+ x = torch.cat((cls_tokens, x), dim=1)
189
+
190
+ x = x + self.pos_embed[:,:x.size(1),:]
191
+ x = self.pos_drop(x)
192
+
193
+ for i,blk in enumerate(self.blocks):
194
+ x = blk(x, register_blk==i)
195
+ x = self.norm(x)
196
+
197
+ return x
198
+
199
+ @torch.jit.ignore()
200
+ def load_pretrained(self, checkpoint_path, prefix=''):
201
+ _load_weights(self, checkpoint_path, prefix)
202
+
203
+
204
+ @torch.no_grad()
205
+ def _load_weights(model: VisionTransformer, checkpoint_path: str, prefix: str = ''):
206
+ """ Load weights from .npz checkpoints for official Google Brain Flax implementation
207
+ """
208
+ import numpy as np
209
+
210
+ def _n2p(w, t=True):
211
+ if w.ndim == 4 and w.shape[0] == w.shape[1] == w.shape[2] == 1:
212
+ w = w.flatten()
213
+ if t:
214
+ if w.ndim == 4:
215
+ w = w.transpose([3, 2, 0, 1])
216
+ elif w.ndim == 3:
217
+ w = w.transpose([2, 0, 1])
218
+ elif w.ndim == 2:
219
+ w = w.transpose([1, 0])
220
+ return torch.from_numpy(w)
221
+
222
+ w = np.load(checkpoint_path)
223
+ if not prefix and 'opt/target/embedding/kernel' in w:
224
+ prefix = 'opt/target/'
225
+
226
+ if hasattr(model.patch_embed, 'backbone'):
227
+ # hybrid
228
+ backbone = model.patch_embed.backbone
229
+ stem_only = not hasattr(backbone, 'stem')
230
+ stem = backbone if stem_only else backbone.stem
231
+ stem.conv.weight.copy_(adapt_input_conv(stem.conv.weight.shape[1], _n2p(w[f'{prefix}conv_root/kernel'])))
232
+ stem.norm.weight.copy_(_n2p(w[f'{prefix}gn_root/scale']))
233
+ stem.norm.bias.copy_(_n2p(w[f'{prefix}gn_root/bias']))
234
+ if not stem_only:
235
+ for i, stage in enumerate(backbone.stages):
236
+ for j, block in enumerate(stage.blocks):
237
+ bp = f'{prefix}block{i + 1}/unit{j + 1}/'
238
+ for r in range(3):
239
+ getattr(block, f'conv{r + 1}').weight.copy_(_n2p(w[f'{bp}conv{r + 1}/kernel']))
240
+ getattr(block, f'norm{r + 1}').weight.copy_(_n2p(w[f'{bp}gn{r + 1}/scale']))
241
+ getattr(block, f'norm{r + 1}').bias.copy_(_n2p(w[f'{bp}gn{r + 1}/bias']))
242
+ if block.downsample is not None:
243
+ block.downsample.conv.weight.copy_(_n2p(w[f'{bp}conv_proj/kernel']))
244
+ block.downsample.norm.weight.copy_(_n2p(w[f'{bp}gn_proj/scale']))
245
+ block.downsample.norm.bias.copy_(_n2p(w[f'{bp}gn_proj/bias']))
246
+ embed_conv_w = _n2p(w[f'{prefix}embedding/kernel'])
247
+ else:
248
+ embed_conv_w = adapt_input_conv(
249
+ model.patch_embed.proj.weight.shape[1], _n2p(w[f'{prefix}embedding/kernel']))
250
+ model.patch_embed.proj.weight.copy_(embed_conv_w)
251
+ model.patch_embed.proj.bias.copy_(_n2p(w[f'{prefix}embedding/bias']))
252
+ model.cls_token.copy_(_n2p(w[f'{prefix}cls'], t=False))
253
+ pos_embed_w = _n2p(w[f'{prefix}Transformer/posembed_input/pos_embedding'], t=False)
254
+ if pos_embed_w.shape != model.pos_embed.shape:
255
+ pos_embed_w = resize_pos_embed( # resize pos embedding when different size from pretrained weights
256
+ pos_embed_w, model.pos_embed, getattr(model, 'num_tokens', 1), model.patch_embed.grid_size)
257
+ model.pos_embed.copy_(pos_embed_w)
258
+ model.norm.weight.copy_(_n2p(w[f'{prefix}Transformer/encoder_norm/scale']))
259
+ model.norm.bias.copy_(_n2p(w[f'{prefix}Transformer/encoder_norm/bias']))
260
+ # if isinstance(model.head, nn.Linear) and model.head.bias.shape[0] == w[f'{prefix}head/bias'].shape[-1]:
261
+ # model.head.weight.copy_(_n2p(w[f'{prefix}head/kernel']))
262
+ # model.head.bias.copy_(_n2p(w[f'{prefix}head/bias']))
263
+ # if isinstance(getattr(model.pre_logits, 'fc', None), nn.Linear) and f'{prefix}pre_logits/bias' in w:
264
+ # model.pre_logits.fc.weight.copy_(_n2p(w[f'{prefix}pre_logits/kernel']))
265
+ # model.pre_logits.fc.bias.copy_(_n2p(w[f'{prefix}pre_logits/bias']))
266
+ for i, block in enumerate(model.blocks.children()):
267
+ block_prefix = f'{prefix}Transformer/encoderblock_{i}/'
268
+ mha_prefix = block_prefix + 'MultiHeadDotProductAttention_1/'
269
+ block.norm1.weight.copy_(_n2p(w[f'{block_prefix}LayerNorm_0/scale']))
270
+ block.norm1.bias.copy_(_n2p(w[f'{block_prefix}LayerNorm_0/bias']))
271
+ block.attn.qkv.weight.copy_(torch.cat([
272
+ _n2p(w[f'{mha_prefix}{n}/kernel'], t=False).flatten(1).T for n in ('query', 'key', 'value')]))
273
+ block.attn.qkv.bias.copy_(torch.cat([
274
+ _n2p(w[f'{mha_prefix}{n}/bias'], t=False).reshape(-1) for n in ('query', 'key', 'value')]))
275
+ block.attn.proj.weight.copy_(_n2p(w[f'{mha_prefix}out/kernel']).flatten(1))
276
+ block.attn.proj.bias.copy_(_n2p(w[f'{mha_prefix}out/bias']))
277
+ for r in range(2):
278
+ getattr(block.mlp, f'fc{r + 1}').weight.copy_(_n2p(w[f'{block_prefix}MlpBlock_3/Dense_{r}/kernel']))
279
+ getattr(block.mlp, f'fc{r + 1}').bias.copy_(_n2p(w[f'{block_prefix}MlpBlock_3/Dense_{r}/bias']))
280
+ block.norm2.weight.copy_(_n2p(w[f'{block_prefix}LayerNorm_2/scale']))
281
+ block.norm2.bias.copy_(_n2p(w[f'{block_prefix}LayerNorm_2/bias']))
282
+
283
+
284
+ def interpolate_pos_embed(pos_embed_checkpoint, visual_encoder):
285
+ # interpolate position embedding
286
+ embedding_size = pos_embed_checkpoint.shape[-1]
287
+ num_patches = visual_encoder.patch_embed.num_patches
288
+ num_extra_tokens = visual_encoder.pos_embed.shape[-2] - num_patches
289
+ # height (== width) for the checkpoint position embedding
290
+ orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)
291
+ # height (== width) for the new position embedding
292
+ new_size = int(num_patches ** 0.5)
293
+
294
+ if orig_size!=new_size:
295
+ # class_token and dist_token are kept unchanged
296
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
297
+ # only the position tokens are interpolated
298
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
299
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
300
+ pos_tokens = torch.nn.functional.interpolate(
301
+ pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)
302
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
303
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
304
+ print('reshape position embedding from %d to %d'%(orig_size ** 2,new_size ** 2))
305
+
306
+ return new_pos_embed
307
+ else:
308
+ return pos_embed_checkpoint
extras/__pycache__/expansion.cpython-310.pyc ADDED
Binary file (3.77 kB). View file
 
extras/__pycache__/face_crop.cpython-310.pyc ADDED
Binary file (1.49 kB). View file
 
extras/__pycache__/interrogate.cpython-310.pyc ADDED
Binary file (2.47 kB). View file
 
extras/__pycache__/ip_adapter.cpython-310.pyc ADDED
Binary file (8.67 kB). View file
 
extras/__pycache__/preprocessors.cpython-310.pyc ADDED
Binary file (2.66 kB). View file
 
extras/__pycache__/resampler.cpython-310.pyc ADDED
Binary file (3.28 kB). View file