Spaces:
Runtime error
Runtime error
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .dockerignore +1 -0
- .gitattributes +1 -0
- .github/CODEOWNERS +1 -0
- .github/FUNDING.yml +14 -0
- .github/ISSUE_TEMPLATE/bug_report.yaml +77 -0
- .github/ISSUE_TEMPLATE/feature_request.yaml +34 -0
- .gitignore +54 -0
- DeFooocus_colab.ipynb +56 -0
- Dockerfile +29 -0
- LICENSE +674 -0
- README.md +2 -8
- args_manager.py +58 -0
- assets/favicon.png +3 -0
- assets/old_preview.png +0 -0
- assets/online_comfyui.png +0 -0
- assets/online_demos.png +0 -0
- assets/online_tools.png +0 -0
- assets/photopea.png +0 -0
- assets/preview.png +0 -0
- assets/rembg.png +0 -0
- auth-example.json +6 -0
- build_launcher.py +26 -0
- css/style.css +231 -0
- docker-compose.yml +38 -0
- docker.md +66 -0
- entry_with_update.py +46 -0
- entrypoint.sh +33 -0
- environment.yaml +7 -0
- experiments_expansion.py +8 -0
- experiments_face.py +7 -0
- experiments_interrogate.py +8 -0
- extras/BLIP/configs/bert_config.json +21 -0
- extras/BLIP/configs/caption_coco.yaml +33 -0
- extras/BLIP/configs/med_config.json +21 -0
- extras/BLIP/configs/nlvr.yaml +21 -0
- extras/BLIP/configs/nocaps.yaml +15 -0
- extras/BLIP/configs/pretrain.yaml +27 -0
- extras/BLIP/configs/retrieval_coco.yaml +34 -0
- extras/BLIP/configs/retrieval_flickr.yaml +34 -0
- extras/BLIP/configs/retrieval_msrvtt.yaml +12 -0
- extras/BLIP/configs/vqa.yaml +25 -0
- extras/BLIP/models/bert_tokenizer/config.json +23 -0
- extras/BLIP/models/bert_tokenizer/tokenizer.json +0 -0
- extras/BLIP/models/bert_tokenizer/tokenizer_config.json +3 -0
- extras/BLIP/models/bert_tokenizer/vocab.txt +0 -0
- extras/BLIP/models/blip.py +239 -0
- extras/BLIP/models/blip_itm.py +76 -0
- extras/BLIP/models/blip_nlvr.py +105 -0
- extras/BLIP/models/blip_pretrain.py +339 -0
- extras/BLIP/models/blip_retrieval.py +319 -0
.dockerignore
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
.idea
|
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
assets/favicon.png filter=lfs diff=lfs merge=lfs -text
|
.github/CODEOWNERS
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
* @ehristoforu
|
.github/FUNDING.yml
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# These are supported funding model platforms
|
2 |
+
|
3 |
+
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
4 |
+
patreon: # Replace with a single Patreon username
|
5 |
+
open_collective: # Replace with a single Open Collective username
|
6 |
+
ko_fi: # Replace with a single Ko-fi username
|
7 |
+
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
8 |
+
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
9 |
+
liberapay: # Replace with a single Liberapay username
|
10 |
+
issuehunt: # Replace with a single IssueHunt username
|
11 |
+
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
12 |
+
polar: # Replace with a single Polar username
|
13 |
+
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
|
14 |
+
custom: ['https://www.donationalerts.com/r/ehristoforu', 'https://www.donationalerts.com/c/ehristoforu'] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
.github/ISSUE_TEMPLATE/bug_report.yaml
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Bug Report
|
2 |
+
description: Describe a problem
|
3 |
+
title: "[Bug]: "
|
4 |
+
labels: ["bug", "triage"]
|
5 |
+
body:
|
6 |
+
- type: markdown
|
7 |
+
attributes:
|
8 |
+
value: |
|
9 |
+
Thank you for taking the time to fill out this bug report form!
|
10 |
+
- type: checkboxes
|
11 |
+
id: prerequisites
|
12 |
+
attributes:
|
13 |
+
label: Prerequisites
|
14 |
+
description: Please make sure to troubleshoot yourself before continuing.
|
15 |
+
options:
|
16 |
+
- label: I have read the [Troubleshooting Guide](https://github.com/ehristoforu/DeFooocus/blob/main/troubleshoot.md)
|
17 |
+
required: true
|
18 |
+
- label: I have checked that this is not a duplicate of an already existing [issue](https://github.com/ehristoforu/DeFooocus/issues)
|
19 |
+
required: true
|
20 |
+
- type: textarea
|
21 |
+
id: description
|
22 |
+
attributes:
|
23 |
+
label: Describe the problem
|
24 |
+
description: Also tell us, what did you expect to happen?
|
25 |
+
placeholder: "A clear and concise description of what the bug is."
|
26 |
+
validations:
|
27 |
+
required: true
|
28 |
+
- type: textarea
|
29 |
+
id: logs
|
30 |
+
attributes:
|
31 |
+
label: Full console log output
|
32 |
+
description: Please copy and paste the **full** console log here. You will make our job easier if you give a **full** log. This will be automatically formatted into code, so no need for backticks.
|
33 |
+
render: shell
|
34 |
+
validations:
|
35 |
+
required: true
|
36 |
+
- type: textarea
|
37 |
+
id: version
|
38 |
+
attributes:
|
39 |
+
label: Version
|
40 |
+
description: What version of Fooocus are you using? (see browser tab title or console log)
|
41 |
+
placeholder: "Example: Fooocus 2.1.855"
|
42 |
+
validations:
|
43 |
+
required: true
|
44 |
+
- type: dropdown
|
45 |
+
id: hosting
|
46 |
+
attributes:
|
47 |
+
label: Where are you running Fooocus?
|
48 |
+
multiple: false
|
49 |
+
options:
|
50 |
+
- Locally
|
51 |
+
- Locally with virtualisation (e.g. Docker)
|
52 |
+
- Cloud (Gradio)
|
53 |
+
- Cloud (other)
|
54 |
+
validations:
|
55 |
+
required: true
|
56 |
+
- type: input
|
57 |
+
id: operating-system
|
58 |
+
attributes:
|
59 |
+
label: Operating System
|
60 |
+
description: What operating system are you using?
|
61 |
+
placeholder: "Example: Windows 10"
|
62 |
+
- type: dropdown
|
63 |
+
id: browsers
|
64 |
+
attributes:
|
65 |
+
label: What browsers are you seeing the problem on?
|
66 |
+
multiple: true
|
67 |
+
options:
|
68 |
+
- Chrome
|
69 |
+
- Firefox
|
70 |
+
- Microsoft Edge
|
71 |
+
- Safari
|
72 |
+
- other
|
73 |
+
validations:
|
74 |
+
required: true
|
75 |
+
- type: markdown
|
76 |
+
attributes:
|
77 |
+
value: "Thank you for completing our form!"
|
.github/ISSUE_TEMPLATE/feature_request.yaml
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Feature request
|
2 |
+
description: Suggest an idea for this project
|
3 |
+
title: "[Feature]: "
|
4 |
+
labels: ["enhancement"]
|
5 |
+
body:
|
6 |
+
- type: markdown
|
7 |
+
attributes:
|
8 |
+
value: |
|
9 |
+
Thank you for taking the time to fill out this feature request form!
|
10 |
+
- type: checkboxes
|
11 |
+
id: prerequisites
|
12 |
+
attributes:
|
13 |
+
label: Prerequisites
|
14 |
+
options:
|
15 |
+
- label: I have checked that this is not a duplicate of an already existing [feature request](https://github.com/ehristoforu/DeFooocus/issues)
|
16 |
+
required: true
|
17 |
+
- type: textarea
|
18 |
+
id: relation-to-problem
|
19 |
+
attributes:
|
20 |
+
label: Is your feature request related to a problem? Please describe.
|
21 |
+
placeholder: "A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
22 |
+
."
|
23 |
+
validations:
|
24 |
+
required: true
|
25 |
+
- type: textarea
|
26 |
+
id: description
|
27 |
+
attributes:
|
28 |
+
label: Describe the idea you'd like
|
29 |
+
placeholder: "A clear and concise description of what you want to happen."
|
30 |
+
validations:
|
31 |
+
required: true
|
32 |
+
- type: markdown
|
33 |
+
attributes:
|
34 |
+
value: "Thank you for completing our form!"
|
.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 |
+
/models/safety_checker_models
|
22 |
+
/modules/*.png
|
23 |
+
/repositories
|
24 |
+
/fooocus_env
|
25 |
+
/venv
|
26 |
+
/tmp
|
27 |
+
/ui-config.json
|
28 |
+
/outputs
|
29 |
+
/config.json
|
30 |
+
/log
|
31 |
+
/webui.settings.bat
|
32 |
+
/embeddings
|
33 |
+
/styles.csv
|
34 |
+
/params.txt
|
35 |
+
/styles.csv.bak
|
36 |
+
/webui-user.bat
|
37 |
+
/webui-user.sh
|
38 |
+
/interrogate
|
39 |
+
/user.css
|
40 |
+
/.idea
|
41 |
+
/notification.ogg
|
42 |
+
/notification.mp3
|
43 |
+
/SwinIR
|
44 |
+
/textual_inversion
|
45 |
+
.vscode
|
46 |
+
/extensions
|
47 |
+
/test/stdout.txt
|
48 |
+
/test/stderr.txt
|
49 |
+
/cache.json*
|
50 |
+
/config_states/
|
51 |
+
/node_modules
|
52 |
+
/package-lock.json
|
53 |
+
/.coverage*
|
54 |
+
/auth.json
|
DeFooocus_colab.ipynb
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": null,
|
6 |
+
"metadata": {
|
7 |
+
"cellView": "form",
|
8 |
+
"id": "VjYy0F2gZIPR"
|
9 |
+
},
|
10 |
+
"outputs": [],
|
11 |
+
"source": [
|
12 |
+
"#@title DeFooocus\n",
|
13 |
+
"#@markdown **Launch the interface DeFocus (Fooocus fork)** | You need to connect with T4/A100/V100\n",
|
14 |
+
"#@markdown ****\n",
|
15 |
+
"#@markdown *Attention!* When working in the interface with the FaceSwap and CPDS controlnet, crashes are possible; it is also recommended to work in *Extreme speed* mode for additional stability. When working with the ImagePrompt and PyraCanny controls, 85% of the work will be stable.\n",
|
16 |
+
"#@markdown ****\n",
|
17 |
+
"\n",
|
18 |
+
"print(\"[DeFooocus] Preparing ...\")\n",
|
19 |
+
"\n",
|
20 |
+
"theme = \"dark\" #@param [\"dark\", \"light\"]\n",
|
21 |
+
"preset = \"deafult\" #@param [\"deafult\", \"realistic\", \"anime\", \"lcm\", \"sai\", \"turbo\", \"lighting\", \"hypersd\", \"playground_v2.5\", \"dpo\", \"spo\", \"sd1.5\"]\n",
|
22 |
+
"advenced_args = \"--share --attention-split --always-high-vram --disable-offload-from-vram --all-in-fp16\" #@param {type: \"string\"}\n",
|
23 |
+
"\n",
|
24 |
+
"if preset != \"deafult\":\n",
|
25 |
+
" args = f\"{advenced_args} --theme {theme} --preset {preset}\"\n",
|
26 |
+
"else:\n",
|
27 |
+
" args = f\"{advenced_args} --theme {theme}\"\n",
|
28 |
+
"\n",
|
29 |
+
"!pip install -q pygit2==1.12.2\n",
|
30 |
+
"%cd /content\n",
|
31 |
+
"!git clone https://github.com/ehristoforu/DeFooocus.git\n",
|
32 |
+
"%cd /content/DeFooocus\n",
|
33 |
+
"!pip install -q -r requirements_versions.txt\n",
|
34 |
+
"\n",
|
35 |
+
"print(\"[DeFooocus] Starting ...\")\n",
|
36 |
+
"!python entry_with_update.py $args"
|
37 |
+
]
|
38 |
+
}
|
39 |
+
],
|
40 |
+
"metadata": {
|
41 |
+
"accelerator": "GPU",
|
42 |
+
"colab": {
|
43 |
+
"gpuType": "T4",
|
44 |
+
"provenance": []
|
45 |
+
},
|
46 |
+
"kernelspec": {
|
47 |
+
"display_name": "Python 3",
|
48 |
+
"name": "python3"
|
49 |
+
},
|
50 |
+
"language_info": {
|
51 |
+
"name": "python"
|
52 |
+
}
|
53 |
+
},
|
54 |
+
"nbformat": 4,
|
55 |
+
"nbformat_minor": 0
|
56 |
+
}
|
Dockerfile
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM nvidia/cuda:12.3.1-base-ubuntu22.04
|
2 |
+
ENV DEBIAN_FRONTEND noninteractive
|
3 |
+
ENV CMDARGS --listen
|
4 |
+
|
5 |
+
RUN apt-get update -y && \
|
6 |
+
apt-get install -y curl libgl1 libglib2.0-0 python3-pip python-is-python3 git && \
|
7 |
+
apt-get clean && \
|
8 |
+
rm -rf /var/lib/apt/lists/*
|
9 |
+
|
10 |
+
COPY requirements_docker.txt requirements_versions.txt /tmp/
|
11 |
+
RUN pip install --no-cache-dir -r /tmp/requirements_docker.txt -r /tmp/requirements_versions.txt && \
|
12 |
+
rm -f /tmp/requirements_docker.txt /tmp/requirements_versions.txt
|
13 |
+
RUN pip install --no-cache-dir xformers==0.0.22 --no-dependencies
|
14 |
+
RUN curl -fsL -o /usr/local/lib/python3.10/dist-packages/gradio/frpc_linux_amd64_v0.2 https://cdn-media.huggingface.co/frpc-gradio-0.2/frpc_linux_amd64 && \
|
15 |
+
chmod +x /usr/local/lib/python3.10/dist-packages/gradio/frpc_linux_amd64_v0.2
|
16 |
+
|
17 |
+
RUN adduser --disabled-password --gecos '' user && \
|
18 |
+
mkdir -p /content/app /content/data
|
19 |
+
|
20 |
+
COPY entrypoint.sh /content/
|
21 |
+
RUN chown -R user:user /content
|
22 |
+
|
23 |
+
WORKDIR /content
|
24 |
+
USER user
|
25 |
+
|
26 |
+
RUN git clone https://github.com/ehristoforu/DeFooocus /content/app
|
27 |
+
RUN mv /content/app/models /content/app/models.org
|
28 |
+
|
29 |
+
CMD [ "sh", "-c", "/content/entrypoint.sh ${CMDARGS}" ]
|
LICENSE
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
635 |
+
Copyright (C) <year> <name of author>
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) <year> <name of author>
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<https://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
README.md
CHANGED
@@ -1,12 +1,6 @@
|
|
1 |
---
|
2 |
title: DeFooocus
|
3 |
-
|
4 |
-
colorFrom: green
|
5 |
-
colorTo: yellow
|
6 |
sdk: gradio
|
7 |
-
sdk_version:
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
---
|
11 |
-
|
12 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
1 |
---
|
2 |
title: DeFooocus
|
3 |
+
app_file: webui.py
|
|
|
|
|
4 |
sdk: gradio
|
5 |
+
sdk_version: 3.41.2
|
|
|
|
|
6 |
---
|
|
|
|
args_manager.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
8 |
+
args_parser.parser.add_argument("--preset", type=str, default=None, help="Apply specified UI preset.")
|
9 |
+
args_parser.parser.add_argument("--disable-preset-selection", action='store_true',
|
10 |
+
help="Disables preset selection in Gradio.")
|
11 |
+
|
12 |
+
args_parser.parser.add_argument("--language", type=str, default='default',
|
13 |
+
help="Translate UI using json files in [language] folder. "
|
14 |
+
"For example, [--language example] will use [language/example.json] for translation.")
|
15 |
+
|
16 |
+
# For example, https://github.com/lllyasviel/Fooocus/issues/849
|
17 |
+
args_parser.parser.add_argument("--disable-offload-from-vram", action="store_true",
|
18 |
+
help="Force loading models to vram when the unload can be avoided. "
|
19 |
+
"Some Mac users may need this.")
|
20 |
+
|
21 |
+
args_parser.parser.add_argument("--theme", type=str, help="launches the UI with light or dark theme", default=None)
|
22 |
+
args_parser.parser.add_argument("--disable-image-log", action='store_true',
|
23 |
+
help="Prevent writing images and logs to hard drive.")
|
24 |
+
|
25 |
+
args_parser.parser.add_argument("--disable-analytics", action='store_true',
|
26 |
+
help="Disables analytics for Gradio.")
|
27 |
+
|
28 |
+
args_parser.parser.add_argument("--disable-metadata", action='store_true',
|
29 |
+
help="Disables saving metadata to images.")
|
30 |
+
|
31 |
+
args_parser.parser.add_argument("--disable-preset-download", action='store_true',
|
32 |
+
help="Disables downloading models for presets", default=False)
|
33 |
+
|
34 |
+
args_parser.parser.add_argument("--always-download-new-model", action='store_true',
|
35 |
+
help="Always download newer models ", default=False)
|
36 |
+
|
37 |
+
args_parser.parser.set_defaults(
|
38 |
+
disable_cuda_malloc=True,
|
39 |
+
in_browser=True,
|
40 |
+
port=None
|
41 |
+
)
|
42 |
+
|
43 |
+
args_parser.args = args_parser.parser.parse_args()
|
44 |
+
|
45 |
+
# (Disable by default because of issues like https://github.com/lllyasviel/Fooocus/issues/724)
|
46 |
+
args_parser.args.always_offload_from_vram = not args_parser.args.disable_offload_from_vram
|
47 |
+
|
48 |
+
if args_parser.args.disable_analytics:
|
49 |
+
import os
|
50 |
+
os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
|
51 |
+
|
52 |
+
if args_parser.args.disable_in_browser:
|
53 |
+
args_parser.args.in_browser = False
|
54 |
+
|
55 |
+
if args_parser.args.temp_path is None:
|
56 |
+
args_parser.args.temp_path = os.path.join(gettempdir(), 'Fooocus')
|
57 |
+
|
58 |
+
args = args_parser.args
|
assets/favicon.png
ADDED
![]() |
Git LFS Details
|
assets/old_preview.png
ADDED
![]() |
assets/online_comfyui.png
ADDED
![]() |
assets/online_demos.png
ADDED
![]() |
assets/online_tools.png
ADDED
![]() |
assets/photopea.png
ADDED
![]() |
assets/preview.png
ADDED
![]() |
assets/rembg.png
ADDED
![]() |
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 |
+
]
|
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 DeFooocus\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
|
css/style.css
ADDED
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
z-index: 100;
|
44 |
+
}
|
45 |
+
|
46 |
+
.canvas-tooltip-info::after {
|
47 |
+
content: '';
|
48 |
+
display: block;
|
49 |
+
width: 2px;
|
50 |
+
height: 7px;
|
51 |
+
background-color: white;
|
52 |
+
margin-top: 2px;
|
53 |
+
}
|
54 |
+
|
55 |
+
.canvas-tooltip-info::before {
|
56 |
+
content: '';
|
57 |
+
display: block;
|
58 |
+
width: 2px;
|
59 |
+
height: 2px;
|
60 |
+
background-color: white;
|
61 |
+
}
|
62 |
+
|
63 |
+
.canvas-tooltip-content {
|
64 |
+
display: none;
|
65 |
+
background-color: #f9f9f9;
|
66 |
+
color: #333;
|
67 |
+
border: 1px solid #ddd;
|
68 |
+
padding: 15px;
|
69 |
+
position: absolute;
|
70 |
+
top: 40px;
|
71 |
+
left: 10px;
|
72 |
+
width: 250px;
|
73 |
+
font-size: 16px;
|
74 |
+
opacity: 0;
|
75 |
+
border-radius: 8px;
|
76 |
+
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
|
77 |
+
z-index: 100;
|
78 |
+
}
|
79 |
+
|
80 |
+
.canvas-tooltip:hover .canvas-tooltip-content {
|
81 |
+
display: block;
|
82 |
+
animation: fadeIn 0.5s;
|
83 |
+
opacity: 1;
|
84 |
+
}
|
85 |
+
|
86 |
+
@keyframes fadeIn {
|
87 |
+
from {
|
88 |
+
opacity: 0;
|
89 |
+
}
|
90 |
+
to {
|
91 |
+
opacity: 1;
|
92 |
+
}
|
93 |
+
}
|
94 |
+
|
95 |
+
.styler {
|
96 |
+
overflow: inherit !important;
|
97 |
+
}
|
98 |
+
|
99 |
+
.gradio-container {
|
100 |
+
overflow: visible;
|
101 |
+
}
|
102 |
+
|
103 |
+
|
104 |
+
/* fullpage image viewer */
|
105 |
+
|
106 |
+
#lightboxModal {
|
107 |
+
display: none;
|
108 |
+
position: fixed;
|
109 |
+
z-index: 1001;
|
110 |
+
left: 0;
|
111 |
+
top: 0;
|
112 |
+
width: 100%;
|
113 |
+
height: 100%;
|
114 |
+
overflow: auto;
|
115 |
+
background-color: rgba(20, 20, 20, 0.95);
|
116 |
+
user-select: none;
|
117 |
+
-webkit-user-select: none;
|
118 |
+
flex-direction: column;
|
119 |
+
}
|
120 |
+
|
121 |
+
.modalControls {
|
122 |
+
display: flex;
|
123 |
+
position: absolute;
|
124 |
+
right: 0px;
|
125 |
+
left: 0px;
|
126 |
+
gap: 1em;
|
127 |
+
padding: 1em;
|
128 |
+
background-color: rgba(0, 0, 0, 0);
|
129 |
+
z-index: 1;
|
130 |
+
transition: 0.2s ease background-color;
|
131 |
+
}
|
132 |
+
|
133 |
+
.modalControls:hover {
|
134 |
+
background-color: rgba(0, 0, 0, 0.9);
|
135 |
+
}
|
136 |
+
|
137 |
+
.modalClose {
|
138 |
+
margin-left: auto;
|
139 |
+
}
|
140 |
+
|
141 |
+
.modalControls span {
|
142 |
+
color: white;
|
143 |
+
text-shadow: 0px 0px 0.25em black;
|
144 |
+
font-size: 35px;
|
145 |
+
font-weight: bold;
|
146 |
+
cursor: pointer;
|
147 |
+
width: 1em;
|
148 |
+
}
|
149 |
+
|
150 |
+
.modalControls span:hover,
|
151 |
+
.modalControls span:focus {
|
152 |
+
color: #999;
|
153 |
+
text-decoration: none;
|
154 |
+
}
|
155 |
+
|
156 |
+
#lightboxModal>img {
|
157 |
+
display: block;
|
158 |
+
margin: auto;
|
159 |
+
width: auto;
|
160 |
+
}
|
161 |
+
|
162 |
+
#lightboxModal>img.modalImageFullscreen {
|
163 |
+
object-fit: contain;
|
164 |
+
height: 100%;
|
165 |
+
width: 100%;
|
166 |
+
min-height: 0;
|
167 |
+
}
|
168 |
+
|
169 |
+
.modalPrev,
|
170 |
+
.modalNext {
|
171 |
+
cursor: pointer;
|
172 |
+
position: absolute;
|
173 |
+
top: 50%;
|
174 |
+
width: auto;
|
175 |
+
padding: 16px;
|
176 |
+
margin-top: -50px;
|
177 |
+
color: white;
|
178 |
+
font-weight: bold;
|
179 |
+
font-size: 20px;
|
180 |
+
transition: 0.6s ease;
|
181 |
+
border-radius: 0 3px 3px 0;
|
182 |
+
user-select: none;
|
183 |
+
-webkit-user-select: none;
|
184 |
+
}
|
185 |
+
|
186 |
+
.modalNext {
|
187 |
+
right: 0;
|
188 |
+
border-radius: 3px 0 0 3px;
|
189 |
+
}
|
190 |
+
|
191 |
+
.modalPrev:hover,
|
192 |
+
.modalNext:hover {
|
193 |
+
background-color: rgba(0, 0, 0, 0.8);
|
194 |
+
}
|
195 |
+
|
196 |
+
#imageARPreview {
|
197 |
+
position: absolute;
|
198 |
+
top: 0px;
|
199 |
+
left: 0px;
|
200 |
+
border: 2px solid red;
|
201 |
+
background: rgba(255, 0, 0, 0.3);
|
202 |
+
z-index: 900;
|
203 |
+
pointer-events: none;
|
204 |
+
display: none;
|
205 |
+
}
|
206 |
+
|
207 |
+
#stylePreviewOverlay {
|
208 |
+
opacity: 0;
|
209 |
+
pointer-events: none;
|
210 |
+
width: 128px;
|
211 |
+
height: 128px;
|
212 |
+
position: fixed;
|
213 |
+
top: 0px;
|
214 |
+
left: 0px;
|
215 |
+
border: solid 1px lightgrey;
|
216 |
+
transform: translate(-140px, 20px);
|
217 |
+
background-size: cover;
|
218 |
+
background-position: center;
|
219 |
+
background-color: rgba(0, 0, 0, 0.3);
|
220 |
+
border-radius: 5px;
|
221 |
+
z-index: 100;
|
222 |
+
transition: transform 0.1s ease, opacity 0.3s ease;
|
223 |
+
}
|
224 |
+
|
225 |
+
#stylePreviewOverlay.lower-half {
|
226 |
+
transform: translate(-140px, -140px);
|
227 |
+
}
|
228 |
+
|
229 |
+
footer {
|
230 |
+
visibility: hidden
|
231 |
+
}
|
docker-compose.yml
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
version: '3.9'
|
2 |
+
|
3 |
+
volumes:
|
4 |
+
fooocus-data:
|
5 |
+
|
6 |
+
services:
|
7 |
+
app:
|
8 |
+
build: .
|
9 |
+
image: fooocus
|
10 |
+
ports:
|
11 |
+
- "7865:7865"
|
12 |
+
environment:
|
13 |
+
- CMDARGS=--listen # Arguments for launch.py.
|
14 |
+
- DATADIR=/content/data # Directory which stores models, outputs dir
|
15 |
+
- config_path=/content/data/config.txt
|
16 |
+
- config_example_path=/content/data/config_modification_tutorial.txt
|
17 |
+
- path_checkpoints=/content/data/models/checkpoints/
|
18 |
+
- path_loras=/content/data/models/loras/
|
19 |
+
- path_embeddings=/content/data/models/embeddings/
|
20 |
+
- path_vae_approx=/content/data/models/vae_approx/
|
21 |
+
- path_upscale_models=/content/data/models/upscale_models/
|
22 |
+
- path_inpaint=/content/data/models/inpaint/
|
23 |
+
- path_controlnet=/content/data/models/controlnet/
|
24 |
+
- path_clip_vision=/content/data/models/clip_vision/
|
25 |
+
- path_fooocus_expansion=/content/data/models/prompt_expansion/fooocus_expansion/
|
26 |
+
- path_outputs=/content/app/outputs/ # Warning: If it is not located under '/content/app', you can't see history log!
|
27 |
+
volumes:
|
28 |
+
- fooocus-data:/content/data
|
29 |
+
#- ./models:/import/models # Once you import files, you don't need to mount again.
|
30 |
+
#- ./outputs:/import/outputs # Once you import files, you don't need to mount again.
|
31 |
+
tty: true
|
32 |
+
deploy:
|
33 |
+
resources:
|
34 |
+
reservations:
|
35 |
+
devices:
|
36 |
+
- driver: nvidia
|
37 |
+
device_ids: ['0']
|
38 |
+
capabilities: [compute, utility]
|
docker.md
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# DeFooocus on Docker
|
2 |
+
|
3 |
+
The docker image is based on NVIDIA CUDA 12.3 and PyTorch 2.0, see [Dockerfile](Dockerfile) and [requirements_docker.txt](requirements_docker.txt) for details.
|
4 |
+
|
5 |
+
## Quick start
|
6 |
+
|
7 |
+
**This is just an easy way for testing. Please find more information in the [notes](#notes).**
|
8 |
+
|
9 |
+
1. Clone this repository
|
10 |
+
2. Build the image with `docker compose build`
|
11 |
+
3. Run the docker container with `docker compose up`. Building the image takes some time.
|
12 |
+
|
13 |
+
When you see the message `Use the app with http://0.0.0.0:7865/` in the console, you can access the URL in your browser.
|
14 |
+
|
15 |
+
Your models and outputs are stored in the `fooocus-data` volume, which, depending on OS, is stored in `/var/lib/docker/volumes`.
|
16 |
+
|
17 |
+
## Details
|
18 |
+
|
19 |
+
### Update the container manually
|
20 |
+
|
21 |
+
When you are using `docker compose up` continuously, the container is not updated to the latest version of Fooocus automatically.
|
22 |
+
Run `git pull` before executing `docker compose build --no-cache` to build an image with the latest Fooocus version.
|
23 |
+
You can then start it with `docker compose up`
|
24 |
+
|
25 |
+
### Import models, outputs
|
26 |
+
If you want to import files from models or the outputs folder, you can uncomment the following settings in the [docker-compose.yml](docker-compose.yml):
|
27 |
+
```
|
28 |
+
#- ./models:/import/models # Once you import files, you don't need to mount again.
|
29 |
+
#- ./outputs:/import/outputs # Once you import files, you don't need to mount again.
|
30 |
+
```
|
31 |
+
After running `docker compose up`, your files will be copied into `/content/data/models` and `/content/data/outputs`
|
32 |
+
Since `/content/data` is a persistent volume folder, your files will be persisted even when you re-run `docker compose up --build` without above volume settings.
|
33 |
+
|
34 |
+
|
35 |
+
### Paths inside the container
|
36 |
+
|
37 |
+
|Path|Details|
|
38 |
+
|-|-|
|
39 |
+
|/content/app|The application stored folder|
|
40 |
+
|/content/app/models.org|Original 'models' folder.<br> Files are copied to the '/content/app/models' which is symlinked to '/content/data/models' every time the container boots. (Existing files will not be overwritten.) |
|
41 |
+
|/content/data|Persistent volume mount point|
|
42 |
+
|/content/data/models|The folder is symlinked to '/content/app/models'|
|
43 |
+
|/content/data/outputs|The folder is symlinked to '/content/app/outputs'|
|
44 |
+
|
45 |
+
### Environments
|
46 |
+
|
47 |
+
You can change `config.txt` parameters by using environment variables.
|
48 |
+
**The priority of using the environments is higher than the values defined in `config.txt`, and they will be saved to the `config_modification_tutorial.txt`**
|
49 |
+
|
50 |
+
Docker specified environments are there. They are used by 'entrypoint.sh'
|
51 |
+
|Environment|Details|
|
52 |
+
|-|-|
|
53 |
+
|DATADIR|'/content/data' location.|
|
54 |
+
|CMDARGS|Arguments for [entry_with_update.py](entry_with_update.py) which is called by [entrypoint.sh](entrypoint.sh)|
|
55 |
+
|config_path|'config.txt' location|
|
56 |
+
|config_example_path|'config_modification_tutorial.txt' location|
|
57 |
+
|
58 |
+
You can also use the same json key names and values explained in the 'config_modification_tutorial.txt' as the environments.
|
59 |
+
See examples in the [docker-compose.yml](docker-compose.yml)
|
60 |
+
|
61 |
+
## Notes
|
62 |
+
|
63 |
+
- Please keep 'path_outputs' under '/content/app'. Otherwise, you may get an error when you open the history log.
|
64 |
+
- Docker on Mac/Windows still has issues in the form of slow volume access when you use "bind mount" volumes. Please refer to [this article](https://docs.docker.com/storage/volumes/#use-a-volume-with-docker-compose) for not using "bind mount".
|
65 |
+
- The MPS backend (Metal Performance Shaders, Apple Silicon M1/M2/etc.) is not yet supported in Docker, see https://github.com/pytorch/pytorch/issues/81224
|
66 |
+
- You can also use `docker compose up -d` to start the container detached and connect to the logs with `docker compose logs -f`. This way you can also close the terminal and keep the container running.
|
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: defooocus
|
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,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
from extras.interrogate import default_interrogator as default_interrogator_photo
|
3 |
+
from extras.wd14tagger import default_interrogator as default_interrogator_anime
|
4 |
+
|
5 |
+
img = cv2.imread('./test_imgs/red_box.jpg')[:, :, ::-1].copy()
|
6 |
+
print(default_interrogator_photo(img))
|
7 |
+
img = cv2.imread('./test_imgs/miku.jpg')[:, :, ::-1].copy()
|
8 |
+
print(default_interrogator_anime(img))
|
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/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)
|