Upload liqi files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .DS_Store +0 -0
- .gitattributes +1 -0
- code/.DS_Store +0 -0
- code/multi_vlm2vec_train/.DS_Store +0 -0
- code/multi_vlm2vec_train/.gitignore +206 -0
- code/multi_vlm2vec_train/Miniconda3-latest-Linux-x86_64.sh +3 -0
- code/multi_vlm2vec_train/__pycache__/logger.cpython-310.pyc +0 -0
- code/multi_vlm2vec_train/__pycache__/logger.cpython-313.pyc +0 -0
- code/multi_vlm2vec_train/bianji_test_10.json +142 -0
- code/multi_vlm2vec_train/bianji_test_200.json +0 -0
- code/multi_vlm2vec_train/case.py +26 -0
- code/multi_vlm2vec_train/collators/__init__.py +11 -0
- code/multi_vlm2vec_train/collators/__pycache__/__init__.cpython-310.pyc +0 -0
- code/multi_vlm2vec_train/collators/__pycache__/__init__.cpython-313.pyc +0 -0
- code/multi_vlm2vec_train/collators/__pycache__/base.cpython-310.pyc +0 -0
- code/multi_vlm2vec_train/collators/__pycache__/base.cpython-313.pyc +0 -0
- code/multi_vlm2vec_train/collators/__pycache__/tuwen_qwen3vl.cpython-313.pyc +0 -0
- code/multi_vlm2vec_train/collators/__pycache__/tuwen_qwen3vl_eval.cpython-310.pyc +0 -0
- code/multi_vlm2vec_train/collators/__pycache__/tuwen_qwen3vl_eval.cpython-313.pyc +0 -0
- code/multi_vlm2vec_train/collators/__pycache__/tuwen_tbstars.cpython-310.pyc +0 -0
- code/multi_vlm2vec_train/collators/__pycache__/tuwen_tbstars.cpython-313.pyc +0 -0
- code/multi_vlm2vec_train/collators/base.py +29 -0
- code/multi_vlm2vec_train/collators/tuwen_qwen3vl.py +42 -0
- code/multi_vlm2vec_train/collators/tuwen_qwen3vl_eval.py +50 -0
- code/multi_vlm2vec_train/collators/tuwen_tbstars.py +78 -0
- code/multi_vlm2vec_train/collators/tuwen_tbstars_eval.py +120 -0
- code/multi_vlm2vec_train/command.sh +17 -0
- code/multi_vlm2vec_train/cot_eval/__init__.py +0 -0
- code/multi_vlm2vec_train/cot_eval/__pycache__/__init__.cpython-313.pyc +0 -0
- code/multi_vlm2vec_train/cot_eval/__pycache__/collator_tuwen_qwen3vl_cot_eval.cpython-313.pyc +0 -0
- code/multi_vlm2vec_train/cot_eval/__pycache__/datasets_tuwen_qwen3vl_cot_eval.cpython-313.pyc +0 -0
- code/multi_vlm2vec_train/cot_eval/__pycache__/eval_config.cpython-313.pyc +0 -0
- code/multi_vlm2vec_train/cot_eval/__pycache__/eval_local.cpython-313.pyc +0 -0
- code/multi_vlm2vec_train/cot_eval/__pycache__/eval_tuwen_qwen3vl_cot.cpython-313.pyc +0 -0
- code/multi_vlm2vec_train/cot_eval/collator_tuwen_qwen3vl_cot_eval.py +72 -0
- code/multi_vlm2vec_train/cot_eval/datasets_tuwen_qwen3vl_cot_eval.py +239 -0
- code/multi_vlm2vec_train/cot_eval/eval_config.py +69 -0
- code/multi_vlm2vec_train/cot_eval/eval_local.py +27 -0
- code/multi_vlm2vec_train/cot_eval/eval_tuwen_qwen3vl_cot.py +424 -0
- code/multi_vlm2vec_train/cot_eval/scripts/eval_local_qwen_cot.sh +61 -0
- code/multi_vlm2vec_train/cot_eval/scripts/eval_nebula_qwen_cot.sh +113 -0
- code/multi_vlm2vec_train/cot_gen/README.md +83 -0
- code/multi_vlm2vec_train/cot_gen/__pycache__/config.cpython-310.pyc +0 -0
- code/multi_vlm2vec_train/cot_gen/__pycache__/config.cpython-313.pyc +0 -0
- code/multi_vlm2vec_train/cot_gen/config.py +49 -0
- code/multi_vlm2vec_train/cot_gen/generate_cot.py +368 -0
- code/multi_vlm2vec_train/cot_gen/merge_shards.py +90 -0
- code/multi_vlm2vec_train/cot_gen/retry_failed.py +126 -0
- code/multi_vlm2vec_train/cot_gen/run_nebula.sh +38 -0
- code/multi_vlm2vec_train/cot_gen/validate_cot.py +83 -0
.DS_Store
ADDED
|
Binary file (10.2 kB). View file
|
|
|
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
code/multi_vlm2vec_train/Miniconda3-latest-Linux-x86_64.sh filter=lfs diff=lfs merge=lfs -text
|
code/.DS_Store
ADDED
|
Binary file (10.2 kB). View file
|
|
|
code/multi_vlm2vec_train/.DS_Store
ADDED
|
Binary file (10.2 kB). View file
|
|
|
code/multi_vlm2vec_train/.gitignore
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Byte-compiled / optimized / DLL files
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*$py.class
|
| 5 |
+
|
| 6 |
+
# C extensions
|
| 7 |
+
*.so
|
| 8 |
+
|
| 9 |
+
# Distribution / packaging
|
| 10 |
+
.Python
|
| 11 |
+
build/
|
| 12 |
+
develop-eggs/
|
| 13 |
+
dist/
|
| 14 |
+
downloads/
|
| 15 |
+
eggs/
|
| 16 |
+
.eggs/
|
| 17 |
+
lib/
|
| 18 |
+
lib64/
|
| 19 |
+
parts/
|
| 20 |
+
sdist/
|
| 21 |
+
var/
|
| 22 |
+
wheels/
|
| 23 |
+
share/python-wheels/
|
| 24 |
+
*.egg-info/
|
| 25 |
+
.installed.cfg
|
| 26 |
+
*.egg
|
| 27 |
+
MANIFEST
|
| 28 |
+
|
| 29 |
+
# PyInstaller
|
| 30 |
+
# Usually these files are written by a python script from a template
|
| 31 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
| 32 |
+
*.manifest
|
| 33 |
+
*.spec
|
| 34 |
+
|
| 35 |
+
# Installer logs
|
| 36 |
+
pip-log.txt
|
| 37 |
+
pip-delete-this-directory.txt
|
| 38 |
+
|
| 39 |
+
# Unit test / coverage reports
|
| 40 |
+
htmlcov/
|
| 41 |
+
.tox/
|
| 42 |
+
.nox/
|
| 43 |
+
.coverage
|
| 44 |
+
.coverage.*
|
| 45 |
+
.cache
|
| 46 |
+
nosetests.xml
|
| 47 |
+
coverage.xml
|
| 48 |
+
*.cover
|
| 49 |
+
*.py,cover
|
| 50 |
+
.hypothesis/
|
| 51 |
+
.pytest_cache/
|
| 52 |
+
cover/
|
| 53 |
+
|
| 54 |
+
# Translations
|
| 55 |
+
*.mo
|
| 56 |
+
*.pot
|
| 57 |
+
|
| 58 |
+
# Django stuff:
|
| 59 |
+
*.log
|
| 60 |
+
local_settings.py
|
| 61 |
+
db.sqlite3
|
| 62 |
+
db.sqlite3-journal
|
| 63 |
+
|
| 64 |
+
# Flask stuff:
|
| 65 |
+
instance/
|
| 66 |
+
.webassets-cache
|
| 67 |
+
|
| 68 |
+
# Scrapy stuff:
|
| 69 |
+
.scrapy
|
| 70 |
+
|
| 71 |
+
# Sphinx documentation
|
| 72 |
+
docs/_build/
|
| 73 |
+
|
| 74 |
+
# PyBuilder
|
| 75 |
+
.pybuilder/
|
| 76 |
+
target/
|
| 77 |
+
|
| 78 |
+
# Jupyter Notebook
|
| 79 |
+
.ipynb_checkpoints
|
| 80 |
+
|
| 81 |
+
# IPython
|
| 82 |
+
profile_default/
|
| 83 |
+
ipython_config.py
|
| 84 |
+
|
| 85 |
+
# pyenv
|
| 86 |
+
# For a library or package, you might want to ignore these files since the code is
|
| 87 |
+
# intended to run in multiple environments; otherwise, check them in:
|
| 88 |
+
# .python-version
|
| 89 |
+
|
| 90 |
+
# pipenv
|
| 91 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
| 92 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
| 93 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
| 94 |
+
# install all needed dependencies.
|
| 95 |
+
#Pipfile.lock
|
| 96 |
+
|
| 97 |
+
# UV
|
| 98 |
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
| 99 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
| 100 |
+
# commonly ignored for libraries.
|
| 101 |
+
#uv.lock
|
| 102 |
+
|
| 103 |
+
# poetry
|
| 104 |
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
| 105 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
| 106 |
+
# commonly ignored for libraries.
|
| 107 |
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
| 108 |
+
#poetry.lock
|
| 109 |
+
|
| 110 |
+
# pdm
|
| 111 |
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
| 112 |
+
#pdm.lock
|
| 113 |
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
| 114 |
+
# in version control.
|
| 115 |
+
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
| 116 |
+
.pdm.toml
|
| 117 |
+
.pdm-python
|
| 118 |
+
.pdm-build/
|
| 119 |
+
|
| 120 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
| 121 |
+
__pypackages__/
|
| 122 |
+
|
| 123 |
+
# Celery stuff
|
| 124 |
+
celerybeat-schedule
|
| 125 |
+
celerybeat.pid
|
| 126 |
+
|
| 127 |
+
# SageMath parsed files
|
| 128 |
+
*.sage.py
|
| 129 |
+
|
| 130 |
+
# Environments
|
| 131 |
+
.env
|
| 132 |
+
.venv
|
| 133 |
+
env/
|
| 134 |
+
venv/
|
| 135 |
+
ENV/
|
| 136 |
+
env.bak/
|
| 137 |
+
venv.bak/
|
| 138 |
+
|
| 139 |
+
# Spyder project settings
|
| 140 |
+
.spyderproject
|
| 141 |
+
.spyproject
|
| 142 |
+
|
| 143 |
+
# Rope project settings
|
| 144 |
+
.ropeproject
|
| 145 |
+
|
| 146 |
+
# mkdocs documentation
|
| 147 |
+
/site
|
| 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 |
+
# Ruff stuff:
|
| 171 |
+
.ruff_cache/
|
| 172 |
+
|
| 173 |
+
# PyPI configuration file
|
| 174 |
+
.pypirc
|
| 175 |
+
|
| 176 |
+
# Cursor
|
| 177 |
+
# Cursor is an AI-powered code editor.`.cursorignore` specifies files/directories to
|
| 178 |
+
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
| 179 |
+
# refer to https://docs.cursor.com/context/ignore-files
|
| 180 |
+
.cursorignore
|
| 181 |
+
.cursorindexingignore
|
| 182 |
+
|
| 183 |
+
## my ignore files
|
| 184 |
+
.vscode/
|
| 185 |
+
LamRA_Ret_eval_results/
|
| 186 |
+
outputs/
|
| 187 |
+
checkpoints/
|
| 188 |
+
*.pth
|
| 189 |
+
saved_checkpoints/
|
| 190 |
+
*.pyc
|
| 191 |
+
hf_upload_checkpoints/
|
| 192 |
+
zeroshot_rerank_files/
|
| 193 |
+
zeroshot_retrieval_eval_results/
|
| 194 |
+
LamRA_Ret_eval_results/
|
| 195 |
+
checkpoints/
|
| 196 |
+
rerank_training_data/
|
| 197 |
+
mbeir_rerank_files/
|
| 198 |
+
utils_data/core-pt*
|
| 199 |
+
core-pt_main_thread*
|
| 200 |
+
core-python*
|
| 201 |
+
*.excp
|
| 202 |
+
*.jpg
|
| 203 |
+
*.png
|
| 204 |
+
*.jpeg
|
| 205 |
+
logs/
|
| 206 |
+
xdg_cache/
|
code/multi_vlm2vec_train/Miniconda3-latest-Linux-x86_64.sh
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:80bc27f13c4de90f10e387aa45e864de4f0860692c1221aef5900009a2b55302
|
| 3 |
+
size 197272282
|
code/multi_vlm2vec_train/__pycache__/logger.cpython-310.pyc
ADDED
|
Binary file (1.75 kB). View file
|
|
|
code/multi_vlm2vec_train/__pycache__/logger.cpython-313.pyc
ADDED
|
Binary file (2.65 kB). View file
|
|
|
code/multi_vlm2vec_train/bianji_test_10.json
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"rn": "40100",
|
| 4 |
+
"query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg",
|
| 5 |
+
"query_bbox": "0 87 279 640",
|
| 6 |
+
"query_text": "想要个钻石形设计的",
|
| 7 |
+
"item_id": "",
|
| 8 |
+
"item_tfsid": "O1CN012QaWsZ29XK3pGfr3b_!!2311728077.jpg",
|
| 9 |
+
"item_key": "",
|
| 10 |
+
"item_title": "定制铝合金大门新款双开门自建房家用入户门别墅农村进户",
|
| 11 |
+
"item_bbox": "83 9 963 1005",
|
| 12 |
+
"ctr_v1cnn": "",
|
| 13 |
+
"ctr_v2cnn": "",
|
| 14 |
+
"label": "0"
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
"rn": "40100",
|
| 18 |
+
"query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg",
|
| 19 |
+
"query_bbox": "0 87 279 640",
|
| 20 |
+
"query_text": "想要个钻石形设计的",
|
| 21 |
+
"item_id": "",
|
| 22 |
+
"item_tfsid": "O1CN01E9hQnH2ALF9iffOHg_!!6000000008186-0-tmap.jpg",
|
| 23 |
+
"item_key": "",
|
| 24 |
+
"item_title": "新款农村防盗门岩棉填充平房室外门仿铜门农村户玻璃门防寒门",
|
| 25 |
+
"item_bbox": "267 7 1604 2867",
|
| 26 |
+
"ctr_v1cnn": "",
|
| 27 |
+
"ctr_v2cnn": "",
|
| 28 |
+
"label": "1"
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"rn": "40100",
|
| 32 |
+
"query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg",
|
| 33 |
+
"query_bbox": "0 87 279 640",
|
| 34 |
+
"query_text": "想要个钻石形设计的",
|
| 35 |
+
"item_id": "",
|
| 36 |
+
"item_tfsid": "O1CN01t6HHaN1IfPRHMgfKr_!!4611686018427381704-0-item_pic.jpg",
|
| 37 |
+
"item_key": "",
|
| 38 |
+
"item_title": "风冷单缸柴油机抽水泵切割微耕机头5 6 9 10 12 16马力发动机",
|
| 39 |
+
"item_bbox": "286 152 764 694",
|
| 40 |
+
"ctr_v1cnn": "",
|
| 41 |
+
"ctr_v2cnn": "",
|
| 42 |
+
"label": "1"
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"rn": "40100",
|
| 46 |
+
"query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg",
|
| 47 |
+
"query_bbox": "0 87 279 640",
|
| 48 |
+
"query_text": "想要个钻石形设计的",
|
| 49 |
+
"item_id": "",
|
| 50 |
+
"item_tfsid": "O1CN01UjoxjE1WqlYIElGF7_!!0-fleamarket.jpg",
|
| 51 |
+
"item_key": "",
|
| 52 |
+
"item_title": "阳台不锈钢需要私聊",
|
| 53 |
+
"item_bbox": "135 194 918 1432",
|
| 54 |
+
"ctr_v1cnn": "",
|
| 55 |
+
"ctr_v2cnn": "",
|
| 56 |
+
"label": "1"
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"rn": "40100",
|
| 60 |
+
"query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg",
|
| 61 |
+
"query_bbox": "0 87 279 640",
|
| 62 |
+
"query_text": "想要个钻石形设计的",
|
| 63 |
+
"item_id": "",
|
| 64 |
+
"item_tfsid": "O1CN011dLYQc1ImH0khViCh_!!1749420935-0-tbvideo.jpg",
|
| 65 |
+
"item_key": "",
|
| 66 |
+
"item_title": "新款桃木双面雕刻千手观音菩萨汽车挂件车内挂饰高档摆件内饰用品",
|
| 67 |
+
"item_bbox": "0 1 720 748",
|
| 68 |
+
"ctr_v1cnn": "",
|
| 69 |
+
"ctr_v2cnn": "",
|
| 70 |
+
"label": "1"
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"rn": "40100",
|
| 74 |
+
"query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg",
|
| 75 |
+
"query_bbox": "0 87 279 640",
|
| 76 |
+
"query_text": "想要个钻石形设计的",
|
| 77 |
+
"item_id": "",
|
| 78 |
+
"item_tfsid": "O1CN018JLFGe1PTEDZzdzH6_!!2216807051841.jpg",
|
| 79 |
+
"item_key": "",
|
| 80 |
+
"item_title": "加厚全铝门断桥铝气窗门防盗门玻璃平房铝合金门保温户外防寒门",
|
| 81 |
+
"item_bbox": "273 29 535 714",
|
| 82 |
+
"ctr_v1cnn": "",
|
| 83 |
+
"ctr_v2cnn": "",
|
| 84 |
+
"label": "1"
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"rn": "40100",
|
| 88 |
+
"query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg",
|
| 89 |
+
"query_bbox": "0 87 279 640",
|
| 90 |
+
"query_text": "想要个钻石形设计的",
|
| 91 |
+
"item_id": "",
|
| 92 |
+
"item_tfsid": "O1CN018HmONW2Ke9kIXMU7u_!!3330569581.jpg",
|
| 93 |
+
"item_key": "",
|
| 94 |
+
"item_title": "2025年春季新款模特走秀恨天高单鞋时尚细跟防水台舞台演出高跟鞋",
|
| 95 |
+
"item_bbox": "0 855 865 1422",
|
| 96 |
+
"ctr_v1cnn": "",
|
| 97 |
+
"ctr_v2cnn": "",
|
| 98 |
+
"label": "1"
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"rn": "40100",
|
| 102 |
+
"query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg",
|
| 103 |
+
"query_bbox": "0 87 279 640",
|
| 104 |
+
"query_text": "想要个钻石形设计的",
|
| 105 |
+
"item_id": "",
|
| 106 |
+
"item_tfsid": "O1CN01XC3ze91FQLY5ImKeK_!!4611686018427387569-0-item_pic.jpg",
|
| 107 |
+
"item_key": "",
|
| 108 |
+
"item_title": "豪华全套中式304不锈钢单门带亮窗庭院进户门防盗防晒防锈双开门",
|
| 109 |
+
"item_bbox": "97 39 685 1077",
|
| 110 |
+
"ctr_v1cnn": "",
|
| 111 |
+
"ctr_v2cnn": "",
|
| 112 |
+
"label": "1"
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"rn": "40100",
|
| 116 |
+
"query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg",
|
| 117 |
+
"query_bbox": "0 87 279 640",
|
| 118 |
+
"query_text": "想要个钻石形设计的",
|
| 119 |
+
"item_id": "",
|
| 120 |
+
"item_tfsid": "O1CN010JeOoe2BCpV18PV6q_!!2212749898303.jpg",
|
| 121 |
+
"item_key": "",
|
| 122 |
+
"item_title": "拿铁女孩自制微透健身瑜伽防晒罩衫性感透气运动长袖瑜伽速干T恤",
|
| 123 |
+
"item_bbox": "96 93 566 748",
|
| 124 |
+
"ctr_v1cnn": "",
|
| 125 |
+
"ctr_v2cnn": "",
|
| 126 |
+
"label": "1"
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"rn": "40100",
|
| 130 |
+
"query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg",
|
| 131 |
+
"query_bbox": "0 87 279 640",
|
| 132 |
+
"query_text": "想要个钻石形设计的",
|
| 133 |
+
"item_id": "",
|
| 134 |
+
"item_tfsid": "O1CN01sMjDOh1WfJvoOMOzB_!!2215334882815.jpg",
|
| 135 |
+
"item_key": "",
|
| 136 |
+
"item_title": "楼宇单元门钢制单元门玻璃单元门防盗门进户门可对视楼宇门对讲门",
|
| 137 |
+
"item_bbox": "77 137 377 799",
|
| 138 |
+
"ctr_v1cnn": "",
|
| 139 |
+
"ctr_v2cnn": "",
|
| 140 |
+
"label": "1"
|
| 141 |
+
}
|
| 142 |
+
]
|
code/multi_vlm2vec_train/bianji_test_200.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
code/multi_vlm2vec_train/case.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
with open('/data/oss_bucket_0/liqi/dataset/embedding_pf/bianji_train.json',"r", encoding="utf-8") as f:
|
| 3 |
+
data = json.load(f)
|
| 4 |
+
number_1 = 0
|
| 5 |
+
number_0 = 0
|
| 6 |
+
print(data[0].keys())
|
| 7 |
+
print(data[0])
|
| 8 |
+
print(data[1])
|
| 9 |
+
print(data[2])
|
| 10 |
+
number = 0
|
| 11 |
+
# for i in data:
|
| 12 |
+
# if i['label'] == '0':
|
| 13 |
+
# number += 1
|
| 14 |
+
# print(i)
|
| 15 |
+
# break
|
| 16 |
+
# if i['rn'] == '037a6b4e192533b2e0dc9ab3fb692806':
|
| 17 |
+
# number += 1
|
| 18 |
+
# if i['label'] == '0':
|
| 19 |
+
# number_0 += 1
|
| 20 |
+
# print(i)
|
| 21 |
+
# if i['label'] == '1':
|
| 22 |
+
# number_1 += 1
|
| 23 |
+
|
| 24 |
+
print(number_0)
|
| 25 |
+
print(number_1)
|
| 26 |
+
print(number)
|
code/multi_vlm2vec_train/collators/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
COLLATORS = {}
|
| 2 |
+
|
| 3 |
+
def register_collator(name):
|
| 4 |
+
def register_collator_cls(cls):
|
| 5 |
+
if name in COLLATORS:
|
| 6 |
+
return COLLATORS[name]
|
| 7 |
+
COLLATORS[name] = cls
|
| 8 |
+
return cls
|
| 9 |
+
return register_collator_cls
|
| 10 |
+
|
| 11 |
+
from .tuwen_tbstars import TuwenTBStarsInfonceDataCollator
|
code/multi_vlm2vec_train/collators/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (560 Bytes). View file
|
|
|
code/multi_vlm2vec_train/collators/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (660 Bytes). View file
|
|
|
code/multi_vlm2vec_train/collators/__pycache__/base.cpython-310.pyc
ADDED
|
Binary file (1.48 kB). View file
|
|
|
code/multi_vlm2vec_train/collators/__pycache__/base.cpython-313.pyc
ADDED
|
Binary file (1.85 kB). View file
|
|
|
code/multi_vlm2vec_train/collators/__pycache__/tuwen_qwen3vl.cpython-313.pyc
ADDED
|
Binary file (2.44 kB). View file
|
|
|
code/multi_vlm2vec_train/collators/__pycache__/tuwen_qwen3vl_eval.cpython-310.pyc
ADDED
|
Binary file (1.77 kB). View file
|
|
|
code/multi_vlm2vec_train/collators/__pycache__/tuwen_qwen3vl_eval.cpython-313.pyc
ADDED
|
Binary file (2.63 kB). View file
|
|
|
code/multi_vlm2vec_train/collators/__pycache__/tuwen_tbstars.cpython-310.pyc
ADDED
|
Binary file (3.37 kB). View file
|
|
|
code/multi_vlm2vec_train/collators/__pycache__/tuwen_tbstars.cpython-313.pyc
ADDED
|
Binary file (4.51 kB). View file
|
|
|
code/multi_vlm2vec_train/collators/base.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC, abstractmethod
|
| 2 |
+
from typing import Dict, Sequence, Optional
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from transformers import PreTrainedTokenizer, AutoProcessor
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class BaseDataCollator(ABC, object):
|
| 9 |
+
"""Collate examples for supervised fine-tuning."""
|
| 10 |
+
def __init__(
|
| 11 |
+
self,
|
| 12 |
+
tokenizer: Optional[PreTrainedTokenizer] = None,
|
| 13 |
+
processor: Optional[AutoProcessor] = None,
|
| 14 |
+
mask_question_tokens: bool = True
|
| 15 |
+
) -> None:
|
| 16 |
+
self.tokenizer = tokenizer
|
| 17 |
+
self.processor = processor
|
| 18 |
+
self.mask_question_tokens = mask_question_tokens
|
| 19 |
+
|
| 20 |
+
@property
|
| 21 |
+
def IGNORE_TOKEN_ID(self) -> int:
|
| 22 |
+
return -100
|
| 23 |
+
|
| 24 |
+
@property
|
| 25 |
+
def PAD_TOKEN_ID(self) -> int:
|
| 26 |
+
return self.tokenizer.pad_token_id
|
| 27 |
+
|
| 28 |
+
@abstractmethod
|
| 29 |
+
def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]: ...
|
code/multi_vlm2vec_train/collators/tuwen_qwen3vl.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## TBStars collator
|
| 2 |
+
import torch
|
| 3 |
+
from typing import Dict, List, Sequence, Tuple
|
| 4 |
+
from .base import BaseDataCollator
|
| 5 |
+
from qwen_vl_utils.vision_process import process_vision_info
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TuwenQwenInfonceDataCollator(BaseDataCollator):
|
| 9 |
+
def __init__(self, processor, max_length: int = 8192):
|
| 10 |
+
self.processor = processor
|
| 11 |
+
self.max_length = max_length
|
| 12 |
+
|
| 13 |
+
def __call__(self, messages: Sequence[Dict]) -> Dict[str, torch.Tensor]:
|
| 14 |
+
query_messages = [message[0] for message in messages]
|
| 15 |
+
positive_messages = [message[1] for message in messages]
|
| 16 |
+
negative_messages = [message[2] for message in messages]
|
| 17 |
+
|
| 18 |
+
## 处理batch_messages
|
| 19 |
+
query_inputs = self.messages_process(query_messages)
|
| 20 |
+
positive_inputs = self.messages_process(positive_messages)
|
| 21 |
+
negative_inputs = self.messages_process(negative_messages)
|
| 22 |
+
|
| 23 |
+
batch_query_dict = dict(
|
| 24 |
+
query_inputs=query_inputs,
|
| 25 |
+
positive_inputs=positive_inputs,
|
| 26 |
+
negative_inputs=negative_inputs,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
return batch_query_dict
|
| 30 |
+
|
| 31 |
+
def messages_process(self, query_messages):
|
| 32 |
+
query_texts = self.processor.apply_chat_template(
|
| 33 |
+
query_messages, add_generation_prompt=True, tokenize=False
|
| 34 |
+
)
|
| 35 |
+
query_images, _ = process_vision_info(query_messages, image_patch_size=16)
|
| 36 |
+
query_videos, query_video_metadata = None, None
|
| 37 |
+
query_inputs = self.processor(
|
| 38 |
+
text=query_texts, images=query_images, videos=query_videos, video_metadata=query_video_metadata, truncation=True,
|
| 39 |
+
max_length=self.max_length, padding=True, do_resize=False, return_tensors='pt'
|
| 40 |
+
)
|
| 41 |
+
return query_inputs
|
| 42 |
+
|
code/multi_vlm2vec_train/collators/tuwen_qwen3vl_eval.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Sequence, Tuple
|
| 2 |
+
import torch
|
| 3 |
+
from .base import BaseDataCollator
|
| 4 |
+
from qwen_vl_utils.vision_process import process_vision_info
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TuwenQwenDataCollator(BaseDataCollator):
|
| 8 |
+
@property
|
| 9 |
+
def PAD_TOKEN_ID(self) -> int:
|
| 10 |
+
return self.tokenizer.pad_token_id
|
| 11 |
+
|
| 12 |
+
def __call__(self, messages: Sequence[Dict]) -> Tuple[Dict[str, torch.Tensor], Dict[str, torch.Tensor], List[str], List[int]]:
|
| 13 |
+
### 输入的是一个list,为batch大小
|
| 14 |
+
### query_tfs, query_message, doc_message
|
| 15 |
+
### 首先处理一下query_message
|
| 16 |
+
new_query_messages = []
|
| 17 |
+
new_doc_messages = []
|
| 18 |
+
qids = []
|
| 19 |
+
labels = []
|
| 20 |
+
itemids = []
|
| 21 |
+
for item in messages:
|
| 22 |
+
new_query_messages.append(item[1])
|
| 23 |
+
new_doc_messages.append(item[2])
|
| 24 |
+
qids.append(item[0])
|
| 25 |
+
labels.append(item[3])
|
| 26 |
+
itemids.append(item[4])
|
| 27 |
+
|
| 28 |
+
## query message处理
|
| 29 |
+
query_texts = self.processor.apply_chat_template(
|
| 30 |
+
new_query_messages, add_generation_prompt=True, tokenize=False
|
| 31 |
+
)
|
| 32 |
+
query_images, _ = process_vision_info(new_query_messages, image_patch_size=16)
|
| 33 |
+
query_videos, query_video_metadata = None, None
|
| 34 |
+
query_inputs = self.processor(
|
| 35 |
+
text=query_texts, images=query_images, videos=query_videos, video_metadata=query_video_metadata, truncation=True,
|
| 36 |
+
max_length=2048, padding=True, do_resize=False, return_tensors='pt'
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
## doc message 处理
|
| 40 |
+
doc_texts = self.processor.apply_chat_template(
|
| 41 |
+
new_doc_messages, add_generation_prompt=True, tokenize=False
|
| 42 |
+
)
|
| 43 |
+
doc_images, _ = process_vision_info(new_doc_messages, image_patch_size=16)
|
| 44 |
+
doc_videos, doc_video_metadata = None, None
|
| 45 |
+
doc_inputs = self.processor(
|
| 46 |
+
text=doc_texts, images=doc_images, videos=doc_videos, video_metadata=doc_video_metadata, truncation=True,
|
| 47 |
+
max_length=2048, padding=True, do_resize=False, return_tensors='pt'
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
return query_inputs, doc_inputs, qids, labels, itemids
|
code/multi_vlm2vec_train/collators/tuwen_tbstars.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## TBStars collator
|
| 2 |
+
import torch
|
| 3 |
+
import random
|
| 4 |
+
from .base import BaseDataCollator
|
| 5 |
+
from . import register_collator
|
| 6 |
+
from typing import Dict, Sequence, Optional
|
| 7 |
+
|
| 8 |
+
from models.tbstars_ecom_emb.src.data.template_guijiang import Template
|
| 9 |
+
|
| 10 |
+
@register_collator("tuwen_tbstars_infonce")
|
| 11 |
+
class TuwenTBStarsInfonceDataCollator(BaseDataCollator):
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
tokenizer = None,
|
| 15 |
+
processor = None,
|
| 16 |
+
mask_question_tokens = True,
|
| 17 |
+
template = None,
|
| 18 |
+
image_type = None,
|
| 19 |
+
text_require = True
|
| 20 |
+
) -> None:
|
| 21 |
+
super().__init__(tokenizer,processor,mask_question_tokens)
|
| 22 |
+
if not template:
|
| 23 |
+
self.template = Template(processor, cutoff_len=256)
|
| 24 |
+
else:
|
| 25 |
+
self.template = template
|
| 26 |
+
self.image_type = image_type
|
| 27 |
+
self.text_require = text_require
|
| 28 |
+
@property
|
| 29 |
+
def PAD_TOKEN_ID(self) -> int:
|
| 30 |
+
return self.tokenizer.pad_token_id
|
| 31 |
+
|
| 32 |
+
def __call__(self, messages: Sequence[Dict]) -> Dict[str, torch.Tensor]:
|
| 33 |
+
query_messages = [message[0] for message in messages]
|
| 34 |
+
positive_messages = [message[1] for message in messages]
|
| 35 |
+
negative_messages = [message[2] for message in messages]
|
| 36 |
+
|
| 37 |
+
batch_messages = query_messages + positive_messages + negative_messages
|
| 38 |
+
## 处理batch_messages
|
| 39 |
+
batch_query_dict = self.messages_process(batch_messages)
|
| 40 |
+
|
| 41 |
+
return batch_query_dict
|
| 42 |
+
|
| 43 |
+
def messages_process(self, query_messages):
|
| 44 |
+
## 处理query_messages
|
| 45 |
+
query_features = [
|
| 46 |
+
self.template.prepare_inputs_train(msg, image_type = self.image_type, text_require=self.text_require)
|
| 47 |
+
for msg in query_messages
|
| 48 |
+
]
|
| 49 |
+
## pixel_values, crop_positions, input_ids
|
| 50 |
+
query_input_ids = [fea["input_ids"] for fea in query_features]
|
| 51 |
+
query_input_ids_max_len = max([t.shape[-1] for t in query_input_ids])
|
| 52 |
+
pad_query_input_ids = [torch.cat([t, torch.full((1, query_input_ids_max_len-t.shape[-1]), self.tokenizer.pad_token_id, dtype=torch.long)], dim=-1) for t in query_input_ids]
|
| 53 |
+
query_input_ids = torch.cat(pad_query_input_ids, dim=0)
|
| 54 |
+
query_attention_mask = (query_input_ids != self.tokenizer.pad_token_id).to(torch.long)
|
| 55 |
+
query_pixel_values = []
|
| 56 |
+
query_crop_positions = []
|
| 57 |
+
for fea in query_features:
|
| 58 |
+
if "pixel_values" in fea.keys():
|
| 59 |
+
query_pixel_values.append(fea["pixel_values"])
|
| 60 |
+
if "crop_positions" in fea.keys():
|
| 61 |
+
query_crop_positions.append(fea["crop_positions"])
|
| 62 |
+
if len(query_pixel_values) >= 1:
|
| 63 |
+
query_pixel_values = torch.cat(query_pixel_values, dim=0)
|
| 64 |
+
else:
|
| 65 |
+
query_pixel_values = None
|
| 66 |
+
if len(query_crop_positions) >=1:
|
| 67 |
+
query_crop_positions = torch.cat(query_crop_positions, dim=0)
|
| 68 |
+
else:
|
| 69 |
+
query_crop_positions = None
|
| 70 |
+
|
| 71 |
+
batch_query_dict = dict(
|
| 72 |
+
input_ids=query_input_ids,
|
| 73 |
+
attention_mask=query_attention_mask,
|
| 74 |
+
pixel_values=query_pixel_values,
|
| 75 |
+
crop_positions=query_crop_positions,
|
| 76 |
+
)
|
| 77 |
+
return batch_query_dict
|
| 78 |
+
|
code/multi_vlm2vec_train/collators/tuwen_tbstars_eval.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, Sequence
|
| 2 |
+
import torch
|
| 3 |
+
from .base import BaseDataCollator
|
| 4 |
+
from typing import Dict, Sequence, Optional
|
| 5 |
+
|
| 6 |
+
from models.tbstars_ecom_emb.src.data.template_guijiang import Template
|
| 7 |
+
|
| 8 |
+
class TuwenTBStarsDataCollator(BaseDataCollator):
|
| 9 |
+
def __init__(
|
| 10 |
+
self,
|
| 11 |
+
tokenizer = None,
|
| 12 |
+
processor = None,
|
| 13 |
+
mask_question_tokens = True,
|
| 14 |
+
template = None,
|
| 15 |
+
image_type = None,
|
| 16 |
+
query_text_require = True,
|
| 17 |
+
doc_text_require = True
|
| 18 |
+
) -> None:
|
| 19 |
+
super().__init__(tokenizer,processor,mask_question_tokens)
|
| 20 |
+
if not template:
|
| 21 |
+
self.template = Template(processor, cutoff_len=256)
|
| 22 |
+
else:
|
| 23 |
+
self.template = template
|
| 24 |
+
self.image_type = image_type
|
| 25 |
+
self.query_text_require = query_text_require
|
| 26 |
+
self.doc_text_require = doc_text_require
|
| 27 |
+
@property
|
| 28 |
+
def PAD_TOKEN_ID(self) -> int:
|
| 29 |
+
return self.tokenizer.pad_token_id
|
| 30 |
+
|
| 31 |
+
def __call__(self, messages: Sequence[Dict]) -> Dict[str, torch.Tensor]:
|
| 32 |
+
### 输入的是一个list,为batch大小
|
| 33 |
+
### query_tfs, query_message, doc_message
|
| 34 |
+
### 首先处理一下query_message
|
| 35 |
+
|
| 36 |
+
'''
|
| 37 |
+
目标输入格式:
|
| 38 |
+
template = "<|im_start|>system\nA conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers. <|im_end|>\n<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n<|im_end|>"
|
| 39 |
+
prompt = "<image>\n魔力彩虹圈塔弹簧圈发光专业弹力圈婴儿童女宝宝益智玩具早教男孩 玉延玩具店 叠叠圈/叠套玩具 福莱萌(母婴) mcs1048 3岁 塑料 中国大陆 男女通用 塑胶玩具 mcs1048"
|
| 40 |
+
prompts = [prompt, prompt]
|
| 41 |
+
|
| 42 |
+
image_paths = ["demo.jpg", "demo.jpg"]
|
| 43 |
+
image_placeholder = "<PLACEHOLDER_33>"
|
| 44 |
+
image_features, image_lens = process_image(image_paths, processor)
|
| 45 |
+
image_features = {f"item_{k}": v for k, v in image_features.items()}
|
| 46 |
+
|
| 47 |
+
prompts = [prompt.replace("<image>", f"<image>{image_placeholder * image_len}</image>") for prompt, image_len in zip(prompts, image_lens)]
|
| 48 |
+
prompts = [template.format(prompt=prompt) for prompt in prompts]
|
| 49 |
+
features = tokenizer(prompts, add_special_tokens=False, return_tensors="pt")
|
| 50 |
+
features = features.to("cuda")
|
| 51 |
+
|
| 52 |
+
inputs = {
|
| 53 |
+
"item_input_ids": features["input_ids"],
|
| 54 |
+
"item_attention_mask": features["attention_mask"],
|
| 55 |
+
**image_features,
|
| 56 |
+
}
|
| 57 |
+
'''
|
| 58 |
+
|
| 59 |
+
new_query_messages = []
|
| 60 |
+
new_doc_messages = []
|
| 61 |
+
qids = []
|
| 62 |
+
labels = []
|
| 63 |
+
itemids = []
|
| 64 |
+
for item in messages:
|
| 65 |
+
new_query_messages.append(item[1])
|
| 66 |
+
new_doc_messages.append(item[2])
|
| 67 |
+
qids.append(item[0])
|
| 68 |
+
labels.append(item[3])
|
| 69 |
+
itemids.append(item[4])
|
| 70 |
+
|
| 71 |
+
query_features = [
|
| 72 |
+
self.template.prepare_inputs(msg, image_type = self.image_type, text_require=self.query_text_require)
|
| 73 |
+
for msg in new_query_messages
|
| 74 |
+
]
|
| 75 |
+
|
| 76 |
+
## pixel_values, crop_positions, input_ids
|
| 77 |
+
query_input_ids = [fea["input_ids"] for fea in query_features]
|
| 78 |
+
query_input_ids_max_len = max([t.shape[-1] for t in query_input_ids])
|
| 79 |
+
pad_query_input_ids = [torch.cat([t, torch.full((1, query_input_ids_max_len-t.shape[-1]), self.tokenizer.pad_token_id, dtype=torch.long)], dim=-1) for t in query_input_ids]
|
| 80 |
+
query_input_ids = torch.cat(pad_query_input_ids, dim=0)
|
| 81 |
+
query_attention_mask = (query_input_ids != self.tokenizer.pad_token_id).to(torch.long)
|
| 82 |
+
|
| 83 |
+
query_pixel_values = [fea["pixel_values"] for fea in query_features]
|
| 84 |
+
query_pixel_values = torch.cat(query_pixel_values, dim=0)
|
| 85 |
+
query_crop_positions = [fea["crop_positions"] for fea in query_features]
|
| 86 |
+
query_crop_positions = torch.cat(query_crop_positions, dim=0)
|
| 87 |
+
|
| 88 |
+
batch_query_dict = dict(
|
| 89 |
+
input_ids=query_input_ids,
|
| 90 |
+
attention_mask=query_attention_mask,
|
| 91 |
+
pixel_values=query_pixel_values,
|
| 92 |
+
crop_positions=query_crop_positions,
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
## doc message 处理
|
| 96 |
+
doc_features = [
|
| 97 |
+
self.template.prepare_inputs(msg, image_type = self.image_type, text_require=self.doc_text_require)
|
| 98 |
+
for msg in new_doc_messages
|
| 99 |
+
]
|
| 100 |
+
|
| 101 |
+
## pixel_values, crop_positions, input_ids
|
| 102 |
+
doc_input_ids = [fea["input_ids"] for fea in doc_features]
|
| 103 |
+
doc_input_ids_max_len = max([t.shape[-1] for t in doc_input_ids])
|
| 104 |
+
pad_doc_input_ids = [torch.cat([t, torch.full((1, doc_input_ids_max_len-t.shape[-1]), self.tokenizer.pad_token_id, dtype=torch.long)], dim=-1) for t in doc_input_ids]
|
| 105 |
+
doc_input_ids = torch.cat(pad_doc_input_ids, dim=0)
|
| 106 |
+
doc_attention_mask = (doc_input_ids != self.tokenizer.pad_token_id).to(torch.long)
|
| 107 |
+
|
| 108 |
+
doc_pixel_values = [fea["pixel_values"] for fea in doc_features]
|
| 109 |
+
doc_pixel_values = torch.cat(doc_pixel_values, dim=0)
|
| 110 |
+
doc_crop_positions = [fea["crop_positions"] for fea in doc_features]
|
| 111 |
+
doc_crop_positions = torch.cat(doc_crop_positions, dim=0)
|
| 112 |
+
|
| 113 |
+
batch_doc_dict = dict(
|
| 114 |
+
input_ids=doc_input_ids,
|
| 115 |
+
attention_mask=doc_attention_mask,
|
| 116 |
+
pixel_values=doc_pixel_values,
|
| 117 |
+
crop_positions=doc_crop_positions,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
return batch_query_dict, batch_doc_dict, qids, labels, itemids
|
code/multi_vlm2vec_train/command.sh
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cloudcli-runner \
|
| 2 |
+
--projects-dir /Users/yiqili \
|
| 3 |
+
--allow-path /Users/yiqili \
|
| 4 |
+
--name yiqili-nebula \
|
| 5 |
+
-v
|
| 6 |
+
|
| 7 |
+
cloudcli-ssh
|
| 8 |
+
claude-runner
|
| 9 |
+
/home/lyq494390/multi_vlm2vec_train
|
| 10 |
+
|
| 11 |
+
CUDA_VISIBLE_DEVICES=3 python eval/eval_tuwen_qwen3vl.py
|
| 12 |
+
|
| 13 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3 python cot_gen/generate_cot.py --test
|
| 14 |
+
accelerate launch --num_processes 4 cot_eval/eval_local.py
|
| 15 |
+
python -m accelerate.commands.launch --num_processes 4 cot_eval/eval_local.py
|
| 16 |
+
CUDA_VISIBLE_DEVICES=3 python cot_eval/eval_local.py
|
| 17 |
+
python -m pip install jsonlines accelerate peft qwen_vl_utils
|
code/multi_vlm2vec_train/cot_eval/__init__.py
ADDED
|
File without changes
|
code/multi_vlm2vec_train/cot_eval/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (157 Bytes). View file
|
|
|
code/multi_vlm2vec_train/cot_eval/__pycache__/collator_tuwen_qwen3vl_cot_eval.cpython-313.pyc
ADDED
|
Binary file (3.96 kB). View file
|
|
|
code/multi_vlm2vec_train/cot_eval/__pycache__/datasets_tuwen_qwen3vl_cot_eval.cpython-313.pyc
ADDED
|
Binary file (13.8 kB). View file
|
|
|
code/multi_vlm2vec_train/cot_eval/__pycache__/eval_config.cpython-313.pyc
ADDED
|
Binary file (2.55 kB). View file
|
|
|
code/multi_vlm2vec_train/cot_eval/__pycache__/eval_local.cpython-313.pyc
ADDED
|
Binary file (1.37 kB). View file
|
|
|
code/multi_vlm2vec_train/cot_eval/__pycache__/eval_tuwen_qwen3vl_cot.cpython-313.pyc
ADDED
|
Binary file (22.7 kB). View file
|
|
|
code/multi_vlm2vec_train/cot_eval/collator_tuwen_qwen3vl_cot_eval.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Sequence, Tuple
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from qwen_vl_utils.vision_process import process_vision_info
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class CoTQueryEvalCollator:
|
| 8 |
+
"""unique query 的 CoT 生成 collator。
|
| 9 |
+
|
| 10 |
+
只 tokenize 到 generation prompt(`<|im_start|>assistant\\n`),
|
| 11 |
+
左 padding,供 model.generate() 批量自回归生成 CoT 使用。
|
| 12 |
+
返回 (query_gen_inputs, q_idxs)。
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
def __init__(self, processor, max_length: int = 2048):
|
| 16 |
+
self.processor = processor
|
| 17 |
+
self.max_length = max_length
|
| 18 |
+
|
| 19 |
+
def __call__(self, instances: Sequence[Tuple]) -> Tuple[Dict[str, torch.Tensor], List[int]]:
|
| 20 |
+
q_idxs = [instance[0] for instance in instances]
|
| 21 |
+
query_messages = [instance[1] for instance in instances]
|
| 22 |
+
|
| 23 |
+
query_texts = self.processor.apply_chat_template(
|
| 24 |
+
query_messages, add_generation_prompt=True, tokenize=False
|
| 25 |
+
)
|
| 26 |
+
query_images, _ = process_vision_info(query_messages, image_patch_size=16)
|
| 27 |
+
|
| 28 |
+
# generate 需要左 padding;processor 内部使用 tokenizer.padding_side
|
| 29 |
+
self.processor.tokenizer.padding_side = "left"
|
| 30 |
+
query_inputs = self.processor(
|
| 31 |
+
text=query_texts, images=query_images, videos=None, video_metadata=None, truncation=True,
|
| 32 |
+
max_length=self.max_length, padding=True, do_resize=False, return_tensors='pt'
|
| 33 |
+
)
|
| 34 |
+
return query_inputs, q_idxs
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class CoTDocEvalCollator:
|
| 38 |
+
"""unique doc 的前向 collator,与训练时的 doc_messages_process 对齐(右 padding)。
|
| 39 |
+
|
| 40 |
+
返回 (doc_inputs, d_idxs)。
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
processor,
|
| 46 |
+
max_length: int = 2048,
|
| 47 |
+
cot_emb_suffix: str = "<|im_end|>",
|
| 48 |
+
doc_append_eos: bool = False,
|
| 49 |
+
):
|
| 50 |
+
self.processor = processor
|
| 51 |
+
self.max_length = max_length
|
| 52 |
+
self.cot_emb_suffix = cot_emb_suffix
|
| 53 |
+
self.doc_append_eos = doc_append_eos
|
| 54 |
+
|
| 55 |
+
def __call__(self, instances: Sequence[Tuple]) -> Tuple[Dict[str, torch.Tensor], List[int]]:
|
| 56 |
+
d_idxs = [instance[0] for instance in instances]
|
| 57 |
+
doc_messages = [instance[1] for instance in instances]
|
| 58 |
+
|
| 59 |
+
doc_texts = self.processor.apply_chat_template(
|
| 60 |
+
doc_messages, add_generation_prompt=True, tokenize=False
|
| 61 |
+
)
|
| 62 |
+
if self.doc_append_eos:
|
| 63 |
+
doc_texts = [text + self.cot_emb_suffix for text in doc_texts]
|
| 64 |
+
|
| 65 |
+
doc_images, _ = process_vision_info(doc_messages, image_patch_size=16)
|
| 66 |
+
|
| 67 |
+
self.processor.tokenizer.padding_side = "right"
|
| 68 |
+
doc_inputs = self.processor(
|
| 69 |
+
text=doc_texts, images=doc_images, videos=None, video_metadata=None, truncation=True,
|
| 70 |
+
max_length=self.max_length, padding=True, do_resize=False, return_tensors='pt'
|
| 71 |
+
)
|
| 72 |
+
return doc_inputs, d_idxs
|
code/multi_vlm2vec_train/cot_eval/datasets_tuwen_qwen3vl_cot_eval.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
current_file_path = os.path.dirname(os.path.abspath(__file__))
|
| 6 |
+
module_path = os.path.join(current_file_path, "../")
|
| 7 |
+
sys.path.append(module_path)
|
| 8 |
+
|
| 9 |
+
from typing import Dict, List, Tuple
|
| 10 |
+
|
| 11 |
+
from PIL import Image
|
| 12 |
+
from torch.utils.data import Dataset
|
| 13 |
+
from tqdm import tqdm
|
| 14 |
+
|
| 15 |
+
# 与训练侧共用 system prompt,保证 train/inference 输入分布一致
|
| 16 |
+
from train_cot.datasets_tuwen_qwen3vl_cot import COT_SYSTEM_PROMPTS, DOC_SYSTEM_PROMPT
|
| 17 |
+
|
| 18 |
+
# 测试集图片在 OSS 上的前缀(与 eval/eval_tuwen_qwen3vl.py 使用的数据集一致)
|
| 19 |
+
OSS_TEST_IMAGE_PREFIX = "peifeng/multi_vlm2vec/dataset/merge/test_image"
|
| 20 |
+
|
| 21 |
+
_OSS_BUCKET = None
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def get_oss_bucket():
|
| 25 |
+
"""懒加载 OSS bucket:本地跑(image_path_prefix 命中)时完全不需要 oss2 依赖。"""
|
| 26 |
+
global _OSS_BUCKET
|
| 27 |
+
if _OSS_BUCKET is None:
|
| 28 |
+
# 与 baseline 评测共用同一个 bucket 配置,保证读到完全相同的测试图片
|
| 29 |
+
from dataset.datasets_tuwen_qwen3vl import load_oss_bucket
|
| 30 |
+
_OSS_BUCKET = load_oss_bucket()
|
| 31 |
+
return _OSS_BUCKET
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class CoTEvalData:
|
| 35 |
+
"""解析 test_json 并按 query / doc 去重。
|
| 36 |
+
|
| 37 |
+
测试集每行是一个 (query, doc) 对,同一个 query(或 doc)会重复出现。
|
| 38 |
+
这里把它拆成三份:
|
| 39 |
+
- unique_queries: [(query_tfsid, query_bbox, query_text)]
|
| 40 |
+
- unique_docs: [(item_tfsid, item_title, item_bbox)]
|
| 41 |
+
- pairs: [(q_idx, d_idx, label_index)]
|
| 42 |
+
query / doc 分别只做一次 CoT 生成 / 前向,最后按 pairs 查表算相似度。
|
| 43 |
+
|
| 44 |
+
去重 key 用构成 message 的全部字段,即使同一 tfsid 带不同 bbox/text
|
| 45 |
+
也不会被错误合并。
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
label_index = {'0': 0, '1': 1}
|
| 49 |
+
|
| 50 |
+
def __init__(self, args):
|
| 51 |
+
self.max_length = 512
|
| 52 |
+
self.parse_json_data(args.test_json, args.max_lines)
|
| 53 |
+
|
| 54 |
+
def parse_json_data(self, json_path: str, max_lines: int):
|
| 55 |
+
with open(json_path, 'r', encoding='utf-8') as f:
|
| 56 |
+
data = json.load(f)
|
| 57 |
+
|
| 58 |
+
num_records_to_read = len(data) if max_lines < 0 else min(len(data), max_lines)
|
| 59 |
+
|
| 60 |
+
self.unique_queries: List[Tuple[str, str, str]] = []
|
| 61 |
+
self.unique_docs: List[Tuple[str, str, str]] = []
|
| 62 |
+
self.pairs: List[Tuple[int, int, int]] = []
|
| 63 |
+
query_key_to_idx: Dict[Tuple, int] = {}
|
| 64 |
+
doc_key_to_idx: Dict[Tuple, int] = {}
|
| 65 |
+
|
| 66 |
+
for i in tqdm(range(num_records_to_read)):
|
| 67 |
+
try:
|
| 68 |
+
record = data[i]
|
| 69 |
+
query_key = (
|
| 70 |
+
record['query_tfsid'],
|
| 71 |
+
record['query_bbox'],
|
| 72 |
+
record['query_text'][:self.max_length - 2],
|
| 73 |
+
)
|
| 74 |
+
doc_key = (
|
| 75 |
+
record['item_tfsid'],
|
| 76 |
+
record['item_title'][:self.max_length - 2],
|
| 77 |
+
record['item_bbox'],
|
| 78 |
+
)
|
| 79 |
+
label = self.label_index[record['label']]
|
| 80 |
+
except Exception as e:
|
| 81 |
+
print("test dataset exception for record {}: {}".format(i, e))
|
| 82 |
+
continue
|
| 83 |
+
|
| 84 |
+
if query_key not in query_key_to_idx:
|
| 85 |
+
query_key_to_idx[query_key] = len(self.unique_queries)
|
| 86 |
+
self.unique_queries.append(query_key)
|
| 87 |
+
if doc_key not in doc_key_to_idx:
|
| 88 |
+
doc_key_to_idx[doc_key] = len(self.unique_docs)
|
| 89 |
+
self.unique_docs.append(doc_key)
|
| 90 |
+
|
| 91 |
+
self.pairs.append((query_key_to_idx[query_key], doc_key_to_idx[doc_key], label))
|
| 92 |
+
|
| 93 |
+
assert len(self.pairs) > 0, "the number of valid item should larger than 0"
|
| 94 |
+
print("total of {} eval pairs, {} unique queries, {} unique docs (json {}).".format(
|
| 95 |
+
len(self.pairs), len(self.unique_queries), len(self.unique_docs), json_path))
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class _CoTEvalImageMixin:
|
| 99 |
+
"""图片读取 / bbox 裁剪 / 长宽比处理(与 baseline 评测一致)。"""
|
| 100 |
+
|
| 101 |
+
min_pixels = 4 * 32 * 32
|
| 102 |
+
max_pixels = 200 * 32 * 32
|
| 103 |
+
|
| 104 |
+
@staticmethod
|
| 105 |
+
def _clamp_aspect_ratio(img: Image.Image, max_ratio: float = 100) -> Image.Image:
|
| 106 |
+
"""如果图片长宽比超过 max_ratio,将其 resize 到长宽比等于 max_ratio。"""
|
| 107 |
+
w, h = img.size
|
| 108 |
+
assert w > 0 and h > 0
|
| 109 |
+
ratio = max(w, h) / min(w, h)
|
| 110 |
+
if ratio <= max_ratio:
|
| 111 |
+
return img
|
| 112 |
+
if w > h:
|
| 113 |
+
new_w = int(h * max_ratio)
|
| 114 |
+
new_h = h
|
| 115 |
+
else:
|
| 116 |
+
new_w = w
|
| 117 |
+
new_h = int(w * max_ratio)
|
| 118 |
+
return img.resize((new_w, new_h), Image.BILINEAR)
|
| 119 |
+
|
| 120 |
+
def _open_image(self, image_name: str) -> Image.Image:
|
| 121 |
+
if self.image_local_dir:
|
| 122 |
+
local_path = os.path.join(self.image_local_dir, image_name)
|
| 123 |
+
if os.path.exists(local_path):
|
| 124 |
+
return Image.open(local_path)
|
| 125 |
+
return Image.open(get_oss_bucket().get_object(f'{OSS_TEST_IMAGE_PREFIX}/{image_name}'))
|
| 126 |
+
|
| 127 |
+
def get_image_from_oss(self, image_name: str, roi: str):
|
| 128 |
+
"""返回 (crop 图, 整图),roi 非法时 crop 图退化为整图。"""
|
| 129 |
+
if len(roi.split(' ')) == 6:
|
| 130 |
+
roi = ' '.join(roi.split(' ')[:4])
|
| 131 |
+
elif len(roi.split(' ')) == 4:
|
| 132 |
+
pass
|
| 133 |
+
else:
|
| 134 |
+
roi = 'ori'
|
| 135 |
+
|
| 136 |
+
image = self._open_image(image_name)
|
| 137 |
+
if image.mode != "RGB":
|
| 138 |
+
image = image.convert("RGB")
|
| 139 |
+
|
| 140 |
+
image_full = image.copy()
|
| 141 |
+
|
| 142 |
+
if roi != 'ori':
|
| 143 |
+
xmin, ymin, xmax, ymax = [int(float(z)) for z in roi.split(' ')[:4]]
|
| 144 |
+
xmin = max(0, xmin)
|
| 145 |
+
xmax = min(image.width - 1, xmax)
|
| 146 |
+
ymin = max(0, ymin)
|
| 147 |
+
ymax = min(image.height - 1, ymax)
|
| 148 |
+
if (ymax - ymin) > 2 and (xmax - xmin) > 2:
|
| 149 |
+
image = image.crop((xmin, ymin, xmax, ymax))
|
| 150 |
+
|
| 151 |
+
# 如果image或者image_full长宽比超过100,将长宽比resize到100
|
| 152 |
+
image = self._clamp_aspect_ratio(image, max_ratio=100)
|
| 153 |
+
image_full = self._clamp_aspect_ratio(image_full, max_ratio=100)
|
| 154 |
+
|
| 155 |
+
return image, image_full
|
| 156 |
+
|
| 157 |
+
@staticmethod
|
| 158 |
+
def _select_images(image_crop, image_full, image_type: str) -> List[Image.Image]:
|
| 159 |
+
if image_type == "full":
|
| 160 |
+
return [image_full]
|
| 161 |
+
if image_type == "crop":
|
| 162 |
+
return [image_crop]
|
| 163 |
+
return [image_full, image_crop]
|
| 164 |
+
|
| 165 |
+
def _build_message(self, system_prompt: str, images: List[Image.Image], text: str) -> List[Dict]:
|
| 166 |
+
content = [
|
| 167 |
+
{"type": "image", "image": image, "min_pixels": self.min_pixels, "max_pixels": self.max_pixels}
|
| 168 |
+
for image in images
|
| 169 |
+
]
|
| 170 |
+
content.append({"type": "text", "text": text})
|
| 171 |
+
return [
|
| 172 |
+
{"role": "system", "content": [{"type": "text", "text": system_prompt}]},
|
| 173 |
+
{"role": "user", "content": content},
|
| 174 |
+
]
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class CoTQueryEvalDataset(_CoTEvalImageMixin, Dataset):
|
| 178 |
+
"""unique query 数据集,产出 (q_idx, query_message)。"""
|
| 179 |
+
|
| 180 |
+
def __init__(self, args, unique_queries: List[Tuple[str, str, str]]):
|
| 181 |
+
super().__init__()
|
| 182 |
+
self.args = args
|
| 183 |
+
self.unique_queries = unique_queries
|
| 184 |
+
self.image_type = getattr(args, "query_image_type", None) or args.image_type
|
| 185 |
+
self.image_local_dir = getattr(args, "image_path_prefix", None)
|
| 186 |
+
|
| 187 |
+
prompt_index = getattr(args, "prompt_index", 0)
|
| 188 |
+
if not 0 <= prompt_index < len(COT_SYSTEM_PROMPTS):
|
| 189 |
+
prompt_index = 0
|
| 190 |
+
self.cot_system_prompt = COT_SYSTEM_PROMPTS[prompt_index]
|
| 191 |
+
|
| 192 |
+
def __len__(self):
|
| 193 |
+
return len(self.unique_queries)
|
| 194 |
+
|
| 195 |
+
def __getitem__(self, index):
|
| 196 |
+
query_tfsid, query_bbox, query_text = self.unique_queries[index]
|
| 197 |
+
query_txt = f"prompt:{query_text}" if self.args.query_text_require else ""
|
| 198 |
+
|
| 199 |
+
try_times = 3
|
| 200 |
+
for i in range(try_times):
|
| 201 |
+
try:
|
| 202 |
+
query_image, query_image_full = self.get_image_from_oss(query_tfsid, query_bbox)
|
| 203 |
+
images = self._select_images(query_image, query_image_full, self.image_type)
|
| 204 |
+
return index, self._build_message(self.cot_system_prompt, images, query_txt)
|
| 205 |
+
except Exception as e:
|
| 206 |
+
print('exception for query getitem {}, try times {}/{} : {}'.format(index, i, try_times, e))
|
| 207 |
+
|
| 208 |
+
print("error testing (query {})".format(query_tfsid))
|
| 209 |
+
return index, self._build_message(self.cot_system_prompt, [], "prompt:Empty.")
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class CoTDocEvalDataset(_CoTEvalImageMixin, Dataset):
|
| 213 |
+
"""unique doc 数据集,产出 (d_idx, doc_message)。"""
|
| 214 |
+
|
| 215 |
+
def __init__(self, args, unique_docs: List[Tuple[str, str, str]]):
|
| 216 |
+
super().__init__()
|
| 217 |
+
self.args = args
|
| 218 |
+
self.unique_docs = unique_docs
|
| 219 |
+
self.image_type = getattr(args, "doc_image_type", None) or args.image_type
|
| 220 |
+
self.image_local_dir = getattr(args, "image_path_prefix", None)
|
| 221 |
+
|
| 222 |
+
def __len__(self):
|
| 223 |
+
return len(self.unique_docs)
|
| 224 |
+
|
| 225 |
+
def __getitem__(self, index):
|
| 226 |
+
item_tfsid, item_title, item_bbox = self.unique_docs[index]
|
| 227 |
+
doc_txt = f"title:{item_title}" if self.args.doc_text_require else ""
|
| 228 |
+
|
| 229 |
+
try_times = 3
|
| 230 |
+
for i in range(try_times):
|
| 231 |
+
try:
|
| 232 |
+
item_image, item_image_full = self.get_image_from_oss(item_tfsid, item_bbox)
|
| 233 |
+
images = self._select_images(item_image, item_image_full, self.image_type)
|
| 234 |
+
return index, self._build_message(DOC_SYSTEM_PROMPT, images, doc_txt)
|
| 235 |
+
except Exception as e:
|
| 236 |
+
print('exception for doc getitem {}, try times {}/{} : {}'.format(index, i, try_times, e))
|
| 237 |
+
|
| 238 |
+
print("error testing (doc {})".format(item_tfsid))
|
| 239 |
+
return index, self._build_message(DOC_SYSTEM_PROMPT, [], "title:Empty.")
|
code/multi_vlm2vec_train/cot_eval/eval_config.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CoT embedding 本地评测参数文件。
|
| 2 |
+
|
| 3 |
+
在这里直接修改参数,然后运行:
|
| 4 |
+
python cot_eval/eval_local.py
|
| 5 |
+
无需在命令行传任何参数。
|
| 6 |
+
|
| 7 |
+
注意:bool 参数直接写 True / False(不是字符串)。
|
| 8 |
+
"""
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from typing import Optional
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@dataclass
|
| 14 |
+
class EvalConfig:
|
| 15 |
+
# ------------------------------------------------------------------
|
| 16 |
+
# 模型
|
| 17 |
+
# ------------------------------------------------------------------
|
| 18 |
+
# base 模型路径(与训练时的 model_local_path 一致)
|
| 19 |
+
model_id: str = "/data/oss_bucket_0/liqi/models/Qwen3-VL-Embedding-2B/"
|
| 20 |
+
emb_dim: int = 2048
|
| 21 |
+
out_dim: int = 2048
|
| 22 |
+
|
| 23 |
+
# 训练产出的 checkpoint:
|
| 24 |
+
# lora=True -> lora_pth 为 LoRA adapter 目录(checkpoint-xxx),base 从 model_id 加载后 merge;
|
| 25 |
+
# lora=False -> lora_pth 为全参微调 checkpoint 目录(checkpoint-xxx),直接加载完整权重;
|
| 26 |
+
# 置空字符串则只评测 model_id 的 base 模型。
|
| 27 |
+
lora: bool = False
|
| 28 |
+
# all_eval=False 时给到单个 checkpoint-xxx 目录;
|
| 29 |
+
# all_eval=True 时给到 run 根目录,会遍历其中所有 checkpoint-*
|
| 30 |
+
ckpt: int = 2500
|
| 31 |
+
root_pth: str = "/data/oss_bucket_0/liqi/cot_embedding/nebula_train/dapei_loraFalse_lr1e-5_btz256_ep4_candidate8_cot0.1_8gpu/train_qwen3vl_cot_lora_False_lmhead_True_epoch_4_lr1e-5_candidate8_cot0.1/"
|
| 32 |
+
lora_pth: str = f"{root_pth}/checkpoint-{ckpt}"
|
| 33 |
+
all_eval: bool = False
|
| 34 |
+
|
| 35 |
+
# ------------------------------------------------------------------
|
| 36 |
+
# 数据集(与 baseline 评测一致)
|
| 37 |
+
# ------------------------------------------------------------------
|
| 38 |
+
test_data_type: str = "dapei"
|
| 39 |
+
test_json: str = f"/data/oss_bucket_0/liqi/dataset/embedding_pf/{test_data_type}_test.json"
|
| 40 |
+
max_lines: int = 100000000
|
| 41 |
+
image_type: str = "both" # full / crop / both
|
| 42 |
+
query_image_type: Optional[str] = None # 不填则用 image_type
|
| 43 |
+
doc_image_type: Optional[str] = None # 不填则用 image_type
|
| 44 |
+
# 本地测试图片目录:命中则本地读取,找不到时回退 OSS;置 None 则全走 OSS
|
| 45 |
+
image_path_prefix: Optional[str] = "/data/oss_bucket_0/peifeng/multi_vlm2vec/dataset/merge/test_image"
|
| 46 |
+
query_text_require: bool = True
|
| 47 |
+
doc_text_require: bool = True
|
| 48 |
+
batch_size: int = 256
|
| 49 |
+
|
| 50 |
+
# ------------------------------------------------------------------
|
| 51 |
+
# CoT 设置(需与训练配置保持一致)
|
| 52 |
+
# ------------------------------------------------------------------
|
| 53 |
+
prompt_index: int = 0
|
| 54 |
+
max_cot_new_tokens: int = 192 # 与训练 max_cot_length 对齐
|
| 55 |
+
cot_emb_suffix: str = "<|im_end|>"
|
| 56 |
+
doc_append_eos: bool = False
|
| 57 |
+
# query = prompt + cot,序列比纯 embedding 评测长
|
| 58 |
+
model_max_length: int = 2048
|
| 59 |
+
|
| 60 |
+
# ------------------------------------------------------------------
|
| 61 |
+
# 结果保存
|
| 62 |
+
# ------------------------------------------------------------------
|
| 63 |
+
# 生成的 CoT 文本(qid -> cot),置空字符串则不保存
|
| 64 |
+
# all_eval=True 时文件名自动加 checkpoint-xxx_ 前缀,每个 ckpt 一个文件
|
| 65 |
+
save_cot_json: str = f"{root_pth}/eval_result/ckpt-{ckpt}/cot.json"
|
| 66 |
+
# 指标结果,置空字符串则不保存
|
| 67 |
+
# all_eval=True 时所有 ckpt 汇总进这一个文件:{checkpoint-xxx: results}
|
| 68 |
+
result_json: str = f"{root_pth}/eval_result/ckpt-{ckpt}/metrics.json"
|
| 69 |
+
train_data_type: str = ""
|
code/multi_vlm2vec_train/cot_eval/eval_local.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CoT embedding 本地评测入口。
|
| 2 |
+
|
| 3 |
+
用法:在 cot_eval/eval_config.py 中修改参数后,直接运行
|
| 4 |
+
python cot_eval/eval_local.py
|
| 5 |
+
|
| 6 |
+
单卡直接跑;多卡也可以用
|
| 7 |
+
accelerate launch --num_processes 4 cot_eval/eval_local.py
|
| 8 |
+
python -m accelerate.commands.launch --num_processes 4 cot_eval/eval_local.py
|
| 9 |
+
python -m pip install jsonlines accelerate peft qwen_vl_utils
|
| 10 |
+
"""
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
|
| 14 |
+
current_file_path = os.path.dirname(os.path.abspath(__file__))
|
| 15 |
+
module_path = os.path.join(current_file_path, "../")
|
| 16 |
+
sys.path.append(module_path)
|
| 17 |
+
|
| 18 |
+
from cot_eval.eval_config import EvalConfig
|
| 19 |
+
from cot_eval.eval_tuwen_qwen3vl_cot import run_eval
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if __name__ == "__main__":
|
| 23 |
+
args = EvalConfig()
|
| 24 |
+
print("eval config:")
|
| 25 |
+
for key, value in vars(args).items():
|
| 26 |
+
print(f" {key}: {value}")
|
| 27 |
+
run_eval(args)
|
code/multi_vlm2vec_train/cot_eval/eval_tuwen_qwen3vl_cot.py
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CoT embedding 评测脚本(query / doc 去重版)。
|
| 2 |
+
|
| 3 |
+
与 eval/eval_tuwen_qwen3vl.py(纯 embedding baseline)保持一致的部分:
|
| 4 |
+
- 测试数据格式、图片读取、bbox 裁剪、长宽比处理;
|
| 5 |
+
- doc 侧一次前向 + last-token pooling;
|
| 6 |
+
- emb_dim 截断、L2 归一化、cos 相似度;
|
| 7 |
+
- 指标计算(eval/eval_utils.py 的 tongkuan_score_print,sim_weight 相同);
|
| 8 |
+
- all_eval 遍历 checkpoint-* 的逻辑。
|
| 9 |
+
|
| 10 |
+
与 baseline 不同的仅有 query 侧 prompt 和 embedding 生成方式:
|
| 11 |
+
1. query 用训练时的 CoT system prompt,先 model.generate() 自回归生成
|
| 12 |
+
一段显式 CoT(直到 `<|im_end|>`),并保留 KV cache;
|
| 13 |
+
2. 复用 cache,仅增量前向尚未进入 cache 的尾 token 和 `<|im_end|>`,
|
| 14 |
+
取 `<|im_end|>` 位置的 hidden state 作为 query embedding,避免重复编码图片、
|
| 15 |
+
prompt 和 CoT,并与训练时 teacher forcing 下的 pooling 位置保持一致。
|
| 16 |
+
|
| 17 |
+
评测流程按三阶段执行,避免同一 query 重复生成 CoT:
|
| 18 |
+
- 阶段1:unique query 批量生成 CoT + cache 增量前向取 query embedding;
|
| 19 |
+
- 阶段2:unique doc 批量前向取 doc embedding;
|
| 20 |
+
- 阶段3:按原始 (query, doc) 对查表算 cos,再聚合指标。
|
| 21 |
+
"""
|
| 22 |
+
import json
|
| 23 |
+
import re
|
| 24 |
+
import sys
|
| 25 |
+
import os
|
| 26 |
+
|
| 27 |
+
current_file_path = os.path.dirname(os.path.abspath(__file__))
|
| 28 |
+
module_path = os.path.join(current_file_path, "../")
|
| 29 |
+
sys.path.append(module_path)
|
| 30 |
+
|
| 31 |
+
import argparse
|
| 32 |
+
|
| 33 |
+
import accelerate
|
| 34 |
+
import torch
|
| 35 |
+
import torch.nn.functional as F
|
| 36 |
+
from accelerate import Accelerator
|
| 37 |
+
from peft import LoraConfig, PeftModel
|
| 38 |
+
from torch.utils.data import DataLoader
|
| 39 |
+
from tqdm import tqdm
|
| 40 |
+
from transformers.models.qwen3_vl.processing_qwen3_vl import Qwen3VLProcessor
|
| 41 |
+
|
| 42 |
+
from train_cot.qwen3_vl_cot_embedding import Qwen3VLForCoTEmbedding, pooling_last
|
| 43 |
+
from cot_eval.datasets_tuwen_qwen3vl_cot_eval import (
|
| 44 |
+
CoTEvalData,
|
| 45 |
+
CoTQueryEvalDataset,
|
| 46 |
+
CoTDocEvalDataset,
|
| 47 |
+
)
|
| 48 |
+
from cot_eval.collator_tuwen_qwen3vl_cot_eval import CoTQueryEvalCollator, CoTDocEvalCollator
|
| 49 |
+
from eval.eval_utils import tongkuan_score_print
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def save_json(path, data):
|
| 53 |
+
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
| 54 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 55 |
+
json.dump(data, f, ensure_ascii=False)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def build_query_cache_inputs(
|
| 59 |
+
sequences, gen_inputs, prompt_position_ids, past_key_values, suffix_ids, pad_token_id
|
| 60 |
+
):
|
| 61 |
+
"""构造复用 generate KV cache 的 suffix 增量前向输入。"""
|
| 62 |
+
if len(suffix_ids) != 1:
|
| 63 |
+
raise ValueError("cot_emb_suffix must encode to exactly one token for cache-based pooling")
|
| 64 |
+
|
| 65 |
+
prompt_len = gen_inputs["input_ids"].shape[1]
|
| 66 |
+
generated_ids = sequences[:, prompt_len:]
|
| 67 |
+
if generated_ids.shape[1] == 0:
|
| 68 |
+
raise ValueError("max_cot_new_tokens must be greater than 0")
|
| 69 |
+
|
| 70 |
+
expected_cache_len = sequences.shape[1] - 1
|
| 71 |
+
cache_len = past_key_values.get_seq_length()
|
| 72 |
+
if cache_len < expected_cache_len:
|
| 73 |
+
raise RuntimeError(
|
| 74 |
+
f"generation cache is shorter than expected: {cache_len} < {expected_cache_len}"
|
| 75 |
+
)
|
| 76 |
+
if cache_len > expected_cache_len:
|
| 77 |
+
past_key_values.crop(expected_cache_len)
|
| 78 |
+
|
| 79 |
+
eos_id = suffix_ids[0]
|
| 80 |
+
batch_size = sequences.shape[0]
|
| 81 |
+
cached_attention_mask = torch.zeros(
|
| 82 |
+
(batch_size, expected_cache_len), dtype=gen_inputs["attention_mask"].dtype,
|
| 83 |
+
device=sequences.device,
|
| 84 |
+
)
|
| 85 |
+
cached_attention_mask[:, :prompt_len] = gen_inputs["attention_mask"]
|
| 86 |
+
|
| 87 |
+
extension_ids_list = []
|
| 88 |
+
first_position_offsets = []
|
| 89 |
+
cot_ids_list = []
|
| 90 |
+
for i, row in enumerate(generated_ids.tolist()):
|
| 91 |
+
if eos_id in row:
|
| 92 |
+
eos_position = row.index(eos_id)
|
| 93 |
+
cached_cot_len = eos_position
|
| 94 |
+
extension_ids = [eos_id]
|
| 95 |
+
first_position_offset = eos_position + 1
|
| 96 |
+
cot_ids = row[:eos_position]
|
| 97 |
+
else:
|
| 98 |
+
cached_cot_len = len(row) - 1
|
| 99 |
+
extension_ids = [row[-1], eos_id]
|
| 100 |
+
first_position_offset = len(row)
|
| 101 |
+
cot_ids = row
|
| 102 |
+
|
| 103 |
+
cached_attention_mask[i, prompt_len:prompt_len + cached_cot_len] = 1
|
| 104 |
+
extension_ids_list.append(extension_ids)
|
| 105 |
+
first_position_offsets.append(first_position_offset)
|
| 106 |
+
cot_ids_list.append(cot_ids)
|
| 107 |
+
|
| 108 |
+
max_extension_len = max(len(ids) for ids in extension_ids_list)
|
| 109 |
+
extension_ids = torch.full(
|
| 110 |
+
(batch_size, max_extension_len), pad_token_id, dtype=sequences.dtype,
|
| 111 |
+
device=sequences.device,
|
| 112 |
+
)
|
| 113 |
+
extension_attention_mask = torch.zeros(
|
| 114 |
+
(batch_size, max_extension_len), dtype=gen_inputs["attention_mask"].dtype,
|
| 115 |
+
device=sequences.device,
|
| 116 |
+
)
|
| 117 |
+
extension_position_ids = torch.zeros(
|
| 118 |
+
(prompt_position_ids.shape[0], batch_size, max_extension_len),
|
| 119 |
+
dtype=prompt_position_ids.dtype,
|
| 120 |
+
device=sequences.device,
|
| 121 |
+
)
|
| 122 |
+
pool_positions = torch.empty(batch_size, dtype=torch.long, device=sequences.device)
|
| 123 |
+
prompt_last_positions = prompt_position_ids[:, :, -1]
|
| 124 |
+
|
| 125 |
+
for i, ids in enumerate(extension_ids_list):
|
| 126 |
+
extension_len = len(ids)
|
| 127 |
+
extension_ids[i, :extension_len] = torch.tensor(ids, dtype=sequences.dtype, device=sequences.device)
|
| 128 |
+
extension_attention_mask[i, :extension_len] = 1
|
| 129 |
+
offsets = torch.arange(
|
| 130 |
+
first_position_offsets[i], first_position_offsets[i] + max_extension_len,
|
| 131 |
+
dtype=prompt_position_ids.dtype,
|
| 132 |
+
device=sequences.device,
|
| 133 |
+
)
|
| 134 |
+
extension_position_ids[:, i, :] = prompt_last_positions[:, i, None] + offsets
|
| 135 |
+
pool_positions[i] = extension_len - 1
|
| 136 |
+
|
| 137 |
+
cache_inputs = {
|
| 138 |
+
"input_ids": extension_ids,
|
| 139 |
+
"attention_mask": torch.cat([cached_attention_mask, extension_attention_mask], dim=1),
|
| 140 |
+
"position_ids": extension_position_ids,
|
| 141 |
+
"past_key_values": past_key_values,
|
| 142 |
+
}
|
| 143 |
+
return cache_inputs, pool_positions, cot_ids_list
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def eval(args):
|
| 147 |
+
## 模型加载
|
| 148 |
+
# lora=True:从 model_id 加载 base,再挂 lora_pth 下的 LoRA adapter 并 merge;
|
| 149 |
+
# lora=False 且 lora_pth 非空:lora_pth 视为全参微调 checkpoint,直接加载完整权重;
|
| 150 |
+
# lora=False 且 lora_pth 为空:只评测 base 模型。
|
| 151 |
+
model_path = args.model_id
|
| 152 |
+
if args.lora:
|
| 153 |
+
model = Qwen3VLForCoTEmbedding.from_pretrained(
|
| 154 |
+
model_path, torch_dtype=torch.bfloat16, trust_remote_code=True
|
| 155 |
+
)
|
| 156 |
+
print("Loading lora ckpt.")
|
| 157 |
+
lora_config = LoraConfig.from_pretrained(args.lora_pth)
|
| 158 |
+
lora_model = PeftModel.from_pretrained(model, args.lora_pth, config=lora_config)
|
| 159 |
+
model = lora_model.merge_and_unload()
|
| 160 |
+
elif args.lora_pth:
|
| 161 |
+
print(f"Loading full finetuned ckpt from {args.lora_pth}.")
|
| 162 |
+
model = Qwen3VLForCoTEmbedding.from_pretrained(
|
| 163 |
+
args.lora_pth, torch_dtype=torch.bfloat16, trust_remote_code=True
|
| 164 |
+
)
|
| 165 |
+
else:
|
| 166 |
+
model = Qwen3VLForCoTEmbedding.from_pretrained(
|
| 167 |
+
model_path, torch_dtype=torch.bfloat16, trust_remote_code=True
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
model.eval()
|
| 171 |
+
model.requires_grad_(False)
|
| 172 |
+
# 生成 CoT 需要 kv cache(训练时被关掉了)
|
| 173 |
+
model.config.use_cache = True
|
| 174 |
+
if hasattr(model.config, "text_config"):
|
| 175 |
+
model.config.text_config.use_cache = True
|
| 176 |
+
|
| 177 |
+
processor = Qwen3VLProcessor.from_pretrained(model_path, padding_side='right')
|
| 178 |
+
tokenizer = processor.tokenizer
|
| 179 |
+
|
| 180 |
+
suffix_ids = tokenizer.encode(args.cot_emb_suffix, add_special_tokens=False)
|
| 181 |
+
if len(suffix_ids) != 1:
|
| 182 |
+
raise ValueError("cot_emb_suffix must encode to exactly one token for cache-based pooling")
|
| 183 |
+
if args.max_cot_new_tokens <= 0:
|
| 184 |
+
raise ValueError("max_cot_new_tokens must be greater than 0")
|
| 185 |
+
pad_token_id = tokenizer.pad_token_id
|
| 186 |
+
|
| 187 |
+
accelerator = Accelerator(mixed_precision='bf16')
|
| 188 |
+
device = accelerator.device
|
| 189 |
+
is_main_process = accelerator.is_main_process
|
| 190 |
+
|
| 191 |
+
## 数据集加载:按 query / doc 去重
|
| 192 |
+
eval_data = CoTEvalData(args)
|
| 193 |
+
query_dataset = CoTQueryEvalDataset(args, eval_data.unique_queries)
|
| 194 |
+
doc_dataset = CoTDocEvalDataset(args, eval_data.unique_docs)
|
| 195 |
+
|
| 196 |
+
query_dataloader = DataLoader(
|
| 197 |
+
query_dataset, batch_size=args.batch_size, num_workers=4,
|
| 198 |
+
shuffle=False, collate_fn=CoTQueryEvalCollator(processor, args.model_max_length),
|
| 199 |
+
pin_memory=True,
|
| 200 |
+
)
|
| 201 |
+
doc_dataloader = DataLoader(
|
| 202 |
+
doc_dataset, batch_size=args.batch_size, num_workers=4,
|
| 203 |
+
shuffle=False, collate_fn=CoTDocEvalCollator(
|
| 204 |
+
processor, args.model_max_length, args.cot_emb_suffix, args.doc_append_eos,
|
| 205 |
+
),
|
| 206 |
+
pin_memory=True,
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
def tensors_to_device(data, device, dtype=model.dtype):
|
| 210 |
+
for key in data.keys():
|
| 211 |
+
if isinstance(data[key], torch.Tensor):
|
| 212 |
+
if 'pixel_values' in key:
|
| 213 |
+
data[key] = data[key].to(device).to(dtype)
|
| 214 |
+
else:
|
| 215 |
+
data[key] = data[key].to(device)
|
| 216 |
+
return data
|
| 217 |
+
|
| 218 |
+
emb_dim = args.emb_dim
|
| 219 |
+
|
| 220 |
+
# 主进程收集:按去重后的索引存放 embedding / CoT 文本
|
| 221 |
+
query_embed_all = torch.zeros(len(query_dataset), emb_dim, dtype=torch.float32)
|
| 222 |
+
doc_embed_all = torch.zeros(len(doc_dataset), emb_dim, dtype=torch.float32)
|
| 223 |
+
cot_by_qidx = {}
|
| 224 |
+
|
| 225 |
+
with torch.no_grad():
|
| 226 |
+
model, query_dataloader, doc_dataloader = accelerator.prepare(
|
| 227 |
+
model, query_dataloader, doc_dataloader
|
| 228 |
+
)
|
| 229 |
+
unwrapped_model = accelerator.unwrap_model(model)
|
| 230 |
+
|
| 231 |
+
## 阶段1:unique query 生成 CoT + embedding
|
| 232 |
+
for query_gen_batch, q_idxs in tqdm(query_dataloader, desc="query cot+embed"):
|
| 233 |
+
query_gen_batch = tensors_to_device(query_gen_batch, device)
|
| 234 |
+
prompt_position_ids = unwrapped_model._prepare_position_ids_for_generation(
|
| 235 |
+
query_gen_batch["input_ids"], dict(query_gen_batch)
|
| 236 |
+
)
|
| 237 |
+
# generate 的 kwargs 校验不接受 mm_token_type_ids,位置已在上面按 M-RoPE 算好
|
| 238 |
+
gen_kwargs = {k: v for k, v in query_gen_batch.items() if k != "mm_token_type_ids"}
|
| 239 |
+
gen_kwargs["position_ids"] = prompt_position_ids
|
| 240 |
+
generation_output = unwrapped_model.generate(
|
| 241 |
+
**gen_kwargs,
|
| 242 |
+
max_new_tokens=args.max_cot_new_tokens,
|
| 243 |
+
do_sample=False,
|
| 244 |
+
eos_token_id=suffix_ids[-1],
|
| 245 |
+
pad_token_id=pad_token_id,
|
| 246 |
+
use_cache=True,
|
| 247 |
+
cache_implementation="dynamic_full",
|
| 248 |
+
return_dict_in_generate=True,
|
| 249 |
+
)
|
| 250 |
+
sequences = generation_output.sequences
|
| 251 |
+
cache_inputs, pool_positions, cot_ids_list = build_query_cache_inputs(
|
| 252 |
+
sequences,
|
| 253 |
+
query_gen_batch,
|
| 254 |
+
prompt_position_ids,
|
| 255 |
+
generation_output.past_key_values,
|
| 256 |
+
suffix_ids,
|
| 257 |
+
pad_token_id,
|
| 258 |
+
)
|
| 259 |
+
query_outputs = model(**cache_inputs)
|
| 260 |
+
row = torch.arange(query_outputs.last_hidden_state.shape[0], device=device)
|
| 261 |
+
query_embed = query_outputs.last_hidden_state[row, pool_positions]
|
| 262 |
+
query_embed = query_embed[..., :emb_dim]
|
| 263 |
+
query_embed = F.normalize(query_embed, p=2, dim=-1)
|
| 264 |
+
|
| 265 |
+
cot_texts = [tokenizer.decode(ids, skip_special_tokens=True).strip() for ids in cot_ids_list]
|
| 266 |
+
|
| 267 |
+
query_embed = accelerator.gather_for_metrics(query_embed)
|
| 268 |
+
q_idxs = accelerate.utils.gather_object(q_idxs)[:query_embed.size(0)]
|
| 269 |
+
cot_texts = accelerate.utils.gather_object(cot_texts)[:query_embed.size(0)]
|
| 270 |
+
|
| 271 |
+
if is_main_process:
|
| 272 |
+
query_embed_all[list(q_idxs)] = query_embed.float().cpu()
|
| 273 |
+
for q_idx, cot in zip(q_idxs, cot_texts):
|
| 274 |
+
cot_by_qidx[q_idx] = cot
|
| 275 |
+
|
| 276 |
+
del query_gen_batch, gen_kwargs, generation_output, sequences
|
| 277 |
+
del cache_inputs, pool_positions, query_outputs, query_embed
|
| 278 |
+
|
| 279 |
+
## 阶段2:unique doc embedding(与 baseline 相同,直接前向取 last token)
|
| 280 |
+
for doc_batch, d_idxs in tqdm(doc_dataloader, desc="doc embed"):
|
| 281 |
+
doc_batch = tensors_to_device(doc_batch, device)
|
| 282 |
+
doc_outputs = model(**doc_batch)
|
| 283 |
+
candidate_embed = pooling_last(doc_outputs.last_hidden_state, doc_batch.get('attention_mask'))
|
| 284 |
+
candidate_embed = candidate_embed[..., :emb_dim]
|
| 285 |
+
candidate_embed = F.normalize(candidate_embed, p=2, dim=-1)
|
| 286 |
+
|
| 287 |
+
candidate_embed = accelerator.gather_for_metrics(candidate_embed)
|
| 288 |
+
d_idxs = accelerate.utils.gather_object(d_idxs)[:candidate_embed.size(0)]
|
| 289 |
+
|
| 290 |
+
if is_main_process:
|
| 291 |
+
doc_embed_all[list(d_idxs)] = candidate_embed.float().cpu()
|
| 292 |
+
|
| 293 |
+
del doc_batch, doc_outputs, candidate_embed
|
| 294 |
+
|
| 295 |
+
accelerator.wait_for_everyone()
|
| 296 |
+
|
| 297 |
+
## 阶段3:按原始 (query, doc) 对查表算 cos,聚合指标
|
| 298 |
+
results_all_dict = None
|
| 299 |
+
if is_main_process:
|
| 300 |
+
pair_q = torch.tensor([p[0] for p in eval_data.pairs], dtype=torch.long)
|
| 301 |
+
pair_d = torch.tensor([p[1] for p in eval_data.pairs], dtype=torch.long)
|
| 302 |
+
cos_sim = (query_embed_all[pair_q] * doc_embed_all[pair_d]).sum(dim=1).tolist()
|
| 303 |
+
|
| 304 |
+
query_dic_all = {}
|
| 305 |
+
for (q_idx, d_idx, label), sim in zip(eval_data.pairs, cos_sim):
|
| 306 |
+
qid = eval_data.unique_queries[q_idx][0]
|
| 307 |
+
itemid = eval_data.unique_docs[d_idx][0]
|
| 308 |
+
if qid not in query_dic_all:
|
| 309 |
+
query_dic_all[qid] = {'label': [], 'sim': [], 'doc_tfs': []}
|
| 310 |
+
query_dic_all[qid]['label'].append(label)
|
| 311 |
+
query_dic_all[qid]['sim'].append(sim)
|
| 312 |
+
query_dic_all[qid]['doc_tfs'].append(itemid)
|
| 313 |
+
|
| 314 |
+
results_all_dict = tongkuan_score_print(query_dic_all, sim_weight=[0.2, 0.2, 0.2, 0.2, 0.2])
|
| 315 |
+
|
| 316 |
+
if args.save_cot_json:
|
| 317 |
+
cot_records = [
|
| 318 |
+
{
|
| 319 |
+
"query_tfsid": query_tfsid,
|
| 320 |
+
"query_text": query_text,
|
| 321 |
+
"cot": cot_by_qidx.get(q_idx, ""),
|
| 322 |
+
}
|
| 323 |
+
for q_idx, (query_tfsid, _query_bbox, query_text) in enumerate(eval_data.unique_queries)
|
| 324 |
+
]
|
| 325 |
+
save_json(args.save_cot_json, cot_records)
|
| 326 |
+
print(f"generated cot saved to {args.save_cot_json}")
|
| 327 |
+
|
| 328 |
+
if args.result_json:
|
| 329 |
+
save_json(args.result_json, results_all_dict)
|
| 330 |
+
|
| 331 |
+
# all_eval 会在同一进程里连续评多个 ckpt,必须先把本次模型和
|
| 332 |
+
# accelerator 持有的引用清干净再加载下一个,否则显存会累积到 OOM
|
| 333 |
+
del unwrapped_model
|
| 334 |
+
model, query_dataloader, doc_dataloader = accelerator.free_memory(
|
| 335 |
+
model, query_dataloader, doc_dataloader
|
| 336 |
+
)
|
| 337 |
+
accelerator.wait_for_everyone()
|
| 338 |
+
|
| 339 |
+
return results_all_dict
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def insert_ckpt_name(path, ckpt_name):
|
| 343 |
+
"""给 path 的文件名加上 checkpoint 前缀,遍历时每个 ckpt 落到独立文件。"""
|
| 344 |
+
if not path:
|
| 345 |
+
return path
|
| 346 |
+
dirname, basename = os.path.split(path)
|
| 347 |
+
return os.path.join(dirname, f"{ckpt_name}_{basename}")
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def run_eval(args):
|
| 351 |
+
"""入口逻辑:all_eval 时遍历 lora_pth 下所有 checkpoint-*,否则单次评测。
|
| 352 |
+
|
| 353 |
+
命令行方式(nebula)和本地参数文件方式(eval_local.py)共用。
|
| 354 |
+
要求 args 上的 bool 字段已经是真正的 bool。
|
| 355 |
+
|
| 356 |
+
all_eval 时每个 ckpt 的 CoT 各存一个文件,指标则汇总进同一个 result_json
|
| 357 |
+
({checkpoint-xxx: results}),每评完一个 ckpt 就落盘一次。
|
| 358 |
+
"""
|
| 359 |
+
if args.all_eval:
|
| 360 |
+
lora_root_path = args.lora_pth
|
| 361 |
+
checkpoint_dirs = [
|
| 362 |
+
os.path.join(lora_root_path, d)
|
| 363 |
+
for d in os.listdir(lora_root_path)
|
| 364 |
+
if os.path.isdir(os.path.join(lora_root_path, d)) and re.match(r"checkpoint-\d+", d)
|
| 365 |
+
]
|
| 366 |
+
if not checkpoint_dirs:
|
| 367 |
+
raise ValueError(
|
| 368 |
+
f"all_eval=True but no checkpoint-* found under {lora_root_path}, "
|
| 369 |
+
"lora_pth should point to the run root dir"
|
| 370 |
+
)
|
| 371 |
+
checkpoint_dirs.sort(key=lambda x: int(re.search(r"checkpoint-(\d+)", x).group(1)))
|
| 372 |
+
|
| 373 |
+
save_cot_json, result_json = args.save_cot_json, args.result_json
|
| 374 |
+
args.result_json = "" # 单 ckpt 指标不单独落盘,由这里汇总
|
| 375 |
+
metrics_all = {}
|
| 376 |
+
for ckpt_dir in checkpoint_dirs:
|
| 377 |
+
args.lora_pth = ckpt_dir
|
| 378 |
+
ckpt_name = os.path.basename(ckpt_dir)
|
| 379 |
+
args.save_cot_json = insert_ckpt_name(save_cot_json, ckpt_name)
|
| 380 |
+
results = eval(args)
|
| 381 |
+
if results is not None and result_json:
|
| 382 |
+
metrics_all[ckpt_name] = results
|
| 383 |
+
save_json(result_json, metrics_all)
|
| 384 |
+
print(f"metrics of {ckpt_name} saved to {result_json}")
|
| 385 |
+
else:
|
| 386 |
+
eval(args)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
if __name__ == "__main__":
|
| 390 |
+
print("begin reading input parameters")
|
| 391 |
+
parser = argparse.ArgumentParser()
|
| 392 |
+
parser.add_argument('--test_json', default="/data/oss_bucket_0/liqi/dataset/embedding_pf/bianji_test.json", type=str, help='Path to test JSON file')
|
| 393 |
+
parser.add_argument('--max_lines', default=10000000, type=int, help='Limit the data length')
|
| 394 |
+
parser.add_argument('--model_max_length', type=int, default=2048)
|
| 395 |
+
parser.add_argument('--model_id', type=str, default="/data/oss_bucket_0/liqi/models/Qwen3-VL-Embedding-2B/")
|
| 396 |
+
parser.add_argument('--image_type', default="both", type=str)
|
| 397 |
+
parser.add_argument('--query_image_type', default=None, type=str, help='query side image type, fall back to image_type')
|
| 398 |
+
parser.add_argument('--doc_image_type', default=None, type=str, help='doc side image type, fall back to image_type')
|
| 399 |
+
parser.add_argument('--image_path_prefix', default=None, type=str, help='local test image dir; fall back to oss when missing')
|
| 400 |
+
parser.add_argument('--emb_dim', default=2048, type=int)
|
| 401 |
+
parser.add_argument('--out_dim', default=2048, type=int)
|
| 402 |
+
parser.add_argument('--batch_size', default=8, type=int)
|
| 403 |
+
parser.add_argument('--query_text_require', type=str, default='True')
|
| 404 |
+
parser.add_argument('--doc_text_require', type=str, default='True')
|
| 405 |
+
parser.add_argument('--lora', type=str, default='False')
|
| 406 |
+
parser.add_argument('--lora_pth', type=str, default='')
|
| 407 |
+
parser.add_argument('--train_data_type', type=str, default='')
|
| 408 |
+
parser.add_argument('--test_data_type', type=str, default='')
|
| 409 |
+
parser.add_argument('--all_eval', type=str, default='False')
|
| 410 |
+
# ---- CoT 相关参数,需与训练配置保持一致 ----
|
| 411 |
+
parser.add_argument('--prompt_index', default=0, type=int, help='index of COT_SYSTEM_PROMPTS used at training')
|
| 412 |
+
parser.add_argument('--max_cot_new_tokens', default=192, type=int, help='max new tokens for cot generation, align with max_cot_length')
|
| 413 |
+
parser.add_argument('--cot_emb_suffix', default='<|im_end|>', type=str, help='suffix whose hidden state is pooled, align with training')
|
| 414 |
+
parser.add_argument('--doc_append_eos', type=str, default='False', help='align with training doc_append_eos')
|
| 415 |
+
parser.add_argument('--save_cot_json', type=str, default='', help='if set, save generated cot as a list of {query_tfsid, query_text, cot} dicts to this json')
|
| 416 |
+
parser.add_argument('--result_json', type=str, default='', help='if set, save metric results to this json')
|
| 417 |
+
args = parser.parse_args()
|
| 418 |
+
args.query_text_require = args.query_text_require.lower() == 'true'
|
| 419 |
+
args.doc_text_require = args.doc_text_require.lower() == 'true'
|
| 420 |
+
args.lora = args.lora.lower() == 'true'
|
| 421 |
+
args.all_eval = args.all_eval.lower() == 'true'
|
| 422 |
+
args.doc_append_eos = args.doc_append_eos.lower() == 'true'
|
| 423 |
+
|
| 424 |
+
run_eval(args)
|
code/multi_vlm2vec_train/cot_eval/scripts/eval_local_qwen_cot.sh
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CoT embedding 评测:query 先 generate 出显式 CoT,再取 <|im_end|> 处的 embedding
|
| 2 |
+
# 除 query 侧 prompt / embedding 生成方式外,其余与 eval/eval_tuwen_qwen3vl.py 保持一致
|
| 3 |
+
set -x
|
| 4 |
+
|
| 5 |
+
## 分布式配置
|
| 6 |
+
NUM_GPUS=1
|
| 7 |
+
|
| 8 |
+
## 模型设置(base 模型,与训练时的 model_local_path 一致)
|
| 9 |
+
MODEL_ID=/data/oss_bucket_0/liqi/models/Qwen3-VL-Embedding-2B/
|
| 10 |
+
EMB_DIM=2048
|
| 11 |
+
OUT_DIM=2048
|
| 12 |
+
|
| 13 |
+
## LoRA ckpt(训练产出)
|
| 14 |
+
LORA=True
|
| 15 |
+
LORA_PTH=/path/to/your/cot_run/checkpoint-xxx/
|
| 16 |
+
## ALL_EVAL=True 时 LORA_PTH 给到 run 根目录,会遍历其中所有 checkpoint-*
|
| 17 |
+
ALL_EVAL=False
|
| 18 |
+
|
| 19 |
+
## 数据集设置(与 baseline 评测一致)
|
| 20 |
+
TEST_JSON=/data/oss_bucket_0/liqi/dataset/embedding_pf/zhaoxiangsi_test.json
|
| 21 |
+
TEST_DATA_TYPE="zhaoxiangsi"
|
| 22 |
+
MAX_LINES=100000000
|
| 23 |
+
IMAGE_TYPE="both"
|
| 24 |
+
QUERY_TEXT="True"
|
| 25 |
+
DOC_TEXT="True"
|
| 26 |
+
BATCH_SIZE=8
|
| 27 |
+
|
| 28 |
+
## CoT 设置(需与训练配置保持一致)
|
| 29 |
+
PROMPT_INDEX=0
|
| 30 |
+
MAX_COT_NEW_TOKENS=192
|
| 31 |
+
DOC_APPEND_EOS=False
|
| 32 |
+
## query = prompt + cot,序列比纯 embedding 评测长
|
| 33 |
+
MODEL_MAX_LEN=2048
|
| 34 |
+
|
| 35 |
+
## 结果保存
|
| 36 |
+
ckpt=
|
| 37 |
+
SAVE_COT_JSON="/data/oss_bucket_0/liqi/cot_embedding/nebula_train/bianji_lora128_lr1e5_btz256_ep20/train_qwen3vl_cot_lora_True_lmhead_True_batch_8_epoch_20/eval_result/ckpt-${ckpt}/cot.json"
|
| 38 |
+
RESULT_JSON=./cot_eval_output/${TEST_DATA_TYPE}_result.json
|
| 39 |
+
|
| 40 |
+
echo "begin cot evaluation!"
|
| 41 |
+
|
| 42 |
+
accelerate launch --num_processes ${NUM_GPUS} cot_eval/eval_tuwen_qwen3vl_cot.py \
|
| 43 |
+
--test_json ${TEST_JSON} \
|
| 44 |
+
--max_lines ${MAX_LINES} \
|
| 45 |
+
--model_max_length ${MODEL_MAX_LEN} \
|
| 46 |
+
--model_id ${MODEL_ID} \
|
| 47 |
+
--image_type ${IMAGE_TYPE} \
|
| 48 |
+
--emb_dim ${EMB_DIM} \
|
| 49 |
+
--out_dim ${OUT_DIM} \
|
| 50 |
+
--batch_size ${BATCH_SIZE} \
|
| 51 |
+
--query_text_require ${QUERY_TEXT} \
|
| 52 |
+
--doc_text_require ${DOC_TEXT} \
|
| 53 |
+
--lora ${LORA} \
|
| 54 |
+
--lora_pth ${LORA_PTH} \
|
| 55 |
+
--test_data_type ${TEST_DATA_TYPE} \
|
| 56 |
+
--all_eval ${ALL_EVAL} \
|
| 57 |
+
--prompt_index ${PROMPT_INDEX} \
|
| 58 |
+
--max_cot_new_tokens ${MAX_COT_NEW_TOKENS} \
|
| 59 |
+
--doc_append_eos ${DOC_APPEND_EOS} \
|
| 60 |
+
--save_cot_json ${SAVE_COT_JSON} \
|
| 61 |
+
--result_json ${RESULT_JSON}
|
code/multi_vlm2vec_train/cot_eval/scripts/eval_nebula_qwen_cot.sh
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# CoT embedding 评测 - Nebula 提交(query 先 generate 出 CoT 再取 embedding)
|
| 3 |
+
# Usage: sh cot_eval/scripts/eval_nebula_qwen_cot.sh
|
| 4 |
+
# 远程机器上 OSS 挂载在 /data/oss_bucket_0/,模型/ckpt/图片/结果都直接走本地路径
|
| 5 |
+
# 参数含义与 cot_eval/eval_config.py 一致,nebula 侧通过命令行传入
|
| 6 |
+
|
| 7 |
+
## 集群资源配置(单 worker 8 卡,accelerate 由 nebula 起的分布式环境自动识别)
|
| 8 |
+
CLUSTER_CONFIG='./cluster_cot_eval.json'
|
| 9 |
+
cat <<EOT > ${CLUSTER_CONFIG}
|
| 10 |
+
{
|
| 11 |
+
"worker": {
|
| 12 |
+
"gpu": 100,
|
| 13 |
+
"cpu": 1200,
|
| 14 |
+
"memory": 50000
|
| 15 |
+
}
|
| 16 |
+
}
|
| 17 |
+
EOT
|
| 18 |
+
|
| 19 |
+
WORKER_COUNT=8
|
| 20 |
+
|
| 21 |
+
## 模型设置(base 模型,与训练时的 model_local_path 一致)
|
| 22 |
+
MODEL_ID=/data/oss_bucket_0/peifeng/vlm2vec/models/qwen/Qwen3-VL-Embedding-2B/
|
| 23 |
+
EMB_DIM=2048
|
| 24 |
+
OUT_DIM=2048
|
| 25 |
+
|
| 26 |
+
## LoRA ckpt(训练产出)
|
| 27 |
+
LORA=True
|
| 28 |
+
YITU=shaixuan
|
| 29 |
+
RUN_DIR=/data/oss_bucket_0/liqi/cot_embedding/nebula_train/shaixuan_loraTrue_lr1e-5_btz256_ep4_candidate8_cot0.1_8gpu/train_qwen3vl_cot_lora_True_lmhead_True_epoch_4_lr1e-5_candidate8_cot0.1/
|
| 30 |
+
### ALL_EVAL=False 时只评 checkpoint-${CKPT};True 时遍历 RUN_DIR 下所有 checkpoint-*
|
| 31 |
+
ALL_EVAL=True
|
| 32 |
+
CKPT=3500
|
| 33 |
+
## python 侧按 lower() 解析,这里也忽略大小写,避免两侧判断不一致
|
| 34 |
+
ALL_EVAL_LOWER=$(echo "${ALL_EVAL}" | tr '[:upper:]' '[:lower:]')
|
| 35 |
+
if [ "${ALL_EVAL_LOWER}" = "true" ]; then
|
| 36 |
+
LORA_PTH=${RUN_DIR}
|
| 37 |
+
else
|
| 38 |
+
LORA_PTH=${RUN_DIR}/checkpoint-${CKPT}
|
| 39 |
+
fi
|
| 40 |
+
|
| 41 |
+
## 数据集设置(与 baseline 评测一致)
|
| 42 |
+
TEST_JSON=/data/oss_bucket_0/liqi/dataset/embedding_pf/${YITU}_test.json
|
| 43 |
+
TEST_DATA_TYPE=${YITU}
|
| 44 |
+
MAX_LINES=100000000
|
| 45 |
+
IMAGE_TYPE="both"
|
| 46 |
+
### 图片所在的 OSS 挂载目录
|
| 47 |
+
IMAGE_PATH_PREFIX=/data/oss_bucket_0/peifeng/multi_vlm2vec/dataset/merge/test_image
|
| 48 |
+
QUERY_TEXT=True
|
| 49 |
+
DOC_TEXT=True
|
| 50 |
+
BATCH_SIZE=128
|
| 51 |
+
|
| 52 |
+
## CoT 设置(需与训练配置保持一致)
|
| 53 |
+
PROMPT_INDEX=0
|
| 54 |
+
MAX_COT_NEW_TOKENS=192
|
| 55 |
+
DOC_APPEND_EOS=False
|
| 56 |
+
## query = prompt + cot,序列比纯 embedding 评测长
|
| 57 |
+
MODEL_MAX_LEN=2048
|
| 58 |
+
|
| 59 |
+
## 结果保存
|
| 60 |
+
## ALL_EVAL=True:每个 ckpt 的 cot 存成 checkpoint-xxx_cot.json(多文件),
|
| 61 |
+
## 指标全部汇总进 RESULT_JSON 一个文件:{checkpoint-xxx: results}
|
| 62 |
+
if [ "${ALL_EVAL_LOWER}" = "true" ]; then
|
| 63 |
+
SAVE_COT_JSON=${RUN_DIR}/eval_result/all/cot.json
|
| 64 |
+
RESULT_JSON=${RUN_DIR}/eval_result/all/metrics_${TEST_DATA_TYPE}.json
|
| 65 |
+
else
|
| 66 |
+
SAVE_COT_JSON=${RUN_DIR}/eval_result/ckpt-${CKPT}/cot2.json
|
| 67 |
+
RESULT_JSON=${RUN_DIR}/eval_result/ckpt-${CKPT}/metrics2.json
|
| 68 |
+
fi
|
| 69 |
+
|
| 70 |
+
echo "begin cot evaluation!"
|
| 71 |
+
|
| 72 |
+
args="\
|
| 73 |
+
--test_json ${TEST_JSON} \
|
| 74 |
+
--max_lines ${MAX_LINES} \
|
| 75 |
+
--model_max_length ${MODEL_MAX_LEN} \
|
| 76 |
+
--model_id ${MODEL_ID} \
|
| 77 |
+
--image_type ${IMAGE_TYPE} \
|
| 78 |
+
--image_path_prefix ${IMAGE_PATH_PREFIX} \
|
| 79 |
+
--emb_dim ${EMB_DIM} \
|
| 80 |
+
--out_dim ${OUT_DIM} \
|
| 81 |
+
--batch_size ${BATCH_SIZE} \
|
| 82 |
+
--query_text_require ${QUERY_TEXT} \
|
| 83 |
+
--doc_text_require ${DOC_TEXT} \
|
| 84 |
+
--lora ${LORA} \
|
| 85 |
+
--lora_pth ${LORA_PTH} \
|
| 86 |
+
--test_data_type ${TEST_DATA_TYPE} \
|
| 87 |
+
--all_eval ${ALL_EVAL} \
|
| 88 |
+
--prompt_index ${PROMPT_INDEX} \
|
| 89 |
+
--max_cot_new_tokens ${MAX_COT_NEW_TOKENS} \
|
| 90 |
+
--doc_append_eos ${DOC_APPEND_EOS} \
|
| 91 |
+
--save_cot_json ${SAVE_COT_JSON} \
|
| 92 |
+
--result_json ${RESULT_JSON}"
|
| 93 |
+
|
| 94 |
+
nebulactl run mdl \
|
| 95 |
+
--engine=xdl \
|
| 96 |
+
--ignore=venv/*,data/*,.git/* \
|
| 97 |
+
--worker_count=${WORKER_COUNT} \
|
| 98 |
+
--queue=pailitao_algo_high_2 \
|
| 99 |
+
--access_id=LTAI5tMZb5HHH6HHgAExAyiL \
|
| 100 |
+
--access_key=6MVP8JnTE01t4TLUHhPoFV0swZNTrb \
|
| 101 |
+
--entry=cot_eval/eval_tuwen_qwen3vl_cot.py \
|
| 102 |
+
--oss_access_id=LTAI5tMZb5HHH6HHgAExAyiL \
|
| 103 |
+
--oss_access_key=6MVP8JnTE01t4TLUHhPoFV0swZNTrb \
|
| 104 |
+
--oss_bucket=pailitao-ai \
|
| 105 |
+
--oss_endpoint=oss-cn-zhangjiakou-internal.aliyuncs.com \
|
| 106 |
+
--algo_name=pytorch2100 \
|
| 107 |
+
--file.cluster_file=${CLUSTER_CONFIG} \
|
| 108 |
+
--user_params="$args" \
|
| 109 |
+
--job_name="eval_qwen3vl_cot_dapei_full_single" \
|
| 110 |
+
--requirements_file_name="./requirements_eval.txt" \
|
| 111 |
+
--force
|
| 112 |
+
|
| 113 |
+
rm ${CLUSTER_CONFIG}
|
code/multi_vlm2vec_train/cot_gen/README.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CoT Data Generation for Embedding Model
|
| 2 |
+
|
| 3 |
+
使用本地 Qwen3.5-397B-A17B (vLLM) 为电商图搜 embedding 模型生成 Chain-of-Thought 数据。
|
| 4 |
+
|
| 5 |
+
## 文件说明
|
| 6 |
+
|
| 7 |
+
| 文件 | 功能 |
|
| 8 |
+
|------|------|
|
| 9 |
+
| `config.py` | 配置(模型路径、OSS、prompt模板等) |
|
| 10 |
+
| `generate_cot.py` | 主生成脚本(vLLM batch推理 + 断点续传) |
|
| 11 |
+
| `retry_failed.py` | 重试失败记录 |
|
| 12 |
+
| `merge_shards.py` | 合并分片输出 |
|
| 13 |
+
| `validate_cot.py` | 质量验证与统计 |
|
| 14 |
+
| `run.sh` | 启动脚本 |
|
| 15 |
+
|
| 16 |
+
## 快速开始
|
| 17 |
+
|
| 18 |
+
### 1. 安装依赖
|
| 19 |
+
|
| 20 |
+
```bash
|
| 21 |
+
pip install vllm oss2 pillow tqdm numpy
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
### 2. 小批量测试
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
cd /home/lyq494390/multi_vlm2vec_train/cot_gen
|
| 28 |
+
bash run.sh --test
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
### 3. 全量生成
|
| 32 |
+
|
| 33 |
+
```bash
|
| 34 |
+
# 全量(支持断点续传,中断后重新运行自动跳过已处理的)
|
| 35 |
+
bash run.sh
|
| 36 |
+
|
| 37 |
+
# 指定范围
|
| 38 |
+
bash run.sh --start 0 --end 100000
|
| 39 |
+
|
| 40 |
+
# 指定TP size
|
| 41 |
+
bash run.sh --tp 4
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
### 4. 验证质量
|
| 45 |
+
|
| 46 |
+
```bash
|
| 47 |
+
python validate_cot.py --cot_path /data/oss_bucket_0/liqi/dataset/embedding_pf/cot_output/zhaoxiangsi_train_cot.jsonl --num_samples 10
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
### 5. 重试失败记录
|
| 51 |
+
|
| 52 |
+
```bash
|
| 53 |
+
python retry_failed.py --failed_path /data/oss_bucket_0/liqi/dataset/embedding_pf/cot_output/failed_records.jsonl
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
## 输出格式
|
| 57 |
+
|
| 58 |
+
每行一条 JSONL:
|
| 59 |
+
|
| 60 |
+
```json
|
| 61 |
+
{
|
| 62 |
+
"rn": "037a6b4e192533b2e0dc9ab3fb692806",
|
| 63 |
+
"query_tfsid": "O1CN01velvra1klBlaW3SfK_!!4611686018427387507-0-imgsearch.jpg",
|
| 64 |
+
"query_bbox": "22 114 414 790",
|
| 65 |
+
"instruction": "更多类似碎花半身裙",
|
| 66 |
+
"cot": "图片中展示了一条碎花印花的A字半身裙,面料轻薄透气,裙身布满小碎花图案...",
|
| 67 |
+
"prompt_index": 0
|
| 68 |
+
}
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
## 资源说明
|
| 72 |
+
|
| 73 |
+
- 模型:`/data/oss_bucket_0/wuxiangyang/model/Qwen3.5-397B-A17B`
|
| 74 |
+
- 4x A800 80GB,tensor_parallel=4
|
| 75 |
+
- 图片通过 OSS bucket `pailitao-ai` 读取
|
| 76 |
+
- 原始数据约 80 万条记录,每条约 10 个 instruction,展开后约 800 万条 CoT 样本
|
| 77 |
+
|
| 78 |
+
## 注意事项
|
| 79 |
+
|
| 80 |
+
- 首次运行建议用 `bash run.sh --test` 验证图片加载和模型推理是否正常
|
| 81 |
+
- 支持断点续传:中断后重新运行会自动跳过已生成的记录
|
| 82 |
+
- 如果 OSS 图片路径与实际不符,修改 `generate_cot.py` 中 `get_image_from_oss` 的 `oss_path`
|
| 83 |
+
- `BATCH_SIZE` 默认64,如果显存不足可在 `config.py` 中调小
|
code/multi_vlm2vec_train/cot_gen/__pycache__/config.cpython-310.pyc
ADDED
|
Binary file (2.05 kB). View file
|
|
|
code/multi_vlm2vec_train/cot_gen/__pycache__/config.cpython-313.pyc
ADDED
|
Binary file (2.23 kB). View file
|
|
|
code/multi_vlm2vec_train/cot_gen/config.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configuration for CoT data generation (local vLLM inference)."""
|
| 2 |
+
|
| 3 |
+
# ========================= Model Config =========================
|
| 4 |
+
# MODEL_PATH = "/data/oss_bucket_0/wuxiangyang/model/Qwen3.5-397B-A17B"
|
| 5 |
+
MODEL_PATH = "/data/oss_bucket_0/planck/hf_models/Qwen3.6-27B"
|
| 6 |
+
TENSOR_PARALLEL_SIZE = 1 # 4x A800 80GB
|
| 7 |
+
GPU_MEMORY_UTILIZATION = 0.90 # vLLM GPU内存占用比例
|
| 8 |
+
MAX_MODEL_LEN = 16384 # 模型最大上下文长度
|
| 9 |
+
|
| 10 |
+
# ========================= Data Paths =========================
|
| 11 |
+
INPUT_PATH = "/data/oss_bucket_0/liqi/dataset/embedding_pf/shaixuan_train.json"
|
| 12 |
+
OUTPUT_DIR = "/data/oss_bucket_0/liqi/dataset/embedding_pf/cot_output_new/"
|
| 13 |
+
OUTPUT_PATH = "/data/oss_bucket_0/liqi/dataset/embedding_pf/cot_output_new/shaixuan_train_cot.jsonl"
|
| 14 |
+
FAILED_LOG_PATH = "/data/oss_bucket_0/liqi/dataset/embedding_pf/cot_output_new/failed_records.jsonl"
|
| 15 |
+
|
| 16 |
+
# ========================= Image Config =========================
|
| 17 |
+
# 本地图片存放目录,子路径为数据集中的 query_tfsid / pos_item_tfsids / neg_item_tfsids 字段
|
| 18 |
+
IMAGE_CDN_PREFIX = "/data/oss_bucket_0/peifeng/multi_vlm2vec/dataset/merge/image/"
|
| 19 |
+
# 单张图片最大像素数(宽x高),超过则等比缩放。Qwen3-VL每28x28 patch产生1个token
|
| 20 |
+
IMAGE_MAX_PIXELS = 1048576 # ~1024×1024,约1280 tokens/张
|
| 21 |
+
|
| 22 |
+
# ========================= Prompt Selection Config =========================
|
| 23 |
+
# "all": 将所有pos_prompts拆开,每个prompt都和query组成一个新样本(数据扩充)
|
| 24 |
+
# "random_one": 从pos_prompts中随机选择一条和图片组成样本,其余抛弃
|
| 25 |
+
PROMPT_SELECT_MODE = "random_one"
|
| 26 |
+
|
| 27 |
+
# ========================= Generation Config =========================
|
| 28 |
+
BATCH_SIZE = 32 # vLLM batch size
|
| 29 |
+
MAX_TOKENS = 128 # CoT生成的最大token数
|
| 30 |
+
TEMPERATURE = 0.7
|
| 31 |
+
TOP_P = 0.9
|
| 32 |
+
SAVE_INTERVAL = 500 # 每处理N条写入一次文件
|
| 33 |
+
|
| 34 |
+
# ========================= Prompt Template =========================
|
| 35 |
+
SYSTEM_PROMPT = """你是一个电商图片搜索的推理助手。给定查询图片和搜索指令,你需要直接输出一段极简的视觉描述文本,仅包含图片中与检索相关的核心视觉特征,用于生成检索向量。"""
|
| 36 |
+
|
| 37 |
+
COT_PROMPT_TEMPLATE = """用户上传了一张查询图片(第一张为原图,第二张为用户关注的裁剪区域),搜索指令为:"{instruction}"
|
| 38 |
+
|
| 39 |
+
以下商品标题仅帮助你理解图中物品是什么,不要在输出中提及这些标题:
|
| 40 |
+
{pos_titles}
|
| 41 |
+
|
| 42 |
+
请直接输出1-2句话,结合搜索指令的意图,描述图片中目标物品与指令相关的核心视觉特征(如品类、颜色、款式、材质、图案等),使输出文本能作为图片+指令的语义概括。
|
| 43 |
+
|
| 44 |
+
严格要求:
|
| 45 |
+
- 只输出1-2句视觉描述,不超过50字
|
| 46 |
+
- 重点描述与搜索指令相关的视觉特征,而非图片所有内容
|
| 47 |
+
- 直接描述你看到的内容,不要出现"用户想找""指令要求""参考标题"等分析性表述
|
| 48 |
+
- 不要复述搜索指令或商品标题原文
|
| 49 |
+
- 不要使用编号、分点或任何格式标记"""
|
code/multi_vlm2vec_train/cot_gen/generate_cot.py
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Generate CoT data for embedding model using local Qwen3.5-397B-A17B via vLLM.
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
# 本地测试(前100条)
|
| 6 |
+
python cot_gen/generate_cot.py --test
|
| 7 |
+
|
| 8 |
+
# 本地全量运行(断点续传)
|
| 9 |
+
python generate_cot.py --resume
|
| 10 |
+
|
| 11 |
+
# 指定范围(分片输出)
|
| 12 |
+
python cot_gen/generate_cot.py --start_idx 0 --end_idx 1000 --shard
|
| 13 |
+
|
| 14 |
+
# 通过 nebula 提交(自动分片,结束后运行 merge_shards.py 合并)
|
| 15 |
+
sh run_nebula.sh
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
import json
|
| 20 |
+
import argparse
|
| 21 |
+
import random
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
from PIL import Image
|
| 25 |
+
from tqdm import tqdm
|
| 26 |
+
from vllm import LLM, SamplingParams
|
| 27 |
+
|
| 28 |
+
from config import (
|
| 29 |
+
MODEL_PATH, TENSOR_PARALLEL_SIZE, GPU_MEMORY_UTILIZATION, MAX_MODEL_LEN,
|
| 30 |
+
INPUT_PATH, OUTPUT_DIR, OUTPUT_PATH, FAILED_LOG_PATH,
|
| 31 |
+
IMAGE_CDN_PREFIX, IMAGE_MAX_PIXELS, PROMPT_SELECT_MODE,
|
| 32 |
+
BATCH_SIZE, MAX_TOKENS, TEMPERATURE, TOP_P, SAVE_INTERVAL,
|
| 33 |
+
SYSTEM_PROMPT, COT_PROMPT_TEMPLATE,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def load_image_pair(image_name: str, bbox: str) -> tuple[Image.Image, Image.Image]:
|
| 38 |
+
"""Load original image and cropped image from local filesystem."""
|
| 39 |
+
image_path = os.path.join(IMAGE_CDN_PREFIX, image_name)
|
| 40 |
+
original = Image.open(image_path)
|
| 41 |
+
if original.mode != "RGB":
|
| 42 |
+
original = original.convert("RGB")
|
| 43 |
+
|
| 44 |
+
if bbox and bbox != "ori":
|
| 45 |
+
parts = bbox.split()
|
| 46 |
+
if len(parts) >= 4:
|
| 47 |
+
xmin, ymin, xmax, ymax = [int(float(z)) for z in parts[:4]]
|
| 48 |
+
xmin = max(0, xmin)
|
| 49 |
+
xmax = min(original.width - 1, xmax)
|
| 50 |
+
ymin = max(0, ymin)
|
| 51 |
+
ymax = min(original.height - 1, ymax)
|
| 52 |
+
if (ymax - ymin) > 2 and (xmax - xmin) > 2:
|
| 53 |
+
cropped = original.crop((xmin, ymin, xmax, ymax))
|
| 54 |
+
else:
|
| 55 |
+
cropped = original.copy()
|
| 56 |
+
else:
|
| 57 |
+
cropped = original.copy()
|
| 58 |
+
else:
|
| 59 |
+
cropped = original.copy()
|
| 60 |
+
|
| 61 |
+
return original, cropped
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def parse_records(raw_data: list[dict]) -> list[dict]:
|
| 65 |
+
"""
|
| 66 |
+
Parse raw records into individual samples.
|
| 67 |
+
Behavior depends on PROMPT_SELECT_MODE:
|
| 68 |
+
- "all": each prompt in pos_prompts becomes a separate sample (data augmentation)
|
| 69 |
+
- "random_one": randomly pick one prompt per record
|
| 70 |
+
"""
|
| 71 |
+
all_samples = []
|
| 72 |
+
for record in raw_data:
|
| 73 |
+
query_tfsid = record["query_tfsid"]
|
| 74 |
+
query_bbox = record["query_bbox"]
|
| 75 |
+
rn = record["rn"]
|
| 76 |
+
|
| 77 |
+
pos_prompts = record["pos_prompts"].split("##")
|
| 78 |
+
pos_titles_list = record["pos_item_titles"].split("##")
|
| 79 |
+
pos_tfsids_list = record["pos_item_tfsids"].split("##")
|
| 80 |
+
pos_bboxs_list = record["pos_item_bboxs"].split("##")
|
| 81 |
+
|
| 82 |
+
neg_tfsids_list = [x for x in record.get("neg_item_tfsids", "").split("##") if x.strip()]
|
| 83 |
+
neg_titles_list = [x for x in record.get("neg_item_titles", "").split("##") if x.strip()]
|
| 84 |
+
neg_bboxs_list = [x for x in record.get("neg_item_bboxs", "").split("##") if x.strip()]
|
| 85 |
+
|
| 86 |
+
def pick_random_neg():
|
| 87 |
+
if not neg_tfsids_list:
|
| 88 |
+
return "", "", ""
|
| 89 |
+
idx = random.randint(0, len(neg_tfsids_list) - 1)
|
| 90 |
+
tfsid = neg_tfsids_list[idx]
|
| 91 |
+
title = neg_titles_list[idx] if idx < len(neg_titles_list) else ""
|
| 92 |
+
bbox = neg_bboxs_list[idx] if idx < len(neg_bboxs_list) else ""
|
| 93 |
+
return tfsid, title, bbox
|
| 94 |
+
|
| 95 |
+
def build_sample(i):
|
| 96 |
+
title_indices = [max(0, i - 1), i, min(len(pos_titles_list) - 1, i + 1)]
|
| 97 |
+
ref_titles = list(dict.fromkeys(
|
| 98 |
+
pos_titles_list[idx] for idx in title_indices if idx < len(pos_titles_list)
|
| 99 |
+
))
|
| 100 |
+
neg_tfsid, neg_title, neg_bbox = pick_random_neg()
|
| 101 |
+
return {
|
| 102 |
+
"rn": rn,
|
| 103 |
+
"query_tfsid": query_tfsid,
|
| 104 |
+
"query_bbox": query_bbox,
|
| 105 |
+
"instruction": pos_prompts[i].strip(),
|
| 106 |
+
"pos_titles_ref": ref_titles,
|
| 107 |
+
"prompt_index": i,
|
| 108 |
+
"pos_item_tfsid": pos_tfsids_list[i] if i < len(pos_tfsids_list) else "",
|
| 109 |
+
"pos_item_title": pos_titles_list[i] if i < len(pos_titles_list) else "",
|
| 110 |
+
"pos_item_bbox": pos_bboxs_list[i] if i < len(pos_bboxs_list) else "",
|
| 111 |
+
"neg_item_tfsid": neg_tfsid,
|
| 112 |
+
"neg_item_title": neg_title,
|
| 113 |
+
"neg_item_bbox": neg_bbox,
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
if PROMPT_SELECT_MODE == "random_one":
|
| 117 |
+
valid_indices = [i for i, p in enumerate(pos_prompts) if p.strip()]
|
| 118 |
+
if not valid_indices:
|
| 119 |
+
continue
|
| 120 |
+
i = random.choice(valid_indices)
|
| 121 |
+
all_samples.append(build_sample(i))
|
| 122 |
+
else:
|
| 123 |
+
for i, prompt in enumerate(pos_prompts):
|
| 124 |
+
if not prompt.strip():
|
| 125 |
+
continue
|
| 126 |
+
all_samples.append(build_sample(i))
|
| 127 |
+
|
| 128 |
+
return all_samples
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def build_vllm_prompt(sample: dict) -> str:
|
| 132 |
+
"""Build the text prompt part for vLLM (image is passed separately)."""
|
| 133 |
+
instruction = sample["instruction"]
|
| 134 |
+
pos_titles = "\n".join(f"- {t}" for t in sample["pos_titles_ref"])
|
| 135 |
+
|
| 136 |
+
user_text = COT_PROMPT_TEMPLATE.format(
|
| 137 |
+
instruction=instruction,
|
| 138 |
+
pos_titles=pos_titles,
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
return user_text
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def build_messages(sample: dict, original: Image.Image, cropped: Image.Image) -> list[dict]:
|
| 145 |
+
"""Build chat messages for vLLM with original and cropped images."""
|
| 146 |
+
user_text = build_vllm_prompt(sample)
|
| 147 |
+
|
| 148 |
+
messages = [
|
| 149 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 150 |
+
{
|
| 151 |
+
"role": "user",
|
| 152 |
+
"content": [
|
| 153 |
+
{"type": "image_pil", "image_pil": original},
|
| 154 |
+
{"type": "image_pil", "image_pil": cropped},
|
| 155 |
+
{"type": "text", "text": user_text},
|
| 156 |
+
],
|
| 157 |
+
},
|
| 158 |
+
]
|
| 159 |
+
return messages
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def load_processed_keys(output_path: str) -> set:
|
| 163 |
+
"""Load already processed (rn, prompt_index) pairs for resume."""
|
| 164 |
+
processed = set()
|
| 165 |
+
if os.path.exists(output_path):
|
| 166 |
+
with open(output_path, "r", encoding="utf-8") as f:
|
| 167 |
+
for line in f:
|
| 168 |
+
if line.strip():
|
| 169 |
+
try:
|
| 170 |
+
item = json.loads(line)
|
| 171 |
+
processed.add((item["rn"], item["prompt_index"]))
|
| 172 |
+
except (json.JSONDecodeError, KeyError):
|
| 173 |
+
continue
|
| 174 |
+
return processed
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def save_results(results: list[dict], output_path: str):
|
| 178 |
+
"""Append results to JSONL file."""
|
| 179 |
+
with open(output_path, "a", encoding="utf-8") as f:
|
| 180 |
+
for item in results:
|
| 181 |
+
f.write(json.dumps(item, ensure_ascii=False) + "\n")
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def save_failed(failed_samples: list[dict], failed_path: str):
|
| 185 |
+
"""Append failed samples to log."""
|
| 186 |
+
with open(failed_path, "a", encoding="utf-8") as f:
|
| 187 |
+
for item in failed_samples:
|
| 188 |
+
f.write(json.dumps(item, ensure_ascii=False) + "\n")
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def main(args):
|
| 192 |
+
# Load data
|
| 193 |
+
print(f"Loading data from {INPUT_PATH} ...")
|
| 194 |
+
with open(INPUT_PATH, "r", encoding="utf-8") as f:
|
| 195 |
+
raw_data = json.load(f)
|
| 196 |
+
print(f"Total raw records: {len(raw_data)}")
|
| 197 |
+
|
| 198 |
+
# Slice
|
| 199 |
+
end_idx = len(raw_data) if args.end_idx < 0 else min(args.end_idx, len(raw_data))
|
| 200 |
+
raw_data = raw_data[args.start_idx:end_idx]
|
| 201 |
+
print(f"Processing records [{args.start_idx}, {end_idx})")
|
| 202 |
+
|
| 203 |
+
# Parse into samples
|
| 204 |
+
all_samples = parse_records(raw_data)
|
| 205 |
+
print(f"Prompt select mode: {PROMPT_SELECT_MODE}")
|
| 206 |
+
print(f"Total samples (query x instruction pairs): {len(all_samples)}")
|
| 207 |
+
|
| 208 |
+
# Output setup
|
| 209 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 210 |
+
|
| 211 |
+
if args.shard:
|
| 212 |
+
base, ext = os.path.splitext(OUTPUT_PATH)
|
| 213 |
+
output_path = f"{base}_{args.start_idx}_{end_idx}{ext}"
|
| 214 |
+
failed_path = f"{base}_{args.start_idx}_{end_idx}_failed{ext}"
|
| 215 |
+
else:
|
| 216 |
+
output_path = OUTPUT_PATH
|
| 217 |
+
failed_path = FAILED_LOG_PATH
|
| 218 |
+
|
| 219 |
+
# Resume
|
| 220 |
+
if args.resume:
|
| 221 |
+
processed = load_processed_keys(output_path)
|
| 222 |
+
before = len(all_samples)
|
| 223 |
+
all_samples = [
|
| 224 |
+
s for s in all_samples
|
| 225 |
+
if (s["rn"], s["prompt_index"]) not in processed
|
| 226 |
+
]
|
| 227 |
+
print(f"Resume: skipping {before - len(all_samples)} processed, {len(all_samples)} remaining")
|
| 228 |
+
|
| 229 |
+
if not all_samples:
|
| 230 |
+
print("No samples to process. Done.")
|
| 231 |
+
return
|
| 232 |
+
|
| 233 |
+
# Initialize vLLM
|
| 234 |
+
print(f"Loading model from {MODEL_PATH} ...")
|
| 235 |
+
print(f" tensor_parallel_size={args.tp or TENSOR_PARALLEL_SIZE}")
|
| 236 |
+
print(f" gpu_memory_utilization={GPU_MEMORY_UTILIZATION}")
|
| 237 |
+
print(f" image_dir={IMAGE_CDN_PREFIX}")
|
| 238 |
+
|
| 239 |
+
llm = LLM(
|
| 240 |
+
model=MODEL_PATH,
|
| 241 |
+
tensor_parallel_size=args.tp or TENSOR_PARALLEL_SIZE,
|
| 242 |
+
gpu_memory_utilization=GPU_MEMORY_UTILIZATION,
|
| 243 |
+
max_model_len=MAX_MODEL_LEN,
|
| 244 |
+
trust_remote_code=True,
|
| 245 |
+
dtype="bfloat16",
|
| 246 |
+
limit_mm_per_prompt={"image": 2},
|
| 247 |
+
mm_processor_kwargs={"max_pixels": IMAGE_MAX_PIXELS},
|
| 248 |
+
enable_prefix_caching=True,
|
| 249 |
+
)
|
| 250 |
+
sampling_params = SamplingParams(
|
| 251 |
+
max_tokens=MAX_TOKENS,
|
| 252 |
+
temperature=TEMPERATURE,
|
| 253 |
+
top_p=TOP_P,
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
print(f"Model loaded. Starting generation...")
|
| 257 |
+
print(f"Output: {output_path}")
|
| 258 |
+
|
| 259 |
+
# Process in batches
|
| 260 |
+
total_success = 0
|
| 261 |
+
total_failed = 0
|
| 262 |
+
batch_results = []
|
| 263 |
+
|
| 264 |
+
for batch_start in tqdm(range(0, len(all_samples), BATCH_SIZE), desc="Batches"):
|
| 265 |
+
batch_samples = all_samples[batch_start:batch_start + BATCH_SIZE]
|
| 266 |
+
|
| 267 |
+
# Prepare batch inputs: load images and build prompts
|
| 268 |
+
valid_samples = []
|
| 269 |
+
batch_inputs = []
|
| 270 |
+
|
| 271 |
+
for sample in batch_samples:
|
| 272 |
+
try:
|
| 273 |
+
original, cropped = load_image_pair(sample["query_tfsid"], sample["query_bbox"])
|
| 274 |
+
messages = build_messages(sample, original, cropped)
|
| 275 |
+
valid_samples.append(sample)
|
| 276 |
+
batch_inputs.append(messages)
|
| 277 |
+
except Exception as e:
|
| 278 |
+
total_failed += 1
|
| 279 |
+
save_failed([{**sample, "error": f"image_load: {str(e)}"}], failed_path)
|
| 280 |
+
|
| 281 |
+
if not batch_inputs:
|
| 282 |
+
continue
|
| 283 |
+
|
| 284 |
+
# vLLM batch inference using chat interface
|
| 285 |
+
try:
|
| 286 |
+
outputs = llm.chat(
|
| 287 |
+
messages=batch_inputs,
|
| 288 |
+
sampling_params=sampling_params,
|
| 289 |
+
chat_template_kwargs={"enable_thinking": False},
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
for sample, output in zip(valid_samples, outputs):
|
| 293 |
+
generated_text = output.outputs[0].text.strip()
|
| 294 |
+
|
| 295 |
+
if generated_text and len(generated_text) >= 10:
|
| 296 |
+
result = {
|
| 297 |
+
"rn": sample["rn"],
|
| 298 |
+
"query_tfsid": sample["query_tfsid"],
|
| 299 |
+
"query_bbox": sample["query_bbox"],
|
| 300 |
+
"instruction": sample["instruction"],
|
| 301 |
+
"cot": generated_text,
|
| 302 |
+
"prompt_index": sample["prompt_index"],
|
| 303 |
+
"pos_item_tfsid": sample["pos_item_tfsid"],
|
| 304 |
+
"pos_item_title": sample["pos_item_title"],
|
| 305 |
+
"pos_item_bbox": sample["pos_item_bbox"],
|
| 306 |
+
"neg_item_tfsid": sample["neg_item_tfsid"],
|
| 307 |
+
"neg_item_title": sample["neg_item_title"],
|
| 308 |
+
"neg_item_bbox": sample["neg_item_bbox"],
|
| 309 |
+
}
|
| 310 |
+
batch_results.append(result)
|
| 311 |
+
total_success += 1
|
| 312 |
+
else:
|
| 313 |
+
total_failed += 1
|
| 314 |
+
save_failed([{**sample, "error": f"short_output: {generated_text}"}], failed_path)
|
| 315 |
+
|
| 316 |
+
except Exception as e:
|
| 317 |
+
print(f"Batch inference error: {e}")
|
| 318 |
+
total_failed += len(valid_samples)
|
| 319 |
+
for sample in valid_samples:
|
| 320 |
+
save_failed([{**sample, "error": f"inference: {str(e)}"}], failed_path)
|
| 321 |
+
|
| 322 |
+
# Periodic save
|
| 323 |
+
if len(batch_results) >= SAVE_INTERVAL:
|
| 324 |
+
save_results(batch_results, output_path)
|
| 325 |
+
batch_results = []
|
| 326 |
+
|
| 327 |
+
# Save remaining
|
| 328 |
+
if batch_results:
|
| 329 |
+
save_results(batch_results, output_path)
|
| 330 |
+
|
| 331 |
+
print(f"\nDone! Success: {total_success}, Failed: {total_failed}")
|
| 332 |
+
print(f"Output: {output_path}")
|
| 333 |
+
if total_failed > 0:
|
| 334 |
+
print(f"Failed log: {failed_path}")
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
if __name__ == "__main__":
|
| 338 |
+
parser = argparse.ArgumentParser(description="Generate CoT data using local Qwen3.5-397B-A17B")
|
| 339 |
+
parser.add_argument("--test", action="store_true", help="Test mode: process first 100 records")
|
| 340 |
+
parser.add_argument("--start_idx", type=int, default=0, help="Start index of raw records")
|
| 341 |
+
parser.add_argument("--end_idx", type=int, default=-1, help="End index (-1 for all)")
|
| 342 |
+
parser.add_argument("--tp", type=int, default=None, help="Override tensor_parallel_size")
|
| 343 |
+
parser.add_argument("--resume", action="store_true", help="Resume from previous progress")
|
| 344 |
+
parser.add_argument("--shard", action="store_true", help="Shard output by index range")
|
| 345 |
+
args = parser.parse_args()
|
| 346 |
+
|
| 347 |
+
if args.test:
|
| 348 |
+
args.start_idx = 0
|
| 349 |
+
args.end_idx = 100
|
| 350 |
+
args.resume = False
|
| 351 |
+
else:
|
| 352 |
+
# Auto-shard based on RANK/WORLD_SIZE env vars (set by nebula/distributed launcher)
|
| 353 |
+
rank = int(os.environ.get("RANK", os.environ.get("INDEX", 0)))
|
| 354 |
+
world_size = int(os.environ.get("WORLD_SIZE", os.environ.get("WORKER_NUM", 1)))
|
| 355 |
+
if world_size > 1:
|
| 356 |
+
with open(INPUT_PATH, "r", encoding="utf-8") as f:
|
| 357 |
+
total_records = len(json.load(f))
|
| 358 |
+
if args.end_idx < 0:
|
| 359 |
+
args.end_idx = total_records
|
| 360 |
+
total = min(args.end_idx, total_records) - args.start_idx
|
| 361 |
+
shard_size = (total + world_size - 1) // world_size
|
| 362 |
+
args.start_idx = args.start_idx + rank * shard_size
|
| 363 |
+
args.end_idx = min(args.start_idx + shard_size, total_records)
|
| 364 |
+
args.shard = True
|
| 365 |
+
print(f"[Auto-shard] rank={rank}, world_size={world_size}, "
|
| 366 |
+
f"processing [{args.start_idx}, {args.end_idx})")
|
| 367 |
+
|
| 368 |
+
main(args)
|
code/multi_vlm2vec_train/cot_gen/merge_shards.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Merge shard outputs from distributed CoT generation into a single JSON file.
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
# 合并指定前缀的分片(如 bianji_train_cot)
|
| 6 |
+
python cot_gen/merge_shards.py --prefix bianji_train_cot --input_dir /data/oss_bucket_0/liqi/dataset/embedding_pf/cot_output2/ --format json
|
| 7 |
+
|
| 8 |
+
# 指定输入目录
|
| 9 |
+
python cot_gen/merge_shards.py --prefix dapei_train_cot --input_dir /path/to/shards
|
| 10 |
+
|
| 11 |
+
# 输出为jsonl格式
|
| 12 |
+
python cot_gen/merge_shards.py --prefix bianji_train_cot --format jsonl
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import re
|
| 17 |
+
import json
|
| 18 |
+
import argparse
|
| 19 |
+
from config import OUTPUT_DIR
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def find_shard_files(input_dir: str, prefix: str) -> list[str]:
|
| 23 |
+
"""Find all shard files matching the prefix pattern (excluding failed files)."""
|
| 24 |
+
pattern = re.compile(rf"^{re.escape(prefix)}_\d+_\d+\.jsonl$")
|
| 25 |
+
|
| 26 |
+
shard_files = []
|
| 27 |
+
for fname in os.listdir(input_dir):
|
| 28 |
+
if pattern.match(fname):
|
| 29 |
+
shard_files.append(os.path.join(input_dir, fname))
|
| 30 |
+
|
| 31 |
+
shard_files.sort(key=lambda f: int(re.search(r"_(\d+)_\d+\.jsonl$", f).group(1)))
|
| 32 |
+
return shard_files
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def merge(args):
|
| 36 |
+
input_dir = args.input_dir or OUTPUT_DIR
|
| 37 |
+
prefix = args.prefix
|
| 38 |
+
|
| 39 |
+
shard_files = find_shard_files(input_dir, prefix)
|
| 40 |
+
|
| 41 |
+
if not shard_files:
|
| 42 |
+
print(f"No shard files found with prefix '{prefix}' in {input_dir}")
|
| 43 |
+
return
|
| 44 |
+
|
| 45 |
+
print(f"Found {len(shard_files)} shard files:")
|
| 46 |
+
for f in shard_files:
|
| 47 |
+
print(f" {os.path.basename(f)}")
|
| 48 |
+
|
| 49 |
+
all_results = []
|
| 50 |
+
seen_keys = set()
|
| 51 |
+
duplicates = 0
|
| 52 |
+
|
| 53 |
+
for shard_path in shard_files:
|
| 54 |
+
with open(shard_path, "r", encoding="utf-8") as f:
|
| 55 |
+
for line in f:
|
| 56 |
+
if not line.strip():
|
| 57 |
+
continue
|
| 58 |
+
item = json.loads(line)
|
| 59 |
+
key = (item["rn"], item["prompt_index"])
|
| 60 |
+
if key in seen_keys:
|
| 61 |
+
duplicates += 1
|
| 62 |
+
continue
|
| 63 |
+
seen_keys.add(key)
|
| 64 |
+
all_results.append(item)
|
| 65 |
+
|
| 66 |
+
if args.format == "json":
|
| 67 |
+
merged_path = os.path.join(input_dir, f"{prefix}.json")
|
| 68 |
+
with open(merged_path, "w", encoding="utf-8") as f:
|
| 69 |
+
json.dump(all_results, f, ensure_ascii=False, indent=2)
|
| 70 |
+
else:
|
| 71 |
+
merged_path = os.path.join(input_dir, f"{prefix}.jsonl")
|
| 72 |
+
with open(merged_path, "w", encoding="utf-8") as f:
|
| 73 |
+
for item in all_results:
|
| 74 |
+
f.write(json.dumps(item, ensure_ascii=False) + "\n")
|
| 75 |
+
|
| 76 |
+
print(f"\nMerged {len(all_results)} records -> {merged_path}")
|
| 77 |
+
if duplicates > 0:
|
| 78 |
+
print(f"Skipped {duplicates} duplicate records")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
if __name__ == "__main__":
|
| 82 |
+
parser = argparse.ArgumentParser(description="Merge CoT shard outputs by prefix")
|
| 83 |
+
parser.add_argument("--prefix", type=str, required=True,
|
| 84 |
+
help="Shard file prefix (e.g. bianji_train_cot, dapei_train_cot)")
|
| 85 |
+
parser.add_argument("--input_dir", type=str, default=None,
|
| 86 |
+
help="Directory containing shard files (default: OUTPUT_DIR from config)")
|
| 87 |
+
parser.add_argument("--format", choices=["json", "jsonl"], default="json",
|
| 88 |
+
help="Output format: json (single array) or jsonl (one per line)")
|
| 89 |
+
args = parser.parse_args()
|
| 90 |
+
merge(args)
|
code/multi_vlm2vec_train/cot_gen/retry_failed.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Retry failed records using local vLLM inference.
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
python retry_failed.py --failed_path /path/to/failed_records.jsonl
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
import json
|
| 10 |
+
import argparse
|
| 11 |
+
|
| 12 |
+
from PIL import Image
|
| 13 |
+
from tqdm import tqdm
|
| 14 |
+
from vllm import LLM, SamplingParams
|
| 15 |
+
|
| 16 |
+
from config import (
|
| 17 |
+
MODEL_PATH, TENSOR_PARALLEL_SIZE, GPU_MEMORY_UTILIZATION, MAX_MODEL_LEN,
|
| 18 |
+
BATCH_SIZE, MAX_TOKENS, TEMPERATURE, TOP_P,
|
| 19 |
+
SYSTEM_PROMPT, COT_PROMPT_TEMPLATE,
|
| 20 |
+
)
|
| 21 |
+
from generate_cot import (
|
| 22 |
+
load_image_pair, build_messages, save_results,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def main(args):
|
| 27 |
+
# Load failed records
|
| 28 |
+
failed_samples = []
|
| 29 |
+
with open(args.failed_path, "r", encoding="utf-8") as f:
|
| 30 |
+
for line in f:
|
| 31 |
+
if line.strip():
|
| 32 |
+
try:
|
| 33 |
+
item = json.loads(line)
|
| 34 |
+
item.pop("error", None)
|
| 35 |
+
failed_samples.append(item)
|
| 36 |
+
except json.JSONDecodeError:
|
| 37 |
+
continue
|
| 38 |
+
|
| 39 |
+
print(f"Loaded {len(failed_samples)} failed records to retry")
|
| 40 |
+
if not failed_samples:
|
| 41 |
+
return
|
| 42 |
+
|
| 43 |
+
base, ext = os.path.splitext(args.failed_path)
|
| 44 |
+
output_path = base.replace("_failed", "") + "_retried" + ext
|
| 45 |
+
still_failed_path = base + "_still_failed" + ext
|
| 46 |
+
|
| 47 |
+
# Init
|
| 48 |
+
llm = LLM(
|
| 49 |
+
model=MODEL_PATH,
|
| 50 |
+
tensor_parallel_size=args.tp or TENSOR_PARALLEL_SIZE,
|
| 51 |
+
gpu_memory_utilization=GPU_MEMORY_UTILIZATION,
|
| 52 |
+
max_model_len=MAX_MODEL_LEN,
|
| 53 |
+
trust_remote_code=True,
|
| 54 |
+
dtype="bfloat16",
|
| 55 |
+
limit_mm_per_prompt={"image": 2},
|
| 56 |
+
)
|
| 57 |
+
sampling_params = SamplingParams(
|
| 58 |
+
max_tokens=MAX_TOKENS,
|
| 59 |
+
temperature=TEMPERATURE,
|
| 60 |
+
top_p=TOP_P,
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
total_success = 0
|
| 64 |
+
total_failed = 0
|
| 65 |
+
results = []
|
| 66 |
+
still_failed = []
|
| 67 |
+
|
| 68 |
+
for batch_start in tqdm(range(0, len(failed_samples), BATCH_SIZE), desc="Retrying"):
|
| 69 |
+
batch = failed_samples[batch_start:batch_start + BATCH_SIZE]
|
| 70 |
+
|
| 71 |
+
valid_samples = []
|
| 72 |
+
batch_inputs = []
|
| 73 |
+
for sample in batch:
|
| 74 |
+
try:
|
| 75 |
+
original, cropped = load_image_pair(sample["query_tfsid"], sample["query_bbox"])
|
| 76 |
+
messages = build_messages(sample, original, cropped)
|
| 77 |
+
valid_samples.append(sample)
|
| 78 |
+
batch_inputs.append(messages)
|
| 79 |
+
except Exception:
|
| 80 |
+
still_failed.append(sample)
|
| 81 |
+
total_failed += 1
|
| 82 |
+
|
| 83 |
+
if not batch_inputs:
|
| 84 |
+
continue
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
outputs = llm.chat(messages=batch_inputs, sampling_params=sampling_params)
|
| 88 |
+
for sample, output in zip(valid_samples, outputs):
|
| 89 |
+
text = output.outputs[0].text.strip()
|
| 90 |
+
if text and len(text) >= 10:
|
| 91 |
+
results.append({
|
| 92 |
+
"rn": sample["rn"],
|
| 93 |
+
"query_tfsid": sample["query_tfsid"],
|
| 94 |
+
"query_bbox": sample["query_bbox"],
|
| 95 |
+
"instruction": sample["instruction"],
|
| 96 |
+
"cot": text,
|
| 97 |
+
"prompt_index": sample["prompt_index"],
|
| 98 |
+
})
|
| 99 |
+
total_success += 1
|
| 100 |
+
else:
|
| 101 |
+
still_failed.append(sample)
|
| 102 |
+
total_failed += 1
|
| 103 |
+
except Exception:
|
| 104 |
+
still_failed.extend(valid_samples)
|
| 105 |
+
total_failed += len(valid_samples)
|
| 106 |
+
|
| 107 |
+
if results:
|
| 108 |
+
save_results(results, output_path)
|
| 109 |
+
if still_failed:
|
| 110 |
+
with open(still_failed_path, "w", encoding="utf-8") as f:
|
| 111 |
+
for item in still_failed:
|
| 112 |
+
f.write(json.dumps(item, ensure_ascii=False) + "\n")
|
| 113 |
+
|
| 114 |
+
print(f"\nRetry done! Success: {total_success}, Still failed: {total_failed}")
|
| 115 |
+
if total_success > 0:
|
| 116 |
+
print(f"Results: {output_path}")
|
| 117 |
+
if total_failed > 0:
|
| 118 |
+
print(f"Still failed: {still_failed_path}")
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
if __name__ == "__main__":
|
| 122 |
+
parser = argparse.ArgumentParser()
|
| 123 |
+
parser.add_argument("--failed_path", type=str, required=True)
|
| 124 |
+
parser.add_argument("--tp", type=int, default=None)
|
| 125 |
+
args = parser.parse_args()
|
| 126 |
+
main(args)
|
code/multi_vlm2vec_train/cot_gen/run_nebula.sh
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# CoT Generation - Nebula Submission
|
| 3 |
+
# Usage: sh cot_gen/run_nebula.sh
|
| 4 |
+
|
| 5 |
+
CLUSTER_CONFIG='./cluster.json'
|
| 6 |
+
cat <<EOT > ${CLUSTER_CONFIG}
|
| 7 |
+
{
|
| 8 |
+
"worker": {
|
| 9 |
+
"gpu": 100,
|
| 10 |
+
"cpu": 1200,
|
| 11 |
+
"memory": 50000
|
| 12 |
+
}
|
| 13 |
+
}
|
| 14 |
+
EOT
|
| 15 |
+
|
| 16 |
+
WORKER_COUNT=8
|
| 17 |
+
|
| 18 |
+
args="--resume"
|
| 19 |
+
nebulactl run mdl --engine=xdl \
|
| 20 |
+
--refresh \
|
| 21 |
+
--ignore=data/*,.git/* \
|
| 22 |
+
--queue=pailitao_algo_high_2 \
|
| 23 |
+
--worker_count=$WORKER_COUNT \
|
| 24 |
+
--odps_project=pailitao_algo_high_2 \
|
| 25 |
+
--entry="./cot_gen/generate_cot.py" \
|
| 26 |
+
--oss_access_id=LTAI5tMZb5HHH6HHgAExAyiL \
|
| 27 |
+
--oss_access_key=6MVP8JnTE01t4TLUHhPoFV0swZNTrb \
|
| 28 |
+
--oss_bucket=pailitao-ai \
|
| 29 |
+
--oss_endpoint=oss-cn-zhangjiakou-internal.aliyuncs.com \
|
| 30 |
+
--algo_name=pytorch2100 \
|
| 31 |
+
--user_params="$args" \
|
| 32 |
+
--job_name=shaixuan-cot-gen-qwen36-27b \
|
| 33 |
+
--file.cluster_file=$CLUSTER_CONFIG \
|
| 34 |
+
--force \
|
| 35 |
+
--max_failover_times=2 \
|
| 36 |
+
--requirements_file_name="./requirements.txt"
|
| 37 |
+
|
| 38 |
+
rm ${CLUSTER_CONFIG}
|
code/multi_vlm2vec_train/cot_gen/validate_cot.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Validate generated CoT data quality.
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
python validate_cot.py --cot_path /path/to/cot.jsonl --num_samples 10
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import argparse
|
| 10 |
+
import numpy as np
|
| 11 |
+
from collections import Counter
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def load_cot_data(path: str) -> list:
|
| 15 |
+
data = []
|
| 16 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 17 |
+
for line in f:
|
| 18 |
+
if line.strip():
|
| 19 |
+
try:
|
| 20 |
+
data.append(json.loads(line))
|
| 21 |
+
except json.JSONDecodeError:
|
| 22 |
+
continue
|
| 23 |
+
return data
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def basic_stats(data: list):
|
| 27 |
+
print(f"\n{'='*60}")
|
| 28 |
+
print(f" Basic Statistics")
|
| 29 |
+
print(f"{'='*60}")
|
| 30 |
+
print(f"Total records: {len(data)}")
|
| 31 |
+
|
| 32 |
+
cot_lengths = [len(item["cot"]) for item in data]
|
| 33 |
+
print(f"\nCoT Length (chars):")
|
| 34 |
+
print(f" Mean: {np.mean(cot_lengths):.1f}")
|
| 35 |
+
print(f" Median: {np.median(cot_lengths):.1f}")
|
| 36 |
+
print(f" Min: {np.min(cot_lengths)}")
|
| 37 |
+
print(f" Max: {np.max(cot_lengths)}")
|
| 38 |
+
print(f" Std: {np.std(cot_lengths):.1f}")
|
| 39 |
+
|
| 40 |
+
short_threshold = 30
|
| 41 |
+
short_count = sum(1 for l in cot_lengths if l < short_threshold)
|
| 42 |
+
print(f"\n Short CoTs (<{short_threshold} chars): {short_count} ({short_count/len(data)*100:.2f}%)")
|
| 43 |
+
|
| 44 |
+
unique_rns = set(item["rn"] for item in data)
|
| 45 |
+
print(f"\nUnique query records covered: {len(unique_rns)}")
|
| 46 |
+
|
| 47 |
+
rn_counts = Counter(item["rn"] for item in data)
|
| 48 |
+
print(f"Instructions per record: mean={np.mean(list(rn_counts.values())):.1f}")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def show_samples(data: list, num_samples: int = 5):
|
| 52 |
+
print(f"\n{'='*60}")
|
| 53 |
+
print(f" Random Samples")
|
| 54 |
+
print(f"{'='*60}")
|
| 55 |
+
|
| 56 |
+
indices = np.random.choice(len(data), min(num_samples, len(data)), replace=False)
|
| 57 |
+
for idx in indices:
|
| 58 |
+
item = data[idx]
|
| 59 |
+
print(f"\n--- Sample (rn={item['rn'][:8]}..., idx={item['prompt_index']}) ---")
|
| 60 |
+
print(f"Instruction: {item['instruction']}")
|
| 61 |
+
print(f"CoT: {item['cot']}")
|
| 62 |
+
print()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def main(args):
|
| 66 |
+
print(f"Loading CoT data from: {args.cot_path}")
|
| 67 |
+
data = load_cot_data(args.cot_path)
|
| 68 |
+
|
| 69 |
+
if not data:
|
| 70 |
+
print("No data loaded!")
|
| 71 |
+
return
|
| 72 |
+
|
| 73 |
+
basic_stats(data)
|
| 74 |
+
show_samples(data, args.num_samples)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
if __name__ == "__main__":
|
| 78 |
+
parser = argparse.ArgumentParser(description="Validate CoT data quality")
|
| 79 |
+
parser.add_argument("--cot_path", type=str, required=True)
|
| 80 |
+
parser.add_argument("--num_samples", type=int, default=5)
|
| 81 |
+
args = parser.parse_args()
|
| 82 |
+
|
| 83 |
+
main(args)
|