Spaces:
Running
on
Zero
Running
on
Zero
Commit
·
edced0a
1
Parent(s):
53c8566
update codes
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .editorconfig +42 -0
- .flake8 +40 -0
- .gitattributes +10 -35
- .gitignore +415 -0
- .pre-commit-config.yaml +75 -0
- .pylintrc +629 -0
- DeepSeek_VL2_paper.pdf +3 -0
- LICENSE-CODE +21 -0
- LICENSE-MODEL +91 -0
- Makefile +97 -0
- README.md +399 -0
- deepseek_vl2/__init__.py +31 -0
- deepseek_vl2/models/__init__.py +26 -0
- deepseek_vl2/models/configuration_deepseek.py +210 -0
- deepseek_vl2/models/conversation.py +310 -0
- deepseek_vl2/models/modeling_deepseek.py +1975 -0
- deepseek_vl2/models/modeling_deepseek_vl_v2.py +697 -0
- deepseek_vl2/models/processing_deepseek_vl_v2.py +675 -0
- deepseek_vl2/models/siglip_vit.py +660 -0
- deepseek_vl2/serve/__init__.py +0 -0
- deepseek_vl2/serve/app_modules/__init__.py +0 -0
- deepseek_vl2/serve/app_modules/gradio_utils.py +83 -0
- deepseek_vl2/serve/app_modules/overwrites.py +81 -0
- deepseek_vl2/serve/app_modules/presets.py +115 -0
- deepseek_vl2/serve/app_modules/utils.py +333 -0
- deepseek_vl2/serve/assets/Kelpy-Codos.js +100 -0
- deepseek_vl2/serve/assets/avatar.png +3 -0
- deepseek_vl2/serve/assets/custom.css +355 -0
- deepseek_vl2/serve/assets/custom.js +22 -0
- deepseek_vl2/serve/assets/favicon.ico +3 -0
- deepseek_vl2/serve/assets/simsun.ttc +3 -0
- deepseek_vl2/serve/inference.py +198 -0
- deepseek_vl2/utils/__init__.py +18 -0
- deepseek_vl2/utils/io.py +80 -0
- images/grounding_conversation_1.jpeg +3 -0
- images/icl_vg_2.jpeg +3 -0
- images/incontext_visual_grounding_1.jpeg +3 -0
- images/logo.png +3 -0
- images/logo.svg +3 -0
- images/monday.jpg +3 -0
- images/multi_image_1.jpeg +3 -0
- images/multi_image_2.jpeg +3 -0
- images/multi_image_3.jpeg +3 -0
- images/qr.jpeg +3 -0
- images/sample.jpg +3 -0
- images/vg_2.jpeg +3 -0
- images/visual_grounding_1.jpeg +3 -0
- images/visual_grounding_2.jpg +3 -0
- images/visual_grounding_3.png +3 -0
- images/vl2_teaser.jpeg +3 -0
.editorconfig
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# https://editorconfig.org/
|
2 |
+
|
3 |
+
root = true
|
4 |
+
|
5 |
+
[*]
|
6 |
+
charset = utf-8
|
7 |
+
end_of_line = lf
|
8 |
+
indent_style = space
|
9 |
+
indent_size = 4
|
10 |
+
trim_trailing_whitespace = true
|
11 |
+
insert_final_newline = true
|
12 |
+
|
13 |
+
[*.py]
|
14 |
+
indent_size = 4
|
15 |
+
src_paths=evaluation
|
16 |
+
|
17 |
+
[*.{yaml,yml,json}]
|
18 |
+
indent_size = 2
|
19 |
+
|
20 |
+
[*.md]
|
21 |
+
indent_size = 2
|
22 |
+
x-soft-wrap-text = true
|
23 |
+
|
24 |
+
[*.rst]
|
25 |
+
indent_size = 4
|
26 |
+
x-soft-wrap-text = true
|
27 |
+
|
28 |
+
[*.{bib,tex}]
|
29 |
+
indent_size = 2
|
30 |
+
|
31 |
+
[Makefile]
|
32 |
+
indent_style = tab
|
33 |
+
|
34 |
+
[*.sh]
|
35 |
+
indent_style = tab
|
36 |
+
|
37 |
+
[*.bat]
|
38 |
+
end_of_line = crlf
|
39 |
+
indent_style = tab
|
40 |
+
|
41 |
+
[*.{cpp,h,cu,cuh}]
|
42 |
+
indent_size = 2
|
.flake8
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[flake8]
|
2 |
+
max-line-length = 120
|
3 |
+
max-doc-length = 100
|
4 |
+
select = B,C,E,F,W,Y,SIM
|
5 |
+
ignore =
|
6 |
+
# E203: whitespace before ':'
|
7 |
+
# W503: line break before binary operator
|
8 |
+
# W504: line break after binary operator
|
9 |
+
# format by black
|
10 |
+
E203,W503,W504,
|
11 |
+
# E501: line too long
|
12 |
+
# W505: doc line too long
|
13 |
+
# too long docstring due to long example blocks
|
14 |
+
E501,W505,
|
15 |
+
per-file-ignores =
|
16 |
+
# F401: module imported but unused
|
17 |
+
# intentionally unused imports
|
18 |
+
__init__.py: F401
|
19 |
+
# F401: module imported but unused
|
20 |
+
# F403: unable to detect undefined names
|
21 |
+
# F405: member mey be undefined, or defined from star imports
|
22 |
+
# members populated from optree
|
23 |
+
# E301: expected 1 blank line
|
24 |
+
# E302: expected 2 blank lines
|
25 |
+
# E305: expected 2 blank lines after class or function definition
|
26 |
+
# E701: multiple statements on one line (colon)
|
27 |
+
# E704: multiple statements on one line (def)
|
28 |
+
# format by black
|
29 |
+
*.pyi: E301,E302,E305,E701,E704
|
30 |
+
exclude =
|
31 |
+
.git,
|
32 |
+
.vscode,
|
33 |
+
venv,
|
34 |
+
third-party,
|
35 |
+
__pycache__,
|
36 |
+
docs/source/conf.py,
|
37 |
+
build,
|
38 |
+
dist,
|
39 |
+
examples,
|
40 |
+
tests
|
.gitattributes
CHANGED
@@ -1,35 +1,10 @@
|
|
1 |
-
|
2 |
-
*.
|
3 |
-
*.
|
4 |
-
*.
|
5 |
-
*.
|
6 |
-
*.
|
7 |
-
*.
|
8 |
-
*.
|
9 |
-
*.
|
10 |
-
*.
|
11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
-
*.xz 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
|
|
|
1 |
+
* text eol=lf
|
2 |
+
*.ipynb linguist-detectable=false
|
3 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.gif binary
|
7 |
+
*.pdf filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.ttc filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.svg filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.ico filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.gitignore
ADDED
@@ -0,0 +1,415 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
##### Python.gitignore #####
|
2 |
+
# Byte-compiled / optimized / DLL files
|
3 |
+
__pycache__/
|
4 |
+
*.py[cod]
|
5 |
+
*$py.class
|
6 |
+
|
7 |
+
# C extensions
|
8 |
+
*.so
|
9 |
+
|
10 |
+
# Distribution / packaging
|
11 |
+
.Python
|
12 |
+
build/
|
13 |
+
develop-eggs/
|
14 |
+
dist/
|
15 |
+
downloads/
|
16 |
+
eggs/
|
17 |
+
.eggs/
|
18 |
+
lib/
|
19 |
+
lib64/
|
20 |
+
parts/
|
21 |
+
sdist/
|
22 |
+
var/
|
23 |
+
wheels/
|
24 |
+
wheelhouse/
|
25 |
+
share/python-wheels/
|
26 |
+
*.egg-info/
|
27 |
+
.installed.cfg
|
28 |
+
*.egg
|
29 |
+
MANIFEST
|
30 |
+
*.whl
|
31 |
+
|
32 |
+
# PyInstaller
|
33 |
+
# Usually these files are written by a python script from a template
|
34 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
35 |
+
*.manifest
|
36 |
+
*.spec
|
37 |
+
|
38 |
+
# Installer logs
|
39 |
+
pip-log.txt
|
40 |
+
pip-delete-this-directory.txt
|
41 |
+
|
42 |
+
# Unit test / coverage reports
|
43 |
+
htmlcov/
|
44 |
+
.tox/
|
45 |
+
.nox/
|
46 |
+
.coverage
|
47 |
+
.coverage.*
|
48 |
+
.cache
|
49 |
+
nosetests.xml
|
50 |
+
coverage.xml
|
51 |
+
*.cover
|
52 |
+
*.py,cover
|
53 |
+
.hypothesis/
|
54 |
+
.pytest_cache/
|
55 |
+
cover/
|
56 |
+
|
57 |
+
# Translations
|
58 |
+
*.mo
|
59 |
+
*.pot
|
60 |
+
|
61 |
+
# Django stuff:
|
62 |
+
*.log
|
63 |
+
local_settings.py
|
64 |
+
db.sqlite3
|
65 |
+
db.sqlite3-journal
|
66 |
+
|
67 |
+
# Flask stuff:
|
68 |
+
instance/
|
69 |
+
.webassets-cache
|
70 |
+
|
71 |
+
# Scrapy stuff:
|
72 |
+
.scrapy
|
73 |
+
|
74 |
+
# Sphinx documentation
|
75 |
+
docs/_build/
|
76 |
+
docs/source/_build/
|
77 |
+
_autosummary/
|
78 |
+
|
79 |
+
# PyBuilder
|
80 |
+
.pybuilder/
|
81 |
+
target/
|
82 |
+
|
83 |
+
# Jupyter Notebook
|
84 |
+
.ipynb_checkpoints
|
85 |
+
|
86 |
+
# IPython
|
87 |
+
profile_default/
|
88 |
+
ipython_config.py
|
89 |
+
|
90 |
+
# pyenv
|
91 |
+
# For a library or package, you might want to ignore these files since the code is
|
92 |
+
# intended to run in multiple environments; otherwise, check them in:
|
93 |
+
.python-version
|
94 |
+
|
95 |
+
# pipenv
|
96 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
97 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
98 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
99 |
+
# install all needed dependencies.
|
100 |
+
#Pipfile.lock
|
101 |
+
|
102 |
+
# poetry
|
103 |
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
104 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
105 |
+
# commonly ignored for libraries.
|
106 |
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
107 |
+
#poetry.lock
|
108 |
+
|
109 |
+
# pdm
|
110 |
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
111 |
+
#pdm.lock
|
112 |
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
113 |
+
# in version control.
|
114 |
+
# https://pdm.fming.dev/#use-with-ide
|
115 |
+
.pdm.toml
|
116 |
+
|
117 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
118 |
+
__pypackages__/
|
119 |
+
|
120 |
+
# Celery stuff
|
121 |
+
celerybeat-schedule
|
122 |
+
celerybeat.pid
|
123 |
+
|
124 |
+
# SageMath parsed files
|
125 |
+
*.sage.py
|
126 |
+
|
127 |
+
# Environments
|
128 |
+
.env
|
129 |
+
.venv
|
130 |
+
env/
|
131 |
+
venv/
|
132 |
+
ENV/
|
133 |
+
env.bak/
|
134 |
+
venv.bak/
|
135 |
+
|
136 |
+
# Spyder project settings
|
137 |
+
.spyderproject
|
138 |
+
.spyproject
|
139 |
+
|
140 |
+
# Rope project settings
|
141 |
+
.ropeproject
|
142 |
+
|
143 |
+
# mkdocs documentation
|
144 |
+
/site
|
145 |
+
|
146 |
+
# ruff
|
147 |
+
.ruff_cache/
|
148 |
+
|
149 |
+
# mypy
|
150 |
+
.mypy_cache/
|
151 |
+
.dmypy.json
|
152 |
+
dmypy.json
|
153 |
+
|
154 |
+
# Pyre type checker
|
155 |
+
.pyre/
|
156 |
+
|
157 |
+
# pytype static type analyzer
|
158 |
+
.pytype/
|
159 |
+
|
160 |
+
# Cython debug symbols
|
161 |
+
cython_debug/
|
162 |
+
|
163 |
+
# PyCharm
|
164 |
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
165 |
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
166 |
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
167 |
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
168 |
+
.idea/
|
169 |
+
|
170 |
+
|
171 |
+
##### macOS.gitignore #####
|
172 |
+
# General
|
173 |
+
.DS_Store
|
174 |
+
.AppleDouble
|
175 |
+
.LSOverride
|
176 |
+
|
177 |
+
# Icon must end with two \r
|
178 |
+
Icon
|
179 |
+
|
180 |
+
# Thumbnails
|
181 |
+
._*
|
182 |
+
|
183 |
+
# Files that might appear in the root of a volume
|
184 |
+
.DocumentRevisions-V100
|
185 |
+
.fseventsd
|
186 |
+
.Spotlight-V100
|
187 |
+
.TemporaryItems
|
188 |
+
.Trashes
|
189 |
+
.VolumeIcon.icns
|
190 |
+
.com.apple.timemachine.donotpresent
|
191 |
+
|
192 |
+
# Directories potentially created on remote AFP share
|
193 |
+
.AppleDB
|
194 |
+
.AppleDesktop
|
195 |
+
Network Trash Folder
|
196 |
+
Temporary Items
|
197 |
+
.apdisk
|
198 |
+
|
199 |
+
|
200 |
+
##### Linux.gitignore #####
|
201 |
+
*~
|
202 |
+
|
203 |
+
# Temporary files which can be created if a process still has a handle open of a deleted file
|
204 |
+
.fuse_hidden*
|
205 |
+
|
206 |
+
# KDE directory preferences
|
207 |
+
.directory
|
208 |
+
|
209 |
+
# Linux trash folder which might appear on any partition or disk
|
210 |
+
.Trash-*
|
211 |
+
|
212 |
+
# .nfs files are created when an open file is removed but is still being accessed
|
213 |
+
.nfs*
|
214 |
+
|
215 |
+
|
216 |
+
##### Windows.gitignore #####
|
217 |
+
# Windows thumbnail cache files
|
218 |
+
Thumbs.db
|
219 |
+
Thumbs.db:encryptable
|
220 |
+
ehthumbs.db
|
221 |
+
ehthumbs_vista.db
|
222 |
+
|
223 |
+
# Dump file
|
224 |
+
*.stackdump
|
225 |
+
|
226 |
+
# Folder config file
|
227 |
+
[Dd]esktop.ini
|
228 |
+
|
229 |
+
# Recycle Bin used on file shares
|
230 |
+
$RECYCLE.BIN/
|
231 |
+
|
232 |
+
# Windows Installer files
|
233 |
+
*.cab
|
234 |
+
*.msi
|
235 |
+
*.msix
|
236 |
+
*.msm
|
237 |
+
*.msp
|
238 |
+
|
239 |
+
# Windows shortcuts
|
240 |
+
*.lnk
|
241 |
+
|
242 |
+
|
243 |
+
##### Archives.gitignore #####
|
244 |
+
# It's better to unpack these files and commit the raw source because
|
245 |
+
# git has its own built in compression methods.
|
246 |
+
*.7z
|
247 |
+
*.jar
|
248 |
+
*.rar
|
249 |
+
*.zip
|
250 |
+
*.gz
|
251 |
+
*.gzip
|
252 |
+
*.tgz
|
253 |
+
*.bzip
|
254 |
+
*.bzip2
|
255 |
+
*.bz2
|
256 |
+
*.xz
|
257 |
+
*.lzma
|
258 |
+
*.cab
|
259 |
+
*.xar
|
260 |
+
|
261 |
+
# Packing-only formats
|
262 |
+
*.iso
|
263 |
+
*.tar
|
264 |
+
|
265 |
+
# Package management formats
|
266 |
+
*.dmg
|
267 |
+
*.xpi
|
268 |
+
*.gem
|
269 |
+
*.egg
|
270 |
+
*.deb
|
271 |
+
*.rpm
|
272 |
+
*.msi
|
273 |
+
*.msm
|
274 |
+
*.msp
|
275 |
+
*.txz
|
276 |
+
|
277 |
+
|
278 |
+
##### Xcode.gitignore #####
|
279 |
+
# Xcode
|
280 |
+
#
|
281 |
+
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
|
282 |
+
|
283 |
+
## User settings
|
284 |
+
xcuserdata/
|
285 |
+
|
286 |
+
## Compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)
|
287 |
+
*.xcscmblueprint
|
288 |
+
*.xccheckout
|
289 |
+
|
290 |
+
## Compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)
|
291 |
+
build/
|
292 |
+
DerivedData/
|
293 |
+
*.moved-aside
|
294 |
+
*.pbxuser
|
295 |
+
!default.pbxuser
|
296 |
+
*.mode1v3
|
297 |
+
!default.mode1v3
|
298 |
+
*.mode2v3
|
299 |
+
!default.mode2v3
|
300 |
+
*.perspectivev3
|
301 |
+
!default.perspectivev3
|
302 |
+
|
303 |
+
## Gcc Patch
|
304 |
+
/*.gcno
|
305 |
+
|
306 |
+
|
307 |
+
##### JetBrains.gitignore #####
|
308 |
+
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
|
309 |
+
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
310 |
+
|
311 |
+
# User settings
|
312 |
+
.idea/*
|
313 |
+
|
314 |
+
# User-specific stuff
|
315 |
+
.idea/**/workspace.xml
|
316 |
+
.idea/**/tasks.xml
|
317 |
+
.idea/**/usage.statistics.xml
|
318 |
+
.idea/**/dictionaries
|
319 |
+
.idea/**/shelf
|
320 |
+
|
321 |
+
# Generated files
|
322 |
+
.idea/**/contentModel.xml
|
323 |
+
|
324 |
+
# Sensitive or high-churn files
|
325 |
+
.idea/**/dataSources/
|
326 |
+
.idea/**/dataSources.ids
|
327 |
+
.idea/**/dataSources.local.xml
|
328 |
+
.idea/**/sqlDataSources.xml
|
329 |
+
.idea/**/dynamic.xml
|
330 |
+
.idea/**/uiDesigner.xml
|
331 |
+
.idea/**/dbnavigator.xml
|
332 |
+
|
333 |
+
# Gradle
|
334 |
+
.idea/**/gradle.xml
|
335 |
+
.idea/**/libraries
|
336 |
+
|
337 |
+
# Gradle and Maven with auto-import
|
338 |
+
# When using Gradle or Maven with auto-import, you should exclude module files,
|
339 |
+
# since they will be recreated, and may cause churn. Uncomment if using
|
340 |
+
# auto-import.
|
341 |
+
# .idea/artifacts
|
342 |
+
# .idea/compiler.xml
|
343 |
+
# .idea/jarRepositories.xml
|
344 |
+
# .idea/modules.xml
|
345 |
+
# .idea/*.iml
|
346 |
+
# .idea/modules
|
347 |
+
# *.iml
|
348 |
+
# *.ipr
|
349 |
+
|
350 |
+
# CMake
|
351 |
+
cmake-build-*/
|
352 |
+
|
353 |
+
# Mongo Explorer plugin
|
354 |
+
.idea/**/mongoSettings.xml
|
355 |
+
|
356 |
+
# File-based project format
|
357 |
+
*.iws
|
358 |
+
|
359 |
+
# IntelliJ
|
360 |
+
out/
|
361 |
+
|
362 |
+
# mpeltonen/sbt-idea plugin
|
363 |
+
.idea_modules/
|
364 |
+
|
365 |
+
# JIRA plugin
|
366 |
+
atlassian-ide-plugin.xml
|
367 |
+
|
368 |
+
# Cursive Clojure plugin
|
369 |
+
.idea/replstate.xml
|
370 |
+
|
371 |
+
# Crashlytics plugin (for Android Studio and IntelliJ)
|
372 |
+
com_crashlytics_export_strings.xml
|
373 |
+
crashlytics.properties
|
374 |
+
crashlytics-build.properties
|
375 |
+
fabric.properties
|
376 |
+
|
377 |
+
# Editor-based Rest Client
|
378 |
+
.idea/httpRequests
|
379 |
+
|
380 |
+
# Android studio 3.1+ serialized cache file
|
381 |
+
.idea/caches/build_file_checksums.ser
|
382 |
+
|
383 |
+
|
384 |
+
##### VisualStudioCode.gitignore #####
|
385 |
+
.vscode/*
|
386 |
+
# !.vscode/settings.json
|
387 |
+
# !.vscode/tasks.json
|
388 |
+
# !.vscode/launch.json
|
389 |
+
!.vscode/extensions.json
|
390 |
+
*.code-workspace
|
391 |
+
|
392 |
+
# Local History for Visual Studio Code
|
393 |
+
.history/
|
394 |
+
|
395 |
+
|
396 |
+
##### Vim.gitignore #####
|
397 |
+
# Swap
|
398 |
+
.*.s[a-v][a-z]
|
399 |
+
!*.svg # comment out if you don't need vector files
|
400 |
+
.*.sw[a-p]
|
401 |
+
.s[a-rt-v][a-z]
|
402 |
+
.ss[a-gi-z]
|
403 |
+
.sw[a-p]
|
404 |
+
|
405 |
+
# Session
|
406 |
+
Session.vim
|
407 |
+
Sessionx.vim
|
408 |
+
|
409 |
+
# Temporary
|
410 |
+
.netrwhist
|
411 |
+
*~
|
412 |
+
# Auto-generated tag files
|
413 |
+
tags
|
414 |
+
# Persistent undo
|
415 |
+
[._]*.un~
|
.pre-commit-config.yaml
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# See https://pre-commit.com for more information
|
2 |
+
# See https://pre-commit.com/hooks.html for more hooks
|
3 |
+
ci:
|
4 |
+
skip: [pylint]
|
5 |
+
autofix_prs: true
|
6 |
+
autofix_commit_msg: "fix: [pre-commit.ci] auto fixes [...]"
|
7 |
+
autoupdate_commit_msg: "chore(pre-commit): [pre-commit.ci] autoupdate"
|
8 |
+
autoupdate_schedule: monthly
|
9 |
+
default_stages: [commit, push, manual]
|
10 |
+
repos:
|
11 |
+
- repo: https://github.com/pre-commit/pre-commit-hooks
|
12 |
+
rev: v4.5.0
|
13 |
+
hooks:
|
14 |
+
- id: check-symlinks
|
15 |
+
- id: destroyed-symlinks
|
16 |
+
- id: trailing-whitespace
|
17 |
+
- id: end-of-file-fixer
|
18 |
+
- id: check-yaml
|
19 |
+
- id: check-toml
|
20 |
+
- id: check-ast
|
21 |
+
- id: check-added-large-files
|
22 |
+
- id: check-merge-conflict
|
23 |
+
- id: check-executables-have-shebangs
|
24 |
+
- id: check-shebang-scripts-are-executable
|
25 |
+
- id: detect-private-key
|
26 |
+
- id: debug-statements
|
27 |
+
- id: double-quote-string-fixer
|
28 |
+
- repo: https://github.com/astral-sh/ruff-pre-commit
|
29 |
+
rev: v0.1.5
|
30 |
+
hooks:
|
31 |
+
- id: ruff
|
32 |
+
args: [--fix, --exit-non-zero-on-fix]
|
33 |
+
- repo: https://github.com/PyCQA/isort
|
34 |
+
rev: 5.12.0
|
35 |
+
hooks:
|
36 |
+
- id: isort
|
37 |
+
- repo: https://github.com/psf/black
|
38 |
+
rev: 23.11.0
|
39 |
+
hooks:
|
40 |
+
- id: black-jupyter
|
41 |
+
- repo: https://github.com/asottile/pyupgrade
|
42 |
+
rev: v3.15.0
|
43 |
+
hooks:
|
44 |
+
- id: pyupgrade
|
45 |
+
args: [--py38-plus] # sync with requires-python
|
46 |
+
exclude: |
|
47 |
+
(?x)(
|
48 |
+
^images/
|
49 |
+
)
|
50 |
+
- repo: https://github.com/pycqa/flake8
|
51 |
+
rev: 6.1.0
|
52 |
+
hooks:
|
53 |
+
- id: flake8
|
54 |
+
additional_dependencies:
|
55 |
+
- flake8-bugbear
|
56 |
+
- flake8-comprehensions
|
57 |
+
- flake8-docstrings
|
58 |
+
- flake8-pyi
|
59 |
+
- flake8-simplify
|
60 |
+
exclude: |
|
61 |
+
(?x)(
|
62 |
+
^images/
|
63 |
+
)
|
64 |
+
- repo: local
|
65 |
+
hooks:
|
66 |
+
- id: pylint
|
67 |
+
name: pylint
|
68 |
+
entry: pylint
|
69 |
+
language: system
|
70 |
+
types: [python]
|
71 |
+
require_serial: true
|
72 |
+
exclude: |
|
73 |
+
(?x)(
|
74 |
+
^images/
|
75 |
+
)
|
.pylintrc
ADDED
@@ -0,0 +1,629 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[MAIN]
|
2 |
+
|
3 |
+
# Analyse import fallback blocks. This can be used to support both Python 2 and
|
4 |
+
# 3 compatible code, which means that the block might have code that exists
|
5 |
+
# only in one or another interpreter, leading to false positives when analysed.
|
6 |
+
analyse-fallback-blocks=no
|
7 |
+
|
8 |
+
# Load and enable all available extensions. Use --list-extensions to see a list
|
9 |
+
# all available extensions.
|
10 |
+
#enable-all-extensions=
|
11 |
+
|
12 |
+
# In error mode, messages with a category besides ERROR or FATAL are
|
13 |
+
# suppressed, and no reports are done by default. Error mode is compatible with
|
14 |
+
# disabling specific errors.
|
15 |
+
#errors-only=
|
16 |
+
|
17 |
+
# Always return a 0 (non-error) status code, even if lint errors are found.
|
18 |
+
# This is primarily useful in continuous integration scripts.
|
19 |
+
#exit-zero=
|
20 |
+
|
21 |
+
# A comma-separated list of package or module names from where C extensions may
|
22 |
+
# be loaded. Extensions are loading into the active Python interpreter and may
|
23 |
+
# run arbitrary code.
|
24 |
+
extension-pkg-allow-list=
|
25 |
+
|
26 |
+
# A comma-separated list of package or module names from where C extensions may
|
27 |
+
# be loaded. Extensions are loading into the active Python interpreter and may
|
28 |
+
# run arbitrary code. (This is an alternative name to extension-pkg-allow-list
|
29 |
+
# for backward compatibility.)
|
30 |
+
extension-pkg-whitelist=
|
31 |
+
|
32 |
+
# Return non-zero exit code if any of these messages/categories are detected,
|
33 |
+
# even if score is above --fail-under value. Syntax same as enable. Messages
|
34 |
+
# specified are enabled, while categories only check already-enabled messages.
|
35 |
+
fail-on=
|
36 |
+
|
37 |
+
# Specify a score threshold under which the program will exit with error.
|
38 |
+
fail-under=10
|
39 |
+
|
40 |
+
# Interpret the stdin as a python script, whose filename needs to be passed as
|
41 |
+
# the module_or_package argument.
|
42 |
+
#from-stdin=
|
43 |
+
|
44 |
+
# Files or directories to be skipped. They should be base names, not paths.
|
45 |
+
ignore=CVS,.vscode,.history
|
46 |
+
|
47 |
+
# Add files or directories matching the regular expressions patterns to the
|
48 |
+
# ignore-list. The regex matches against paths and can be in Posix or Windows
|
49 |
+
# format. Because '\' represents the directory delimiter on Windows systems, it
|
50 |
+
# can't be used as an escape character.
|
51 |
+
ignore-paths=^images/$
|
52 |
+
|
53 |
+
# Files or directories matching the regular expression patterns are skipped.
|
54 |
+
# The regex matches against base names, not paths. The default value ignores
|
55 |
+
# Emacs file locks
|
56 |
+
ignore-patterns=^\.#
|
57 |
+
|
58 |
+
# List of module names for which member attributes should not be checked
|
59 |
+
# (useful for modules/projects where namespaces are manipulated during runtime
|
60 |
+
# and thus existing member attributes cannot be deduced by static analysis). It
|
61 |
+
# supports qualified module names, as well as Unix pattern matching.
|
62 |
+
ignored-modules=
|
63 |
+
|
64 |
+
# Python code to execute, usually for sys.path manipulation such as
|
65 |
+
# pygtk.require().
|
66 |
+
#init-hook=
|
67 |
+
|
68 |
+
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
|
69 |
+
# number of processors available to use, and will cap the count on Windows to
|
70 |
+
# avoid hangs.
|
71 |
+
jobs=0
|
72 |
+
|
73 |
+
# Control the amount of potential inferred values when inferring a single
|
74 |
+
# object. This can help the performance when dealing with large functions or
|
75 |
+
# complex, nested conditions.
|
76 |
+
limit-inference-results=100
|
77 |
+
|
78 |
+
# List of plugins (as comma separated values of python module names) to load,
|
79 |
+
# usually to register additional checkers.
|
80 |
+
load-plugins=
|
81 |
+
|
82 |
+
# Pickle collected data for later comparisons.
|
83 |
+
persistent=yes
|
84 |
+
|
85 |
+
# Minimum Python version to use for version dependent checks. Will default to
|
86 |
+
# the version used to run pylint.
|
87 |
+
py-version=3.8 # the lowest version we support (sync with requires-python in pyproject.toml)
|
88 |
+
|
89 |
+
# Discover python modules and packages in the file system subtree.
|
90 |
+
recursive=no
|
91 |
+
|
92 |
+
# When enabled, pylint would attempt to guess common misconfiguration and emit
|
93 |
+
# user-friendly hints instead of false-positive error messages.
|
94 |
+
suggestion-mode=yes
|
95 |
+
|
96 |
+
# Allow loading of arbitrary C extensions. Extensions are imported into the
|
97 |
+
# active Python interpreter and may run arbitrary code.
|
98 |
+
unsafe-load-any-extension=no
|
99 |
+
|
100 |
+
# In verbose mode, extra non-checker-related info will be displayed.
|
101 |
+
#verbose=
|
102 |
+
|
103 |
+
|
104 |
+
[BASIC]
|
105 |
+
|
106 |
+
# Naming style matching correct argument names.
|
107 |
+
argument-naming-style=snake_case
|
108 |
+
|
109 |
+
# Regular expression matching correct argument names. Overrides argument-
|
110 |
+
# naming-style. If left empty, argument names will be checked with the set
|
111 |
+
# naming style.
|
112 |
+
#argument-rgx=
|
113 |
+
|
114 |
+
# Naming style matching correct attribute names.
|
115 |
+
attr-naming-style=snake_case
|
116 |
+
|
117 |
+
# Regular expression matching correct attribute names. Overrides attr-naming-
|
118 |
+
# style. If left empty, attribute names will be checked with the set naming
|
119 |
+
# style.
|
120 |
+
#attr-rgx=
|
121 |
+
|
122 |
+
# Bad variable names which should always be refused, separated by a comma.
|
123 |
+
bad-names=foo,
|
124 |
+
bar,
|
125 |
+
baz,
|
126 |
+
toto,
|
127 |
+
tutu,
|
128 |
+
tata
|
129 |
+
|
130 |
+
# Bad variable names regexes, separated by a comma. If names match any regex,
|
131 |
+
# they will always be refused
|
132 |
+
bad-names-rgxs=
|
133 |
+
|
134 |
+
# Naming style matching correct class attribute names.
|
135 |
+
class-attribute-naming-style=any
|
136 |
+
|
137 |
+
# Regular expression matching correct class attribute names. Overrides class-
|
138 |
+
# attribute-naming-style. If left empty, class attribute names will be checked
|
139 |
+
# with the set naming style.
|
140 |
+
#class-attribute-rgx=
|
141 |
+
|
142 |
+
# Naming style matching correct class constant names.
|
143 |
+
class-const-naming-style=UPPER_CASE
|
144 |
+
|
145 |
+
# Regular expression matching correct class constant names. Overrides class-
|
146 |
+
# const-naming-style. If left empty, class constant names will be checked with
|
147 |
+
# the set naming style.
|
148 |
+
#class-const-rgx=
|
149 |
+
|
150 |
+
# Naming style matching correct class names.
|
151 |
+
class-naming-style=PascalCase
|
152 |
+
|
153 |
+
# Regular expression matching correct class names. Overrides class-naming-
|
154 |
+
# style. If left empty, class names will be checked with the set naming style.
|
155 |
+
#class-rgx=
|
156 |
+
|
157 |
+
# Naming style matching correct constant names.
|
158 |
+
const-naming-style=UPPER_CASE
|
159 |
+
|
160 |
+
# Regular expression matching correct constant names. Overrides const-naming-
|
161 |
+
# style. If left empty, constant names will be checked with the set naming
|
162 |
+
# style.
|
163 |
+
#const-rgx=
|
164 |
+
|
165 |
+
# Minimum line length for functions/classes that require docstrings, shorter
|
166 |
+
# ones are exempt.
|
167 |
+
docstring-min-length=-1
|
168 |
+
|
169 |
+
# Naming style matching correct function names.
|
170 |
+
function-naming-style=snake_case
|
171 |
+
|
172 |
+
# Regular expression matching correct function names. Overrides function-
|
173 |
+
# naming-style. If left empty, function names will be checked with the set
|
174 |
+
# naming style.
|
175 |
+
#function-rgx=
|
176 |
+
|
177 |
+
# Good variable names which should always be accepted, separated by a comma.
|
178 |
+
good-names=i,
|
179 |
+
j,
|
180 |
+
k,
|
181 |
+
ex,
|
182 |
+
Run,
|
183 |
+
_,
|
184 |
+
op,
|
185 |
+
fn,
|
186 |
+
f,
|
187 |
+
g,
|
188 |
+
p,
|
189 |
+
u,
|
190 |
+
t,
|
191 |
+
lr,
|
192 |
+
mu,
|
193 |
+
nu,
|
194 |
+
x,
|
195 |
+
y
|
196 |
+
|
197 |
+
# Good variable names regexes, separated by a comma. If names match any regex,
|
198 |
+
# they will always be accepted
|
199 |
+
good-names-rgxs=
|
200 |
+
|
201 |
+
# Include a hint for the correct naming format with invalid-name.
|
202 |
+
include-naming-hint=no
|
203 |
+
|
204 |
+
# Naming style matching correct inline iteration names.
|
205 |
+
inlinevar-naming-style=any
|
206 |
+
|
207 |
+
# Regular expression matching correct inline iteration names. Overrides
|
208 |
+
# inlinevar-naming-style. If left empty, inline iteration names will be checked
|
209 |
+
# with the set naming style.
|
210 |
+
#inlinevar-rgx=
|
211 |
+
|
212 |
+
# Naming style matching correct method names.
|
213 |
+
method-naming-style=snake_case
|
214 |
+
|
215 |
+
# Regular expression matching correct method names. Overrides method-naming-
|
216 |
+
# style. If left empty, method names will be checked with the set naming style.
|
217 |
+
#method-rgx=
|
218 |
+
|
219 |
+
# Naming style matching correct module names.
|
220 |
+
module-naming-style=snake_case
|
221 |
+
|
222 |
+
# Regular expression matching correct module names. Overrides module-naming-
|
223 |
+
# style. If left empty, module names will be checked with the set naming style.
|
224 |
+
#module-rgx=
|
225 |
+
|
226 |
+
# Colon-delimited sets of names that determine each other's naming style when
|
227 |
+
# the name regexes allow several styles.
|
228 |
+
name-group=
|
229 |
+
|
230 |
+
# Regular expression which should only match function or class names that do
|
231 |
+
# not require a docstring.
|
232 |
+
no-docstring-rgx=^_
|
233 |
+
|
234 |
+
# List of decorators that produce properties, such as abc.abstractproperty. Add
|
235 |
+
# to this list to register other decorators that produce valid properties.
|
236 |
+
# These decorators are taken in consideration only for invalid-name.
|
237 |
+
property-classes=abc.abstractproperty
|
238 |
+
|
239 |
+
# Regular expression matching correct type variable names. If left empty, type
|
240 |
+
# variable names will be checked with the set naming style.
|
241 |
+
#typevar-rgx=
|
242 |
+
|
243 |
+
# Naming style matching correct variable names.
|
244 |
+
variable-naming-style=snake_case
|
245 |
+
|
246 |
+
# Regular expression matching correct variable names. Overrides variable-
|
247 |
+
# naming-style. If left empty, variable names will be checked with the set
|
248 |
+
# naming style.
|
249 |
+
#variable-rgx=
|
250 |
+
|
251 |
+
|
252 |
+
[CLASSES]
|
253 |
+
|
254 |
+
# Warn about protected attribute access inside special methods
|
255 |
+
check-protected-access-in-special-methods=no
|
256 |
+
|
257 |
+
# List of method names used to declare (i.e. assign) instance attributes.
|
258 |
+
defining-attr-methods=__init__,
|
259 |
+
__new__,
|
260 |
+
setUp,
|
261 |
+
__post_init__
|
262 |
+
|
263 |
+
# List of member names, which should be excluded from the protected access
|
264 |
+
# warning.
|
265 |
+
exclude-protected=_asdict,
|
266 |
+
_fields,
|
267 |
+
_replace,
|
268 |
+
_source,
|
269 |
+
_make
|
270 |
+
|
271 |
+
# List of valid names for the first argument in a class method.
|
272 |
+
valid-classmethod-first-arg=cls
|
273 |
+
|
274 |
+
# List of valid names for the first argument in a metaclass class method.
|
275 |
+
valid-metaclass-classmethod-first-arg=cls
|
276 |
+
|
277 |
+
|
278 |
+
[DESIGN]
|
279 |
+
|
280 |
+
# List of regular expressions of class ancestor names to ignore when counting
|
281 |
+
# public methods (see R0903)
|
282 |
+
exclude-too-few-public-methods=
|
283 |
+
|
284 |
+
# List of qualified class names to ignore when counting class parents (see
|
285 |
+
# R0901)
|
286 |
+
ignored-parents=
|
287 |
+
|
288 |
+
# Maximum number of arguments for function / method.
|
289 |
+
max-args=5
|
290 |
+
|
291 |
+
# Maximum number of attributes for a class (see R0902).
|
292 |
+
max-attributes=7
|
293 |
+
|
294 |
+
# Maximum number of boolean expressions in an if statement (see R0916).
|
295 |
+
max-bool-expr=5
|
296 |
+
|
297 |
+
# Maximum number of branch for function / method body.
|
298 |
+
max-branches=12
|
299 |
+
|
300 |
+
# Maximum number of locals for function / method body.
|
301 |
+
max-locals=15
|
302 |
+
|
303 |
+
# Maximum number of parents for a class (see R0901).
|
304 |
+
max-parents=7
|
305 |
+
|
306 |
+
# Maximum number of public methods for a class (see R0904).
|
307 |
+
max-public-methods=20
|
308 |
+
|
309 |
+
# Maximum number of return / yield for function / method body.
|
310 |
+
max-returns=6
|
311 |
+
|
312 |
+
# Maximum number of statements in function / method body.
|
313 |
+
max-statements=50
|
314 |
+
|
315 |
+
# Minimum number of public methods for a class (see R0903).
|
316 |
+
min-public-methods=2
|
317 |
+
|
318 |
+
|
319 |
+
[EXCEPTIONS]
|
320 |
+
|
321 |
+
# Exceptions that will emit a warning when caught.
|
322 |
+
overgeneral-exceptions=builtins.BaseException,
|
323 |
+
builtins.Exception
|
324 |
+
|
325 |
+
|
326 |
+
[FORMAT]
|
327 |
+
|
328 |
+
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
|
329 |
+
expected-line-ending-format=
|
330 |
+
|
331 |
+
# Regexp for a line that is allowed to be longer than the limit.
|
332 |
+
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
|
333 |
+
|
334 |
+
# Number of spaces of indent required inside a hanging or continued line.
|
335 |
+
indent-after-paren=4
|
336 |
+
|
337 |
+
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
|
338 |
+
# tab).
|
339 |
+
indent-string=' '
|
340 |
+
|
341 |
+
# Maximum number of characters on a single line.
|
342 |
+
max-line-length=120
|
343 |
+
|
344 |
+
# Maximum number of lines in a module.
|
345 |
+
max-module-lines=1000
|
346 |
+
|
347 |
+
# Allow the body of a class to be on the same line as the declaration if body
|
348 |
+
# contains single statement.
|
349 |
+
single-line-class-stmt=no
|
350 |
+
|
351 |
+
# Allow the body of an if to be on the same line as the test if there is no
|
352 |
+
# else.
|
353 |
+
single-line-if-stmt=no
|
354 |
+
|
355 |
+
|
356 |
+
[IMPORTS]
|
357 |
+
|
358 |
+
# List of modules that can be imported at any level, not just the top level
|
359 |
+
# one.
|
360 |
+
allow-any-import-level=
|
361 |
+
|
362 |
+
# Allow wildcard imports from modules that define __all__.
|
363 |
+
allow-wildcard-with-all=no
|
364 |
+
|
365 |
+
# Deprecated modules which should not be used, separated by a comma.
|
366 |
+
deprecated-modules=
|
367 |
+
|
368 |
+
# Output a graph (.gv or any supported image format) of external dependencies
|
369 |
+
# to the given file (report RP0402 must not be disabled).
|
370 |
+
ext-import-graph=
|
371 |
+
|
372 |
+
# Output a graph (.gv or any supported image format) of all (i.e. internal and
|
373 |
+
# external) dependencies to the given file (report RP0402 must not be
|
374 |
+
# disabled).
|
375 |
+
import-graph=
|
376 |
+
|
377 |
+
# Output a graph (.gv or any supported image format) of internal dependencies
|
378 |
+
# to the given file (report RP0402 must not be disabled).
|
379 |
+
int-import-graph=
|
380 |
+
|
381 |
+
# Force import order to recognize a module as part of the standard
|
382 |
+
# compatibility libraries.
|
383 |
+
known-standard-library=
|
384 |
+
|
385 |
+
# Force import order to recognize a module as part of a third party library.
|
386 |
+
known-third-party=enchant
|
387 |
+
|
388 |
+
# Couples of modules and preferred modules, separated by a comma.
|
389 |
+
preferred-modules=
|
390 |
+
|
391 |
+
|
392 |
+
[LOGGING]
|
393 |
+
|
394 |
+
# The type of string formatting that logging methods do. `old` means using %
|
395 |
+
# formatting, `new` is for `{}` formatting.
|
396 |
+
logging-format-style=old
|
397 |
+
|
398 |
+
# Logging modules to check that the string format arguments are in logging
|
399 |
+
# function parameter format.
|
400 |
+
logging-modules=logging
|
401 |
+
|
402 |
+
|
403 |
+
[MESSAGES CONTROL]
|
404 |
+
|
405 |
+
# Only show warnings with the listed confidence levels. Leave empty to show
|
406 |
+
# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE,
|
407 |
+
# UNDEFINED.
|
408 |
+
confidence=HIGH,
|
409 |
+
CONTROL_FLOW,
|
410 |
+
INFERENCE,
|
411 |
+
INFERENCE_FAILURE,
|
412 |
+
UNDEFINED
|
413 |
+
|
414 |
+
# Disable the message, report, category or checker with the given id(s). You
|
415 |
+
# can either give multiple identifiers separated by comma (,) or put this
|
416 |
+
# option multiple times (only on the command line, not in the configuration
|
417 |
+
# file where it should appear only once). You can also use "--disable=all" to
|
418 |
+
# disable everything first and then re-enable specific checks. For example, if
|
419 |
+
# you want to run only the similarities checker, you can use "--disable=all
|
420 |
+
# --enable=similarities". If you want to run only the classes checker, but have
|
421 |
+
# no Warning level messages displayed, use "--disable=all --enable=classes
|
422 |
+
# --disable=W".
|
423 |
+
disable=duplicate-code,
|
424 |
+
consider-using-from-import
|
425 |
+
|
426 |
+
# Enable the message, report, category or checker with the given id(s). You can
|
427 |
+
# either give multiple identifier separated by comma (,) or put this option
|
428 |
+
# multiple time (only on the command line, not in the configuration file where
|
429 |
+
# it should appear only once). See also the "--disable" option for examples.
|
430 |
+
enable=c-extension-no-member
|
431 |
+
|
432 |
+
|
433 |
+
[METHOD_ARGS]
|
434 |
+
|
435 |
+
# List of qualified names (i.e., library.method) which require a timeout
|
436 |
+
# parameter e.g. 'requests.api.get,requests.api.post'
|
437 |
+
timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request
|
438 |
+
|
439 |
+
|
440 |
+
[MISCELLANEOUS]
|
441 |
+
|
442 |
+
# List of note tags to take in consideration, separated by a comma.
|
443 |
+
notes=FIXME,
|
444 |
+
XXX,
|
445 |
+
TODO
|
446 |
+
|
447 |
+
# Regular expression of note tags to take in consideration.
|
448 |
+
notes-rgx=
|
449 |
+
|
450 |
+
|
451 |
+
[REFACTORING]
|
452 |
+
|
453 |
+
# Maximum number of nested blocks for function / method body
|
454 |
+
max-nested-blocks=5
|
455 |
+
|
456 |
+
# Complete name of functions that never returns. When checking for
|
457 |
+
# inconsistent-return-statements if a never returning function is called then
|
458 |
+
# it will be considered as an explicit return statement and no message will be
|
459 |
+
# printed.
|
460 |
+
never-returning-functions=sys.exit,argparse.parse_error
|
461 |
+
|
462 |
+
|
463 |
+
[REPORTS]
|
464 |
+
|
465 |
+
# Python expression which should return a score less than or equal to 10. You
|
466 |
+
# have access to the variables 'fatal', 'error', 'warning', 'refactor',
|
467 |
+
# 'convention', and 'info' which contain the number of messages in each
|
468 |
+
# category, as well as 'statement' which is the total number of statements
|
469 |
+
# analyzed. This score is used by the global evaluation report (RP0004).
|
470 |
+
evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))
|
471 |
+
|
472 |
+
# Template used to display messages. This is a python new-style format string
|
473 |
+
# used to format the message information. See doc for all details.
|
474 |
+
msg-template=
|
475 |
+
|
476 |
+
# Set the output format. Available formats are text, parseable, colorized, json
|
477 |
+
# and msvs (visual studio). You can also give a reporter class, e.g.
|
478 |
+
# mypackage.mymodule.MyReporterClass.
|
479 |
+
#output-format=
|
480 |
+
|
481 |
+
# Tells whether to display a full report or only the messages.
|
482 |
+
reports=no
|
483 |
+
|
484 |
+
# Activate the evaluation score.
|
485 |
+
score=yes
|
486 |
+
|
487 |
+
|
488 |
+
[SIMILARITIES]
|
489 |
+
|
490 |
+
# Comments are removed from the similarity computation
|
491 |
+
ignore-comments=yes
|
492 |
+
|
493 |
+
# Docstrings are removed from the similarity computation
|
494 |
+
ignore-docstrings=yes
|
495 |
+
|
496 |
+
# Imports are removed from the similarity computation
|
497 |
+
ignore-imports=yes
|
498 |
+
|
499 |
+
# Signatures are removed from the similarity computation
|
500 |
+
ignore-signatures=yes
|
501 |
+
|
502 |
+
# Minimum lines number of a similarity.
|
503 |
+
min-similarity-lines=4
|
504 |
+
|
505 |
+
|
506 |
+
[SPELLING]
|
507 |
+
|
508 |
+
# Limits count of emitted suggestions for spelling mistakes.
|
509 |
+
max-spelling-suggestions=4
|
510 |
+
|
511 |
+
# Spelling dictionary name. Available dictionaries: en_AU (hunspell), en_CA
|
512 |
+
# (hunspell), en_GB (hunspell), en_US (hunspell), en_ZA (hunspell).
|
513 |
+
spelling-dict=
|
514 |
+
|
515 |
+
# List of comma separated words that should be considered directives if they
|
516 |
+
# appear at the beginning of a comment and should not be checked.
|
517 |
+
spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:
|
518 |
+
|
519 |
+
# List of comma separated words that should not be checked.
|
520 |
+
spelling-ignore-words=
|
521 |
+
|
522 |
+
# A path to a file that contains the private dictionary; one word per line.
|
523 |
+
spelling-private-dict-file=docs/source/spelling_wordlist.txt
|
524 |
+
|
525 |
+
# Tells whether to store unknown words to the private dictionary (see the
|
526 |
+
# --spelling-private-dict-file option) instead of raising a message.
|
527 |
+
spelling-store-unknown-words=no
|
528 |
+
|
529 |
+
|
530 |
+
[STRING]
|
531 |
+
|
532 |
+
# This flag controls whether inconsistent-quotes generates a warning when the
|
533 |
+
# character used as a quote delimiter is used inconsistently within a module.
|
534 |
+
check-quote-consistency=no
|
535 |
+
|
536 |
+
# This flag controls whether the implicit-str-concat should generate a warning
|
537 |
+
# on implicit string concatenation in sequences defined over several lines.
|
538 |
+
check-str-concat-over-line-jumps=no
|
539 |
+
|
540 |
+
|
541 |
+
[TYPECHECK]
|
542 |
+
|
543 |
+
# List of decorators that produce context managers, such as
|
544 |
+
# contextlib.contextmanager. Add to this list to register other decorators that
|
545 |
+
# produce valid context managers.
|
546 |
+
contextmanager-decorators=contextlib.contextmanager
|
547 |
+
|
548 |
+
# List of members which are set dynamically and missed by pylint inference
|
549 |
+
# system, and so shouldn't trigger E1101 when accessed. Python regular
|
550 |
+
# expressions are accepted.
|
551 |
+
generated-members=numpy.*,
|
552 |
+
torch.*
|
553 |
+
|
554 |
+
# Tells whether missing members accessed in mixin class should be ignored. A
|
555 |
+
# class is considered mixin if its name matches the mixin-class-rgx option.
|
556 |
+
ignore-mixin-members=yes
|
557 |
+
|
558 |
+
# Tells whether to warn about missing members when the owner of the attribute
|
559 |
+
# is inferred to be None.
|
560 |
+
ignore-none=yes
|
561 |
+
|
562 |
+
# This flag controls whether pylint should warn about no-member and similar
|
563 |
+
# checks whenever an opaque object is returned when inferring. The inference
|
564 |
+
# can return multiple potential results while evaluating a Python object, but
|
565 |
+
# some branches might not be evaluated, which results in partial inference. In
|
566 |
+
# that case, it might be useful to still emit no-member and other checks for
|
567 |
+
# the rest of the inferred objects.
|
568 |
+
ignore-on-opaque-inference=yes
|
569 |
+
|
570 |
+
# List of symbolic message names to ignore for Mixin members.
|
571 |
+
ignored-checks-for-mixins=no-member,
|
572 |
+
not-async-context-manager,
|
573 |
+
not-context-manager,
|
574 |
+
attribute-defined-outside-init
|
575 |
+
|
576 |
+
# List of class names for which member attributes should not be checked (useful
|
577 |
+
# for classes with dynamically set attributes). This supports the use of
|
578 |
+
# qualified names.
|
579 |
+
ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace
|
580 |
+
|
581 |
+
# Show a hint with possible names when a member name was not found. The aspect
|
582 |
+
# of finding the hint is based on edit distance.
|
583 |
+
missing-member-hint=yes
|
584 |
+
|
585 |
+
# The minimum edit distance a name should have in order to be considered a
|
586 |
+
# similar match for a missing member name.
|
587 |
+
missing-member-hint-distance=1
|
588 |
+
|
589 |
+
# The total number of similar names that should be taken in consideration when
|
590 |
+
# showing a hint for a missing member.
|
591 |
+
missing-member-max-choices=1
|
592 |
+
|
593 |
+
# Regex pattern to define which classes are considered mixins.
|
594 |
+
mixin-class-rgx=.*[Mm]ixin
|
595 |
+
|
596 |
+
# List of decorators that change the signature of a decorated function.
|
597 |
+
signature-mutators=
|
598 |
+
|
599 |
+
|
600 |
+
[VARIABLES]
|
601 |
+
|
602 |
+
# List of additional names supposed to be defined in builtins. Remember that
|
603 |
+
# you should avoid defining new builtins when possible.
|
604 |
+
additional-builtins=
|
605 |
+
|
606 |
+
# Tells whether unused global variables should be treated as a violation.
|
607 |
+
allow-global-unused-variables=yes
|
608 |
+
|
609 |
+
# List of names allowed to shadow builtins
|
610 |
+
allowed-redefined-builtins=
|
611 |
+
|
612 |
+
# List of strings which can identify a callback function by name. A callback
|
613 |
+
# name must start or end with one of those strings.
|
614 |
+
callbacks=cb_,
|
615 |
+
_cb
|
616 |
+
|
617 |
+
# A regular expression matching the name of dummy variables (i.e. expected to
|
618 |
+
# not be used).
|
619 |
+
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
|
620 |
+
|
621 |
+
# Argument names that match this expression will be ignored.
|
622 |
+
ignored-argument-names=_.*|^ignored_|^unused_
|
623 |
+
|
624 |
+
# Tells whether we should check for unused import in __init__ files.
|
625 |
+
init-import=no
|
626 |
+
|
627 |
+
# List of qualified module names which can have objects that can redefine
|
628 |
+
# builtins.
|
629 |
+
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
|
DeepSeek_VL2_paper.pdf
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a79c31356d7a353ef25df880d983527ed0843aa9b160e568942001f40630ddbe
|
3 |
+
size 5888873
|
LICENSE-CODE
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2023 DeepSeek
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
LICENSE-MODEL
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
DEEPSEEK LICENSE AGREEMENT
|
2 |
+
|
3 |
+
Version 1.0, 23 October 2023
|
4 |
+
|
5 |
+
Copyright (c) 2023 DeepSeek
|
6 |
+
|
7 |
+
Section I: PREAMBLE
|
8 |
+
|
9 |
+
Large generative models are being widely adopted and used, and have the potential to transform the way individuals conceive and benefit from AI or ML technologies.
|
10 |
+
|
11 |
+
Notwithstanding the current and potential benefits that these artifacts can bring to society at large, there are also concerns about potential misuses of them, either due to their technical limitations or ethical considerations.
|
12 |
+
|
13 |
+
In short, this license strives for both the open and responsible downstream use of the accompanying model. When it comes to the open character, we took inspiration from open source permissive licenses regarding the grant of IP rights. Referring to the downstream responsible use, we added use-based restrictions not permitting the use of the model in very specific scenarios, in order for the licensor to be able to enforce the license in case potential misuses of the Model may occur. At the same time, we strive to promote open and responsible research on generative models for content generation.
|
14 |
+
|
15 |
+
Even though downstream derivative versions of the model could be released under different licensing terms, the latter will always have to include - at minimum - the same use-based restrictions as the ones in the original license (this license). We believe in the intersection between open and responsible AI development; thus, this agreement aims to strike a balance between both in order to enable responsible open-science in the field of AI.
|
16 |
+
|
17 |
+
This License governs the use of the model (and its derivatives) and is informed by the model card associated with the model.
|
18 |
+
|
19 |
+
NOW THEREFORE, You and DeepSeek agree as follows:
|
20 |
+
|
21 |
+
1. Definitions
|
22 |
+
"License" means the terms and conditions for use, reproduction, and Distribution as defined in this document.
|
23 |
+
"Data" means a collection of information and/or content extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License.
|
24 |
+
"Output" means the results of operating a Model as embodied in informational content resulting therefrom.
|
25 |
+
"Model" means any accompanying machine-learning based assemblies (including checkpoints), consisting of learnt weights, parameters (including optimizer states), corresponding to the model architecture as embodied in the Complementary Material, that have been trained or tuned, in whole or in part on the Data, using the Complementary Material.
|
26 |
+
"Derivatives of the Model" means all modifications to the Model, works based on the Model, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of the Model, to the other model, in order to cause the other model to perform similarly to the Model, including - but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by the Model for training the other model.
|
27 |
+
"Complementary Material" means the accompanying source code and scripts used to define, run, load, benchmark or evaluate the Model, and used to prepare data for training or evaluation, if any. This includes any accompanying documentation, tutorials, examples, etc, if any.
|
28 |
+
"Distribution" means any transmission, reproduction, publication or other sharing of the Model or Derivatives of the Model to a third party, including providing the Model as a hosted service made available by electronic or other remote means - e.g. API-based or web access.
|
29 |
+
"DeepSeek" (or "we") means Beijing DeepSeek Artificial Intelligence Fundamental Technology Research Co., Ltd., Hangzhou DeepSeek Artificial Intelligence Fundamental Technology Research Co., Ltd. and/or any of their affiliates.
|
30 |
+
"You" (or "Your") means an individual or Legal Entity exercising permissions granted by this License and/or making use of the Model for whichever purpose and in any field of use, including usage of the Model in an end-use application - e.g. chatbot, translator, etc.
|
31 |
+
"Third Parties" means individuals or legal entities that are not under common control with DeepSeek or You.
|
32 |
+
|
33 |
+
Section II: INTELLECTUAL PROPERTY RIGHTS
|
34 |
+
|
35 |
+
Both copyright and patent grants apply to the Model, Derivatives of the Model and Complementary Material. The Model and Derivatives of the Model are subject to additional terms as described in Section III.
|
36 |
+
|
37 |
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, DeepSeek hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare, publicly display, publicly perform, sublicense, and distribute the Complementary Material, the Model, and Derivatives of the Model.
|
38 |
+
|
39 |
+
3. Grant of Patent License. Subject to the terms and conditions of this License and where and as applicable, DeepSeek hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this paragraph) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model and the Complementary Material, where such license applies only to those patent claims licensable by DeepSeek that are necessarily infringed by its contribution(s). If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model and/or Complementary Material constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for the Model and/or works shall terminate as of the date such litigation is asserted or filed.
|
40 |
+
|
41 |
+
|
42 |
+
Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION
|
43 |
+
|
44 |
+
4. Distribution and Redistribution. You may host for Third Party remote access purposes (e.g. software-as-a-service), reproduce and distribute copies of the Model or Derivatives of the Model thereof in any medium, with or without modifications, provided that You meet the following conditions:
|
45 |
+
a. Use-based restrictions as referenced in paragraph 5 MUST be included as an enforceable provision by You in any type of legal agreement (e.g. a license) governing the use and/or distribution of the Model or Derivatives of the Model, and You shall give notice to subsequent users You Distribute to, that the Model or Derivatives of the Model are subject to paragraph 5. This provision does not apply to the use of Complementary Material.
|
46 |
+
b. You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License;
|
47 |
+
c. You must cause any modified files to carry prominent notices stating that You changed the files;
|
48 |
+
d. You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of the Model, Derivatives of the Model.
|
49 |
+
e. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions - respecting paragraph 4.a. – for use, reproduction, or Distribution of Your modifications, or for any such Derivatives of the Model as a whole, provided Your use, reproduction, and Distribution of the Model otherwise complies with the conditions stated in this License.
|
50 |
+
|
51 |
+
5. Use-based restrictions. The restrictions set forth in Attachment A are considered Use-based restrictions. Therefore You cannot use the Model and the Derivatives of the Model for the specified restricted uses. You may use the Model subject to this License, including only for lawful purposes and in accordance with the License. Use may include creating any content with, finetuning, updating, running, training, evaluating and/or reparametrizing the Model. You shall require all of Your users who use the Model or a Derivative of the Model to comply with the terms of this paragraph (paragraph 5).
|
52 |
+
|
53 |
+
6. The Output You Generate. Except as set forth herein, DeepSeek claims no rights in the Output You generate using the Model. You are accountable for the Output you generate and its subsequent uses. No use of the output can contravene any provision as stated in the License.
|
54 |
+
|
55 |
+
Section IV: OTHER PROVISIONS
|
56 |
+
|
57 |
+
7. Updates and Runtime Restrictions. To the maximum extent permitted by law, DeepSeek reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License.
|
58 |
+
|
59 |
+
8. Trademarks and related. Nothing in this License permits You to make use of DeepSeek’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by DeepSeek.
|
60 |
+
|
61 |
+
9. Personal information, IP rights and related. This Model may contain personal information and works with IP rights. You commit to complying with applicable laws and regulations in the handling of personal information and the use of such works. Please note that DeepSeek's license granted to you to use the Model does not imply that you have obtained a legitimate basis for processing the related information or works. As an independent personal information processor and IP rights user, you need to ensure full compliance with relevant legal and regulatory requirements when handling personal information and works with IP rights that may be contained in the Model, and are willing to assume solely any risks and consequences that may arise from that.
|
62 |
+
|
63 |
+
10. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, DeepSeek provides the Model and the Complementary Material on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Model, Derivatives of the Model, and the Complementary Material and assume any risks associated with Your exercise of permissions under this License.
|
64 |
+
|
65 |
+
11. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall DeepSeek be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Model and the Complementary Material (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if DeepSeek has been advised of the possibility of such damages.
|
66 |
+
|
67 |
+
12. Accepting Warranty or Additional Liability. While redistributing the Model, Derivatives of the Model and the Complementary Material thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of DeepSeek, and only if You agree to indemnify, defend, and hold DeepSeek harmless for any liability incurred by, or claims asserted against, DeepSeek by reason of your accepting any such warranty or additional liability.
|
68 |
+
|
69 |
+
13. If any provision of this License is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.
|
70 |
+
|
71 |
+
14. Governing Law and Jurisdiction. This agreement will be governed and construed under PRC laws without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this agreement. The courts located in the domicile of Hangzhou DeepSeek Artificial Intelligence Fundamental Technology Research Co., Ltd. shall have exclusive jurisdiction of any dispute arising out of this agreement.
|
72 |
+
|
73 |
+
END OF TERMS AND CONDITIONS
|
74 |
+
|
75 |
+
Attachment A
|
76 |
+
|
77 |
+
Use Restrictions
|
78 |
+
|
79 |
+
You agree not to use the Model or Derivatives of the Model:
|
80 |
+
|
81 |
+
- In any way that violates any applicable national or international law or regulation or infringes upon the lawful rights and interests of any third party;
|
82 |
+
- For military use in any way;
|
83 |
+
- For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
|
84 |
+
- To generate or disseminate verifiably false information and/or content with the purpose of harming others;
|
85 |
+
- To generate or disseminate inappropriate content subject to applicable regulatory requirements;
|
86 |
+
- To generate or disseminate personal identifiable information without due authorization or for unreasonable use;
|
87 |
+
- To defame, disparage or otherwise harass others;
|
88 |
+
- For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation;
|
89 |
+
- For any use intended to or which has the effect of discriminating against or harming individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics;
|
90 |
+
- To exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;
|
91 |
+
- For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories.
|
Makefile
ADDED
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
print-% : ; @echo $* = $($*)
|
2 |
+
PROJECT_NAME = DeepSeek-VL
|
3 |
+
COPYRIGHT = "DeepSeek."
|
4 |
+
PROJECT_PATH = deepseek_vl
|
5 |
+
SHELL = /bin/bash
|
6 |
+
SOURCE_FOLDERS = deepseek_vl
|
7 |
+
PYTHON_FILES = $(shell find $(SOURCE_FOLDERS) -type f -name "*.py" -o -name "*.pyi") cli_chat.py inference.py
|
8 |
+
COMMIT_HASH = $(shell git log -1 --format=%h)
|
9 |
+
PATH := $(HOME)/go/bin:$(PATH)
|
10 |
+
PYTHON ?= $(shell command -v python3 || command -v python)
|
11 |
+
PYTESTOPTS ?=
|
12 |
+
|
13 |
+
.PHONY: default
|
14 |
+
default: install
|
15 |
+
|
16 |
+
# Tools Installation
|
17 |
+
|
18 |
+
check_pip_install = $(PYTHON) -m pip show $(1) &>/dev/null || (cd && $(PYTHON) -m pip install $(1) --upgrade)
|
19 |
+
check_pip_install_extra = $(PYTHON) -m pip show $(1) &>/dev/null || (cd && $(PYTHON) -m pip install $(2) --upgrade)
|
20 |
+
|
21 |
+
pylint-install:
|
22 |
+
$(call check_pip_install_extra,pylint,pylint[spelling])
|
23 |
+
$(call check_pip_install,pyenchant)
|
24 |
+
|
25 |
+
flake8-install:
|
26 |
+
$(call check_pip_install,flake8)
|
27 |
+
$(call check_pip_install,flake8-bugbear)
|
28 |
+
$(call check_pip_install,flake8-comprehensions)
|
29 |
+
$(call check_pip_install,flake8-docstrings)
|
30 |
+
$(call check_pip_install,flake8-pyi)
|
31 |
+
$(call check_pip_install,flake8-simplify)
|
32 |
+
|
33 |
+
py-format-install:
|
34 |
+
$(call check_pip_install,isort)
|
35 |
+
$(call check_pip_install_extra,black,black[jupyter])
|
36 |
+
|
37 |
+
ruff-install:
|
38 |
+
$(call check_pip_install,ruff)
|
39 |
+
|
40 |
+
mypy-install:
|
41 |
+
$(call check_pip_install,mypy)
|
42 |
+
|
43 |
+
pre-commit-install:
|
44 |
+
$(call check_pip_install,pre-commit)
|
45 |
+
$(PYTHON) -m pre_commit install --install-hooks
|
46 |
+
|
47 |
+
go-install:
|
48 |
+
# requires go >= 1.16
|
49 |
+
command -v go || (sudo apt-get install -y golang && sudo ln -sf /usr/lib/go/bin/go /usr/bin/go)
|
50 |
+
|
51 |
+
addlicense-install: go-install
|
52 |
+
command -v addlicense || go install github.com/google/addlicense@latest
|
53 |
+
|
54 |
+
addlicense: addlicense-install
|
55 |
+
addlicense -c $(COPYRIGHT) -ignore tests/coverage.xml -l mit -y 2023-$(shell date +"%Y") -check $(SOURCE_FOLDERS)
|
56 |
+
|
57 |
+
# Python linters
|
58 |
+
|
59 |
+
pylint: pylint-install
|
60 |
+
$(PYTHON) -m pylint $(PROJECT_PATH)
|
61 |
+
|
62 |
+
flake8: flake8-install
|
63 |
+
$(PYTHON) -m flake8 --count --show-source --statistics
|
64 |
+
|
65 |
+
py-format: py-format-install
|
66 |
+
$(PYTHON) -m isort --project $(PROJECT_PATH) --check $(PYTHON_FILES) && \
|
67 |
+
$(PYTHON) -m black --check $(PYTHON_FILES)
|
68 |
+
|
69 |
+
ruff: ruff-install
|
70 |
+
$(PYTHON) -m ruff check .
|
71 |
+
|
72 |
+
ruff-fix: ruff-install
|
73 |
+
$(PYTHON) -m ruff check . --fix --exit-non-zero-on-fix
|
74 |
+
|
75 |
+
mypy: mypy-install
|
76 |
+
$(PYTHON) -m mypy $(PROJECT_PATH) --install-types --non-interactive
|
77 |
+
|
78 |
+
pre-commit: pre-commit-install
|
79 |
+
$(PYTHON) -m pre_commit run --all-files
|
80 |
+
|
81 |
+
# Utility functions
|
82 |
+
|
83 |
+
lint: ruff flake8 py-format mypy pylint addlicense
|
84 |
+
|
85 |
+
format: py-format-install ruff-install addlicense-install
|
86 |
+
$(PYTHON) -m isort --project $(PROJECT_PATH) $(PYTHON_FILES)
|
87 |
+
$(PYTHON) -m black $(PYTHON_FILES)
|
88 |
+
$(PYTHON) -m ruff check . --fix --exit-zero
|
89 |
+
addlicense -c $(COPYRIGHT) -ignore tests/coverage.xml -l mit -y 2023-$(shell date +"%Y") $(SOURCE_FOLDERS) cli_chat.py inference.py
|
90 |
+
|
91 |
+
clean-py:
|
92 |
+
find . -type f -name '*.py[co]' -delete
|
93 |
+
find . -depth -type d -name "__pycache__" -exec rm -r "{}" +
|
94 |
+
find . -depth -type d -name ".ruff_cache" -exec rm -r "{}" +
|
95 |
+
find . -depth -type d -name ".mypy_cache" -exec rm -r "{}" +
|
96 |
+
|
97 |
+
clean: clean-py
|
README.md
ADDED
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<!-- markdownlint-disable first-line-h1 -->
|
2 |
+
<!-- markdownlint-disable html -->
|
3 |
+
<!-- markdownlint-disable no-duplicate-header -->
|
4 |
+
|
5 |
+
<div align="center">
|
6 |
+
<img src="images/logo.svg" width="60%" alt="DeepSeek LLM" />
|
7 |
+
</div>
|
8 |
+
<hr>
|
9 |
+
<div align="center">
|
10 |
+
|
11 |
+
<a href="https://www.deepseek.com/" target="_blank">
|
12 |
+
<img alt="Homepage" src="images/badge.svg" />
|
13 |
+
</a>
|
14 |
+
<a href="" target="_blank">
|
15 |
+
<img alt="Chat" src="https://img.shields.io/badge/🤖%20Chat-DeepSeek%20VL-536af5?color=536af5&logoColor=white" />
|
16 |
+
</a>
|
17 |
+
<a href="https://huggingface.co/deepseek-ai" target="_blank">
|
18 |
+
<img alt="Hugging Face" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-DeepSeek%20AI-ffc107?color=ffc107&logoColor=white" />
|
19 |
+
</a>
|
20 |
+
|
21 |
+
</div>
|
22 |
+
|
23 |
+
|
24 |
+
<div align="center">
|
25 |
+
|
26 |
+
<a href="https://discord.gg/Tc7c45Zzu5" target="_blank">
|
27 |
+
<img alt="Discord" src="https://img.shields.io/badge/Discord-DeepSeek%20AI-7289da?logo=discord&logoColor=white&color=7289da" />
|
28 |
+
</a>
|
29 |
+
<a href="images/qr.jpeg" target="_blank">
|
30 |
+
<img alt="Wechat" src="https://img.shields.io/badge/WeChat-DeepSeek%20AI-brightgreen?logo=wechat&logoColor=white" />
|
31 |
+
</a>
|
32 |
+
<a href="https://twitter.com/deepseek_ai" target="_blank">
|
33 |
+
<img alt="Twitter Follow" src="https://img.shields.io/badge/Twitter-deepseek_ai-white?logo=x&logoColor=white" />
|
34 |
+
</a>
|
35 |
+
|
36 |
+
</div>
|
37 |
+
|
38 |
+
<div align="center">
|
39 |
+
|
40 |
+
<a href="LICENSE-CODE">
|
41 |
+
<img alt="Code License" src="https://img.shields.io/badge/Code_License-MIT-f5de53?&color=f5de53">
|
42 |
+
</a>
|
43 |
+
<a href="LICENSE-MODEL">
|
44 |
+
<img alt="Model License" src="https://img.shields.io/badge/Model_License-Model_Agreement-f5de53?&color=f5de53">
|
45 |
+
</a>
|
46 |
+
</div>
|
47 |
+
|
48 |
+
|
49 |
+
<p align="center">
|
50 |
+
<a href="https://github.com/deepseek-ai/DeepSeek-VL2/tree/main?tab=readme-ov-file#3-model-download"><b>📥 Model Download</b></a> |
|
51 |
+
<a href="https://github.com/deepseek-ai/DeepSeek-VL2/tree/main?tab=readme-ov-file#4-quick-start"><b>⚡ Quick Start</b></a> |
|
52 |
+
<a href="https://github.com/deepseek-ai/DeepSeek-VL2/tree/main?tab=readme-ov-file#5-license"><b>📜 License</b></a> |
|
53 |
+
<a href="https://github.com/deepseek-ai/DeepSeek-VL2/tree/main?tab=readme-ov-file#6-citation"><b>📖 Citation</b></a> <br>
|
54 |
+
<a href="./DeepSeek_VL2_paper.pdf"><b>📄 Paper Link</b></a> |
|
55 |
+
<a href="https://arxiv.org/abs/2412.10302"><b>📄 Arxiv Paper Link</b></a> |
|
56 |
+
<a href=""><b>👁️ Demo</b></a>
|
57 |
+
</p>
|
58 |
+
|
59 |
+
## 1. Introduction
|
60 |
+
|
61 |
+
Introducing DeepSeek-VL2, an advanced series of large Mixture-of-Experts (MoE) Vision-Language Models that significantly improves upon its predecessor, DeepSeek-VL. DeepSeek-VL2 demonstrates superior capabilities across various tasks, including but not limited to visual question answering, optical character recognition, document/table/chart understanding, and visual grounding. Our model series is composed of three variants: DeepSeek-VL2-Tiny, DeepSeek-VL2-Small and DeepSeek-VL2, with 1.0B, 2.8B and 4.5B activated parameters respectively.
|
62 |
+
DeepSeek-VL2 achieves competitive or state-of-the-art performance with similar or fewer activated parameters compared to existing open-source dense and MoE-based models.
|
63 |
+
|
64 |
+
|
65 |
+
[DeepSeek-VL2: Mixture-of-Experts Vision-Language Models for Advanced Multimodal Understanding]()
|
66 |
+
|
67 |
+
Zhiyu Wu*, Xiaokang Chen*, Zizheng Pan*, Xingchao Liu*, Wen Liu**, Damai Dai, Huazuo Gao, Yiyang Ma, Chengyue Wu, Bingxuan Wang, Zhenda Xie, Yu Wu, Kai Hu, Jiawei Wang, Yaofeng Sun, Yukun Li, Yishi Piao, Kang Guan, Aixin Liu, Xin Xie, Yuxiang You, Kai Dong, Xingkai Yu, Haowei Zhang, Liang Zhao, Yisong Wang, Chong Ruan*** (* Equal Contribution, ** Project Lead, *** Corresponding author)
|
68 |
+
|
69 |
+
![](./images/vl2_teaser.jpeg)
|
70 |
+
|
71 |
+
## 2. Release
|
72 |
+
✅ <b>2024-12-25</b>: Gradio Demo Example, Incremental Prefilling and VLMEvalKit Support.
|
73 |
+
|
74 |
+
✅ <b>2024-12-13</b>: DeepSeek-VL2 family released, including <code>DeepSeek-VL2-tiny</code>, <code>DeepSeek-VL2-small</code>, <code>DeepSeek-VL2</code>.
|
75 |
+
|
76 |
+
## 3. Model Download
|
77 |
+
|
78 |
+
We release the DeepSeek-VL2 family, including <code>DeepSeek-VL2-tiny</code>, <code>DeepSeek-VL2-small</code>, <code>DeepSeek-VL2</code>.
|
79 |
+
To support a broader and more diverse range of research within both academic and commercial communities.
|
80 |
+
Please note that the use of this model is subject to the terms outlined in [License section](#5-license).
|
81 |
+
|
82 |
+
### Huggingface
|
83 |
+
|
84 |
+
| Model | Sequence Length | Download |
|
85 |
+
|--------------|-----------------|-----------------------------------------------------------------------------|
|
86 |
+
| DeepSeek-VL2-tiny | 4096 | [🤗 Hugging Face](https://huggingface.co/deepseek-ai/deepseek-vl2-tiny) |
|
87 |
+
| DeepSeek-VL2-small | 4096 | [🤗 Hugging Face](https://huggingface.co/deepseek-ai/deepseek-vl2-small) |
|
88 |
+
| DeepSeek-VL2 | 4096 | [🤗 Hugging Face](https://huggingface.co/deepseek-ai/deepseek-vl2) |
|
89 |
+
|
90 |
+
|
91 |
+
## 4. Quick Start
|
92 |
+
|
93 |
+
### Installation
|
94 |
+
|
95 |
+
On the basis of `Python >= 3.8` environment, install the necessary dependencies by running the following command:
|
96 |
+
|
97 |
+
```shell
|
98 |
+
pip install -e .
|
99 |
+
```
|
100 |
+
|
101 |
+
### Simple Inference Example with One Image
|
102 |
+
|
103 |
+
**Note: You may need 80GB GPU memory to run this script with deepseek-vl2-small and even larger for deepseek-vl2.**
|
104 |
+
|
105 |
+
```python
|
106 |
+
import torch
|
107 |
+
from transformers import AutoModelForCausalLM
|
108 |
+
|
109 |
+
from deepseek_vl2.models import DeepseekVLV2Processor, DeepseekVLV2ForCausalLM
|
110 |
+
from deepseek_vl2.utils.io import load_pil_images
|
111 |
+
|
112 |
+
|
113 |
+
# specify the path to the model
|
114 |
+
model_path = "deepseek-ai/deepseek-vl2-tiny"
|
115 |
+
vl_chat_processor: DeepseekVLV2Processor = DeepseekVLV2Processor.from_pretrained(model_path)
|
116 |
+
tokenizer = vl_chat_processor.tokenizer
|
117 |
+
|
118 |
+
vl_gpt: DeepseekVLV2ForCausalLM = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True)
|
119 |
+
vl_gpt = vl_gpt.to(torch.bfloat16).cuda().eval()
|
120 |
+
|
121 |
+
## single image conversation example
|
122 |
+
## Please note that <|ref|> and <|/ref|> are designed specifically for the object localization feature. These special tokens are not required for normal conversations.
|
123 |
+
## If you would like to experience the grounded captioning functionality (responses that include both object localization and reasoning), you need to add the special token <|grounding|> at the beginning of the prompt. Examples could be found in Figure 9 of our paper.
|
124 |
+
conversation = [
|
125 |
+
{
|
126 |
+
"role": "<|User|>",
|
127 |
+
"content": "<image>\n<|ref|>The giraffe at the back.<|/ref|>.",
|
128 |
+
"images": ["./images/visual_grounding_1.jpeg"],
|
129 |
+
},
|
130 |
+
{"role": "<|Assistant|>", "content": ""},
|
131 |
+
]
|
132 |
+
|
133 |
+
# load images and prepare for inputs
|
134 |
+
pil_images = load_pil_images(conversation)
|
135 |
+
prepare_inputs = vl_chat_processor(
|
136 |
+
conversations=conversation,
|
137 |
+
images=pil_images,
|
138 |
+
force_batchify=True,
|
139 |
+
system_prompt=""
|
140 |
+
).to(vl_gpt.device)
|
141 |
+
|
142 |
+
# run image encoder to get the image embeddings
|
143 |
+
inputs_embeds = vl_gpt.prepare_inputs_embeds(**prepare_inputs)
|
144 |
+
|
145 |
+
# run the model to get the response
|
146 |
+
outputs = vl_gpt.language.generate(
|
147 |
+
inputs_embeds=inputs_embeds,
|
148 |
+
attention_mask=prepare_inputs.attention_mask,
|
149 |
+
pad_token_id=tokenizer.eos_token_id,
|
150 |
+
bos_token_id=tokenizer.bos_token_id,
|
151 |
+
eos_token_id=tokenizer.eos_token_id,
|
152 |
+
max_new_tokens=512,
|
153 |
+
do_sample=False,
|
154 |
+
use_cache=True
|
155 |
+
)
|
156 |
+
|
157 |
+
answer = tokenizer.decode(outputs[0].cpu().tolist(), skip_special_tokens=False)
|
158 |
+
print(f"{prepare_inputs['sft_format'][0]}", answer)
|
159 |
+
```
|
160 |
+
|
161 |
+
And the output is something like:
|
162 |
+
```
|
163 |
+
<|User|>: <image>
|
164 |
+
<|ref|>The giraffe at the back.<|/ref|>.
|
165 |
+
|
166 |
+
<|Assistant|>: <|ref|>The giraffe at the back.<|/ref|><|det|>[[580, 270, 999, 900]]<|/det|><|end▁of▁sentence|>
|
167 |
+
```
|
168 |
+
|
169 |
+
### Simple Inference Example with Multiple Images
|
170 |
+
|
171 |
+
**Note: You may need 80GB GPU memory to run this script with deepseek-vl2-small and even larger for deepseek-vl2.**
|
172 |
+
|
173 |
+
```python
|
174 |
+
import torch
|
175 |
+
from transformers import AutoModelForCausalLM
|
176 |
+
|
177 |
+
from deepseek_vl2.models import DeepseekVLV2Processor, DeepseekVLV2ForCausalLM
|
178 |
+
from deepseek_vl2.utils.io import load_pil_images
|
179 |
+
|
180 |
+
|
181 |
+
# specify the path to the model
|
182 |
+
model_path = "deepseek-ai/deepseek-vl2-tiny"
|
183 |
+
vl_chat_processor: DeepseekVLV2Processor = DeepseekVLV2Processor.from_pretrained(model_path)
|
184 |
+
tokenizer = vl_chat_processor.tokenizer
|
185 |
+
|
186 |
+
vl_gpt: DeepseekVLV2ForCausalLM = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True)
|
187 |
+
vl_gpt = vl_gpt.to(torch.bfloat16).cuda().eval()
|
188 |
+
|
189 |
+
# multiple images/interleaved image-text
|
190 |
+
conversation = [
|
191 |
+
{
|
192 |
+
"role": "<|User|>",
|
193 |
+
"content": "This is image_1: <image>\n"
|
194 |
+
"This is image_2: <image>\n"
|
195 |
+
"This is image_3: <image>\n Can you tell me what are in the images?",
|
196 |
+
"images": [
|
197 |
+
"images/multi_image_1.jpeg",
|
198 |
+
"images/multi_image_2.jpeg",
|
199 |
+
"images/multi_image_3.jpeg",
|
200 |
+
],
|
201 |
+
},
|
202 |
+
{"role": "<|Assistant|>", "content": ""}
|
203 |
+
]
|
204 |
+
|
205 |
+
# load images and prepare for inputs
|
206 |
+
pil_images = load_pil_images(conversation)
|
207 |
+
prepare_inputs = vl_chat_processor(
|
208 |
+
conversations=conversation,
|
209 |
+
images=pil_images,
|
210 |
+
force_batchify=True,
|
211 |
+
system_prompt=""
|
212 |
+
).to(vl_gpt.device)
|
213 |
+
|
214 |
+
# run image encoder to get the image embeddings
|
215 |
+
inputs_embeds = vl_gpt.prepare_inputs_embeds(**prepare_inputs)
|
216 |
+
|
217 |
+
# run the model to get the response
|
218 |
+
outputs = vl_gpt.language.generate(
|
219 |
+
inputs_embeds=inputs_embeds,
|
220 |
+
attention_mask=prepare_inputs.attention_mask,
|
221 |
+
pad_token_id=tokenizer.eos_token_id,
|
222 |
+
bos_token_id=tokenizer.bos_token_id,
|
223 |
+
eos_token_id=tokenizer.eos_token_id,
|
224 |
+
max_new_tokens=512,
|
225 |
+
do_sample=False,
|
226 |
+
use_cache=True
|
227 |
+
)
|
228 |
+
|
229 |
+
answer = tokenizer.decode(outputs[0].cpu().tolist(), skip_special_tokens=False)
|
230 |
+
print(f"{prepare_inputs['sft_format'][0]}", answer)
|
231 |
+
```
|
232 |
+
|
233 |
+
And the output is something like:
|
234 |
+
```
|
235 |
+
<|User|>: This is image_1: <image>
|
236 |
+
This is image_2: <image>
|
237 |
+
This is image_3: <image>
|
238 |
+
Can you tell me what are in the images?
|
239 |
+
|
240 |
+
<|Assistant|>: The images show three different types of vegetables. Image_1 features carrots, which are orange with green tops. Image_2 displays corn cobs, which are yellow with green husks. Image_3 contains raw pork ribs, which are pinkish-red with some marbling.<|end▁of▁sentence|>
|
241 |
+
```
|
242 |
+
|
243 |
+
### Simple Inference Example with Incremental Prefilling
|
244 |
+
|
245 |
+
**Note: We use incremental prefilling to inference within 40GB GPU using deepseek-vl2-small.**
|
246 |
+
|
247 |
+
```python
|
248 |
+
import torch
|
249 |
+
from transformers import AutoModelForCausalLM
|
250 |
+
|
251 |
+
from deepseek_vl2.models import DeepseekVLV2Processor, DeepseekVLV2ForCausalLM
|
252 |
+
from deepseek_vl2.utils.io import load_pil_images
|
253 |
+
|
254 |
+
|
255 |
+
# specify the path to the model
|
256 |
+
model_path = "deepseek-ai/deepseek-vl2-small"
|
257 |
+
vl_chat_processor: DeepseekVLV2Processor = DeepseekVLV2Processor.from_pretrained(model_path)
|
258 |
+
tokenizer = vl_chat_processor.tokenizer
|
259 |
+
|
260 |
+
vl_gpt: DeepseekVLV2ForCausalLM = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True)
|
261 |
+
vl_gpt = vl_gpt.to(torch.bfloat16).cuda().eval()
|
262 |
+
|
263 |
+
# multiple images/interleaved image-text
|
264 |
+
conversation = [
|
265 |
+
{
|
266 |
+
"role": "<|User|>",
|
267 |
+
"content": "This is image_1: <image>\n"
|
268 |
+
"This is image_2: <image>\n"
|
269 |
+
"This is image_3: <image>\n Can you tell me what are in the images?",
|
270 |
+
"images": [
|
271 |
+
"images/multi_image_1.jpeg",
|
272 |
+
"images/multi_image_2.jpeg",
|
273 |
+
"images/multi_image_3.jpeg",
|
274 |
+
],
|
275 |
+
},
|
276 |
+
{"role": "<|Assistant|>", "content": ""}
|
277 |
+
]
|
278 |
+
|
279 |
+
# load images and prepare for inputs
|
280 |
+
pil_images = load_pil_images(conversation)
|
281 |
+
prepare_inputs = vl_chat_processor(
|
282 |
+
conversations=conversation,
|
283 |
+
images=pil_images,
|
284 |
+
force_batchify=True,
|
285 |
+
system_prompt=""
|
286 |
+
).to(vl_gpt.device)
|
287 |
+
|
288 |
+
with torch.no_grad():
|
289 |
+
# run image encoder to get the image embeddings
|
290 |
+
inputs_embeds = vl_gpt.prepare_inputs_embeds(**prepare_inputs)
|
291 |
+
|
292 |
+
# incremental_prefilling when using 40G GPU for vl2-small
|
293 |
+
inputs_embeds, past_key_values = vl_gpt.incremental_prefilling(
|
294 |
+
input_ids=prepare_inputs.input_ids,
|
295 |
+
images=prepare_inputs.images,
|
296 |
+
images_seq_mask=prepare_inputs.images_seq_mask,
|
297 |
+
images_spatial_crop=prepare_inputs.images_spatial_crop,
|
298 |
+
attention_mask=prepare_inputs.attention_mask,
|
299 |
+
chunk_size=512 # prefilling size
|
300 |
+
)
|
301 |
+
|
302 |
+
# run the model to get the response
|
303 |
+
outputs = vl_gpt.generate(
|
304 |
+
inputs_embeds=inputs_embeds,
|
305 |
+
input_ids=prepare_inputs.input_ids,
|
306 |
+
images=prepare_inputs.images,
|
307 |
+
images_seq_mask=prepare_inputs.images_seq_mask,
|
308 |
+
images_spatial_crop=prepare_inputs.images_spatial_crop,
|
309 |
+
attention_mask=prepare_inputs.attention_mask,
|
310 |
+
past_key_values=past_key_values,
|
311 |
+
|
312 |
+
pad_token_id=tokenizer.eos_token_id,
|
313 |
+
bos_token_id=tokenizer.bos_token_id,
|
314 |
+
eos_token_id=tokenizer.eos_token_id,
|
315 |
+
max_new_tokens=512,
|
316 |
+
|
317 |
+
do_sample=False,
|
318 |
+
use_cache=True,
|
319 |
+
)
|
320 |
+
|
321 |
+
answer = tokenizer.decode(outputs[0][len(prepare_inputs.input_ids[0]):].cpu().tolist(), skip_special_tokens=False)
|
322 |
+
|
323 |
+
print(f"{prepare_inputs['sft_format'][0]}", answer)
|
324 |
+
```
|
325 |
+
|
326 |
+
And the output is something like:
|
327 |
+
```
|
328 |
+
<|User|>: This is image_1: <image>
|
329 |
+
This is image_2: <image>
|
330 |
+
This is image_3: <image>
|
331 |
+
Can you tell me what are in the images?
|
332 |
+
|
333 |
+
<|Assistant|>: The first image contains carrots. The second image contains corn. The third image contains meat.<|end▁of▁sentence|>
|
334 |
+
```
|
335 |
+
|
336 |
+
### Full Inference Example
|
337 |
+
```shell
|
338 |
+
# without incremental prefilling
|
339 |
+
CUDA_VISIBLE_DEVICES=0 python inference.py --model_path "deepseek-ai/deepseek-vl2"
|
340 |
+
|
341 |
+
# with incremental prefilling, when using 40G GPU for vl2-small
|
342 |
+
CUDA_VISIBLE_DEVICES=0 python inference.py --model_path "deepseek-ai/deepseek-vl2-small" --chunk_size 512
|
343 |
+
|
344 |
+
```
|
345 |
+
|
346 |
+
|
347 |
+
### Gradio Demo
|
348 |
+
|
349 |
+
* Install the necessary dependencies:
|
350 |
+
```shell
|
351 |
+
pip install -e .[gradio]
|
352 |
+
```
|
353 |
+
|
354 |
+
* then run the following command:
|
355 |
+
|
356 |
+
```shell
|
357 |
+
# vl2-tiny, 3.37B-MoE in total, activated 1B, can be run on a single GPU < 40GB
|
358 |
+
CUDA_VISIBLE_DEVICES=2 python web_demo.py \
|
359 |
+
--model_name "deepseek-ai/deepseek-vl2-tiny" \
|
360 |
+
--port 37914
|
361 |
+
|
362 |
+
|
363 |
+
# vl2-small, 16.1B-MoE in total, activated 2.4B
|
364 |
+
# If run on A100 40GB GPU, you need to set the `--chunk_size 512` for incremental prefilling for saving memory and it might be slow.
|
365 |
+
# If run on > 40GB GPU, you can ignore the `--chunk_size 512` for faster response.
|
366 |
+
CUDA_VISIBLE_DEVICES=2 python web_demo.py \
|
367 |
+
--model_name "deepseek-ai/deepseek-vl2-small" \
|
368 |
+
--port 37914 \
|
369 |
+
--chunk_size 512
|
370 |
+
|
371 |
+
# # vl27.5-MoE in total, activated 4.2B
|
372 |
+
CUDA_VISIBLE_DEVICES=2 python web_demo.py \
|
373 |
+
--model_name "deepseek-ai/deepseek-vl2" \
|
374 |
+
--port 37914
|
375 |
+
```
|
376 |
+
|
377 |
+
* **Important**: This is a basic and native demo implementation without any deployment optimizations, which may result in slower performance. For production environments, consider using optimized deployment solutions, such as vllm, sglang, lmdeploy, etc. These optimizations will help achieve faster response times and better cost efficiency.
|
378 |
+
|
379 |
+
## 5. License
|
380 |
+
|
381 |
+
This code repository is licensed under [MIT License](./LICENSE-CODE). The use of DeepSeek-VL2 models is subject to [DeepSeek Model License](./LICENSE-MODEL). DeepSeek-VL2 series supports commercial use.
|
382 |
+
|
383 |
+
## 6. Citation
|
384 |
+
|
385 |
+
```
|
386 |
+
@misc{wu2024deepseekvl2mixtureofexpertsvisionlanguagemodels,
|
387 |
+
title={DeepSeek-VL2: Mixture-of-Experts Vision-Language Models for Advanced Multimodal Understanding},
|
388 |
+
author={Zhiyu Wu and Xiaokang Chen and Zizheng Pan and Xingchao Liu and Wen Liu and Damai Dai and Huazuo Gao and Yiyang Ma and Chengyue Wu and Bingxuan Wang and Zhenda Xie and Yu Wu and Kai Hu and Jiawei Wang and Yaofeng Sun and Yukun Li and Yishi Piao and Kang Guan and Aixin Liu and Xin Xie and Yuxiang You and Kai Dong and Xingkai Yu and Haowei Zhang and Liang Zhao and Yisong Wang and Chong Ruan},
|
389 |
+
year={2024},
|
390 |
+
eprint={2412.10302},
|
391 |
+
archivePrefix={arXiv},
|
392 |
+
primaryClass={cs.CV},
|
393 |
+
url={https://arxiv.org/abs/2412.10302},
|
394 |
+
}
|
395 |
+
```
|
396 |
+
|
397 |
+
## 7. Contact
|
398 |
+
|
399 |
+
If you have any questions, please raise an issue or contact us at [service@deepseek.com](mailto:service@deepseek.com).
|
deepseek_vl2/__init__.py
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2023-2024 DeepSeek.
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of
|
4 |
+
# this software and associated documentation files (the "Software"), to deal in
|
5 |
+
# the Software without restriction, including without limitation the rights to
|
6 |
+
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
7 |
+
# the Software, and to permit persons to whom the Software is furnished to do so,
|
8 |
+
# subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in all
|
11 |
+
# copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
15 |
+
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
16 |
+
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
17 |
+
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
18 |
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
19 |
+
|
20 |
+
|
21 |
+
# check if python version is above 3.10
|
22 |
+
import sys
|
23 |
+
|
24 |
+
if sys.version_info >= (3, 10):
|
25 |
+
print("Python version is above 3.10, patching the collections module.")
|
26 |
+
# Monkey patch collections
|
27 |
+
import collections
|
28 |
+
import collections.abc
|
29 |
+
|
30 |
+
for type_name in collections.abc.__all__:
|
31 |
+
setattr(collections, type_name, getattr(collections.abc, type_name))
|
deepseek_vl2/models/__init__.py
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2023-2024 DeepSeek.
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of
|
4 |
+
# this software and associated documentation files (the "Software"), to deal in
|
5 |
+
# the Software without restriction, including without limitation the rights to
|
6 |
+
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
7 |
+
# the Software, and to permit persons to whom the Software is furnished to do so,
|
8 |
+
# subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in all
|
11 |
+
# copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
15 |
+
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
16 |
+
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
17 |
+
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
18 |
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
19 |
+
|
20 |
+
from .processing_deepseek_vl_v2 import DeepseekVLV2Processor
|
21 |
+
from .modeling_deepseek_vl_v2 import DeepseekVLV2ForCausalLM
|
22 |
+
|
23 |
+
__all__ = [
|
24 |
+
"DeepseekVLV2Processor",
|
25 |
+
"DeepseekVLV2ForCausalLM",
|
26 |
+
]
|
deepseek_vl2/models/configuration_deepseek.py
ADDED
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers.configuration_utils import PretrainedConfig
|
2 |
+
from transformers.utils import logging
|
3 |
+
|
4 |
+
logger = logging.get_logger(__name__)
|
5 |
+
|
6 |
+
DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
7 |
+
class DeepseekV2Config(PretrainedConfig):
|
8 |
+
r"""
|
9 |
+
This is the configuration class to store the configuration of a [`DeepseekV2Model`]. It is used to instantiate an DeepSeek
|
10 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
11 |
+
defaults will yield a similar configuration to that of the DeepSeek-V2 with multi-latent attention.
|
12 |
+
|
13 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
14 |
+
documentation from [`PretrainedConfig`] for more information.
|
15 |
+
|
16 |
+
|
17 |
+
Args:
|
18 |
+
vocab_size (`int`, *optional*, defaults to 102400):
|
19 |
+
Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
|
20 |
+
`inputs_ids` passed when calling [`DeepseekV2Model`]
|
21 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
22 |
+
Dimension of the hidden representations.
|
23 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
24 |
+
Dimension of the MLP representations.
|
25 |
+
moe_intermediate_size (`int`, *optional*, defaults to 1407):
|
26 |
+
Dimension of the MoE representations.
|
27 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
28 |
+
Number of hidden layers in the Transformer decoder.
|
29 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
30 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
31 |
+
n_shared_experts (`int`, *optional*, defaults to None):
|
32 |
+
Number of shared experts, None means dense model.
|
33 |
+
n_routed_experts (`int`, *optional*, defaults to None):
|
34 |
+
Number of routed experts, None means dense model.
|
35 |
+
routed_scaling_factor (`float`, *optional*, defaults to 1.0):
|
36 |
+
Scaling factor or routed experts.
|
37 |
+
topk_method (`str`, *optional*, defaults to `gready`):
|
38 |
+
Topk method used in routed gate.
|
39 |
+
n_group (`int`, *optional*, defaults to None):
|
40 |
+
Number of groups for routed experts.
|
41 |
+
topk_group (`int`, *optional*, defaults to None):
|
42 |
+
Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
|
43 |
+
num_experts_per_tok (`int`, *optional*, defaults to None):
|
44 |
+
Number of selected experts, None means dense model.
|
45 |
+
moe_layer_freq (`int`, *optional*, defaults to 1):
|
46 |
+
The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
|
47 |
+
first_k_dense_replace (`int`, *optional*, defaults to 0):
|
48 |
+
Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
|
49 |
+
\--k dense layers--/
|
50 |
+
norm_topk_prob (`bool`, *optional*, defaults to False):
|
51 |
+
Whether to normalize the weights of the routed experts.
|
52 |
+
scoring_func (`str`, *optional*, defaults to 'softmax'):
|
53 |
+
Method of computing expert weights.
|
54 |
+
aux_loss_alpha (`float`, *optional*, defaults to 0.001):
|
55 |
+
Auxiliary loss weight coefficient.
|
56 |
+
seq_aux = (`bool`, *optional*, defaults to True):
|
57 |
+
Whether to compute the auxiliary loss for each individual sample.
|
58 |
+
num_key_value_heads (`int`, *optional*):
|
59 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
60 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
61 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
62 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
63 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
64 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
65 |
+
`num_attention_heads`.
|
66 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
67 |
+
The non-linear activation function (function or string) in the decoder.
|
68 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
69 |
+
The maximum sequence length that this model might ever be used with.
|
70 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
71 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
72 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
73 |
+
The epsilon used by the rms normalization layers.
|
74 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
75 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
76 |
+
relevant if `config.is_decoder=True`.
|
77 |
+
pad_token_id (`int`, *optional*):
|
78 |
+
Padding token id.
|
79 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
80 |
+
Beginning of stream token id.
|
81 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
82 |
+
End of stream token id.
|
83 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
84 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
85 |
+
document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
|
86 |
+
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
87 |
+
issue](https://github.com/pytorch/pytorch/issues/76232).
|
88 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
89 |
+
Whether to tie weight embeddings
|
90 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
91 |
+
The base period of the RoPE embeddings.
|
92 |
+
rope_scaling (`Dict`, *optional*):
|
93 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
94 |
+
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
|
95 |
+
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
96 |
+
`max_position_embeddings` to the expected new maximum.
|
97 |
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
98 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
99 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
100 |
+
The dropout ratio for the attention probabilities.
|
101 |
+
use_mla (`bool`, *optional*, defaults to `True`): Use multi-latent attention or multi-head attention. If True,
|
102 |
+
the model will use multi-latent attention, otherwise, it will use multi-head attention.
|
103 |
+
|
104 |
+
```python
|
105 |
+
>>> from transformers import DeepseekV2Model, DeepseekV2Config
|
106 |
+
|
107 |
+
>>> # Initializing a Deepseek-V2 style configuration
|
108 |
+
>>> configuration = DeepseekV2Config()
|
109 |
+
|
110 |
+
>>> # Accessing the model configuration
|
111 |
+
>>> configuration = model.config
|
112 |
+
```"""
|
113 |
+
|
114 |
+
model_type = "deepseek_v2"
|
115 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
116 |
+
|
117 |
+
def __init__(
|
118 |
+
self,
|
119 |
+
vocab_size=102400,
|
120 |
+
hidden_size=4096,
|
121 |
+
intermediate_size=11008,
|
122 |
+
moe_intermediate_size = 1407,
|
123 |
+
num_hidden_layers=30,
|
124 |
+
num_attention_heads=32,
|
125 |
+
num_key_value_heads=32,
|
126 |
+
n_shared_experts = None,
|
127 |
+
n_routed_experts = None,
|
128 |
+
ep_size = 1,
|
129 |
+
routed_scaling_factor = 1.0,
|
130 |
+
kv_lora_rank = 512,
|
131 |
+
q_lora_rank = 1536,
|
132 |
+
qk_rope_head_dim = 64,
|
133 |
+
v_head_dim = 128,
|
134 |
+
qk_nope_head_dim = 128,
|
135 |
+
topk_method = 'gready',
|
136 |
+
n_group = None,
|
137 |
+
topk_group = None,
|
138 |
+
num_experts_per_tok = None,
|
139 |
+
moe_layer_freq = 1,
|
140 |
+
first_k_dense_replace = 0,
|
141 |
+
norm_topk_prob = False,
|
142 |
+
scoring_func = 'softmax',
|
143 |
+
aux_loss_alpha = 0.001,
|
144 |
+
seq_aux = True,
|
145 |
+
hidden_act="silu",
|
146 |
+
max_position_embeddings=2048,
|
147 |
+
initializer_range=0.02,
|
148 |
+
rms_norm_eps=1e-6,
|
149 |
+
use_cache=True,
|
150 |
+
pad_token_id=None,
|
151 |
+
bos_token_id=100000,
|
152 |
+
eos_token_id=100001,
|
153 |
+
pretraining_tp=1,
|
154 |
+
tie_word_embeddings=False,
|
155 |
+
rope_theta=10000.0,
|
156 |
+
rope_scaling=None,
|
157 |
+
attention_bias=False,
|
158 |
+
attention_dropout=0.0,
|
159 |
+
use_mla=True,
|
160 |
+
**kwargs,
|
161 |
+
):
|
162 |
+
self.vocab_size = vocab_size
|
163 |
+
self.max_position_embeddings = max_position_embeddings
|
164 |
+
self.hidden_size = hidden_size
|
165 |
+
self.intermediate_size = intermediate_size
|
166 |
+
self.moe_intermediate_size = moe_intermediate_size
|
167 |
+
self.num_hidden_layers = num_hidden_layers
|
168 |
+
self.num_attention_heads = num_attention_heads
|
169 |
+
self.n_shared_experts = n_shared_experts
|
170 |
+
self.n_routed_experts = n_routed_experts
|
171 |
+
self.ep_size = ep_size
|
172 |
+
self.routed_scaling_factor = routed_scaling_factor
|
173 |
+
self.kv_lora_rank = kv_lora_rank
|
174 |
+
self.q_lora_rank = q_lora_rank
|
175 |
+
self.qk_rope_head_dim = qk_rope_head_dim
|
176 |
+
self.v_head_dim = v_head_dim
|
177 |
+
self.qk_nope_head_dim = qk_nope_head_dim
|
178 |
+
self.topk_method = topk_method
|
179 |
+
self.n_group = n_group
|
180 |
+
self.topk_group = topk_group
|
181 |
+
self.num_experts_per_tok = num_experts_per_tok
|
182 |
+
self.moe_layer_freq = moe_layer_freq
|
183 |
+
self.first_k_dense_replace = first_k_dense_replace
|
184 |
+
self.norm_topk_prob = norm_topk_prob
|
185 |
+
self.scoring_func = scoring_func
|
186 |
+
self.aux_loss_alpha = aux_loss_alpha
|
187 |
+
self.seq_aux = seq_aux
|
188 |
+
# for backward compatibility
|
189 |
+
if num_key_value_heads is None:
|
190 |
+
num_key_value_heads = num_attention_heads
|
191 |
+
|
192 |
+
self.num_key_value_heads = num_key_value_heads
|
193 |
+
self.hidden_act = hidden_act
|
194 |
+
self.initializer_range = initializer_range
|
195 |
+
self.rms_norm_eps = float(rms_norm_eps)
|
196 |
+
self.pretraining_tp = pretraining_tp
|
197 |
+
self.use_cache = use_cache
|
198 |
+
self.rope_theta = rope_theta
|
199 |
+
self.rope_scaling = rope_scaling
|
200 |
+
self.attention_bias = attention_bias
|
201 |
+
self.attention_dropout = attention_dropout
|
202 |
+
self.use_mla = use_mla
|
203 |
+
|
204 |
+
super().__init__(
|
205 |
+
pad_token_id=pad_token_id,
|
206 |
+
bos_token_id=bos_token_id,
|
207 |
+
eos_token_id=eos_token_id,
|
208 |
+
tie_word_embeddings=tie_word_embeddings,
|
209 |
+
**kwargs,
|
210 |
+
)
|
deepseek_vl2/models/conversation.py
ADDED
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
From https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py
|
3 |
+
"""
|
4 |
+
|
5 |
+
import dataclasses
|
6 |
+
from enum import IntEnum, auto
|
7 |
+
from typing import Any, Dict, List
|
8 |
+
|
9 |
+
|
10 |
+
class SeparatorStyle(IntEnum):
|
11 |
+
"""Separator styles."""
|
12 |
+
|
13 |
+
DeepSeek = auto()
|
14 |
+
DeepSeekV2 = auto()
|
15 |
+
PLAIN = auto()
|
16 |
+
ALIGNMENT = auto()
|
17 |
+
|
18 |
+
|
19 |
+
@dataclasses.dataclass
|
20 |
+
class Conversation:
|
21 |
+
"""A class that manages prompt templates and keeps all conversation history."""
|
22 |
+
|
23 |
+
# The name of this template
|
24 |
+
name: str
|
25 |
+
# The template of the system prompt
|
26 |
+
system_template: str = "{system_message}"
|
27 |
+
# The system message
|
28 |
+
system_message: str = ""
|
29 |
+
# The names of two roles
|
30 |
+
roles: List[str] = (("USER", "ASSISTANT"),)
|
31 |
+
# All messages. Each item is (role, message).
|
32 |
+
messages: List[List[str]] = ()
|
33 |
+
# The number of few shot examples
|
34 |
+
offset: int = 0
|
35 |
+
# The separator style and configurations
|
36 |
+
sep_style: SeparatorStyle = SeparatorStyle.DeepSeek
|
37 |
+
sep: str = "\n"
|
38 |
+
sep2: str = None
|
39 |
+
# Stop criteria (the default one is EOS token)
|
40 |
+
stop_str: str = None
|
41 |
+
# Stops generation if meeting any token in this list
|
42 |
+
stop_token_ids: List[int] = None
|
43 |
+
|
44 |
+
def get_prompt(self) -> str:
|
45 |
+
"""Get the prompt for generation."""
|
46 |
+
system_prompt = self.system_template.format(system_message=self.system_message)
|
47 |
+
if self.sep_style == SeparatorStyle.DeepSeek:
|
48 |
+
seps = [self.sep, self.sep2]
|
49 |
+
if system_prompt == "" or system_prompt is None:
|
50 |
+
ret = ""
|
51 |
+
else:
|
52 |
+
ret = system_prompt + seps[0]
|
53 |
+
for i, (role, message) in enumerate(self.messages):
|
54 |
+
if message:
|
55 |
+
ret += role + ": " + message + seps[i % 2]
|
56 |
+
else:
|
57 |
+
ret += role + ":"
|
58 |
+
return ret
|
59 |
+
elif self.sep_style == SeparatorStyle.DeepSeekV2:
|
60 |
+
seps = [self.sep, self.sep2]
|
61 |
+
if system_prompt == "" or system_prompt is None:
|
62 |
+
ret = ""
|
63 |
+
else:
|
64 |
+
ret = system_prompt + seps[0]
|
65 |
+
for i, (role, message) in enumerate(self.messages):
|
66 |
+
if message:
|
67 |
+
if role == "User":
|
68 |
+
ret += "<|sft▁begin|>\n" + message + self.sep #<|sft▁begin|>User Input<|sft▁end|>\nResponse<|end▁of▁sentence|>
|
69 |
+
else:
|
70 |
+
ret += message + self.sep2
|
71 |
+
else:
|
72 |
+
ret = ret
|
73 |
+
return ret
|
74 |
+
|
75 |
+
elif self.sep_style == SeparatorStyle.PLAIN:
|
76 |
+
seps = [self.sep, self.sep2]
|
77 |
+
ret = ""
|
78 |
+
for i, (role, message) in enumerate(self.messages):
|
79 |
+
if message:
|
80 |
+
if type(message) is tuple:
|
81 |
+
message, _, _ = message
|
82 |
+
if i % 2 == 0:
|
83 |
+
ret += message + seps[i % 2]
|
84 |
+
else:
|
85 |
+
ret += message + seps[i % 2]
|
86 |
+
else:
|
87 |
+
ret += ""
|
88 |
+
return ret
|
89 |
+
elif self.sep_style == SeparatorStyle.ALIGNMENT:
|
90 |
+
seps = [self.sep, self.sep2]
|
91 |
+
ret = ""
|
92 |
+
for i, (role, message) in enumerate(self.messages):
|
93 |
+
if message:
|
94 |
+
if type(message) is tuple:
|
95 |
+
message, _, _ = message
|
96 |
+
if i % 2 == 0:
|
97 |
+
ret += '<image>\n' + seps[i % 2]
|
98 |
+
else:
|
99 |
+
ret += message + seps[i % 2]
|
100 |
+
else:
|
101 |
+
ret += ""
|
102 |
+
return ret
|
103 |
+
else:
|
104 |
+
raise ValueError(f"Invalid style: {self.sep_style}")
|
105 |
+
|
106 |
+
def set_system_message(self, system_message: str):
|
107 |
+
"""Set the system message."""
|
108 |
+
self.system_message = system_message
|
109 |
+
|
110 |
+
def append_message(self, role: str, message: str):
|
111 |
+
"""Append a new message."""
|
112 |
+
self.messages.append([role, message])
|
113 |
+
|
114 |
+
def update_last_message(self, message: str):
|
115 |
+
"""Update the last output.
|
116 |
+
|
117 |
+
The last message is typically set to be None when constructing the prompt,
|
118 |
+
so we need to update it in-place after getting the response from a model.
|
119 |
+
"""
|
120 |
+
self.messages[-1][1] = message
|
121 |
+
|
122 |
+
def reset_message(self):
|
123 |
+
"""Reset a new message."""
|
124 |
+
self.messages = []
|
125 |
+
|
126 |
+
def to_gradio_chatbot(self):
|
127 |
+
"""Convert the conversation to gradio chatbot format."""
|
128 |
+
ret = []
|
129 |
+
for i, (role, msg) in enumerate(self.messages[self.offset :]):
|
130 |
+
if i % 2 == 0:
|
131 |
+
ret.append([msg, None])
|
132 |
+
else:
|
133 |
+
ret[-1][-1] = msg
|
134 |
+
return ret
|
135 |
+
|
136 |
+
def to_openai_api_messages(self):
|
137 |
+
"""Convert the conversation to OpenAI chat completion format."""
|
138 |
+
system_prompt = self.system_template.format(system_message=self.system_message)
|
139 |
+
ret = [{"role": "system", "content": system_prompt}]
|
140 |
+
|
141 |
+
for i, (_, msg) in enumerate(self.messages[self.offset :]):
|
142 |
+
if i % 2 == 0:
|
143 |
+
ret.append({"role": "user", "content": msg})
|
144 |
+
else:
|
145 |
+
if msg is not None:
|
146 |
+
ret.append({"role": "assistant", "content": msg})
|
147 |
+
return ret
|
148 |
+
|
149 |
+
def copy(self):
|
150 |
+
return Conversation(
|
151 |
+
name=self.name,
|
152 |
+
system_template=self.system_template,
|
153 |
+
system_message=self.system_message,
|
154 |
+
roles=self.roles,
|
155 |
+
messages=[[x, y] for x, y in self.messages],
|
156 |
+
offset=self.offset,
|
157 |
+
sep_style=self.sep_style,
|
158 |
+
sep=self.sep,
|
159 |
+
sep2=self.sep2,
|
160 |
+
stop_str=self.stop_str,
|
161 |
+
stop_token_ids=self.stop_token_ids,
|
162 |
+
)
|
163 |
+
|
164 |
+
def dict(self):
|
165 |
+
return {
|
166 |
+
"template_name": self.name,
|
167 |
+
"system_message": self.system_message,
|
168 |
+
"roles": self.roles,
|
169 |
+
"messages": self.messages,
|
170 |
+
"offset": self.offset,
|
171 |
+
}
|
172 |
+
|
173 |
+
|
174 |
+
# A global registry for all conversation templates
|
175 |
+
conv_templates: Dict[str, Conversation] = {}
|
176 |
+
|
177 |
+
|
178 |
+
def register_conv_template(template: Conversation, override: bool = False):
|
179 |
+
"""Register a new conversation template."""
|
180 |
+
if not override:
|
181 |
+
assert template.name not in conv_templates, f"{template.name} has been registered."
|
182 |
+
|
183 |
+
conv_templates[template.name] = template
|
184 |
+
|
185 |
+
|
186 |
+
def get_conv_template(name: str) -> Conversation:
|
187 |
+
"""Get a conversation template."""
|
188 |
+
return conv_templates[name].copy()
|
189 |
+
|
190 |
+
|
191 |
+
# register_conv_template(
|
192 |
+
# Conversation(
|
193 |
+
# name="deepseek",
|
194 |
+
# system_template="{system_message}",
|
195 |
+
# # system_message="You are a helpful assistant. Please answer truthfully and write out your "
|
196 |
+
# # "thinking step by step to be sure you get the right answer.",
|
197 |
+
# system_message="",
|
198 |
+
# roles=("User", "Assistant"),
|
199 |
+
# messages=(),
|
200 |
+
# offset=0,
|
201 |
+
# sep_style=SeparatorStyle.DeepSeek,
|
202 |
+
# sep="\n\n",
|
203 |
+
# sep2="<|end▁of▁sentence|>",
|
204 |
+
# stop_token_ids=[100001],
|
205 |
+
# stop_str=["User:", "<|end▁of▁sentence|>"]
|
206 |
+
# )
|
207 |
+
# )
|
208 |
+
register_conv_template(
|
209 |
+
Conversation(
|
210 |
+
name="deepseek",
|
211 |
+
system_template="{system_message}",
|
212 |
+
# system_message="You are a helpful assistant. Please answer truthfully and write out your "
|
213 |
+
# "thinking step by step to be sure you get the right answer.",
|
214 |
+
system_message="",
|
215 |
+
roles=("<|User|>", "<|Assistant|>"),
|
216 |
+
messages=(),
|
217 |
+
offset=0,
|
218 |
+
sep_style=SeparatorStyle.DeepSeek,
|
219 |
+
sep="\n\n",
|
220 |
+
sep2="<|end▁of▁sentence|>",
|
221 |
+
stop_token_ids=[100001],
|
222 |
+
stop_str=["User:", "<|end▁of▁sentence|>"]
|
223 |
+
)
|
224 |
+
)
|
225 |
+
# register_conv_template(
|
226 |
+
# Conversation(
|
227 |
+
# name="deepseekv2",
|
228 |
+
# system_template="{system_message}",
|
229 |
+
# system_message="",
|
230 |
+
# roles=("User", "Assistant"),
|
231 |
+
# messages=(),
|
232 |
+
# offset=0,
|
233 |
+
# sep_style=SeparatorStyle.DeepSeekV2,
|
234 |
+
# sep="\n<|sft▁end|>",
|
235 |
+
# sep2="<|end▁of▁sentence|>",
|
236 |
+
# stop_token_ids=[100001],
|
237 |
+
# stop_str=["User:", "<|end▁of▁sentence|>"]
|
238 |
+
# )
|
239 |
+
# )
|
240 |
+
register_conv_template(
|
241 |
+
Conversation(
|
242 |
+
name="deepseekv2",
|
243 |
+
system_template="{system_message}",
|
244 |
+
system_message="",
|
245 |
+
roles=("|<User>|", "|<Assistant>|"),
|
246 |
+
messages=(),
|
247 |
+
offset=0,
|
248 |
+
sep_style=SeparatorStyle.DeepSeekV2,
|
249 |
+
sep="\n<|sft▁end|>",
|
250 |
+
sep2="<|end▁of▁sentence|>",
|
251 |
+
stop_token_ids=[100001],
|
252 |
+
stop_str=["User:", "<|end▁of▁sentence|>"]
|
253 |
+
)
|
254 |
+
)
|
255 |
+
|
256 |
+
|
257 |
+
register_conv_template(
|
258 |
+
Conversation(
|
259 |
+
name="plain",
|
260 |
+
system_template="",
|
261 |
+
system_message="",
|
262 |
+
roles=("", ""),
|
263 |
+
messages=(),
|
264 |
+
offset=0,
|
265 |
+
sep_style=SeparatorStyle.PLAIN,
|
266 |
+
sep="",
|
267 |
+
sep2="",
|
268 |
+
stop_token_ids=[100001],
|
269 |
+
stop_str=['</s>'],
|
270 |
+
)
|
271 |
+
)
|
272 |
+
|
273 |
+
|
274 |
+
register_conv_template(
|
275 |
+
Conversation(
|
276 |
+
name="alignment",
|
277 |
+
system_template="",
|
278 |
+
system_message="",
|
279 |
+
roles=("", ""),
|
280 |
+
messages=(),
|
281 |
+
offset=0,
|
282 |
+
sep_style=SeparatorStyle.ALIGNMENT,
|
283 |
+
sep="",
|
284 |
+
sep2="",
|
285 |
+
stop_token_ids=[100001],
|
286 |
+
stop_str=['</s>'],
|
287 |
+
)
|
288 |
+
)
|
289 |
+
|
290 |
+
|
291 |
+
if __name__ == "__main__":
|
292 |
+
print("deepseek template:")
|
293 |
+
conv = get_conv_template("deepseek")
|
294 |
+
conv.append_message(conv.roles[0], "Hello!")
|
295 |
+
conv.append_message(conv.roles[1], "Hi! This is Tony.")
|
296 |
+
conv.append_message(conv.roles[0], "Who are you?")
|
297 |
+
conv.append_message(conv.roles[1], "I am a helpful assistant.")
|
298 |
+
conv.append_message(conv.roles[0], "How are you?")
|
299 |
+
conv.append_message(conv.roles[1], None)
|
300 |
+
print(conv.get_prompt())
|
301 |
+
|
302 |
+
print("deepseekv2 template:")
|
303 |
+
conv = get_conv_template("deepseekv2")
|
304 |
+
conv.append_message(conv.roles[0], "Hello!")
|
305 |
+
conv.append_message(conv.roles[1], "Hi! This is Tony.")
|
306 |
+
conv.append_message(conv.roles[0], "Who are you?")
|
307 |
+
conv.append_message(conv.roles[1], "I am a helpful assistant.")
|
308 |
+
conv.append_message(conv.roles[0], "How are you?")
|
309 |
+
conv.append_message(conv.roles[1], None)
|
310 |
+
print(conv.get_prompt())
|
deepseek_vl2/models/modeling_deepseek.py
ADDED
@@ -0,0 +1,1975 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 DeepSeek-AI and The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
""" PyTorch DeepSeek model and compatible with both DeepSeekV2 and DeepSeekV3"""
|
21 |
+
import math
|
22 |
+
import warnings
|
23 |
+
from typing import List, Optional, Tuple, Union
|
24 |
+
import numpy as np
|
25 |
+
|
26 |
+
import torch
|
27 |
+
import torch.nn.functional as F
|
28 |
+
import torch.utils.checkpoint
|
29 |
+
import torch.distributed as dist
|
30 |
+
from einops import repeat
|
31 |
+
from torch import nn
|
32 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
33 |
+
|
34 |
+
from transformers.activations import ACT2FN
|
35 |
+
from transformers.cache_utils import Cache, DynamicCache
|
36 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
|
37 |
+
from transformers.models.llama.modeling_llama import (
|
38 |
+
LlamaAttention,
|
39 |
+
LlamaFlashAttention2
|
40 |
+
)
|
41 |
+
from transformers.modeling_outputs import (
|
42 |
+
BaseModelOutputWithPast,
|
43 |
+
CausalLMOutputWithPast,
|
44 |
+
SequenceClassifierOutputWithPast,
|
45 |
+
)
|
46 |
+
from transformers.modeling_utils import PreTrainedModel
|
47 |
+
from transformers.pytorch_utils import (
|
48 |
+
ALL_LAYERNORM_LAYERS,
|
49 |
+
is_torch_greater_or_equal_than_1_13,
|
50 |
+
)
|
51 |
+
from transformers.utils import (
|
52 |
+
add_start_docstrings,
|
53 |
+
add_start_docstrings_to_model_forward,
|
54 |
+
is_flash_attn_2_available,
|
55 |
+
is_flash_attn_greater_or_equal_2_10,
|
56 |
+
logging,
|
57 |
+
replace_return_docstrings,
|
58 |
+
)
|
59 |
+
from transformers.utils.import_utils import is_torch_fx_available
|
60 |
+
|
61 |
+
from .configuration_deepseek import DeepseekV2Config
|
62 |
+
|
63 |
+
if is_flash_attn_2_available():
|
64 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
65 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
66 |
+
|
67 |
+
# This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
|
68 |
+
# It means that the function will not be traced through and simply appear as a node in the graph.
|
69 |
+
if is_torch_fx_available():
|
70 |
+
if not is_torch_greater_or_equal_than_1_13:
|
71 |
+
import torch.fx
|
72 |
+
|
73 |
+
_prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
|
74 |
+
|
75 |
+
logger = logging.get_logger(__name__)
|
76 |
+
|
77 |
+
_CONFIG_FOR_DOC = "DeepseekV2Config"
|
78 |
+
|
79 |
+
|
80 |
+
def _get_unpad_data(attention_mask):
|
81 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
82 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
83 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
84 |
+
cu_seqlens = F.pad(
|
85 |
+
torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
|
86 |
+
)
|
87 |
+
return (
|
88 |
+
indices,
|
89 |
+
cu_seqlens,
|
90 |
+
max_seqlen_in_batch,
|
91 |
+
)
|
92 |
+
|
93 |
+
|
94 |
+
class DeepseekV2RMSNorm(nn.Module):
|
95 |
+
def __init__(self, hidden_size, eps=1e-6):
|
96 |
+
"""
|
97 |
+
DeepseekV2RMSNorm is equivalent to T5LayerNorm
|
98 |
+
"""
|
99 |
+
super().__init__()
|
100 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
101 |
+
self.variance_epsilon = eps
|
102 |
+
|
103 |
+
def forward(self, hidden_states):
|
104 |
+
input_dtype = hidden_states.dtype
|
105 |
+
hidden_states = hidden_states.to(torch.float32)
|
106 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
107 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
108 |
+
return self.weight * hidden_states.to(input_dtype)
|
109 |
+
|
110 |
+
|
111 |
+
ALL_LAYERNORM_LAYERS.append(DeepseekV2RMSNorm)
|
112 |
+
|
113 |
+
|
114 |
+
class DeepseekV2RotaryEmbedding(nn.Module):
|
115 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
116 |
+
super().__init__()
|
117 |
+
|
118 |
+
self.dim = dim
|
119 |
+
self.max_position_embeddings = max_position_embeddings
|
120 |
+
self.base = base
|
121 |
+
inv_freq = 1.0 / (
|
122 |
+
self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
|
123 |
+
)
|
124 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
125 |
+
|
126 |
+
# Build here to make `torch.jit.trace` work.
|
127 |
+
self._set_cos_sin_cache(
|
128 |
+
seq_len=max_position_embeddings,
|
129 |
+
device=self.inv_freq.device,
|
130 |
+
dtype=torch.get_default_dtype(),
|
131 |
+
)
|
132 |
+
self.max_seq_len_cached = None
|
133 |
+
|
134 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
135 |
+
self.max_seq_len_cached = seq_len
|
136 |
+
t = torch.arange(
|
137 |
+
self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
|
138 |
+
)
|
139 |
+
|
140 |
+
freqs = torch.outer(t, self.inv_freq.to(t.device))
|
141 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
142 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
143 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
144 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
145 |
+
|
146 |
+
def forward(self, x, seq_len=None):
|
147 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
148 |
+
if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
|
149 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
150 |
+
|
151 |
+
return (
|
152 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
153 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
154 |
+
)
|
155 |
+
|
156 |
+
|
157 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV2
|
158 |
+
class DeepseekV2LinearScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
|
159 |
+
"""DeepseekV2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
160 |
+
|
161 |
+
def __init__(
|
162 |
+
self,
|
163 |
+
dim,
|
164 |
+
max_position_embeddings=2048,
|
165 |
+
base=10000,
|
166 |
+
device=None,
|
167 |
+
scaling_factor=1.0,
|
168 |
+
):
|
169 |
+
self.scaling_factor = scaling_factor
|
170 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
171 |
+
|
172 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
173 |
+
self.max_seq_len_cached = seq_len
|
174 |
+
t = torch.arange(
|
175 |
+
self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
|
176 |
+
)
|
177 |
+
t = t / self.scaling_factor
|
178 |
+
|
179 |
+
freqs = torch.outer(t, self.inv_freq)
|
180 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
181 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
182 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
183 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
184 |
+
|
185 |
+
|
186 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV2
|
187 |
+
class DeepseekV2DynamicNTKScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
|
188 |
+
"""DeepseekV2RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
189 |
+
|
190 |
+
def __init__(
|
191 |
+
self,
|
192 |
+
dim,
|
193 |
+
max_position_embeddings=2048,
|
194 |
+
base=10000,
|
195 |
+
device=None,
|
196 |
+
scaling_factor=1.0,
|
197 |
+
):
|
198 |
+
self.scaling_factor = scaling_factor
|
199 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
200 |
+
|
201 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
202 |
+
self.max_seq_len_cached = seq_len
|
203 |
+
|
204 |
+
if seq_len > self.max_position_embeddings:
|
205 |
+
base = self.base * (
|
206 |
+
(self.scaling_factor * seq_len / self.max_position_embeddings)
|
207 |
+
- (self.scaling_factor - 1)
|
208 |
+
) ** (self.dim / (self.dim - 2))
|
209 |
+
inv_freq = 1.0 / (
|
210 |
+
base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
|
211 |
+
)
|
212 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
213 |
+
|
214 |
+
t = torch.arange(
|
215 |
+
self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
|
216 |
+
)
|
217 |
+
|
218 |
+
freqs = torch.outer(t, self.inv_freq)
|
219 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
220 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
221 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
222 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
223 |
+
|
224 |
+
|
225 |
+
# Inverse dim formula to find dim based on number of rotations
|
226 |
+
def yarn_find_correction_dim(
|
227 |
+
num_rotations, dim, base=10000, max_position_embeddings=2048
|
228 |
+
):
|
229 |
+
return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
|
230 |
+
2 * math.log(base)
|
231 |
+
)
|
232 |
+
|
233 |
+
|
234 |
+
# Find dim range bounds based on rotations
|
235 |
+
def yarn_find_correction_range(
|
236 |
+
low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
|
237 |
+
):
|
238 |
+
low = math.floor(
|
239 |
+
yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
|
240 |
+
)
|
241 |
+
high = math.ceil(
|
242 |
+
yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
|
243 |
+
)
|
244 |
+
return max(low, 0), min(high, dim - 1) # Clamp values just in case
|
245 |
+
|
246 |
+
|
247 |
+
def yarn_get_mscale(scale=1, mscale=1):
|
248 |
+
if scale <= 1:
|
249 |
+
return 1.0
|
250 |
+
return 0.1 * mscale * math.log(scale) + 1.0
|
251 |
+
|
252 |
+
|
253 |
+
def yarn_linear_ramp_mask(min, max, dim):
|
254 |
+
if min == max:
|
255 |
+
max += 0.001 # Prevent singularity
|
256 |
+
|
257 |
+
linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
|
258 |
+
ramp_func = torch.clamp(linear_func, 0, 1)
|
259 |
+
return ramp_func
|
260 |
+
|
261 |
+
|
262 |
+
class DeepseekV2YarnRotaryEmbedding(DeepseekV2RotaryEmbedding):
|
263 |
+
|
264 |
+
def __init__(
|
265 |
+
self,
|
266 |
+
dim,
|
267 |
+
max_position_embeddings=2048,
|
268 |
+
base=10000,
|
269 |
+
device=None,
|
270 |
+
scaling_factor=1.0,
|
271 |
+
original_max_position_embeddings=4096,
|
272 |
+
beta_fast=32,
|
273 |
+
beta_slow=1,
|
274 |
+
mscale=1,
|
275 |
+
mscale_all_dim=0,
|
276 |
+
):
|
277 |
+
self.scaling_factor = scaling_factor
|
278 |
+
self.original_max_position_embeddings = original_max_position_embeddings
|
279 |
+
self.beta_fast = beta_fast
|
280 |
+
self.beta_slow = beta_slow
|
281 |
+
self.mscale = mscale
|
282 |
+
self.mscale_all_dim = mscale_all_dim
|
283 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
284 |
+
|
285 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
286 |
+
self.max_seq_len_cached = seq_len
|
287 |
+
dim = self.dim
|
288 |
+
|
289 |
+
freq_extra = 1.0 / (
|
290 |
+
self.base
|
291 |
+
** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
|
292 |
+
)
|
293 |
+
freq_inter = 1.0 / (
|
294 |
+
self.scaling_factor
|
295 |
+
* self.base
|
296 |
+
** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
|
297 |
+
)
|
298 |
+
|
299 |
+
low, high = yarn_find_correction_range(
|
300 |
+
self.beta_fast,
|
301 |
+
self.beta_slow,
|
302 |
+
dim,
|
303 |
+
self.base,
|
304 |
+
self.original_max_position_embeddings,
|
305 |
+
)
|
306 |
+
inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
|
307 |
+
device=device, dtype=torch.float32
|
308 |
+
)
|
309 |
+
inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
|
310 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
311 |
+
|
312 |
+
t = torch.arange(seq_len, device=device, dtype=torch.float32)
|
313 |
+
|
314 |
+
freqs = torch.outer(t, inv_freq)
|
315 |
+
|
316 |
+
_mscale = float(
|
317 |
+
yarn_get_mscale(self.scaling_factor, self.mscale)
|
318 |
+
/ yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
|
319 |
+
)
|
320 |
+
|
321 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
322 |
+
self.register_buffer(
|
323 |
+
"cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
|
324 |
+
)
|
325 |
+
self.register_buffer(
|
326 |
+
"sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
|
327 |
+
)
|
328 |
+
|
329 |
+
|
330 |
+
# Copied from transformers.models.llama.modeling_llama.rotate_half
|
331 |
+
def rotate_half(x):
|
332 |
+
"""Rotates half the hidden dims of the input."""
|
333 |
+
x1 = x[..., : x.shape[-1] // 2]
|
334 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
335 |
+
return torch.cat((-x2, x1), dim=-1)
|
336 |
+
|
337 |
+
|
338 |
+
# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
|
339 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
340 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
341 |
+
|
342 |
+
Args:
|
343 |
+
q (`torch.Tensor`): The query tensor.
|
344 |
+
k (`torch.Tensor`): The key tensor.
|
345 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
346 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
347 |
+
position_ids (`torch.Tensor`):
|
348 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
349 |
+
used to pass offsetted position ids when working with a KV-cache.
|
350 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
351 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
352 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
353 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
354 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
355 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
356 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
357 |
+
Returns:
|
358 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
359 |
+
"""
|
360 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
361 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
362 |
+
|
363 |
+
b, h, s, d = q.shape
|
364 |
+
q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
|
365 |
+
|
366 |
+
b, h, s, d = k.shape
|
367 |
+
k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
|
368 |
+
|
369 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
370 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
371 |
+
return q_embed, k_embed
|
372 |
+
|
373 |
+
|
374 |
+
class DeepseekV2MLP(nn.Module):
|
375 |
+
def __init__(self, config, hidden_size=None, intermediate_size=None):
|
376 |
+
super().__init__()
|
377 |
+
self.config = config
|
378 |
+
self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
|
379 |
+
self.intermediate_size = (
|
380 |
+
config.intermediate_size if intermediate_size is None else intermediate_size
|
381 |
+
)
|
382 |
+
|
383 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
384 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
385 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
386 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
387 |
+
|
388 |
+
def forward(self, x):
|
389 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
390 |
+
return down_proj
|
391 |
+
|
392 |
+
|
393 |
+
class MoEGate(nn.Module):
|
394 |
+
def __init__(self, config):
|
395 |
+
super().__init__()
|
396 |
+
self.config = config
|
397 |
+
self.top_k = config.num_experts_per_tok
|
398 |
+
self.n_routed_experts = config.n_routed_experts
|
399 |
+
self.routed_scaling_factor = config.routed_scaling_factor
|
400 |
+
self.scoring_func = config.scoring_func
|
401 |
+
self.alpha = config.aux_loss_alpha
|
402 |
+
self.seq_aux = config.seq_aux
|
403 |
+
self.topk_method = config.topk_method
|
404 |
+
self.n_group = config.n_group
|
405 |
+
self.topk_group = config.topk_group
|
406 |
+
|
407 |
+
# topk selection algorithm
|
408 |
+
self.norm_topk_prob = config.norm_topk_prob
|
409 |
+
self.gating_dim = config.hidden_size
|
410 |
+
self.weight = nn.Parameter(
|
411 |
+
torch.empty((self.n_routed_experts, self.gating_dim))
|
412 |
+
)
|
413 |
+
if self.topk_method == "noaux_tc":
|
414 |
+
self.e_score_correction_bias = nn.Parameter(
|
415 |
+
torch.empty((self.n_routed_experts))
|
416 |
+
)
|
417 |
+
self.reset_parameters()
|
418 |
+
|
419 |
+
def reset_parameters(self) -> None:
|
420 |
+
import torch.nn.init as init
|
421 |
+
|
422 |
+
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
|
423 |
+
|
424 |
+
def forward(self, hidden_states):
|
425 |
+
bsz, seq_len, h = hidden_states.shape
|
426 |
+
### compute gating score
|
427 |
+
hidden_states = hidden_states.view(-1, h)
|
428 |
+
logits = F.linear(
|
429 |
+
hidden_states.type(torch.float32), self.weight.type(torch.float32), None
|
430 |
+
)
|
431 |
+
if self.scoring_func == "softmax":
|
432 |
+
scores = logits.softmax(dim=-1, dtype=torch.float32)
|
433 |
+
elif self.scoring_func == "sigmoid":
|
434 |
+
scores = logits.sigmoid()
|
435 |
+
else:
|
436 |
+
raise NotImplementedError(
|
437 |
+
f"insupportable scoring function for MoE gating: {self.scoring_func}"
|
438 |
+
)
|
439 |
+
|
440 |
+
### select top-k experts
|
441 |
+
if self.topk_method == "greedy":
|
442 |
+
topk_weight, topk_idx = torch.topk(
|
443 |
+
scores, k=self.top_k, dim=-1, sorted=False
|
444 |
+
)
|
445 |
+
elif self.topk_method == "group_limited_greedy":
|
446 |
+
group_scores = (
|
447 |
+
scores.view(bsz * seq_len, self.n_group, -1).max(dim=-1).values
|
448 |
+
) # [n, n_group]
|
449 |
+
group_idx = torch.topk(
|
450 |
+
group_scores, k=self.topk_group, dim=-1, sorted=False
|
451 |
+
)[
|
452 |
+
1
|
453 |
+
] # [n, top_k_group]
|
454 |
+
group_mask = torch.zeros_like(group_scores) # [n, n_group]
|
455 |
+
group_mask.scatter_(1, group_idx, 1) # [n, n_group]
|
456 |
+
score_mask = (
|
457 |
+
group_mask.unsqueeze(-1)
|
458 |
+
.expand(
|
459 |
+
bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
|
460 |
+
)
|
461 |
+
.reshape(bsz * seq_len, -1)
|
462 |
+
) # [n, e]
|
463 |
+
tmp_scores = scores.masked_fill(~score_mask.bool(), 0.0) # [n, e]
|
464 |
+
topk_weight, topk_idx = torch.topk(
|
465 |
+
tmp_scores, k=self.top_k, dim=-1, sorted=False
|
466 |
+
)
|
467 |
+
elif self.topk_method == "noaux_tc":
|
468 |
+
assert not self.training
|
469 |
+
scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
|
470 |
+
group_scores = (
|
471 |
+
scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
|
472 |
+
) # [n, n_group]
|
473 |
+
group_idx = torch.topk(
|
474 |
+
group_scores, k=self.topk_group, dim=-1, sorted=False
|
475 |
+
)[
|
476 |
+
1
|
477 |
+
] # [n, top_k_group]
|
478 |
+
group_mask = torch.zeros_like(group_scores) # [n, n_group]
|
479 |
+
group_mask.scatter_(1, group_idx, 1) # [n, n_group]
|
480 |
+
score_mask = (
|
481 |
+
group_mask.unsqueeze(-1)
|
482 |
+
.expand(
|
483 |
+
bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
|
484 |
+
)
|
485 |
+
.reshape(bsz * seq_len, -1)
|
486 |
+
) # [n, e]
|
487 |
+
tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), 0.0) # [n, e]
|
488 |
+
_, topk_idx = torch.topk(
|
489 |
+
tmp_scores, k=self.top_k, dim=-1, sorted=False
|
490 |
+
)
|
491 |
+
topk_weight = scores.gather(1, topk_idx)
|
492 |
+
|
493 |
+
### norm gate to sum 1
|
494 |
+
if self.top_k > 1 and self.norm_topk_prob:
|
495 |
+
denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
|
496 |
+
topk_weight = topk_weight / denominator * self.routed_scaling_factor
|
497 |
+
else:
|
498 |
+
topk_weight = topk_weight * self.routed_scaling_factor
|
499 |
+
### expert-level computation auxiliary loss
|
500 |
+
if self.training and self.alpha > 0.0:
|
501 |
+
scores_for_aux = scores
|
502 |
+
aux_topk = self.top_k
|
503 |
+
# always compute aux loss based on the naive greedy topk method
|
504 |
+
topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
|
505 |
+
if self.seq_aux:
|
506 |
+
scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
|
507 |
+
ce = torch.zeros(
|
508 |
+
bsz, self.n_routed_experts, device=hidden_states.device
|
509 |
+
)
|
510 |
+
ce.scatter_add_(
|
511 |
+
1,
|
512 |
+
topk_idx_for_aux_loss,
|
513 |
+
torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device),
|
514 |
+
).div_(seq_len * aux_topk / self.n_routed_experts)
|
515 |
+
aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(
|
516 |
+
dim=1
|
517 |
+
).mean() * self.alpha
|
518 |
+
else:
|
519 |
+
mask_ce = F.one_hot(
|
520 |
+
topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts
|
521 |
+
)
|
522 |
+
ce = mask_ce.float().mean(0)
|
523 |
+
Pi = scores_for_aux.mean(0)
|
524 |
+
fi = ce * self.n_routed_experts
|
525 |
+
aux_loss = (Pi * fi).sum() * self.alpha
|
526 |
+
else:
|
527 |
+
aux_loss = None
|
528 |
+
return topk_idx, topk_weight, aux_loss
|
529 |
+
|
530 |
+
|
531 |
+
class AddAuxiliaryLoss(torch.autograd.Function):
|
532 |
+
"""
|
533 |
+
The trick function of adding auxiliary (aux) loss,
|
534 |
+
which includes the gradient of the aux loss during backpropagation.
|
535 |
+
"""
|
536 |
+
|
537 |
+
@staticmethod
|
538 |
+
def forward(ctx, x, loss):
|
539 |
+
assert loss.numel() == 1
|
540 |
+
ctx.dtype = loss.dtype
|
541 |
+
ctx.required_aux_loss = loss.requires_grad
|
542 |
+
return x
|
543 |
+
|
544 |
+
@staticmethod
|
545 |
+
def backward(ctx, grad_output):
|
546 |
+
grad_loss = None
|
547 |
+
if ctx.required_aux_loss:
|
548 |
+
grad_loss = torch.ones(1, dtype=ctx.dtype, device=grad_output.device)
|
549 |
+
return grad_output, grad_loss
|
550 |
+
|
551 |
+
|
552 |
+
class DeepseekV2MoE(nn.Module):
|
553 |
+
"""
|
554 |
+
A mixed expert module containing shared experts.
|
555 |
+
"""
|
556 |
+
|
557 |
+
def __init__(self, config):
|
558 |
+
super().__init__()
|
559 |
+
self.config = config
|
560 |
+
self.num_experts_per_tok = config.num_experts_per_tok
|
561 |
+
|
562 |
+
if hasattr(config, "ep_size") and config.ep_size > 1:
|
563 |
+
assert config.ep_size == dist.get_world_size()
|
564 |
+
self.ep_size = config.ep_size
|
565 |
+
self.experts_per_rank = config.n_routed_experts // config.ep_size
|
566 |
+
self.ep_rank = dist.get_rank()
|
567 |
+
self.experts = nn.ModuleList(
|
568 |
+
[
|
569 |
+
(
|
570 |
+
DeepseekV2MLP(
|
571 |
+
config, intermediate_size=config.moe_intermediate_size
|
572 |
+
)
|
573 |
+
if i >= self.ep_rank * self.experts_per_rank
|
574 |
+
and i < (self.ep_rank + 1) * self.experts_per_rank
|
575 |
+
else None
|
576 |
+
)
|
577 |
+
for i in range(config.n_routed_experts)
|
578 |
+
]
|
579 |
+
)
|
580 |
+
else:
|
581 |
+
self.ep_size = 1
|
582 |
+
self.experts_per_rank = config.n_routed_experts
|
583 |
+
self.ep_rank = 0
|
584 |
+
self.experts = nn.ModuleList(
|
585 |
+
[
|
586 |
+
DeepseekV2MLP(
|
587 |
+
config, intermediate_size=config.moe_intermediate_size
|
588 |
+
)
|
589 |
+
for i in range(config.n_routed_experts)
|
590 |
+
]
|
591 |
+
)
|
592 |
+
self.gate = MoEGate(config)
|
593 |
+
if config.n_shared_experts is not None:
|
594 |
+
intermediate_size = config.moe_intermediate_size * config.n_shared_experts
|
595 |
+
self.shared_experts = DeepseekV2MLP(
|
596 |
+
config=config, intermediate_size=intermediate_size
|
597 |
+
)
|
598 |
+
|
599 |
+
def forward(self, hidden_states):
|
600 |
+
identity = hidden_states
|
601 |
+
orig_shape = hidden_states.shape
|
602 |
+
topk_idx, topk_weight, aux_loss = self.gate(hidden_states)
|
603 |
+
hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
|
604 |
+
flat_topk_idx = topk_idx.view(-1)
|
605 |
+
if self.training:
|
606 |
+
hidden_states = hidden_states.repeat_interleave(
|
607 |
+
self.num_experts_per_tok, dim=0
|
608 |
+
)
|
609 |
+
y = torch.empty_like(hidden_states)
|
610 |
+
for i, expert in enumerate(self.experts):
|
611 |
+
y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
|
612 |
+
y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
|
613 |
+
y = y.to(hidden_states.dtype).view(*orig_shape)
|
614 |
+
y = AddAuxiliaryLoss.apply(y, aux_loss)
|
615 |
+
else:
|
616 |
+
y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
|
617 |
+
if self.config.n_shared_experts is not None:
|
618 |
+
y = y + self.shared_experts(identity)
|
619 |
+
return y
|
620 |
+
|
621 |
+
@torch.no_grad()
|
622 |
+
def moe_infer(self, x, topk_ids, topk_weight):
|
623 |
+
cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
|
624 |
+
cnts.scatter_(1, topk_ids, 1)
|
625 |
+
tokens_per_expert = cnts.sum(dim=0)
|
626 |
+
idxs = topk_ids.view(-1).argsort()
|
627 |
+
sorted_tokens = x[idxs // topk_ids.shape[1]]
|
628 |
+
sorted_tokens_shape = sorted_tokens.shape
|
629 |
+
if self.ep_size > 1:
|
630 |
+
tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
|
631 |
+
tokens_per_expert_group = tokens_per_expert.new_empty(
|
632 |
+
tokens_per_expert.shape[0]
|
633 |
+
)
|
634 |
+
dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
|
635 |
+
output_splits = (
|
636 |
+
tokens_per_expert_group.view(self.ep_size, -1)
|
637 |
+
.sum(1)
|
638 |
+
.cpu()
|
639 |
+
.numpy()
|
640 |
+
.tolist()
|
641 |
+
)
|
642 |
+
gathered_tokens = sorted_tokens.new_empty(
|
643 |
+
tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
|
644 |
+
)
|
645 |
+
input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
|
646 |
+
dist.all_to_all(
|
647 |
+
list(gathered_tokens.split(output_splits)),
|
648 |
+
list(sorted_tokens.split(input_split_sizes)),
|
649 |
+
)
|
650 |
+
tokens_per_expert_post_gather = tokens_per_expert_group.view(
|
651 |
+
self.ep_size, self.experts_per_rank
|
652 |
+
).sum(dim=0)
|
653 |
+
gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
|
654 |
+
s = 0
|
655 |
+
for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
|
656 |
+
gatherd_idxs[s : s + k] = i % self.experts_per_rank
|
657 |
+
s += k
|
658 |
+
gatherd_idxs = gatherd_idxs.argsort()
|
659 |
+
sorted_tokens = gathered_tokens[gatherd_idxs]
|
660 |
+
tokens_per_expert = tokens_per_expert_post_gather
|
661 |
+
tokens_per_expert = tokens_per_expert.cpu().numpy()
|
662 |
+
|
663 |
+
outputs = []
|
664 |
+
start_idx = 0
|
665 |
+
for i, num_tokens in enumerate(tokens_per_expert):
|
666 |
+
end_idx = start_idx + num_tokens
|
667 |
+
if num_tokens == 0:
|
668 |
+
continue
|
669 |
+
expert = self.experts[i + self.ep_rank * self.experts_per_rank]
|
670 |
+
tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
|
671 |
+
expert_out = expert(tokens_for_this_expert)
|
672 |
+
outputs.append(expert_out)
|
673 |
+
start_idx = end_idx
|
674 |
+
|
675 |
+
outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
|
676 |
+
if self.ep_size > 1:
|
677 |
+
new_x = torch.empty_like(outs)
|
678 |
+
new_x[gatherd_idxs] = outs
|
679 |
+
gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
|
680 |
+
dist.all_to_all(
|
681 |
+
list(gathered_tokens.split(input_split_sizes)),
|
682 |
+
list(new_x.split(output_splits)),
|
683 |
+
)
|
684 |
+
outs = gathered_tokens
|
685 |
+
|
686 |
+
new_x = torch.empty_like(outs)
|
687 |
+
new_x[idxs] = outs
|
688 |
+
final_out = (
|
689 |
+
new_x.view(*topk_ids.shape, -1)
|
690 |
+
.type(topk_weight.dtype)
|
691 |
+
.mul_(topk_weight.unsqueeze(dim=-1))
|
692 |
+
.sum(dim=1)
|
693 |
+
.type(new_x.dtype)
|
694 |
+
)
|
695 |
+
return final_out
|
696 |
+
|
697 |
+
|
698 |
+
# Copied from transformers.models.llama.modeling_llama.repeat_kv
|
699 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
700 |
+
"""
|
701 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
702 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
703 |
+
"""
|
704 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
705 |
+
if n_rep == 1:
|
706 |
+
return hidden_states
|
707 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(
|
708 |
+
batch, num_key_value_heads, n_rep, slen, head_dim
|
709 |
+
)
|
710 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
711 |
+
|
712 |
+
|
713 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV2
|
714 |
+
class DeepseekV2Attention(nn.Module):
|
715 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
716 |
+
|
717 |
+
def __init__(self, config: DeepseekV2Config, layer_idx: Optional[int] = None):
|
718 |
+
super().__init__()
|
719 |
+
self.config = config
|
720 |
+
self.layer_idx = layer_idx
|
721 |
+
if layer_idx is None:
|
722 |
+
logger.warning_once(
|
723 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
724 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
725 |
+
"when creating this class."
|
726 |
+
)
|
727 |
+
|
728 |
+
self.attention_dropout = config.attention_dropout
|
729 |
+
self.hidden_size = config.hidden_size
|
730 |
+
self.num_heads = config.num_attention_heads
|
731 |
+
|
732 |
+
self.max_position_embeddings = config.max_position_embeddings
|
733 |
+
self.rope_theta = config.rope_theta
|
734 |
+
self.q_lora_rank = config.q_lora_rank
|
735 |
+
self.qk_rope_head_dim = config.qk_rope_head_dim
|
736 |
+
self.kv_lora_rank = config.kv_lora_rank
|
737 |
+
self.v_head_dim = config.v_head_dim
|
738 |
+
self.qk_nope_head_dim = config.qk_nope_head_dim
|
739 |
+
self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
|
740 |
+
|
741 |
+
self.is_causal = True
|
742 |
+
|
743 |
+
if self.q_lora_rank is None:
|
744 |
+
self.q_proj = nn.Linear(
|
745 |
+
self.hidden_size, self.num_heads * self.q_head_dim, bias=False
|
746 |
+
)
|
747 |
+
else:
|
748 |
+
self.q_a_proj = nn.Linear(
|
749 |
+
self.hidden_size, config.q_lora_rank, bias=config.attention_bias
|
750 |
+
)
|
751 |
+
self.q_a_layernorm = DeepseekV2RMSNorm(config.q_lora_rank)
|
752 |
+
self.q_b_proj = nn.Linear(
|
753 |
+
config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
|
754 |
+
)
|
755 |
+
|
756 |
+
self.kv_a_proj_with_mqa = nn.Linear(
|
757 |
+
self.hidden_size,
|
758 |
+
config.kv_lora_rank + config.qk_rope_head_dim,
|
759 |
+
bias=config.attention_bias,
|
760 |
+
)
|
761 |
+
self.kv_a_layernorm = DeepseekV2RMSNorm(config.kv_lora_rank)
|
762 |
+
self.kv_b_proj = nn.Linear(
|
763 |
+
config.kv_lora_rank,
|
764 |
+
self.num_heads
|
765 |
+
* (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
|
766 |
+
bias=False,
|
767 |
+
)
|
768 |
+
|
769 |
+
self.o_proj = nn.Linear(
|
770 |
+
self.num_heads * self.v_head_dim,
|
771 |
+
self.hidden_size,
|
772 |
+
bias=config.attention_bias,
|
773 |
+
)
|
774 |
+
self._init_rope()
|
775 |
+
|
776 |
+
self.softmax_scale = self.q_head_dim ** (-0.5)
|
777 |
+
if self.config.rope_scaling is not None:
|
778 |
+
mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
|
779 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
780 |
+
if mscale_all_dim:
|
781 |
+
mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
|
782 |
+
self.softmax_scale = self.softmax_scale * mscale * mscale
|
783 |
+
|
784 |
+
def _init_rope(self):
|
785 |
+
if self.config.rope_scaling is None:
|
786 |
+
self.rotary_emb = DeepseekV2RotaryEmbedding(
|
787 |
+
self.qk_rope_head_dim,
|
788 |
+
max_position_embeddings=self.max_position_embeddings,
|
789 |
+
base=self.rope_theta,
|
790 |
+
)
|
791 |
+
else:
|
792 |
+
scaling_type = self.config.rope_scaling["type"]
|
793 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
794 |
+
if scaling_type == "linear":
|
795 |
+
self.rotary_emb = DeepseekV2LinearScalingRotaryEmbedding(
|
796 |
+
self.qk_rope_head_dim,
|
797 |
+
max_position_embeddings=self.max_position_embeddings,
|
798 |
+
scaling_factor=scaling_factor,
|
799 |
+
base=self.rope_theta,
|
800 |
+
)
|
801 |
+
elif scaling_type == "dynamic":
|
802 |
+
self.rotary_emb = DeepseekV2DynamicNTKScalingRotaryEmbedding(
|
803 |
+
self.qk_rope_head_dim,
|
804 |
+
max_position_embeddings=self.max_position_embeddings,
|
805 |
+
scaling_factor=scaling_factor,
|
806 |
+
base=self.rope_theta,
|
807 |
+
)
|
808 |
+
elif scaling_type == "yarn":
|
809 |
+
kwargs = {
|
810 |
+
key: self.config.rope_scaling[key]
|
811 |
+
for key in [
|
812 |
+
"original_max_position_embeddings",
|
813 |
+
"beta_fast",
|
814 |
+
"beta_slow",
|
815 |
+
"mscale",
|
816 |
+
"mscale_all_dim",
|
817 |
+
]
|
818 |
+
if key in self.config.rope_scaling
|
819 |
+
}
|
820 |
+
self.rotary_emb = DeepseekV2YarnRotaryEmbedding(
|
821 |
+
self.qk_rope_head_dim,
|
822 |
+
max_position_embeddings=self.max_position_embeddings,
|
823 |
+
scaling_factor=scaling_factor,
|
824 |
+
base=self.rope_theta,
|
825 |
+
**kwargs,
|
826 |
+
)
|
827 |
+
else:
|
828 |
+
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
829 |
+
|
830 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
831 |
+
return (
|
832 |
+
tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
|
833 |
+
.transpose(1, 2)
|
834 |
+
.contiguous()
|
835 |
+
)
|
836 |
+
|
837 |
+
def forward(
|
838 |
+
self,
|
839 |
+
hidden_states: torch.Tensor,
|
840 |
+
attention_mask: Optional[torch.Tensor] = None,
|
841 |
+
position_ids: Optional[torch.LongTensor] = None,
|
842 |
+
past_key_value: Optional[Cache] = None,
|
843 |
+
output_attentions: bool = False,
|
844 |
+
use_cache: bool = False,
|
845 |
+
**kwargs,
|
846 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
847 |
+
if "padding_mask" in kwargs:
|
848 |
+
warnings.warn(
|
849 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
850 |
+
)
|
851 |
+
bsz, q_len, _ = hidden_states.size()
|
852 |
+
|
853 |
+
if self.q_lora_rank is None:
|
854 |
+
q = self.q_proj(hidden_states)
|
855 |
+
else:
|
856 |
+
q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
|
857 |
+
q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
|
858 |
+
q_nope, q_pe = torch.split(
|
859 |
+
q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
|
860 |
+
)
|
861 |
+
|
862 |
+
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
|
863 |
+
compressed_kv, k_pe = torch.split(
|
864 |
+
compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
|
865 |
+
)
|
866 |
+
compressed_kv = self.kv_a_layernorm(compressed_kv)
|
867 |
+
k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
|
868 |
+
|
869 |
+
kv_seq_len = k_pe.shape[-2]
|
870 |
+
if past_key_value is not None:
|
871 |
+
if self.layer_idx is None:
|
872 |
+
raise ValueError(
|
873 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
874 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
875 |
+
"with a layer index."
|
876 |
+
)
|
877 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
878 |
+
|
879 |
+
cos, sin = self.rotary_emb(q_pe, seq_len=kv_seq_len)
|
880 |
+
q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
|
881 |
+
|
882 |
+
if past_key_value is not None:
|
883 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
884 |
+
compressed_kv = compressed_kv.unsqueeze(1)
|
885 |
+
k_pe, compressed_kv = past_key_value.update(k_pe, compressed_kv, self.layer_idx, cache_kwargs)
|
886 |
+
compressed_kv = compressed_kv.squeeze(1)
|
887 |
+
|
888 |
+
kv_b_proj = self.kv_b_proj.weight.view(self.num_heads, -1, self.kv_lora_rank)
|
889 |
+
q_absorb = kv_b_proj[:, :self.qk_nope_head_dim, :]
|
890 |
+
out_absorb = kv_b_proj[:, self.qk_nope_head_dim:, :]
|
891 |
+
|
892 |
+
q_nope = torch.matmul(q_nope, q_absorb)
|
893 |
+
attn_weights = (torch.matmul(q_pe, k_pe.mT) +
|
894 |
+
torch.matmul(q_nope, compressed_kv.unsqueeze(-3).mT)) * self.softmax_scale
|
895 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
896 |
+
raise ValueError(
|
897 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
898 |
+
f" {attn_weights.size()}"
|
899 |
+
)
|
900 |
+
assert attention_mask is not None
|
901 |
+
if attention_mask is not None:
|
902 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
903 |
+
raise ValueError(
|
904 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
905 |
+
)
|
906 |
+
attn_weights = attn_weights + attention_mask
|
907 |
+
|
908 |
+
# upcast attention to fp32
|
909 |
+
attn_weights = nn.functional.softmax(
|
910 |
+
attn_weights, dim=-1, dtype=torch.float32
|
911 |
+
).to(q_pe.dtype)
|
912 |
+
attn_weights = nn.functional.dropout(
|
913 |
+
attn_weights, p=self.attention_dropout, training=self.training
|
914 |
+
)
|
915 |
+
attn_output = torch.einsum('bhql,blc->bhqc', attn_weights, compressed_kv)
|
916 |
+
|
917 |
+
attn_output = torch.matmul(attn_output, out_absorb.mT)
|
918 |
+
|
919 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
|
920 |
+
raise ValueError(
|
921 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
|
922 |
+
f" {attn_output.size()}"
|
923 |
+
)
|
924 |
+
|
925 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
926 |
+
|
927 |
+
attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
|
928 |
+
|
929 |
+
attn_output = self.o_proj(attn_output)
|
930 |
+
|
931 |
+
if not output_attentions:
|
932 |
+
attn_weights = None
|
933 |
+
|
934 |
+
return attn_output, attn_weights, past_key_value
|
935 |
+
|
936 |
+
|
937 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV2
|
938 |
+
class DeepseekV2FlashAttention2(DeepseekV2Attention):
|
939 |
+
"""
|
940 |
+
DeepseekV2 flash attention module. This module inherits from `DeepseekV2Attention` as the weights of the module stays
|
941 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
942 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
943 |
+
"""
|
944 |
+
|
945 |
+
def __init__(self, *args, **kwargs):
|
946 |
+
super().__init__(*args, **kwargs)
|
947 |
+
|
948 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
949 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
950 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
|
951 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
952 |
+
|
953 |
+
def forward(
|
954 |
+
self,
|
955 |
+
hidden_states: torch.Tensor,
|
956 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
957 |
+
position_ids: Optional[torch.LongTensor] = None,
|
958 |
+
past_key_value: Optional[Cache] = None,
|
959 |
+
output_attentions: bool = False,
|
960 |
+
use_cache: bool = False,
|
961 |
+
**kwargs,
|
962 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
963 |
+
# DeepseekV2FlashAttention2 attention does not support output_attentions
|
964 |
+
if "padding_mask" in kwargs:
|
965 |
+
warnings.warn(
|
966 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
967 |
+
)
|
968 |
+
|
969 |
+
# overwrite attention_mask with padding_mask
|
970 |
+
attention_mask = kwargs.pop("padding_mask")
|
971 |
+
|
972 |
+
output_attentions = False
|
973 |
+
|
974 |
+
bsz, q_len, _ = hidden_states.size()
|
975 |
+
|
976 |
+
if self.q_lora_rank is None:
|
977 |
+
q = self.q_proj(hidden_states)
|
978 |
+
else:
|
979 |
+
q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
|
980 |
+
q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
|
981 |
+
q_nope, q_pe = torch.split(
|
982 |
+
q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
|
983 |
+
)
|
984 |
+
|
985 |
+
# Flash attention requires the input to have the shape
|
986 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
987 |
+
# therefore we just need to keep the original shape
|
988 |
+
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
|
989 |
+
compressed_kv, k_pe = torch.split(
|
990 |
+
compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
|
991 |
+
)
|
992 |
+
k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
|
993 |
+
kv = (
|
994 |
+
self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
|
995 |
+
.view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
|
996 |
+
.transpose(1, 2)
|
997 |
+
)
|
998 |
+
|
999 |
+
k_nope, value_states = torch.split(
|
1000 |
+
kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
|
1001 |
+
)
|
1002 |
+
kv_seq_len = value_states.shape[-2]
|
1003 |
+
|
1004 |
+
kv_seq_len = value_states.shape[-2]
|
1005 |
+
if past_key_value is not None:
|
1006 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
1007 |
+
|
1008 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
1009 |
+
q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
|
1010 |
+
|
1011 |
+
query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
|
1012 |
+
query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
|
1013 |
+
query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
|
1014 |
+
|
1015 |
+
key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
|
1016 |
+
key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
|
1017 |
+
key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
|
1018 |
+
|
1019 |
+
if self.q_head_dim != self.v_head_dim:
|
1020 |
+
value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
|
1021 |
+
|
1022 |
+
# TODO: support compressed_kv for kv_cache (instead of key_states, value_states) in flash_attention version
|
1023 |
+
if past_key_value is not None:
|
1024 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
1025 |
+
key_states, value_states = past_key_value.update(
|
1026 |
+
key_states, value_states, self.layer_idx, cache_kwargs
|
1027 |
+
)
|
1028 |
+
|
1029 |
+
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
|
1030 |
+
# to be able to avoid many of these transpose/reshape/view.
|
1031 |
+
query_states = query_states.transpose(1, 2)
|
1032 |
+
key_states = key_states.transpose(1, 2)
|
1033 |
+
value_states = value_states.transpose(1, 2)
|
1034 |
+
|
1035 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
1036 |
+
|
1037 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
1038 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
1039 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
1040 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
1041 |
+
# in fp32. (DeepseekV2RMSNorm handles it correctly)
|
1042 |
+
|
1043 |
+
input_dtype = query_states.dtype
|
1044 |
+
if input_dtype == torch.float32:
|
1045 |
+
# Handle the case where the model is quantized
|
1046 |
+
if hasattr(self.config, "_pre_quantization_dtype"):
|
1047 |
+
target_dtype = self.config._pre_quantization_dtype
|
1048 |
+
elif torch.is_autocast_enabled():
|
1049 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
1050 |
+
else:
|
1051 |
+
target_dtype = (
|
1052 |
+
self.q_proj.weight.dtype
|
1053 |
+
if self.q_lora_rank is None
|
1054 |
+
else self.q_a_proj.weight.dtype
|
1055 |
+
)
|
1056 |
+
|
1057 |
+
logger.warning_once(
|
1058 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
1059 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
1060 |
+
f" {target_dtype}."
|
1061 |
+
)
|
1062 |
+
|
1063 |
+
query_states = query_states.to(target_dtype)
|
1064 |
+
key_states = key_states.to(target_dtype)
|
1065 |
+
value_states = value_states.to(target_dtype)
|
1066 |
+
|
1067 |
+
attn_output = self._flash_attention_forward(
|
1068 |
+
query_states,
|
1069 |
+
key_states,
|
1070 |
+
value_states,
|
1071 |
+
attention_mask,
|
1072 |
+
q_len,
|
1073 |
+
dropout=dropout_rate,
|
1074 |
+
softmax_scale=self.softmax_scale,
|
1075 |
+
)
|
1076 |
+
if self.q_head_dim != self.v_head_dim:
|
1077 |
+
attn_output = attn_output[:, :, :, : self.v_head_dim]
|
1078 |
+
|
1079 |
+
attn_output = attn_output.reshape(
|
1080 |
+
bsz, q_len, self.num_heads * self.v_head_dim
|
1081 |
+
).contiguous()
|
1082 |
+
attn_output = self.o_proj(attn_output)
|
1083 |
+
|
1084 |
+
if not output_attentions:
|
1085 |
+
attn_weights = None
|
1086 |
+
|
1087 |
+
return attn_output, attn_weights, past_key_value
|
1088 |
+
|
1089 |
+
def _flash_attention_forward(
|
1090 |
+
self,
|
1091 |
+
query_states,
|
1092 |
+
key_states,
|
1093 |
+
value_states,
|
1094 |
+
attention_mask,
|
1095 |
+
query_length,
|
1096 |
+
dropout=0.0,
|
1097 |
+
softmax_scale=None,
|
1098 |
+
):
|
1099 |
+
"""
|
1100 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
1101 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
1102 |
+
|
1103 |
+
Args:
|
1104 |
+
query_states (`torch.Tensor`):
|
1105 |
+
Input query states to be passed to Flash Attention API
|
1106 |
+
key_states (`torch.Tensor`):
|
1107 |
+
Input key states to be passed to Flash Attention API
|
1108 |
+
value_states (`torch.Tensor`):
|
1109 |
+
Input value states to be passed to Flash Attention API
|
1110 |
+
attention_mask (`torch.Tensor`):
|
1111 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
1112 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
1113 |
+
dropout (`int`, *optional*):
|
1114 |
+
Attention dropout
|
1115 |
+
softmax_scale (`float`, *optional*):
|
1116 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
1117 |
+
"""
|
1118 |
+
if not self._flash_attn_uses_top_left_mask:
|
1119 |
+
causal = self.is_causal
|
1120 |
+
else:
|
1121 |
+
# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekV2FlashAttention2 __init__.
|
1122 |
+
causal = self.is_causal and query_length != 1
|
1123 |
+
|
1124 |
+
# Contains at least one padding token in the sequence
|
1125 |
+
if attention_mask is not None:
|
1126 |
+
batch_size = query_states.shape[0]
|
1127 |
+
(
|
1128 |
+
query_states,
|
1129 |
+
key_states,
|
1130 |
+
value_states,
|
1131 |
+
indices_q,
|
1132 |
+
cu_seq_lens,
|
1133 |
+
max_seq_lens,
|
1134 |
+
) = self._upad_input(
|
1135 |
+
query_states, key_states, value_states, attention_mask, query_length
|
1136 |
+
)
|
1137 |
+
|
1138 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
1139 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
1140 |
+
|
1141 |
+
attn_output_unpad = flash_attn_varlen_func(
|
1142 |
+
query_states,
|
1143 |
+
key_states,
|
1144 |
+
value_states,
|
1145 |
+
cu_seqlens_q=cu_seqlens_q,
|
1146 |
+
cu_seqlens_k=cu_seqlens_k,
|
1147 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
1148 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
1149 |
+
dropout_p=dropout,
|
1150 |
+
softmax_scale=softmax_scale,
|
1151 |
+
causal=causal,
|
1152 |
+
)
|
1153 |
+
|
1154 |
+
attn_output = pad_input(
|
1155 |
+
attn_output_unpad, indices_q, batch_size, query_length
|
1156 |
+
)
|
1157 |
+
else:
|
1158 |
+
attn_output = flash_attn_func(
|
1159 |
+
query_states,
|
1160 |
+
key_states,
|
1161 |
+
value_states,
|
1162 |
+
dropout,
|
1163 |
+
softmax_scale=softmax_scale,
|
1164 |
+
causal=causal,
|
1165 |
+
)
|
1166 |
+
|
1167 |
+
return attn_output
|
1168 |
+
|
1169 |
+
def _upad_input(
|
1170 |
+
self, query_layer, key_layer, value_layer, attention_mask, query_length
|
1171 |
+
):
|
1172 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
1173 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
1174 |
+
|
1175 |
+
key_layer = index_first_axis(
|
1176 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
|
1177 |
+
indices_k,
|
1178 |
+
)
|
1179 |
+
value_layer = index_first_axis(
|
1180 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
|
1181 |
+
indices_k,
|
1182 |
+
)
|
1183 |
+
if query_length == kv_seq_len:
|
1184 |
+
query_layer = index_first_axis(
|
1185 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
|
1186 |
+
indices_k,
|
1187 |
+
)
|
1188 |
+
cu_seqlens_q = cu_seqlens_k
|
1189 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
1190 |
+
indices_q = indices_k
|
1191 |
+
elif query_length == 1:
|
1192 |
+
max_seqlen_in_batch_q = 1
|
1193 |
+
cu_seqlens_q = torch.arange(
|
1194 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
1195 |
+
) # There is a memcpy here, that is very bad.
|
1196 |
+
indices_q = cu_seqlens_q[:-1]
|
1197 |
+
query_layer = query_layer.squeeze(1)
|
1198 |
+
else:
|
1199 |
+
# The -q_len: slice assumes left padding.
|
1200 |
+
attention_mask = attention_mask[:, -query_length:]
|
1201 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
|
1202 |
+
query_layer, attention_mask
|
1203 |
+
)
|
1204 |
+
|
1205 |
+
return (
|
1206 |
+
query_layer,
|
1207 |
+
key_layer,
|
1208 |
+
value_layer,
|
1209 |
+
indices_q,
|
1210 |
+
(cu_seqlens_q, cu_seqlens_k),
|
1211 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
1212 |
+
)
|
1213 |
+
|
1214 |
+
|
1215 |
+
ATTENTION_CLASSES = {
|
1216 |
+
"eager": DeepseekV2Attention,
|
1217 |
+
"flash_attention_2": DeepseekV2FlashAttention2,
|
1218 |
+
|
1219 |
+
"mla_eager": DeepseekV2Attention,
|
1220 |
+
"mla_flash_attention_2": DeepseekV2FlashAttention2,
|
1221 |
+
|
1222 |
+
"mha_eager": LlamaAttention,
|
1223 |
+
"mha_flash_attention_2": LlamaFlashAttention2
|
1224 |
+
}
|
1225 |
+
|
1226 |
+
|
1227 |
+
class DeepseekV2DecoderLayer(nn.Module):
|
1228 |
+
def __init__(self, config: DeepseekV2Config, layer_idx: int):
|
1229 |
+
super().__init__()
|
1230 |
+
self.hidden_size = config.hidden_size
|
1231 |
+
|
1232 |
+
if config.use_mla:
|
1233 |
+
attn_implementation = "mla_" + config._attn_implementation
|
1234 |
+
else:
|
1235 |
+
attn_implementation = "mha_" + config._attn_implementation
|
1236 |
+
|
1237 |
+
self.self_attn = ATTENTION_CLASSES[attn_implementation](
|
1238 |
+
config=config, layer_idx=layer_idx
|
1239 |
+
)
|
1240 |
+
|
1241 |
+
self.mlp = (
|
1242 |
+
DeepseekV2MoE(config)
|
1243 |
+
if (
|
1244 |
+
config.n_routed_experts is not None
|
1245 |
+
and layer_idx >= config.first_k_dense_replace
|
1246 |
+
and layer_idx % config.moe_layer_freq == 0
|
1247 |
+
)
|
1248 |
+
else DeepseekV2MLP(config)
|
1249 |
+
)
|
1250 |
+
self.input_layernorm = DeepseekV2RMSNorm(
|
1251 |
+
config.hidden_size, eps=config.rms_norm_eps
|
1252 |
+
)
|
1253 |
+
self.post_attention_layernorm = DeepseekV2RMSNorm(
|
1254 |
+
config.hidden_size, eps=config.rms_norm_eps
|
1255 |
+
)
|
1256 |
+
|
1257 |
+
def forward(
|
1258 |
+
self,
|
1259 |
+
hidden_states: torch.Tensor,
|
1260 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1261 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1262 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
1263 |
+
output_attentions: Optional[bool] = False,
|
1264 |
+
use_cache: Optional[bool] = False,
|
1265 |
+
**kwargs,
|
1266 |
+
) -> Tuple[
|
1267 |
+
torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
|
1268 |
+
]:
|
1269 |
+
"""
|
1270 |
+
Args:
|
1271 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
1272 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
1273 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
1274 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
1275 |
+
output_attentions (`bool`, *optional*):
|
1276 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
1277 |
+
returned tensors for more detail.
|
1278 |
+
use_cache (`bool`, *optional*):
|
1279 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
1280 |
+
(see `past_key_values`).
|
1281 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
1282 |
+
"""
|
1283 |
+
if "padding_mask" in kwargs:
|
1284 |
+
warnings.warn(
|
1285 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
1286 |
+
)
|
1287 |
+
residual = hidden_states
|
1288 |
+
|
1289 |
+
hidden_states = self.input_layernorm(hidden_states)
|
1290 |
+
|
1291 |
+
# Self Attention
|
1292 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
1293 |
+
hidden_states=hidden_states,
|
1294 |
+
attention_mask=attention_mask,
|
1295 |
+
position_ids=position_ids,
|
1296 |
+
past_key_value=past_key_value,
|
1297 |
+
output_attentions=output_attentions,
|
1298 |
+
use_cache=use_cache,
|
1299 |
+
**kwargs,
|
1300 |
+
)
|
1301 |
+
hidden_states = residual + hidden_states
|
1302 |
+
|
1303 |
+
# Fully Connected
|
1304 |
+
residual = hidden_states
|
1305 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
1306 |
+
hidden_states = self.mlp(hidden_states)
|
1307 |
+
hidden_states = residual + hidden_states
|
1308 |
+
|
1309 |
+
outputs = (hidden_states,)
|
1310 |
+
|
1311 |
+
if output_attentions:
|
1312 |
+
outputs += (self_attn_weights,)
|
1313 |
+
|
1314 |
+
if use_cache:
|
1315 |
+
outputs += (present_key_value,)
|
1316 |
+
|
1317 |
+
return outputs
|
1318 |
+
|
1319 |
+
|
1320 |
+
DeepseekV2_START_DOCSTRING = r"""
|
1321 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
1322 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
1323 |
+
etc.)
|
1324 |
+
|
1325 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
1326 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
1327 |
+
and behavior.
|
1328 |
+
|
1329 |
+
Parameters:
|
1330 |
+
config ([`DeepseekV2Config`]):
|
1331 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
1332 |
+
load the weights associated with the model, only the configuration. Check out the
|
1333 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
1334 |
+
"""
|
1335 |
+
|
1336 |
+
|
1337 |
+
@add_start_docstrings(
|
1338 |
+
"The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
|
1339 |
+
DeepseekV2_START_DOCSTRING,
|
1340 |
+
)
|
1341 |
+
class DeepseekV2PreTrainedModel(PreTrainedModel):
|
1342 |
+
config_class = DeepseekV2Config
|
1343 |
+
base_model_prefix = "model"
|
1344 |
+
supports_gradient_checkpointing = True
|
1345 |
+
_no_split_modules = ["DeepseekV2DecoderLayer"]
|
1346 |
+
_skip_keys_device_placement = "past_key_values"
|
1347 |
+
_supports_flash_attn_2 = True
|
1348 |
+
_supports_cache_class = True
|
1349 |
+
|
1350 |
+
def _init_weights(self, module):
|
1351 |
+
std = self.config.initializer_range
|
1352 |
+
if isinstance(module, nn.Linear):
|
1353 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
1354 |
+
if module.bias is not None:
|
1355 |
+
module.bias.data.zero_()
|
1356 |
+
elif isinstance(module, nn.Embedding):
|
1357 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
1358 |
+
if module.padding_idx is not None:
|
1359 |
+
module.weight.data[module.padding_idx].zero_()
|
1360 |
+
|
1361 |
+
|
1362 |
+
DeepseekV2_INPUTS_DOCSTRING = r"""
|
1363 |
+
Args:
|
1364 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
1365 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
1366 |
+
it.
|
1367 |
+
|
1368 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
1369 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
1370 |
+
|
1371 |
+
[What are input IDs?](../glossary#input-ids)
|
1372 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1373 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
1374 |
+
|
1375 |
+
- 1 for tokens that are **not masked**,
|
1376 |
+
- 0 for tokens that are **masked**.
|
1377 |
+
|
1378 |
+
[What are attention masks?](../glossary#attention-mask)
|
1379 |
+
|
1380 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
1381 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
1382 |
+
|
1383 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
1384 |
+
`past_key_values`).
|
1385 |
+
|
1386 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
1387 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
1388 |
+
information on the default strategy.
|
1389 |
+
|
1390 |
+
- 1 indicates the head is **not masked**,
|
1391 |
+
- 0 indicates the head is **masked**.
|
1392 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1393 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
1394 |
+
config.n_positions - 1]`.
|
1395 |
+
|
1396 |
+
[What are position IDs?](../glossary#position-ids)
|
1397 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
1398 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
1399 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
1400 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
1401 |
+
|
1402 |
+
Two formats are allowed:
|
1403 |
+
- a [`~cache_utils.Cache`] instance;
|
1404 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
1405 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
1406 |
+
cache format.
|
1407 |
+
|
1408 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
1409 |
+
legacy cache format will be returned.
|
1410 |
+
|
1411 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
1412 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
1413 |
+
of shape `(batch_size, sequence_length)`.
|
1414 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
1415 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
1416 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
1417 |
+
model's internal embedding lookup matrix.
|
1418 |
+
use_cache (`bool`, *optional*):
|
1419 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
1420 |
+
`past_key_values`).
|
1421 |
+
output_attentions (`bool`, *optional*):
|
1422 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
1423 |
+
tensors for more detail.
|
1424 |
+
output_hidden_states (`bool`, *optional*):
|
1425 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
1426 |
+
more detail.
|
1427 |
+
return_dict (`bool`, *optional*):
|
1428 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
1429 |
+
"""
|
1430 |
+
|
1431 |
+
|
1432 |
+
@add_start_docstrings(
|
1433 |
+
"The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
|
1434 |
+
DeepseekV2_START_DOCSTRING,
|
1435 |
+
)
|
1436 |
+
class DeepseekV2Model(DeepseekV2PreTrainedModel):
|
1437 |
+
"""
|
1438 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV2DecoderLayer`]
|
1439 |
+
|
1440 |
+
Args:
|
1441 |
+
config: DeepseekV2Config
|
1442 |
+
"""
|
1443 |
+
|
1444 |
+
def __init__(self, config: DeepseekV2Config):
|
1445 |
+
super().__init__(config)
|
1446 |
+
self.padding_idx = config.pad_token_id
|
1447 |
+
self.vocab_size = config.vocab_size
|
1448 |
+
|
1449 |
+
self.embed_tokens = nn.Embedding(
|
1450 |
+
config.vocab_size, config.hidden_size, self.padding_idx
|
1451 |
+
)
|
1452 |
+
self.layers = nn.ModuleList(
|
1453 |
+
[
|
1454 |
+
DeepseekV2DecoderLayer(config, layer_idx)
|
1455 |
+
for layer_idx in range(config.num_hidden_layers)
|
1456 |
+
]
|
1457 |
+
)
|
1458 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
1459 |
+
self.norm = DeepseekV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
1460 |
+
|
1461 |
+
self.gradient_checkpointing = False
|
1462 |
+
# Initialize weights and apply final processing
|
1463 |
+
self.post_init()
|
1464 |
+
|
1465 |
+
def get_input_embeddings(self):
|
1466 |
+
return self.embed_tokens
|
1467 |
+
|
1468 |
+
def set_input_embeddings(self, value):
|
1469 |
+
self.embed_tokens = value
|
1470 |
+
|
1471 |
+
@add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
|
1472 |
+
def forward(
|
1473 |
+
self,
|
1474 |
+
input_ids: torch.LongTensor = None,
|
1475 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1476 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1477 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1478 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1479 |
+
use_cache: Optional[bool] = None,
|
1480 |
+
output_attentions: Optional[bool] = None,
|
1481 |
+
output_hidden_states: Optional[bool] = None,
|
1482 |
+
return_dict: Optional[bool] = None,
|
1483 |
+
cache_position: Optional[torch.LongTensor] = None
|
1484 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
1485 |
+
output_attentions = (
|
1486 |
+
output_attentions
|
1487 |
+
if output_attentions is not None
|
1488 |
+
else self.config.output_attentions
|
1489 |
+
)
|
1490 |
+
output_hidden_states = (
|
1491 |
+
output_hidden_states
|
1492 |
+
if output_hidden_states is not None
|
1493 |
+
else self.config.output_hidden_states
|
1494 |
+
)
|
1495 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1496 |
+
|
1497 |
+
return_dict = (
|
1498 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1499 |
+
)
|
1500 |
+
|
1501 |
+
# retrieve input_ids and inputs_embeds
|
1502 |
+
if input_ids is not None and inputs_embeds is not None:
|
1503 |
+
raise ValueError(
|
1504 |
+
"You cannot specify both input_ids and inputs_embeds at the same time"
|
1505 |
+
)
|
1506 |
+
elif input_ids is not None:
|
1507 |
+
batch_size, seq_length = input_ids.shape[:2]
|
1508 |
+
elif inputs_embeds is not None:
|
1509 |
+
batch_size, seq_length = inputs_embeds.shape[:2]
|
1510 |
+
else:
|
1511 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
1512 |
+
|
1513 |
+
if self.gradient_checkpointing and self.training:
|
1514 |
+
if use_cache:
|
1515 |
+
logger.warning_once(
|
1516 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
|
1517 |
+
)
|
1518 |
+
use_cache = False
|
1519 |
+
|
1520 |
+
past_key_values_length = 0
|
1521 |
+
if use_cache:
|
1522 |
+
use_legacy_cache = not isinstance(past_key_values, Cache)
|
1523 |
+
if use_legacy_cache:
|
1524 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
1525 |
+
past_key_values_length = past_key_values.get_usable_length(seq_length)
|
1526 |
+
|
1527 |
+
if position_ids is None:
|
1528 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
1529 |
+
position_ids = torch.arange(
|
1530 |
+
past_key_values_length,
|
1531 |
+
seq_length + past_key_values_length,
|
1532 |
+
dtype=torch.long,
|
1533 |
+
device=device,
|
1534 |
+
)
|
1535 |
+
position_ids = position_ids.unsqueeze(0)
|
1536 |
+
|
1537 |
+
if inputs_embeds is None:
|
1538 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
1539 |
+
|
1540 |
+
if self._use_flash_attention_2:
|
1541 |
+
# 2d mask is passed through the layers
|
1542 |
+
attention_mask = (
|
1543 |
+
attention_mask
|
1544 |
+
if (attention_mask is not None and 0 in attention_mask)
|
1545 |
+
else None
|
1546 |
+
)
|
1547 |
+
else:
|
1548 |
+
# 4d mask is passed through the layers
|
1549 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
1550 |
+
attention_mask,
|
1551 |
+
(batch_size, seq_length),
|
1552 |
+
inputs_embeds,
|
1553 |
+
past_key_values_length,
|
1554 |
+
)
|
1555 |
+
|
1556 |
+
# embed positions
|
1557 |
+
hidden_states = inputs_embeds
|
1558 |
+
|
1559 |
+
# decoder layers
|
1560 |
+
all_hidden_states = () if output_hidden_states else None
|
1561 |
+
all_self_attns = () if output_attentions else None
|
1562 |
+
next_decoder_cache = None
|
1563 |
+
|
1564 |
+
for decoder_layer in self.layers:
|
1565 |
+
if output_hidden_states:
|
1566 |
+
all_hidden_states += (hidden_states,)
|
1567 |
+
|
1568 |
+
if self.gradient_checkpointing and self.training:
|
1569 |
+
layer_outputs = self._gradient_checkpointing_func(
|
1570 |
+
decoder_layer.__call__,
|
1571 |
+
hidden_states,
|
1572 |
+
attention_mask,
|
1573 |
+
position_ids,
|
1574 |
+
past_key_values,
|
1575 |
+
output_attentions,
|
1576 |
+
use_cache,
|
1577 |
+
)
|
1578 |
+
else:
|
1579 |
+
layer_outputs = decoder_layer(
|
1580 |
+
hidden_states,
|
1581 |
+
attention_mask=attention_mask,
|
1582 |
+
position_ids=position_ids,
|
1583 |
+
past_key_value=past_key_values,
|
1584 |
+
output_attentions=output_attentions,
|
1585 |
+
use_cache=use_cache,
|
1586 |
+
)
|
1587 |
+
|
1588 |
+
hidden_states = layer_outputs[0]
|
1589 |
+
|
1590 |
+
if use_cache:
|
1591 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
1592 |
+
|
1593 |
+
if output_attentions:
|
1594 |
+
all_self_attns += (layer_outputs[1],)
|
1595 |
+
|
1596 |
+
hidden_states = self.norm(hidden_states)
|
1597 |
+
|
1598 |
+
# add hidden states from the last decoder layer
|
1599 |
+
if output_hidden_states:
|
1600 |
+
all_hidden_states += (hidden_states,)
|
1601 |
+
|
1602 |
+
next_cache = None
|
1603 |
+
if use_cache:
|
1604 |
+
next_cache = (
|
1605 |
+
next_decoder_cache.to_legacy_cache()
|
1606 |
+
if use_legacy_cache
|
1607 |
+
else next_decoder_cache
|
1608 |
+
)
|
1609 |
+
if not return_dict:
|
1610 |
+
return tuple(
|
1611 |
+
v
|
1612 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
|
1613 |
+
if v is not None
|
1614 |
+
)
|
1615 |
+
return BaseModelOutputWithPast(
|
1616 |
+
last_hidden_state=hidden_states,
|
1617 |
+
past_key_values=next_cache,
|
1618 |
+
hidden_states=all_hidden_states,
|
1619 |
+
attentions=all_self_attns,
|
1620 |
+
)
|
1621 |
+
|
1622 |
+
|
1623 |
+
class DeepseekV2ForCausalLM(DeepseekV2PreTrainedModel):
|
1624 |
+
_tied_weights_keys = ["lm_head.weight"]
|
1625 |
+
|
1626 |
+
def __init__(self, config):
|
1627 |
+
super().__init__(config)
|
1628 |
+
self.model = DeepseekV2Model(config)
|
1629 |
+
self.vocab_size = config.vocab_size
|
1630 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
1631 |
+
|
1632 |
+
# Initialize weights and apply final processing
|
1633 |
+
self.post_init()
|
1634 |
+
|
1635 |
+
def get_input_embeddings(self):
|
1636 |
+
return self.model.embed_tokens
|
1637 |
+
|
1638 |
+
def set_input_embeddings(self, value):
|
1639 |
+
self.model.embed_tokens = value
|
1640 |
+
|
1641 |
+
def get_output_embeddings(self):
|
1642 |
+
return self.lm_head
|
1643 |
+
|
1644 |
+
def set_output_embeddings(self, new_embeddings):
|
1645 |
+
self.lm_head = new_embeddings
|
1646 |
+
|
1647 |
+
def set_decoder(self, decoder):
|
1648 |
+
self.model = decoder
|
1649 |
+
|
1650 |
+
def get_decoder(self):
|
1651 |
+
return self.model
|
1652 |
+
|
1653 |
+
@add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
|
1654 |
+
@replace_return_docstrings(
|
1655 |
+
output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
|
1656 |
+
)
|
1657 |
+
def forward(
|
1658 |
+
self,
|
1659 |
+
input_ids: torch.LongTensor = None,
|
1660 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1661 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1662 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1663 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1664 |
+
labels: Optional[torch.LongTensor] = None,
|
1665 |
+
use_cache: Optional[bool] = None,
|
1666 |
+
output_attentions: Optional[bool] = None,
|
1667 |
+
output_hidden_states: Optional[bool] = None,
|
1668 |
+
return_dict: Optional[bool] = None,
|
1669 |
+
cache_position: Optional[torch.LongTensor] = None
|
1670 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1671 |
+
r"""
|
1672 |
+
Args:
|
1673 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1674 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
|
1675 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1676 |
+
(masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
|
1677 |
+
|
1678 |
+
Returns:
|
1679 |
+
|
1680 |
+
Example:
|
1681 |
+
|
1682 |
+
```python
|
1683 |
+
>>> from transformers import AutoTokenizer, DeepseekV2ForCausalLM
|
1684 |
+
|
1685 |
+
>>> model = DeepseekV2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
1686 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
1687 |
+
|
1688 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
1689 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1690 |
+
|
1691 |
+
>>> # Generate
|
1692 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1693 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1694 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
1695 |
+
```"""
|
1696 |
+
output_attentions = (
|
1697 |
+
output_attentions
|
1698 |
+
if output_attentions is not None
|
1699 |
+
else self.config.output_attentions
|
1700 |
+
)
|
1701 |
+
output_hidden_states = (
|
1702 |
+
output_hidden_states
|
1703 |
+
if output_hidden_states is not None
|
1704 |
+
else self.config.output_hidden_states
|
1705 |
+
)
|
1706 |
+
return_dict = (
|
1707 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1708 |
+
)
|
1709 |
+
|
1710 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1711 |
+
outputs = self.model(
|
1712 |
+
input_ids=input_ids,
|
1713 |
+
attention_mask=attention_mask,
|
1714 |
+
position_ids=position_ids,
|
1715 |
+
past_key_values=past_key_values,
|
1716 |
+
inputs_embeds=inputs_embeds,
|
1717 |
+
use_cache=use_cache,
|
1718 |
+
output_attentions=output_attentions,
|
1719 |
+
output_hidden_states=output_hidden_states,
|
1720 |
+
return_dict=return_dict,
|
1721 |
+
cache_position=cache_position
|
1722 |
+
)
|
1723 |
+
|
1724 |
+
hidden_states = outputs[0]
|
1725 |
+
logits = self.lm_head(hidden_states)
|
1726 |
+
logits = logits.float()
|
1727 |
+
|
1728 |
+
loss = None
|
1729 |
+
if labels is not None:
|
1730 |
+
# Shift so that tokens < n predict n
|
1731 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1732 |
+
shift_labels = labels[..., 1:].contiguous()
|
1733 |
+
# Flatten the tokens
|
1734 |
+
loss_fct = CrossEntropyLoss()
|
1735 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1736 |
+
shift_labels = shift_labels.view(-1)
|
1737 |
+
# Enable model parallelism
|
1738 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1739 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1740 |
+
|
1741 |
+
if not return_dict:
|
1742 |
+
output = (logits,) + outputs[1:]
|
1743 |
+
return (loss,) + output if loss is not None else output
|
1744 |
+
|
1745 |
+
return CausalLMOutputWithPast(
|
1746 |
+
loss=loss,
|
1747 |
+
logits=logits,
|
1748 |
+
past_key_values=outputs.past_key_values,
|
1749 |
+
hidden_states=outputs.hidden_states,
|
1750 |
+
attentions=outputs.attentions,
|
1751 |
+
)
|
1752 |
+
|
1753 |
+
def prepare_inputs_for_generation(
|
1754 |
+
self,
|
1755 |
+
input_ids,
|
1756 |
+
past_key_values=None,
|
1757 |
+
attention_mask=None,
|
1758 |
+
inputs_embeds=None,
|
1759 |
+
**kwargs,
|
1760 |
+
):
|
1761 |
+
past_length = 0
|
1762 |
+
if past_key_values is not None:
|
1763 |
+
if isinstance(past_key_values, Cache):
|
1764 |
+
cache_length = past_key_values.get_seq_length()
|
1765 |
+
past_length = past_key_values.seen_tokens
|
1766 |
+
max_cache_length = past_key_values.get_max_length()
|
1767 |
+
else:
|
1768 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
1769 |
+
max_cache_length = None
|
1770 |
+
|
1771 |
+
# Keep only the unprocessed tokens:
|
1772 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
1773 |
+
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
|
1774 |
+
# input)
|
1775 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
1776 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
|
1777 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
1778 |
+
# input_ids based on the past_length.
|
1779 |
+
elif past_length < input_ids.shape[1]:
|
1780 |
+
input_ids = input_ids[:, past_length:]
|
1781 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
1782 |
+
|
1783 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
1784 |
+
if (
|
1785 |
+
max_cache_length is not None
|
1786 |
+
and attention_mask is not None
|
1787 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
1788 |
+
):
|
1789 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
1790 |
+
|
1791 |
+
position_ids = kwargs.get("position_ids", None)
|
1792 |
+
if attention_mask is not None and position_ids is None:
|
1793 |
+
# create position_ids on the fly for batch generation
|
1794 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1795 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1796 |
+
if past_key_values:
|
1797 |
+
position_ids = position_ids[:, -input_ids.shape[1]:]
|
1798 |
+
|
1799 |
+
if self.generation_config.cache_implementation == "static":
|
1800 |
+
# generation with static cache
|
1801 |
+
cache_position = kwargs.get("cache_position", None)
|
1802 |
+
if cache_position is None:
|
1803 |
+
past_length = 0
|
1804 |
+
else:
|
1805 |
+
past_length = cache_position[-1] + 1
|
1806 |
+
input_ids = input_ids[:, past_length:]
|
1807 |
+
position_ids = position_ids[:, past_length:]
|
1808 |
+
|
1809 |
+
# TODO @gante we should only keep a `cache_position` in generate, and do +=1.
|
1810 |
+
# same goes for position ids. Could also help with continued generation.
|
1811 |
+
cache_position = torch.arange(past_length, past_length + position_ids.shape[-1], device=position_ids.device)
|
1812 |
+
|
1813 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1814 |
+
if inputs_embeds is not None and past_key_values is None:
|
1815 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1816 |
+
else:
|
1817 |
+
# The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
|
1818 |
+
# recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
|
1819 |
+
# TODO: use `next_tokens` directly instead.
|
1820 |
+
model_inputs = {"input_ids": input_ids.contiguous()}
|
1821 |
+
|
1822 |
+
model_inputs.update(
|
1823 |
+
{
|
1824 |
+
"position_ids": position_ids.contiguous(),
|
1825 |
+
"cache_position": cache_position,
|
1826 |
+
"past_key_values": past_key_values,
|
1827 |
+
"use_cache": kwargs.get("use_cache"),
|
1828 |
+
"attention_mask": attention_mask,
|
1829 |
+
}
|
1830 |
+
)
|
1831 |
+
return model_inputs
|
1832 |
+
|
1833 |
+
@staticmethod
|
1834 |
+
def _reorder_cache(past_key_values, beam_idx):
|
1835 |
+
reordered_past = ()
|
1836 |
+
for layer_past in past_key_values:
|
1837 |
+
reordered_past += (
|
1838 |
+
tuple(
|
1839 |
+
past_state.index_select(0, beam_idx.to(past_state.device))
|
1840 |
+
for past_state in layer_past
|
1841 |
+
),
|
1842 |
+
)
|
1843 |
+
return reordered_past
|
1844 |
+
|
1845 |
+
|
1846 |
+
@add_start_docstrings(
|
1847 |
+
"""
|
1848 |
+
The DeepseekV2 Model transformer with a sequence classification head on top (linear layer).
|
1849 |
+
|
1850 |
+
[`DeepseekV2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
1851 |
+
(e.g. GPT-2) do.
|
1852 |
+
|
1853 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
1854 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
1855 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
1856 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
1857 |
+
each row of the batch).
|
1858 |
+
""",
|
1859 |
+
DeepseekV2_START_DOCSTRING,
|
1860 |
+
)
|
1861 |
+
class DeepseekV2ForSequenceClassification(DeepseekV2PreTrainedModel):
|
1862 |
+
def __init__(self, config):
|
1863 |
+
super().__init__(config)
|
1864 |
+
self.num_labels = config.num_labels
|
1865 |
+
self.model = DeepseekV2Model(config)
|
1866 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
1867 |
+
|
1868 |
+
# Initialize weights and apply final processing
|
1869 |
+
self.post_init()
|
1870 |
+
|
1871 |
+
def get_input_embeddings(self):
|
1872 |
+
return self.model.embed_tokens
|
1873 |
+
|
1874 |
+
def set_input_embeddings(self, value):
|
1875 |
+
self.model.embed_tokens = value
|
1876 |
+
|
1877 |
+
@add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
|
1878 |
+
def forward(
|
1879 |
+
self,
|
1880 |
+
input_ids: torch.LongTensor = None,
|
1881 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1882 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1883 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1884 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1885 |
+
labels: Optional[torch.LongTensor] = None,
|
1886 |
+
use_cache: Optional[bool] = None,
|
1887 |
+
output_attentions: Optional[bool] = None,
|
1888 |
+
output_hidden_states: Optional[bool] = None,
|
1889 |
+
return_dict: Optional[bool] = None,
|
1890 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1891 |
+
r"""
|
1892 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1893 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
|
1894 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1895 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1896 |
+
"""
|
1897 |
+
return_dict = (
|
1898 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1899 |
+
)
|
1900 |
+
|
1901 |
+
transformer_outputs = self.model(
|
1902 |
+
input_ids,
|
1903 |
+
attention_mask=attention_mask,
|
1904 |
+
position_ids=position_ids,
|
1905 |
+
past_key_values=past_key_values,
|
1906 |
+
inputs_embeds=inputs_embeds,
|
1907 |
+
use_cache=use_cache,
|
1908 |
+
output_attentions=output_attentions,
|
1909 |
+
output_hidden_states=output_hidden_states,
|
1910 |
+
return_dict=return_dict,
|
1911 |
+
)
|
1912 |
+
hidden_states = transformer_outputs[0]
|
1913 |
+
logits = self.score(hidden_states)
|
1914 |
+
|
1915 |
+
if input_ids is not None:
|
1916 |
+
batch_size = input_ids.shape[0]
|
1917 |
+
else:
|
1918 |
+
batch_size = inputs_embeds.shape[0]
|
1919 |
+
|
1920 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
1921 |
+
raise ValueError(
|
1922 |
+
"Cannot handle batch sizes > 1 if no padding token is defined."
|
1923 |
+
)
|
1924 |
+
if self.config.pad_token_id is None:
|
1925 |
+
sequence_lengths = -1
|
1926 |
+
else:
|
1927 |
+
if input_ids is not None:
|
1928 |
+
sequence_lengths = (
|
1929 |
+
torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
1930 |
+
).to(logits.device)
|
1931 |
+
else:
|
1932 |
+
sequence_lengths = -1
|
1933 |
+
|
1934 |
+
pooled_logits = logits[
|
1935 |
+
torch.arange(batch_size, device=logits.device), sequence_lengths
|
1936 |
+
]
|
1937 |
+
|
1938 |
+
loss = None
|
1939 |
+
if labels is not None:
|
1940 |
+
labels = labels.to(logits.device)
|
1941 |
+
if self.config.problem_type is None:
|
1942 |
+
if self.num_labels == 1:
|
1943 |
+
self.config.problem_type = "regression"
|
1944 |
+
elif self.num_labels > 1 and (
|
1945 |
+
labels.dtype == torch.long or labels.dtype == torch.int
|
1946 |
+
):
|
1947 |
+
self.config.problem_type = "single_label_classification"
|
1948 |
+
else:
|
1949 |
+
self.config.problem_type = "multi_label_classification"
|
1950 |
+
|
1951 |
+
if self.config.problem_type == "regression":
|
1952 |
+
loss_fct = MSELoss()
|
1953 |
+
if self.num_labels == 1:
|
1954 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1955 |
+
else:
|
1956 |
+
loss = loss_fct(pooled_logits, labels)
|
1957 |
+
elif self.config.problem_type == "single_label_classification":
|
1958 |
+
loss_fct = CrossEntropyLoss()
|
1959 |
+
loss = loss_fct(
|
1960 |
+
pooled_logits.view(-1, self.num_labels), labels.view(-1)
|
1961 |
+
)
|
1962 |
+
elif self.config.problem_type == "multi_label_classification":
|
1963 |
+
loss_fct = BCEWithLogitsLoss()
|
1964 |
+
loss = loss_fct(pooled_logits, labels)
|
1965 |
+
if not return_dict:
|
1966 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1967 |
+
return ((loss,) + output) if loss is not None else output
|
1968 |
+
|
1969 |
+
return SequenceClassifierOutputWithPast(
|
1970 |
+
loss=loss,
|
1971 |
+
logits=pooled_logits,
|
1972 |
+
past_key_values=transformer_outputs.past_key_values,
|
1973 |
+
hidden_states=transformer_outputs.hidden_states,
|
1974 |
+
attentions=transformer_outputs.attentions,
|
1975 |
+
)
|
deepseek_vl2/models/modeling_deepseek_vl_v2.py
ADDED
@@ -0,0 +1,697 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from attrdict import AttrDict
|
2 |
+
from dataclasses import dataclass
|
3 |
+
import logging
|
4 |
+
import gc
|
5 |
+
|
6 |
+
from einops import rearrange, repeat
|
7 |
+
from typing import Optional, List, Tuple, Callable, Union
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import torch.nn as nn
|
11 |
+
import torch.nn.functional as F
|
12 |
+
|
13 |
+
from transformers.utils import (
|
14 |
+
add_start_docstrings,
|
15 |
+
add_start_docstrings_to_model_forward,
|
16 |
+
)
|
17 |
+
from transformers.modeling_outputs import ModelOutput
|
18 |
+
from transformers.configuration_utils import PretrainedConfig
|
19 |
+
from transformers import (
|
20 |
+
AutoConfig,
|
21 |
+
AutoModelForCausalLM,
|
22 |
+
PreTrainedModel
|
23 |
+
)
|
24 |
+
from transformers.utils import logging
|
25 |
+
|
26 |
+
from .siglip_vit import VisionTransformer
|
27 |
+
from .configuration_deepseek import DeepseekV2Config
|
28 |
+
from .modeling_deepseek import DeepseekV2ForCausalLM
|
29 |
+
|
30 |
+
|
31 |
+
logger = logging.get_logger(__name__)
|
32 |
+
|
33 |
+
|
34 |
+
class MlpProjector(nn.Module):
|
35 |
+
|
36 |
+
def __init__(self, cfg):
|
37 |
+
|
38 |
+
super().__init__()
|
39 |
+
|
40 |
+
self.cfg = cfg
|
41 |
+
|
42 |
+
if cfg.projector_type == "identity":
|
43 |
+
modules = nn.Identity()
|
44 |
+
|
45 |
+
elif cfg.projector_type == "linear":
|
46 |
+
modules = nn.Linear(cfg.input_dim, cfg.n_embed)
|
47 |
+
|
48 |
+
elif cfg.projector_type == "mlp_gelu":
|
49 |
+
mlp_depth = cfg.depth
|
50 |
+
modules = [nn.Linear(cfg.input_dim, cfg.n_embed)]
|
51 |
+
for _ in range(1, mlp_depth):
|
52 |
+
modules.append(nn.GELU())
|
53 |
+
modules.append(nn.Linear(cfg.n_embed, cfg.n_embed))
|
54 |
+
modules = nn.Sequential(*modules)
|
55 |
+
|
56 |
+
elif cfg.projector_type == "downsample_mlp_gelu":
|
57 |
+
mlp_depth = cfg.depth
|
58 |
+
mlp_ratio = cfg.mlp_ratio
|
59 |
+
modules = [nn.Linear(cfg.input_dim * cfg.downsample_ratio * cfg.downsample_ratio, cfg.n_embed * mlp_ratio)]
|
60 |
+
for _ in range(1, mlp_depth - 1):
|
61 |
+
modules.append(nn.GELU())
|
62 |
+
modules.append(nn.Linear(cfg.n_embed * mlp_ratio, cfg.n_embed * mlp_ratio))
|
63 |
+
modules.append(nn.GELU())
|
64 |
+
modules.append(nn.Linear(cfg.n_embed * mlp_ratio, cfg.n_embed))
|
65 |
+
modules = nn.Sequential(*modules)
|
66 |
+
|
67 |
+
else:
|
68 |
+
raise ValueError(f"Unknown projector type: {cfg.projector_type}")
|
69 |
+
|
70 |
+
if cfg.token_pooling:
|
71 |
+
self.token_pooling_layer = nn.Linear(cfg.input_dim * 4, cfg.input_dim)
|
72 |
+
|
73 |
+
self.layers = modules
|
74 |
+
|
75 |
+
def forward(self, x):
|
76 |
+
if self.cfg.token_pooling:
|
77 |
+
batch_size, wxh, channels = x.shape
|
78 |
+
w = h = int(wxh ** 0.5)
|
79 |
+
x = x.view(batch_size, w, h, channels)
|
80 |
+
x = x.permute(0, 3, 1, 2)
|
81 |
+
# import ipdb; ipdb.set_trace()
|
82 |
+
patches = x.unfold(2, 2, 2).unfold(3, 2, 2)
|
83 |
+
batch_size, channels, h_patches, w_patches, _, _ = patches.size()
|
84 |
+
# 在通道维度上拼接
|
85 |
+
patches = patches.contiguous().view(batch_size, channels, h_patches * w_patches, -1)
|
86 |
+
|
87 |
+
# 通过线性层
|
88 |
+
patches = patches.permute(0, 2, 1, 3).contiguous()
|
89 |
+
patches = patches.view(batch_size, h_patches * w_patches, channels * 4)
|
90 |
+
|
91 |
+
x = self.token_pooling_layer(patches)
|
92 |
+
|
93 |
+
elif self.cfg.projector_type == 'downsample_mlp_gelu':
|
94 |
+
bs, hw, input_dim = x.shape
|
95 |
+
h = w = int((hw) ** 0.5)
|
96 |
+
|
97 |
+
"""compute padding"""
|
98 |
+
if h % self.cfg.downsample_ratio:
|
99 |
+
pad = self.cfg.downsample_ratio - h % self.cfg.downsample_ratio
|
100 |
+
else:
|
101 |
+
pad = 0
|
102 |
+
x = x.reshape(bs, h, w, input_dim)
|
103 |
+
if pad > 0:
|
104 |
+
x = F.pad(x, (0, 0, 0, pad, 0, pad), "constant", 0)
|
105 |
+
|
106 |
+
"""4 to 1 concat"""
|
107 |
+
x = x.permute(0, 3, 1, 2) # B, C, H, W
|
108 |
+
x = F.unfold(x, kernel_size=self.cfg.downsample_ratio, stride=self.cfg.downsample_ratio,
|
109 |
+
padding=0) # B, C*4, HW // 4
|
110 |
+
x = x.permute(0, 2, 1)
|
111 |
+
|
112 |
+
return self.layers(x)
|
113 |
+
|
114 |
+
|
115 |
+
class VisionEncoderConfig(PretrainedConfig):
|
116 |
+
model_type: str = "vision"
|
117 |
+
|
118 |
+
model_name: str = "siglip_large_patch16_384"
|
119 |
+
image_size: int = 384
|
120 |
+
patch_size: int = 16
|
121 |
+
width: int = 1024
|
122 |
+
layers: int = 24
|
123 |
+
heads: int = 16
|
124 |
+
mlp_ratio: int = 4
|
125 |
+
global_pool: str = "map"
|
126 |
+
ignore_head: bool = True
|
127 |
+
class_token: bool = False
|
128 |
+
num_classes: int = 0
|
129 |
+
use_checkpoint: bool = False
|
130 |
+
weight_init: str = "skip"
|
131 |
+
deterministic: bool = False
|
132 |
+
num_recomputing_layers: int = 0
|
133 |
+
|
134 |
+
def __init__(
|
135 |
+
self,
|
136 |
+
model_name: str = "siglip_large_patch16_384",
|
137 |
+
image_size: int = 384,
|
138 |
+
patch_size: int = 16,
|
139 |
+
width: int = 1024,
|
140 |
+
layers: int = 24,
|
141 |
+
heads: int = 16,
|
142 |
+
mlp_ratio: int = 4,
|
143 |
+
global_pool: str = "map",
|
144 |
+
ignore_head: bool = True,
|
145 |
+
class_token: bool = False,
|
146 |
+
num_classes: int = 0,
|
147 |
+
use_checkpoint: bool = False,
|
148 |
+
**kwargs
|
149 |
+
):
|
150 |
+
self.model_name = model_name
|
151 |
+
self.image_size = image_size
|
152 |
+
self.patch_size = patch_size
|
153 |
+
self.width = width
|
154 |
+
self.layers = layers
|
155 |
+
self.heads = heads
|
156 |
+
self.mlp_ratio = mlp_ratio
|
157 |
+
self.global_pool = global_pool
|
158 |
+
self.ignore_head = ignore_head
|
159 |
+
self.class_token = class_token
|
160 |
+
self.num_classes = num_classes
|
161 |
+
self.use_checkpoint = use_checkpoint
|
162 |
+
|
163 |
+
super().__init__(**kwargs)
|
164 |
+
|
165 |
+
|
166 |
+
class MlpProjectorConfig(PretrainedConfig):
|
167 |
+
model_type = "mlp_projector"
|
168 |
+
projector_type: str = "downsample_mlp_gelu"
|
169 |
+
input_dim: int = 1152
|
170 |
+
n_embed: int = 2048
|
171 |
+
depth: int = 2
|
172 |
+
mlp_ratio: int = 1
|
173 |
+
downsample_ratio: int = 2
|
174 |
+
token_pooling: bool = False
|
175 |
+
|
176 |
+
def __init__(
|
177 |
+
self,
|
178 |
+
projector_type: str = "downsample_mlp_gelu",
|
179 |
+
input_dim: int = 1152,
|
180 |
+
n_embed: int = 2048,
|
181 |
+
depth: int = 2,
|
182 |
+
mlp_ratio: int = 1,
|
183 |
+
downsample_ratio: int = 2,
|
184 |
+
**kwargs
|
185 |
+
):
|
186 |
+
self.projector_type = projector_type
|
187 |
+
self.input_dim = input_dim
|
188 |
+
self.n_embed = n_embed
|
189 |
+
self.depth = depth
|
190 |
+
self.mlp_ratio = mlp_ratio
|
191 |
+
self.downsample_ratio = downsample_ratio
|
192 |
+
|
193 |
+
super().__init__(**kwargs)
|
194 |
+
|
195 |
+
|
196 |
+
@dataclass
|
197 |
+
class DeepSeekVLV2CausalLMOutputWithPast(ModelOutput):
|
198 |
+
"""
|
199 |
+
Base class for DeepSeek-VL2 causal language model (or autoregressive) outputs.
|
200 |
+
|
201 |
+
Args:
|
202 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
203 |
+
Language modeling loss (for next-token prediction).
|
204 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
205 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
206 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
207 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
208 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`)
|
209 |
+
|
210 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
|
211 |
+
`past_key_values` input) to speed up sequential decoding.
|
212 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
213 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
214 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
215 |
+
|
216 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
217 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
218 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
219 |
+
sequence_length)`.
|
220 |
+
|
221 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
222 |
+
heads.
|
223 |
+
rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
|
224 |
+
The rope index difference between sequence length and multimodal rope.
|
225 |
+
"""
|
226 |
+
|
227 |
+
loss: Optional[torch.FloatTensor] = None
|
228 |
+
logits: torch.FloatTensor = None
|
229 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None
|
230 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
231 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
232 |
+
rope_deltas: Optional[torch.LongTensor] = None
|
233 |
+
|
234 |
+
|
235 |
+
class DeepseekVLV2Config(PretrainedConfig):
|
236 |
+
model_type = "deepseek_vl_v2"
|
237 |
+
vision_config: VisionEncoderConfig
|
238 |
+
projector_config: MlpProjectorConfig
|
239 |
+
language_config: DeepseekV2Config
|
240 |
+
|
241 |
+
tile_tag: str = "2D"
|
242 |
+
global_view_pos: str = "head"
|
243 |
+
candidate_resolutions: Tuple[Tuple[int, int]] = ((384, 384),)
|
244 |
+
|
245 |
+
def __init__(
|
246 |
+
self,
|
247 |
+
tile_tag: str = "tile_tag",
|
248 |
+
global_view_pos: str = "head",
|
249 |
+
candidate_resolutions: Tuple[Tuple[int, int]] = ((384, 384),),
|
250 |
+
**kwargs
|
251 |
+
):
|
252 |
+
super().__init__(**kwargs)
|
253 |
+
|
254 |
+
vision_config = kwargs.get("vision_config", {})
|
255 |
+
self.vision_config = VisionEncoderConfig(**vision_config)
|
256 |
+
|
257 |
+
projector_config = kwargs.get("projector_config", {})
|
258 |
+
self.projector_config = MlpProjectorConfig(**projector_config)
|
259 |
+
|
260 |
+
language_config = kwargs.get("language_config", {})
|
261 |
+
if isinstance(language_config, DeepseekV2Config):
|
262 |
+
self.language_config = language_config
|
263 |
+
else:
|
264 |
+
self.language_config = DeepseekV2Config(**language_config)
|
265 |
+
|
266 |
+
self.tile_tag = tile_tag
|
267 |
+
self.global_view_pos = global_view_pos
|
268 |
+
self.candidate_resolutions = candidate_resolutions
|
269 |
+
|
270 |
+
|
271 |
+
class DeepseekVLV2PreTrainedModel(PreTrainedModel):
|
272 |
+
config_class = DeepseekVLV2Config
|
273 |
+
base_model_prefix = "deepseek_vl_v2"
|
274 |
+
_no_split_modules = []
|
275 |
+
_skip_keys_device_placement = "past_key_values"
|
276 |
+
|
277 |
+
|
278 |
+
class DeepseekVLV2ForCausalLM(DeepseekVLV2PreTrainedModel):
|
279 |
+
|
280 |
+
def __init__(self, config: DeepseekVLV2Config):
|
281 |
+
super().__init__(config)
|
282 |
+
|
283 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
284 |
+
|
285 |
+
# ----------- vision encoder ------------
|
286 |
+
vision_config = config.vision_config
|
287 |
+
self.vision = VisionTransformer(
|
288 |
+
img_size=vision_config.image_size,
|
289 |
+
patch_size=vision_config.patch_size,
|
290 |
+
embed_dim=vision_config.width,
|
291 |
+
depth=vision_config.layers,
|
292 |
+
num_heads=vision_config.heads,
|
293 |
+
mlp_ratio=vision_config.mlp_ratio,
|
294 |
+
class_token=vision_config.class_token,
|
295 |
+
global_pool=vision_config.global_pool,
|
296 |
+
ignore_head=vision_config.ignore_head,
|
297 |
+
weight_init=vision_config.weight_init,
|
298 |
+
num_classes=0,
|
299 |
+
deterministic=vision_config.deterministic,
|
300 |
+
num_recomputing_layers=vision_config.num_recomputing_layers
|
301 |
+
)
|
302 |
+
|
303 |
+
# ----------- vl projector ------------
|
304 |
+
projector_config = config.projector_config
|
305 |
+
self.projector = MlpProjector(projector_config)
|
306 |
+
|
307 |
+
# image token format 形式
|
308 |
+
# FIXME 目前tile tag & global_view_pos的默认取值都是之前的实验策略;后续应当去掉默认取值,改为没有取值就raise error
|
309 |
+
self.tile_tag = config.tile_tag
|
310 |
+
self.global_view_pos = config.global_view_pos
|
311 |
+
|
312 |
+
# 用于format image token sequence的特殊token
|
313 |
+
embed_std = 1 / torch.sqrt(torch.tensor(projector_config.n_embed, dtype=torch.float32))
|
314 |
+
if self.tile_tag == "2D":
|
315 |
+
# <|view_separator|>, <|\n|>
|
316 |
+
self.image_newline = nn.Parameter(torch.randn(projector_config.n_embed) * embed_std)
|
317 |
+
# fix the typo: view_seperater
|
318 |
+
self.view_seperator = nn.Parameter(torch.randn(projector_config.n_embed) * embed_std)
|
319 |
+
elif self.tile_tag == "1D":
|
320 |
+
# <|tile_x|>, <|tile_global|>
|
321 |
+
candidate_resolutions = config.candidate_resolutions
|
322 |
+
if len(candidate_resolutions) == 0:
|
323 |
+
raise ValueError(
|
324 |
+
f"len(candidate_resolutions) should be larger than 0, but got {len(candidate_resolutions)}")
|
325 |
+
tile_variants_num = len(candidate_resolutions)
|
326 |
+
self.tile_indicators = nn.Parameter(
|
327 |
+
torch.randn(size=(tile_variants_num + 1, config.aligner.params.n_embed)) * embed_std
|
328 |
+
)
|
329 |
+
else:
|
330 |
+
raise ValueError(f"tile tag should be either 1D or 2D, but got {self.tile_tag}")
|
331 |
+
|
332 |
+
# ----------- language model ------------
|
333 |
+
language_config = config.language_config
|
334 |
+
self.language = DeepseekV2ForCausalLM(language_config)
|
335 |
+
|
336 |
+
def prepare_inputs_embeds(
|
337 |
+
self,
|
338 |
+
input_ids: torch.LongTensor,
|
339 |
+
images: Optional[torch.FloatTensor] = None,
|
340 |
+
images_seq_mask: Optional[torch.LongTensor] = None,
|
341 |
+
images_spatial_crop: Optional[torch.LongTensor] = None,
|
342 |
+
**ignore_kwargs
|
343 |
+
):
|
344 |
+
"""
|
345 |
+
|
346 |
+
Args:
|
347 |
+
input_ids (torch.LongTensor): [b, T]
|
348 |
+
images (torch.FloatTensor): [b, max_n_images, 3, height, width]
|
349 |
+
images_seq_mask (torch.BoolTensor): [b, T]
|
350 |
+
images_spatial_crop (torch.LongTensor): [b, max_n_images, 2]
|
351 |
+
|
352 |
+
Returns:
|
353 |
+
input_embeds (torch.Tensor): [b, T, D]
|
354 |
+
"""
|
355 |
+
|
356 |
+
if images is None or images_spatial_crop.sum() == 0:
|
357 |
+
return self.language.get_input_embeddings()(input_ids)
|
358 |
+
|
359 |
+
bs, max_n_images, _ = images_spatial_crop.shape
|
360 |
+
batch_num_tiles = [0 for _ in range(bs)]
|
361 |
+
total_tiles = []
|
362 |
+
for idx in range(bs):
|
363 |
+
for jdx in range(max_n_images):
|
364 |
+
num_width_tiles, num_height_tiles = images_spatial_crop[idx, jdx]
|
365 |
+
if num_width_tiles == 0 or num_height_tiles == 0:
|
366 |
+
break
|
367 |
+
batch_num_tiles[idx] += (1 + num_width_tiles * num_height_tiles)
|
368 |
+
|
369 |
+
total_tiles.append(images[idx, :batch_num_tiles[idx]])
|
370 |
+
|
371 |
+
# [batch_all_tiles, 3, height, width]
|
372 |
+
total_tiles = torch.cat(total_tiles, dim=0)
|
373 |
+
assert total_tiles.shape[0] == sum(batch_num_tiles)
|
374 |
+
if total_tiles.shape[0] == 0:
|
375 |
+
return self.language.get_input_embeddings()(input_ids)
|
376 |
+
|
377 |
+
# [batch_all_tiles, vit_seq_len, c]
|
378 |
+
images_feature = self.vision(total_tiles)
|
379 |
+
|
380 |
+
# [batch_all_tiles, hw, D]
|
381 |
+
images_embeds = self.projector(images_feature)
|
382 |
+
_, hw, n_dim = images_embeds.shape
|
383 |
+
h = w = int(hw ** 0.5)
|
384 |
+
|
385 |
+
# put image tokens into the input_embeds, [b, T, D]
|
386 |
+
input_embeds = self.language.get_input_embeddings()(input_ids)
|
387 |
+
|
388 |
+
# 根据self.tile_tag & self.global_view_pos填充image token sequence
|
389 |
+
tile_index = 0
|
390 |
+
for idx in range(images_spatial_crop.shape[0]):
|
391 |
+
images_in_this_batch = []
|
392 |
+
for jdx in range(images_spatial_crop.shape[1]):
|
393 |
+
|
394 |
+
# extra global & local features
|
395 |
+
num_width_tiles, num_height_tiles = images_spatial_crop[idx, jdx]
|
396 |
+
if num_width_tiles == 0 or num_height_tiles == 0:
|
397 |
+
break
|
398 |
+
|
399 |
+
num_tiles_in_image = num_width_tiles * num_height_tiles
|
400 |
+
|
401 |
+
# [hw, D]
|
402 |
+
global_features = images_embeds[tile_index]
|
403 |
+
|
404 |
+
# [num_height_tiles * num_width_tiles, hw, D]
|
405 |
+
local_features = images_embeds[tile_index + 1: tile_index + 1 + num_tiles_in_image]
|
406 |
+
|
407 |
+
tile_index += num_tiles_in_image + 1
|
408 |
+
|
409 |
+
# format global and local features
|
410 |
+
if self.tile_tag == "2D":
|
411 |
+
|
412 |
+
# ----------------- global view add newline -----------------
|
413 |
+
# [hw, D] -> [h, w, D]
|
414 |
+
global_features = global_features.view(h, w, n_dim)
|
415 |
+
# [D] -> [h, 1, D]
|
416 |
+
new_lines_in_global = repeat(self.image_newline, "d -> h 1 d", h=h)
|
417 |
+
# cat([h, w, D], [h, 1, D], dim=1) -> [h, w + 1, D]
|
418 |
+
global_features = torch.cat([global_features, new_lines_in_global], dim=1)
|
419 |
+
# [h, w + 1, D] -> [h * (w + 1), D]
|
420 |
+
global_features = global_features.view(-1, n_dim)
|
421 |
+
|
422 |
+
# ----------------- local view add newline -----------------
|
423 |
+
# [num_height_tiles * num_width_tiles, h * w, D] -> [num_height_tiles * h, num_width_tiles * w, D]
|
424 |
+
local_features = rearrange(
|
425 |
+
local_features,
|
426 |
+
"(th tw) (h w) d -> (th h) (tw w) d",
|
427 |
+
th=num_height_tiles,
|
428 |
+
tw=num_width_tiles,
|
429 |
+
h=h,
|
430 |
+
w=w
|
431 |
+
)
|
432 |
+
|
433 |
+
# [D] -> [num_height_tiles * h, 1, D]
|
434 |
+
new_lines_in_local = repeat(
|
435 |
+
self.image_newline,
|
436 |
+
"d -> (th h) 1 d",
|
437 |
+
th=num_height_tiles,
|
438 |
+
h=h
|
439 |
+
)
|
440 |
+
|
441 |
+
# [num_height_tiles * h, num_width_tiles * w + 1, D]
|
442 |
+
local_features = torch.cat([local_features, new_lines_in_local], dim=1)
|
443 |
+
|
444 |
+
# [num_height_tiles * h, num_width_tiles * w + 1, D]
|
445 |
+
# --> [(num_height_tiles * h) * (num_width_tiles * w + 1), D]
|
446 |
+
local_features = local_features.view(-1, n_dim)
|
447 |
+
|
448 |
+
# ----------------- merge global and local tiles -----------------
|
449 |
+
if self.global_view_pos == "head":
|
450 |
+
global_local_features = torch.cat(
|
451 |
+
[global_features, self.view_seperator[None, :], local_features], dim=0)
|
452 |
+
else:
|
453 |
+
global_local_features = torch.cat(
|
454 |
+
[local_features, self.view_seperator[None, :], global_features], dim=0)
|
455 |
+
|
456 |
+
else:
|
457 |
+
# abandoned,实际上不会走这个逻辑
|
458 |
+
global_features = torch.cat(
|
459 |
+
[self.tile_indicators[0:1], global_features], dim=0
|
460 |
+
)
|
461 |
+
local_features = torch.cat(
|
462 |
+
[self.tile_indicators[1:num_tiles_in_image + 1].unsqueeze(1), local_features], dim=1
|
463 |
+
)
|
464 |
+
local_features = rearrange(local_features, 'crop_num hw d -> (crop_num hw) d')
|
465 |
+
|
466 |
+
if self.global_view_pos == "head":
|
467 |
+
global_local_features = torch.cat([global_features, local_features], dim=0)
|
468 |
+
else:
|
469 |
+
global_local_features = torch.cat([local_features, global_features], dim=0)
|
470 |
+
|
471 |
+
images_in_this_batch.append(global_local_features)
|
472 |
+
|
473 |
+
if len(images_in_this_batch) > 0:
|
474 |
+
images_in_this_batch = torch.cat(images_in_this_batch, dim=0)
|
475 |
+
input_embeds[idx].masked_scatter_(images_seq_mask[idx].unsqueeze(-1), images_in_this_batch)
|
476 |
+
|
477 |
+
return input_embeds
|
478 |
+
|
479 |
+
@torch.no_grad()
|
480 |
+
def incremental_prefilling(
|
481 |
+
self,
|
482 |
+
input_ids: Optional[torch.LongTensor] = None,
|
483 |
+
attention_mask: Optional[torch.Tensor] = None,
|
484 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
485 |
+
|
486 |
+
images: Optional[torch.FloatTensor] = None,
|
487 |
+
images_seq_mask: Optional[torch.LongTensor] = None,
|
488 |
+
images_spatial_crop: Optional[torch.LongTensor] = None,
|
489 |
+
chunk_size: int = 1024
|
490 |
+
):
|
491 |
+
if inputs_embeds is None:
|
492 |
+
inputs_embeds = self.prepare_inputs_embeds(
|
493 |
+
input_ids=input_ids,
|
494 |
+
images=images,
|
495 |
+
images_seq_mask=images_seq_mask,
|
496 |
+
images_spatial_crop=images_spatial_crop,
|
497 |
+
)
|
498 |
+
|
499 |
+
del images
|
500 |
+
del images_seq_mask
|
501 |
+
del images_spatial_crop
|
502 |
+
|
503 |
+
if attention_mask is not None:
|
504 |
+
attention_mask = attention_mask.to(inputs_embeds.device)
|
505 |
+
|
506 |
+
self._clear_cuda_cache()
|
507 |
+
|
508 |
+
bzs, seq_len, _ = inputs_embeds.shape
|
509 |
+
past_key_values = None
|
510 |
+
|
511 |
+
# remain the last token for the next forward
|
512 |
+
prefilling_len = seq_len - 1
|
513 |
+
for i in range(0, prefilling_len, chunk_size):
|
514 |
+
chunk_start = i
|
515 |
+
chunk_end = min(i + chunk_size, prefilling_len)
|
516 |
+
chunk_inputs_embeds = inputs_embeds[:, chunk_start: chunk_end]
|
517 |
+
chunk_attention_mask = attention_mask[:, 0: chunk_end]
|
518 |
+
# print(f"start = {chunk_start}, end = {chunk_end}, prefilling_len = {prefilling_len}, seq_len = {seq_len}")
|
519 |
+
|
520 |
+
# compute position_ids
|
521 |
+
if past_key_values is not None:
|
522 |
+
position_ids = torch.arange(
|
523 |
+
chunk_start,
|
524 |
+
chunk_end,
|
525 |
+
dtype=torch.long,
|
526 |
+
device=inputs_embeds.device
|
527 |
+
).unsqueeze(0)
|
528 |
+
past_key_values = self._move_past_key_values_to_gpu(past_key_values, inputs_embeds.device)
|
529 |
+
else:
|
530 |
+
position_ids = None
|
531 |
+
|
532 |
+
# chunk-forward
|
533 |
+
with torch.no_grad():
|
534 |
+
outputs = self.forward(
|
535 |
+
inputs_embeds=chunk_inputs_embeds,
|
536 |
+
attention_mask=chunk_attention_mask,
|
537 |
+
past_key_values=past_key_values,
|
538 |
+
position_ids=position_ids,
|
539 |
+
use_cache=True,
|
540 |
+
)
|
541 |
+
# update past_key_values
|
542 |
+
past_key_values = outputs.past_key_values
|
543 |
+
past_key_values = self._move_past_key_values_to_cpu(past_key_values)
|
544 |
+
|
545 |
+
del outputs, position_ids
|
546 |
+
self._clear_cuda_cache()
|
547 |
+
|
548 |
+
prefilling_key_values = []
|
549 |
+
for layer_past in past_key_values:
|
550 |
+
prefilling_key_values.append(
|
551 |
+
(
|
552 |
+
layer_past[0][:, :, 0: prefilling_len, ...].to(inputs_embeds.device),
|
553 |
+
layer_past[1][:, :, 0: prefilling_len, ...].to(inputs_embeds.device),
|
554 |
+
)
|
555 |
+
)
|
556 |
+
|
557 |
+
return inputs_embeds, prefilling_key_values
|
558 |
+
|
559 |
+
def forward(
|
560 |
+
self,
|
561 |
+
input_ids: Optional[torch.LongTensor] = None,
|
562 |
+
|
563 |
+
attention_mask: Optional[torch.Tensor] = None,
|
564 |
+
position_ids: Optional[torch.LongTensor] = None,
|
565 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
566 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
567 |
+
|
568 |
+
images: Optional[torch.FloatTensor] = None,
|
569 |
+
images_seq_mask: Optional[torch.LongTensor] = None,
|
570 |
+
images_spatial_crop: Optional[torch.LongTensor] = None,
|
571 |
+
|
572 |
+
labels: Optional[torch.LongTensor] = None,
|
573 |
+
use_cache: Optional[bool] = None,
|
574 |
+
output_attentions: Optional[bool] = None,
|
575 |
+
output_hidden_states: Optional[bool] = None,
|
576 |
+
return_dict: Optional[bool] = None,
|
577 |
+
cache_position: Optional[torch.LongTensor] = None,
|
578 |
+
):
|
579 |
+
|
580 |
+
output_attentions = (
|
581 |
+
output_attentions
|
582 |
+
if output_attentions is not None
|
583 |
+
else self.config.output_attentions
|
584 |
+
)
|
585 |
+
output_hidden_states = (
|
586 |
+
output_hidden_states
|
587 |
+
if output_hidden_states is not None
|
588 |
+
else self.config.output_hidden_states
|
589 |
+
)
|
590 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
591 |
+
|
592 |
+
return_dict = (
|
593 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
594 |
+
)
|
595 |
+
if inputs_embeds is None:
|
596 |
+
inputs_embeds = self.prepare_inputs_embeds(
|
597 |
+
input_ids=input_ids,
|
598 |
+
images=images,
|
599 |
+
images_seq_mask=images_seq_mask,
|
600 |
+
images_spatial_crop=images_spatial_crop,
|
601 |
+
)
|
602 |
+
|
603 |
+
if attention_mask is not None:
|
604 |
+
attention_mask = attention_mask.to(inputs_embeds.device)
|
605 |
+
|
606 |
+
# print(inputs_embeds.shape)
|
607 |
+
outputs = self.language.forward(
|
608 |
+
input_ids=None,
|
609 |
+
attention_mask=attention_mask,
|
610 |
+
position_ids=position_ids,
|
611 |
+
past_key_values=past_key_values,
|
612 |
+
inputs_embeds=inputs_embeds,
|
613 |
+
labels=labels,
|
614 |
+
use_cache=use_cache,
|
615 |
+
output_attentions=output_attentions,
|
616 |
+
output_hidden_states=output_hidden_states,
|
617 |
+
return_dict=return_dict,
|
618 |
+
cache_position=cache_position
|
619 |
+
)
|
620 |
+
|
621 |
+
return outputs
|
622 |
+
|
623 |
+
def _clear_cuda_cache(self):
|
624 |
+
"""clear CUDA memory cache"""
|
625 |
+
gc.collect()
|
626 |
+
if torch.cuda.is_available():
|
627 |
+
torch.cuda.empty_cache()
|
628 |
+
torch.cuda.synchronize()
|
629 |
+
|
630 |
+
def _move_past_key_values_to_cpu(self, past_key_values):
|
631 |
+
# print(f"past_key_values -> cpu")
|
632 |
+
if past_key_values is None:
|
633 |
+
return None
|
634 |
+
return tuple(tuple(t.cpu() for t in layer) for layer in past_key_values)
|
635 |
+
|
636 |
+
def _move_past_key_values_to_gpu(self, past_key_values, device="cuda:0"):
|
637 |
+
# print(f"past_key_values -> gpu")
|
638 |
+
if past_key_values is None:
|
639 |
+
return None
|
640 |
+
return tuple(tuple(t.to(device) for t in layer) for layer in past_key_values)
|
641 |
+
|
642 |
+
def prepare_inputs_for_generation(
|
643 |
+
self,
|
644 |
+
input_ids,
|
645 |
+
past_key_values=None,
|
646 |
+
inputs_embeds=None,
|
647 |
+
|
648 |
+
images: Optional[torch.FloatTensor] = None,
|
649 |
+
images_seq_mask: Optional[torch.LongTensor] = None,
|
650 |
+
images_spatial_crop: Optional[torch.LongTensor] = None,
|
651 |
+
|
652 |
+
attention_mask=None,
|
653 |
+
cache_position=None,
|
654 |
+
|
655 |
+
pixel_values=None,
|
656 |
+
image_sizes=None,
|
657 |
+
num_logits_to_keep=None,
|
658 |
+
**kwargs,
|
659 |
+
):
|
660 |
+
# Overwritten -- in specific circumstances we don't want to forward image inputs to the model
|
661 |
+
model_inputs = self.language.prepare_inputs_for_generation(
|
662 |
+
input_ids,
|
663 |
+
past_key_values=past_key_values,
|
664 |
+
inputs_embeds=inputs_embeds,
|
665 |
+
attention_mask=attention_mask,
|
666 |
+
cache_position=cache_position,
|
667 |
+
num_logits_to_keep=num_logits_to_keep,
|
668 |
+
**kwargs,
|
669 |
+
)
|
670 |
+
|
671 |
+
# If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
|
672 |
+
# Otherwise we need pixel values to be passed to model
|
673 |
+
cache_position = model_inputs["cache_position"]
|
674 |
+
if cache_position[0] == 0:
|
675 |
+
model_inputs["images"] = images
|
676 |
+
model_inputs["images_seq_mask"] = images_seq_mask
|
677 |
+
model_inputs["images_spatial_crop"] = images_spatial_crop
|
678 |
+
|
679 |
+
return model_inputs
|
680 |
+
|
681 |
+
@staticmethod
|
682 |
+
def _reorder_cache(past_key_values, beam_idx):
|
683 |
+
reordered_past = ()
|
684 |
+
for layer_past in past_key_values:
|
685 |
+
reordered_past += (
|
686 |
+
tuple(
|
687 |
+
past_state.index_select(0, beam_idx.to(past_state.device))
|
688 |
+
for past_state in layer_past
|
689 |
+
),
|
690 |
+
)
|
691 |
+
return reordered_past
|
692 |
+
|
693 |
+
|
694 |
+
AutoConfig.register("vision", VisionEncoderConfig)
|
695 |
+
AutoConfig.register("mlp_projector", MlpProjectorConfig)
|
696 |
+
AutoConfig.register("deepseek_vl_v2", DeepseekVLV2Config)
|
697 |
+
AutoModelForCausalLM.register(DeepseekVLV2Config, DeepseekVLV2ForCausalLM)
|
deepseek_vl2/models/processing_deepseek_vl_v2.py
ADDED
@@ -0,0 +1,675 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2023-2024 DeepSeek.
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of
|
4 |
+
# this software and associated documentation files (the "Software"), to deal in
|
5 |
+
# the Software without restriction, including without limitation the rights to
|
6 |
+
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
7 |
+
# the Software, and to permit persons to whom the Software is furnished to do so,
|
8 |
+
# subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in all
|
11 |
+
# copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
15 |
+
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
16 |
+
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
17 |
+
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
18 |
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
19 |
+
|
20 |
+
from dataclasses import dataclass
|
21 |
+
from typing import Dict, Tuple, List, Literal, Optional
|
22 |
+
import math
|
23 |
+
|
24 |
+
import torch
|
25 |
+
from torch.nn.utils.rnn import pad_sequence
|
26 |
+
import torchvision.transforms as T
|
27 |
+
from transformers import LlamaTokenizerFast
|
28 |
+
from transformers.processing_utils import ProcessorMixin
|
29 |
+
from PIL import Image, ImageOps
|
30 |
+
|
31 |
+
from .conversation import get_conv_template
|
32 |
+
|
33 |
+
|
34 |
+
def select_best_resolution(image_size, candidate_resolutions):
|
35 |
+
# used for cropping
|
36 |
+
original_width, original_height = image_size
|
37 |
+
best_fit = None
|
38 |
+
max_effective_resolution = 0
|
39 |
+
min_wasted_resolution = float("inf")
|
40 |
+
|
41 |
+
for width, height in candidate_resolutions:
|
42 |
+
scale = min(width / original_width, height / original_height)
|
43 |
+
downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
|
44 |
+
effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
|
45 |
+
wasted_resolution = (width * height) - effective_resolution
|
46 |
+
|
47 |
+
if effective_resolution > max_effective_resolution or (effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution):
|
48 |
+
max_effective_resolution = effective_resolution
|
49 |
+
min_wasted_resolution = wasted_resolution
|
50 |
+
best_fit = (width, height)
|
51 |
+
|
52 |
+
return best_fit
|
53 |
+
|
54 |
+
|
55 |
+
class DictOutput(object):
|
56 |
+
def keys(self):
|
57 |
+
return self.__dict__.keys()
|
58 |
+
|
59 |
+
def __getitem__(self, item):
|
60 |
+
return self.__dict__[item]
|
61 |
+
|
62 |
+
def __setitem__(self, key, value):
|
63 |
+
self.__dict__[key] = value
|
64 |
+
|
65 |
+
|
66 |
+
# 对于inference sample也可以维护input_ids,反正最后不会用到
|
67 |
+
@dataclass
|
68 |
+
class VLChatProcessorOutput(DictOutput):
|
69 |
+
sft_format: str
|
70 |
+
input_ids: torch.LongTensor
|
71 |
+
target_ids: torch.LongTensor
|
72 |
+
images: torch.Tensor
|
73 |
+
images_seq_mask: torch.BoolTensor
|
74 |
+
images_spatial_crop: torch.LongTensor
|
75 |
+
num_image_tokens: List[int]
|
76 |
+
|
77 |
+
def __len__(self):
|
78 |
+
return len(self.input_ids)
|
79 |
+
|
80 |
+
|
81 |
+
@dataclass
|
82 |
+
class BatchCollateOutput(DictOutput):
|
83 |
+
sft_format: List[str]
|
84 |
+
input_ids: torch.LongTensor
|
85 |
+
labels: torch.LongTensor
|
86 |
+
images: torch.Tensor
|
87 |
+
attention_mask: torch.Tensor
|
88 |
+
images_seq_mask: torch.BoolTensor
|
89 |
+
images_spatial_crop: torch.LongTensor
|
90 |
+
seq_lens: List[int]
|
91 |
+
|
92 |
+
def to(self, device, dtype=torch.bfloat16):
|
93 |
+
self.input_ids = self.input_ids.to(device)
|
94 |
+
self.labels = self.labels.to(device)
|
95 |
+
self.attention_mask = self.attention_mask.to(device)
|
96 |
+
self.images_seq_mask = self.images_seq_mask.to(device)
|
97 |
+
self.images_spatial_crop = self.images_spatial_crop.to(device)
|
98 |
+
self.images = self.images.to(device=device, dtype=dtype)
|
99 |
+
return self
|
100 |
+
|
101 |
+
|
102 |
+
class ImageTransform(object):
|
103 |
+
def __init__(
|
104 |
+
self,
|
105 |
+
mean: Optional[Tuple[float, float, float]] = (0.5, 0.5, 0.5),
|
106 |
+
std: Optional[Tuple[float, float, float]] = (0.5, 0.5, 0.5),
|
107 |
+
normalize: bool = True
|
108 |
+
):
|
109 |
+
self.mean = mean
|
110 |
+
self.std = std
|
111 |
+
self.normalize = normalize
|
112 |
+
|
113 |
+
transform_pipelines = [
|
114 |
+
T.ToTensor()
|
115 |
+
]
|
116 |
+
|
117 |
+
if normalize:
|
118 |
+
transform_pipelines.append(T.Normalize(mean, std))
|
119 |
+
|
120 |
+
self.transform = T.Compose(transform_pipelines)
|
121 |
+
|
122 |
+
def __call__(self, pil_img: Image.Image):
|
123 |
+
x = self.transform(pil_img)
|
124 |
+
return x
|
125 |
+
|
126 |
+
|
127 |
+
|
128 |
+
class DeepseekVLV2Processor(ProcessorMixin):
|
129 |
+
tokenizer_class = ("LlamaTokenizer", "LlamaTokenizerFast")
|
130 |
+
attributes = ["tokenizer"]
|
131 |
+
|
132 |
+
def __init__(
|
133 |
+
self,
|
134 |
+
tokenizer: LlamaTokenizerFast,
|
135 |
+
candidate_resolutions: Tuple[Tuple[int, int]],
|
136 |
+
patch_size: int,
|
137 |
+
downsample_ratio: int,
|
138 |
+
image_mean: Tuple[float, float, float] = (0.5, 0.5, 0.5),
|
139 |
+
image_std: Tuple[float, float, float] = (0.5, 0.5, 0.5),
|
140 |
+
normalize: bool = True,
|
141 |
+
image_token: str = "<image>",
|
142 |
+
pad_token: str = "<|▁pad▁|>",
|
143 |
+
add_special_token: bool = False,
|
144 |
+
sft_format: str = "deepseek",
|
145 |
+
mask_prompt: bool = True,
|
146 |
+
ignore_id: int = -100,
|
147 |
+
**kwargs,
|
148 |
+
):
|
149 |
+
|
150 |
+
self.candidate_resolutions = candidate_resolutions
|
151 |
+
self.image_size = candidate_resolutions[0][0]
|
152 |
+
self.patch_size = patch_size
|
153 |
+
self.image_mean = image_mean
|
154 |
+
self.image_std = image_std
|
155 |
+
self.normalize = normalize
|
156 |
+
self.downsample_ratio = downsample_ratio
|
157 |
+
|
158 |
+
self.image_transform = ImageTransform(mean=image_mean, std=image_std, normalize=normalize)
|
159 |
+
self.tokenizer = tokenizer
|
160 |
+
self.tokenizer.padding_side = 'left' # must set this,padding side with make a difference in batch inference
|
161 |
+
|
162 |
+
# add the pad_token as special token to use 'tokenizer.pad_token' and 'tokenizer.pad_token_id'
|
163 |
+
if tokenizer.pad_token is None:
|
164 |
+
self.tokenizer.add_special_tokens({'pad_token': pad_token})
|
165 |
+
print(f"Add pad token = ['{pad_token}'] to the tokenizer\n"
|
166 |
+
f"{pad_token}:{tokenizer.encode(pad_token, add_special_tokens=False)[0]}")
|
167 |
+
|
168 |
+
# add image token
|
169 |
+
image_token_id = self.tokenizer.vocab.get(image_token)
|
170 |
+
if image_token_id is None:
|
171 |
+
special_tokens = [image_token]
|
172 |
+
special_tokens_dict = {"additional_special_tokens": special_tokens}
|
173 |
+
self.tokenizer.add_special_tokens(special_tokens_dict)
|
174 |
+
self.image_token_id = self.tokenizer.vocab.get(image_token)
|
175 |
+
print(f"Add image token = ['{image_token}'] to the tokenizer\n"
|
176 |
+
f"{image_token}:{tokenizer.encode(image_token, add_special_tokens=False)[0]}")
|
177 |
+
|
178 |
+
# add five special tokens for grounding-related tasks
|
179 |
+
# <|ref|>, <|/ref|>, <|det|>, <|/det|>, <|grounding|>
|
180 |
+
special_tokens = ['<|ref|>', '<|/ref|>', '<|det|>', '<|/det|>', '<|grounding|>']
|
181 |
+
special_tokens_dict = {"additional_special_tokens": special_tokens}
|
182 |
+
self.tokenizer.add_special_tokens(special_tokens_dict)
|
183 |
+
print(f"Add grounding-related tokens = {special_tokens} to the tokenizer with input_ids\n"
|
184 |
+
f"<|ref|>:{tokenizer.encode('<|ref|>', add_special_tokens=False)[0]}\n"
|
185 |
+
f"<|/ref|>:{tokenizer.encode('<|/ref|>', add_special_tokens=False)[0]}\n"
|
186 |
+
f"<|det|>:{tokenizer.encode('<|det|>', add_special_tokens=False)[0]}\n"
|
187 |
+
f"<|/det|>:{tokenizer.encode('<|/det|>', add_special_tokens=False)[0]}\n"
|
188 |
+
f"<|grounding|>:{tokenizer.encode('<|grounding|>', add_special_tokens=False)[0]}")
|
189 |
+
|
190 |
+
# add special tokens for SFT data
|
191 |
+
special_tokens = ["<|User|>", "<|Assistant|>"]
|
192 |
+
special_tokens_dict = {"additional_special_tokens": special_tokens}
|
193 |
+
self.tokenizer.add_special_tokens(special_tokens_dict)
|
194 |
+
print(f"Add chat tokens = {special_tokens} to the tokenizer with input_ids\n"
|
195 |
+
f"<|User|>:{tokenizer.encode('<|User|>', add_special_tokens=False)[0]}\n"
|
196 |
+
f"<|Assistant|>:{tokenizer.encode('<|Assistant|>', add_special_tokens=False)[0]}\n")
|
197 |
+
|
198 |
+
self.image_token = image_token
|
199 |
+
self.pad_token = pad_token
|
200 |
+
self.add_special_token = add_special_token
|
201 |
+
self.sft_format = sft_format
|
202 |
+
self.mask_prompt = mask_prompt
|
203 |
+
self.ignore_id = ignore_id
|
204 |
+
|
205 |
+
super().__init__(
|
206 |
+
tokenizer,
|
207 |
+
**kwargs,
|
208 |
+
)
|
209 |
+
|
210 |
+
def new_chat_template(self):
|
211 |
+
conv = get_conv_template(self.sft_format)
|
212 |
+
return conv
|
213 |
+
|
214 |
+
def format_messages(
|
215 |
+
self,
|
216 |
+
conversations: List[Dict[str, str]],
|
217 |
+
sft_format: str = "deepseek",
|
218 |
+
system_prompt: str = "",
|
219 |
+
):
|
220 |
+
"""
|
221 |
+
Applies the SFT template to conversation.
|
222 |
+
|
223 |
+
Args:
|
224 |
+
conversations (List[Dict]): A List of messages.
|
225 |
+
sft_format (str, optional): The format of the SFT template to use. Defaults to "deepseek".
|
226 |
+
system_prompt (str, optional): The system prompt to use in the SFT template. Defaults to "".
|
227 |
+
|
228 |
+
Returns:
|
229 |
+
sft_prompt (str): The formatted text.
|
230 |
+
"""
|
231 |
+
|
232 |
+
conv = get_conv_template(sft_format)
|
233 |
+
conv.set_system_message(system_prompt)
|
234 |
+
for message in conversations:
|
235 |
+
conv.append_message(message["role"], message["content"].strip())
|
236 |
+
sft_prompt = conv.get_prompt().strip()
|
237 |
+
|
238 |
+
return sft_prompt
|
239 |
+
|
240 |
+
def format_messages_v2(self, messages, pil_images, systems=None):
|
241 |
+
"""play the role of format_messages_v2 and get_images_info in the last version"""
|
242 |
+
tokenized_data = []
|
243 |
+
masked_tokenized_data = [] # labels
|
244 |
+
images_list = []
|
245 |
+
images_seq_mask = []
|
246 |
+
images_spatial_crop = []
|
247 |
+
num_image_tokens = []
|
248 |
+
|
249 |
+
image_index = 0
|
250 |
+
|
251 |
+
conv = get_conv_template(self.sft_format)
|
252 |
+
conv_system_message = conv.system_message
|
253 |
+
|
254 |
+
for idx, message in enumerate(messages):
|
255 |
+
if idx == 0:
|
256 |
+
tokenized_data += [self.bos_id]
|
257 |
+
masked_tokenized_data += [self.bos_id]
|
258 |
+
images_seq_mask += [False]
|
259 |
+
conv.system_message = conv_system_message
|
260 |
+
else:
|
261 |
+
conv.system_message = ''
|
262 |
+
|
263 |
+
if message['role'] == conv.roles[0] or message['role'] == "user":
|
264 |
+
conv.reset_message()
|
265 |
+
conv.append_message(conv.roles[0], str(message['content']).strip())
|
266 |
+
conv.append_message(conv.roles[1], '')
|
267 |
+
formatted_question = conv.get_prompt()
|
268 |
+
tokenized_str, images, seq_mask, spatial_crop, n_image_tokens = self.tokenize_with_images(
|
269 |
+
formatted_question,
|
270 |
+
pil_images[image_index: image_index + formatted_question.count(self.image_token)],
|
271 |
+
bos=False,
|
272 |
+
eos=False,
|
273 |
+
cropping=len(pil_images) <= 2
|
274 |
+
)
|
275 |
+
image_index += formatted_question.count(self.image_token)
|
276 |
+
|
277 |
+
tokenized_data += tokenized_str
|
278 |
+
if self.mask_prompt:
|
279 |
+
masked_tokenized_data += [self.ignore_id] * len(tokenized_str)
|
280 |
+
else:
|
281 |
+
masked_tokenized_data += tokenized_str
|
282 |
+
images_list += images
|
283 |
+
images_seq_mask += seq_mask
|
284 |
+
images_spatial_crop += spatial_crop
|
285 |
+
num_image_tokens += n_image_tokens
|
286 |
+
|
287 |
+
elif message['role'] == conv.roles[1] or message['role'] == "assistant":
|
288 |
+
formatted_answer = message['content'].strip()
|
289 |
+
assert formatted_answer.count(
|
290 |
+
self.image_token) == 0, f"there should be no {self.image_token} in the assistant's reply, but got {messages}"
|
291 |
+
tokenized_str, images, seq_mask, spatial_crop, n_image_tokens = self.tokenize_with_images(
|
292 |
+
formatted_answer,
|
293 |
+
[],
|
294 |
+
bos=False,
|
295 |
+
eos=True,
|
296 |
+
cropping=len(pil_images) <= 2)
|
297 |
+
|
298 |
+
tokenized_data += tokenized_str
|
299 |
+
masked_tokenized_data += tokenized_str
|
300 |
+
images_seq_mask += seq_mask
|
301 |
+
|
302 |
+
elif message['role'] == 'system' or message['role'] == 'deepseekapi-sys':
|
303 |
+
# 如果message里面有system,那就只允许出现在message的第一句,同时conv原本的system就会失效
|
304 |
+
assert idx == 0, 'system information should only exist in the begining of the conversation'
|
305 |
+
formatted_system = message['content'].strip()
|
306 |
+
tokenized_str = self.encode(formatted_system, bos=False, eos=False)
|
307 |
+
tokenized_data += tokenized_str
|
308 |
+
if self.mask_prompt:
|
309 |
+
masked_tokenized_data += [self.ignore_id] * len(tokenized_str)
|
310 |
+
else:
|
311 |
+
masked_tokenized_data += tokenized_str
|
312 |
+
seq_mask = [False] * len(tokenized_str)
|
313 |
+
images_seq_mask += seq_mask
|
314 |
+
|
315 |
+
else:
|
316 |
+
assert False, f"Unknown role: {message['role']}"
|
317 |
+
|
318 |
+
assert len(tokenized_data) == len(
|
319 |
+
images_seq_mask), f"format_messages_v2: tokenized_str's length {len(tokenized_str)} is not equal to imags_seq_mask's length {len(images_seq_mask)}"
|
320 |
+
assert len(images_spatial_crop) == len(num_image_tokens), f"image number should be compatible"
|
321 |
+
|
322 |
+
return tokenized_data, masked_tokenized_data, images_list, images_seq_mask, images_spatial_crop, num_image_tokens
|
323 |
+
|
324 |
+
def format_prompts(
|
325 |
+
self,
|
326 |
+
prompts: str,
|
327 |
+
sft_format: str = "deepseek",
|
328 |
+
system_prompt: str = "",
|
329 |
+
):
|
330 |
+
"""
|
331 |
+
Applies the SFT template to prompts.
|
332 |
+
|
333 |
+
Args:
|
334 |
+
prompts (str): the non-sft formatted prompt;
|
335 |
+
sft_format (str, optional): The format of the SFT template to use. Defaults to "deepseek".
|
336 |
+
system_prompt (str, optional): The system prompt to use in the SFT template. Defaults to "".
|
337 |
+
|
338 |
+
Returns:
|
339 |
+
sft_prompt (str): The formatted text.
|
340 |
+
"""
|
341 |
+
|
342 |
+
conv = get_conv_template(sft_format)
|
343 |
+
conv.set_system_message(system_prompt)
|
344 |
+
conv.append_message(conv.roles[0], prompts.strip())
|
345 |
+
conv.append_message(conv.roles[1], "")
|
346 |
+
|
347 |
+
sft_prompt = conv.get_prompt().strip()
|
348 |
+
|
349 |
+
return sft_prompt
|
350 |
+
|
351 |
+
@property
|
352 |
+
def bos_id(self):
|
353 |
+
return self.tokenizer.bos_token_id
|
354 |
+
|
355 |
+
@property
|
356 |
+
def eos_id(self):
|
357 |
+
return self.tokenizer.eos_token_id
|
358 |
+
|
359 |
+
@property
|
360 |
+
def pad_id(self):
|
361 |
+
return self.tokenizer.pad_token_id
|
362 |
+
|
363 |
+
def encode(self, text: str, bos: bool = True, eos: bool = False):
|
364 |
+
t = self.tokenizer.encode(text, add_special_tokens=False)
|
365 |
+
|
366 |
+
if bos:
|
367 |
+
t = [self.bos_id] + t
|
368 |
+
if eos:
|
369 |
+
t = t + [self.eos_id]
|
370 |
+
|
371 |
+
return t
|
372 |
+
|
373 |
+
def decode(self, t: List[int], **kwargs) -> str:
|
374 |
+
return self.tokenizer.decode(t, **kwargs)
|
375 |
+
|
376 |
+
def process_one(
|
377 |
+
self,
|
378 |
+
prompt: str = None,
|
379 |
+
conversations: List[Dict[str, str]] = None,
|
380 |
+
images: List[Image.Image] = None,
|
381 |
+
apply_sft_format: bool = False,
|
382 |
+
inference_mode: bool = True,
|
383 |
+
system_prompt: str = "",
|
384 |
+
**kwargs,
|
385 |
+
):
|
386 |
+
"""
|
387 |
+
|
388 |
+
Args:
|
389 |
+
prompt (str): the formatted prompt;
|
390 |
+
conversations (List[Dict]): conversations with a list of messages;
|
391 |
+
images (List[ImageType]): the list of images;
|
392 |
+
apply_sft_format (bool): if prompt is not None, then apply the SFT format to prompt;
|
393 |
+
if conversations is not None, then it will always apply the SFT format to conversations;
|
394 |
+
inference_mode (bool): if True, then remove the last eos token;
|
395 |
+
system_prompt (str): the system prompt;
|
396 |
+
**kwargs:
|
397 |
+
|
398 |
+
Returns:
|
399 |
+
outputs (BaseProcessorOutput): the output of the processor,
|
400 |
+
- input_ids (torch.LongTensor): [N + image tokens]
|
401 |
+
- target_ids (torch.LongTensor): [N + image tokens]
|
402 |
+
- images (torch.FloatTensor): [n_images, 3, H, W]
|
403 |
+
- image_id (int): the id of the image token
|
404 |
+
- num_image_tokens (List[int]): the number of image tokens
|
405 |
+
"""
|
406 |
+
|
407 |
+
assert (
|
408 |
+
prompt is None or conversations is None
|
409 |
+
), "prompt and conversations cannot be used at the same time."
|
410 |
+
|
411 |
+
if prompt is None:
|
412 |
+
# apply sft format
|
413 |
+
sft_format = self.format_messages(
|
414 |
+
conversations=conversations,
|
415 |
+
sft_format=self.sft_format,
|
416 |
+
system_prompt=system_prompt,
|
417 |
+
)
|
418 |
+
tokenized_str, masked_tokenized_str, images_list, images_seq_mask, images_spatial_crop, num_image_tokens = self.format_messages_v2(
|
419 |
+
conversations, images)
|
420 |
+
else:
|
421 |
+
if apply_sft_format:
|
422 |
+
sft_format = self.format_prompts(
|
423 |
+
prompts=prompt,
|
424 |
+
sft_format=self.sft_format,
|
425 |
+
system_prompt=system_prompt
|
426 |
+
)
|
427 |
+
else:
|
428 |
+
sft_format = prompt
|
429 |
+
tokenized_str, images_list, images_seq_mask, images_spatial_crop, num_image_tokens = self.tokenize_with_images(
|
430 |
+
sft_format, images, bos=True, eos=True, cropping=len(images) <= 2)
|
431 |
+
masked_tokenized_str = []
|
432 |
+
for token_index in tokenized_str:
|
433 |
+
if token_index != self.image_token_id:
|
434 |
+
masked_tokenized_str.append(token_index)
|
435 |
+
else:
|
436 |
+
masked_tokenized_str.append(self.ignore_id)
|
437 |
+
|
438 |
+
assert len(tokenized_str) == len(images_seq_mask) == len(masked_tokenized_str), \
|
439 |
+
(f"tokenized_str's length {len(tokenized_str)}, input_ids' length {len(masked_tokenized_str)}, "
|
440 |
+
f"imags_seq_mask's length {len(images_seq_mask)}, are not equal")
|
441 |
+
|
442 |
+
input_ids = torch.LongTensor(tokenized_str)
|
443 |
+
target_ids = torch.LongTensor(masked_tokenized_str)
|
444 |
+
images_seq_mask = torch.tensor(images_seq_mask, dtype=torch.bool)
|
445 |
+
|
446 |
+
# set input_ids < 0 | input_ids == self.image_token_id as ignore_id
|
447 |
+
target_ids[(input_ids < 0) | (input_ids == self.image_token_id)] = self.ignore_id
|
448 |
+
input_ids[input_ids < 0] = self.pad_id
|
449 |
+
|
450 |
+
if inference_mode:
|
451 |
+
# 去掉结尾的eos token
|
452 |
+
assert input_ids[-1] == self.eos_id
|
453 |
+
input_ids = input_ids[:-1]
|
454 |
+
target_ids = target_ids[:-1]
|
455 |
+
images_seq_mask = images_seq_mask[:-1]
|
456 |
+
|
457 |
+
if len(images_list) == 0:
|
458 |
+
images = torch.zeros((1, 3, self.image_size, self.image_size))
|
459 |
+
images_spatial_crop = torch.zeros((1, 2), dtype=torch.long)
|
460 |
+
else:
|
461 |
+
images = torch.stack(images_list, dim=0)
|
462 |
+
images_spatial_crop = torch.tensor(images_spatial_crop, dtype=torch.long)
|
463 |
+
|
464 |
+
prepare = VLChatProcessorOutput(
|
465 |
+
sft_format=sft_format,
|
466 |
+
input_ids=input_ids,
|
467 |
+
target_ids=target_ids,
|
468 |
+
images=images,
|
469 |
+
images_seq_mask=images_seq_mask,
|
470 |
+
images_spatial_crop=images_spatial_crop,
|
471 |
+
num_image_tokens=num_image_tokens
|
472 |
+
)
|
473 |
+
|
474 |
+
return prepare
|
475 |
+
|
476 |
+
def __call__(
|
477 |
+
self,
|
478 |
+
*,
|
479 |
+
prompt: str = None,
|
480 |
+
conversations: List[Dict[str, str]] = None,
|
481 |
+
images: List[Image.Image] = None,
|
482 |
+
apply_sft_format: bool = False,
|
483 |
+
force_batchify: bool = True,
|
484 |
+
inference_mode: bool = True,
|
485 |
+
system_prompt: str = "",
|
486 |
+
**kwargs,
|
487 |
+
):
|
488 |
+
"""
|
489 |
+
|
490 |
+
Args:
|
491 |
+
prompt (str): the formatted prompt;
|
492 |
+
conversations (List[Dict]): conversations with a list of messages;
|
493 |
+
images (List[ImageType]): the list of images;
|
494 |
+
apply_sft_format (bool): if prompt is not None, then apply the SFT format to prompt;
|
495 |
+
if conversations is not None, then it will always apply the SFT format to conversations;
|
496 |
+
force_batchify (bool): force batchify the inputs;
|
497 |
+
inference_mode (bool): if True, then remove the last eos token;
|
498 |
+
system_prompt (str): the system prompt;
|
499 |
+
**kwargs:
|
500 |
+
|
501 |
+
Returns:
|
502 |
+
outputs (BaseProcessorOutput): the output of the processor,
|
503 |
+
- input_ids (torch.LongTensor): [N + image tokens]
|
504 |
+
- images (torch.FloatTensor): [n_images, 3, H, W]
|
505 |
+
- image_id (int): the id of the image token
|
506 |
+
- num_image_tokens (List[int]): the number of image tokens
|
507 |
+
"""
|
508 |
+
|
509 |
+
prepare = self.process_one(
|
510 |
+
prompt=prompt,
|
511 |
+
conversations=conversations,
|
512 |
+
images=images,
|
513 |
+
apply_sft_format=apply_sft_format,
|
514 |
+
inference_mode=inference_mode,
|
515 |
+
system_prompt=system_prompt
|
516 |
+
)
|
517 |
+
|
518 |
+
if force_batchify:
|
519 |
+
prepare = self.batchify([prepare])
|
520 |
+
|
521 |
+
return prepare
|
522 |
+
|
523 |
+
def tokenize_with_images(
|
524 |
+
self,
|
525 |
+
conversation: str,
|
526 |
+
images: List[Image.Image],
|
527 |
+
bos: bool = True,
|
528 |
+
eos: bool = True,
|
529 |
+
cropping: bool = True,
|
530 |
+
):
|
531 |
+
"""Tokenize text with <image> tags."""
|
532 |
+
assert conversation.count(self.image_token) == len(images)
|
533 |
+
text_splits = conversation.split(self.image_token)
|
534 |
+
images_list, images_seq_mask, images_spatial_crop = [], [], []
|
535 |
+
num_image_tokens = []
|
536 |
+
tokenized_str = []
|
537 |
+
for text_sep, image in zip(text_splits, images):
|
538 |
+
"""encode text_sep"""
|
539 |
+
tokenized_sep = self.encode(text_sep, bos=False, eos=False)
|
540 |
+
tokenized_str += tokenized_sep
|
541 |
+
images_seq_mask += [False] * len(tokenized_sep)
|
542 |
+
|
543 |
+
"""select best resolution for anyres"""
|
544 |
+
if cropping:
|
545 |
+
best_width, best_height = select_best_resolution(image.size, self.candidate_resolutions)
|
546 |
+
else:
|
547 |
+
best_width, best_height = self.image_size, self.image_size
|
548 |
+
# print(image.size, (best_width, best_height)) # check the select_best_resolutions func
|
549 |
+
|
550 |
+
"""process the global view"""
|
551 |
+
global_view = ImageOps.pad(image, (self.image_size, self.image_size),
|
552 |
+
color=tuple(int(x * 255) for x in self.image_transform.mean))
|
553 |
+
images_list.append(self.image_transform(global_view))
|
554 |
+
|
555 |
+
"""process the local views"""
|
556 |
+
local_view = ImageOps.pad(image, (best_width, best_height),
|
557 |
+
color=tuple(int(x * 255) for x in self.image_transform.mean))
|
558 |
+
for i in range(0, best_height, self.image_size):
|
559 |
+
for j in range(0, best_width, self.image_size):
|
560 |
+
images_list.append(
|
561 |
+
self.image_transform(local_view.crop((j, i, j + self.image_size, i + self.image_size))))
|
562 |
+
|
563 |
+
"""record height / width crop num"""
|
564 |
+
num_width_tiles, num_height_tiles = best_width // self.image_size, best_height // self.image_size
|
565 |
+
images_spatial_crop.append([num_width_tiles, num_height_tiles])
|
566 |
+
|
567 |
+
"""add image tokens"""
|
568 |
+
h = w = math.ceil((self.image_size // self.patch_size) / self.downsample_ratio)
|
569 |
+
# global views tokens h * (w + 1), 1 is for line seperator
|
570 |
+
tokenized_image = [self.image_token_id] * h * (w + 1)
|
571 |
+
# add a seperator between global and local views
|
572 |
+
tokenized_image += [self.image_token_id]
|
573 |
+
# local views tokens, (num_height_tiles * h) * (num_width_tiles * w + 1)
|
574 |
+
tokenized_image += [self.image_token_id] * (num_height_tiles * h) * (num_width_tiles * w + 1)
|
575 |
+
|
576 |
+
tokenized_str += tokenized_image
|
577 |
+
images_seq_mask += [True] * len(tokenized_image)
|
578 |
+
num_image_tokens.append(len(tokenized_image))
|
579 |
+
# print(width_crop_num, height_crop_num, len(tokenized_image)) # test the correctness of the number of image-related tokens
|
580 |
+
|
581 |
+
"""process the last text split"""
|
582 |
+
tokenized_sep = self.encode(text_splits[-1], bos=False, eos=False)
|
583 |
+
tokenized_str += tokenized_sep
|
584 |
+
images_seq_mask += [False] * len(tokenized_sep)
|
585 |
+
|
586 |
+
"""add the bos and eos tokens"""
|
587 |
+
if bos:
|
588 |
+
tokenized_str = [self.bos_id] + tokenized_str
|
589 |
+
images_seq_mask = [False] + images_seq_mask
|
590 |
+
if eos:
|
591 |
+
tokenized_str = tokenized_str + [self.eos_id]
|
592 |
+
images_seq_mask = images_seq_mask + [False]
|
593 |
+
|
594 |
+
assert len(tokenized_str) == len(
|
595 |
+
images_seq_mask), f"tokenize_with_images func: tokenized_str's length {len(tokenized_str)} is not equal to imags_seq_mask's length {len(images_seq_mask)}"
|
596 |
+
|
597 |
+
return tokenized_str, images_list, images_seq_mask, images_spatial_crop, num_image_tokens
|
598 |
+
|
599 |
+
def batchify(
|
600 |
+
self,
|
601 |
+
sample_list: List[VLChatProcessorOutput],
|
602 |
+
padding: Literal["left", "right"] = "left"
|
603 |
+
) -> BatchCollateOutput:
|
604 |
+
"""
|
605 |
+
Preprocesses the inputs for multimodal inference.
|
606 |
+
|
607 |
+
Args:
|
608 |
+
sample_list (List[VLChatProcessorOutput]): A list of VLChatProcessorOutput.
|
609 |
+
padding (str): The padding method. Defaults to "left".
|
610 |
+
|
611 |
+
Returns:
|
612 |
+
BatchCollateOutput: A dictionary of the inputs to use for multimodal inference.
|
613 |
+
"""
|
614 |
+
|
615 |
+
batched_sft_format = [sample.sft_format for sample in sample_list]
|
616 |
+
batched_input_ids = [sample.input_ids for sample in sample_list]
|
617 |
+
batched_labels = [sample.target_ids for sample in sample_list]
|
618 |
+
batched_images_seq_mask = [sample["images_seq_mask"] for sample in sample_list]
|
619 |
+
seq_lens = [len(sample) for sample in sample_list]
|
620 |
+
|
621 |
+
"""padding input_ids and images_seq_mask"""
|
622 |
+
if padding == "left":
|
623 |
+
# the tokenizer is default to pad at left
|
624 |
+
## TODO, You're using a LlamaTokenizerFast tokenizer.
|
625 |
+
# Please note that with a fast tokenizer, using the `__call__` method is faster than
|
626 |
+
# using a method to encode the text followed by a call to the `pad` method to get a padded encoding.
|
627 |
+
padded_input_ids = self.tokenizer.pad({"input_ids": batched_input_ids})
|
628 |
+
batched_input_ids, batched_attention_mask = padded_input_ids["input_ids"], padded_input_ids[
|
629 |
+
"attention_mask"].bool()
|
630 |
+
batched_labels = self.tokenizer.pad({"input_ids": batched_labels})["input_ids"]
|
631 |
+
batched_labels[batched_labels == self.pad_id] = self.ignore_id # labels正常不会出现pad_id,无需额外保护
|
632 |
+
batched_images_seq_mask = self.tokenizer.pad({"input_ids": batched_images_seq_mask})["input_ids"]
|
633 |
+
batched_images_seq_mask[batched_images_seq_mask == self.pad_id] = False
|
634 |
+
else:
|
635 |
+
batched_input_ids = pad_sequence(batched_input_ids, batch_first=True, padding_value=self.pad_id)
|
636 |
+
batched_labels = pad_sequence(batched_labels, batch_first=True, padding_value=self.ignore_id)
|
637 |
+
batched_images_seq_mask = pad_sequence(batched_images_seq_mask, batch_first=True, padding_value=0)
|
638 |
+
batched_attention_mask = batched_input_ids != self.pad_id
|
639 |
+
|
640 |
+
"""padding images to max_patch_num"""
|
641 |
+
max_n_patches = max(sample["images"].shape[0] for sample in sample_list)
|
642 |
+
batched_images = []
|
643 |
+
for sample in sample_list:
|
644 |
+
images = sample["images"]
|
645 |
+
n_pads = max_n_patches - images.shape[0]
|
646 |
+
if n_pads > 0:
|
647 |
+
pad_images = torch.zeros((n_pads, *images.shape[1:]), dtype=images.dtype)
|
648 |
+
images = torch.cat([images, pad_images], dim=0)
|
649 |
+
batched_images.append(images)
|
650 |
+
batched_images = torch.stack(batched_images, dim=0)
|
651 |
+
|
652 |
+
"""padding images_spatial_crop to max_n_images"""
|
653 |
+
max_n_images = max(sample["images_spatial_crop"].shape[0] for sample in sample_list)
|
654 |
+
batched_images_spatial_crop = []
|
655 |
+
for sample in sample_list:
|
656 |
+
images_spatial_crop = sample["images_spatial_crop"]
|
657 |
+
n_pads = max_n_images - sample["images_spatial_crop"].shape[0]
|
658 |
+
if n_pads > 0:
|
659 |
+
pad_images_spatial_crop = torch.full((n_pads, 2), 0, dtype=images_spatial_crop.dtype)
|
660 |
+
images_spatial_crop = torch.cat([images_spatial_crop, pad_images_spatial_crop], dim=0)
|
661 |
+
batched_images_spatial_crop.append(images_spatial_crop)
|
662 |
+
batched_images_spatial_crop = torch.stack(batched_images_spatial_crop, dim=0)
|
663 |
+
|
664 |
+
batched_samples = BatchCollateOutput(
|
665 |
+
input_ids=batched_input_ids,
|
666 |
+
attention_mask=batched_attention_mask,
|
667 |
+
labels=batched_labels,
|
668 |
+
images=batched_images,
|
669 |
+
images_seq_mask=batched_images_seq_mask,
|
670 |
+
images_spatial_crop=batched_images_spatial_crop,
|
671 |
+
sft_format=batched_sft_format,
|
672 |
+
seq_lens=seq_lens
|
673 |
+
)
|
674 |
+
|
675 |
+
return batched_samples
|
deepseek_vl2/models/siglip_vit.py
ADDED
@@ -0,0 +1,660 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py
|
2 |
+
from dataclasses import dataclass
|
3 |
+
import numpy as np
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
import torch.nn.functional as F
|
7 |
+
from typing import Final, Optional, Callable, Union, Tuple, List, Set, Dict, Type, Literal, Sequence
|
8 |
+
import math
|
9 |
+
import warnings
|
10 |
+
from timm.layers import (
|
11 |
+
PatchEmbed, Mlp, DropPath,
|
12 |
+
AttentionPoolLatent, PatchDropout, resample_abs_pos_embed, LayerType
|
13 |
+
)
|
14 |
+
from timm.models._manipulate import named_apply, checkpoint_seq, adapt_input_conv
|
15 |
+
from transformers.modeling_utils import is_flash_attn_2_available
|
16 |
+
from xformers.ops import memory_efficient_attention
|
17 |
+
from functools import partial
|
18 |
+
|
19 |
+
|
20 |
+
if is_flash_attn_2_available():
|
21 |
+
from flash_attn import flash_attn_qkvpacked_func
|
22 |
+
|
23 |
+
|
24 |
+
def _no_grad_trunc_normal_(tensor, mean, std, a, b):
|
25 |
+
# Cut & paste from PyTorch official master until it's in a few official releases - RW
|
26 |
+
# Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
|
27 |
+
def norm_cdf(x):
|
28 |
+
# Computes standard normal cumulative distribution function
|
29 |
+
return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
|
30 |
+
|
31 |
+
if (mean < a - 2 * std) or (mean > b + 2 * std):
|
32 |
+
warnings.warn(
|
33 |
+
"mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
|
34 |
+
"The distribution of values may be incorrect.",
|
35 |
+
stacklevel=2,
|
36 |
+
)
|
37 |
+
|
38 |
+
with torch.no_grad():
|
39 |
+
# Values are generated by using a truncated uniform distribution and
|
40 |
+
# then using the inverse CDF for the normal distribution.
|
41 |
+
# Get upper and lower cdf values
|
42 |
+
l = norm_cdf((a - mean) / std) # noqa: E741
|
43 |
+
u = norm_cdf((b - mean) / std)
|
44 |
+
|
45 |
+
# Uniformly fill tensor with values from [l, u], then translate to
|
46 |
+
# [2l-1, 2u-1].
|
47 |
+
tensor.uniform_(2 * l - 1, 2 * u - 1)
|
48 |
+
|
49 |
+
# Use inverse cdf transform for normal distribution to get truncated
|
50 |
+
# standard normal
|
51 |
+
tensor.erfinv_()
|
52 |
+
|
53 |
+
# Transform to proper mean, std
|
54 |
+
tensor.mul_(std * math.sqrt(2.0))
|
55 |
+
tensor.add_(mean)
|
56 |
+
|
57 |
+
# Clamp to ensure it's in the proper range
|
58 |
+
tensor.clamp_(min=a, max=b)
|
59 |
+
return tensor
|
60 |
+
|
61 |
+
|
62 |
+
def trunc_normal_(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0):
|
63 |
+
# type: (torch.Tensor, float, float, float, float) -> torch.Tensor
|
64 |
+
r"""The original timm.models.layers.weight_init.trunc_normal_ can not handle bfloat16 yet, here we first
|
65 |
+
convert the tensor to float32, apply the trunc_normal_() in float32, and then convert it back to its orignal dtype.
|
66 |
+
Fills the input Tensor with values drawn from a truncated normal distribution. The values are effectively drawn
|
67 |
+
from the normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
|
68 |
+
with values outside :math:`[a, b]` redrawn until they are within
|
69 |
+
the bounds. The method used for generating the random values works
|
70 |
+
best when :math:`a \leq \text{mean} \leq b`.
|
71 |
+
Args:
|
72 |
+
tensor: an n-dimensional `torch.Tensor`
|
73 |
+
mean: the mean of the normal distribution
|
74 |
+
std: the standard deviation of the normal distribution
|
75 |
+
a: the minimum cutoff value
|
76 |
+
b: the maximum cutoff value
|
77 |
+
Examples:
|
78 |
+
>>> w = torch.empty(3, 5)
|
79 |
+
>>> nn.init.trunc_normal_(w)
|
80 |
+
"""
|
81 |
+
|
82 |
+
with torch.no_grad():
|
83 |
+
dtype = tensor.dtype
|
84 |
+
tensor_fp32 = tensor.float()
|
85 |
+
tensor_fp32 = _no_grad_trunc_normal_(tensor_fp32, mean, std, a, b)
|
86 |
+
tensor_dtype = tensor_fp32.to(dtype=dtype)
|
87 |
+
tensor.copy_(tensor_dtype)
|
88 |
+
|
89 |
+
|
90 |
+
def init_weights(self):
|
91 |
+
if self.pos_embed is not None:
|
92 |
+
trunc_normal_(self.pos_embed, std=self.pos_embed.shape[1] ** -0.5)
|
93 |
+
trunc_normal_(self.latent, std=self.latent_dim ** -0.5)
|
94 |
+
|
95 |
+
|
96 |
+
def init_weights_vit_timm(module: nn.Module, name: str = '') -> None:
|
97 |
+
""" ViT weight initialization, original timm impl (for reproducibility) """
|
98 |
+
if isinstance(module, nn.Linear):
|
99 |
+
trunc_normal_(module.weight, std=.02)
|
100 |
+
if module.bias is not None:
|
101 |
+
nn.init.zeros_(module.bias)
|
102 |
+
elif hasattr(module, 'init_weights'):
|
103 |
+
module.init_weights()
|
104 |
+
|
105 |
+
|
106 |
+
class Attention(nn.Module):
|
107 |
+
fused_attn: Final[bool]
|
108 |
+
|
109 |
+
def __init__(
|
110 |
+
self,
|
111 |
+
dim: int,
|
112 |
+
num_heads: int = 8,
|
113 |
+
qkv_bias: bool = False,
|
114 |
+
qk_norm: bool = False,
|
115 |
+
attn_drop: float = 0.,
|
116 |
+
proj_drop: float = 0.,
|
117 |
+
norm_layer: nn.Module = nn.LayerNorm,
|
118 |
+
deterministic: bool = False,
|
119 |
+
) -> None:
|
120 |
+
super().__init__()
|
121 |
+
assert dim % num_heads == 0, 'dim should be divisible by num_heads'
|
122 |
+
self.num_heads = num_heads
|
123 |
+
self.head_dim = dim // num_heads
|
124 |
+
self.scale = self.head_dim ** -0.5
|
125 |
+
self.qk_norm = qk_norm
|
126 |
+
self.fused_attn = True
|
127 |
+
self.deterministic = deterministic
|
128 |
+
|
129 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
130 |
+
self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
|
131 |
+
self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
|
132 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
133 |
+
self.proj = nn.Linear(dim, dim)
|
134 |
+
self.proj_drop = nn.Dropout(proj_drop) if proj_drop > 0. else nn.Identity()
|
135 |
+
|
136 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
137 |
+
B, N, C = x.shape
|
138 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim)
|
139 |
+
|
140 |
+
if not self.qk_norm:
|
141 |
+
if self.head_dim % 32 == 0 and is_flash_attn_2_available():
|
142 |
+
# flashattn must have head_dim as a multiple of 32
|
143 |
+
x = flash_attn_qkvpacked_func(qkv, dropout_p=self.attn_drop.p if self.training else 0.,
|
144 |
+
deterministic=self.deterministic)
|
145 |
+
else:
|
146 |
+
q, k, v = qkv.unbind(2)
|
147 |
+
x = memory_efficient_attention(q, k, v, p=self.attn_drop.p if self.training else 0.)
|
148 |
+
x = x.reshape(B, N, C)
|
149 |
+
x = self.proj(x)
|
150 |
+
x = self.proj_drop(x)
|
151 |
+
return x
|
152 |
+
|
153 |
+
qkv = qkv.permute(2, 0, 3, 1, 4)
|
154 |
+
q, k, v = qkv.unbind(0)
|
155 |
+
q, k = self.q_norm(q), self.k_norm(k)
|
156 |
+
|
157 |
+
if self.fused_attn:
|
158 |
+
with torch.backends.cuda.sdp_kernel(enable_math=False, enable_mem_efficient=False):
|
159 |
+
# 用上下文的方式强行使用fa
|
160 |
+
x = F.scaled_dot_product_attention(
|
161 |
+
q, k, v,
|
162 |
+
dropout_p=self.attn_drop.p if self.training else 0.,
|
163 |
+
)
|
164 |
+
else:
|
165 |
+
q = q * self.scale
|
166 |
+
attn = q @ k.transpose(-2, -1)
|
167 |
+
attn = attn.softmax(dim=-1)
|
168 |
+
attn = self.attn_drop(attn)
|
169 |
+
x = attn @ v
|
170 |
+
|
171 |
+
x = x.transpose(1, 2).reshape(B, N, C)
|
172 |
+
x = self.proj(x)
|
173 |
+
x = self.proj_drop(x)
|
174 |
+
return x
|
175 |
+
|
176 |
+
|
177 |
+
class LayerScale(nn.Module):
|
178 |
+
def __init__(
|
179 |
+
self,
|
180 |
+
dim: int,
|
181 |
+
init_values: float = 1e-5,
|
182 |
+
inplace: bool = False,
|
183 |
+
) -> None:
|
184 |
+
super().__init__()
|
185 |
+
self.inplace = inplace
|
186 |
+
self.gamma = nn.Parameter(init_values * torch.ones(dim))
|
187 |
+
|
188 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
189 |
+
return x.mul_(self.gamma) if self.inplace else x * self.gamma
|
190 |
+
|
191 |
+
|
192 |
+
class Block(nn.Module):
|
193 |
+
def __init__(
|
194 |
+
self,
|
195 |
+
dim: int,
|
196 |
+
num_heads: int,
|
197 |
+
mlp_ratio: float = 4.,
|
198 |
+
qkv_bias: bool = False,
|
199 |
+
qk_norm: bool = False,
|
200 |
+
proj_drop: float = 0.,
|
201 |
+
attn_drop: float = 0.,
|
202 |
+
init_values: Optional[float] = None,
|
203 |
+
drop_path: float = 0.,
|
204 |
+
act_layer: nn.Module = nn.GELU,
|
205 |
+
norm_layer: nn.Module = nn.LayerNorm,
|
206 |
+
mlp_layer: nn.Module = Mlp,
|
207 |
+
deterministic: bool = False,
|
208 |
+
) -> None:
|
209 |
+
super().__init__()
|
210 |
+
self.norm1 = norm_layer(dim)
|
211 |
+
self.attn = Attention(
|
212 |
+
dim,
|
213 |
+
num_heads=num_heads,
|
214 |
+
qkv_bias=qkv_bias,
|
215 |
+
qk_norm=qk_norm,
|
216 |
+
attn_drop=attn_drop,
|
217 |
+
proj_drop=proj_drop,
|
218 |
+
norm_layer=norm_layer,
|
219 |
+
deterministic=deterministic,
|
220 |
+
)
|
221 |
+
self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
|
222 |
+
self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
223 |
+
|
224 |
+
self.norm2 = norm_layer(dim)
|
225 |
+
self.mlp = mlp_layer(
|
226 |
+
in_features=dim,
|
227 |
+
hidden_features=int(dim * mlp_ratio),
|
228 |
+
act_layer=act_layer,
|
229 |
+
drop=proj_drop,
|
230 |
+
)
|
231 |
+
self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
|
232 |
+
self.drop_path2 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
233 |
+
|
234 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
235 |
+
x = x + self.drop_path1(self.ls1(self.attn(self.norm1(x))))
|
236 |
+
x = x + self.drop_path2(self.ls2(self.mlp(self.norm2(x))))
|
237 |
+
return x
|
238 |
+
|
239 |
+
|
240 |
+
class VisionTransformer(nn.Module):
|
241 |
+
""" Vision Transformer
|
242 |
+
|
243 |
+
A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale`
|
244 |
+
- https://arxiv.org/abs/2010.11929
|
245 |
+
"""
|
246 |
+
dynamic_img_size: Final[bool]
|
247 |
+
|
248 |
+
def __init__(
|
249 |
+
self,
|
250 |
+
img_size: Union[int, Tuple[int, int]] = 224,
|
251 |
+
patch_size: Union[int, Tuple[int, int]] = 16,
|
252 |
+
in_chans: int = 3,
|
253 |
+
num_classes: int = 1000,
|
254 |
+
global_pool: Literal['', 'avg', 'token', 'map'] = 'token',
|
255 |
+
embed_dim: int = 768,
|
256 |
+
depth: int = 12,
|
257 |
+
num_heads: int = 12,
|
258 |
+
mlp_ratio: float = 4.,
|
259 |
+
qkv_bias: bool = True,
|
260 |
+
qk_norm: bool = False,
|
261 |
+
init_values: Optional[float] = None,
|
262 |
+
class_token: bool = True,
|
263 |
+
no_embed_class: bool = False,
|
264 |
+
reg_tokens: int = 0,
|
265 |
+
pre_norm: bool = False,
|
266 |
+
fc_norm: Optional[bool] = None,
|
267 |
+
dynamic_img_size: bool = False,
|
268 |
+
dynamic_img_pad: bool = False,
|
269 |
+
drop_rate: float = 0.,
|
270 |
+
pos_drop_rate: float = 0.,
|
271 |
+
patch_drop_rate: float = 0.,
|
272 |
+
proj_drop_rate: float = 0.,
|
273 |
+
attn_drop_rate: float = 0.,
|
274 |
+
drop_path_rate: float = 0.,
|
275 |
+
weight_init: Literal['skip', 'jax', 'jax_nlhb', 'moco', ''] = '',
|
276 |
+
embed_layer: Callable = PatchEmbed,
|
277 |
+
norm_layer: Optional[LayerType] = None,
|
278 |
+
act_layer: Optional[LayerType] = None,
|
279 |
+
block_fn: Type[nn.Module] = Block,
|
280 |
+
mlp_layer: Type[nn.Module] = Mlp,
|
281 |
+
ignore_head: bool = False,
|
282 |
+
deterministic: bool = False,
|
283 |
+
num_recomputing_layers: int = 0
|
284 |
+
) -> None:
|
285 |
+
"""
|
286 |
+
Args:
|
287 |
+
img_size: Input image size.
|
288 |
+
patch_size: Patch size.
|
289 |
+
in_chans: Number of image input channels.
|
290 |
+
num_classes: Mumber of classes for classification head.
|
291 |
+
global_pool: Type of global pooling for final sequence (default: 'token').
|
292 |
+
embed_dim: Transformer embedding dimension.
|
293 |
+
depth: Depth of transformer.
|
294 |
+
num_heads: Number of attention heads.
|
295 |
+
mlp_ratio: Ratio of mlp hidden dim to embedding dim.
|
296 |
+
qkv_bias: Enable bias for qkv projections if True.
|
297 |
+
init_values: Layer-scale init values (layer-scale enabled if not None).
|
298 |
+
class_token: Use class token.
|
299 |
+
no_embed_class: Don't include position embeddings for class (or reg) tokens.
|
300 |
+
reg_tokens: Number of register tokens.
|
301 |
+
fc_norm: Pre head norm after pool (instead of before), if None, enabled when global_pool == 'avg'.
|
302 |
+
drop_rate: Head dropout rate.
|
303 |
+
pos_drop_rate: Position embedding dropout rate.
|
304 |
+
attn_drop_rate: Attention dropout rate.
|
305 |
+
drop_path_rate: Stochastic depth rate.
|
306 |
+
weight_init: Weight initialization scheme.
|
307 |
+
embed_layer: Patch embedding layer.
|
308 |
+
norm_layer: Normalization layer.
|
309 |
+
act_layer: MLP activation layer.
|
310 |
+
block_fn: Transformer block layer.
|
311 |
+
"""
|
312 |
+
super().__init__()
|
313 |
+
assert global_pool in ('', 'avg', 'token', 'map')
|
314 |
+
assert class_token or global_pool != 'token'
|
315 |
+
use_fc_norm = global_pool == 'avg' if fc_norm is None else fc_norm
|
316 |
+
# norm_layer = get_norm_layer(norm_layer) or partial(nn.LayerNorm, eps=1e-6)
|
317 |
+
# act_layer = get_act_layer(act_layer) or nn.GELU
|
318 |
+
norm_layer = partial(nn.LayerNorm, eps=1e-6)
|
319 |
+
# siglip use PytorchGELUTanh() rather than the vanilla nn.GELU()
|
320 |
+
# https://github.com/huggingface/transformers/blob/78b2929c0554b79e0489b451ce4ece14d265ead2/src/transformers/models/siglip/configuration_siglip.py#L191
|
321 |
+
act_layer = partial(nn.GELU, approximate='tanh')
|
322 |
+
|
323 |
+
self.num_classes = num_classes
|
324 |
+
self.global_pool = global_pool
|
325 |
+
self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
|
326 |
+
self.num_prefix_tokens = 1 if class_token else 0
|
327 |
+
self.num_prefix_tokens += reg_tokens
|
328 |
+
self.num_reg_tokens = reg_tokens
|
329 |
+
self.has_class_token = class_token
|
330 |
+
self.no_embed_class = no_embed_class # don't embed prefix positions (includes reg)
|
331 |
+
self.dynamic_img_size = dynamic_img_size
|
332 |
+
self.grad_checkpointing = False
|
333 |
+
self.ignore_head = ignore_head
|
334 |
+
self.num_recomputing_layers = num_recomputing_layers
|
335 |
+
|
336 |
+
embed_args = {}
|
337 |
+
if dynamic_img_size:
|
338 |
+
# flatten deferred until after pos embed
|
339 |
+
embed_args.update(dict(strict_img_size=False, output_fmt='NHWC'))
|
340 |
+
self.patch_embed = embed_layer(
|
341 |
+
img_size=img_size,
|
342 |
+
patch_size=patch_size,
|
343 |
+
in_chans=in_chans,
|
344 |
+
embed_dim=embed_dim,
|
345 |
+
bias=not pre_norm, # disable bias if pre-norm is used (e.g. CLIP)
|
346 |
+
dynamic_img_pad=dynamic_img_pad,
|
347 |
+
**embed_args,
|
348 |
+
)
|
349 |
+
num_patches = self.patch_embed.num_patches
|
350 |
+
|
351 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) if class_token else None
|
352 |
+
self.reg_token = nn.Parameter(torch.zeros(1, reg_tokens, embed_dim)) if reg_tokens else None
|
353 |
+
embed_len = num_patches if no_embed_class else num_patches + self.num_prefix_tokens
|
354 |
+
self.pos_embed = nn.Parameter(torch.randn(1, embed_len, embed_dim) * .02)
|
355 |
+
self.pos_drop = nn.Dropout(p=pos_drop_rate)
|
356 |
+
if patch_drop_rate > 0:
|
357 |
+
self.patch_drop = PatchDropout(
|
358 |
+
patch_drop_rate,
|
359 |
+
num_prefix_tokens=self.num_prefix_tokens,
|
360 |
+
)
|
361 |
+
else:
|
362 |
+
self.patch_drop = nn.Identity()
|
363 |
+
self.norm_pre = norm_layer(embed_dim) if pre_norm else nn.Identity()
|
364 |
+
|
365 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
|
366 |
+
self.blocks = nn.Sequential(*[
|
367 |
+
block_fn(
|
368 |
+
dim=embed_dim,
|
369 |
+
num_heads=num_heads,
|
370 |
+
mlp_ratio=mlp_ratio,
|
371 |
+
qkv_bias=qkv_bias,
|
372 |
+
qk_norm=qk_norm,
|
373 |
+
init_values=init_values,
|
374 |
+
proj_drop=proj_drop_rate,
|
375 |
+
attn_drop=attn_drop_rate,
|
376 |
+
drop_path=dpr[i],
|
377 |
+
norm_layer=norm_layer,
|
378 |
+
act_layer=act_layer,
|
379 |
+
mlp_layer=mlp_layer,
|
380 |
+
deterministic=deterministic,
|
381 |
+
)
|
382 |
+
for i in range(depth)])
|
383 |
+
self.norm = norm_layer(embed_dim) if not use_fc_norm else nn.Identity()
|
384 |
+
|
385 |
+
# Classifier Head
|
386 |
+
if global_pool == 'map':
|
387 |
+
AttentionPoolLatent.init_weights = init_weights
|
388 |
+
self.attn_pool = AttentionPoolLatent(
|
389 |
+
self.embed_dim,
|
390 |
+
num_heads=num_heads,
|
391 |
+
mlp_ratio=mlp_ratio,
|
392 |
+
norm_layer=norm_layer,
|
393 |
+
)
|
394 |
+
else:
|
395 |
+
self.attn_pool = None
|
396 |
+
self.fc_norm = norm_layer(embed_dim) if use_fc_norm else nn.Identity()
|
397 |
+
self.head_drop = nn.Dropout(drop_rate)
|
398 |
+
self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
|
399 |
+
|
400 |
+
if weight_init != 'skip':
|
401 |
+
self.init_weights(weight_init)
|
402 |
+
|
403 |
+
def init_weights(self, mode: Literal['jax', 'jax_nlhb', 'moco', ''] = '') -> None:
|
404 |
+
assert mode in ('jax', 'jax_nlhb', 'moco', '')
|
405 |
+
head_bias = -math.log(self.num_classes) if 'nlhb' in mode else 0.
|
406 |
+
trunc_normal_(self.pos_embed, std=.02)
|
407 |
+
if self.cls_token is not None:
|
408 |
+
nn.init.normal_(self.cls_token, std=1e-6)
|
409 |
+
named_apply(init_weights_vit_timm, self)
|
410 |
+
|
411 |
+
@torch.jit.ignore
|
412 |
+
def no_weight_decay(self) -> Set:
|
413 |
+
return {'pos_embed', 'cls_token', 'dist_token'}
|
414 |
+
|
415 |
+
@torch.jit.ignore
|
416 |
+
def group_matcher(self, coarse: bool = False) -> Dict:
|
417 |
+
return dict(
|
418 |
+
stem=r'^cls_token|pos_embed|patch_embed', # stem and embed
|
419 |
+
blocks=[(r'^blocks\.(\d+)', None), (r'^norm', (99999,))]
|
420 |
+
)
|
421 |
+
|
422 |
+
@torch.jit.ignore
|
423 |
+
def set_grad_checkpointing(self, enable: bool = True) -> None:
|
424 |
+
self.grad_checkpointing = enable
|
425 |
+
|
426 |
+
@torch.jit.ignore
|
427 |
+
def get_classifier(self) -> nn.Module:
|
428 |
+
return self.head
|
429 |
+
|
430 |
+
def reset_classifier(self, num_classes: int, global_pool=None) -> None:
|
431 |
+
self.num_classes = num_classes
|
432 |
+
if global_pool is not None:
|
433 |
+
assert global_pool in ('', 'avg', 'token', 'map')
|
434 |
+
if global_pool == 'map' and self.attn_pool is None:
|
435 |
+
assert False, "Cannot currently add attention pooling in reset_classifier()."
|
436 |
+
elif global_pool != 'map ' and self.attn_pool is not None:
|
437 |
+
self.attn_pool = None # remove attention pooling
|
438 |
+
self.global_pool = global_pool
|
439 |
+
self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
|
440 |
+
|
441 |
+
def _pos_embed(self, x: torch.Tensor) -> torch.Tensor:
|
442 |
+
if self.dynamic_img_size:
|
443 |
+
B, H, W, C = x.shape
|
444 |
+
pos_embed = resample_abs_pos_embed(
|
445 |
+
self.pos_embed,
|
446 |
+
(H, W),
|
447 |
+
num_prefix_tokens=0 if self.no_embed_class else self.num_prefix_tokens,
|
448 |
+
)
|
449 |
+
x = x.view(B, -1, C)
|
450 |
+
else:
|
451 |
+
pos_embed = self.pos_embed
|
452 |
+
|
453 |
+
to_cat = []
|
454 |
+
if self.cls_token is not None:
|
455 |
+
to_cat.append(self.cls_token.expand(x.shape[0], -1, -1))
|
456 |
+
if self.reg_token is not None:
|
457 |
+
to_cat.append(self.reg_token.expand(x.shape[0], -1, -1))
|
458 |
+
|
459 |
+
if self.no_embed_class:
|
460 |
+
# deit-3, updated JAX (big vision)
|
461 |
+
# position embedding does not overlap with class token, add then concat
|
462 |
+
x = x + pos_embed
|
463 |
+
if to_cat:
|
464 |
+
x = torch.cat(to_cat + [x], dim=1)
|
465 |
+
else:
|
466 |
+
# original timm, JAX, and deit vit impl
|
467 |
+
# pos_embed has entry for class token, concat then add
|
468 |
+
if to_cat:
|
469 |
+
x = torch.cat(to_cat + [x], dim=1)
|
470 |
+
x = x + pos_embed
|
471 |
+
|
472 |
+
return self.pos_drop(x)
|
473 |
+
|
474 |
+
def _intermediate_layers(
|
475 |
+
self,
|
476 |
+
x: torch.Tensor,
|
477 |
+
n: Union[int, Sequence] = 1,
|
478 |
+
) -> List[torch.Tensor]:
|
479 |
+
outputs, num_blocks = [], len(self.blocks)
|
480 |
+
take_indices = set(range(num_blocks - n, num_blocks) if isinstance(n, int) else n)
|
481 |
+
|
482 |
+
# forward pass
|
483 |
+
x = self.patch_embed(x)
|
484 |
+
x = self._pos_embed(x)
|
485 |
+
x = self.patch_drop(x)
|
486 |
+
x = self.norm_pre(x)
|
487 |
+
for i, blk in enumerate(self.blocks):
|
488 |
+
x = blk(x)
|
489 |
+
if i in take_indices:
|
490 |
+
outputs.append(x)
|
491 |
+
|
492 |
+
return outputs
|
493 |
+
|
494 |
+
def get_intermediate_layers(
|
495 |
+
self,
|
496 |
+
x: torch.Tensor,
|
497 |
+
n: Union[int, Sequence] = 1,
|
498 |
+
reshape: bool = False,
|
499 |
+
return_prefix_tokens: bool = False,
|
500 |
+
norm: bool = False,
|
501 |
+
) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]:
|
502 |
+
""" Intermediate layer accessor (NOTE: This is a WIP experiment).
|
503 |
+
Inspired by DINO / DINOv2 interface
|
504 |
+
"""
|
505 |
+
# take last n blocks if n is an int, if in is a sequence, select by matching indices
|
506 |
+
outputs = self._intermediate_layers(x, n)
|
507 |
+
if norm:
|
508 |
+
outputs = [self.norm(out) for out in outputs]
|
509 |
+
prefix_tokens = [out[:, 0:self.num_prefix_tokens] for out in outputs]
|
510 |
+
outputs = [out[:, self.num_prefix_tokens:] for out in outputs]
|
511 |
+
|
512 |
+
if reshape:
|
513 |
+
grid_size = self.patch_embed.grid_size
|
514 |
+
outputs = [
|
515 |
+
out.reshape(x.shape[0], grid_size[0], grid_size[1], -1).permute(0, 3, 1, 2).contiguous()
|
516 |
+
for out in outputs
|
517 |
+
]
|
518 |
+
|
519 |
+
if return_prefix_tokens:
|
520 |
+
return tuple(zip(outputs, prefix_tokens))
|
521 |
+
return tuple(outputs)
|
522 |
+
|
523 |
+
def forward_features(self, x: torch.Tensor) -> torch.Tensor:
|
524 |
+
if getattr(self, "is_first_stage", True):
|
525 |
+
x = self.patch_embed(x)
|
526 |
+
x = self._pos_embed(x)
|
527 |
+
x = self.patch_drop(x)
|
528 |
+
x = self.norm_pre(x)
|
529 |
+
if self.grad_checkpointing and not torch.jit.is_scripting():
|
530 |
+
skip_last = max(1, len(self.blocks) - self.num_recomputing_layers)
|
531 |
+
x = checkpoint_seq(self.blocks, x, skip_last=skip_last)
|
532 |
+
else:
|
533 |
+
x = self.blocks(x)
|
534 |
+
if getattr(self, "is_last_stage", True):
|
535 |
+
x = self.norm(x)
|
536 |
+
return x
|
537 |
+
|
538 |
+
def forward_head(self, x: torch.Tensor, pre_logits: bool = False) -> torch.Tensor:
|
539 |
+
if not getattr(self, "is_last_stage", True):
|
540 |
+
return x
|
541 |
+
if self.attn_pool is not None:
|
542 |
+
x = self.attn_pool(x)
|
543 |
+
elif self.global_pool == 'avg':
|
544 |
+
x = x[:, self.num_prefix_tokens:].mean(dim=1)
|
545 |
+
elif self.global_pool:
|
546 |
+
x = x[:, 0] # class token
|
547 |
+
x = self.fc_norm(x)
|
548 |
+
x = self.head_drop(x)
|
549 |
+
return x if pre_logits else self.head(x)
|
550 |
+
|
551 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
552 |
+
x = self.forward_features(x)
|
553 |
+
if not self.ignore_head:
|
554 |
+
x = self.forward_head(x)
|
555 |
+
return x
|
556 |
+
|
557 |
+
def to_pipeline(self, pp_size, pp_rank, pp_splits: Optional[List[int]] = None):
|
558 |
+
self.is_first_stage = pp_rank == 0
|
559 |
+
self.is_last_stage = pp_rank == pp_size - 1
|
560 |
+
if not self.is_first_stage and hasattr(self, "patch_embed"):
|
561 |
+
del self.patch_embed, self.cls_token, self.reg_token, self.pos_embed, self.pos_drop, self.patch_drop, self.norm_pre
|
562 |
+
if not self.is_last_stage and hasattr(self, "norm"):
|
563 |
+
del self.norm, self.attn_pool, self.fc_norm, self.head_drop, self.head
|
564 |
+
if pp_splits is not None:
|
565 |
+
assert len(self.blocks) == sum(pp_splits)
|
566 |
+
splits = np.cumsum([0] + pp_splits)
|
567 |
+
self.blocks = self.blocks[splits[pp_rank]:splits[pp_rank + 1]]
|
568 |
+
return self
|
569 |
+
|
570 |
+
|
571 |
+
@dataclass
|
572 |
+
class SigLIPVisionCfg:
|
573 |
+
width: int = 1152
|
574 |
+
layers: Union[Tuple[int, int, int, int], int] = 27
|
575 |
+
heads: int = 16
|
576 |
+
patch_size: int = 14
|
577 |
+
image_size: Union[Tuple[int, int], int] = 336
|
578 |
+
global_pool: str = "map"
|
579 |
+
mlp_ratio: float = 3.7362
|
580 |
+
class_token: bool = False
|
581 |
+
num_classes: int = 0
|
582 |
+
use_checkpoint: bool = False
|
583 |
+
|
584 |
+
|
585 |
+
SigLIP_MODEL_CONFIG = {
|
586 |
+
"siglip_so400m_patch14_384": {
|
587 |
+
"image_size": 384,
|
588 |
+
"patch_size": 14,
|
589 |
+
"width": 1152,
|
590 |
+
"layers": 27,
|
591 |
+
"heads": 16,
|
592 |
+
"mlp_ratio": 3.7362,
|
593 |
+
"global_pool": "map",
|
594 |
+
"use_checkpoint": False
|
595 |
+
},
|
596 |
+
|
597 |
+
"siglip_so400m_patch14_224": {
|
598 |
+
"image_size": 224,
|
599 |
+
"patch_size": 14,
|
600 |
+
"width": 1152,
|
601 |
+
"layers": 27,
|
602 |
+
"heads": 16,
|
603 |
+
"mlp_ratio": 3.7362,
|
604 |
+
"global_pool": "map",
|
605 |
+
"use_checkpoint": False
|
606 |
+
},
|
607 |
+
|
608 |
+
"siglip_large_patch16_384": {
|
609 |
+
"image_size": 384,
|
610 |
+
"patch_size": 16,
|
611 |
+
"width": 1024,
|
612 |
+
"layers": 24,
|
613 |
+
"heads": 16,
|
614 |
+
"mlp_ratio": 4,
|
615 |
+
"global_pool": "map",
|
616 |
+
"use_checkpoint": False
|
617 |
+
}
|
618 |
+
}
|
619 |
+
|
620 |
+
|
621 |
+
def create_siglip_vit(
|
622 |
+
model_name: str = "siglip_so400m_patch14_384",
|
623 |
+
image_size: int = 384,
|
624 |
+
select_layer: int = -1,
|
625 |
+
ckpt_path: str = "",
|
626 |
+
**kwargs
|
627 |
+
):
|
628 |
+
assert model_name in SigLIP_MODEL_CONFIG.keys(), f"model name should be in {SigLIP_MODEL_CONFIG.keys()}"
|
629 |
+
|
630 |
+
vision_cfg = SigLIPVisionCfg(**SigLIP_MODEL_CONFIG[model_name])
|
631 |
+
|
632 |
+
if select_layer <= 0:
|
633 |
+
layers = min(vision_cfg.layers, vision_cfg.layers + select_layer + 1)
|
634 |
+
else:
|
635 |
+
layers = min(vision_cfg.layers, select_layer)
|
636 |
+
|
637 |
+
model = VisionTransformer(
|
638 |
+
img_size=image_size,
|
639 |
+
patch_size=vision_cfg.patch_size,
|
640 |
+
embed_dim=vision_cfg.width,
|
641 |
+
depth=layers,
|
642 |
+
num_heads=vision_cfg.heads,
|
643 |
+
mlp_ratio=vision_cfg.mlp_ratio,
|
644 |
+
class_token=vision_cfg.class_token,
|
645 |
+
global_pool=vision_cfg.global_pool,
|
646 |
+
ignore_head=kwargs.get("ignore_head", True),
|
647 |
+
weight_init=kwargs.get("weight_init", "skip"),
|
648 |
+
num_classes=0,
|
649 |
+
deterministic=kwargs.get("deterministic", False),
|
650 |
+
num_recomputing_layers=kwargs.get("num_recomputing_layers", 0)
|
651 |
+
)
|
652 |
+
|
653 |
+
if ckpt_path:
|
654 |
+
state_dict = torch.load(ckpt_path, map_location="cpu")
|
655 |
+
|
656 |
+
incompatible_keys = model.load_state_dict(state_dict, strict=False)
|
657 |
+
print(f"SigLIP-ViT restores from {ckpt_path},\n"
|
658 |
+
f"\tincompatible_keys:', {incompatible_keys}.")
|
659 |
+
|
660 |
+
return model
|
deepseek_vl2/serve/__init__.py
ADDED
File without changes
|
deepseek_vl2/serve/app_modules/__init__.py
ADDED
File without changes
|
deepseek_vl2/serve/app_modules/gradio_utils.py
ADDED
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2023-2024 DeepSeek.
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of
|
4 |
+
# this software and associated documentation files (the "Software"), to deal in
|
5 |
+
# the Software without restriction, including without limitation the rights to
|
6 |
+
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
7 |
+
# the Software, and to permit persons to whom the Software is furnished to do so,
|
8 |
+
# subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in all
|
11 |
+
# copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
15 |
+
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
16 |
+
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
17 |
+
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
18 |
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
19 |
+
|
20 |
+
from functools import wraps
|
21 |
+
|
22 |
+
import gradio as gr
|
23 |
+
|
24 |
+
|
25 |
+
def wrap_gen_fn(gen_fn):
|
26 |
+
@wraps(gen_fn)
|
27 |
+
def wrapped_gen_fn(prompt, *args, **kwargs):
|
28 |
+
try:
|
29 |
+
yield from gen_fn(prompt, *args, **kwargs)
|
30 |
+
except gr.Error as g_err:
|
31 |
+
raise g_err
|
32 |
+
except Exception as e:
|
33 |
+
raise gr.Error(f"Failed to generate text: {e}") from e
|
34 |
+
|
35 |
+
return wrapped_gen_fn
|
36 |
+
|
37 |
+
|
38 |
+
def delete_last_conversation(chatbot, history):
|
39 |
+
if len(history) % 2 != 0:
|
40 |
+
gr.Error("history length is not even")
|
41 |
+
return (
|
42 |
+
chatbot,
|
43 |
+
history,
|
44 |
+
"Delete Done",
|
45 |
+
)
|
46 |
+
|
47 |
+
if len(chatbot) > 0:
|
48 |
+
chatbot.pop()
|
49 |
+
|
50 |
+
if len(history) > 0 and len(history) % 2 == 0:
|
51 |
+
history.pop()
|
52 |
+
history.pop()
|
53 |
+
|
54 |
+
return (
|
55 |
+
chatbot,
|
56 |
+
history,
|
57 |
+
"Delete Done",
|
58 |
+
)
|
59 |
+
|
60 |
+
|
61 |
+
def reset_state():
|
62 |
+
return [], [], None, "Reset Done"
|
63 |
+
|
64 |
+
|
65 |
+
def reset_textbox():
|
66 |
+
return gr.update(value=""), ""
|
67 |
+
|
68 |
+
|
69 |
+
def cancel_outputing():
|
70 |
+
return "Stop Done"
|
71 |
+
|
72 |
+
|
73 |
+
class State:
|
74 |
+
interrupted = False
|
75 |
+
|
76 |
+
def interrupt(self):
|
77 |
+
self.interrupted = True
|
78 |
+
|
79 |
+
def recover(self):
|
80 |
+
self.interrupted = False
|
81 |
+
|
82 |
+
|
83 |
+
shared_state = State()
|
deepseek_vl2/serve/app_modules/overwrites.py
ADDED
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2023-2024 DeepSeek.
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of
|
4 |
+
# this software and associated documentation files (the "Software"), to deal in
|
5 |
+
# the Software without restriction, including without limitation the rights to
|
6 |
+
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
7 |
+
# the Software, and to permit persons to whom the Software is furnished to do so,
|
8 |
+
# subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in all
|
11 |
+
# copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
15 |
+
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
16 |
+
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
17 |
+
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
18 |
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
19 |
+
|
20 |
+
from __future__ import annotations
|
21 |
+
|
22 |
+
import logging
|
23 |
+
from typing import List, Tuple
|
24 |
+
|
25 |
+
from deepseek_vl2.serve.app_modules.presets import gr
|
26 |
+
from deepseek_vl2.serve.app_modules.utils import convert_asis, convert_mdtext, detect_converted_mark
|
27 |
+
|
28 |
+
|
29 |
+
def compact_text_chunks(self, prompt, text_chunks: List[str]) -> List[str]:
|
30 |
+
logging.debug("Compacting text chunks...🚀🚀🚀")
|
31 |
+
combined_str = [c.strip() for c in text_chunks if c.strip()]
|
32 |
+
combined_str = [f"[{index+1}] {c}" for index, c in enumerate(combined_str)]
|
33 |
+
combined_str = "\n\n".join(combined_str)
|
34 |
+
# resplit based on self.max_chunk_overlap
|
35 |
+
text_splitter = self.get_text_splitter_given_prompt(prompt, 1, padding=1)
|
36 |
+
return text_splitter.split_text(combined_str)
|
37 |
+
|
38 |
+
|
39 |
+
def postprocess(
|
40 |
+
self, y: List[Tuple[str | None, str | None]]
|
41 |
+
) -> List[Tuple[str | None, str | None]]:
|
42 |
+
"""
|
43 |
+
Parameters:
|
44 |
+
y: List of tuples representing the message and response pairs. Each message and response should be a string, which may be in Markdown format.
|
45 |
+
Returns:
|
46 |
+
List of tuples representing the message and response. Each message and response will be a string of HTML.
|
47 |
+
"""
|
48 |
+
if y is None or y == []:
|
49 |
+
return []
|
50 |
+
temp = []
|
51 |
+
for x in y:
|
52 |
+
user, bot = x
|
53 |
+
if not detect_converted_mark(user):
|
54 |
+
user = convert_asis(user)
|
55 |
+
if not detect_converted_mark(bot):
|
56 |
+
bot = convert_mdtext(bot)
|
57 |
+
temp.append((user, bot))
|
58 |
+
return temp
|
59 |
+
|
60 |
+
|
61 |
+
with open("deepseek_vl2/serve/assets/custom.js", "r", encoding="utf-8") as f, open(
|
62 |
+
"deepseek_vl2/serve/assets/Kelpy-Codos.js", "r", encoding="utf-8"
|
63 |
+
) as f2:
|
64 |
+
customJS = f.read()
|
65 |
+
kelpyCodos = f2.read()
|
66 |
+
|
67 |
+
|
68 |
+
def reload_javascript():
|
69 |
+
print("Reloading javascript...")
|
70 |
+
js = f"<script>{customJS}</script><script>{kelpyCodos}</script>"
|
71 |
+
|
72 |
+
def template_response(*args, **kwargs):
|
73 |
+
res = GradioTemplateResponseOriginal(*args, **kwargs)
|
74 |
+
res.body = res.body.replace(b"</html>", f"{js}</html>".encode("utf8"))
|
75 |
+
res.init_headers()
|
76 |
+
return res
|
77 |
+
|
78 |
+
gr.routes.templates.TemplateResponse = template_response
|
79 |
+
|
80 |
+
|
81 |
+
GradioTemplateResponseOriginal = gr.routes.templates.TemplateResponse
|
deepseek_vl2/serve/app_modules/presets.py
ADDED
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2023-2024 DeepSeek.
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of
|
4 |
+
# this software and associated documentation files (the "Software"), to deal in
|
5 |
+
# the Software without restriction, including without limitation the rights to
|
6 |
+
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
7 |
+
# the Software, and to permit persons to whom the Software is furnished to do so,
|
8 |
+
# subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in all
|
11 |
+
# copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
15 |
+
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
16 |
+
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
17 |
+
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
18 |
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
19 |
+
|
20 |
+
# -*- coding:utf-8 -*-
|
21 |
+
import gradio as gr
|
22 |
+
|
23 |
+
title = """<h1 align="left" style="min-width:200px; margin-top:0;">Chat with DeepSeek-VL2 </h1>"""
|
24 |
+
description_top = """Special Tokens: `<image>`, Visual Grounding: `<|ref|>{query}<|/ref|>`, Grounding Conversation: `<|grounding|>{question}`"""
|
25 |
+
description = """"""
|
26 |
+
CONCURRENT_COUNT = 1
|
27 |
+
MAX_EVENTS = 10
|
28 |
+
MAX_IMAGE_SIZE = 800
|
29 |
+
MIN_IMAGE_SIZE = 400
|
30 |
+
|
31 |
+
BOX2COLOR = {
|
32 |
+
0: (255, 0, 0),
|
33 |
+
1: (0, 255, 0),
|
34 |
+
2: (0, 0, 255),
|
35 |
+
3: (0, 255, 255),
|
36 |
+
4: (255, 255, 0),
|
37 |
+
5: (255, 0, 255),
|
38 |
+
6: (127, 127, 127),
|
39 |
+
7: (255, 255, 127),
|
40 |
+
8: (255, 127, 255),
|
41 |
+
9: (127, 255, 255),
|
42 |
+
10: (127, 127, 255),
|
43 |
+
11: (127, 255, 127),
|
44 |
+
12: (255, 127, 127),
|
45 |
+
}
|
46 |
+
|
47 |
+
|
48 |
+
ALREADY_CONVERTED_MARK = "<!-- ALREADY CONVERTED BY PARSER. -->"
|
49 |
+
|
50 |
+
small_and_beautiful_theme = gr.themes.Soft(
|
51 |
+
primary_hue=gr.themes.Color(
|
52 |
+
c50="#EBFAF2",
|
53 |
+
c100="#CFF3E1",
|
54 |
+
c200="#A8EAC8",
|
55 |
+
c300="#77DEA9",
|
56 |
+
c400="#3FD086",
|
57 |
+
c500="#02C160",
|
58 |
+
c600="#06AE56",
|
59 |
+
c700="#05974E",
|
60 |
+
c800="#057F45",
|
61 |
+
c900="#04673D",
|
62 |
+
c950="#2E5541",
|
63 |
+
name="small_and_beautiful",
|
64 |
+
),
|
65 |
+
secondary_hue=gr.themes.Color(
|
66 |
+
c50="#576b95",
|
67 |
+
c100="#576b95",
|
68 |
+
c200="#576b95",
|
69 |
+
c300="#576b95",
|
70 |
+
c400="#576b95",
|
71 |
+
c500="#576b95",
|
72 |
+
c600="#576b95",
|
73 |
+
c700="#576b95",
|
74 |
+
c800="#576b95",
|
75 |
+
c900="#576b95",
|
76 |
+
c950="#576b95",
|
77 |
+
),
|
78 |
+
neutral_hue=gr.themes.Color(
|
79 |
+
name="gray",
|
80 |
+
c50="#f6f7f8",
|
81 |
+
# c100="#f3f4f6",
|
82 |
+
c100="#F2F2F2",
|
83 |
+
c200="#e5e7eb",
|
84 |
+
c300="#d1d5db",
|
85 |
+
c400="#B2B2B2",
|
86 |
+
c500="#808080",
|
87 |
+
c600="#636363",
|
88 |
+
c700="#515151",
|
89 |
+
c800="#393939",
|
90 |
+
# c900="#272727",
|
91 |
+
c900="#2B2B2B",
|
92 |
+
c950="#171717",
|
93 |
+
),
|
94 |
+
radius_size=gr.themes.sizes.radius_sm,
|
95 |
+
).set(
|
96 |
+
# button_primary_background_fill="*primary_500",
|
97 |
+
button_primary_background_fill_dark="*primary_600",
|
98 |
+
# button_primary_background_fill_hover="*primary_400",
|
99 |
+
# button_primary_border_color="*primary_500",
|
100 |
+
button_primary_border_color_dark="*primary_600",
|
101 |
+
button_primary_text_color="white",
|
102 |
+
button_primary_text_color_dark="white",
|
103 |
+
button_secondary_background_fill="*neutral_100",
|
104 |
+
button_secondary_background_fill_hover="*neutral_50",
|
105 |
+
button_secondary_background_fill_dark="*neutral_900",
|
106 |
+
button_secondary_text_color="*neutral_800",
|
107 |
+
button_secondary_text_color_dark="white",
|
108 |
+
# background_fill_primary="#F7F7F7",
|
109 |
+
# background_fill_primary_dark="#1F1F1F",
|
110 |
+
# block_title_text_color="*primary_500",
|
111 |
+
block_title_background_fill_dark="*primary_900",
|
112 |
+
block_label_background_fill_dark="*primary_900",
|
113 |
+
input_background_fill="#F6F6F6",
|
114 |
+
# chatbot_code_background_color_dark="*neutral_950",
|
115 |
+
)
|
deepseek_vl2/serve/app_modules/utils.py
ADDED
@@ -0,0 +1,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2023-2024 DeepSeek.
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of
|
4 |
+
# this software and associated documentation files (the "Software"), to deal in
|
5 |
+
# the Software without restriction, including without limitation the rights to
|
6 |
+
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
7 |
+
# the Software, and to permit persons to whom the Software is furnished to do so,
|
8 |
+
# subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in all
|
11 |
+
# copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
15 |
+
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
16 |
+
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
17 |
+
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
18 |
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
19 |
+
|
20 |
+
# -*- coding:utf-8 -*-
|
21 |
+
from __future__ import annotations
|
22 |
+
|
23 |
+
import html
|
24 |
+
import logging
|
25 |
+
import io
|
26 |
+
import os
|
27 |
+
import re
|
28 |
+
import base64
|
29 |
+
import time
|
30 |
+
from PIL import Image, ImageDraw, ImageFont
|
31 |
+
|
32 |
+
import mdtex2html
|
33 |
+
from markdown import markdown
|
34 |
+
from pygments import highlight
|
35 |
+
from pygments.formatters import HtmlFormatter
|
36 |
+
from pygments.lexers import ClassNotFound, get_lexer_by_name, guess_lexer
|
37 |
+
|
38 |
+
from deepseek_vl2.serve.app_modules.presets import (
|
39 |
+
ALREADY_CONVERTED_MARK,
|
40 |
+
BOX2COLOR,
|
41 |
+
MAX_IMAGE_SIZE,
|
42 |
+
MIN_IMAGE_SIZE
|
43 |
+
)
|
44 |
+
|
45 |
+
logger = logging.getLogger("gradio_logger")
|
46 |
+
|
47 |
+
|
48 |
+
def configure_logger():
|
49 |
+
logger = logging.getLogger("gradio_logger")
|
50 |
+
logger.setLevel(logging.DEBUG)
|
51 |
+
|
52 |
+
timestr = time.strftime("%Y%m%d-%H%M%S")
|
53 |
+
os.makedirs("deepseek_vl2/serve/logs", exist_ok=True)
|
54 |
+
file_handler = logging.FileHandler(
|
55 |
+
f"deepseek_vl2/serve/logs/{timestr}_gradio_log.log"
|
56 |
+
)
|
57 |
+
console_handler = logging.StreamHandler()
|
58 |
+
|
59 |
+
formatter = logging.Formatter(
|
60 |
+
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
61 |
+
)
|
62 |
+
console_handler.setFormatter(formatter)
|
63 |
+
file_handler.setFormatter(formatter)
|
64 |
+
|
65 |
+
console_handler.setLevel(logging.INFO)
|
66 |
+
file_handler.setLevel(logging.INFO)
|
67 |
+
|
68 |
+
logger.addHandler(console_handler)
|
69 |
+
logger.addHandler(file_handler)
|
70 |
+
|
71 |
+
return logger
|
72 |
+
|
73 |
+
|
74 |
+
def strip_stop_words(x, stop_words):
|
75 |
+
for w in stop_words:
|
76 |
+
if w in x:
|
77 |
+
return x[: x.index(w)].strip()
|
78 |
+
return x.strip()
|
79 |
+
|
80 |
+
|
81 |
+
def format_output(history, text, x):
|
82 |
+
updated_history = history + [[text, x]]
|
83 |
+
a = [[y[0], convert_to_markdown(y[1])] for y in updated_history]
|
84 |
+
return a, updated_history
|
85 |
+
|
86 |
+
|
87 |
+
def markdown_to_html_with_syntax_highlight(md_str): # deprecated
|
88 |
+
def replacer(match):
|
89 |
+
lang = match.group(1) or "text"
|
90 |
+
code = match.group(2)
|
91 |
+
|
92 |
+
try:
|
93 |
+
lexer = get_lexer_by_name(lang, stripall=True)
|
94 |
+
except ValueError:
|
95 |
+
lexer = get_lexer_by_name("text", stripall=True)
|
96 |
+
|
97 |
+
formatter = HtmlFormatter()
|
98 |
+
highlighted_code = highlight(code, lexer, formatter)
|
99 |
+
|
100 |
+
return f'<pre><code class="{lang}">{highlighted_code}</code></pre>'
|
101 |
+
|
102 |
+
code_block_pattern = r"```(\w+)?\n([\s\S]+?)\n```"
|
103 |
+
md_str = re.sub(code_block_pattern, replacer, md_str, flags=re.MULTILINE)
|
104 |
+
|
105 |
+
html_str = markdown(md_str)
|
106 |
+
return html_str
|
107 |
+
|
108 |
+
|
109 |
+
def normalize_markdown(md_text: str) -> str: # deprecated
|
110 |
+
lines = md_text.split("\n")
|
111 |
+
normalized_lines = []
|
112 |
+
inside_list = False
|
113 |
+
|
114 |
+
for i, line in enumerate(lines):
|
115 |
+
if re.match(r"^(\d+\.|-|\*|\+)\s", line.strip()):
|
116 |
+
if not inside_list and i > 0 and lines[i - 1].strip() != "":
|
117 |
+
normalized_lines.append("")
|
118 |
+
inside_list = True
|
119 |
+
normalized_lines.append(line)
|
120 |
+
elif inside_list and line.strip() == "":
|
121 |
+
if i < len(lines) - 1 and not re.match(
|
122 |
+
r"^(\d+\.|-|\*|\+)\s", lines[i + 1].strip()
|
123 |
+
):
|
124 |
+
normalized_lines.append(line)
|
125 |
+
continue
|
126 |
+
else:
|
127 |
+
inside_list = False
|
128 |
+
normalized_lines.append(line)
|
129 |
+
|
130 |
+
return "\n".join(normalized_lines)
|
131 |
+
|
132 |
+
|
133 |
+
def convert_mdtext(md_text):
|
134 |
+
code_block_pattern = re.compile(r"```(.*?)(?:```|$)", re.DOTALL)
|
135 |
+
inline_code_pattern = re.compile(r"`(.*?)`", re.DOTALL)
|
136 |
+
code_blocks = code_block_pattern.findall(md_text)
|
137 |
+
non_code_parts = code_block_pattern.split(md_text)[::2]
|
138 |
+
|
139 |
+
result = []
|
140 |
+
for non_code, code in zip(non_code_parts, code_blocks + [""]):
|
141 |
+
if non_code.strip():
|
142 |
+
non_code = normalize_markdown(non_code)
|
143 |
+
if inline_code_pattern.search(non_code):
|
144 |
+
result.append(markdown(non_code, extensions=["tables"]))
|
145 |
+
else:
|
146 |
+
result.append(mdtex2html.convert(non_code, extensions=["tables"]))
|
147 |
+
if code.strip():
|
148 |
+
code = f"\n```{code}\n\n```"
|
149 |
+
code = markdown_to_html_with_syntax_highlight(code)
|
150 |
+
result.append(code)
|
151 |
+
result = "".join(result)
|
152 |
+
result += ALREADY_CONVERTED_MARK
|
153 |
+
return result
|
154 |
+
|
155 |
+
|
156 |
+
def convert_asis(userinput):
|
157 |
+
return f'<p style="white-space:pre-wrap;">{html.escape(userinput)}</p>{ALREADY_CONVERTED_MARK}'
|
158 |
+
|
159 |
+
|
160 |
+
def is_stop_word_or_prefix(s: str, stop_words: list) -> bool:
|
161 |
+
return any(s.endswith(stop_word) for stop_word in stop_words)
|
162 |
+
|
163 |
+
|
164 |
+
def detect_converted_mark(userinput):
|
165 |
+
return bool(userinput.endswith(ALREADY_CONVERTED_MARK))
|
166 |
+
|
167 |
+
|
168 |
+
def detect_language(code):
|
169 |
+
first_line = "" if code.startswith("\n") else code.strip().split("\n", 1)[0]
|
170 |
+
language = first_line.lower() if first_line else ""
|
171 |
+
code_without_language = code[len(first_line) :].lstrip() if first_line else code
|
172 |
+
return language, code_without_language
|
173 |
+
|
174 |
+
|
175 |
+
def convert_to_markdown(text):
|
176 |
+
text = text.replace("$", "$")
|
177 |
+
text = text.replace("\r\n", "\n")
|
178 |
+
|
179 |
+
def replace_leading_tabs_and_spaces(line):
|
180 |
+
new_line = []
|
181 |
+
|
182 |
+
for char in line:
|
183 |
+
if char == "\t":
|
184 |
+
new_line.append("	")
|
185 |
+
elif char == " ":
|
186 |
+
new_line.append(" ")
|
187 |
+
else:
|
188 |
+
break
|
189 |
+
return "".join(new_line) + line[len(new_line) :]
|
190 |
+
|
191 |
+
markdown_text = ""
|
192 |
+
lines = text.split("\n")
|
193 |
+
in_code_block = False
|
194 |
+
|
195 |
+
for line in lines:
|
196 |
+
if in_code_block is False and line.startswith("```"):
|
197 |
+
in_code_block = True
|
198 |
+
markdown_text += f"{line}\n"
|
199 |
+
elif in_code_block is True and line.startswith("```"):
|
200 |
+
in_code_block = False
|
201 |
+
markdown_text += f"{line}\n"
|
202 |
+
elif in_code_block:
|
203 |
+
markdown_text += f"{line}\n"
|
204 |
+
else:
|
205 |
+
line = replace_leading_tabs_and_spaces(line)
|
206 |
+
line = re.sub(r"^(#)", r"\\\1", line)
|
207 |
+
markdown_text += f"{line} \n"
|
208 |
+
|
209 |
+
return markdown_text
|
210 |
+
|
211 |
+
|
212 |
+
def add_language_tag(text):
|
213 |
+
def detect_language(code_block):
|
214 |
+
try:
|
215 |
+
lexer = guess_lexer(code_block)
|
216 |
+
return lexer.name.lower()
|
217 |
+
except ClassNotFound:
|
218 |
+
return ""
|
219 |
+
|
220 |
+
code_block_pattern = re.compile(r"(```)(\w*\n[^`]+```)", re.MULTILINE)
|
221 |
+
|
222 |
+
def replacement(match):
|
223 |
+
code_block = match.group(2)
|
224 |
+
if match.group(2).startswith("\n"):
|
225 |
+
language = detect_language(code_block)
|
226 |
+
return (
|
227 |
+
f"```{language}{code_block}```" if language else f"```\n{code_block}```"
|
228 |
+
)
|
229 |
+
else:
|
230 |
+
return match.group(1) + code_block + "```"
|
231 |
+
|
232 |
+
text2 = code_block_pattern.sub(replacement, text)
|
233 |
+
return text2
|
234 |
+
|
235 |
+
|
236 |
+
def is_variable_assigned(var_name: str) -> bool:
|
237 |
+
return var_name in locals()
|
238 |
+
|
239 |
+
|
240 |
+
def pil_to_base64(
|
241 |
+
image: Image.Image,
|
242 |
+
alt: str = "user upload image",
|
243 |
+
resize: bool = True,
|
244 |
+
max_size: int = MAX_IMAGE_SIZE,
|
245 |
+
min_size: int = MIN_IMAGE_SIZE,
|
246 |
+
format: str = "JPEG",
|
247 |
+
quality: int = 95
|
248 |
+
) -> str:
|
249 |
+
|
250 |
+
if resize:
|
251 |
+
max_hw, min_hw = max(image.size), min(image.size)
|
252 |
+
aspect_ratio = max_hw / min_hw
|
253 |
+
shortest_edge = int(min(max_size / aspect_ratio, min_size, min_hw))
|
254 |
+
longest_edge = int(shortest_edge * aspect_ratio)
|
255 |
+
W, H = image.size
|
256 |
+
if H > W:
|
257 |
+
H, W = longest_edge, shortest_edge
|
258 |
+
else:
|
259 |
+
H, W = shortest_edge, longest_edge
|
260 |
+
image = image.resize((W, H))
|
261 |
+
|
262 |
+
buffered = io.BytesIO()
|
263 |
+
image.save(buffered, format=format, quality=quality)
|
264 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
265 |
+
img_str = f'<img src="data:image/png;base64,{img_b64_str}" alt="{alt}" />'
|
266 |
+
|
267 |
+
return img_str
|
268 |
+
|
269 |
+
|
270 |
+
def parse_ref_bbox(response, image: Image.Image):
|
271 |
+
try:
|
272 |
+
image = image.copy()
|
273 |
+
image_h, image_w = image.size
|
274 |
+
draw = ImageDraw.Draw(image)
|
275 |
+
|
276 |
+
ref = re.findall(r'<\|ref\|>.*?<\|/ref\|>', response)
|
277 |
+
bbox = re.findall(r'<\|det\|>.*?<\|/det\|>', response)
|
278 |
+
assert len(ref) == len(bbox)
|
279 |
+
|
280 |
+
if len(ref) == 0:
|
281 |
+
return None
|
282 |
+
|
283 |
+
boxes, labels = [], []
|
284 |
+
for box, label in zip(bbox, ref):
|
285 |
+
box = box.replace('<|det|>', '').replace('<|/det|>', '')
|
286 |
+
label = label.replace('<|ref|>', '').replace('<|/ref|>', '')
|
287 |
+
box = box[1:-1]
|
288 |
+
for onebox in re.findall(r'\[.*?\]', box):
|
289 |
+
boxes.append(eval(onebox))
|
290 |
+
labels.append(label)
|
291 |
+
|
292 |
+
for indice, (box, label) in enumerate(zip(boxes, labels)):
|
293 |
+
box = (
|
294 |
+
int(box[0] / 999 * image_h),
|
295 |
+
int(box[1] / 999 * image_w),
|
296 |
+
int(box[2] / 999 * image_h),
|
297 |
+
int(box[3] / 999 * image_w),
|
298 |
+
)
|
299 |
+
|
300 |
+
box_color = BOX2COLOR[indice % len(BOX2COLOR.keys())]
|
301 |
+
box_width = 3
|
302 |
+
draw.rectangle(box, outline=box_color, width=box_width)
|
303 |
+
|
304 |
+
text_x = box[0]
|
305 |
+
text_y = box[1] - 20
|
306 |
+
text_color = box_color
|
307 |
+
font = ImageFont.truetype("deepseek_vl2/serve/assets/simsun.ttc", size=20)
|
308 |
+
draw.text((text_x, text_y), label, font=font, fill=text_color)
|
309 |
+
|
310 |
+
# print(f"boxes = {boxes}, labels = {labels}, re-render = {image}")
|
311 |
+
return image
|
312 |
+
except:
|
313 |
+
return None
|
314 |
+
|
315 |
+
|
316 |
+
def display_example(image_list):
|
317 |
+
images_html = ""
|
318 |
+
for i, img_path in enumerate(image_list):
|
319 |
+
image = Image.open(img_path)
|
320 |
+
buffered = io.BytesIO()
|
321 |
+
image.save(buffered, format="PNG", quality=100)
|
322 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
323 |
+
img_str = f'<img src="data:image/png;base64,{img_b64_str}" alt="{img_path}" style="height:80px; margin-right: 10px;" />'
|
324 |
+
images_html += img_str
|
325 |
+
|
326 |
+
result_html = f"""
|
327 |
+
<div style="display: flex; align-items: center; margin-bottom: 10px;">
|
328 |
+
<div style="flex: 1; margin-right: 10px;">{images_html}</div>
|
329 |
+
</div>
|
330 |
+
"""
|
331 |
+
|
332 |
+
return result_html
|
333 |
+
|
deepseek_vl2/serve/assets/Kelpy-Codos.js
ADDED
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/**
|
2 |
+
* Copyright (c) 2023-2024 DeepSeek.
|
3 |
+
*
|
4 |
+
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
5 |
+
* this software and associated documentation files (the "Software"), to deal in
|
6 |
+
* the Software without restriction, including without limitation the rights to
|
7 |
+
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
8 |
+
* the Software, and to permit persons to whom the Software is furnished to do so,
|
9 |
+
* subject to the following conditions:
|
10 |
+
*
|
11 |
+
* The above copyright notice and this permission notice shall be included in all
|
12 |
+
* copies or substantial portions of the Software.
|
13 |
+
*
|
14 |
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
15 |
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
16 |
+
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
17 |
+
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
18 |
+
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
19 |
+
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
20 |
+
*/
|
21 |
+
|
22 |
+
// ==UserScript==
|
23 |
+
// @name Kelpy Codos
|
24 |
+
// @namespace https://github.com/Keldos-Li/Kelpy-Codos
|
25 |
+
// @version 1.0.5
|
26 |
+
// @author Keldos; https://keldos.me/
|
27 |
+
// @description Add copy button to PRE tags before CODE tag, for Chuanhu ChatGPT especially.
|
28 |
+
// Based on Chuanhu ChatGPT version: ac04408 (2023-3-22)
|
29 |
+
// @license GPL-3.0
|
30 |
+
// @grant none
|
31 |
+
// ==/UserScript==
|
32 |
+
|
33 |
+
(function () {
|
34 |
+
"use strict";
|
35 |
+
|
36 |
+
function addCopyButton(pre) {
|
37 |
+
var code = pre.querySelector("code");
|
38 |
+
if (!code) {
|
39 |
+
return; // 如果没有找到 <code> 元素,则不添加按钮
|
40 |
+
}
|
41 |
+
var firstChild = code.firstChild;
|
42 |
+
if (!firstChild) {
|
43 |
+
return; // 如果 <code> 元素没有子节点,则不添加按钮
|
44 |
+
}
|
45 |
+
var button = document.createElement("button");
|
46 |
+
button.textContent = "\uD83D\uDCCE"; // 使用 📎 符号作为“复制”按钮的文本
|
47 |
+
button.style.position = "relative";
|
48 |
+
button.style.float = "right";
|
49 |
+
button.style.fontSize = "1em"; // 可选:调整按钮大小
|
50 |
+
button.style.background = "none"; // 可选:去掉背景颜色
|
51 |
+
button.style.border = "none"; // 可选:去掉边框
|
52 |
+
button.style.cursor = "pointer"; // 可选:显示指针样式
|
53 |
+
button.addEventListener("click", function () {
|
54 |
+
var range = document.createRange();
|
55 |
+
range.selectNodeContents(code);
|
56 |
+
range.setStartBefore(firstChild); // 将范围设置为第一个子节点之前
|
57 |
+
var selection = window.getSelection();
|
58 |
+
selection.removeAllRanges();
|
59 |
+
selection.addRange(range);
|
60 |
+
|
61 |
+
try {
|
62 |
+
var success = document.execCommand("copy");
|
63 |
+
if (success) {
|
64 |
+
button.textContent = "\u2714";
|
65 |
+
setTimeout(function () {
|
66 |
+
button.textContent = "\uD83D\uDCCE"; // 恢复按钮为“复制”
|
67 |
+
}, 2000);
|
68 |
+
} else {
|
69 |
+
button.textContent = "\u2716";
|
70 |
+
}
|
71 |
+
} catch (e) {
|
72 |
+
console.error(e);
|
73 |
+
button.textContent = "\u2716";
|
74 |
+
}
|
75 |
+
|
76 |
+
selection.removeAllRanges();
|
77 |
+
});
|
78 |
+
code.insertBefore(button, firstChild); // 将按钮插入到第一个子元素之前
|
79 |
+
}
|
80 |
+
|
81 |
+
function handleNewElements(mutationsList, observer) {
|
82 |
+
for (var mutation of mutationsList) {
|
83 |
+
if (mutation.type === "childList") {
|
84 |
+
for (var node of mutation.addedNodes) {
|
85 |
+
if (node.nodeName === "PRE") {
|
86 |
+
addCopyButton(node);
|
87 |
+
}
|
88 |
+
}
|
89 |
+
}
|
90 |
+
}
|
91 |
+
}
|
92 |
+
|
93 |
+
var observer = new MutationObserver(handleNewElements);
|
94 |
+
observer.observe(document.documentElement, {
|
95 |
+
childList: true,
|
96 |
+
subtree: true,
|
97 |
+
});
|
98 |
+
|
99 |
+
document.querySelectorAll("pre").forEach(addCopyButton);
|
100 |
+
})();
|
deepseek_vl2/serve/assets/avatar.png
ADDED
![]() |
Git LFS Details
|
deepseek_vl2/serve/assets/custom.css
ADDED
@@ -0,0 +1,355 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/**
|
2 |
+
* Copyright (c) 2023-2024 DeepSeek.
|
3 |
+
*
|
4 |
+
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
5 |
+
* this software and associated documentation files (the "Software"), to deal in
|
6 |
+
* the Software without restriction, including without limitation the rights to
|
7 |
+
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
8 |
+
* the Software, and to permit persons to whom the Software is furnished to do so,
|
9 |
+
* subject to the following conditions:
|
10 |
+
*
|
11 |
+
* The above copyright notice and this permission notice shall be included in all
|
12 |
+
* copies or substantial portions of the Software.
|
13 |
+
*
|
14 |
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
15 |
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
16 |
+
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
17 |
+
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
18 |
+
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
19 |
+
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
20 |
+
*/
|
21 |
+
|
22 |
+
:root {
|
23 |
+
--chatbot-color-light: #f3f3f3;
|
24 |
+
--chatbot-color-dark: #121111;
|
25 |
+
}
|
26 |
+
|
27 |
+
/* status_display */
|
28 |
+
#status_display {
|
29 |
+
display: flex;
|
30 |
+
min-height: 2.5em;
|
31 |
+
align-items: flex-end;
|
32 |
+
justify-content: flex-end;
|
33 |
+
}
|
34 |
+
#status_display p {
|
35 |
+
font-size: 0.85em;
|
36 |
+
font-family: monospace;
|
37 |
+
color: var(--body-text-color-subdued);
|
38 |
+
}
|
39 |
+
|
40 |
+
/* usage_display */
|
41 |
+
#usage_display {
|
42 |
+
height: 1em;
|
43 |
+
}
|
44 |
+
#usage_display p {
|
45 |
+
padding: 0 1em;
|
46 |
+
font-size: 0.85em;
|
47 |
+
font-family: monospace;
|
48 |
+
color: var(--body-text-color-subdued);
|
49 |
+
}
|
50 |
+
/* list */
|
51 |
+
ol:not(.options),
|
52 |
+
ul:not(.options) {
|
53 |
+
padding-inline-start: 2em !important;
|
54 |
+
}
|
55 |
+
|
56 |
+
/* Thank @Keldos-Li for fixing it */
|
57 |
+
/* Light mode (default) */
|
58 |
+
#deepseek_chatbot {
|
59 |
+
background-color: var(--chatbot-color-light) !important;
|
60 |
+
color: #000000 !important;
|
61 |
+
}
|
62 |
+
[data-testid="bot"] {
|
63 |
+
background-color: #ffffff !important;
|
64 |
+
}
|
65 |
+
[data-testid="user"] {
|
66 |
+
background-color: #95ec69 !important;
|
67 |
+
}
|
68 |
+
|
69 |
+
/* Dark mode */
|
70 |
+
.dark #deepseek_chatbot {
|
71 |
+
background-color: var(--chatbot-color-dark) !important;
|
72 |
+
color: #ffffff !important;
|
73 |
+
}
|
74 |
+
.dark [data-testid="bot"] {
|
75 |
+
background-color: #2c2c2c !important;
|
76 |
+
}
|
77 |
+
.dark [data-testid="user"] {
|
78 |
+
background-color: #26b561 !important;
|
79 |
+
}
|
80 |
+
|
81 |
+
#deepseek_chatbot {
|
82 |
+
height: 100%;
|
83 |
+
min-height: 800px;
|
84 |
+
flex-grow: 1;
|
85 |
+
overflow: auto;
|
86 |
+
}
|
87 |
+
|
88 |
+
[class*="message"] {
|
89 |
+
border-radius: var(--radius-xl) !important;
|
90 |
+
border: none;
|
91 |
+
padding: var(--spacing-xl) !important;
|
92 |
+
font-size: var(--text-md) !important;
|
93 |
+
line-height: var(--line-md) !important;
|
94 |
+
min-height: calc(var(--text-md) * var(--line-md) + 2 * var(--spacing-xl));
|
95 |
+
min-width: calc(var(--text-md) * var(--line-md) + 2 * var(--spacing-xl));
|
96 |
+
}
|
97 |
+
[data-testid="bot"] {
|
98 |
+
max-width: 85%;
|
99 |
+
border-bottom-left-radius: 0 !important;
|
100 |
+
}
|
101 |
+
[data-testid="user"] {
|
102 |
+
max-width: 85%;
|
103 |
+
width: auto !important;
|
104 |
+
border-bottom-right-radius: 0 !important;
|
105 |
+
}
|
106 |
+
/* Table */
|
107 |
+
table {
|
108 |
+
margin: 1em 0;
|
109 |
+
border-collapse: collapse;
|
110 |
+
empty-cells: show;
|
111 |
+
}
|
112 |
+
td,
|
113 |
+
th {
|
114 |
+
border: 1.2px solid var(--border-color-primary) !important;
|
115 |
+
padding: 0.2em;
|
116 |
+
}
|
117 |
+
thead {
|
118 |
+
background-color: rgba(175, 184, 193, 0.2);
|
119 |
+
}
|
120 |
+
thead th {
|
121 |
+
padding: 0.5em 0.2em;
|
122 |
+
}
|
123 |
+
/* Inline code */
|
124 |
+
#deepseek_chatbot code {
|
125 |
+
display: inline;
|
126 |
+
white-space: break-spaces;
|
127 |
+
border-radius: 6px;
|
128 |
+
margin: 0 2px 0 2px;
|
129 |
+
padding: 0.2em 0.4em 0.1em 0.4em;
|
130 |
+
background-color: rgba(175, 184, 193, 0.2);
|
131 |
+
}
|
132 |
+
/* Code block */
|
133 |
+
#deepseek_chatbot pre code {
|
134 |
+
display: block;
|
135 |
+
overflow: auto;
|
136 |
+
white-space: pre;
|
137 |
+
background-color: #1c1d1e !important;
|
138 |
+
border-radius: 10px;
|
139 |
+
padding: 1.4em 1.2em 0em 1.4em;
|
140 |
+
margin: 1.2em 2em 1.2em 0.5em;
|
141 |
+
color: #fdf8f8;
|
142 |
+
box-shadow: 6px 6px 16px hsla(0, 0%, 0%, 0.2);
|
143 |
+
}
|
144 |
+
/* Hightlight */
|
145 |
+
#deepseek_chatbot .highlight {
|
146 |
+
background-color: transparent;
|
147 |
+
}
|
148 |
+
#deepseek_chatbot .highlight .hll {
|
149 |
+
background-color: #49483e;
|
150 |
+
}
|
151 |
+
#deepseek_chatbot .highlight .c {
|
152 |
+
color: #75715e;
|
153 |
+
} /* Comment */
|
154 |
+
#deepseek_chatbot .highlight .err {
|
155 |
+
color: #960050;
|
156 |
+
background-color: #1e0010;
|
157 |
+
} /* Error */
|
158 |
+
#deepseek_chatbot .highlight .k {
|
159 |
+
color: #66d9ef;
|
160 |
+
} /* Keyword */
|
161 |
+
#deepseek_chatbot .highlight .l {
|
162 |
+
color: #ae81ff;
|
163 |
+
} /* Literal */
|
164 |
+
#deepseek_chatbot .highlight .n {
|
165 |
+
color: #f8f8f2;
|
166 |
+
} /* Name */
|
167 |
+
#deepseek_chatbot .highlight .o {
|
168 |
+
color: #f92672;
|
169 |
+
} /* Operator */
|
170 |
+
#deepseek_chatbot .highlight .p {
|
171 |
+
color: #f8f8f2;
|
172 |
+
} /* Punctuation */
|
173 |
+
#deepseek_chatbot .highlight .ch {
|
174 |
+
color: #75715e;
|
175 |
+
} /* Comment.Hashbang */
|
176 |
+
#deepseek_chatbot .highlight .cm {
|
177 |
+
color: #75715e;
|
178 |
+
} /* Comment.Multiline */
|
179 |
+
#deepseek_chatbot .highlight .cp {
|
180 |
+
color: #75715e;
|
181 |
+
} /* Comment.Preproc */
|
182 |
+
#deepseek_chatbot .highlight .cpf {
|
183 |
+
color: #75715e;
|
184 |
+
} /* Comment.PreprocFile */
|
185 |
+
#deepseek_chatbot .highlight .c1 {
|
186 |
+
color: #75715e;
|
187 |
+
} /* Comment.Single */
|
188 |
+
#deepseek_chatbot .highlight .cs {
|
189 |
+
color: #75715e;
|
190 |
+
} /* Comment.Special */
|
191 |
+
#deepseek_chatbot .highlight .gd {
|
192 |
+
color: #f92672;
|
193 |
+
} /* Generic.Deleted */
|
194 |
+
#deepseek_chatbot .highlight .ge {
|
195 |
+
font-style: italic;
|
196 |
+
} /* Generic.Emph */
|
197 |
+
#deepseek_chatbot .highlight .gi {
|
198 |
+
color: #a6e22e;
|
199 |
+
} /* Generic.Inserted */
|
200 |
+
#deepseek_chatbot .highlight .gs {
|
201 |
+
font-weight: bold;
|
202 |
+
} /* Generic.Strong */
|
203 |
+
#deepseek_chatbot .highlight .gu {
|
204 |
+
color: #75715e;
|
205 |
+
} /* Generic.Subheading */
|
206 |
+
#deepseek_chatbot .highlight .kc {
|
207 |
+
color: #66d9ef;
|
208 |
+
} /* Keyword.Constant */
|
209 |
+
#deepseek_chatbot .highlight .kd {
|
210 |
+
color: #66d9ef;
|
211 |
+
} /* Keyword.Declaration */
|
212 |
+
#deepseek_chatbot .highlight .kn {
|
213 |
+
color: #f92672;
|
214 |
+
} /* Keyword.Namespace */
|
215 |
+
#deepseek_chatbot .highlight .kp {
|
216 |
+
color: #66d9ef;
|
217 |
+
} /* Keyword.Pseudo */
|
218 |
+
#deepseek_chatbot .highlight .kr {
|
219 |
+
color: #66d9ef;
|
220 |
+
} /* Keyword.Reserved */
|
221 |
+
#deepseek_chatbot .highlight .kt {
|
222 |
+
color: #66d9ef;
|
223 |
+
} /* Keyword.Type */
|
224 |
+
#deepseek_chatbot .highlight .ld {
|
225 |
+
color: #e6db74;
|
226 |
+
} /* Literal.Date */
|
227 |
+
#deepseek_chatbot .highlight .m {
|
228 |
+
color: #ae81ff;
|
229 |
+
} /* Literal.Number */
|
230 |
+
#deepseek_chatbot .highlight .s {
|
231 |
+
color: #e6db74;
|
232 |
+
} /* Literal.String */
|
233 |
+
#deepseek_chatbot .highlight .na {
|
234 |
+
color: #a6e22e;
|
235 |
+
} /* Name.Attribute */
|
236 |
+
#deepseek_chatbot .highlight .nb {
|
237 |
+
color: #f8f8f2;
|
238 |
+
} /* Name.Builtin */
|
239 |
+
#deepseek_chatbot .highlight .nc {
|
240 |
+
color: #a6e22e;
|
241 |
+
} /* Name.Class */
|
242 |
+
#deepseek_chatbot .highlight .no {
|
243 |
+
color: #66d9ef;
|
244 |
+
} /* Name.Constant */
|
245 |
+
#deepseek_chatbot .highlight .nd {
|
246 |
+
color: #a6e22e;
|
247 |
+
} /* Name.Decorator */
|
248 |
+
#deepseek_chatbot .highlight .ni {
|
249 |
+
color: #f8f8f2;
|
250 |
+
} /* Name.Entity */
|
251 |
+
#deepseek_chatbot .highlight .ne {
|
252 |
+
color: #a6e22e;
|
253 |
+
} /* Name.Exception */
|
254 |
+
#deepseek_chatbot .highlight .nf {
|
255 |
+
color: #a6e22e;
|
256 |
+
} /* Name.Function */
|
257 |
+
#deepseek_chatbot .highlight .nl {
|
258 |
+
color: #f8f8f2;
|
259 |
+
} /* Name.Label */
|
260 |
+
#deepseek_chatbot .highlight .nn {
|
261 |
+
color: #f8f8f2;
|
262 |
+
} /* Name.Namespace */
|
263 |
+
#deepseek_chatbot .highlight .nx {
|
264 |
+
color: #a6e22e;
|
265 |
+
} /* Name.Other */
|
266 |
+
#deepseek_chatbot .highlight .py {
|
267 |
+
color: #f8f8f2;
|
268 |
+
} /* Name.Property */
|
269 |
+
#deepseek_chatbot .highlight .nt {
|
270 |
+
color: #f92672;
|
271 |
+
} /* Name.Tag */
|
272 |
+
#deepseek_chatbot .highlight .nv {
|
273 |
+
color: #f8f8f2;
|
274 |
+
} /* Name.Variable */
|
275 |
+
#deepseek_chatbot .highlight .ow {
|
276 |
+
color: #f92672;
|
277 |
+
} /* Operator.Word */
|
278 |
+
#deepseek_chatbot .highlight .w {
|
279 |
+
color: #f8f8f2;
|
280 |
+
} /* Text.Whitespace */
|
281 |
+
#deepseek_chatbot .highlight .mb {
|
282 |
+
color: #ae81ff;
|
283 |
+
} /* Literal.Number.Bin */
|
284 |
+
#deepseek_chatbot .highlight .mf {
|
285 |
+
color: #ae81ff;
|
286 |
+
} /* Literal.Number.Float */
|
287 |
+
#deepseek_chatbot .highlight .mh {
|
288 |
+
color: #ae81ff;
|
289 |
+
} /* Literal.Number.Hex */
|
290 |
+
#deepseek_chatbot .highlight .mi {
|
291 |
+
color: #ae81ff;
|
292 |
+
} /* Literal.Number.Integer */
|
293 |
+
#deepseek_chatbot .highlight .mo {
|
294 |
+
color: #ae81ff;
|
295 |
+
} /* Literal.Number.Oct */
|
296 |
+
#deepseek_chatbot .highlight .sa {
|
297 |
+
color: #e6db74;
|
298 |
+
} /* Literal.String.Affix */
|
299 |
+
#deepseek_chatbot .highlight .sb {
|
300 |
+
color: #e6db74;
|
301 |
+
} /* Literal.String.Backtick */
|
302 |
+
#deepseek_chatbot .highlight .sc {
|
303 |
+
color: #e6db74;
|
304 |
+
} /* Literal.String.Char */
|
305 |
+
#deepseek_chatbot .highlight .dl {
|
306 |
+
color: #e6db74;
|
307 |
+
} /* Literal.String.Delimiter */
|
308 |
+
#deepseek_chatbot .highlight .sd {
|
309 |
+
color: #e6db74;
|
310 |
+
} /* Literal.String.Doc */
|
311 |
+
#deepseek_chatbot .highlight .s2 {
|
312 |
+
color: #e6db74;
|
313 |
+
} /* Literal.String.Double */
|
314 |
+
#deepseek_chatbot .highlight .se {
|
315 |
+
color: #ae81ff;
|
316 |
+
} /* Literal.String.Escape */
|
317 |
+
#deepseek_chatbot .highlight .sh {
|
318 |
+
color: #e6db74;
|
319 |
+
} /* Literal.String.Heredoc */
|
320 |
+
#deepseek_chatbot .highlight .si {
|
321 |
+
color: #e6db74;
|
322 |
+
} /* Literal.String.Interpol */
|
323 |
+
#deepseek_chatbot .highlight .sx {
|
324 |
+
color: #e6db74;
|
325 |
+
} /* Literal.String.Other */
|
326 |
+
#deepseek_chatbot .highlight .sr {
|
327 |
+
color: #e6db74;
|
328 |
+
} /* Literal.String.Regex */
|
329 |
+
#deepseek_chatbot .highlight .s1 {
|
330 |
+
color: #e6db74;
|
331 |
+
} /* Literal.String.Single */
|
332 |
+
#deepseek_chatbot .highlight .ss {
|
333 |
+
color: #e6db74;
|
334 |
+
} /* Literal.String.Symbol */
|
335 |
+
#deepseek_chatbot .highlight .bp {
|
336 |
+
color: #f8f8f2;
|
337 |
+
} /* Name.Builtin.Pseudo */
|
338 |
+
#deepseek_chatbot .highlight .fm {
|
339 |
+
color: #a6e22e;
|
340 |
+
} /* Name.Function.Magic */
|
341 |
+
#deepseek_chatbot .highlight .vc {
|
342 |
+
color: #f8f8f2;
|
343 |
+
} /* Name.Variable.Class */
|
344 |
+
#deepseek_chatbot .highlight .vg {
|
345 |
+
color: #f8f8f2;
|
346 |
+
} /* Name.Variable.Global */
|
347 |
+
#deepseek_chatbot .highlight .vi {
|
348 |
+
color: #f8f8f2;
|
349 |
+
} /* Name.Variable.Instance */
|
350 |
+
#deepseek_chatbot .highlight .vm {
|
351 |
+
color: #f8f8f2;
|
352 |
+
} /* Name.Variable.Magic */
|
353 |
+
#deepseek_chatbot .highlight .il {
|
354 |
+
color: #ae81ff;
|
355 |
+
} /* Literal.Number.Integer.Long */
|
deepseek_vl2/serve/assets/custom.js
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/**
|
2 |
+
* Copyright (c) 2023-2024 DeepSeek.
|
3 |
+
*
|
4 |
+
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
5 |
+
* this software and associated documentation files (the "Software"), to deal in
|
6 |
+
* the Software without restriction, including without limitation the rights to
|
7 |
+
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
8 |
+
* the Software, and to permit persons to whom the Software is furnished to do so,
|
9 |
+
* subject to the following conditions:
|
10 |
+
*
|
11 |
+
* The above copyright notice and this permission notice shall be included in all
|
12 |
+
* copies or substantial portions of the Software.
|
13 |
+
*
|
14 |
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
15 |
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
16 |
+
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
17 |
+
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
18 |
+
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
19 |
+
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
20 |
+
*/
|
21 |
+
|
22 |
+
// custom javascript here
|
deepseek_vl2/serve/assets/favicon.ico
ADDED
|
Git LFS Details
|
deepseek_vl2/serve/assets/simsun.ttc
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ff7d69bfa6588d3fdedbddbe3a29ac11f0c50236723ee72a9ea49ec3e2553f5d
|
3 |
+
size 15323200
|
deepseek_vl2/serve/inference.py
ADDED
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2023-2024 DeepSeek.
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of
|
4 |
+
# this software and associated documentation files (the "Software"), to deal in
|
5 |
+
# the Software without restriction, including without limitation the rights to
|
6 |
+
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
7 |
+
# the Software, and to permit persons to whom the Software is furnished to do so,
|
8 |
+
# subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in all
|
11 |
+
# copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
15 |
+
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
16 |
+
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
17 |
+
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
18 |
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
19 |
+
|
20 |
+
from threading import Thread
|
21 |
+
from typing import List
|
22 |
+
|
23 |
+
import torch
|
24 |
+
import transformers
|
25 |
+
from joblib.externals.cloudpickle import instance
|
26 |
+
from transformers import (
|
27 |
+
AutoModelForCausalLM,
|
28 |
+
StoppingCriteria,
|
29 |
+
StoppingCriteriaList,
|
30 |
+
TextIteratorStreamer,
|
31 |
+
)
|
32 |
+
|
33 |
+
from deepseek_vl2.models import DeepseekVLV2Processor, DeepseekVLV2ForCausalLM
|
34 |
+
from deepseek_vl2.models.conversation import Conversation
|
35 |
+
|
36 |
+
|
37 |
+
def load_model(model_path, dtype=torch.bfloat16):
|
38 |
+
vl_chat_processor = DeepseekVLV2Processor.from_pretrained(model_path)
|
39 |
+
tokenizer = vl_chat_processor.tokenizer
|
40 |
+
|
41 |
+
vl_gpt: DeepseekVLV2ForCausalLM = AutoModelForCausalLM.from_pretrained(
|
42 |
+
model_path, trust_remote_code=True, torch_dtype=dtype
|
43 |
+
)
|
44 |
+
vl_gpt = vl_gpt.cuda().eval()
|
45 |
+
return tokenizer, vl_gpt, vl_chat_processor
|
46 |
+
|
47 |
+
|
48 |
+
def convert_conversation_to_prompts(conversation: Conversation):
|
49 |
+
conv_prompts = []
|
50 |
+
|
51 |
+
last_image = None
|
52 |
+
|
53 |
+
messages = conversation.messages
|
54 |
+
for i in range(0, len(messages), 2):
|
55 |
+
|
56 |
+
if isinstance(messages[i][1], tuple):
|
57 |
+
text, images = messages[i][1]
|
58 |
+
last_image = images[-1]
|
59 |
+
else:
|
60 |
+
text, images = messages[i][1], []
|
61 |
+
|
62 |
+
prompt = {
|
63 |
+
"role": messages[i][0],
|
64 |
+
"content": text,
|
65 |
+
"images": images
|
66 |
+
}
|
67 |
+
response = {"role": messages[i + 1][0], "content": messages[i + 1][1]}
|
68 |
+
conv_prompts.extend([prompt, response])
|
69 |
+
|
70 |
+
return conv_prompts, last_image
|
71 |
+
|
72 |
+
|
73 |
+
class StoppingCriteriaSub(StoppingCriteria):
|
74 |
+
def __init__(self, stops=[], encounters=1):
|
75 |
+
super().__init__()
|
76 |
+
self.stops = [stop.to("cuda") for stop in stops]
|
77 |
+
|
78 |
+
def __call__(
|
79 |
+
self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs
|
80 |
+
):
|
81 |
+
for stop in self.stops:
|
82 |
+
if input_ids.shape[-1] < len(stop):
|
83 |
+
continue
|
84 |
+
if torch.all((stop == input_ids[0][-len(stop) :])).item():
|
85 |
+
return True
|
86 |
+
|
87 |
+
return False
|
88 |
+
|
89 |
+
|
90 |
+
@torch.inference_mode()
|
91 |
+
def deepseek_generate(
|
92 |
+
conversations: list,
|
93 |
+
vl_gpt: torch.nn.Module,
|
94 |
+
vl_chat_processor: DeepseekVLV2Processor,
|
95 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
96 |
+
stop_words: list,
|
97 |
+
max_length: int = 256,
|
98 |
+
temperature: float = 1.0,
|
99 |
+
top_p: float = 1.0,
|
100 |
+
repetition_penalty: float = 1.1,
|
101 |
+
chunk_size: int = -1
|
102 |
+
):
|
103 |
+
pil_images = []
|
104 |
+
for message in conversations:
|
105 |
+
if "images" not in message:
|
106 |
+
continue
|
107 |
+
pil_images.extend(message["images"])
|
108 |
+
|
109 |
+
prepare_inputs = vl_chat_processor.__call__(
|
110 |
+
conversations=conversations,
|
111 |
+
images=pil_images,
|
112 |
+
inference_mode=True,
|
113 |
+
force_batchify=True,
|
114 |
+
system_prompt=""
|
115 |
+
).to(vl_gpt.device)
|
116 |
+
|
117 |
+
return generate(
|
118 |
+
vl_gpt,
|
119 |
+
tokenizer,
|
120 |
+
prepare_inputs,
|
121 |
+
max_gen_len=max_length,
|
122 |
+
temperature=temperature,
|
123 |
+
repetition_penalty=repetition_penalty,
|
124 |
+
top_p=top_p,
|
125 |
+
stop_words=stop_words,
|
126 |
+
chunk_size=chunk_size
|
127 |
+
)
|
128 |
+
|
129 |
+
|
130 |
+
@torch.inference_mode()
|
131 |
+
def generate(
|
132 |
+
vl_gpt,
|
133 |
+
tokenizer,
|
134 |
+
prepare_inputs,
|
135 |
+
max_gen_len: int = 256,
|
136 |
+
temperature: float = 0,
|
137 |
+
repetition_penalty=1.1,
|
138 |
+
top_p: float = 0.95,
|
139 |
+
stop_words: List[str] = [],
|
140 |
+
chunk_size: int = -1
|
141 |
+
):
|
142 |
+
"""Stream the text output from the multimodality model with prompt and image inputs."""
|
143 |
+
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True)
|
144 |
+
|
145 |
+
stop_words_ids = [
|
146 |
+
torch.tensor(tokenizer.encode(stop_word)) for stop_word in stop_words
|
147 |
+
]
|
148 |
+
stopping_criteria = StoppingCriteriaList(
|
149 |
+
[StoppingCriteriaSub(stops=stop_words_ids)]
|
150 |
+
)
|
151 |
+
|
152 |
+
if chunk_size != -1:
|
153 |
+
inputs_embeds, past_key_values = vl_gpt.incremental_prefilling(
|
154 |
+
input_ids=prepare_inputs.input_ids,
|
155 |
+
images=prepare_inputs.images,
|
156 |
+
images_seq_mask=prepare_inputs.images_seq_mask,
|
157 |
+
images_spatial_crop=prepare_inputs.images_spatial_crop,
|
158 |
+
attention_mask=prepare_inputs.attention_mask,
|
159 |
+
chunk_size=chunk_size
|
160 |
+
)
|
161 |
+
else:
|
162 |
+
inputs_embeds = vl_gpt.prepare_inputs_embeds(**prepare_inputs)
|
163 |
+
past_key_values = None
|
164 |
+
|
165 |
+
generation_config = dict(
|
166 |
+
inputs_embeds=inputs_embeds,
|
167 |
+
input_ids=prepare_inputs.input_ids,
|
168 |
+
images=prepare_inputs.images,
|
169 |
+
images_seq_mask=prepare_inputs.images_seq_mask,
|
170 |
+
images_spatial_crop=prepare_inputs.images_spatial_crop,
|
171 |
+
attention_mask=prepare_inputs.attention_mask,
|
172 |
+
past_key_values=past_key_values,
|
173 |
+
pad_token_id=tokenizer.eos_token_id,
|
174 |
+
bos_token_id=tokenizer.bos_token_id,
|
175 |
+
eos_token_id=tokenizer.eos_token_id,
|
176 |
+
max_new_tokens=max_gen_len,
|
177 |
+
do_sample=True,
|
178 |
+
use_cache=True,
|
179 |
+
streamer=streamer,
|
180 |
+
stopping_criteria=stopping_criteria,
|
181 |
+
)
|
182 |
+
|
183 |
+
if temperature > 0:
|
184 |
+
generation_config.update(
|
185 |
+
{
|
186 |
+
"do_sample": True,
|
187 |
+
"top_p": top_p,
|
188 |
+
"temperature": temperature,
|
189 |
+
"repetition_penalty": repetition_penalty,
|
190 |
+
}
|
191 |
+
)
|
192 |
+
else:
|
193 |
+
generation_config["do_sample"] = False
|
194 |
+
|
195 |
+
thread = Thread(target=vl_gpt.generate, kwargs=generation_config)
|
196 |
+
thread.start()
|
197 |
+
|
198 |
+
yield from streamer
|
deepseek_vl2/utils/__init__.py
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2023-2024 DeepSeek.
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of
|
4 |
+
# this software and associated documentation files (the "Software"), to deal in
|
5 |
+
# the Software without restriction, including without limitation the rights to
|
6 |
+
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
7 |
+
# the Software, and to permit persons to whom the Software is furnished to do so,
|
8 |
+
# subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in all
|
11 |
+
# copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
15 |
+
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
16 |
+
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
17 |
+
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
18 |
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
deepseek_vl2/utils/io.py
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2023-2024 DeepSeek.
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of
|
4 |
+
# this software and associated documentation files (the "Software"), to deal in
|
5 |
+
# the Software without restriction, including without limitation the rights to
|
6 |
+
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
7 |
+
# the Software, and to permit persons to whom the Software is furnished to do so,
|
8 |
+
# subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in all
|
11 |
+
# copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
15 |
+
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
16 |
+
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
17 |
+
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
18 |
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
19 |
+
|
20 |
+
import json
|
21 |
+
from typing import Dict, List
|
22 |
+
|
23 |
+
import PIL.Image
|
24 |
+
import torch
|
25 |
+
from transformers import AutoModelForCausalLM
|
26 |
+
|
27 |
+
|
28 |
+
def load_pretrained_model(model_path: str):
|
29 |
+
|
30 |
+
from deepseek_vl2.models.processing_deepseek_vl_v2 import DeepseekVLV2Processor
|
31 |
+
from deepseek_vl2.models.modeling_deepseek_vl_v2 import DeepseekVLV2ForCausalLM
|
32 |
+
|
33 |
+
vl_chat_processor = DeepseekVLV2Processor.from_pretrained(model_path)
|
34 |
+
tokenizer = vl_chat_processor.tokenizer
|
35 |
+
|
36 |
+
vl_gpt: DeepseekVLV2ForCausalLM = AutoModelForCausalLM.from_pretrained(
|
37 |
+
model_path, trust_remote_code=True
|
38 |
+
)
|
39 |
+
vl_gpt = vl_gpt.to(torch.bfloat16).cuda().eval()
|
40 |
+
|
41 |
+
return tokenizer, vl_chat_processor, vl_gpt
|
42 |
+
|
43 |
+
|
44 |
+
def load_pil_images(conversations: List[Dict[str, str]]) -> List[PIL.Image.Image]:
|
45 |
+
"""
|
46 |
+
|
47 |
+
Args:
|
48 |
+
conversations (List[Dict[str, str]]): the conversations with a list of messages. An example is :
|
49 |
+
[
|
50 |
+
{
|
51 |
+
"role": "User",
|
52 |
+
"content": "<image>\nExtract all information from this image and convert them into markdown format.",
|
53 |
+
"images": ["./examples/table_datasets.png"]
|
54 |
+
},
|
55 |
+
{"role": "Assistant", "content": ""},
|
56 |
+
]
|
57 |
+
|
58 |
+
Returns:
|
59 |
+
pil_images (List[PIL.Image.Image]): the list of PIL images.
|
60 |
+
|
61 |
+
"""
|
62 |
+
|
63 |
+
pil_images = []
|
64 |
+
|
65 |
+
for message in conversations:
|
66 |
+
if "images" not in message:
|
67 |
+
continue
|
68 |
+
|
69 |
+
for image_path in message["images"]:
|
70 |
+
pil_img = PIL.Image.open(image_path)
|
71 |
+
pil_img = pil_img.convert("RGB")
|
72 |
+
pil_images.append(pil_img)
|
73 |
+
|
74 |
+
return pil_images
|
75 |
+
|
76 |
+
|
77 |
+
def load_json(filepath):
|
78 |
+
with open(filepath, "r") as f:
|
79 |
+
data = json.load(f)
|
80 |
+
return data
|
images/grounding_conversation_1.jpeg
ADDED
![]() |
Git LFS Details
|
images/icl_vg_2.jpeg
ADDED
![]() |
Git LFS Details
|
images/incontext_visual_grounding_1.jpeg
ADDED
![]() |
Git LFS Details
|
images/logo.png
ADDED
![]() |
Git LFS Details
|
images/logo.svg
ADDED
|
Git LFS Details
|
images/monday.jpg
ADDED
![]() |
Git LFS Details
|
images/multi_image_1.jpeg
ADDED
![]() |
Git LFS Details
|
images/multi_image_2.jpeg
ADDED
![]() |
Git LFS Details
|
images/multi_image_3.jpeg
ADDED
![]() |
Git LFS Details
|
images/qr.jpeg
ADDED
![]() |
Git LFS Details
|
images/sample.jpg
ADDED
![]() |
Git LFS Details
|
images/vg_2.jpeg
ADDED
![]() |
Git LFS Details
|
images/visual_grounding_1.jpeg
ADDED
![]() |
Git LFS Details
|
images/visual_grounding_2.jpg
ADDED
![]() |
Git LFS Details
|
images/visual_grounding_3.png
ADDED
![]() |
Git LFS Details
|
images/vl2_teaser.jpeg
ADDED
![]() |
Git LFS Details
|