diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..a1292055c66b901e469061443f3564bdb7b50916 Binary files /dev/null and b/.DS_Store differ diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..368258ab02f3704622d19548e9fe6e61e5d2412b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +code/multi_vlm2vec_train/Miniconda3-latest-Linux-x86_64.sh filter=lfs diff=lfs merge=lfs -text diff --git a/code/.DS_Store b/code/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..a1db1c801f5aa81bf7205d4dab7f16afb27e88c2 Binary files /dev/null and b/code/.DS_Store differ diff --git a/code/multi_vlm2vec_train/.DS_Store b/code/multi_vlm2vec_train/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..22ff1d158fb21ec43a1360667d1c2f7d3182dd83 Binary files /dev/null and b/code/multi_vlm2vec_train/.DS_Store differ diff --git a/code/multi_vlm2vec_train/.gitignore b/code/multi_vlm2vec_train/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..2d4a6d07c93897d9ebba95db42d330634ac50024 --- /dev/null +++ b/code/multi_vlm2vec_train/.gitignore @@ -0,0 +1,206 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# UV +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +#uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/latest/usage/project/#working-with-version-control +.pdm.toml +.pdm-python +.pdm-build/ + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc + +# Cursor +# Cursor is an AI-powered code editor.`.cursorignore` specifies files/directories to +# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data +# refer to https://docs.cursor.com/context/ignore-files +.cursorignore +.cursorindexingignore + +## my ignore files +.vscode/ +LamRA_Ret_eval_results/ +outputs/ +checkpoints/ +*.pth +saved_checkpoints/ +*.pyc +hf_upload_checkpoints/ +zeroshot_rerank_files/ +zeroshot_retrieval_eval_results/ +LamRA_Ret_eval_results/ +checkpoints/ +rerank_training_data/ +mbeir_rerank_files/ +utils_data/core-pt* +core-pt_main_thread* +core-python* +*.excp +*.jpg +*.png +*.jpeg +logs/ +xdg_cache/ \ No newline at end of file diff --git a/code/multi_vlm2vec_train/Miniconda3-latest-Linux-x86_64.sh b/code/multi_vlm2vec_train/Miniconda3-latest-Linux-x86_64.sh new file mode 100644 index 0000000000000000000000000000000000000000..66807b66ab8bca5bd42221f6f4bb8d7b535d761a --- /dev/null +++ b/code/multi_vlm2vec_train/Miniconda3-latest-Linux-x86_64.sh @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:80bc27f13c4de90f10e387aa45e864de4f0860692c1221aef5900009a2b55302 +size 197272282 diff --git a/code/multi_vlm2vec_train/__pycache__/logger.cpython-310.pyc b/code/multi_vlm2vec_train/__pycache__/logger.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36bd67c8000d6e25c4031b83f40724ac25f1cdfe Binary files /dev/null and b/code/multi_vlm2vec_train/__pycache__/logger.cpython-310.pyc differ diff --git a/code/multi_vlm2vec_train/__pycache__/logger.cpython-313.pyc b/code/multi_vlm2vec_train/__pycache__/logger.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fc307afdbd8f7b0188d75f3306239696a687ae5 Binary files /dev/null and b/code/multi_vlm2vec_train/__pycache__/logger.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/bianji_test_10.json b/code/multi_vlm2vec_train/bianji_test_10.json new file mode 100644 index 0000000000000000000000000000000000000000..4c22cfefc40eb42757b7846d724c80d29a8eab4f --- /dev/null +++ b/code/multi_vlm2vec_train/bianji_test_10.json @@ -0,0 +1,142 @@ +[ + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN012QaWsZ29XK3pGfr3b_!!2311728077.jpg", + "item_key": "", + "item_title": "定制铝合金大门新款双开门自建房家用入户门别墅农村进户", + "item_bbox": "83 9 963 1005", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "0" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01E9hQnH2ALF9iffOHg_!!6000000008186-0-tmap.jpg", + "item_key": "", + "item_title": "新款农村防盗门岩棉填充平房室外门仿铜门农村户玻璃门防寒门", + "item_bbox": "267 7 1604 2867", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01t6HHaN1IfPRHMgfKr_!!4611686018427381704-0-item_pic.jpg", + "item_key": "", + "item_title": "风冷单缸柴油机抽水泵切割微耕机头5 6 9 10 12 16马力发动机", + "item_bbox": "286 152 764 694", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01UjoxjE1WqlYIElGF7_!!0-fleamarket.jpg", + "item_key": "", + "item_title": "阳台不锈钢需要私聊", + "item_bbox": "135 194 918 1432", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN011dLYQc1ImH0khViCh_!!1749420935-0-tbvideo.jpg", + "item_key": "", + "item_title": "新款桃木双面雕刻千手观音菩萨汽车挂件车内挂饰高档摆件内饰用品", + "item_bbox": "0 1 720 748", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN018JLFGe1PTEDZzdzH6_!!2216807051841.jpg", + "item_key": "", + "item_title": "加厚全铝门断桥铝气窗门防盗门玻璃平房铝合金门保温户外防寒门", + "item_bbox": "273 29 535 714", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN018HmONW2Ke9kIXMU7u_!!3330569581.jpg", + "item_key": "", + "item_title": "2025年春季新款模特走秀恨天高单鞋时尚细跟防水台舞台演出高跟鞋", + "item_bbox": "0 855 865 1422", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01XC3ze91FQLY5ImKeK_!!4611686018427387569-0-item_pic.jpg", + "item_key": "", + "item_title": "豪华全套中式304不锈钢单门带亮窗庭院进户门防盗防晒防锈双开门", + "item_bbox": "97 39 685 1077", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN010JeOoe2BCpV18PV6q_!!2212749898303.jpg", + "item_key": "", + "item_title": "拿铁女孩自制微透健身瑜伽防晒罩衫性感透气运动长袖瑜伽速干T恤", + "item_bbox": "96 93 566 748", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01sMjDOh1WfJvoOMOzB_!!2215334882815.jpg", + "item_key": "", + "item_title": "楼宇单元门钢制单元门玻璃单元门防盗门进户门可对视楼宇门对讲门", + "item_bbox": "77 137 377 799", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + } +] \ No newline at end of file diff --git a/code/multi_vlm2vec_train/bianji_test_200.json b/code/multi_vlm2vec_train/bianji_test_200.json new file mode 100644 index 0000000000000000000000000000000000000000..a9780347f46e376430ec969ca168b52836a0714d --- /dev/null +++ b/code/multi_vlm2vec_train/bianji_test_200.json @@ -0,0 +1,2802 @@ +[ + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN012QaWsZ29XK3pGfr3b_!!2311728077.jpg", + "item_key": "", + "item_title": "定制铝合金大门新款双开门自建房家用入户门别墅农村进户", + "item_bbox": "83 9 963 1005", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "0" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01E9hQnH2ALF9iffOHg_!!6000000008186-0-tmap.jpg", + "item_key": "", + "item_title": "新款农村防盗门岩棉填充平房室外门仿铜门农村户玻璃门防寒门", + "item_bbox": "267 7 1604 2867", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01t6HHaN1IfPRHMgfKr_!!4611686018427381704-0-item_pic.jpg", + "item_key": "", + "item_title": "风冷单缸柴油机抽水泵切割微耕机头5 6 9 10 12 16马力发动机", + "item_bbox": "286 152 764 694", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01UjoxjE1WqlYIElGF7_!!0-fleamarket.jpg", + "item_key": "", + "item_title": "阳台不锈钢需要私聊", + "item_bbox": "135 194 918 1432", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN011dLYQc1ImH0khViCh_!!1749420935-0-tbvideo.jpg", + "item_key": "", + "item_title": "新款桃木双面雕刻千手观音菩萨汽车挂件车内挂饰高档摆件内饰用品", + "item_bbox": "0 1 720 748", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN018JLFGe1PTEDZzdzH6_!!2216807051841.jpg", + "item_key": "", + "item_title": "加厚全铝门断桥铝气窗门防盗门玻璃平房铝合金门保温户外防寒门", + "item_bbox": "273 29 535 714", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN018HmONW2Ke9kIXMU7u_!!3330569581.jpg", + "item_key": "", + "item_title": "2025年春季新款模特走秀恨天高单鞋时尚细跟防水台舞台演出高跟鞋", + "item_bbox": "0 855 865 1422", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01XC3ze91FQLY5ImKeK_!!4611686018427387569-0-item_pic.jpg", + "item_key": "", + "item_title": "豪华全套中式304不锈钢单门带亮窗庭院进户门防盗防晒防锈双开门", + "item_bbox": "97 39 685 1077", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN010JeOoe2BCpV18PV6q_!!2212749898303.jpg", + "item_key": "", + "item_title": "拿铁女孩自制微透健身瑜伽防晒罩衫性感透气运动长袖瑜伽速干T恤", + "item_bbox": "96 93 566 748", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01sMjDOh1WfJvoOMOzB_!!2215334882815.jpg", + "item_key": "", + "item_title": "楼宇单元门钢制单元门玻璃单元门防盗门进户门可对视楼宇门对讲门", + "item_bbox": "77 137 377 799", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01OzN1lJ1yiLkynDCEI_!!2217676106612.jpg", + "item_key": "", + "item_title": "无印良品衣物收纳袋家居收纳包化妆包行李箱整理袋便携分装包内衣", + "item_bbox": "80 302 721 710", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01Rben4f1ZF9qgm8Dzu_!!2632523164.jpg", + "item_key": "", + "item_title": "锦鲤如意气窗防盗门平房外门仿铜门农村户外门加厚门玻璃门防寒门", + "item_bbox": "204 138 516 795", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01YEfKgx23trjnXalnQ_!!6000000007314-0-yinhe.jpg", + "item_key": "", + "item_title": "暖腰贴腰部热敷贴护腰贴自发热暖宝宝贴暖腰腹部疼热贴神器1767F", + "item_bbox": "432 387 744 624", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01aXDlvf22e0K7Tiu3T_!!1130817144.jpg", + "item_key": "", + "item_title": "锌合金农村自建房别墅大门双开门钢化玻璃门进户门堂屋客厅入户门", + "item_bbox": "62 94 337 380", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01vFMgPS2LuTCtAKfwX_!!652989752.jpg", + "item_key": "", + "item_title": "年轻款紫色妈妈婚宴礼服遮肚子2022秋款平时可穿高贵喜婆婆婚宴装", + "item_bbox": "266 144 553 736", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN018qTeHL1g6duYEotXD_!!0-item_pic.jpg", + "item_key": "", + "item_title": "楚阁定制铝合金双开对开乡村别墅四开六开门农村庭院大门自建房子", + "item_bbox": "0 0 874 1218", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01EhMoFY1d1ezoyylsh_!!4611686018427379852-0-item_pic.jpg", + "item_key": "", + "item_title": "旋钮钮电吉他银st黑上卷钮 扭弦 琴弦弦复古准电吉他弦弦器钮sq", + "item_bbox": "267 59 802 907", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01H8M6x71ZFA2F80b76_!!2632523164.jpg", + "item_key": "", + "item_title": "防盗门农村平房岩棉防盗门平房室外门仿铜门农村户玻璃门防寒门", + "item_bbox": "432 44 727 782", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01Ng1qSg1S91ZDkLtFB_!!720102203.jpg", + "item_key": "", + "item_title": "新米上市江西高安米州贡宫庭贡米29斤装大米籼米14.5kg农家米家用", + "item_bbox": "66 112 408 694", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01P982OQ2EEc00PEtq0_!!2219080958713.png", + "item_key": "", + "item_title": "甲级防盗门C级锁进户入户门家用单门加高防晒防雨通风锌合金现货", + "item_bbox": "523 42 946 931", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN015OJULl2FBEaDsXYJP_!!2684558841.jpg", + "item_key": "", + "item_title": "高端婚纱新宾娘新款婚礼主纱长袖缎迎面晚礼气质高66523级感拖服", + "item_bbox": "68 112 732 792", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01vOT61V26sthuU2qqn_!!180467718.jpg", + "item_key": "", + "item_title": "九公分真甲级防盗门高端家用进户门安全门子母门对开门带气窗上亮", + "item_bbox": "0 29 348 764", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01oO5jhv2Ddy2b8Ekvh_!!1117898633.jpg", + "item_key": "", + "item_title": "极窄2.0钻石型枪灰色淋浴房全套五金配件304不锈钢黑色可下沉式", + "item_bbox": "249 144 608 732", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01WlPPrI21qXiTR8GeU_!!2218799287036.jpg", + "item_key": "", + "item_title": "四开锌合金别墅大门双门防盗门入户庭院门农村自建房家用进户门", + "item_bbox": "154 698 772 1391", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01Wcrzr821KTzjLN5oh_!!0-fleamarket.jpg", + "item_key": "", + "item_title": "正品宜家卡莱克 搁架单元客厅隔断书柜4*4格子/16格147", + "item_bbox": "49 1019 1198 1916", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01gpWQLm26XpdxgNcxX_!!4611686018427380104-0-fleamarket.jpg", + "item_key": "", + "item_title": "索尼3D眼镜,全新", + "item_bbox": "792 378 1190 1499", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01myQfuC1tbPn2ideMI_!!2212777285920.jpg", + "item_key": "", + "item_title": "笔筒大容量超大景德镇青花瓷手绘大笔筒画笔毛书画缸兰花20口径花", + "item_bbox": "256 122 919 914", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01Da4dIJ20oshHqlbai_!!4611686018427380737-0-fleamarket.jpg", + "item_key": "", + "item_title": "龙婆moon生命伴侣小模限时秒杀特价", + "item_bbox": "0 0 1437 1916", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01EA5R1O1P1kP5P8eRD_!!4611686018427382581-0-fleamarket.jpg", + "item_key": "", + "item_title": "Nike romaleos3 白 44.5", + "item_bbox": "126 144 596 640", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01cjslbe1tMkrVOruaB_!!0-fleamarket.jpg", + "item_key": "", + "item_title": "B型三角皮带,四条,九成新,太长了,2800的。打包包邮价。", + "item_bbox": "0 0 1440 1918", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN013NPhZ524jA6naGnfG_!!2200575497426.jpg", + "item_key": "", + "item_title": "天然阿富汗玉石葫芦福禄平安摆件客厅玄关博古架中式桌面生财摆设", + "item_bbox": "236 75 584 718", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN01zINRJx20PgU1OjS8I_!!0-item_pic.jpg", + "item_key": "", + "item_title": "全龙戏装 京剧服装戏曲用品演出服装戏剧用品帽子女兵额子 小额子", + "item_bbox": "118 19 609 508", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40100", + "query_tfsid": "O1CN01sHMaye1Vu9CoofcEh_!!4611686018427382280-0-imgsearch.jpg", + "query_bbox": "0 87 279 640", + "query_text": "想要个钻石形设计的", + "item_id": "", + "item_tfsid": "O1CN0148v95L1nSoZBiMDd8_!!2218480965089.jpg", + "item_key": "", + "item_title": "厂家古典舞舞蹈服女纱衣中国舞仙气珍珠飘逸上衣演出服练功服装", + "item_bbox": "146 80 625 696", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01AnSYYX1VmMCEmAMG4_!!2754702695.jpg", + "item_key": "", + "item_title": "雪纺披肩婚纱摄影化妆造型影楼专用美容围布美发吹风新品美妆披肩", + "item_bbox": "265 229 788 675", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "0" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01rT3uA21FEQrtgglqC_!!2207828890455.jpg", + "item_key": "", + "item_title": "理发店围布发廊专用发型师高档潮防水不沾发剪发烫染加长透视围布", + "item_bbox": "126 142 747 799", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01eDTd2S1idjzMaigeL_!!665964436.jpg", + "item_key": "", + "item_title": "夏季新款个性简约竖条纹男童衬衫纯棉儿童字母休闲衬衣百搭上衣潮", + "item_bbox": "170 248 1017 1105", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01afV9P11HK2s96uX7F_!!1733900738.jpg", + "item_key": "", + "item_title": "美发披肩理发店专用烫染专用 影楼 化妆专用 围布", + "item_bbox": "28 347 690 667", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01IgCvms1spKARjzdFZ_!!1730145815.jpg", + "item_key": "", + "item_title": "塑料船双层加厚钓鱼平板船河道保洁捕渔船pe冲锋舟可装电动汽油机", + "item_bbox": "67 8 332 782", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01O4GPRT2D9k9lUZACf_!!3320258567.jpg", + "item_key": "", + "item_title": "厂家现货防水披肩 发廊专用焗油染发披肩美发用品烫染小工具围布", + "item_bbox": "32 142 755 716", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN012QaWsZ29XK3pGfr3b_!!2311728077.jpg", + "item_key": "", + "item_title": "定制铝合金大门新款双开门自建房家用入户门别墅农村进户", + "item_bbox": "83 9 963 1005", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01FqMrlE2AN4kh0fu7S_!!3505108190.jpg", + "item_key": "", + "item_title": "发廊影楼专用吹风造型护衣小披肩理发店围布彩色化妆美妆披肩洗发", + "item_bbox": "63 180 957 958", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN010Cdut023r7UoyOnDY_!!808737308-0-third_party_goods_pic.jpg", + "item_key": "", + "item_title": "摆地摊夜市皮带牛筋自动扣腰带比牛皮还牛的礼品航空皮带男士", + "item_bbox": "26 218 388 576", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01zNxAye1ntNFNIvVq2_!!2200754595147.jpg", + "item_key": "", + "item_title": "加长剪发围布理发店发廊专用网红高档潮美发店烫染围布客袍不沾发", + "item_bbox": "97 146 679 799", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01Y6YO0K1L2srj6ZBHX_!!720811242.png", + "item_key": "", + "item_title": "曼娅奴2022夏季新款直筒宽松高腰阔腿裤子通勤西装裤女MM24BA622", + "item_bbox": "292 113 504 404", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01KkxMh21ZzQ8gSRZN3_!!2217816383265.jpg", + "item_key": "", + "item_title": "发廊围布烫染剪防水化妆_披肩理发店美发焗油洗头专用防发布围巾", + "item_bbox": "188 208 712 557", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01SJo5YB27N7qIZXJ80_!!2041027784.jpg", + "item_key": "", + "item_title": "手工特殊如意天珠", + "item_bbox": "0 88 821 700", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01ep3ROV1dlSbYK7PRl_!!885913776.jpg", + "item_key": "", + "item_title": "防水不沾发带袖款理发店围布发廊专用高档潮网红剪发美发烫染围布", + "item_bbox": "41 586 1430 1873", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01DMStdk1dYB1xF11mT_!!2920223747.jpg", + "item_key": "", + "item_title": "英氏儿童毛衣春秋冬长袖男女童羊毛羊绒保暖针织衫纯色百搭套头衫", + "item_bbox": "172 187 625 609", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01fRpsAf1SIdvWBhWF2_!!4611686018427379728-0-item_pic.jpg", + "item_key": "", + "item_title": "厂家批发发廊理发店条纹围布不沾发剪发围布美发用品成人理发围布", + "item_bbox": "6 202 542 704", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01BHa0v42BGUi9WKcCf_!!2900708311.jpg", + "item_key": "", + "item_title": "适用三星S24Ultra磁吸支架A16保护套S25磨砂透明ZFoldSEcase", + "item_bbox": "224 80 489 720", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01HqxpVO1xajGxOhvIk_!!84026460.jpg", + "item_key": "", + "item_title": "NUSKIN如新周边nuskin围布浴帽防水成人女款淋浴头套厨房女士围兜", + "item_bbox": "5 565 993 1365", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01lhu1W01DDrIGJHaeX_!!2129090183.jpg", + "item_key": "", + "item_title": "现货迪士尼怪兽大学大眼仔婴儿纯棉胎帽新生儿立体造型小帽子", + "item_bbox": "36 34 371 340", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01i9mVhU1x9FWV9GFmZ_!!1811806400.jpg", + "item_key": "", + "item_title": "透明高档发型师理发围布不沾发发廊剪发专用潮牌美发围裙定制logo", + "item_bbox": "98 156 669 672", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01nUksLi1xwiS8kcLfU_!!777006508.jpg", + "item_key": "", + "item_title": "EK衣恋童装专柜正品23秋款男女童纯棉休闲卫衣 MWD3802B TMD3802B", + "item_bbox": "130 220 1299 1405", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01iI6aBM1VmMCGinLGf_!!2754702695.jpg", + "item_key": "", + "item_title": "美发披肩理发店专用烫染垫肩发廊洗发剪发防水围布化妆店家用围巾", + "item_bbox": "270 314 799 642", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01JxWEVS1J1ONm6ejCe_!!2217729380968.jpg", + "item_key": "", + "item_title": "书桌.桌写字台禅意古典风垫台布书法垫布古风中式学生新中国茶桌", + "item_bbox": "96 240 701 800", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01OLRLIZ2IrJdH6wryz_!!54539339.jpg", + "item_key": "", + "item_title": "定制高端影楼美容美发吹风造型专用披肩新娘化妆围布美妆披肩印字", + "item_bbox": "65 271 636 799", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01AwXtkL2ERQrhQbX81_!!1682198741.jpg", + "item_key": "", + "item_title": "宽松百搭短裤女2023夏季新款洋气复古简约纯色时尚港味风休闲裤潮", + "item_bbox": "165 0 748 750", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01PM9eb51nMP2axsGsO_!!4611686018427386387-0-item_pic.jpg", + "item_key": "", + "item_title": "影楼婚纱礼服照相馆美妆连锁店化妆围布医美拍照用围脖化妆师专用", + "item_bbox": "16 298 780 684", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01dBBMcm1xtVu1145gI_!!1633946501.jpg", + "item_key": "", + "item_title": "日本LASTARTS单板滑雪鞋 双boa双钢丝扣刻滑进阶硬度7全能滑雪靴", + "item_bbox": "158 80 627 638", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01b6JQBr1eaIRfYNjwG_!!1830763887.jpg", + "item_key": "", + "item_title": "网红理发围布发廊专用剪发不沾发高档专业美发围裙潮透气定制logo", + "item_bbox": "0 244 798 800", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01ZMoOQ71UVaF6hymzQ_!!1970812523.jpg", + "item_key": "", + "item_title": "户外高硬度多功能小刀不锈钢刀具户外露营刀荒野求生刀随身刀水果", + "item_bbox": "0 0 794 798", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01QYwSGJ1ePJ0NvmOGJ_!!633363863.jpg", + "item_key": "", + "item_title": "2024新款法式一字扣带水钻凉鞋性感露趾防水台粗跟中空高跟鞋", + "item_bbox": "122 0 798 798", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01W5tWUu1nbWBfq3D5Z_!!3336555108.jpg", + "item_key": "", + "item_title": "新款藏族舞蹈民族演出服装表演服群舞大摆裙艺考裙练习裙", + "item_bbox": "209 519 607 818", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01X0ScPI1SxrJumzaUR_!!2211017642314.jpg", + "item_key": "", + "item_title": "品牌折扣奢侈款专柜捡漏!短袖t恤男夏季潮流帅气圆领百搭男上衣", + "item_bbox": "144 150 640 721", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01g9NzM81iRpgLD9aWF_!!4611686018427381450-0-item_pic.jpg", + "item_key": "", + "item_title": "2025春季新款设计感通勤穿搭上衣时髦洋气宽松显瘦百搭小众小衫", + "item_bbox": "106 38 669 780", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN01KUD8n527QKoBQ5zwJ_!!775177791.jpg", + "item_key": "", + "item_title": "拉夏贝尔丹宁蓝天丝直筒牛仔裤女夏薄款高个子窄版加长冰丝阔腿裤", + "item_bbox": "297 71 504 743", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40101", + "query_tfsid": "O1CN01HKydmc1WutPgMRLDT_!!4611686018427386977-0-imgsearch.jpg", + "query_bbox": "0 308 275 501", + "query_text": "来个雪纺的披肩", + "item_id": "", + "item_tfsid": "O1CN017eMTBO22vPXy3rZhV_!!2207793897182.jpg", + "item_key": "", + "item_title": "纸先生云深不知处中国古风手账本礼盒套装彩页笔记本本子文艺记事本学生日记本手帐本素材工具全套送生日礼物", + "item_bbox": "47 13 624 585", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN018LzP731Kq3ipwzG5y_!!4071171214.jpg", + "item_key": "", + "item_title": "韩版直筒牛仔裤女2025春秋冬显瘦宽松水泥灰小个子窄版阔腿裤", + "item_bbox": "90 63 283 729", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "0" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01FydQjg21oFcgKzww8_!!125327031.jpg", + "item_key": "", + "item_title": "RAINY 美式直筒美拉德色系水洗做旧牛仔裤宽松阔腿百搭高腰裤子", + "item_bbox": "271 96 489 750", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01HoVMEd1s0wRDYzJkj_!!1092575705.jpg", + "item_key": "", + "item_title": "秋装女2025年新款休闲时尚高腰短款工装牛仔外套半身裙套装两件套", + "item_bbox": "345 227 500 698", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01wmsCLE1cOGsLtFA6a_!!2214717363590.jpg", + "item_key": "", + "item_title": "遮胯窄版阔腿牛仔裤女春秋冬2024新款高腰加绒垂感水泥灰复古直筒", + "item_bbox": "223 161 391 742", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01kJTxCD1r1ZKJ78y60_!!2732585571.jpg", + "item_key": "", + "item_title": "轻奢便携式旅行茶具套装简约高档日式茶壶快客茶杯收纳包定制LOGO", + "item_bbox": "59 135 721 709", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN010f87QV1fxUG2scKLb_!!2235734073.jpg", + "item_key": "", + "item_title": "复古蓝色不贴腿微喇牛仔裤女早秋穿搭大码胖mm高腰显瘦百搭直筒裤", + "item_bbox": "170 179 332 729", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01PxgGBr2ENlqlHtLMt_!!2021898733.jpg", + "item_key": "", + "item_title": "创意日式玻璃清酒杯套装江沪切子手工刻花杯清酒杯壶创意家用酒杯", + "item_bbox": "199 186 598 533", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN017lrlf32CRJYg1j0Ta_!!2201328470.jpg", + "item_key": "", + "item_title": "加长阔腿牛仔裤女春秋新款高个子175窄版高腰显瘦170超长直筒裤子", + "item_bbox": "249 198 586 799", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01crhL091q0pChe7BeI_!!2206626555434.jpg", + "item_key": "", + "item_title": "外套男春秋季2024新款潮流帅气休闲薄款夹克时尚情侣装反光男褂子", + "item_bbox": "391 11 799 545", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01VrHROI1EBOxQeKJXQ_!!900090313.jpg", + "item_key": "", + "item_title": "MA家三衣Boyiyiyi2024年秋季新款直筒阔腿裤女弹力牛仔长裤93236", + "item_bbox": "311 160 628 915", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01qLp17r1ZYr7fu1zbC_!!3044463207.jpg", + "item_key": "", + "item_title": "实木衣柜家用卧室欧式出租房用储物柜儿童简易包安装四五门大衣橱", + "item_bbox": "277 68 546 648", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN019z7s1d1VwtV5EyRcK_!!1108362718.jpg", + "item_key": "", + "item_title": "阔腿牛仔裤女2024秋冬新款高腰弹力美式复古宽松垂感显瘦喇叭裤子", + "item_bbox": "327 367 486 741", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01bN9t8E1ObBUEAG4Kv_!!2415511723.jpg", + "item_key": "", + "item_title": "实木转角手办展示架高达盲盒收纳架卧室积木玩具置物架模型陈列架", + "item_bbox": "342 37 579 758", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01pGLyvh2GYsh7LGSz7_!!2312299028.jpg", + "item_key": "", + "item_title": "加绒高腰牛仔裤女冬季新款小个子大码窄版直筒宽松显瘦阔腿长裤子", + "item_bbox": "125 125 336 750", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01eAj2Mc1Fterq0v5d5_!!2214195490545.jpg", + "item_key": "", + "item_title": "冬季显白山羊绒围巾手工diy粗毛线团编织礼物钩针材料包男女朋友", + "item_bbox": "183 2 795 722", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01GlZc1O27dcDxpBrpM_!!771557820.jpg", + "item_key": "", + "item_title": "2024新款舒尔美8802蓝色百搭高腰宽松显瘦直筒牛仔阔腿裤女秋季", + "item_bbox": "154 60 452 704", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01WywcY71Xyq9TMdSYV_!!1030862993.jpg", + "item_key": "", + "item_title": "工作高跟鞋10cm夜场防水台细跟职业百搭黑色礼仪少女尖头单鞋春秋", + "item_bbox": "322 76 724 714", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01rJhM6U2I8tRBh3CK5_!!2206508409242.jpg", + "item_key": "", + "item_title": "美式休闲直筒阔腿牛仔裤女春秋2025新款复古vintage宽松高街裤子", + "item_bbox": "147 88 597 906", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01eDTd2S1idjzMaigeL_!!665964436.jpg", + "item_key": "", + "item_title": "夏季新款个性简约竖条纹男童衬衫纯棉儿童字母休闲衬衣百搭上衣潮", + "item_bbox": "170 248 1017 1105", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01nnvWw51sMveC4WGVu_!!2215713305753.jpg", + "item_key": "", + "item_title": "高腰直筒牛仔裤女2025年秋季新款梨形身材大码显瘦复古窄版阔腿裤", + "item_bbox": "484 394 975 1809", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01jPxaUX1fstziQeaYQ_!!6000000004063-0-tmap.jpg", + "item_key": "", + "item_title": "台电u盘8G乐影钥匙扣车载创意防水学生可爱商务金属激光定制优盘", + "item_bbox": "477 0 1030 718", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01pArv791bz4yEl8EKZ_!!2773663535.jpg", + "item_key": "", + "item_title": "水泥灰直筒牛仔裤女高腰2024春秋新款加长显瘦垂感复古窄版阔腿裤", + "item_bbox": "133 236 291 726", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01UnmAz92MpGZQhR0vv_!!12069876.jpg", + "item_key": "", + "item_title": "2021新款switch oled主机用分体式TPU保护套全包磨砂软壳可插底座", + "item_bbox": "172 83 900 455", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01yi2c3p29ugEMfdOyg_!!793828128.jpg", + "item_key": "", + "item_title": "复古蓝水洗牛仔裤女秋冬新款显瘦高腰直筒拖地裤窄版阔腿牛仔裤", + "item_bbox": "198 46 562 760", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01u9Fnhb23DjMvyzZlT_!!2215860277222-0-third_party_goods_pic.jpg", + "item_key": "", + "item_title": "women clothes 辣妹网纱透视长袖欧美ins连体衣性感修身百搭显瘦", + "item_bbox": "126 134 477 514", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01kaFuKX1UoMMTapo5f_!!2636832564.jpg", + "item_key": "", + "item_title": "办公室励志标语墙贴创意防水防潮自粘房间背景墙装饰墙壁贴纸定制", + "item_bbox": "26 65 773 456", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01uoHLxH1RYNvCZN5ec_!!2208346792123.jpg", + "item_key": "", + "item_title": "全新国产假面骑士csm天帝腰带凯撒驱动器台词BGM可联动光剑变身器", + "item_bbox": "147 432 791 666", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01mVKYNA2L70fhgcIDO_!!4611686018427383276-0-item_pic.jpg", + "item_key": "", + "item_title": "可定做玻璃冷肼冷凝器 此款球直径50毫米蛇形管高170毫米", + "item_bbox": "272 0 742 464", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01z5vaa81oyhq1QujPC_!!1067625294.jpg", + "item_key": "", + "item_title": "婴儿夏季衣服女童韩系无袖薄款包屁衣小月龄宝宝哈衣夏日连体爬服", + "item_bbox": "513 916 1205 1696", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01xDh4zt1Eei6Ksr42a_!!3934190377.jpg", + "item_key": "", + "item_title": "粉蝶古筝指甲初学者成人专业演奏级甲片大号儿童小号考级专用义甲", + "item_bbox": "243 231 444 507", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01ousePY2HsrMXGvoNV_!!1586079207.jpg", + "item_key": "", + "item_title": "纯棉针织1*1罗纹布宝宝高弹力袖口领口护腰口睡袋侧拼螺纹布料", + "item_bbox": "0 0 798 798", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01b5Y9ga1n5urFWC9fb_!!3483125039.jpg", + "item_key": "", + "item_title": "洋气妈妈小香风外套2025新款女士秋装时髦减龄短款春秋高级感上衣", + "item_bbox": "249 122 1276 1384", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40102", + "query_tfsid": "O1CN01oDz7EH1c0SHho32kN_!!0-imgsearch.jpg", + "query_bbox": "0 0 201 557", + "query_text": "来条深绿色的裤子", + "item_id": "", + "item_tfsid": "O1CN01Ug1xDQ1KZZYTfYmsZ_!!0-item_pic.jpg", + "item_key": "", + "item_title": "西装女正装职业套装春秋2024新款修身气质女神范珠宝店前台工作服", + "item_bbox": "236 202 622 692", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01aMLGxs24Mim3EiJkt_!!795497377.jpg", + "item_key": "", + "item_title": "杭州高端大牌真丝衬衫女士长袖金丝绒小衫2025早秋新款桑蚕丝上衣", + "item_bbox": "0 82 1195 1595", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "0" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01VHq8ru1Oiy1NlR09h_!!3068391740.jpg", + "item_key": "", + "item_title": "2023秋装新款气质尖领黑色拼接丝绒衬衫女设计感小众长袖别致上衣", + "item_bbox": "122 44 700 728", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01zINRJx20PgU1OjS8I_!!0-item_pic.jpg", + "item_key": "", + "item_title": "全龙戏装 京剧服装戏曲用品演出服装戏剧用品帽子女兵额子 小额子", + "item_bbox": "118 19 609 508", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01MQIbFP2FoAIjyFS7A_!!4611686018427381070-0-item_pic.jpg", + "item_key": "", + "item_title": "2025爆款春季法式轻熟内搭上衣轻奢高级感气质黑色丝绒衬衫女新款", + "item_bbox": "96 212 676 685", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN014KbI7Y2HyMCScOvIz_!!2214236339219.jpg", + "item_key": "", + "item_title": "品牌折扣店专柜撤柜清仓童装儿童背心夏装新款韩版卡通男宝宝衣服", + "item_bbox": "196 120 602 684", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01u1FD3f2IcClxcvV3g_!!2521899306.jpg", + "item_key": "", + "item_title": "清仓捡漏~春秋蕾丝网纱娃娃领拼接长袖衬衫女设计感撞色丝绒上衣", + "item_bbox": "2 46 795 795", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01DMStdk1dYB1xF11mT_!!2920223747.jpg", + "item_key": "", + "item_title": "英氏儿童毛衣春秋冬长袖男女童羊毛羊绒保暖针织衫纯色百搭套头衫", + "item_bbox": "172 187 625 609", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01dwA9ar2NU1iC67ew3_!!133619965.jpg", + "item_key": "", + "item_title": "赫本风翻领衬衫女春秋装2024新款法式设计感高端简约气质开衫冬", + "item_bbox": "125 112 669 732", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01KVI9pA2LR9eozRN9x_!!1071709688.jpg", + "item_key": "", + "item_title": "一次性桌布加厚饭店酒席红色台布优质婚庆餐桌布塑料圆桌餐布超大", + "item_bbox": "130 59 655 752", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN018uMxS11QlpmJbYiH9_!!23682017.jpg", + "item_key": "", + "item_title": "【折】轻奢法式复古真丝丝绒撞色Polo领长袖衬衫女2024春季新款", + "item_bbox": "0 132 798 798", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01fRKeCq1Cthwz6Abff_!!1677940139.jpg", + "item_key": "", + "item_title": "圣诞老人服装男圣诞节老公公套装老爷爷服饰成人cos装扮演出衣服", + "item_bbox": "46 623 171 769", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN013jMH7p1tdhhyrdZc8_!!2784355925.jpg", + "item_key": "", + "item_title": "ZA2025春季新品女装长袖衬衫 0009128 侧面条纹带饰裤子 0022128", + "item_bbox": "121 207 624 799", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01PBTC4L1FxJbKWnbHl_!!2504500553.jpg", + "item_key": "", + "item_title": "日本MT metatron灰色修护系列化妆水精华乳液面霜面膜舒缓保湿套", + "item_bbox": "422 134 586 704", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01UJMVxU1e8M87s8X0e_!!2224603826.jpg", + "item_key": "", + "item_title": "方领衬衫女2023年春秋新款金丝绒上衣修身百搭显瘦减龄丝绒衬衣潮", + "item_bbox": "104 280 659 978", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01lcjuvB22ksTGBClEE_!!2218802817159.jpg", + "item_key": "", + "item_title": "甲级乙级防火窗钢制防火窗家装工程消防验收商场酒店耐火窗可定制", + "item_bbox": "89 87 710 707", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01UF5GRJ1i5qVUkWcNW_!!2209035044362.jpg", + "item_key": "", + "item_title": "小香风法式高端丝绒娃娃领衬衫女2025秋装设计感欧货黑色打底上衣", + "item_bbox": "123 80 599 639", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01yarE5H1wFpyDHuAgX_!!2214950386279.jpg", + "item_key": "", + "item_title": "高清可拍照双摄可爱数码相机儿童校园照相机学生上传手机旅游记录", + "item_bbox": "9 33 616 616", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01GKMKbK27ScS5oPKl6_!!2625027796.jpg", + "item_key": "", + "item_title": "黑色丝绒衬衫外套女装秋冬法式设计感小众衬衣2022年新款长袖上衣", + "item_bbox": "76 346 452 773", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01UHBKlH2HJb2jKjd0k_!!55579130.jpg", + "item_key": "", + "item_title": "美妞英国代购2024年新款棕色直筒版型纯色简约常规青年春秋休闲裤", + "item_bbox": "324 58 697 767", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01ADRX8Q1geziVpVV6M_!!3108424168.jpg", + "item_key": "", + "item_title": "黑色丝绒长袖衬衫女2025夏季新款气质名媛蝴蝶结显瘦别致钉珠衬衣", + "item_bbox": "13 106 562 747", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN010voz5z1NSBbS42l30_!!73961568.jpg", + "item_key": "", + "item_title": "美式长绒棉四件套全棉纯棉床单 深色被套床上用品裸睡网红床笠款", + "item_bbox": "0 263 748 999", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01Nv4iHm23BRP3L7ZdC_!!2332797217.jpg", + "item_key": "", + "item_title": "杭州高端大牌真丝衬衫女士2025早秋新款长袖金丝绒小衫桑蚕丝上衣", + "item_bbox": "9 54 791 790", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01VCeMRg1kOHlDaVb90_!!2217682494673.png", + "item_key": "", + "item_title": "【凤凰宸】2024年新品100%桑蚕丝宋锦内里混种羊皮平底单鞋LJ1101", + "item_bbox": "192 192 516 692", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01D16b9r1af5ybZvmcy_!!830423356.jpg", + "item_key": "", + "item_title": "黑色丝绒衬衫外套女装秋季法式设计感小众衬衣2022年新款长袖上衣", + "item_bbox": "76 346 452 773", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01ZVWGeA1pTqe5mQ3Ct_!!0-fleamarket.jpg", + "item_key": "", + "item_title": "#35码女鞋全新35码中跟百搭小皮鞋2024春秋新款学生韩版", + "item_bbox": "397 704 993 1411", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01vKMU3v2N9sQTYmBN2_!!2217839099921.jpg", + "item_key": "", + "item_title": "德国客厅地毯2025新款轻奢高级免洗可擦沙发卧室床边毯大面积地垫", + "item_bbox": "0 258 799 799", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01Fb6l3j1bNyyZPiEjC_!!2217281013454.jpg", + "item_key": "", + "item_title": "微胖服套装纯欲风体操啦啦队服女日系体操学院少女学姐沙滩泳装风", + "item_bbox": "100 374 388 608", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01Vp6cE6200V4I05XrH_!!0-fleamarket.jpg", + "item_key": "", + "item_title": "国内现货:最新款日本马里奥任天堂新款问号三连包,可做收纳包,", + "item_bbox": "0 374 1435 1660", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01w1GdE11dWLMLccO1A_!!2209412223743.jpg", + "item_key": "", + "item_title": ".打火机zippo正版防风 黑裂漆236康斯坦丁 原装正品煤油zppo男士", + "item_bbox": "162 72 632 728", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01v44fGQ25QDQZTUoKG_!!3859237520.png", + "item_key": "", + "item_title": "适配长安逸动致尚悦翔V3V5V7CS35CS55CS75全合成发动机机油5W-40", + "item_bbox": "102 37 694 764", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN016VT7Bi23lAKl0B1Ao_!!858757295.jpg", + "item_key": "", + "item_title": "(二手瑕疵)soldierstory兵人 1/6 SS081 海豹 MK46机枪手 鞋子", + "item_bbox": "221 1462 1920 2691", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01O7NYQX1iziwQZsXst_!!2217893354484.jpg", + "item_key": "", + "item_title": "【L-亚洲码】阿迪达斯女短袖 断码清仓", + "item_bbox": "152 64 644 734", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40104", + "query_tfsid": "O1CN01qi7vkr21FtyzbyruZ_!!0-imgsearch.jpg", + "query_bbox": "0 124 350 639", + "query_text": "来个娃娃领的吧", + "item_id": "", + "item_tfsid": "O1CN01iwWZjI2LSXK0p2GnU_!!2219582589691.jpg", + "item_key": "", + "item_title": "100档冰敷制冷高速手持风扇充款手持便携学生高速风扇L", + "item_bbox": "577 11 1355 1868", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01fflQKT1GjPboAv2Rd_!!3496260658.jpg", + "item_key": "", + "item_title": "儿童保暖滑雪手套加绒防寒防泼水冬季户外玩雪防冻包指手套骑行", + "item_bbox": "105 297 416 919", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "0" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01oo7mpR1C4PLlFZcCs_!!6000000000027-0-tbvideo.jpg", + "item_key": "", + "item_title": "冬季户外遇水显印花儿童滑雪玩雪长筒手套防寒防水防风内加绒保暖", + "item_bbox": "474 332 825 1165", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01LuTyK11lApTJr1HcB_!!2201302334779.jpg", + "item_key": "", + "item_title": "黑板灰板绿板水性水彩笔液态粉笔吸磁小号8色装儿童涂鸦黑板粉笔", + "item_bbox": "356 81 420 601", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01EkP3DR1L70adoeLRs_!!2206817961251.jpg", + "item_key": "", + "item_title": "加长儿童手套玩雪防水冬加厚加绒保暖打雪仗防寒防风滑雪骑行手套", + "item_bbox": "864 109 1381 1274", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01rgEU0F1gFLQdbF2E4_!!2211820994112.jpg", + "item_key": "", + "item_title": "奢椰子鞋350黑生胶满天星男鞋2024新款夏季OG YEEZY透气运动鞋女", + "item_bbox": "62 222 750 577", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01HZQ6Rb1iiJuK3dNrF_!!3956754446.jpg", + "item_key": "", + "item_title": "儿童冬季3-17岁加厚防寒防水防风防滑保暖滑雪玩雪棉加绒触屏手套", + "item_bbox": "391 124 676 681", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN019oZ8tW1mi63TABma3_!!71124987.jpg", + "item_key": "", + "item_title": "Niegeloh-德国索林根尼格鲁 Capri 不锈钢 修甲美甲工具多件套装", + "item_bbox": "244 24 560 766", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01iwWLYz1D12PE8CyjU_!!1649180155.jpg", + "item_key": "", + "item_title": "巴拉巴拉儿童手套小童宝宝可爱保暖冬季新款加绒男童女童滑雪骑行", + "item_bbox": "140 102 385 559", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01ffgfwi2C5myfxduuL_!!2200714088423.jpg", + "item_key": "", + "item_title": "骑士西服夏季薄款比赛西服骑马装备马术用品骑马服装男马术西装男", + "item_bbox": "0 409 544 672", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01VLaWZs1TZQ4tJcUY3_!!2209480702396.jpg", + "item_key": "", + "item_title": "美人鱼儿童滑雪手套女童秋冬季保暖卡通连指加厚防水玩雪防寒手套", + "item_bbox": "227 202 761 1231", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01u4SKpj2EeicjTwoDo_!!2218785708770.jpg", + "item_key": "", + "item_title": "贝易宝宝游戏宇航员围栏地上爬行儿童垫室内家用婴儿客厅搭防护栏", + "item_bbox": "6 103 787 687", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN019CRorl21l2g1cjZJT_!!2983867024-0-beehive-scenes.jpg", + "item_key": "", + "item_title": "VECTOR玩可拓新款儿童滑雪手套分指防水保暖户外滑雪手套女童男童", + "item_bbox": "109 138 403 767", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01lK07J02FtCcKyfKjg_!!2217456968937.jpg", + "item_key": "", + "item_title": "高品质拔萝卜玩具 可啃咬宝宝早教抓握训练益智婴幼儿玩具", + "item_bbox": "0 216 798 798", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01nrr6711XCITcCwyz8_!!4611686018427385015-0-item_pic.jpg", + "item_key": "", + "item_title": "水星家纺凉感毯A类抑菌毛毯夏季凉爽午休可水洗单人空调毯旅行毯", + "item_bbox": "281 221 698 672", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01gul6AX1XoJKY8SkbM_!!1727182970.jpg", + "item_key": "", + "item_title": "URAX2024冬季新款女装雅丹风简约立领棉衣面包服棉服外套", + "item_bbox": "108 34 1076 1037", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01LOS41r1KhokVy1Cwq_!!2210718421196.jpg", + "item_key": "", + "item_title": "性感复古印花微透网纱立领上衣女夏季新款国风新中式气质连体背心", + "item_bbox": "183 286 321 511", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01Xr07721jz6462LEs8_!!4611686018427386202-0-item_pic.jpg", + "item_key": "", + "item_title": "优选质CD收纳架iPS4游戏碟片架桌面CD架游戏光盘架子展示支架收", + "item_bbox": "105 203 671 658", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01OCDbuY1SiI6wVIzsj_!!2220203442280.jpg", + "item_key": "", + "item_title": "【顺丰次日达】晶华USB 2.0扩展器 USB HUB+TFSD读卡 电脑集线器", + "item_bbox": "45 139 741 620", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01hUis9m1uptUhycg6a_!!2806646087.jpg", + "item_key": "", + "item_title": "创意陶瓷大容量马克杯早餐杯甜品杯个性北欧家用可微波卡通牛奶杯", + "item_bbox": "18 128 779 666", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01Ab0cyc1xKhgab3YsV_!!2217905626425.jpg", + "item_key": "", + "item_title": "Cross rPint 字Crew Neck Short Sle45617eveW hite T-Shirt 十架", + "item_bbox": "160 42 640 620", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01yrhoTK2KSFFwjk1Zx_!!2215666919555.jpg", + "item_key": "", + "item_title": "合金拖车玩具道路拯救车城市平板运输吊车汽车运输模型工程汽车男", + "item_bbox": "63 368 704 745", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01BPgAIe1XnOaTZ1pje_!!2216617172968.jpg", + "item_key": "", + "item_title": "护脚踝套冬季保暖套脚腕护踝石墨烯保暖防寒女脚脖子扭伤理疗神器", + "item_bbox": "374 73 766 622", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01q96U7w1efKsjmPSml_!!4611686018427381322-0-item_pic.jpg", + "item_key": "", + "item_title": "适用华为nova13手机壳全包防摔华为nova12pro曲面屏高级感nove11毛绒挂绳10硅胶保护套9超火新款女咖色帽子kt", + "item_bbox": "100 10 572 660", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01hTdB1r1EqcITbwEmE_!!0-item_pic.jpg", + "item_key": "", + "item_title": "惠威新款DIY专用双8寸落地酸枝实木木皮音箱空箱", + "item_bbox": "165 15 397 712", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01o8qFQC2HU85uh2Sfh_!!277029153.jpg", + "item_key": "", + "item_title": "【富山草莓】秋冬多巴胺樱桃小猫加厚全棉磨毛四件套纯棉床单被套", + "item_bbox": "0 0 798 798", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01Tk6K5c2CEUZSNMgW8_!!2215990558442.jpg", + "item_key": "", + "item_title": "科里芙健身衣女宽松休闲透气瑜伽服专业跑步训练高级感运动T短袖", + "item_bbox": "300 54 494 286", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40105", + "query_tfsid": "O1CN01Rw6Qzj20c3hIpdDco_!!4611686018427386181-0-imgsearch.jpg", + "query_bbox": "283 206 426 522", + "query_text": "来个粉色的吧", + "item_id": "", + "item_tfsid": "O1CN01mFTOU61bHZSt3G39Y_!!50983440.jpg", + "item_key": "", + "item_title": "弹簧剪纱剪绣花裁缝剪家用缝纫剪线头型小剪刀剪线头剪刀携带ABS", + "item_bbox": "26 683 472 1408", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01oIbtKZ1HNGAtw0GD5_!!2214182960745.jpg", + "item_key": "", + "item_title": "DOBE 任天堂switch 续航版NS手柄二代直插式握把一体直连震动体感", + "item_bbox": "0 389 749 956", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "0" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01RSGpXK1alyFWZfwjF_!!2667943371.jpg", + "item_key": "", + "item_title": "8Bitdo/八位堂 Ultimate手机游戏手柄 蓝牙 霍尔效应摇杆 黑 新款", + "item_bbox": "85 484 1411 1016", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN013avaJR1Gs6pbYAJHC_!!0-item_pic.jpg", + "item_key": "", + "item_title": "卡通呆呆猫咪抱枕被子两用靠垫珊瑚绒汽车办公室空调被靠枕毯枕头", + "item_bbox": "82 65 756 657", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01TV1LyB28MxWz2BtUA_!!2208628707919.jpg", + "item_key": "", + "item_title": "善能Q101无线拉伸游戏手柄安卓苹果手机平板电脑switch震动体感", + "item_bbox": "703 796 2585 1755", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01zhsPPq1Id7SEhvPqM_!!1746960915.jpg", + "item_key": "", + "item_title": "辣妹不规则修身显瘦设计感短袖T恤休闲阔腿裤2025夏季新款套装女", + "item_bbox": "206 434 412 915", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN010p70701Ka20Lb8wU4_!!2209735461179.jpg", + "item_key": "", + "item_title": "蛋仔派对游戏手柄一键双刀三刀快速高低抛苹果安卓通用外设", + "item_bbox": "336 388 781 736", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN0193jGpG1tPxrI5pzap_!!2213307625895.png", + "item_key": "", + "item_title": "职场新人百搭时尚通勤提花吊带2025夏新款不挑人显瘦流行爆款美背", + "item_bbox": "86 31 742 743", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01NgvS9q21gT0xYJ9mr_!!2201503607014.jpg", + "item_key": "", + "item_title": "HKII游戏手柄手机原神手游我的世界小鸡悟饭模拟器苹果安卓PC笔记本电脑蓝牙无线绝区零黑神话燕云十六声", + "item_bbox": "20 269 549 628", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01qUBtNs1EVYQnbJlp9_!!3916470357.jpg", + "item_key": "", + "item_title": "F383 2025美式高街MA1飞行员夹克棉服痞帅廓形设计感夹棉外套男女", + "item_bbox": "257 197 1255 1734", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01KUD8n527QKoBQ5zwJ_!!775177791.jpg", + "item_key": "", + "item_title": "拉夏贝尔丹宁蓝天丝直筒牛仔裤女夏薄款高个子窄版加长冰丝阔腿裤", + "item_bbox": "297 71 504 743", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01xKnp1I2Ex2Os2n3rX_!!755838810.jpg", + "item_key": "", + "item_title": "背包旅游轻便大容量登山包女2025新款旅行包男书包户外徒步双肩包", + "item_bbox": "174 227 605 693", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01qy47mz1y95Kwk9hZL_!!165936535.jpg", + "item_key": "", + "item_title": "童泰夏季新款婴儿薄款翻领飞袖连体衣女宝洋气短袖哈衣满印爬爬服", + "item_bbox": "185 104 620 702", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01k1mlsT1rPO4L3p1Xx_!!1830715623.jpg", + "item_key": "", + "item_title": "迷你创意布丁杯果冻一次性塑料透明杯子方形烘焙盒子慕斯杯甜品台", + "item_bbox": "155 187 642 641", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01JRY8JZ1oUTczZ00lT_!!3545645228.jpg", + "item_key": "", + "item_title": "SANDMARC Travel Pouch 手机镜头 单肩手提整理收纳包 摄影包", + "item_bbox": "216 349 1261 1238", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01CmERIn1JMuV6IFEc6_!!2507181015.jpg", + "item_key": "", + "item_title": "石材水泥切大理石的切割片开墙糟125花岗岩混凝土干切专用锯片", + "item_bbox": "1 1 797 797", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01ls8YlR23DjNQxlcCT_!!2215860277222-0-third_party_goods_pic.jpg", + "item_key": "", + "item_title": "屈臣氏cos小恶魔漫画假睫毛仙子毛女自然仿真嫁接可分段上眼睫毛", + "item_bbox": "29 408 797 798", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01GRuMiv21KwRaroplD_!!152066967.jpg", + "item_key": "", + "item_title": "马摆件工艺品马拉车招财骏马金马装饰马到成功马上发财马年吉祥物", + "item_bbox": "96 127 710 789", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01FiXf4p1Ffv3SYuNKc_!!2220082700515.jpg", + "item_key": "", + "item_title": "简约木质报刊架落地书报架创意杂志架报夹办公报纸架宣传资料架子", + "item_bbox": "116 18 303 384", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01Tuli0c2DtXmZfPGiZ_!!2219562208667.jpg", + "item_key": "", + "item_title": "东耐伦智能紫外线电动牙刷架消毒器杀菌风干架子壁挂式免打孔情侣", + "item_bbox": "76 219 737 507", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN016dryZz2Dkprk4oyR0_!!0-item_pic.jpg", + "item_key": "", + "item_title": "VeeLa 蕾丝雪纺衫", + "item_bbox": "256 1 716 796", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN0109aplp1EnPwqMJkD9_!!2999120396.jpg", + "item_key": "", + "item_title": "美式加绒运动卫裤男款冬季硬汉风健身训练裤子cleanfit垂感弯刀裤", + "item_bbox": "589 628 778 1414", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01YPEgcH1mM6uyLx241_!!1834424939.jpg", + "item_key": "", + "item_title": "依古拉水晶珠帘门帘玄关隔断成品帘子挂帘吊客厅屏风橄榄切面 454", + "item_bbox": "37 0 701 932", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01oBHXRV1dwuO5l2l6T_!!2201508063801.jpg", + "item_key": "", + "item_title": "速干裤男2026春夏季薄款休闲宽松直筒裤户外防水运动冲锋多袋裤潮", + "item_bbox": "236 28 549 778", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN01T0Kqhf2FlPy82pkr3_!!3897518920.jpg", + "item_key": "", + "item_title": "国内代购CK Jeans男士休闲松紧腰系带针织短裤J325563 吊牌990八", + "item_bbox": "211 402 1305 1527", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40106", + "query_tfsid": "O1CN01ExrKWE1PSJTPCKxbD_!!4611686018427387695-0-imgsearch.jpg", + "query_bbox": "270 162 551 373", + "query_text": "要个DOBE牌的Switch手柄", + "item_id": "", + "item_tfsid": "O1CN018DcvWX1j3O42l25hR_!!765304492.jpg", + "item_key": "", + "item_title": "韩国MLB儿童帽24年夏季新款男孩女孩拼色款网眼透气遮阳防晒帽", + "item_bbox": "90 141 698 614", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40107", + "query_tfsid": "O1CN01bNZr0U1Rsziwbmf47_!!4611686018427380632-0-imgsearch.jpg", + "query_bbox": "164 177 439 524", + "query_text": "想要个FILA的", + "item_id": "", + "item_tfsid": "O1CN01jNSMJ71xEkceybXSS_!!6000000006412-0-tbvideo.jpg", + "item_key": "", + "item_title": "FILA 斐乐官方女士梭织外套2025夏新款户外运动基础防晒连帽上衣", + "item_bbox": "424 323 805 773", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "0" + }, + { + "rn": "40107", + "query_tfsid": "O1CN01bNZr0U1Rsziwbmf47_!!4611686018427380632-0-imgsearch.jpg", + "query_bbox": "164 177 439 524", + "query_text": "想要个FILA的", + "item_id": "", + "item_tfsid": "O1CN01eKEpNp1gxJgnRVpkE_!!4611686018427382672-0-fleamarket.jpg", + "item_key": "", + "item_title": "可隆女款外套", + "item_bbox": "29 470 964 1676", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40107", + "query_tfsid": "O1CN01bNZr0U1Rsziwbmf47_!!4611686018427380632-0-imgsearch.jpg", + "query_bbox": "164 177 439 524", + "query_text": "想要个FILA的", + "item_id": "", + "item_tfsid": "O1CN01gul6AX1XoJKY8SkbM_!!1727182970.jpg", + "item_key": "", + "item_title": "URAX2024冬季新款女装雅丹风简约立领棉衣面包服棉服外套", + "item_bbox": "108 34 1076 1037", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40107", + "query_tfsid": "O1CN01bNZr0U1Rsziwbmf47_!!4611686018427380632-0-imgsearch.jpg", + "query_bbox": "164 177 439 524", + "query_text": "想要个FILA的", + "item_id": "", + "item_tfsid": "O1CN01oQtq1t1UUD8Ol6rn2_!!2216684472520.jpg", + "item_key": "", + "item_title": "衣尺街指洞防晒衣女大码新款轻薄透气冰丝宽松显瘦运动凉感防晒服", + "item_bbox": "203 62 595 743", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40107", + "query_tfsid": "O1CN01bNZr0U1Rsziwbmf47_!!4611686018427380632-0-imgsearch.jpg", + "query_bbox": "164 177 439 524", + "query_text": "想要个FILA的", + "item_id": "", + "item_tfsid": "O1CN01bdflBD1rPqAb99SV4_!!0-item_pic.jpg", + "item_key": "", + "item_title": "新品劳保鞋男士夏季防滑透气钢头防砸防刺穿四季款轻便安全工地工", + "item_bbox": "39 309 766 751", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40107", + "query_tfsid": "O1CN01bNZr0U1Rsziwbmf47_!!4611686018427380632-0-imgsearch.jpg", + "query_bbox": "164 177 439 524", + "query_text": "想要个FILA的", + "item_id": "", + "item_tfsid": "O1CN01GnPw6P1ibRvkLAt3s_!!2218064804431.jpg", + "item_key": "", + "item_title": "定金(力口薇d65797 )夏专柜正品代购女士夹克外套-", + "item_bbox": "0 132 798 692", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40107", + "query_tfsid": "O1CN01bNZr0U1Rsziwbmf47_!!4611686018427380632-0-imgsearch.jpg", + "query_bbox": "164 177 439 524", + "query_text": "想要个FILA的", + "item_id": "", + "item_tfsid": "O1CN010eg20g1ePlTli5pPp_!!2973343864.jpg", + "item_key": "", + "item_title": "欧洲单男女款布莱雅克黑牦牛考杜拉CORDURA 尼龙混纺抓绒外套", + "item_bbox": "11 60 718 1085", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40107", + "query_tfsid": "O1CN01bNZr0U1Rsziwbmf47_!!4611686018427380632-0-imgsearch.jpg", + "query_bbox": "164 177 439 524", + "query_text": "想要个FILA的", + "item_id": "", + "item_tfsid": "O1CN01GInstz1g6dvV9pZrj_!!405734093.png", + "item_key": "", + "item_title": "JAKET爵克女装国内代购春夏夹克外套 03F0530210 1069", + "item_bbox": "0 44 653 977", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40107", + "query_tfsid": "O1CN01bNZr0U1Rsziwbmf47_!!4611686018427380632-0-imgsearch.jpg", + "query_bbox": "164 177 439 524", + "query_text": "想要个FILA的", + "item_id": "", + "item_tfsid": "O1CN0199AhOU1dqUj9IR0AD_!!896113787.jpg", + "item_key": "", + "item_title": "2023原创y2k辣妹软皮包高级感托特包斜挎单肩休闲大容量包包女", + "item_bbox": "172 258 530 545", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40107", + "query_tfsid": "O1CN01bNZr0U1Rsziwbmf47_!!4611686018427380632-0-imgsearch.jpg", + "query_bbox": "164 177 439 524", + "query_text": "想要个FILA的", + "item_id": "", + "item_tfsid": "O1CN01YCIDku1ZaEL5dsjGt_!!902613210.jpg", + "item_key": "", + "item_title": "KOLONSPORT2024夏专柜正品女士夹克外套LKJK4MN120-1190", + "item_bbox": "175 151 1047 1241", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40107", + "query_tfsid": "O1CN01bNZr0U1Rsziwbmf47_!!4611686018427380632-0-imgsearch.jpg", + "query_bbox": "164 177 439 524", + "query_text": "想要个FILA的", + "item_id": "", + "item_tfsid": "O1CN01k5dsjV1dD6lG2bPp9_!!0-fleamarket.jpg", + "item_key": "", + "item_title": "120升涡流研磨机 9成9新 内胶漂亮 合适联系!", + "item_bbox": "0 495 1277 1703", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40107", + "query_tfsid": "O1CN01bNZr0U1Rsziwbmf47_!!4611686018427380632-0-imgsearch.jpg", + "query_bbox": "164 177 439 524", + "query_text": "想要个FILA的", + "item_id": "", + "item_tfsid": "O1CN01PRcpO31yOCB9CeERr_!!3390256568.jpg", + "item_key": "", + "item_title": "T212287182骆驼户外休闲茄克女春夏新款运动防风上衣女式弹力外套", + "item_bbox": "88 52 652 794", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40107", + "query_tfsid": "O1CN01bNZr0U1Rsziwbmf47_!!4611686018427380632-0-imgsearch.jpg", + "query_bbox": "164 177 439 524", + "query_text": "想要个FILA的", + "item_id": "", + "item_tfsid": "O1CN01pDOYWQ1ZWZF16R0Vp_!!4611686018427386322-0-item_pic.jpg", + "item_key": "", + "item_title": "台球集球器台球桌托盘天盛者静音自动回球轨道黑八回球器", + "item_bbox": "0 0 798 798", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + }, + { + "rn": "40107", + "query_tfsid": "O1CN01bNZr0U1Rsziwbmf47_!!4611686018427380632-0-imgsearch.jpg", + "query_bbox": "164 177 439 524", + "query_text": "想要个FILA的", + "item_id": "", + "item_tfsid": "O1CN015a6Dru1rbklr2c7Uk_!!2218741065650.jpg", + "item_key": "", + "item_title": "KOLON SPORT可隆户外休闲衣女运动夹克帽子可收纳徒步露营外套潮", + "item_bbox": "412 327 1017 1117", + "ctr_v1cnn": "", + "ctr_v2cnn": "", + "label": "1" + } +] \ No newline at end of file diff --git a/code/multi_vlm2vec_train/case.py b/code/multi_vlm2vec_train/case.py new file mode 100644 index 0000000000000000000000000000000000000000..7e27442a3d9483ee83e69fdd8c63e1e907b6acbe --- /dev/null +++ b/code/multi_vlm2vec_train/case.py @@ -0,0 +1,26 @@ +import json +with open('/data/oss_bucket_0/liqi/dataset/embedding_pf/bianji_train.json',"r", encoding="utf-8") as f: + data = json.load(f) +number_1 = 0 +number_0 = 0 +print(data[0].keys()) +print(data[0]) +print(data[1]) +print(data[2]) +number = 0 +# for i in data: + # if i['label'] == '0': + # number += 1 + # print(i) + # break + # if i['rn'] == '037a6b4e192533b2e0dc9ab3fb692806': + # number += 1 + # if i['label'] == '0': + # number_0 += 1 + # print(i) + # if i['label'] == '1': + # number_1 += 1 + +print(number_0) +print(number_1) +print(number) \ No newline at end of file diff --git a/code/multi_vlm2vec_train/collators/__init__.py b/code/multi_vlm2vec_train/collators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..07434926acfd77332f01186bca6db57cf52cea82 --- /dev/null +++ b/code/multi_vlm2vec_train/collators/__init__.py @@ -0,0 +1,11 @@ +COLLATORS = {} + +def register_collator(name): + def register_collator_cls(cls): + if name in COLLATORS: + return COLLATORS[name] + COLLATORS[name] = cls + return cls + return register_collator_cls + +from .tuwen_tbstars import TuwenTBStarsInfonceDataCollator diff --git a/code/multi_vlm2vec_train/collators/__pycache__/__init__.cpython-310.pyc b/code/multi_vlm2vec_train/collators/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b83dde9209382a46b3cd382ccb9be5946e1fb1a7 Binary files /dev/null and b/code/multi_vlm2vec_train/collators/__pycache__/__init__.cpython-310.pyc differ diff --git a/code/multi_vlm2vec_train/collators/__pycache__/__init__.cpython-313.pyc b/code/multi_vlm2vec_train/collators/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f91ecf608e4869f9e012b9ce548fbfeedb49d9a Binary files /dev/null and b/code/multi_vlm2vec_train/collators/__pycache__/__init__.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/collators/__pycache__/base.cpython-310.pyc b/code/multi_vlm2vec_train/collators/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7ea5158748979b1f03d5b027060e6af5b1cdc76 Binary files /dev/null and b/code/multi_vlm2vec_train/collators/__pycache__/base.cpython-310.pyc differ diff --git a/code/multi_vlm2vec_train/collators/__pycache__/base.cpython-313.pyc b/code/multi_vlm2vec_train/collators/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50862b4bf6f2817a8682fa7ec74bb303230bf7ea Binary files /dev/null and b/code/multi_vlm2vec_train/collators/__pycache__/base.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/collators/__pycache__/tuwen_qwen3vl.cpython-313.pyc b/code/multi_vlm2vec_train/collators/__pycache__/tuwen_qwen3vl.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de8022ed1cc03fb8708382046d63323bc5b9c497 Binary files /dev/null and b/code/multi_vlm2vec_train/collators/__pycache__/tuwen_qwen3vl.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/collators/__pycache__/tuwen_qwen3vl_eval.cpython-310.pyc b/code/multi_vlm2vec_train/collators/__pycache__/tuwen_qwen3vl_eval.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0cec9f6b2554debd0187126505162ca698ad5fe0 Binary files /dev/null and b/code/multi_vlm2vec_train/collators/__pycache__/tuwen_qwen3vl_eval.cpython-310.pyc differ diff --git a/code/multi_vlm2vec_train/collators/__pycache__/tuwen_qwen3vl_eval.cpython-313.pyc b/code/multi_vlm2vec_train/collators/__pycache__/tuwen_qwen3vl_eval.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6add3e33d36d37217a15e686f9f6db616051a174 Binary files /dev/null and b/code/multi_vlm2vec_train/collators/__pycache__/tuwen_qwen3vl_eval.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/collators/__pycache__/tuwen_tbstars.cpython-310.pyc b/code/multi_vlm2vec_train/collators/__pycache__/tuwen_tbstars.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9aa0c641c6fd3be0b87e63b91a76658dceffb510 Binary files /dev/null and b/code/multi_vlm2vec_train/collators/__pycache__/tuwen_tbstars.cpython-310.pyc differ diff --git a/code/multi_vlm2vec_train/collators/__pycache__/tuwen_tbstars.cpython-313.pyc b/code/multi_vlm2vec_train/collators/__pycache__/tuwen_tbstars.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70293daf0ec585648211a0e15614bf514d35658e Binary files /dev/null and b/code/multi_vlm2vec_train/collators/__pycache__/tuwen_tbstars.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/collators/base.py b/code/multi_vlm2vec_train/collators/base.py new file mode 100644 index 0000000000000000000000000000000000000000..6ee6be04e5d4c33f670fbd16f2fd5ae85d8b35e9 --- /dev/null +++ b/code/multi_vlm2vec_train/collators/base.py @@ -0,0 +1,29 @@ +from abc import ABC, abstractmethod +from typing import Dict, Sequence, Optional + +import torch +from transformers import PreTrainedTokenizer, AutoProcessor + + +class BaseDataCollator(ABC, object): + """Collate examples for supervised fine-tuning.""" + def __init__( + self, + tokenizer: Optional[PreTrainedTokenizer] = None, + processor: Optional[AutoProcessor] = None, + mask_question_tokens: bool = True + ) -> None: + self.tokenizer = tokenizer + self.processor = processor + self.mask_question_tokens = mask_question_tokens + + @property + def IGNORE_TOKEN_ID(self) -> int: + return -100 + + @property + def PAD_TOKEN_ID(self) -> int: + return self.tokenizer.pad_token_id + + @abstractmethod + def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]: ... \ No newline at end of file diff --git a/code/multi_vlm2vec_train/collators/tuwen_qwen3vl.py b/code/multi_vlm2vec_train/collators/tuwen_qwen3vl.py new file mode 100644 index 0000000000000000000000000000000000000000..86b543cbf2ec195eac5a5753b87624f17ad6197f --- /dev/null +++ b/code/multi_vlm2vec_train/collators/tuwen_qwen3vl.py @@ -0,0 +1,42 @@ +## TBStars collator +import torch +from typing import Dict, List, Sequence, Tuple +from .base import BaseDataCollator +from qwen_vl_utils.vision_process import process_vision_info + + +class TuwenQwenInfonceDataCollator(BaseDataCollator): + def __init__(self, processor, max_length: int = 8192): + self.processor = processor + self.max_length = max_length + + def __call__(self, messages: Sequence[Dict]) -> Dict[str, torch.Tensor]: + query_messages = [message[0] for message in messages] + positive_messages = [message[1] for message in messages] + negative_messages = [message[2] for message in messages] + + ## 处理batch_messages + query_inputs = self.messages_process(query_messages) + positive_inputs = self.messages_process(positive_messages) + negative_inputs = self.messages_process(negative_messages) + + batch_query_dict = dict( + query_inputs=query_inputs, + positive_inputs=positive_inputs, + negative_inputs=negative_inputs, + ) + + return batch_query_dict + + def messages_process(self, query_messages): + query_texts = self.processor.apply_chat_template( + query_messages, add_generation_prompt=True, tokenize=False + ) + query_images, _ = process_vision_info(query_messages, image_patch_size=16) + query_videos, query_video_metadata = None, None + query_inputs = self.processor( + text=query_texts, images=query_images, videos=query_videos, video_metadata=query_video_metadata, truncation=True, + max_length=self.max_length, padding=True, do_resize=False, return_tensors='pt' + ) + return query_inputs + diff --git a/code/multi_vlm2vec_train/collators/tuwen_qwen3vl_eval.py b/code/multi_vlm2vec_train/collators/tuwen_qwen3vl_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..7e23d897d549ba695e81d74ae3ea144eb823bfed --- /dev/null +++ b/code/multi_vlm2vec_train/collators/tuwen_qwen3vl_eval.py @@ -0,0 +1,50 @@ +from typing import Dict, List, Sequence, Tuple +import torch +from .base import BaseDataCollator +from qwen_vl_utils.vision_process import process_vision_info + + +class TuwenQwenDataCollator(BaseDataCollator): + @property + def PAD_TOKEN_ID(self) -> int: + return self.tokenizer.pad_token_id + + def __call__(self, messages: Sequence[Dict]) -> Tuple[Dict[str, torch.Tensor], Dict[str, torch.Tensor], List[str], List[int]]: + ### 输入的是一个list,为batch大小 + ### query_tfs, query_message, doc_message + ### 首先处理一下query_message + new_query_messages = [] + new_doc_messages = [] + qids = [] + labels = [] + itemids = [] + for item in messages: + new_query_messages.append(item[1]) + new_doc_messages.append(item[2]) + qids.append(item[0]) + labels.append(item[3]) + itemids.append(item[4]) + + ## query message处理 + query_texts = self.processor.apply_chat_template( + new_query_messages, add_generation_prompt=True, tokenize=False + ) + query_images, _ = process_vision_info(new_query_messages, image_patch_size=16) + query_videos, query_video_metadata = None, None + query_inputs = self.processor( + text=query_texts, images=query_images, videos=query_videos, video_metadata=query_video_metadata, truncation=True, + max_length=2048, padding=True, do_resize=False, return_tensors='pt' + ) + + ## doc message 处理 + doc_texts = self.processor.apply_chat_template( + new_doc_messages, add_generation_prompt=True, tokenize=False + ) + doc_images, _ = process_vision_info(new_doc_messages, image_patch_size=16) + doc_videos, doc_video_metadata = None, None + doc_inputs = self.processor( + text=doc_texts, images=doc_images, videos=doc_videos, video_metadata=doc_video_metadata, truncation=True, + max_length=2048, padding=True, do_resize=False, return_tensors='pt' + ) + + return query_inputs, doc_inputs, qids, labels, itemids \ No newline at end of file diff --git a/code/multi_vlm2vec_train/collators/tuwen_tbstars.py b/code/multi_vlm2vec_train/collators/tuwen_tbstars.py new file mode 100644 index 0000000000000000000000000000000000000000..df46312d343cd0e99cf2e76078e3b639da4a6e70 --- /dev/null +++ b/code/multi_vlm2vec_train/collators/tuwen_tbstars.py @@ -0,0 +1,78 @@ +## TBStars collator +import torch +import random +from .base import BaseDataCollator +from . import register_collator +from typing import Dict, Sequence, Optional + +from models.tbstars_ecom_emb.src.data.template_guijiang import Template + +@register_collator("tuwen_tbstars_infonce") +class TuwenTBStarsInfonceDataCollator(BaseDataCollator): + def __init__( + self, + tokenizer = None, + processor = None, + mask_question_tokens = True, + template = None, + image_type = None, + text_require = True + ) -> None: + super().__init__(tokenizer,processor,mask_question_tokens) + if not template: + self.template = Template(processor, cutoff_len=256) + else: + self.template = template + self.image_type = image_type + self.text_require = text_require + @property + def PAD_TOKEN_ID(self) -> int: + return self.tokenizer.pad_token_id + + def __call__(self, messages: Sequence[Dict]) -> Dict[str, torch.Tensor]: + query_messages = [message[0] for message in messages] + positive_messages = [message[1] for message in messages] + negative_messages = [message[2] for message in messages] + + batch_messages = query_messages + positive_messages + negative_messages + ## 处理batch_messages + batch_query_dict = self.messages_process(batch_messages) + + return batch_query_dict + + def messages_process(self, query_messages): + ## 处理query_messages + query_features = [ + self.template.prepare_inputs_train(msg, image_type = self.image_type, text_require=self.text_require) + for msg in query_messages + ] + ## pixel_values, crop_positions, input_ids + query_input_ids = [fea["input_ids"] for fea in query_features] + query_input_ids_max_len = max([t.shape[-1] for t in query_input_ids]) + 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] + query_input_ids = torch.cat(pad_query_input_ids, dim=0) + query_attention_mask = (query_input_ids != self.tokenizer.pad_token_id).to(torch.long) + query_pixel_values = [] + query_crop_positions = [] + for fea in query_features: + if "pixel_values" in fea.keys(): + query_pixel_values.append(fea["pixel_values"]) + if "crop_positions" in fea.keys(): + query_crop_positions.append(fea["crop_positions"]) + if len(query_pixel_values) >= 1: + query_pixel_values = torch.cat(query_pixel_values, dim=0) + else: + query_pixel_values = None + if len(query_crop_positions) >=1: + query_crop_positions = torch.cat(query_crop_positions, dim=0) + else: + query_crop_positions = None + + batch_query_dict = dict( + input_ids=query_input_ids, + attention_mask=query_attention_mask, + pixel_values=query_pixel_values, + crop_positions=query_crop_positions, + ) + return batch_query_dict + diff --git a/code/multi_vlm2vec_train/collators/tuwen_tbstars_eval.py b/code/multi_vlm2vec_train/collators/tuwen_tbstars_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..a8c798c5f0211dc13f71b766f49a53cc62ab38a3 --- /dev/null +++ b/code/multi_vlm2vec_train/collators/tuwen_tbstars_eval.py @@ -0,0 +1,120 @@ +from typing import Dict, Sequence +import torch +from .base import BaseDataCollator +from typing import Dict, Sequence, Optional + +from models.tbstars_ecom_emb.src.data.template_guijiang import Template + +class TuwenTBStarsDataCollator(BaseDataCollator): + def __init__( + self, + tokenizer = None, + processor = None, + mask_question_tokens = True, + template = None, + image_type = None, + query_text_require = True, + doc_text_require = True + ) -> None: + super().__init__(tokenizer,processor,mask_question_tokens) + if not template: + self.template = Template(processor, cutoff_len=256) + else: + self.template = template + self.image_type = image_type + self.query_text_require = query_text_require + self.doc_text_require = doc_text_require + @property + def PAD_TOKEN_ID(self) -> int: + return self.tokenizer.pad_token_id + + def __call__(self, messages: Sequence[Dict]) -> Dict[str, torch.Tensor]: + ### 输入的是一个list,为batch大小 + ### query_tfs, query_message, doc_message + ### 首先处理一下query_message + + ''' + 目标输入格式: + 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|>" + prompt = "\n魔力彩虹圈塔弹簧圈发光专业弹力圈婴儿童女宝宝益智玩具早教男孩 玉延玩具店 叠叠圈/叠套玩具 福莱萌(母婴) mcs1048 3岁 塑料 中国大陆 男女通用 塑胶玩具 mcs1048" + prompts = [prompt, prompt] + + image_paths = ["demo.jpg", "demo.jpg"] + image_placeholder = "" + image_features, image_lens = process_image(image_paths, processor) + image_features = {f"item_{k}": v for k, v in image_features.items()} + + prompts = [prompt.replace("", f"{image_placeholder * image_len}") for prompt, image_len in zip(prompts, image_lens)] + prompts = [template.format(prompt=prompt) for prompt in prompts] + features = tokenizer(prompts, add_special_tokens=False, return_tensors="pt") + features = features.to("cuda") + + inputs = { + "item_input_ids": features["input_ids"], + "item_attention_mask": features["attention_mask"], + **image_features, + } + ''' + + new_query_messages = [] + new_doc_messages = [] + qids = [] + labels = [] + itemids = [] + for item in messages: + new_query_messages.append(item[1]) + new_doc_messages.append(item[2]) + qids.append(item[0]) + labels.append(item[3]) + itemids.append(item[4]) + + query_features = [ + self.template.prepare_inputs(msg, image_type = self.image_type, text_require=self.query_text_require) + for msg in new_query_messages + ] + + ## pixel_values, crop_positions, input_ids + query_input_ids = [fea["input_ids"] for fea in query_features] + query_input_ids_max_len = max([t.shape[-1] for t in query_input_ids]) + 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] + query_input_ids = torch.cat(pad_query_input_ids, dim=0) + query_attention_mask = (query_input_ids != self.tokenizer.pad_token_id).to(torch.long) + + query_pixel_values = [fea["pixel_values"] for fea in query_features] + query_pixel_values = torch.cat(query_pixel_values, dim=0) + query_crop_positions = [fea["crop_positions"] for fea in query_features] + query_crop_positions = torch.cat(query_crop_positions, dim=0) + + batch_query_dict = dict( + input_ids=query_input_ids, + attention_mask=query_attention_mask, + pixel_values=query_pixel_values, + crop_positions=query_crop_positions, + ) + + ## doc message 处理 + doc_features = [ + self.template.prepare_inputs(msg, image_type = self.image_type, text_require=self.doc_text_require) + for msg in new_doc_messages + ] + + ## pixel_values, crop_positions, input_ids + doc_input_ids = [fea["input_ids"] for fea in doc_features] + doc_input_ids_max_len = max([t.shape[-1] for t in doc_input_ids]) + 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] + doc_input_ids = torch.cat(pad_doc_input_ids, dim=0) + doc_attention_mask = (doc_input_ids != self.tokenizer.pad_token_id).to(torch.long) + + doc_pixel_values = [fea["pixel_values"] for fea in doc_features] + doc_pixel_values = torch.cat(doc_pixel_values, dim=0) + doc_crop_positions = [fea["crop_positions"] for fea in doc_features] + doc_crop_positions = torch.cat(doc_crop_positions, dim=0) + + batch_doc_dict = dict( + input_ids=doc_input_ids, + attention_mask=doc_attention_mask, + pixel_values=doc_pixel_values, + crop_positions=doc_crop_positions, + ) + + return batch_query_dict, batch_doc_dict, qids, labels, itemids \ No newline at end of file diff --git a/code/multi_vlm2vec_train/command.sh b/code/multi_vlm2vec_train/command.sh new file mode 100644 index 0000000000000000000000000000000000000000..01c5349feb7d939b1e9b870fa637dbe9f716bf87 --- /dev/null +++ b/code/multi_vlm2vec_train/command.sh @@ -0,0 +1,17 @@ +cloudcli-runner \ + --projects-dir /Users/yiqili \ + --allow-path /Users/yiqili \ + --name yiqili-nebula \ + -v + +cloudcli-ssh +claude-runner +/home/lyq494390/multi_vlm2vec_train + +CUDA_VISIBLE_DEVICES=3 python eval/eval_tuwen_qwen3vl.py + +CUDA_VISIBLE_DEVICES=0,1,2,3 python cot_gen/generate_cot.py --test +accelerate launch --num_processes 4 cot_eval/eval_local.py +python -m accelerate.commands.launch --num_processes 4 cot_eval/eval_local.py +CUDA_VISIBLE_DEVICES=3 python cot_eval/eval_local.py +python -m pip install jsonlines accelerate peft qwen_vl_utils \ No newline at end of file diff --git a/code/multi_vlm2vec_train/cot_eval/__init__.py b/code/multi_vlm2vec_train/cot_eval/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/multi_vlm2vec_train/cot_eval/__pycache__/__init__.cpython-313.pyc b/code/multi_vlm2vec_train/cot_eval/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbf918f737a0b8b1a99d3e0f1baa2df57c406c39 Binary files /dev/null and b/code/multi_vlm2vec_train/cot_eval/__pycache__/__init__.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/cot_eval/__pycache__/collator_tuwen_qwen3vl_cot_eval.cpython-313.pyc b/code/multi_vlm2vec_train/cot_eval/__pycache__/collator_tuwen_qwen3vl_cot_eval.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c1b36d400f7c661ea5e02581ff937f24d5c8d1f Binary files /dev/null and b/code/multi_vlm2vec_train/cot_eval/__pycache__/collator_tuwen_qwen3vl_cot_eval.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/cot_eval/__pycache__/datasets_tuwen_qwen3vl_cot_eval.cpython-313.pyc b/code/multi_vlm2vec_train/cot_eval/__pycache__/datasets_tuwen_qwen3vl_cot_eval.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d2fcc4da940350eb3bca1d80f0cd74cd9f8cd6e Binary files /dev/null and b/code/multi_vlm2vec_train/cot_eval/__pycache__/datasets_tuwen_qwen3vl_cot_eval.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/cot_eval/__pycache__/eval_config.cpython-313.pyc b/code/multi_vlm2vec_train/cot_eval/__pycache__/eval_config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d11129c80f464c8908bc6bd04079499a4d025247 Binary files /dev/null and b/code/multi_vlm2vec_train/cot_eval/__pycache__/eval_config.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/cot_eval/__pycache__/eval_local.cpython-313.pyc b/code/multi_vlm2vec_train/cot_eval/__pycache__/eval_local.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9545ca6f3b4078ce6b615e9e9a3e4780adffa956 Binary files /dev/null and b/code/multi_vlm2vec_train/cot_eval/__pycache__/eval_local.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/cot_eval/__pycache__/eval_tuwen_qwen3vl_cot.cpython-313.pyc b/code/multi_vlm2vec_train/cot_eval/__pycache__/eval_tuwen_qwen3vl_cot.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0be8caf9b1b6c92c540fe3c377ab07f48b454a2 Binary files /dev/null and b/code/multi_vlm2vec_train/cot_eval/__pycache__/eval_tuwen_qwen3vl_cot.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/cot_eval/collator_tuwen_qwen3vl_cot_eval.py b/code/multi_vlm2vec_train/cot_eval/collator_tuwen_qwen3vl_cot_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..b60d3ef3b00a2363d9eb4dddd3cd5b0477ada6dc --- /dev/null +++ b/code/multi_vlm2vec_train/cot_eval/collator_tuwen_qwen3vl_cot_eval.py @@ -0,0 +1,72 @@ +from typing import Dict, List, Sequence, Tuple + +import torch +from qwen_vl_utils.vision_process import process_vision_info + + +class CoTQueryEvalCollator: + """unique query 的 CoT 生成 collator。 + + 只 tokenize 到 generation prompt(`<|im_start|>assistant\\n`), + 左 padding,供 model.generate() 批量自回归生成 CoT 使用。 + 返回 (query_gen_inputs, q_idxs)。 + """ + + def __init__(self, processor, max_length: int = 2048): + self.processor = processor + self.max_length = max_length + + def __call__(self, instances: Sequence[Tuple]) -> Tuple[Dict[str, torch.Tensor], List[int]]: + q_idxs = [instance[0] for instance in instances] + query_messages = [instance[1] for instance in instances] + + query_texts = self.processor.apply_chat_template( + query_messages, add_generation_prompt=True, tokenize=False + ) + query_images, _ = process_vision_info(query_messages, image_patch_size=16) + + # generate 需要左 padding;processor 内部使用 tokenizer.padding_side + self.processor.tokenizer.padding_side = "left" + query_inputs = self.processor( + text=query_texts, images=query_images, videos=None, video_metadata=None, truncation=True, + max_length=self.max_length, padding=True, do_resize=False, return_tensors='pt' + ) + return query_inputs, q_idxs + + +class CoTDocEvalCollator: + """unique doc 的前向 collator,与训练时的 doc_messages_process 对齐(右 padding)。 + + 返回 (doc_inputs, d_idxs)。 + """ + + def __init__( + self, + processor, + max_length: int = 2048, + cot_emb_suffix: str = "<|im_end|>", + doc_append_eos: bool = False, + ): + self.processor = processor + self.max_length = max_length + self.cot_emb_suffix = cot_emb_suffix + self.doc_append_eos = doc_append_eos + + def __call__(self, instances: Sequence[Tuple]) -> Tuple[Dict[str, torch.Tensor], List[int]]: + d_idxs = [instance[0] for instance in instances] + doc_messages = [instance[1] for instance in instances] + + doc_texts = self.processor.apply_chat_template( + doc_messages, add_generation_prompt=True, tokenize=False + ) + if self.doc_append_eos: + doc_texts = [text + self.cot_emb_suffix for text in doc_texts] + + doc_images, _ = process_vision_info(doc_messages, image_patch_size=16) + + self.processor.tokenizer.padding_side = "right" + doc_inputs = self.processor( + text=doc_texts, images=doc_images, videos=None, video_metadata=None, truncation=True, + max_length=self.max_length, padding=True, do_resize=False, return_tensors='pt' + ) + return doc_inputs, d_idxs diff --git a/code/multi_vlm2vec_train/cot_eval/datasets_tuwen_qwen3vl_cot_eval.py b/code/multi_vlm2vec_train/cot_eval/datasets_tuwen_qwen3vl_cot_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..fdc72f5d611bdbedb1617df9e637aed814c9e13f --- /dev/null +++ b/code/multi_vlm2vec_train/cot_eval/datasets_tuwen_qwen3vl_cot_eval.py @@ -0,0 +1,239 @@ +import json +import os +import sys + +current_file_path = os.path.dirname(os.path.abspath(__file__)) +module_path = os.path.join(current_file_path, "../") +sys.path.append(module_path) + +from typing import Dict, List, Tuple + +from PIL import Image +from torch.utils.data import Dataset +from tqdm import tqdm + +# 与训练侧共用 system prompt,保证 train/inference 输入分布一致 +from train_cot.datasets_tuwen_qwen3vl_cot import COT_SYSTEM_PROMPTS, DOC_SYSTEM_PROMPT + +# 测试集图片在 OSS 上的前缀(与 eval/eval_tuwen_qwen3vl.py 使用的数据集一致) +OSS_TEST_IMAGE_PREFIX = "peifeng/multi_vlm2vec/dataset/merge/test_image" + +_OSS_BUCKET = None + + +def get_oss_bucket(): + """懒加载 OSS bucket:本地跑(image_path_prefix 命中)时完全不需要 oss2 依赖。""" + global _OSS_BUCKET + if _OSS_BUCKET is None: + # 与 baseline 评测共用同一个 bucket 配置,保证读到完全相同的测试图片 + from dataset.datasets_tuwen_qwen3vl import load_oss_bucket + _OSS_BUCKET = load_oss_bucket() + return _OSS_BUCKET + + +class CoTEvalData: + """解析 test_json 并按 query / doc 去重。 + + 测试集每行是一个 (query, doc) 对,同一个 query(或 doc)会重复出现。 + 这里把它拆成三份: + - unique_queries: [(query_tfsid, query_bbox, query_text)] + - unique_docs: [(item_tfsid, item_title, item_bbox)] + - pairs: [(q_idx, d_idx, label_index)] + query / doc 分别只做一次 CoT 生成 / 前向,最后按 pairs 查表算相似度。 + + 去重 key 用构成 message 的全部字段,即使同一 tfsid 带不同 bbox/text + 也不会被错误合并。 + """ + + label_index = {'0': 0, '1': 1} + + def __init__(self, args): + self.max_length = 512 + self.parse_json_data(args.test_json, args.max_lines) + + def parse_json_data(self, json_path: str, max_lines: int): + with open(json_path, 'r', encoding='utf-8') as f: + data = json.load(f) + + num_records_to_read = len(data) if max_lines < 0 else min(len(data), max_lines) + + self.unique_queries: List[Tuple[str, str, str]] = [] + self.unique_docs: List[Tuple[str, str, str]] = [] + self.pairs: List[Tuple[int, int, int]] = [] + query_key_to_idx: Dict[Tuple, int] = {} + doc_key_to_idx: Dict[Tuple, int] = {} + + for i in tqdm(range(num_records_to_read)): + try: + record = data[i] + query_key = ( + record['query_tfsid'], + record['query_bbox'], + record['query_text'][:self.max_length - 2], + ) + doc_key = ( + record['item_tfsid'], + record['item_title'][:self.max_length - 2], + record['item_bbox'], + ) + label = self.label_index[record['label']] + except Exception as e: + print("test dataset exception for record {}: {}".format(i, e)) + continue + + if query_key not in query_key_to_idx: + query_key_to_idx[query_key] = len(self.unique_queries) + self.unique_queries.append(query_key) + if doc_key not in doc_key_to_idx: + doc_key_to_idx[doc_key] = len(self.unique_docs) + self.unique_docs.append(doc_key) + + self.pairs.append((query_key_to_idx[query_key], doc_key_to_idx[doc_key], label)) + + assert len(self.pairs) > 0, "the number of valid item should larger than 0" + print("total of {} eval pairs, {} unique queries, {} unique docs (json {}).".format( + len(self.pairs), len(self.unique_queries), len(self.unique_docs), json_path)) + + +class _CoTEvalImageMixin: + """图片读取 / bbox 裁剪 / 长宽比处理(与 baseline 评测一致)。""" + + min_pixels = 4 * 32 * 32 + max_pixels = 200 * 32 * 32 + + @staticmethod + def _clamp_aspect_ratio(img: Image.Image, max_ratio: float = 100) -> Image.Image: + """如果图片长宽比超过 max_ratio,将其 resize 到长宽比等于 max_ratio。""" + w, h = img.size + assert w > 0 and h > 0 + ratio = max(w, h) / min(w, h) + if ratio <= max_ratio: + return img + if w > h: + new_w = int(h * max_ratio) + new_h = h + else: + new_w = w + new_h = int(w * max_ratio) + return img.resize((new_w, new_h), Image.BILINEAR) + + def _open_image(self, image_name: str) -> Image.Image: + if self.image_local_dir: + local_path = os.path.join(self.image_local_dir, image_name) + if os.path.exists(local_path): + return Image.open(local_path) + return Image.open(get_oss_bucket().get_object(f'{OSS_TEST_IMAGE_PREFIX}/{image_name}')) + + def get_image_from_oss(self, image_name: str, roi: str): + """返回 (crop 图, 整图),roi 非法时 crop 图退化为整图。""" + if len(roi.split(' ')) == 6: + roi = ' '.join(roi.split(' ')[:4]) + elif len(roi.split(' ')) == 4: + pass + else: + roi = 'ori' + + image = self._open_image(image_name) + if image.mode != "RGB": + image = image.convert("RGB") + + image_full = image.copy() + + if roi != 'ori': + xmin, ymin, xmax, ymax = [int(float(z)) for z in roi.split(' ')[:4]] + xmin = max(0, xmin) + xmax = min(image.width - 1, xmax) + ymin = max(0, ymin) + ymax = min(image.height - 1, ymax) + if (ymax - ymin) > 2 and (xmax - xmin) > 2: + image = image.crop((xmin, ymin, xmax, ymax)) + + # 如果image或者image_full长宽比超过100,将长宽比resize到100 + image = self._clamp_aspect_ratio(image, max_ratio=100) + image_full = self._clamp_aspect_ratio(image_full, max_ratio=100) + + return image, image_full + + @staticmethod + def _select_images(image_crop, image_full, image_type: str) -> List[Image.Image]: + if image_type == "full": + return [image_full] + if image_type == "crop": + return [image_crop] + return [image_full, image_crop] + + def _build_message(self, system_prompt: str, images: List[Image.Image], text: str) -> List[Dict]: + content = [ + {"type": "image", "image": image, "min_pixels": self.min_pixels, "max_pixels": self.max_pixels} + for image in images + ] + content.append({"type": "text", "text": text}) + return [ + {"role": "system", "content": [{"type": "text", "text": system_prompt}]}, + {"role": "user", "content": content}, + ] + + +class CoTQueryEvalDataset(_CoTEvalImageMixin, Dataset): + """unique query 数据集,产出 (q_idx, query_message)。""" + + def __init__(self, args, unique_queries: List[Tuple[str, str, str]]): + super().__init__() + self.args = args + self.unique_queries = unique_queries + self.image_type = getattr(args, "query_image_type", None) or args.image_type + self.image_local_dir = getattr(args, "image_path_prefix", None) + + prompt_index = getattr(args, "prompt_index", 0) + if not 0 <= prompt_index < len(COT_SYSTEM_PROMPTS): + prompt_index = 0 + self.cot_system_prompt = COT_SYSTEM_PROMPTS[prompt_index] + + def __len__(self): + return len(self.unique_queries) + + def __getitem__(self, index): + query_tfsid, query_bbox, query_text = self.unique_queries[index] + query_txt = f"prompt:{query_text}" if self.args.query_text_require else "" + + try_times = 3 + for i in range(try_times): + try: + query_image, query_image_full = self.get_image_from_oss(query_tfsid, query_bbox) + images = self._select_images(query_image, query_image_full, self.image_type) + return index, self._build_message(self.cot_system_prompt, images, query_txt) + except Exception as e: + print('exception for query getitem {}, try times {}/{} : {}'.format(index, i, try_times, e)) + + print("error testing (query {})".format(query_tfsid)) + return index, self._build_message(self.cot_system_prompt, [], "prompt:Empty.") + + +class CoTDocEvalDataset(_CoTEvalImageMixin, Dataset): + """unique doc 数据集,产出 (d_idx, doc_message)。""" + + def __init__(self, args, unique_docs: List[Tuple[str, str, str]]): + super().__init__() + self.args = args + self.unique_docs = unique_docs + self.image_type = getattr(args, "doc_image_type", None) or args.image_type + self.image_local_dir = getattr(args, "image_path_prefix", None) + + def __len__(self): + return len(self.unique_docs) + + def __getitem__(self, index): + item_tfsid, item_title, item_bbox = self.unique_docs[index] + doc_txt = f"title:{item_title}" if self.args.doc_text_require else "" + + try_times = 3 + for i in range(try_times): + try: + item_image, item_image_full = self.get_image_from_oss(item_tfsid, item_bbox) + images = self._select_images(item_image, item_image_full, self.image_type) + return index, self._build_message(DOC_SYSTEM_PROMPT, images, doc_txt) + except Exception as e: + print('exception for doc getitem {}, try times {}/{} : {}'.format(index, i, try_times, e)) + + print("error testing (doc {})".format(item_tfsid)) + return index, self._build_message(DOC_SYSTEM_PROMPT, [], "title:Empty.") diff --git a/code/multi_vlm2vec_train/cot_eval/eval_config.py b/code/multi_vlm2vec_train/cot_eval/eval_config.py new file mode 100644 index 0000000000000000000000000000000000000000..44a0e883e4169cb56c715287be9dac6baaacb3a0 --- /dev/null +++ b/code/multi_vlm2vec_train/cot_eval/eval_config.py @@ -0,0 +1,69 @@ +"""CoT embedding 本地评测参数文件。 + +在这里直接修改参数,然后运行: + python cot_eval/eval_local.py +无需在命令行传任何参数。 + +注意:bool 参数直接写 True / False(不是字符串)。 +""" +from dataclasses import dataclass +from typing import Optional + + +@dataclass +class EvalConfig: + # ------------------------------------------------------------------ + # 模型 + # ------------------------------------------------------------------ + # base 模型路径(与训练时的 model_local_path 一致) + model_id: str = "/data/oss_bucket_0/liqi/models/Qwen3-VL-Embedding-2B/" + emb_dim: int = 2048 + out_dim: int = 2048 + + # 训练产出的 checkpoint: + # lora=True -> lora_pth 为 LoRA adapter 目录(checkpoint-xxx),base 从 model_id 加载后 merge; + # lora=False -> lora_pth 为全参微调 checkpoint 目录(checkpoint-xxx),直接加载完整权重; + # 置空字符串则只评测 model_id 的 base 模型。 + lora: bool = False + # all_eval=False 时给到单个 checkpoint-xxx 目录; + # all_eval=True 时给到 run 根目录,会遍历其中所有 checkpoint-* + ckpt: int = 2500 + 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/" + lora_pth: str = f"{root_pth}/checkpoint-{ckpt}" + all_eval: bool = False + + # ------------------------------------------------------------------ + # 数据集(与 baseline 评测一致) + # ------------------------------------------------------------------ + test_data_type: str = "dapei" + test_json: str = f"/data/oss_bucket_0/liqi/dataset/embedding_pf/{test_data_type}_test.json" + max_lines: int = 100000000 + image_type: str = "both" # full / crop / both + query_image_type: Optional[str] = None # 不填则用 image_type + doc_image_type: Optional[str] = None # 不填则用 image_type + # 本地测试图片目录:命中则本地读取,找不到时回退 OSS;置 None 则全走 OSS + image_path_prefix: Optional[str] = "/data/oss_bucket_0/peifeng/multi_vlm2vec/dataset/merge/test_image" + query_text_require: bool = True + doc_text_require: bool = True + batch_size: int = 256 + + # ------------------------------------------------------------------ + # CoT 设置(需与训练配置保持一致) + # ------------------------------------------------------------------ + prompt_index: int = 0 + max_cot_new_tokens: int = 192 # 与训练 max_cot_length 对齐 + cot_emb_suffix: str = "<|im_end|>" + doc_append_eos: bool = False + # query = prompt + cot,序列比纯 embedding 评测长 + model_max_length: int = 2048 + + # ------------------------------------------------------------------ + # 结果保存 + # ------------------------------------------------------------------ + # 生成的 CoT 文本(qid -> cot),置空字符串则不保存 + # all_eval=True 时文件名自动加 checkpoint-xxx_ 前缀,每个 ckpt 一个文件 + save_cot_json: str = f"{root_pth}/eval_result/ckpt-{ckpt}/cot.json" + # 指标结果,置空字符串则不保存 + # all_eval=True 时所有 ckpt 汇总进这一个文件:{checkpoint-xxx: results} + result_json: str = f"{root_pth}/eval_result/ckpt-{ckpt}/metrics.json" + train_data_type: str = "" diff --git a/code/multi_vlm2vec_train/cot_eval/eval_local.py b/code/multi_vlm2vec_train/cot_eval/eval_local.py new file mode 100644 index 0000000000000000000000000000000000000000..28dced3650a161978b283210151538e535045fec --- /dev/null +++ b/code/multi_vlm2vec_train/cot_eval/eval_local.py @@ -0,0 +1,27 @@ +"""CoT embedding 本地评测入口。 + +用法:在 cot_eval/eval_config.py 中修改参数后,直接运行 + python cot_eval/eval_local.py + +单卡直接跑;多卡也可以用 + accelerate launch --num_processes 4 cot_eval/eval_local.py + python -m accelerate.commands.launch --num_processes 4 cot_eval/eval_local.py + python -m pip install jsonlines accelerate peft qwen_vl_utils +""" +import os +import sys + +current_file_path = os.path.dirname(os.path.abspath(__file__)) +module_path = os.path.join(current_file_path, "../") +sys.path.append(module_path) + +from cot_eval.eval_config import EvalConfig +from cot_eval.eval_tuwen_qwen3vl_cot import run_eval + + +if __name__ == "__main__": + args = EvalConfig() + print("eval config:") + for key, value in vars(args).items(): + print(f" {key}: {value}") + run_eval(args) diff --git a/code/multi_vlm2vec_train/cot_eval/eval_tuwen_qwen3vl_cot.py b/code/multi_vlm2vec_train/cot_eval/eval_tuwen_qwen3vl_cot.py new file mode 100644 index 0000000000000000000000000000000000000000..a7c86b59e0c14ca50ff7e7cb270e6d6530ea44f5 --- /dev/null +++ b/code/multi_vlm2vec_train/cot_eval/eval_tuwen_qwen3vl_cot.py @@ -0,0 +1,424 @@ +"""CoT embedding 评测脚本(query / doc 去重版)。 + +与 eval/eval_tuwen_qwen3vl.py(纯 embedding baseline)保持一致的部分: +- 测试数据格式、图片读取、bbox 裁剪、长宽比处理; +- doc 侧一次前向 + last-token pooling; +- emb_dim 截断、L2 归一化、cos 相似度; +- 指标计算(eval/eval_utils.py 的 tongkuan_score_print,sim_weight 相同); +- all_eval 遍历 checkpoint-* 的逻辑。 + +与 baseline 不同的仅有 query 侧 prompt 和 embedding 生成方式: +1. query 用训练时的 CoT system prompt,先 model.generate() 自回归生成 + 一段显式 CoT(直到 `<|im_end|>`),并保留 KV cache; +2. 复用 cache,仅增量前向尚未进入 cache 的尾 token 和 `<|im_end|>`, + 取 `<|im_end|>` 位置的 hidden state 作为 query embedding,避免重复编码图片、 + prompt 和 CoT,并与训练时 teacher forcing 下的 pooling 位置保持一致。 + +评测流程按三阶段执行,避免同一 query 重复生成 CoT: +- 阶段1:unique query 批量生成 CoT + cache 增量前向取 query embedding; +- 阶段2:unique doc 批量前向取 doc embedding; +- 阶段3:按原始 (query, doc) 对查表算 cos,再聚合指标。 +""" +import json +import re +import sys +import os + +current_file_path = os.path.dirname(os.path.abspath(__file__)) +module_path = os.path.join(current_file_path, "../") +sys.path.append(module_path) + +import argparse + +import accelerate +import torch +import torch.nn.functional as F +from accelerate import Accelerator +from peft import LoraConfig, PeftModel +from torch.utils.data import DataLoader +from tqdm import tqdm +from transformers.models.qwen3_vl.processing_qwen3_vl import Qwen3VLProcessor + +from train_cot.qwen3_vl_cot_embedding import Qwen3VLForCoTEmbedding, pooling_last +from cot_eval.datasets_tuwen_qwen3vl_cot_eval import ( + CoTEvalData, + CoTQueryEvalDataset, + CoTDocEvalDataset, +) +from cot_eval.collator_tuwen_qwen3vl_cot_eval import CoTQueryEvalCollator, CoTDocEvalCollator +from eval.eval_utils import tongkuan_score_print + + +def save_json(path, data): + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + with open(path, "w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False) + + +def build_query_cache_inputs( + sequences, gen_inputs, prompt_position_ids, past_key_values, suffix_ids, pad_token_id +): + """构造复用 generate KV cache 的 suffix 增量前向输入。""" + if len(suffix_ids) != 1: + raise ValueError("cot_emb_suffix must encode to exactly one token for cache-based pooling") + + prompt_len = gen_inputs["input_ids"].shape[1] + generated_ids = sequences[:, prompt_len:] + if generated_ids.shape[1] == 0: + raise ValueError("max_cot_new_tokens must be greater than 0") + + expected_cache_len = sequences.shape[1] - 1 + cache_len = past_key_values.get_seq_length() + if cache_len < expected_cache_len: + raise RuntimeError( + f"generation cache is shorter than expected: {cache_len} < {expected_cache_len}" + ) + if cache_len > expected_cache_len: + past_key_values.crop(expected_cache_len) + + eos_id = suffix_ids[0] + batch_size = sequences.shape[0] + cached_attention_mask = torch.zeros( + (batch_size, expected_cache_len), dtype=gen_inputs["attention_mask"].dtype, + device=sequences.device, + ) + cached_attention_mask[:, :prompt_len] = gen_inputs["attention_mask"] + + extension_ids_list = [] + first_position_offsets = [] + cot_ids_list = [] + for i, row in enumerate(generated_ids.tolist()): + if eos_id in row: + eos_position = row.index(eos_id) + cached_cot_len = eos_position + extension_ids = [eos_id] + first_position_offset = eos_position + 1 + cot_ids = row[:eos_position] + else: + cached_cot_len = len(row) - 1 + extension_ids = [row[-1], eos_id] + first_position_offset = len(row) + cot_ids = row + + cached_attention_mask[i, prompt_len:prompt_len + cached_cot_len] = 1 + extension_ids_list.append(extension_ids) + first_position_offsets.append(first_position_offset) + cot_ids_list.append(cot_ids) + + max_extension_len = max(len(ids) for ids in extension_ids_list) + extension_ids = torch.full( + (batch_size, max_extension_len), pad_token_id, dtype=sequences.dtype, + device=sequences.device, + ) + extension_attention_mask = torch.zeros( + (batch_size, max_extension_len), dtype=gen_inputs["attention_mask"].dtype, + device=sequences.device, + ) + extension_position_ids = torch.zeros( + (prompt_position_ids.shape[0], batch_size, max_extension_len), + dtype=prompt_position_ids.dtype, + device=sequences.device, + ) + pool_positions = torch.empty(batch_size, dtype=torch.long, device=sequences.device) + prompt_last_positions = prompt_position_ids[:, :, -1] + + for i, ids in enumerate(extension_ids_list): + extension_len = len(ids) + extension_ids[i, :extension_len] = torch.tensor(ids, dtype=sequences.dtype, device=sequences.device) + extension_attention_mask[i, :extension_len] = 1 + offsets = torch.arange( + first_position_offsets[i], first_position_offsets[i] + max_extension_len, + dtype=prompt_position_ids.dtype, + device=sequences.device, + ) + extension_position_ids[:, i, :] = prompt_last_positions[:, i, None] + offsets + pool_positions[i] = extension_len - 1 + + cache_inputs = { + "input_ids": extension_ids, + "attention_mask": torch.cat([cached_attention_mask, extension_attention_mask], dim=1), + "position_ids": extension_position_ids, + "past_key_values": past_key_values, + } + return cache_inputs, pool_positions, cot_ids_list + + +def eval(args): + ## 模型加载 + # lora=True:从 model_id 加载 base,再挂 lora_pth 下的 LoRA adapter 并 merge; + # lora=False 且 lora_pth 非空:lora_pth 视为全参微调 checkpoint,直接加载完整权重; + # lora=False 且 lora_pth 为空:只评测 base 模型。 + model_path = args.model_id + if args.lora: + model = Qwen3VLForCoTEmbedding.from_pretrained( + model_path, torch_dtype=torch.bfloat16, trust_remote_code=True + ) + print("Loading lora ckpt.") + lora_config = LoraConfig.from_pretrained(args.lora_pth) + lora_model = PeftModel.from_pretrained(model, args.lora_pth, config=lora_config) + model = lora_model.merge_and_unload() + elif args.lora_pth: + print(f"Loading full finetuned ckpt from {args.lora_pth}.") + model = Qwen3VLForCoTEmbedding.from_pretrained( + args.lora_pth, torch_dtype=torch.bfloat16, trust_remote_code=True + ) + else: + model = Qwen3VLForCoTEmbedding.from_pretrained( + model_path, torch_dtype=torch.bfloat16, trust_remote_code=True + ) + + model.eval() + model.requires_grad_(False) + # 生成 CoT 需要 kv cache(训练时被关掉了) + model.config.use_cache = True + if hasattr(model.config, "text_config"): + model.config.text_config.use_cache = True + + processor = Qwen3VLProcessor.from_pretrained(model_path, padding_side='right') + tokenizer = processor.tokenizer + + suffix_ids = tokenizer.encode(args.cot_emb_suffix, add_special_tokens=False) + if len(suffix_ids) != 1: + raise ValueError("cot_emb_suffix must encode to exactly one token for cache-based pooling") + if args.max_cot_new_tokens <= 0: + raise ValueError("max_cot_new_tokens must be greater than 0") + pad_token_id = tokenizer.pad_token_id + + accelerator = Accelerator(mixed_precision='bf16') + device = accelerator.device + is_main_process = accelerator.is_main_process + + ## 数据集加载:按 query / doc 去重 + eval_data = CoTEvalData(args) + query_dataset = CoTQueryEvalDataset(args, eval_data.unique_queries) + doc_dataset = CoTDocEvalDataset(args, eval_data.unique_docs) + + query_dataloader = DataLoader( + query_dataset, batch_size=args.batch_size, num_workers=4, + shuffle=False, collate_fn=CoTQueryEvalCollator(processor, args.model_max_length), + pin_memory=True, + ) + doc_dataloader = DataLoader( + doc_dataset, batch_size=args.batch_size, num_workers=4, + shuffle=False, collate_fn=CoTDocEvalCollator( + processor, args.model_max_length, args.cot_emb_suffix, args.doc_append_eos, + ), + pin_memory=True, + ) + + def tensors_to_device(data, device, dtype=model.dtype): + for key in data.keys(): + if isinstance(data[key], torch.Tensor): + if 'pixel_values' in key: + data[key] = data[key].to(device).to(dtype) + else: + data[key] = data[key].to(device) + return data + + emb_dim = args.emb_dim + + # 主进程收集:按去重后的索引存放 embedding / CoT 文本 + query_embed_all = torch.zeros(len(query_dataset), emb_dim, dtype=torch.float32) + doc_embed_all = torch.zeros(len(doc_dataset), emb_dim, dtype=torch.float32) + cot_by_qidx = {} + + with torch.no_grad(): + model, query_dataloader, doc_dataloader = accelerator.prepare( + model, query_dataloader, doc_dataloader + ) + unwrapped_model = accelerator.unwrap_model(model) + + ## 阶段1:unique query 生成 CoT + embedding + for query_gen_batch, q_idxs in tqdm(query_dataloader, desc="query cot+embed"): + query_gen_batch = tensors_to_device(query_gen_batch, device) + prompt_position_ids = unwrapped_model._prepare_position_ids_for_generation( + query_gen_batch["input_ids"], dict(query_gen_batch) + ) + # generate 的 kwargs 校验不接受 mm_token_type_ids,位置已在上面按 M-RoPE 算好 + gen_kwargs = {k: v for k, v in query_gen_batch.items() if k != "mm_token_type_ids"} + gen_kwargs["position_ids"] = prompt_position_ids + generation_output = unwrapped_model.generate( + **gen_kwargs, + max_new_tokens=args.max_cot_new_tokens, + do_sample=False, + eos_token_id=suffix_ids[-1], + pad_token_id=pad_token_id, + use_cache=True, + cache_implementation="dynamic_full", + return_dict_in_generate=True, + ) + sequences = generation_output.sequences + cache_inputs, pool_positions, cot_ids_list = build_query_cache_inputs( + sequences, + query_gen_batch, + prompt_position_ids, + generation_output.past_key_values, + suffix_ids, + pad_token_id, + ) + query_outputs = model(**cache_inputs) + row = torch.arange(query_outputs.last_hidden_state.shape[0], device=device) + query_embed = query_outputs.last_hidden_state[row, pool_positions] + query_embed = query_embed[..., :emb_dim] + query_embed = F.normalize(query_embed, p=2, dim=-1) + + cot_texts = [tokenizer.decode(ids, skip_special_tokens=True).strip() for ids in cot_ids_list] + + query_embed = accelerator.gather_for_metrics(query_embed) + q_idxs = accelerate.utils.gather_object(q_idxs)[:query_embed.size(0)] + cot_texts = accelerate.utils.gather_object(cot_texts)[:query_embed.size(0)] + + if is_main_process: + query_embed_all[list(q_idxs)] = query_embed.float().cpu() + for q_idx, cot in zip(q_idxs, cot_texts): + cot_by_qidx[q_idx] = cot + + del query_gen_batch, gen_kwargs, generation_output, sequences + del cache_inputs, pool_positions, query_outputs, query_embed + + ## 阶段2:unique doc embedding(与 baseline 相同,直接前向取 last token) + for doc_batch, d_idxs in tqdm(doc_dataloader, desc="doc embed"): + doc_batch = tensors_to_device(doc_batch, device) + doc_outputs = model(**doc_batch) + candidate_embed = pooling_last(doc_outputs.last_hidden_state, doc_batch.get('attention_mask')) + candidate_embed = candidate_embed[..., :emb_dim] + candidate_embed = F.normalize(candidate_embed, p=2, dim=-1) + + candidate_embed = accelerator.gather_for_metrics(candidate_embed) + d_idxs = accelerate.utils.gather_object(d_idxs)[:candidate_embed.size(0)] + + if is_main_process: + doc_embed_all[list(d_idxs)] = candidate_embed.float().cpu() + + del doc_batch, doc_outputs, candidate_embed + + accelerator.wait_for_everyone() + + ## 阶段3:按原始 (query, doc) 对查表算 cos,聚合指标 + results_all_dict = None + if is_main_process: + pair_q = torch.tensor([p[0] for p in eval_data.pairs], dtype=torch.long) + pair_d = torch.tensor([p[1] for p in eval_data.pairs], dtype=torch.long) + cos_sim = (query_embed_all[pair_q] * doc_embed_all[pair_d]).sum(dim=1).tolist() + + query_dic_all = {} + for (q_idx, d_idx, label), sim in zip(eval_data.pairs, cos_sim): + qid = eval_data.unique_queries[q_idx][0] + itemid = eval_data.unique_docs[d_idx][0] + if qid not in query_dic_all: + query_dic_all[qid] = {'label': [], 'sim': [], 'doc_tfs': []} + query_dic_all[qid]['label'].append(label) + query_dic_all[qid]['sim'].append(sim) + query_dic_all[qid]['doc_tfs'].append(itemid) + + results_all_dict = tongkuan_score_print(query_dic_all, sim_weight=[0.2, 0.2, 0.2, 0.2, 0.2]) + + if args.save_cot_json: + cot_records = [ + { + "query_tfsid": query_tfsid, + "query_text": query_text, + "cot": cot_by_qidx.get(q_idx, ""), + } + for q_idx, (query_tfsid, _query_bbox, query_text) in enumerate(eval_data.unique_queries) + ] + save_json(args.save_cot_json, cot_records) + print(f"generated cot saved to {args.save_cot_json}") + + if args.result_json: + save_json(args.result_json, results_all_dict) + + # all_eval 会在同一进程里连续评多个 ckpt,必须先把本次模型和 + # accelerator 持有的引用清干净再加载下一个,否则显存会累积到 OOM + del unwrapped_model + model, query_dataloader, doc_dataloader = accelerator.free_memory( + model, query_dataloader, doc_dataloader + ) + accelerator.wait_for_everyone() + + return results_all_dict + + +def insert_ckpt_name(path, ckpt_name): + """给 path 的文件名加上 checkpoint 前缀,遍历时每个 ckpt 落到独立文件。""" + if not path: + return path + dirname, basename = os.path.split(path) + return os.path.join(dirname, f"{ckpt_name}_{basename}") + + +def run_eval(args): + """入口逻辑:all_eval 时遍历 lora_pth 下所有 checkpoint-*,否则单次评测。 + + 命令行方式(nebula)和本地参数文件方式(eval_local.py)共用。 + 要求 args 上的 bool 字段已经是真正的 bool。 + + all_eval 时每个 ckpt 的 CoT 各存一个文件,指标则汇总进同一个 result_json + ({checkpoint-xxx: results}),每评完一个 ckpt 就落盘一次。 + """ + if args.all_eval: + lora_root_path = args.lora_pth + checkpoint_dirs = [ + os.path.join(lora_root_path, d) + for d in os.listdir(lora_root_path) + if os.path.isdir(os.path.join(lora_root_path, d)) and re.match(r"checkpoint-\d+", d) + ] + if not checkpoint_dirs: + raise ValueError( + f"all_eval=True but no checkpoint-* found under {lora_root_path}, " + "lora_pth should point to the run root dir" + ) + checkpoint_dirs.sort(key=lambda x: int(re.search(r"checkpoint-(\d+)", x).group(1))) + + save_cot_json, result_json = args.save_cot_json, args.result_json + args.result_json = "" # 单 ckpt 指标不单独落盘,由这里汇总 + metrics_all = {} + for ckpt_dir in checkpoint_dirs: + args.lora_pth = ckpt_dir + ckpt_name = os.path.basename(ckpt_dir) + args.save_cot_json = insert_ckpt_name(save_cot_json, ckpt_name) + results = eval(args) + if results is not None and result_json: + metrics_all[ckpt_name] = results + save_json(result_json, metrics_all) + print(f"metrics of {ckpt_name} saved to {result_json}") + else: + eval(args) + + +if __name__ == "__main__": + print("begin reading input parameters") + parser = argparse.ArgumentParser() + 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') + parser.add_argument('--max_lines', default=10000000, type=int, help='Limit the data length') + parser.add_argument('--model_max_length', type=int, default=2048) + parser.add_argument('--model_id', type=str, default="/data/oss_bucket_0/liqi/models/Qwen3-VL-Embedding-2B/") + parser.add_argument('--image_type', default="both", type=str) + parser.add_argument('--query_image_type', default=None, type=str, help='query side image type, fall back to image_type') + parser.add_argument('--doc_image_type', default=None, type=str, help='doc side image type, fall back to image_type') + parser.add_argument('--image_path_prefix', default=None, type=str, help='local test image dir; fall back to oss when missing') + parser.add_argument('--emb_dim', default=2048, type=int) + parser.add_argument('--out_dim', default=2048, type=int) + parser.add_argument('--batch_size', default=8, type=int) + parser.add_argument('--query_text_require', type=str, default='True') + parser.add_argument('--doc_text_require', type=str, default='True') + parser.add_argument('--lora', type=str, default='False') + parser.add_argument('--lora_pth', type=str, default='') + parser.add_argument('--train_data_type', type=str, default='') + parser.add_argument('--test_data_type', type=str, default='') + parser.add_argument('--all_eval', type=str, default='False') + # ---- CoT 相关参数,需与训练配置保持一致 ---- + parser.add_argument('--prompt_index', default=0, type=int, help='index of COT_SYSTEM_PROMPTS used at training') + parser.add_argument('--max_cot_new_tokens', default=192, type=int, help='max new tokens for cot generation, align with max_cot_length') + parser.add_argument('--cot_emb_suffix', default='<|im_end|>', type=str, help='suffix whose hidden state is pooled, align with training') + parser.add_argument('--doc_append_eos', type=str, default='False', help='align with training doc_append_eos') + 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') + parser.add_argument('--result_json', type=str, default='', help='if set, save metric results to this json') + args = parser.parse_args() + args.query_text_require = args.query_text_require.lower() == 'true' + args.doc_text_require = args.doc_text_require.lower() == 'true' + args.lora = args.lora.lower() == 'true' + args.all_eval = args.all_eval.lower() == 'true' + args.doc_append_eos = args.doc_append_eos.lower() == 'true' + + run_eval(args) \ No newline at end of file diff --git a/code/multi_vlm2vec_train/cot_eval/scripts/eval_local_qwen_cot.sh b/code/multi_vlm2vec_train/cot_eval/scripts/eval_local_qwen_cot.sh new file mode 100644 index 0000000000000000000000000000000000000000..893e69e8aa486ee6ca31320ca6216cbd3b8050c1 --- /dev/null +++ b/code/multi_vlm2vec_train/cot_eval/scripts/eval_local_qwen_cot.sh @@ -0,0 +1,61 @@ +# CoT embedding 评测:query 先 generate 出显式 CoT,再取 <|im_end|> 处的 embedding +# 除 query 侧 prompt / embedding 生成方式外,其余与 eval/eval_tuwen_qwen3vl.py 保持一致 +set -x + +## 分布式配置 +NUM_GPUS=1 + +## 模型设置(base 模型,与训练时的 model_local_path 一致) +MODEL_ID=/data/oss_bucket_0/liqi/models/Qwen3-VL-Embedding-2B/ +EMB_DIM=2048 +OUT_DIM=2048 + +## LoRA ckpt(训练产出) +LORA=True +LORA_PTH=/path/to/your/cot_run/checkpoint-xxx/ +## ALL_EVAL=True 时 LORA_PTH 给到 run 根目录,会遍历其中所有 checkpoint-* +ALL_EVAL=False + +## 数据集设置(与 baseline 评测一致) +TEST_JSON=/data/oss_bucket_0/liqi/dataset/embedding_pf/zhaoxiangsi_test.json +TEST_DATA_TYPE="zhaoxiangsi" +MAX_LINES=100000000 +IMAGE_TYPE="both" +QUERY_TEXT="True" +DOC_TEXT="True" +BATCH_SIZE=8 + +## CoT 设置(需与训练配置保持一致) +PROMPT_INDEX=0 +MAX_COT_NEW_TOKENS=192 +DOC_APPEND_EOS=False +## query = prompt + cot,序列比纯 embedding 评测长 +MODEL_MAX_LEN=2048 + +## 结果保存 +ckpt= +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" +RESULT_JSON=./cot_eval_output/${TEST_DATA_TYPE}_result.json + +echo "begin cot evaluation!" + +accelerate launch --num_processes ${NUM_GPUS} cot_eval/eval_tuwen_qwen3vl_cot.py \ + --test_json ${TEST_JSON} \ + --max_lines ${MAX_LINES} \ + --model_max_length ${MODEL_MAX_LEN} \ + --model_id ${MODEL_ID} \ + --image_type ${IMAGE_TYPE} \ + --emb_dim ${EMB_DIM} \ + --out_dim ${OUT_DIM} \ + --batch_size ${BATCH_SIZE} \ + --query_text_require ${QUERY_TEXT} \ + --doc_text_require ${DOC_TEXT} \ + --lora ${LORA} \ + --lora_pth ${LORA_PTH} \ + --test_data_type ${TEST_DATA_TYPE} \ + --all_eval ${ALL_EVAL} \ + --prompt_index ${PROMPT_INDEX} \ + --max_cot_new_tokens ${MAX_COT_NEW_TOKENS} \ + --doc_append_eos ${DOC_APPEND_EOS} \ + --save_cot_json ${SAVE_COT_JSON} \ + --result_json ${RESULT_JSON} diff --git a/code/multi_vlm2vec_train/cot_eval/scripts/eval_nebula_qwen_cot.sh b/code/multi_vlm2vec_train/cot_eval/scripts/eval_nebula_qwen_cot.sh new file mode 100644 index 0000000000000000000000000000000000000000..99c5a57748c61c45c6c4e43e209f8db76e7caca8 --- /dev/null +++ b/code/multi_vlm2vec_train/cot_eval/scripts/eval_nebula_qwen_cot.sh @@ -0,0 +1,113 @@ +#!/bin/bash +# CoT embedding 评测 - Nebula 提交(query 先 generate 出 CoT 再取 embedding) +# Usage: sh cot_eval/scripts/eval_nebula_qwen_cot.sh +# 远程机器上 OSS 挂载在 /data/oss_bucket_0/,模型/ckpt/图片/结果都直接走本地路径 +# 参数含义与 cot_eval/eval_config.py 一致,nebula 侧通过命令行传入 + +## 集群资源配置(单 worker 8 卡,accelerate 由 nebula 起的分布式环境自动识别) +CLUSTER_CONFIG='./cluster_cot_eval.json' +cat < ${CLUSTER_CONFIG} +{ + "worker": { + "gpu": 100, + "cpu": 1200, + "memory": 50000 + } +} +EOT + +WORKER_COUNT=8 + +## 模型设置(base 模型,与训练时的 model_local_path 一致) +MODEL_ID=/data/oss_bucket_0/peifeng/vlm2vec/models/qwen/Qwen3-VL-Embedding-2B/ +EMB_DIM=2048 +OUT_DIM=2048 + +## LoRA ckpt(训练产出) +LORA=True +YITU=shaixuan +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/ +### ALL_EVAL=False 时只评 checkpoint-${CKPT};True 时遍历 RUN_DIR 下所有 checkpoint-* +ALL_EVAL=True +CKPT=3500 +## python 侧按 lower() 解析,这里也忽略大小写,避免两侧判断不一致 +ALL_EVAL_LOWER=$(echo "${ALL_EVAL}" | tr '[:upper:]' '[:lower:]') +if [ "${ALL_EVAL_LOWER}" = "true" ]; then + LORA_PTH=${RUN_DIR} +else + LORA_PTH=${RUN_DIR}/checkpoint-${CKPT} +fi + +## 数据集设置(与 baseline 评测一致) +TEST_JSON=/data/oss_bucket_0/liqi/dataset/embedding_pf/${YITU}_test.json +TEST_DATA_TYPE=${YITU} +MAX_LINES=100000000 +IMAGE_TYPE="both" +### 图片所在的 OSS 挂载目录 +IMAGE_PATH_PREFIX=/data/oss_bucket_0/peifeng/multi_vlm2vec/dataset/merge/test_image +QUERY_TEXT=True +DOC_TEXT=True +BATCH_SIZE=128 + +## CoT 设置(需与训练配置保持一致) +PROMPT_INDEX=0 +MAX_COT_NEW_TOKENS=192 +DOC_APPEND_EOS=False +## query = prompt + cot,序列比纯 embedding 评测长 +MODEL_MAX_LEN=2048 + +## 结果保存 +## ALL_EVAL=True:每个 ckpt 的 cot 存成 checkpoint-xxx_cot.json(多文件), +## 指标全部汇总进 RESULT_JSON 一个文件:{checkpoint-xxx: results} +if [ "${ALL_EVAL_LOWER}" = "true" ]; then + SAVE_COT_JSON=${RUN_DIR}/eval_result/all/cot.json + RESULT_JSON=${RUN_DIR}/eval_result/all/metrics_${TEST_DATA_TYPE}.json +else + SAVE_COT_JSON=${RUN_DIR}/eval_result/ckpt-${CKPT}/cot2.json + RESULT_JSON=${RUN_DIR}/eval_result/ckpt-${CKPT}/metrics2.json +fi + +echo "begin cot evaluation!" + +args="\ + --test_json ${TEST_JSON} \ + --max_lines ${MAX_LINES} \ + --model_max_length ${MODEL_MAX_LEN} \ + --model_id ${MODEL_ID} \ + --image_type ${IMAGE_TYPE} \ + --image_path_prefix ${IMAGE_PATH_PREFIX} \ + --emb_dim ${EMB_DIM} \ + --out_dim ${OUT_DIM} \ + --batch_size ${BATCH_SIZE} \ + --query_text_require ${QUERY_TEXT} \ + --doc_text_require ${DOC_TEXT} \ + --lora ${LORA} \ + --lora_pth ${LORA_PTH} \ + --test_data_type ${TEST_DATA_TYPE} \ + --all_eval ${ALL_EVAL} \ + --prompt_index ${PROMPT_INDEX} \ + --max_cot_new_tokens ${MAX_COT_NEW_TOKENS} \ + --doc_append_eos ${DOC_APPEND_EOS} \ + --save_cot_json ${SAVE_COT_JSON} \ + --result_json ${RESULT_JSON}" + +nebulactl run mdl \ + --engine=xdl \ + --ignore=venv/*,data/*,.git/* \ + --worker_count=${WORKER_COUNT} \ + --queue=pailitao_algo_high_2 \ + --access_id=LTAI5tMZb5HHH6HHgAExAyiL \ + --access_key=6MVP8JnTE01t4TLUHhPoFV0swZNTrb \ + --entry=cot_eval/eval_tuwen_qwen3vl_cot.py \ + --oss_access_id=LTAI5tMZb5HHH6HHgAExAyiL \ + --oss_access_key=6MVP8JnTE01t4TLUHhPoFV0swZNTrb \ + --oss_bucket=pailitao-ai \ + --oss_endpoint=oss-cn-zhangjiakou-internal.aliyuncs.com \ + --algo_name=pytorch2100 \ + --file.cluster_file=${CLUSTER_CONFIG} \ + --user_params="$args" \ + --job_name="eval_qwen3vl_cot_dapei_full_single" \ + --requirements_file_name="./requirements_eval.txt" \ + --force + +rm ${CLUSTER_CONFIG} diff --git a/code/multi_vlm2vec_train/cot_gen/README.md b/code/multi_vlm2vec_train/cot_gen/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b43c5d5df881de1c8ff665673378d11eca1be134 --- /dev/null +++ b/code/multi_vlm2vec_train/cot_gen/README.md @@ -0,0 +1,83 @@ +# CoT Data Generation for Embedding Model + +使用本地 Qwen3.5-397B-A17B (vLLM) 为电商图搜 embedding 模型生成 Chain-of-Thought 数据。 + +## 文件说明 + +| 文件 | 功能 | +|------|------| +| `config.py` | 配置(模型路径、OSS、prompt模板等) | +| `generate_cot.py` | 主生成脚本(vLLM batch推理 + 断点续传) | +| `retry_failed.py` | 重试失败记录 | +| `merge_shards.py` | 合并分片输出 | +| `validate_cot.py` | 质量验证与统计 | +| `run.sh` | 启动脚本 | + +## 快速开始 + +### 1. 安装依赖 + +```bash +pip install vllm oss2 pillow tqdm numpy +``` + +### 2. 小批量测试 + +```bash +cd /home/lyq494390/multi_vlm2vec_train/cot_gen +bash run.sh --test +``` + +### 3. 全量生成 + +```bash +# 全量(支持断点续传,中断后重新运行自动跳过已处理的) +bash run.sh + +# 指定范围 +bash run.sh --start 0 --end 100000 + +# 指定TP size +bash run.sh --tp 4 +``` + +### 4. 验证质量 + +```bash +python validate_cot.py --cot_path /data/oss_bucket_0/liqi/dataset/embedding_pf/cot_output/zhaoxiangsi_train_cot.jsonl --num_samples 10 +``` + +### 5. 重试失败记录 + +```bash +python retry_failed.py --failed_path /data/oss_bucket_0/liqi/dataset/embedding_pf/cot_output/failed_records.jsonl +``` + +## 输出格式 + +每行一条 JSONL: + +```json +{ + "rn": "037a6b4e192533b2e0dc9ab3fb692806", + "query_tfsid": "O1CN01velvra1klBlaW3SfK_!!4611686018427387507-0-imgsearch.jpg", + "query_bbox": "22 114 414 790", + "instruction": "更多类似碎花半身裙", + "cot": "图片中展示了一条碎花印花的A字半身裙,面料轻薄透气,裙身布满小碎花图案...", + "prompt_index": 0 +} +``` + +## 资源说明 + +- 模型:`/data/oss_bucket_0/wuxiangyang/model/Qwen3.5-397B-A17B` +- 4x A800 80GB,tensor_parallel=4 +- 图片通过 OSS bucket `pailitao-ai` 读取 +- 原始数据约 80 万条记录,每条约 10 个 instruction,展开后约 800 万条 CoT 样本 + +## 注意事项 + +- 首次运行建议用 `bash run.sh --test` 验证图片加载和模型推理是否正常 +- 支持断点续传:中断后重新运行会自动跳过已生成的记录 +- 如果 OSS 图片路径与实际不符,修改 `generate_cot.py` 中 `get_image_from_oss` 的 `oss_path` +- `BATCH_SIZE` 默认64,如果显存不足可在 `config.py` 中调小 diff --git a/code/multi_vlm2vec_train/cot_gen/__pycache__/config.cpython-310.pyc b/code/multi_vlm2vec_train/cot_gen/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f72795f0934411e9490be9640787e85e72e4c1c Binary files /dev/null and b/code/multi_vlm2vec_train/cot_gen/__pycache__/config.cpython-310.pyc differ diff --git a/code/multi_vlm2vec_train/cot_gen/__pycache__/config.cpython-313.pyc b/code/multi_vlm2vec_train/cot_gen/__pycache__/config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e186609ee4c712724e19637b04265defd94583bf Binary files /dev/null and b/code/multi_vlm2vec_train/cot_gen/__pycache__/config.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/cot_gen/config.py b/code/multi_vlm2vec_train/cot_gen/config.py new file mode 100644 index 0000000000000000000000000000000000000000..62409af3e64eec5b427de69e2621fdaf255bc29a --- /dev/null +++ b/code/multi_vlm2vec_train/cot_gen/config.py @@ -0,0 +1,49 @@ +"""Configuration for CoT data generation (local vLLM inference).""" + +# ========================= Model Config ========================= +# MODEL_PATH = "/data/oss_bucket_0/wuxiangyang/model/Qwen3.5-397B-A17B" +MODEL_PATH = "/data/oss_bucket_0/planck/hf_models/Qwen3.6-27B" +TENSOR_PARALLEL_SIZE = 1 # 4x A800 80GB +GPU_MEMORY_UTILIZATION = 0.90 # vLLM GPU内存占用比例 +MAX_MODEL_LEN = 16384 # 模型最大上下文长度 + +# ========================= Data Paths ========================= +INPUT_PATH = "/data/oss_bucket_0/liqi/dataset/embedding_pf/shaixuan_train.json" +OUTPUT_DIR = "/data/oss_bucket_0/liqi/dataset/embedding_pf/cot_output_new/" +OUTPUT_PATH = "/data/oss_bucket_0/liqi/dataset/embedding_pf/cot_output_new/shaixuan_train_cot.jsonl" +FAILED_LOG_PATH = "/data/oss_bucket_0/liqi/dataset/embedding_pf/cot_output_new/failed_records.jsonl" + +# ========================= Image Config ========================= +# 本地图片存放目录,子路径为数据集中的 query_tfsid / pos_item_tfsids / neg_item_tfsids 字段 +IMAGE_CDN_PREFIX = "/data/oss_bucket_0/peifeng/multi_vlm2vec/dataset/merge/image/" +# 单张图片最大像素数(宽x高),超过则等比缩放。Qwen3-VL每28x28 patch产生1个token +IMAGE_MAX_PIXELS = 1048576 # ~1024×1024,约1280 tokens/张 + +# ========================= Prompt Selection Config ========================= +# "all": 将所有pos_prompts拆开,每个prompt都和query组成一个新样本(数据扩充) +# "random_one": 从pos_prompts中随机选择一条和图片组成样本,其余抛弃 +PROMPT_SELECT_MODE = "random_one" + +# ========================= Generation Config ========================= +BATCH_SIZE = 32 # vLLM batch size +MAX_TOKENS = 128 # CoT生成的最大token数 +TEMPERATURE = 0.7 +TOP_P = 0.9 +SAVE_INTERVAL = 500 # 每处理N条写入一次文件 + +# ========================= Prompt Template ========================= +SYSTEM_PROMPT = """你是一个电商图片搜索的推理助手。给定查询图片和搜索指令,你需要直接输出一段极简的视觉描述文本,仅包含图片中与检索相关的核心视觉特征,用于生成检索向量。""" + +COT_PROMPT_TEMPLATE = """用户上传了一张查询图片(第一张为原图,第二张为用户关注的裁剪区域),搜索指令为:"{instruction}" + +以下商品标题仅帮助你理解图中物品是什么,不要在输出中提及这些标题: +{pos_titles} + +请直接输出1-2句话,结合搜索指令的意图,描述图片中目标物品与指令相关的核心视觉特征(如品类、颜色、款式、材质、图案等),使输出文本能作为图片+指令的语义概括。 + +严格要求: +- 只输出1-2句视觉描述,不超过50字 +- 重点描述与搜索指令相关的视觉特征,而非图片所有内容 +- 直接描述你看到的内容,不要出现"用户想找""指令要求""参考标题"等分析性表述 +- 不要复述搜索指令或商品标题原文 +- 不要使用编号、分点或任何格式标记""" diff --git a/code/multi_vlm2vec_train/cot_gen/generate_cot.py b/code/multi_vlm2vec_train/cot_gen/generate_cot.py new file mode 100644 index 0000000000000000000000000000000000000000..5759e288f51f29114ed943501be5774115bcf630 --- /dev/null +++ b/code/multi_vlm2vec_train/cot_gen/generate_cot.py @@ -0,0 +1,368 @@ +""" +Generate CoT data for embedding model using local Qwen3.5-397B-A17B via vLLM. + +Usage: + # 本地测试(前100条) + python cot_gen/generate_cot.py --test + + # 本地全量运行(断点续传) + python generate_cot.py --resume + + # 指定范围(分片输出) + python cot_gen/generate_cot.py --start_idx 0 --end_idx 1000 --shard + + # 通过 nebula 提交(自动分片,结束后运行 merge_shards.py 合并) + sh run_nebula.sh +""" + +import os +import json +import argparse +import random +from pathlib import Path + +from PIL import Image +from tqdm import tqdm +from vllm import LLM, SamplingParams + +from config import ( + MODEL_PATH, TENSOR_PARALLEL_SIZE, GPU_MEMORY_UTILIZATION, MAX_MODEL_LEN, + INPUT_PATH, OUTPUT_DIR, OUTPUT_PATH, FAILED_LOG_PATH, + IMAGE_CDN_PREFIX, IMAGE_MAX_PIXELS, PROMPT_SELECT_MODE, + BATCH_SIZE, MAX_TOKENS, TEMPERATURE, TOP_P, SAVE_INTERVAL, + SYSTEM_PROMPT, COT_PROMPT_TEMPLATE, +) + + +def load_image_pair(image_name: str, bbox: str) -> tuple[Image.Image, Image.Image]: + """Load original image and cropped image from local filesystem.""" + image_path = os.path.join(IMAGE_CDN_PREFIX, image_name) + original = Image.open(image_path) + if original.mode != "RGB": + original = original.convert("RGB") + + if bbox and bbox != "ori": + parts = bbox.split() + if len(parts) >= 4: + xmin, ymin, xmax, ymax = [int(float(z)) for z in parts[:4]] + xmin = max(0, xmin) + xmax = min(original.width - 1, xmax) + ymin = max(0, ymin) + ymax = min(original.height - 1, ymax) + if (ymax - ymin) > 2 and (xmax - xmin) > 2: + cropped = original.crop((xmin, ymin, xmax, ymax)) + else: + cropped = original.copy() + else: + cropped = original.copy() + else: + cropped = original.copy() + + return original, cropped + + +def parse_records(raw_data: list[dict]) -> list[dict]: + """ + Parse raw records into individual samples. + Behavior depends on PROMPT_SELECT_MODE: + - "all": each prompt in pos_prompts becomes a separate sample (data augmentation) + - "random_one": randomly pick one prompt per record + """ + all_samples = [] + for record in raw_data: + query_tfsid = record["query_tfsid"] + query_bbox = record["query_bbox"] + rn = record["rn"] + + pos_prompts = record["pos_prompts"].split("##") + pos_titles_list = record["pos_item_titles"].split("##") + pos_tfsids_list = record["pos_item_tfsids"].split("##") + pos_bboxs_list = record["pos_item_bboxs"].split("##") + + neg_tfsids_list = [x for x in record.get("neg_item_tfsids", "").split("##") if x.strip()] + neg_titles_list = [x for x in record.get("neg_item_titles", "").split("##") if x.strip()] + neg_bboxs_list = [x for x in record.get("neg_item_bboxs", "").split("##") if x.strip()] + + def pick_random_neg(): + if not neg_tfsids_list: + return "", "", "" + idx = random.randint(0, len(neg_tfsids_list) - 1) + tfsid = neg_tfsids_list[idx] + title = neg_titles_list[idx] if idx < len(neg_titles_list) else "" + bbox = neg_bboxs_list[idx] if idx < len(neg_bboxs_list) else "" + return tfsid, title, bbox + + def build_sample(i): + title_indices = [max(0, i - 1), i, min(len(pos_titles_list) - 1, i + 1)] + ref_titles = list(dict.fromkeys( + pos_titles_list[idx] for idx in title_indices if idx < len(pos_titles_list) + )) + neg_tfsid, neg_title, neg_bbox = pick_random_neg() + return { + "rn": rn, + "query_tfsid": query_tfsid, + "query_bbox": query_bbox, + "instruction": pos_prompts[i].strip(), + "pos_titles_ref": ref_titles, + "prompt_index": i, + "pos_item_tfsid": pos_tfsids_list[i] if i < len(pos_tfsids_list) else "", + "pos_item_title": pos_titles_list[i] if i < len(pos_titles_list) else "", + "pos_item_bbox": pos_bboxs_list[i] if i < len(pos_bboxs_list) else "", + "neg_item_tfsid": neg_tfsid, + "neg_item_title": neg_title, + "neg_item_bbox": neg_bbox, + } + + if PROMPT_SELECT_MODE == "random_one": + valid_indices = [i for i, p in enumerate(pos_prompts) if p.strip()] + if not valid_indices: + continue + i = random.choice(valid_indices) + all_samples.append(build_sample(i)) + else: + for i, prompt in enumerate(pos_prompts): + if not prompt.strip(): + continue + all_samples.append(build_sample(i)) + + return all_samples + + +def build_vllm_prompt(sample: dict) -> str: + """Build the text prompt part for vLLM (image is passed separately).""" + instruction = sample["instruction"] + pos_titles = "\n".join(f"- {t}" for t in sample["pos_titles_ref"]) + + user_text = COT_PROMPT_TEMPLATE.format( + instruction=instruction, + pos_titles=pos_titles, + ) + + return user_text + + +def build_messages(sample: dict, original: Image.Image, cropped: Image.Image) -> list[dict]: + """Build chat messages for vLLM with original and cropped images.""" + user_text = build_vllm_prompt(sample) + + messages = [ + {"role": "system", "content": SYSTEM_PROMPT}, + { + "role": "user", + "content": [ + {"type": "image_pil", "image_pil": original}, + {"type": "image_pil", "image_pil": cropped}, + {"type": "text", "text": user_text}, + ], + }, + ] + return messages + + +def load_processed_keys(output_path: str) -> set: + """Load already processed (rn, prompt_index) pairs for resume.""" + processed = set() + if os.path.exists(output_path): + with open(output_path, "r", encoding="utf-8") as f: + for line in f: + if line.strip(): + try: + item = json.loads(line) + processed.add((item["rn"], item["prompt_index"])) + except (json.JSONDecodeError, KeyError): + continue + return processed + + +def save_results(results: list[dict], output_path: str): + """Append results to JSONL file.""" + with open(output_path, "a", encoding="utf-8") as f: + for item in results: + f.write(json.dumps(item, ensure_ascii=False) + "\n") + + +def save_failed(failed_samples: list[dict], failed_path: str): + """Append failed samples to log.""" + with open(failed_path, "a", encoding="utf-8") as f: + for item in failed_samples: + f.write(json.dumps(item, ensure_ascii=False) + "\n") + + +def main(args): + # Load data + print(f"Loading data from {INPUT_PATH} ...") + with open(INPUT_PATH, "r", encoding="utf-8") as f: + raw_data = json.load(f) + print(f"Total raw records: {len(raw_data)}") + + # Slice + end_idx = len(raw_data) if args.end_idx < 0 else min(args.end_idx, len(raw_data)) + raw_data = raw_data[args.start_idx:end_idx] + print(f"Processing records [{args.start_idx}, {end_idx})") + + # Parse into samples + all_samples = parse_records(raw_data) + print(f"Prompt select mode: {PROMPT_SELECT_MODE}") + print(f"Total samples (query x instruction pairs): {len(all_samples)}") + + # Output setup + os.makedirs(OUTPUT_DIR, exist_ok=True) + + if args.shard: + base, ext = os.path.splitext(OUTPUT_PATH) + output_path = f"{base}_{args.start_idx}_{end_idx}{ext}" + failed_path = f"{base}_{args.start_idx}_{end_idx}_failed{ext}" + else: + output_path = OUTPUT_PATH + failed_path = FAILED_LOG_PATH + + # Resume + if args.resume: + processed = load_processed_keys(output_path) + before = len(all_samples) + all_samples = [ + s for s in all_samples + if (s["rn"], s["prompt_index"]) not in processed + ] + print(f"Resume: skipping {before - len(all_samples)} processed, {len(all_samples)} remaining") + + if not all_samples: + print("No samples to process. Done.") + return + + # Initialize vLLM + print(f"Loading model from {MODEL_PATH} ...") + print(f" tensor_parallel_size={args.tp or TENSOR_PARALLEL_SIZE}") + print(f" gpu_memory_utilization={GPU_MEMORY_UTILIZATION}") + print(f" image_dir={IMAGE_CDN_PREFIX}") + + llm = LLM( + model=MODEL_PATH, + tensor_parallel_size=args.tp or TENSOR_PARALLEL_SIZE, + gpu_memory_utilization=GPU_MEMORY_UTILIZATION, + max_model_len=MAX_MODEL_LEN, + trust_remote_code=True, + dtype="bfloat16", + limit_mm_per_prompt={"image": 2}, + mm_processor_kwargs={"max_pixels": IMAGE_MAX_PIXELS}, + enable_prefix_caching=True, + ) + sampling_params = SamplingParams( + max_tokens=MAX_TOKENS, + temperature=TEMPERATURE, + top_p=TOP_P, + ) + + print(f"Model loaded. Starting generation...") + print(f"Output: {output_path}") + + # Process in batches + total_success = 0 + total_failed = 0 + batch_results = [] + + for batch_start in tqdm(range(0, len(all_samples), BATCH_SIZE), desc="Batches"): + batch_samples = all_samples[batch_start:batch_start + BATCH_SIZE] + + # Prepare batch inputs: load images and build prompts + valid_samples = [] + batch_inputs = [] + + for sample in batch_samples: + try: + original, cropped = load_image_pair(sample["query_tfsid"], sample["query_bbox"]) + messages = build_messages(sample, original, cropped) + valid_samples.append(sample) + batch_inputs.append(messages) + except Exception as e: + total_failed += 1 + save_failed([{**sample, "error": f"image_load: {str(e)}"}], failed_path) + + if not batch_inputs: + continue + + # vLLM batch inference using chat interface + try: + outputs = llm.chat( + messages=batch_inputs, + sampling_params=sampling_params, + chat_template_kwargs={"enable_thinking": False}, + ) + + for sample, output in zip(valid_samples, outputs): + generated_text = output.outputs[0].text.strip() + + if generated_text and len(generated_text) >= 10: + result = { + "rn": sample["rn"], + "query_tfsid": sample["query_tfsid"], + "query_bbox": sample["query_bbox"], + "instruction": sample["instruction"], + "cot": generated_text, + "prompt_index": sample["prompt_index"], + "pos_item_tfsid": sample["pos_item_tfsid"], + "pos_item_title": sample["pos_item_title"], + "pos_item_bbox": sample["pos_item_bbox"], + "neg_item_tfsid": sample["neg_item_tfsid"], + "neg_item_title": sample["neg_item_title"], + "neg_item_bbox": sample["neg_item_bbox"], + } + batch_results.append(result) + total_success += 1 + else: + total_failed += 1 + save_failed([{**sample, "error": f"short_output: {generated_text}"}], failed_path) + + except Exception as e: + print(f"Batch inference error: {e}") + total_failed += len(valid_samples) + for sample in valid_samples: + save_failed([{**sample, "error": f"inference: {str(e)}"}], failed_path) + + # Periodic save + if len(batch_results) >= SAVE_INTERVAL: + save_results(batch_results, output_path) + batch_results = [] + + # Save remaining + if batch_results: + save_results(batch_results, output_path) + + print(f"\nDone! Success: {total_success}, Failed: {total_failed}") + print(f"Output: {output_path}") + if total_failed > 0: + print(f"Failed log: {failed_path}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Generate CoT data using local Qwen3.5-397B-A17B") + parser.add_argument("--test", action="store_true", help="Test mode: process first 100 records") + parser.add_argument("--start_idx", type=int, default=0, help="Start index of raw records") + parser.add_argument("--end_idx", type=int, default=-1, help="End index (-1 for all)") + parser.add_argument("--tp", type=int, default=None, help="Override tensor_parallel_size") + parser.add_argument("--resume", action="store_true", help="Resume from previous progress") + parser.add_argument("--shard", action="store_true", help="Shard output by index range") + args = parser.parse_args() + + if args.test: + args.start_idx = 0 + args.end_idx = 100 + args.resume = False + else: + # Auto-shard based on RANK/WORLD_SIZE env vars (set by nebula/distributed launcher) + rank = int(os.environ.get("RANK", os.environ.get("INDEX", 0))) + world_size = int(os.environ.get("WORLD_SIZE", os.environ.get("WORKER_NUM", 1))) + if world_size > 1: + with open(INPUT_PATH, "r", encoding="utf-8") as f: + total_records = len(json.load(f)) + if args.end_idx < 0: + args.end_idx = total_records + total = min(args.end_idx, total_records) - args.start_idx + shard_size = (total + world_size - 1) // world_size + args.start_idx = args.start_idx + rank * shard_size + args.end_idx = min(args.start_idx + shard_size, total_records) + args.shard = True + print(f"[Auto-shard] rank={rank}, world_size={world_size}, " + f"processing [{args.start_idx}, {args.end_idx})") + + main(args) diff --git a/code/multi_vlm2vec_train/cot_gen/merge_shards.py b/code/multi_vlm2vec_train/cot_gen/merge_shards.py new file mode 100644 index 0000000000000000000000000000000000000000..52d734a86c0945b710158d73986faf58858a387b --- /dev/null +++ b/code/multi_vlm2vec_train/cot_gen/merge_shards.py @@ -0,0 +1,90 @@ +""" +Merge shard outputs from distributed CoT generation into a single JSON file. + +Usage: + # 合并指定前缀的分片(如 bianji_train_cot) + python cot_gen/merge_shards.py --prefix bianji_train_cot --input_dir /data/oss_bucket_0/liqi/dataset/embedding_pf/cot_output2/ --format json + + # 指定输入目录 + python cot_gen/merge_shards.py --prefix dapei_train_cot --input_dir /path/to/shards + + # 输出为jsonl格式 + python cot_gen/merge_shards.py --prefix bianji_train_cot --format jsonl +""" + +import os +import re +import json +import argparse +from config import OUTPUT_DIR + + +def find_shard_files(input_dir: str, prefix: str) -> list[str]: + """Find all shard files matching the prefix pattern (excluding failed files).""" + pattern = re.compile(rf"^{re.escape(prefix)}_\d+_\d+\.jsonl$") + + shard_files = [] + for fname in os.listdir(input_dir): + if pattern.match(fname): + shard_files.append(os.path.join(input_dir, fname)) + + shard_files.sort(key=lambda f: int(re.search(r"_(\d+)_\d+\.jsonl$", f).group(1))) + return shard_files + + +def merge(args): + input_dir = args.input_dir or OUTPUT_DIR + prefix = args.prefix + + shard_files = find_shard_files(input_dir, prefix) + + if not shard_files: + print(f"No shard files found with prefix '{prefix}' in {input_dir}") + return + + print(f"Found {len(shard_files)} shard files:") + for f in shard_files: + print(f" {os.path.basename(f)}") + + all_results = [] + seen_keys = set() + duplicates = 0 + + for shard_path in shard_files: + with open(shard_path, "r", encoding="utf-8") as f: + for line in f: + if not line.strip(): + continue + item = json.loads(line) + key = (item["rn"], item["prompt_index"]) + if key in seen_keys: + duplicates += 1 + continue + seen_keys.add(key) + all_results.append(item) + + if args.format == "json": + merged_path = os.path.join(input_dir, f"{prefix}.json") + with open(merged_path, "w", encoding="utf-8") as f: + json.dump(all_results, f, ensure_ascii=False, indent=2) + else: + merged_path = os.path.join(input_dir, f"{prefix}.jsonl") + with open(merged_path, "w", encoding="utf-8") as f: + for item in all_results: + f.write(json.dumps(item, ensure_ascii=False) + "\n") + + print(f"\nMerged {len(all_results)} records -> {merged_path}") + if duplicates > 0: + print(f"Skipped {duplicates} duplicate records") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Merge CoT shard outputs by prefix") + parser.add_argument("--prefix", type=str, required=True, + help="Shard file prefix (e.g. bianji_train_cot, dapei_train_cot)") + parser.add_argument("--input_dir", type=str, default=None, + help="Directory containing shard files (default: OUTPUT_DIR from config)") + parser.add_argument("--format", choices=["json", "jsonl"], default="json", + help="Output format: json (single array) or jsonl (one per line)") + args = parser.parse_args() + merge(args) diff --git a/code/multi_vlm2vec_train/cot_gen/retry_failed.py b/code/multi_vlm2vec_train/cot_gen/retry_failed.py new file mode 100644 index 0000000000000000000000000000000000000000..c6067e26ef02b6bacf23516800346659dfba4b9c --- /dev/null +++ b/code/multi_vlm2vec_train/cot_gen/retry_failed.py @@ -0,0 +1,126 @@ +""" +Retry failed records using local vLLM inference. + +Usage: + python retry_failed.py --failed_path /path/to/failed_records.jsonl +""" + +import os +import json +import argparse + +from PIL import Image +from tqdm import tqdm +from vllm import LLM, SamplingParams + +from config import ( + MODEL_PATH, TENSOR_PARALLEL_SIZE, GPU_MEMORY_UTILIZATION, MAX_MODEL_LEN, + BATCH_SIZE, MAX_TOKENS, TEMPERATURE, TOP_P, + SYSTEM_PROMPT, COT_PROMPT_TEMPLATE, +) +from generate_cot import ( + load_image_pair, build_messages, save_results, +) + + +def main(args): + # Load failed records + failed_samples = [] + with open(args.failed_path, "r", encoding="utf-8") as f: + for line in f: + if line.strip(): + try: + item = json.loads(line) + item.pop("error", None) + failed_samples.append(item) + except json.JSONDecodeError: + continue + + print(f"Loaded {len(failed_samples)} failed records to retry") + if not failed_samples: + return + + base, ext = os.path.splitext(args.failed_path) + output_path = base.replace("_failed", "") + "_retried" + ext + still_failed_path = base + "_still_failed" + ext + + # Init + llm = LLM( + model=MODEL_PATH, + tensor_parallel_size=args.tp or TENSOR_PARALLEL_SIZE, + gpu_memory_utilization=GPU_MEMORY_UTILIZATION, + max_model_len=MAX_MODEL_LEN, + trust_remote_code=True, + dtype="bfloat16", + limit_mm_per_prompt={"image": 2}, + ) + sampling_params = SamplingParams( + max_tokens=MAX_TOKENS, + temperature=TEMPERATURE, + top_p=TOP_P, + ) + + total_success = 0 + total_failed = 0 + results = [] + still_failed = [] + + for batch_start in tqdm(range(0, len(failed_samples), BATCH_SIZE), desc="Retrying"): + batch = failed_samples[batch_start:batch_start + BATCH_SIZE] + + valid_samples = [] + batch_inputs = [] + for sample in batch: + try: + original, cropped = load_image_pair(sample["query_tfsid"], sample["query_bbox"]) + messages = build_messages(sample, original, cropped) + valid_samples.append(sample) + batch_inputs.append(messages) + except Exception: + still_failed.append(sample) + total_failed += 1 + + if not batch_inputs: + continue + + try: + outputs = llm.chat(messages=batch_inputs, sampling_params=sampling_params) + for sample, output in zip(valid_samples, outputs): + text = output.outputs[0].text.strip() + if text and len(text) >= 10: + results.append({ + "rn": sample["rn"], + "query_tfsid": sample["query_tfsid"], + "query_bbox": sample["query_bbox"], + "instruction": sample["instruction"], + "cot": text, + "prompt_index": sample["prompt_index"], + }) + total_success += 1 + else: + still_failed.append(sample) + total_failed += 1 + except Exception: + still_failed.extend(valid_samples) + total_failed += len(valid_samples) + + if results: + save_results(results, output_path) + if still_failed: + with open(still_failed_path, "w", encoding="utf-8") as f: + for item in still_failed: + f.write(json.dumps(item, ensure_ascii=False) + "\n") + + print(f"\nRetry done! Success: {total_success}, Still failed: {total_failed}") + if total_success > 0: + print(f"Results: {output_path}") + if total_failed > 0: + print(f"Still failed: {still_failed_path}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--failed_path", type=str, required=True) + parser.add_argument("--tp", type=int, default=None) + args = parser.parse_args() + main(args) diff --git a/code/multi_vlm2vec_train/cot_gen/run_nebula.sh b/code/multi_vlm2vec_train/cot_gen/run_nebula.sh new file mode 100644 index 0000000000000000000000000000000000000000..769e0033eb6c990ce67441afa7e5c945b7ef6e82 --- /dev/null +++ b/code/multi_vlm2vec_train/cot_gen/run_nebula.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# CoT Generation - Nebula Submission +# Usage: sh cot_gen/run_nebula.sh + +CLUSTER_CONFIG='./cluster.json' +cat < ${CLUSTER_CONFIG} +{ + "worker": { + "gpu": 100, + "cpu": 1200, + "memory": 50000 + } +} +EOT + +WORKER_COUNT=8 + +args="--resume" +nebulactl run mdl --engine=xdl \ + --refresh \ + --ignore=data/*,.git/* \ + --queue=pailitao_algo_high_2 \ + --worker_count=$WORKER_COUNT \ + --odps_project=pailitao_algo_high_2 \ + --entry="./cot_gen/generate_cot.py" \ + --oss_access_id=LTAI5tMZb5HHH6HHgAExAyiL \ + --oss_access_key=6MVP8JnTE01t4TLUHhPoFV0swZNTrb \ + --oss_bucket=pailitao-ai \ + --oss_endpoint=oss-cn-zhangjiakou-internal.aliyuncs.com \ + --algo_name=pytorch2100 \ + --user_params="$args" \ + --job_name=shaixuan-cot-gen-qwen36-27b \ + --file.cluster_file=$CLUSTER_CONFIG \ + --force \ + --max_failover_times=2 \ + --requirements_file_name="./requirements.txt" + +rm ${CLUSTER_CONFIG} diff --git a/code/multi_vlm2vec_train/cot_gen/validate_cot.py b/code/multi_vlm2vec_train/cot_gen/validate_cot.py new file mode 100644 index 0000000000000000000000000000000000000000..20b1a41848236074c3cbbea26a67fcfde0f082c7 --- /dev/null +++ b/code/multi_vlm2vec_train/cot_gen/validate_cot.py @@ -0,0 +1,83 @@ +""" +Validate generated CoT data quality. + +Usage: + python validate_cot.py --cot_path /path/to/cot.jsonl --num_samples 10 +""" + +import json +import argparse +import numpy as np +from collections import Counter + + +def load_cot_data(path: str) -> list: + data = [] + with open(path, "r", encoding="utf-8") as f: + for line in f: + if line.strip(): + try: + data.append(json.loads(line)) + except json.JSONDecodeError: + continue + return data + + +def basic_stats(data: list): + print(f"\n{'='*60}") + print(f" Basic Statistics") + print(f"{'='*60}") + print(f"Total records: {len(data)}") + + cot_lengths = [len(item["cot"]) for item in data] + print(f"\nCoT Length (chars):") + print(f" Mean: {np.mean(cot_lengths):.1f}") + print(f" Median: {np.median(cot_lengths):.1f}") + print(f" Min: {np.min(cot_lengths)}") + print(f" Max: {np.max(cot_lengths)}") + print(f" Std: {np.std(cot_lengths):.1f}") + + short_threshold = 30 + short_count = sum(1 for l in cot_lengths if l < short_threshold) + print(f"\n Short CoTs (<{short_threshold} chars): {short_count} ({short_count/len(data)*100:.2f}%)") + + unique_rns = set(item["rn"] for item in data) + print(f"\nUnique query records covered: {len(unique_rns)}") + + rn_counts = Counter(item["rn"] for item in data) + print(f"Instructions per record: mean={np.mean(list(rn_counts.values())):.1f}") + + +def show_samples(data: list, num_samples: int = 5): + print(f"\n{'='*60}") + print(f" Random Samples") + print(f"{'='*60}") + + indices = np.random.choice(len(data), min(num_samples, len(data)), replace=False) + for idx in indices: + item = data[idx] + print(f"\n--- Sample (rn={item['rn'][:8]}..., idx={item['prompt_index']}) ---") + print(f"Instruction: {item['instruction']}") + print(f"CoT: {item['cot']}") + print() + + +def main(args): + print(f"Loading CoT data from: {args.cot_path}") + data = load_cot_data(args.cot_path) + + if not data: + print("No data loaded!") + return + + basic_stats(data) + show_samples(data, args.num_samples) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Validate CoT data quality") + parser.add_argument("--cot_path", type=str, required=True) + parser.add_argument("--num_samples", type=int, default=5) + args = parser.parse_args() + + main(args) diff --git a/code/multi_vlm2vec_train/dataset/__pycache__/datasets_tuwen_qwen3vl.cpython-310.pyc b/code/multi_vlm2vec_train/dataset/__pycache__/datasets_tuwen_qwen3vl.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab61c9c519c3b57accf5d1aaff64ef87596f4ed7 Binary files /dev/null and b/code/multi_vlm2vec_train/dataset/__pycache__/datasets_tuwen_qwen3vl.cpython-310.pyc differ diff --git a/code/multi_vlm2vec_train/dataset/__pycache__/datasets_tuwen_qwen3vl.cpython-313.pyc b/code/multi_vlm2vec_train/dataset/__pycache__/datasets_tuwen_qwen3vl.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d43eb53ce9f108f14b798747a6435268840af40 Binary files /dev/null and b/code/multi_vlm2vec_train/dataset/__pycache__/datasets_tuwen_qwen3vl.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/dataset/__pycache__/datasets_tuwen_qwen3vl_cot_append.cpython-313.pyc b/code/multi_vlm2vec_train/dataset/__pycache__/datasets_tuwen_qwen3vl_cot_append.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3b04959bc1be2b51b33ce663e83535934b12f6b Binary files /dev/null and b/code/multi_vlm2vec_train/dataset/__pycache__/datasets_tuwen_qwen3vl_cot_append.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/dataset/__pycache__/datasets_tuwen_qwen3vl_infonce.cpython-313.pyc b/code/multi_vlm2vec_train/dataset/__pycache__/datasets_tuwen_qwen3vl_infonce.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5722d5b2dd69c154281a8db0fab3f2e4ac9dad6 Binary files /dev/null and b/code/multi_vlm2vec_train/dataset/__pycache__/datasets_tuwen_qwen3vl_infonce.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/dataset/datasets_tuwen_qwen3vl.py b/code/multi_vlm2vec_train/dataset/datasets_tuwen_qwen3vl.py new file mode 100644 index 0000000000000000000000000000000000000000..90c20d994289fefe8c0a83218aee292e6b257b3b --- /dev/null +++ b/code/multi_vlm2vec_train/dataset/datasets_tuwen_qwen3vl.py @@ -0,0 +1,284 @@ +import json +from torch.utils.data import Dataset +from PIL import Image + + + +from tqdm import tqdm +import traceback +import oss2 as oss + +def load_oss_bucket(): + endpoint = 'http://oss-cn-zhangjiakou-internal.aliyuncs.com' # + akey = 'LTAI5tMZb5HHH6HHgAExAyiL' # + aid = '6MVP8JnTE01t4TLUHhPoFV0swZNTrb' # 'xxx' + bucket = 'pailitao-ai' # + auth = oss.Auth(akey, aid) + bucket = oss.Bucket(auth, endpoint, bucket) + return bucket + +OSS_BUCKET = load_oss_bucket() + +## 测试数据集 +class TuwenQwenEvalDataset(Dataset): + def __init__(self, args): + super(TuwenQwenEvalDataset, self).__init__() + + self.args = args + self.label_index = {'0': 0, '1': 1} + self.parse_json_data(args.test_json) + + self.min_pixels = 4 * 32 * 32 + self.max_pixels = 200 * 32 * 32 + + def __len__(self): + return len(self.test_images) + + def _prepare_data_dict(self, img_base64=None, img_crop_base64=None, txt=''): + if img_base64 is None and img_crop_base64 is None: + return {"txt": txt} + elif img_crop_base64 is None: + return {"txt": txt, "image": img_base64} + elif img_base64 is None: + return {"txt": txt, "image_crop": img_crop_base64} + elif txt == '': + return {"image": img_base64, "image_crop": img_crop_base64} + else: + return {"txt": txt, "image": img_base64, "image_crop": img_crop_base64} + + def construct_messages(self, data_dict): + if 'txt' in data_dict and 'image' in data_dict and 'image_crop' in data_dict: + message = [ + { + "role": "system", + "content": [ + {"type": "text", "text": "Represent the user's input."} + ] + }, + { + "role": "user", + "content": [ + {"type": "image", "image": data_dict['image'], "min_pixels": self.min_pixels, "max_pixels": self.max_pixels}, + {"type": "image", "image": data_dict['image_crop'], "min_pixels": self.min_pixels, "max_pixels": self.max_pixels}, + {"type": "text", "text": f"{data_dict['txt']}"} + ] + }, + ] + elif 'txt' in data_dict and 'image' in data_dict: + message = [ + { + "role": "system", + "content": [ + {"type": "text", "text": "Represent the user's input."} + ] + }, + { + "role": "user", + "content": [ + {"type": "image", "image": data_dict['image'], "min_pixels": self.min_pixels, "max_pixels": self.max_pixels}, + {"type": "text", "text": f"{data_dict['txt']}"} + ] + }, + ] + elif 'txt' in data_dict and 'image_crop' in data_dict: + message = [ + { + "role": "system", + "content": [ + {"type": "text", "text": "Represent the user's input."} + ] + }, + { + "role": "user", + "content": [ + {"type": "image", "image": data_dict['image_crop'], "min_pixels": self.min_pixels, "max_pixels": self.max_pixels}, + {"type": "text", "text": f"{data_dict['txt']}"} + ] + }, + ] + elif 'txt' in data_dict: + message = [ + { + "role": "system", + "content": [ + {"type": "text", "text": "Represent the user's input."} + ] + }, + { + "role": "user", + "content": [ + {"type": "text", "text": f"{data_dict['txt']}"} + ] + }, + ] + elif 'image' in data_dict and 'image_crop' in data_dict: + message = [ + { + "role": "system", + "content": [ + {"type": "text", "text": "Represent the user's input."} + ] + }, + { + "role": "user", + "content": [ + {"type": "image", "image": data_dict['image'], "min_pixels": self.min_pixels, "max_pixels": self.max_pixels}, + {"type": "image", "image": data_dict['image_crop'], "min_pixels": self.min_pixels, "max_pixels": self.max_pixels}, + {"type": "text", "text": f" "} + ] + }, + ] + elif 'image' in data_dict: + message = [ + { + "role": "system", + "content": [ + {"type": "text", "text": "Represent the user's input."} + ] + }, + { + "role": "user", + "content": [ + {"type": "image", "image": data_dict['image'], "min_pixels": self.min_pixels, "max_pixels": self.max_pixels}, + {"type": "text", "text": f""} + ] + }, + ] + elif 'image_crop' in data_dict: + message = [ + { + "role": "system", + "content": [ + {"type": "text", "text": "Represent the user's input."} + ] + }, + { + "role": "user", + "content": [ + {"type": "image", "image": data_dict['image_crop'], "min_pixels": self.min_pixels, "max_pixels": self.max_pixels}, + {"type": "text", "text": f""} + ] + }, + ] + return message + + @staticmethod + def _clamp_aspect_ratio(img: Image.Image, max_ratio: float = 100) -> Image.Image: + """如果图片长宽比超过 max_ratio,将其 resize 到长宽比等于 max_ratio。""" + w, h = img.size + assert w > 0 and h > 0 + ratio = max(w, h) / min(w, h) + if ratio <= max_ratio: + return img + if w > h: + new_w = int(h * max_ratio) + new_h = h + else: + new_w = w + new_h = int(w * max_ratio) + return img.resize((new_w, new_h), Image.BILINEAR) + + def get_image_from_oss(self, image_name, roi): + if len(roi.split(' ')) == 6: + roi = ' '.join(roi.split(' ')[:4]) + elif len(roi.split(' ')) == 4: + pass + else: + roi = 'ori' + + oss_path = f'peifeng/multi_vlm2vec/dataset/merge/test_image/{image_name}' + image = Image.open(OSS_BUCKET.get_object(oss_path)) + if image.mode != "RGB": + image = image.convert("RGB") + + image_full = image.copy() + + if roi != 'ori': + xmin, ymin, xmax, ymax = [int(float(z)) for z in roi.split(' ')[:4]] + xmin = max(0, xmin) + xmax = min(image.width - 1, xmax) + ymin = max(0, ymin) + ymax = min(image.height - 1, ymax) + if (ymax - ymin) > 2 and (xmax - xmin) > 2: + image = image.crop((xmin, ymin, xmax, ymax)) + + # 如果image或者image_full长宽比超过100,将长宽比resize到100 + image = self._clamp_aspect_ratio(image, max_ratio=100) + image_full = self._clamp_aspect_ratio(image_full, max_ratio=100) + + return image, image_full + + def __getitem__(self, index): + try_times = 3 + i = 0 + while i < try_times: + try: + query_tfsid, query_bbox, query_text, item_tfsid, item_title, item_bbox, label = self.test_images[index] + + query_image, query_image_full = self.get_image_from_oss(query_tfsid, query_bbox) + item_image, item_image_full = self.get_image_from_oss(item_tfsid, item_bbox) + + ## 构建query txt + if self.args.query_text_require: + query_txt = f"prompt:{query_text}" + else: + query_txt = f"" + + ## 构建doc txt + if self.args.doc_text_require: + doc_txt = f"title:{item_title}" + else: + doc_txt = f"" + + ## 根据image_type构建符合格式的dict + if self.args.image_type == "full": + query_dict = self._prepare_data_dict(img_base64=query_image_full, txt=query_txt) + item_dict = self._prepare_data_dict(img_base64=item_image_full, txt=doc_txt) + elif self.args.image_type == "crop": + query_dict = self._prepare_data_dict(img_crop_base64=query_image, txt=query_txt) + item_dict = self._prepare_data_dict(img_crop_base64=item_image, txt=doc_txt) + else: + query_dict = self._prepare_data_dict(img_base64=query_image_full, img_crop_base64=query_image, txt=query_txt) + item_dict = self._prepare_data_dict(img_base64=item_image_full, img_crop_base64=item_image, txt=doc_txt) + + query_message = self.construct_messages(query_dict) + item_message = self.construct_messages(item_dict) + + label_index = self.label_index[label] + + # return f"{query_tfsid}_#_{query_bbox}_#_{query_text}", query_message, item_message, label_index, f"{item_tfsid}_#_{item_bbox}_#_{item_title}" + return query_tfsid, query_message, item_message, label_index, item_tfsid + except Exception as e: + print('exception for getitem {}, try times {}/{} : {}'.format(self.test_images[index], i, try_times, e)) + i += 1 + + query_dict = {"txt": 'Empty.'} + item_dict = {"txt": 'Empty.'} + query_message = self.construct_messages(query_dict) + item_message = self.construct_messages(item_dict) + print("error testing") + return 'None', query_message, item_message, 'None', 'None' + + def parse_json_data(self, json_path): + with open(json_path, 'r', encoding='utf-8') as f: + data = json.load(f) + + num_records_to_read = len(data) if self.args.max_lines < 0 else min(len(data), self.args.max_lines) + + self.test_images = list() + self.max_length = 512 + for i in tqdm(range(num_records_to_read)): + try: + record = data[i] + query_tfsid = record['query_tfsid'] + query_bbox = record['query_bbox'] + query_text = record['query_text'][:self.max_length - 2] + item_tfsid = record['item_tfsid'] + item_title = record['item_title'][:self.max_length - 2] + item_bbox = record['item_bbox'] + label = record['label'] + + self.test_images.append([query_tfsid, query_bbox, query_text, item_tfsid, item_title, item_bbox, label]) + except Exception as e: + print("test dataset exception for record {}: {}".format(i, e)) + diff --git a/code/multi_vlm2vec_train/dataset/datasets_tuwen_qwen3vl_cot_append.py b/code/multi_vlm2vec_train/dataset/datasets_tuwen_qwen3vl_cot_append.py new file mode 100644 index 0000000000000000000000000000000000000000..9120d9aff3eb19c60844ba272a85e396174b3e83 --- /dev/null +++ b/code/multi_vlm2vec_train/dataset/datasets_tuwen_qwen3vl_cot_append.py @@ -0,0 +1,88 @@ +import json +import os +import sys + +current_file_path = os.path.dirname(os.path.abspath(__file__)) +module_path = os.path.join(current_file_path, "../") +sys.path.append(module_path) + +from dataset.datasets_tuwen_qwen3vl import TuwenQwenEvalDataset + + +class TuwenQwenCotAppendEvalDataset(TuwenQwenEvalDataset): + """在 baseline 评测数据集的基础上,把离线生成的 CoT 文本追加到 query 文本后面。 + + CoT 文件是一个 json list,每条形如 + {"query_tfsid": ..., "query_text": ..., "cot": ...} + 按 (query_tfsid, query_text) 与 test_json 对齐;未命中的 query 退化为 baseline 输入。 + doc 侧不做任何改动。 + """ + + def __init__(self, args): + self.cot_map = self._load_cot(args.cot_json) + super().__init__(args) + + def _load_cot(self, cot_json): + with open(cot_json, 'r', encoding='utf-8') as f: + data = json.load(f) + + cot_map = {} + for record in data: + cot = (record.get('cot') or '').strip() + if cot: + cot_map[(record['query_tfsid'], record['query_text'])] = cot + print("loaded {} cot records from {}".format(len(cot_map), cot_json)) + return cot_map + + def parse_json_data(self, json_path): + super().parse_json_data(json_path) + + self.cot_texts = [] + for query_tfsid, _, query_text, *_ in self.test_images: + self.cot_texts.append(self.cot_map.get((query_tfsid, query_text), '')) + + hit = sum(1 for cot in self.cot_texts if cot) + print("cot hit {}/{} eval pairs.".format(hit, len(self.cot_texts))) + + def build_query_txt(self, query_text, cot): + if self.args.query_text_require and cot: + return f"prompt:{query_text}\n{cot}" + if self.args.query_text_require: + return f"prompt:{query_text}" + return cot + + def __getitem__(self, index): + try_times = 3 + i = 0 + while i < try_times: + try: + query_tfsid, query_bbox, query_text, item_tfsid, item_title, item_bbox, label = self.test_images[index] + + query_image, query_image_full = self.get_image_from_oss(query_tfsid, query_bbox) + item_image, item_image_full = self.get_image_from_oss(item_tfsid, item_bbox) + + query_txt = self.build_query_txt(query_text, self.cot_texts[index]) + doc_txt = f"title:{item_title}" if self.args.doc_text_require else "" + + if self.args.image_type == "full": + query_dict = self._prepare_data_dict(img_base64=query_image_full, txt=query_txt) + item_dict = self._prepare_data_dict(img_base64=item_image_full, txt=doc_txt) + elif self.args.image_type == "crop": + query_dict = self._prepare_data_dict(img_crop_base64=query_image, txt=query_txt) + item_dict = self._prepare_data_dict(img_crop_base64=item_image, txt=doc_txt) + else: + query_dict = self._prepare_data_dict(img_base64=query_image_full, img_crop_base64=query_image, txt=query_txt) + item_dict = self._prepare_data_dict(img_base64=item_image_full, img_crop_base64=item_image, txt=doc_txt) + + query_message = self.construct_messages(query_dict) + item_message = self.construct_messages(item_dict) + + return query_tfsid, query_message, item_message, self.label_index[label], item_tfsid + except Exception as e: + print('exception for getitem {}, try times {}/{} : {}'.format(self.test_images[index], i, try_times, e)) + i += 1 + + query_message = self.construct_messages({"txt": 'Empty.'}) + item_message = self.construct_messages({"txt": 'Empty.'}) + print("error testing") + return 'None', query_message, item_message, 'None', 'None' diff --git a/code/multi_vlm2vec_train/dataset/datasets_tuwen_qwen3vl_infonce.py b/code/multi_vlm2vec_train/dataset/datasets_tuwen_qwen3vl_infonce.py new file mode 100644 index 0000000000000000000000000000000000000000..aab8466768aa747b2380cb95b93fc0f90937f122 --- /dev/null +++ b/code/multi_vlm2vec_train/dataset/datasets_tuwen_qwen3vl_infonce.py @@ -0,0 +1,244 @@ +import json +import os +import random +from typing import Dict, List + +from PIL import Image +from torch.utils.data import Dataset + +# InfoNCE embedding 训练沿用 Qwen3-VL-Embedding 的默认 instruction +SYSTEM_PROMPT = "Represent the user's input." + +# nebula 提交后,远程机器上 OSS bucket 直接挂载为本地目录,图片按本地路径读取即可 +DEFAULT_IMAGE_DIR = "/data/oss_bucket_0/peifeng/multi_vlm2vec/dataset/merge/image" + + +class CIRDataset_tuwen(Dataset): + """InfoNCE 三元组数据集(本地 json 读取,与 CoT 数据格式统一)。 + + 每条样本产出 (query_message, pos_message, neg_message)。 + 数据来自 data_args.data_path 指向的 json 文件(train_cot/data_example.json 的格式, + 忽略其中的 cot / prompt_index 字段),支持单个 json / json 目录 / 逗号分隔的多个 json。 + 图片从 data_args.image_path_prefix 指向的本地目录读取。 + """ + + def __init__(self, args): + self.args = args + + self.min_pixels = 4 * 32 * 32 + self.max_pixels = 200 * 32 * 32 + + self.image_type = args.image_type + # 图片目录:不指定时默认用远程机器上的 OSS 挂载路径 + self.image_local_dir = args.image_path_prefix or DEFAULT_IMAGE_DIR + + data_path = args.data_path + assert data_path, "data_path is required: json file / dir / comma-separated json files" + self.parse_local_json(data_path) + + def __len__(self): + return len(self.records) + + # ------------------------------------------------------------------ + # 数据读取 + # ------------------------------------------------------------------ + @staticmethod + def _resolve_json_files(data_path: str) -> List[str]: + """把 data_path 展开成 json 文件列表:支持单文件 / 目录 / 逗号分隔多文件。""" + json_files = [] + for path in data_path.split(","): + path = path.strip() + if not path: + continue + if os.path.isdir(path): + json_files.extend(sorted( + os.path.join(path, name) + for name in os.listdir(path) if name.endswith(".json") + )) + else: + json_files.append(path) + assert len(json_files) > 0, f"no json file found in data_path: {data_path}" + return json_files + + def parse_local_json(self, data_path: str): + records = [] + for json_file in self._resolve_json_files(data_path): + with open(json_file, "r", encoding="utf-8") as f: + records.extend(json.load(f)) + + max_lines = self.args.max_lines + if max_lines is not None and max_lines >= 0: + records = records[:max_lines] + + self.records = [self._normalize_record(record) for record in records] + assert len(self.records) > 0, "the number of valid item should larger than 0" + print("total of {} items (local json {}).".format(len(self.records), data_path)) + + @staticmethod + def _split_multi(value) -> List[str]: + return str(value).split("##") if value else [] + + @staticmethod + def _pick(values: List[str], index: int, default: str = "") -> str: + if not values: + return default + return values[index] if index < len(values) else default + + @classmethod + def _normalize_record(cls, record: Dict) -> Dict: + """兼容两种数据格式:ODPS 导出的 ## 多候选字段,以及 CoT 数据的单候选字段。""" + if "pos_item_tfsids" in record: + instructions = cls._split_multi(record.get("pos_prompts")) + pos_tfsids = cls._split_multi(record["pos_item_tfsids"]) + pos_titles = cls._split_multi(record.get("pos_item_titles")) + pos_bboxs = cls._split_multi(record.get("pos_item_bboxs")) + neg_tfsids = cls._split_multi(record["neg_item_tfsids"]) + neg_titles = cls._split_multi(record.get("neg_item_titles")) + neg_bboxs = cls._split_multi(record.get("neg_item_bboxs")) + else: + instructions = [record.get("instruction") or ""] + pos_tfsids = [record["pos_item_tfsid"]] + pos_titles = [record.get("pos_item_title") or ""] + pos_bboxs = [record.get("pos_item_bbox") or "ori"] + neg_tfsids = [record["neg_item_tfsid"]] + neg_titles = [record.get("neg_item_title") or ""] + neg_bboxs = [record.get("neg_item_bbox") or "ori"] + + return { + "query_tfsid": record["query_tfsid"], + "query_bbox": record.get("query_bbox") or "ori", + "instructions": instructions, + "pos_item_tfsids": pos_tfsids, + "pos_item_titles": pos_titles, + "pos_item_bboxs": pos_bboxs, + "neg_item_tfsids": neg_tfsids, + "neg_item_titles": neg_titles, + "neg_item_bboxs": neg_bboxs, + } + + # ------------------------------------------------------------------ + # 图片处理 + # ------------------------------------------------------------------ + @staticmethod + def _clamp_aspect_ratio(img: Image.Image, max_ratio: float = 100) -> Image.Image: + """如果图片长宽比超过 max_ratio,将其 resize 到长宽比等于 max_ratio。""" + w, h = img.size + assert w > 0 and h > 0 + ratio = max(w, h) / min(w, h) + if ratio <= max_ratio: + return img + if w > h: + new_w = int(h * max_ratio) + new_h = h + else: + new_w = w + new_h = int(w * max_ratio) + return img.resize((new_w, new_h), Image.BILINEAR) + + def _open_image(self, image_name: str) -> Image.Image: + local_path = os.path.join(self.image_local_dir, image_name) + return Image.open(local_path) + + def get_image(self, image_name: str, roi: str): + """返回 (crop 图, 整图),roi 非法时 crop 图退化为整图。""" + if len(roi.split(' ')) == 6: + roi = ' '.join(roi.split(' ')[:4]) + elif len(roi.split(' ')) == 4: + pass + else: + roi = 'ori' + + image = self._open_image(image_name) + if image.mode != "RGB": + image = image.convert("RGB") + + image_full = image.copy() + + if roi != 'ori': + xmin, ymin, xmax, ymax = [int(float(z)) for z in roi.split(' ')[:4]] + xmin = max(0, xmin) + xmax = min(image.width - 1, xmax) + ymin = max(0, ymin) + ymax = min(image.height - 1, ymax) + if (ymax - ymin) > 2 and (xmax - xmin) > 2: + image = image.crop((xmin, ymin, xmax, ymax)) + + # 如果image或者image_full长宽比超过100,将长宽比resize到100 + image = self._clamp_aspect_ratio(image, max_ratio=100) + image_full = self._clamp_aspect_ratio(image_full, max_ratio=100) + + return image, image_full + + # ------------------------------------------------------------------ + # message 构造 + # ------------------------------------------------------------------ + def _select_images(self, image_crop, image_full) -> List[Image.Image]: + if self.image_type == "full": + return [image_full] + if self.image_type == "crop": + return [image_crop] + return [image_full, image_crop] + + def _build_message(self, images: List[Image.Image], text: str) -> List[Dict]: + content = [ + {"type": "image", "image": image, "min_pixels": self.min_pixels, "max_pixels": self.max_pixels} + for image in images + ] + content.append({"type": "text", "text": text}) + return [ + {"role": "system", "content": [{"type": "text", "text": SYSTEM_PROMPT}]}, + {"role": "user", "content": content}, + ] + + def _fallback_item(self): + """取数失败时返回纯文本占位样本,避免单条脏数据打断训练。""" + query_message = self._build_message([], "prompt:Empty.") + doc_message = self._build_message([], "title:Empty.") + return query_message, doc_message, doc_message + + def __getitem__(self, index): + try_times = 2 + i = 0 + while i < try_times: + try: + record = self.records[index] + + pos_idx = random.randrange(len(record["pos_item_tfsids"])) + neg_idx = random.randrange(len(record["neg_item_tfsids"])) + + query_image, query_image_full = self.get_image( + record["query_tfsid"], record["query_bbox"] + ) + pos_image, pos_image_full = self.get_image( + record["pos_item_tfsids"][pos_idx], + self._pick(record["pos_item_bboxs"], pos_idx, "ori"), + ) + neg_image, neg_image_full = self.get_image( + record["neg_item_tfsids"][neg_idx], + self._pick(record["neg_item_bboxs"], neg_idx, "ori"), + ) + + instruction = self._pick(record["instructions"], pos_idx) + pos_title = self._pick(record["pos_item_titles"], pos_idx) + neg_title = self._pick(record["neg_item_titles"], neg_idx) + + query_message = self._build_message( + self._select_images(query_image, query_image_full), + f"prompt:{instruction}", + ) + pos_message = self._build_message( + self._select_images(pos_image, pos_image_full), + f"title:{pos_title}", + ) + neg_message = self._build_message( + self._select_images(neg_image, neg_image_full), + f"title:{neg_title}", + ) + + return query_message, pos_message, neg_message + except Exception as e: + print('exception for getitem {}, try times {}/{} : {}'.format(index, i, try_times, e)) + i += 1 + + print("error testing") + return self._fallback_item() diff --git a/code/multi_vlm2vec_train/dataset/datasets_tuwen_tbstars.py b/code/multi_vlm2vec_train/dataset/datasets_tuwen_tbstars.py new file mode 100644 index 0000000000000000000000000000000000000000..20f84c5feb8e01c2a4ad1790b98ff5069a19bb6c --- /dev/null +++ b/code/multi_vlm2vec_train/dataset/datasets_tuwen_tbstars.py @@ -0,0 +1,241 @@ +import torch +import io +import json +import random +from typing import Optional, Union + +import oss2 as oss +from PIL import Image +from torch.utils.data import Dataset +import common_io +from tqdm import tqdm + +def load_oss_bucket(): + endpoint = 'http://oss-cn-zhangjiakou-internal.aliyuncs.com' # + akey = 'LTAI5tMZb5HHH6HHgAExAyiL' # + aid = '6MVP8JnTE01t4TLUHhPoFV0swZNTrb' # 'xxx' + bucket = 'pailitao-ai' # + auth = oss.Auth(akey, aid) + bucket = oss.Bucket(auth, endpoint, bucket) + return bucket + +OSS_BUCKET = load_oss_bucket() + +## 测试数据集 +class TuwenTBStarsEvalDataset(Dataset): + def __init__(self, args): + super(TuwenTBStarsEvalDataset, self).__init__() + self.args = args + self.label_index = {'0': 0, '1': 1} + self.parse_odps_data(args.tables) + + def __len__(self): + return len(self.test_images) + + def _prepare_data_dict(self, img_base64=None, img_crop_base64=None, txt=''): + if img_base64 is None and img_crop_base64 is None: + return {"txt": txt} + elif img_crop_base64 is None: + return {"txt": txt, "image": img_base64} + elif img_base64 is None: + return {"txt": txt, "image_crop": img_crop_base64} + elif txt == '': + return {"image": img_base64, "image_crop": img_crop_base64} + else: + return {"txt": txt, "image": img_base64, "image_crop": img_crop_base64} + + def construct_messages(self, data_dict): + if 'txt' in data_dict and 'image' in data_dict and 'image_crop' in data_dict: + message = [ + { + "role": "user", + "content": [ + {"type": "image", "image": data_dict['image']}, + {"type": "image", "image": data_dict['image_crop']}, + {"type": "text", "text": f"{data_dict['txt']}"} + ] + }, + { + "role": "assistant", + "content": [ + {"type": "text", "text": f"."} + ] + }, + ] + elif 'txt' in data_dict and 'image' in data_dict: + message = [ + { + "role": "user", + "content": [ + {"type": "image", "image": data_dict['image']}, + {"type": "text", "text": f"{data_dict['txt']}"} + ] + }, + { + "role": "assistant", + "content": [ + {"type": "text", "text": f"."} + ] + }, + ] + elif 'txt' in data_dict and 'image_crop' in data_dict: + message = [ + { + "role": "user", + "content": [ + {"type": "image", "image": data_dict['image_crop']}, + {"type": "text", "text": f"{data_dict['txt']}"} + ] + }, + { + "role": "assistant", + "content": [ + {"type": "text", "text": f"."} + ] + }, + ] + elif 'txt' in data_dict: + message = [ + { + "role": "user", + "content": [ + {"type": "text", "text": f"{data_dict['txt']}"} + ] + }, + { + "role": "assistant", + "content": [ + {"type": "text", "text": f"."} + ] + }, + ] + elif 'image' in data_dict and 'image_crop' in data_dict: + message = [ + { + "role": "user", + "content": [ + {"type": "image", "image": data_dict['image']}, + {"type": "image", "image": data_dict['image_crop']}, + {"type": "text", "text": f""} + ] + }, + { + "role": "assistant", + "content": [ + {"type": "text", "text": f"."} + ] + }, + ] + elif 'image' in data_dict: + message = [ + { + "role": "user", + "content": [ + {"type": "image", "image": data_dict['image']}, + {"type": "text", "text": f""} + ] + }, + { + "role": "assistant", + "content": [ + {"type": "text", "text": f"."} + ] + }, + ] + elif 'image_crop' in data_dict: + message = [ + { + "role": "user", + "content": [ + {"type": "image", "image": data_dict['image_crop']}, + {"type": "text", "text": f""} + ] + }, + { + "role": "assistant", + "content": [ + {"type": "text", "text": f"."} + ] + }, + ] + return message + + def get_image_from_oss(self, image_name, roi): + if len(roi.split(' ')) == 6: + roi = ' '.join(roi.split(' ')[:4]) + elif len(roi.split(' ')) == 4: + pass + else: + roi = 'ori' + + oss_path = f'peifeng/multi_vlm2vec/dataset/merge/test_image/{image_name}' + image = Image.open(OSS_BUCKET.get_object(oss_path)) + if image.mode != "RGB": + image = image.convert("RGB") + + image_full = image.copy() + + if roi != 'ori': + xmin, ymin, xmax, ymax = [int(float(z)) for z in roi.split(' ')[:4]] + xmin = max(0, xmin) + xmax = min(image.width - 1, xmax) + ymin = max(0, ymin) + ymax = min(image.height - 1, ymax) + if (ymax - ymin) > 2 and (xmax - xmin) > 2: + image = image.crop((xmin, ymin, xmax, ymax)) + + return image, image_full + + def __getitem__(self, index): + try_times = 3 + i = 0 + while i < try_times: + try: + query_tfsid, query_bbox, query_text, item_tfsid, item_title, item_bbox, label = self.test_images[index] + + query_image, query_image_full = self.get_image_from_oss(query_tfsid, query_bbox) + item_image, item_image_full = self.get_image_from_oss(item_tfsid, item_bbox) + + query_dict = self._prepare_data_dict(img_base64=query_image_full, img_crop_base64=query_image, txt=f"prompt:{query_text}") + query_message = self.construct_messages(query_dict) + + item_dict = self._prepare_data_dict(img_base64=item_image_full, img_crop_base64=item_image, txt=f"title:{item_title}") + item_message = self.construct_messages(item_dict) + + label_index = self.label_index[label] + + # return f"{query_tfsid}_#_{query_bbox}_#_{query_text}", query_message, item_message, label_index, f"{item_tfsid}_#_{item_bbox}_#_{item_title}" + return query_tfsid, query_message, item_message, label_index, item_tfsid + except Exception as e: + print('exception for getitem {}, try times {}/{} : {}'.format(self.test_images[index], i, try_times, e)) + i += 1 + + query_dict = {"txt": 'Empty.'} + item_dict = {"txt": 'Empty.'} + query_message = self.construct_messages(query_dict) + item_message = self.construct_messages(item_dict) + print("error testing") + return 'None', query_message, item_message, 'None', 'None' + + def parse_odps_data(self, odps_table): + + reader = common_io.table.TableReader(odps_table, slice_id=0, slice_count=1, + selected_cols="query_tfsid, query_bbox, query_text, item_tfsid, item_title, item_bbox, label", + excluded_cols="", num_threads=16) + num_records = reader.get_row_count() + num_records_to_read = num_records if self.args.max_lines < 0 else min(num_records, self.args.max_lines) # max_lines用来设定dataset的大小,进行截断 + odps_records = reader.read(num_records=num_records_to_read) + + self.test_images = list() + self.max_length = 512 + for i in tqdm(range(num_records_to_read)): + try: + query_tfsid, query_bbox, query_text, item_tfsid, item_title, item_bbox, label = [x if type(x) in [type(1), type(None), type('1')] else x.decode() for x in odps_records[i]] + query_text = query_text[:self.max_length - 2] + item_title = item_title[:self.max_length - 2] + + self.test_images.append([query_tfsid, query_bbox, query_text, item_tfsid, item_title, item_bbox, label]) + except Exception as e: + print("test dataset exception for reader {}".format(e)) + + reader.close() diff --git a/code/multi_vlm2vec_train/dataset/datasets_tuwen_tbstars_infonce.py b/code/multi_vlm2vec_train/dataset/datasets_tuwen_tbstars_infonce.py new file mode 100644 index 0000000000000000000000000000000000000000..0d2f889022736061a5081711ed28e72ea74422f0 --- /dev/null +++ b/code/multi_vlm2vec_train/dataset/datasets_tuwen_tbstars_infonce.py @@ -0,0 +1,285 @@ +import torch +import io +import json +import random +from typing import Optional, Union + +import oss2 as oss +from PIL import Image +from torch.utils.data import Dataset +import common_io +from tqdm import tqdm + +def load_oss_bucket(): + endpoint = 'http://oss-cn-zhangjiakou-internal.aliyuncs.com' # + akey = 'LTAI5tMZb5HHH6HHgAExAyiL' # + aid = '6MVP8JnTE01t4TLUHhPoFV0swZNTrb' # 'xxx' + bucket = 'pailitao-ai' # + auth = oss.Auth(akey, aid) + bucket = oss.Bucket(auth, endpoint, bucket) + return bucket + +OSS_BUCKET = load_oss_bucket() + + +class CIRDataset_tuwen(Dataset): + """ + 三元组数据采集 + """ + def __init__(self, args, tokenizer): + ## data args init + self.args = args + ## parse_odps_data + self.parse_odps_data(self.args.tables) + self.tokenizer = tokenizer + + def __len__(self): + return self.num_records_to_read_all + + def _prepare_data_dict(self, img_base64=None, img_crop_base64=None, txt=''): + if img_base64 is None and img_crop_base64 is None: + return {"txt": txt} + elif img_crop_base64 is None: + return {"txt": txt, "image": img_base64} + elif img_base64 is None: + return {"txt": txt, "image_crop": img_crop_base64} + elif txt == '': + return {"image": img_base64, "image_crop": img_crop_base64} + else: + return {"txt": txt, "image": img_base64, "image_crop": img_crop_base64} + + def construct_messages(self, data_dict): + if 'txt' in data_dict and 'image' in data_dict and 'image_crop' in data_dict: + message = [ + { + "role": "user", + "content": [ + {"type": "image", "image": data_dict['image']}, + {"type": "image", "image": data_dict['image_crop']}, + {"type": "text", "text": f"{data_dict['txt']}"} + ] + }, + { + "role": "assistant", + "content": [ + {"type": "text", "text": f"."} + ] + }, + ] + elif 'txt' in data_dict and 'image' in data_dict: + message = [ + { + "role": "user", + "content": [ + {"type": "image", "image": data_dict['image']}, + {"type": "text", "text": f"{data_dict['txt']}"} + ] + }, + { + "role": "assistant", + "content": [ + {"type": "text", "text": f"."} + ] + }, + ] + elif 'txt' in data_dict and 'image_crop' in data_dict: + message = [ + { + "role": "user", + "content": [ + {"type": "image", "image": data_dict['image_crop']}, + {"type": "text", "text": f"{data_dict['txt']}"} + ] + }, + { + "role": "assistant", + "content": [ + {"type": "text", "text": f"."} + ] + }, + ] + elif 'txt' in data_dict: + message = [ + { + "role": "user", + "content": [ + {"type": "text", "text": f"{data_dict['txt']}"} + ] + }, + { + "role": "assistant", + "content": [ + {"type": "text", "text": f"."} + ] + }, + ] + elif 'image' in data_dict and 'image_crop' in data_dict: + message = [ + { + "role": "user", + "content": [ + {"type": "image", "image": data_dict['image']}, + {"type": "image", "image": data_dict['image_crop']}, + {"type": "text", "text": f""} + ] + }, + { + "role": "assistant", + "content": [ + {"type": "text", "text": f"."} + ] + }, + ] + elif 'image' in data_dict: + message = [ + { + "role": "user", + "content": [ + {"type": "image", "image": data_dict['image']}, + {"type": "text", "text": f""} + ] + }, + { + "role": "assistant", + "content": [ + {"type": "text", "text": f"."} + ] + }, + ] + elif 'image_crop' in data_dict: + message = [ + { + "role": "user", + "content": [ + {"type": "image", "image": data_dict['image_crop']}, + {"type": "text", "text": f""} + ] + }, + { + "role": "assistant", + "content": [ + {"type": "text", "text": f"."} + ] + }, + ] + return message + + def get_image_from_oss(self, image_name, roi): + if len(roi.split(' ')) == 6: + roi = ' '.join(roi.split(' ')[:4]) + elif len(roi.split(' ')) == 4: + pass + else: + roi = 'ori' + + oss_path = f'peifeng/multi_vlm2vec/dataset/merge/image/{image_name}' + image = Image.open(OSS_BUCKET.get_object(oss_path)) + if image.mode != "RGB": + image = image.convert("RGB") + + image_full = image.copy() + + if roi != 'ori': + xmin, ymin, xmax, ymax = [int(float(z)) for z in roi.split(' ')[:4]] + xmin = max(0, xmin) + xmax = min(image.width - 1, xmax) + ymin = max(0, ymin) + ymax = min(image.height - 1, ymax) + if (ymax - ymin) > 2 and (xmax - xmin) > 2: + image = image.crop((xmin, ymin, xmax, ymax)) + + return image, image_full + + def __getitem__(self, index): + try_times = 2 + i = 0 + while i < try_times: + try: + # query + query_tfsid = self.query_tfsid_list[index] + query_bbox = self.query_bbox_list[index] + query_image, query_image_full = self.get_image_from_oss(query_tfsid, query_bbox) + + # pos_item + pos_item_idx = random.randint(0, len(self.pos_item_tfsids_list[index]) - 1) + query_prompt = self.pos_prompts_list[index][pos_item_idx] + pos_item_tfsid = self.pos_item_tfsids_list[index][pos_item_idx] + pos_item_title = self.pos_item_titles_list[index][pos_item_idx] + pos_item_bbox = self.pos_item_bboxs_list[index][pos_item_idx] + pos_item_image, pos_item_image_full = self.get_image_from_oss(pos_item_tfsid, pos_item_bbox) + + # neg_item + neg_item_idx = random.randint(0, len(self.neg_item_tfsids_list[index]) - 1) + neg_item_tfsid = self.neg_item_tfsids_list[index][neg_item_idx] + neg_item_title = self.neg_item_titles_list[index][neg_item_idx] + neg_item_bbox = self.neg_item_bboxs_list[index][neg_item_idx] + neg_item_image, neg_item_image_full = self.get_image_from_oss(neg_item_tfsid, neg_item_bbox) + + # 构造三元组 + query_dict = self._prepare_data_dict(img_base64=query_image_full, img_crop_base64=query_image, txt=f"prompt:{query_prompt}") + query_message = self.construct_messages(query_dict) + + pos_item_dict = self._prepare_data_dict(img_base64=pos_item_image_full, img_crop_base64=pos_item_image, txt=f"title:{pos_item_title}") + pos_item_message = self.construct_messages(pos_item_dict) + + neg_item_dict = self._prepare_data_dict(img_base64=neg_item_image_full, img_crop_base64=neg_item_image, txt=f"title:{neg_item_title}") + neg_item_message = self.construct_messages(neg_item_dict) + + return query_message, pos_item_message, neg_item_message + except Exception as e: + print('exception for getitem {}, try times {}/{} : {}'.format(index, i, try_times, e)) + i += 1 + + query_message = self.construct_messages({"txt": 'Empty.'}) + pos_item_message = self.construct_messages({"txt": 'Empty.'}) + neg_item_message = self.construct_messages({"txt": 'Empty.'}) + print("error testing") + return query_message, pos_item_message, neg_item_message + + def parse_odps_data(self, odps_table): + reader = common_io.table.TableReader(odps_table, slice_id=0, slice_count=1, + selected_cols="query_tfsid,query_bbox,pos_prompts,pos_item_tfsids,pos_item_titles,pos_item_bboxs,neg_item_tfsids,neg_item_titles,neg_item_bboxs", + excluded_cols="", num_threads=16) + num_records = reader.get_row_count() + num_records_to_read = num_records if self.args.max_lines < 0 else min(num_records, self.args.max_lines) # max_lines用来设定dataset的大小,进行截断 + print('total of {} lines. read {} lines'.format(num_records_to_read, num_records_to_read)) + + odps_records = reader.read(num_records=num_records_to_read) + ## 获取总共的样本数量,以及当前rank包含的样本数量 + self.num_records_to_read_all = num_records_to_read + + self.query_tfsid_list = [] + self.query_bbox_list = [] + self.pos_prompts_list = [] + self.pos_item_tfsids_list = [] + self.pos_item_titles_list = [] + self.pos_item_bboxs_list = [] + self.neg_item_tfsids_list = [] + self.neg_item_titles_list = [] + self.neg_item_bboxs_list = [] + + for i in tqdm(range(num_records_to_read)): + row = odps_records[i] + query_tfsid = row[0] if isinstance(row[0], (int, type(None), str)) else row[0].decode() + query_bbox = row[1] if isinstance(row[1], (int, type(None), str)) else row[1].decode() + pos_prompts = row[2] if isinstance(row[2], (int, type(None), str)) else row[2].decode() + pos_item_tfsids = row[3] if isinstance(row[3], (int, type(None), str)) else row[3].decode() + pos_item_titles = row[4] if isinstance(row[4], (int, type(None), str)) else row[4].decode() + pos_item_bboxs = row[5] if isinstance(row[5], (int, type(None), str)) else row[5].decode() + neg_item_tfsids = row[6] if isinstance(row[6], (int, type(None), str)) else row[6].decode() + neg_item_titles = row[7] if isinstance(row[7], (int, type(None), str)) else row[7].decode() + neg_item_bboxs = row[8] if isinstance(row[8], (int, type(None), str)) else row[8].decode() + + self.query_tfsid_list.append(query_tfsid) + self.query_bbox_list.append(query_bbox) + self.pos_prompts_list.append(pos_prompts.split('##')) + self.pos_item_tfsids_list.append(pos_item_tfsids.split('##')) + self.pos_item_titles_list.append(pos_item_titles.split('##')) + self.pos_item_bboxs_list.append(pos_item_bboxs.split('##')) + self.neg_item_tfsids_list.append(neg_item_tfsids.split('##')) + self.neg_item_titles_list.append(neg_item_titles.split('##')) + self.neg_item_bboxs_list.append(neg_item_bboxs.split('##')) + reader.close() + + assert len(self.query_tfsid_list) > 0, 'the number of valid item should larger than 0' + print('total of {} items (rewritten parse).'.format(len(self.query_tfsid_list))) \ No newline at end of file diff --git a/code/multi_vlm2vec_train/dataset/tfsClient.py b/code/multi_vlm2vec_train/dataset/tfsClient.py new file mode 100644 index 0000000000000000000000000000000000000000..623505f386c54d9f2ff2bb21635f93f84d6cc96e --- /dev/null +++ b/code/multi_vlm2vec_train/dataset/tfsClient.py @@ -0,0 +1,107 @@ +# -*- encoding: utf-8 -*- +""" +@File : tfsManager.py +@Contact : zhangwang.zhang@alibaba-inc.com +@License : (C)Copyright 2021, Alibaba Group + +@Modify Time @Author @Version @Desciption +------------ ------- -------- ----------- +2021/10/20 21:53 heqing 1.0 None + +# import lib +from tfsClient import tfsManager +# 初始化客户端(初始化一次即可) +downloader = tfsManager('1316bec91c411') + +response = downloader.fetchFile('O1CN01LkpGBC1itIwx70XNy_!!0-rate.jpg', timeout=3) + + +""" + +import random +import time +import urllib +import urllib.request + +# import lib +import requests + + +class tfsError(Exception): + """base tfs Error""" + + +class tfsManager: + def __init__(self, appkey): + self.appKey = str(appkey) + self.tmpTfsProxyList = [] + self.lastRefreshTime = 0 + + def getTfsProxyList(self): + """ + 获取tfs的vip列表 + """ + try: + tfsResponse = requests.get( + "http://restful-store.vip.tbsite.net:3800/tfs.list" + ) + if tfsResponse.status_code == 200: + self.tmpTfsProxyList = tfsResponse.text.split("\n")[1:] + if len(self.tmpTfsProxyList) == 0: + raise RuntimeError("tmpTfsProxyList is empty") + self.lastRefreshTime = time.time() + else: + raise tfsError("ResponseError:", tfsResponse.status_code) + except requests.ConnectionError: + raise tfsError("ConnectionError:", str(requests.ConnectionError)) + + def refreshTfsProxyList(self): + """ + 判断是否需要刷新vip列表 + """ + needRefresh = False + if len(self.tmpTfsProxyList) == 0: + needRefresh = True + else: + diffTime = time.time() - self.lastRefreshTime + if diffTime >= 60: + needRefresh = True + if needRefresh: + self.getTfsProxyList() + + def fetchFile(self, tfsFileName, timeout=None): + """ + 从tfs服务器获取文件 + :param tfsFileName: 请求的文件名 + :return: http response + """ + self.refreshTfsProxyList() + headers = {"user-agent": "Picasso-Python-Client-V1.0.2"} + Host = random.choice(self.tmpTfsProxyList) + requestUrl = "http://" + Host + "/v1/" + self.appKey + "/" + tfsFileName + # response = requests.get(requestUrl, headers=headers, timeout=timeout) + request = urllib.request.Request(requestUrl, headers=headers) + response = urllib.request.urlopen(request, timeout=timeout) + return response + + def fetchMetadata(self, tfsFileName, timeout=None): + """ + 获取一个TFS文件的元信息 + :param tfsFileName: 请求的文件名 + :return: http response + """ + self.refreshTfsProxyList() + headers = {"user-agent": "Picasso-Python-Client-V1.0.2"} + Host = random.choice(self.tmpTfsProxyList) + requestUrl = ( + "http://" + + Host + + "/v1/" + + self.appKey + + "/" + + "metadata" + + "/" + + tfsFileName + ) + response = requests.get(requestUrl, headers=headers, timeout=timeout) + return response \ No newline at end of file diff --git a/code/multi_vlm2vec_train/ds_configs/zero2.json b/code/multi_vlm2vec_train/ds_configs/zero2.json new file mode 100644 index 0000000000000000000000000000000000000000..5e55d244f856c021c072c5a89eee390b3c8847eb --- /dev/null +++ b/code/multi_vlm2vec_train/ds_configs/zero2.json @@ -0,0 +1,24 @@ +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "bf16": { + "enabled": "auto" + }, + "train_micro_batch_size_per_gpu": "auto", + "train_batch_size": "auto", + "gradient_accumulation_steps": "auto", + "zero_optimization": { + "stage": 2, + "overlap_comm": false, + "contiguous_gradients": true, + "sub_group_size": 1e9, + "reduce_bucket_size": "auto" + }, + "overlap_comm": true +} \ No newline at end of file diff --git a/code/multi_vlm2vec_train/ds_configs/zero3.json b/code/multi_vlm2vec_train/ds_configs/zero3.json new file mode 100644 index 0000000000000000000000000000000000000000..6917317af62da757ca759a92b326ddfa65b203cc --- /dev/null +++ b/code/multi_vlm2vec_train/ds_configs/zero3.json @@ -0,0 +1,28 @@ +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "bf16": { + "enabled": "auto" + }, + "train_micro_batch_size_per_gpu": "auto", + "train_batch_size": "auto", + "gradient_accumulation_steps": "auto", + "zero_optimization": { + "stage": 3, + "overlap_comm": true, + "contiguous_gradients": true, + "sub_group_size": 1e9, + "reduce_bucket_size": "auto", + "stage3_prefetch_bucket_size": "auto", + "stage3_param_persistence_threshold": "auto", + "stage3_max_live_parameters": 1e9, + "stage3_max_reuse_distance": 1e9, + "stage3_gather_16bit_weights_on_model_save": true + } +} \ No newline at end of file diff --git a/code/multi_vlm2vec_train/eval/__pycache__/eval_tuwen_qwen3vl.cpython-313.pyc b/code/multi_vlm2vec_train/eval/__pycache__/eval_tuwen_qwen3vl.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29a068e0e58625734429a99e64a7ae05e817e28f Binary files /dev/null and b/code/multi_vlm2vec_train/eval/__pycache__/eval_tuwen_qwen3vl.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/eval/__pycache__/eval_utils.cpython-310.pyc b/code/multi_vlm2vec_train/eval/__pycache__/eval_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb023a10776d79aab207c8369ecf61f74e8442b6 Binary files /dev/null and b/code/multi_vlm2vec_train/eval/__pycache__/eval_utils.cpython-310.pyc differ diff --git a/code/multi_vlm2vec_train/eval/__pycache__/eval_utils.cpython-313.pyc b/code/multi_vlm2vec_train/eval/__pycache__/eval_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efbb10c099a82d437fa58959e592f3f4724a1a6d Binary files /dev/null and b/code/multi_vlm2vec_train/eval/__pycache__/eval_utils.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/eval/eval_tuwen_qwen3vl.py b/code/multi_vlm2vec_train/eval/eval_tuwen_qwen3vl.py new file mode 100644 index 0000000000000000000000000000000000000000..d2e45eec2070c2cd98272b685ad3d061649d01eb --- /dev/null +++ b/code/multi_vlm2vec_train/eval/eval_tuwen_qwen3vl.py @@ -0,0 +1,198 @@ +import json +import jsonlines +import re +import sys +import os +current_file_path = os.path.dirname(os.path.abspath(__file__)) +module_path = os.path.join(current_file_path, "../") +sys.path.append(module_path) + +from peft import LoraConfig, get_peft_model, PeftModel +import torch +import argparse +import accelerate + +from torch.utils.data import DataLoader +import torch.nn.functional as F +from accelerate import Accelerator +from tqdm import tqdm + +from models.qwen3_vl_embedding import Qwen3VLForEmbedding, Qwen3VLProcessor +from dataset.datasets_tuwen_qwen3vl import TuwenQwenEvalDataset +from collators.tuwen_qwen3vl_eval import TuwenQwenDataCollator +from eval.eval_utils import * + + +def load_json(path): + with open(path, 'r', encoding='utf-8') as f: + data = json.load(f) # 将文件内容解析为Python字典或列表 + return data + +def save_json(path, data): + with open(path, "w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False) # 直接写入文件 + + +def pooling_last(hidden_state: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor: + flipped_tensor = attention_mask.flip(dims=[1]) + last_one_positions = flipped_tensor.argmax(dim=1) + col = attention_mask.shape[1] - last_one_positions - 1 + row = torch.arange(hidden_state.shape[0], device=hidden_state.device) + return hidden_state[row, col] + +def eval(args): + ## 模型加载 + model_path = args.model_id + model = Qwen3VLForEmbedding.from_pretrained( + model_path, trust_remote_code=True + ) + + if args.lora: + print("Loading lora ckpt.") + lora_config = LoraConfig.from_pretrained(args.lora_pth) + lora_model = PeftModel.from_pretrained(model, args.lora_pth, config=lora_config) + model = lora_model.merge_and_unload() + + model.eval() + model.requires_grad_(False) + + # 全参 checkpoint 目录里通常没有 tokenizer/processor 文件, + # 用 --processor_path 指定底座模型路径;不传则回退到 model_path + processor_path = args.processor_path or model_path + processor = Qwen3VLProcessor.from_pretrained( + processor_path, padding_side='right' + ) + tokenizer = processor.tokenizer + + accelerator = Accelerator(mixed_precision='bf16') + device = accelerator.device + is_main_process = accelerator.is_main_process + ## 数据集加载 + query_doc_dataset = TuwenQwenEvalDataset(args) + query_doc_collator = TuwenQwenDataCollator(tokenizer=tokenizer, processor=processor) + query_doc_dataloader = DataLoader(query_doc_dataset, batch_size=64, num_workers=4, shuffle=False, collate_fn=query_doc_collator, pin_memory=True) + ## 数据集加载 + def tensors_to_device(data, device, dtype=model.dtype): + for key in data.keys(): + if isinstance(data[key], torch.Tensor): + if 'pixel_values' in key: + data[key] = data[key].to(device).to(dtype) + else: + data[key] = data[key].to(device) + return data + + query_dic_all = {} + + emb_dim = args.emb_dim + out_dim = args.out_dim + + with torch.no_grad(): + model, query_doc_dataloader= accelerator.prepare(model, query_doc_dataloader) + + for query_batch, doc_batch, query_tfs, label_list, doc_tfs in tqdm(query_doc_dataloader): + doc_batch = tensors_to_device(doc_batch, device) + doc_outputs = model(**doc_batch) + candidate_embed = pooling_last(doc_outputs.last_hidden_state, doc_batch.get('attention_mask')) + candidate_embed = candidate_embed[..., :emb_dim] + candidate_embed = F.normalize(candidate_embed, p=2, dim=-1) + + candidate_embed = accelerator.gather_for_metrics(candidate_embed) + + query_batch = tensors_to_device(query_batch, device) + query_outputs = model(**query_batch) + query_embed = pooling_last(query_outputs.last_hidden_state, query_batch.get('attention_mask')) + query_embed = query_embed[..., :emb_dim] + query_embed = F.normalize(query_embed, p=2, dim=-1) + + query_embed = accelerator.gather_for_metrics(query_embed) + + cos_sim = (query_embed * candidate_embed).sum(1).reshape(-1).tolist() # shape=bs + query_tfs = accelerate.utils.gather_object(query_tfs)[:len(cos_sim)] + doc_tfs = accelerate.utils.gather_object(doc_tfs)[:len(cos_sim)] + label_list = accelerate.utils.gather_object(label_list)[:len(cos_sim)] + + if is_main_process: + for i in range(len(query_tfs)): + if query_tfs[i] not in query_dic_all: + query_dic_all[query_tfs[i]] = {} + query_dic_all[query_tfs[i]]['label'] = [label_list[i]] + else: + query_dic_all[query_tfs[i]]['label'].append(label_list[i]) + + for i in range(len(query_tfs)): + if 'sim' not in query_dic_all[query_tfs[i]]: + query_dic_all[query_tfs[i]]['sim'] = [cos_sim[i]] + else: + query_dic_all[query_tfs[i]]['sim'].append(cos_sim[i]) + + for i in range(len(query_tfs)): + if 'doc_tfs' not in query_dic_all[query_tfs[i]]: + query_dic_all[query_tfs[i]]['doc_tfs'] = [doc_tfs[i]] + else: + query_dic_all[query_tfs[i]]['doc_tfs'].append(doc_tfs[i]) + + accelerator.wait_for_everyone() + + if is_main_process: + results_all_dict = tongkuan_score_print(query_dic_all, sim_weight = [0.2, 0.2, 0.2, 0.2, 0.2]) + ckpt_tag = os.path.basename(os.path.normpath(args.lora_pth if args.lora else args.model_id)) + if args.all_eval: + data = {ckpt_tag: {"results": results_all_dict}} + with jsonlines.open(args.eval_json, mode='a') as writer: + writer.write(data) + if args.result_json: + result_path = args.result_json + if args.all_eval: + root, ext = os.path.splitext(result_path) + result_path = f"{root}_{ckpt_tag}{ext or '.json'}" + os.makedirs(os.path.dirname(result_path) or '.', exist_ok=True) + save_json(result_path, results_all_dict) + +""" +CUDA_VISIABLE_DEVICE=3 python eval/eval_tuwen_qwen3vl.py +python -m accelerate.commands.launch --num_processes 4 eval/eval_tuwen_qwen3vl.py +python -m pip install jsonlines accelerate peft qwen_vl_utils +""" +if __name__ == "__main__": + print("begin reading input parameters") + parser = argparse.ArgumentParser() + 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') + parser.add_argument('--max_lines', default=10000000, type=int, help='Limit the data length') + parser.add_argument('--model_max_length', type=int, default=512) + parser.add_argument('--model_id', type=str, default="/data/oss_bucket_0/peifeng/vlm2vec/models/qwen/Qwen3-VL-Embedding-2B/") + parser.add_argument('--image_type', default="both",type=str) + parser.add_argument('--emb_dim', default=2048,type=int) + parser.add_argument('--out_dim', default=2048,type=int) + parser.add_argument('--query_text_require', type=str, default='True') + parser.add_argument('--doc_text_require', type=str, default='True') + parser.add_argument('--lora', type=str, default='True') + parser.add_argument('--lora_pth', type=str, default='/data/oss_bucket_0/liqi/cot_embedding/qwenvl_baseline_loraTrue/qwen_train_baseline_loraTrue/checkpoint-24092') + parser.add_argument('--processor_path', type=str, default='/data/oss_bucket_0/peifeng/vlm2vec/models/qwen/Qwen3-VL-Embedding-2B/', help='processor/tokenizer 所在路径(通常是底座模型),全参 checkpoint 评测时必传') + parser.add_argument('--result_json', type=str, default='/data/oss_bucket_0/liqi/cot_embedding/qwenvl_baseline_loraTrue/qwen_train_baseline_loraTrue/eval_result/24092-bianji.json', help='评测结果保存路径,不传则只打印') + parser.add_argument('--train_data_type', type=str, default='') + parser.add_argument('--test_data_type', type=str, default='') + parser.add_argument('--eval_json', type=str, default='') + parser.add_argument('--all_eval', type=str, default='False') + args = parser.parse_args() + args.query_text_require = args.query_text_require.lower() == 'true' + args.doc_text_require = args.doc_text_require.lower() == 'true' + args.lora = args.lora.lower() == 'true' + args.all_eval = args.all_eval.lower() == 'true' + if args.all_eval: + # lora 模式遍历 lora_pth 下的 checkpoint-*;全参模式遍历 model_id 下的 checkpoint-* + ckpt_root_path = args.lora_pth if args.lora else args.model_id + args.eval_json = os.path.join(ckpt_root_path, f"eval_{args.test_data_type}.json") + checkpoint_dirs = [ + os.path.join(ckpt_root_path, d) + for d in os.listdir(ckpt_root_path) + if os.path.isdir(os.path.join(ckpt_root_path, d)) and re.match(r"checkpoint-\d+", d) + ] + checkpoint_dirs.sort(key=lambda x: int(re.search(r"checkpoint-(\d+)", x).group(1))) + for ckpt_dir in checkpoint_dirs: + if args.lora: + args.lora_pth = ckpt_dir + else: + args.model_id = ckpt_dir + eval(args) + else: + eval(args) \ No newline at end of file diff --git a/code/multi_vlm2vec_train/eval/eval_tuwen_qwen3vl_cot_append.py b/code/multi_vlm2vec_train/eval/eval_tuwen_qwen3vl_cot_append.py new file mode 100644 index 0000000000000000000000000000000000000000..9c8c184248aa42bdee12d6506afee4c13d1d0096 --- /dev/null +++ b/code/multi_vlm2vec_train/eval/eval_tuwen_qwen3vl_cot_append.py @@ -0,0 +1,200 @@ +import json +import jsonlines +import re +import sys +import os +current_file_path = os.path.dirname(os.path.abspath(__file__)) +module_path = os.path.join(current_file_path, "../") +sys.path.append(module_path) + +from peft import LoraConfig, get_peft_model, PeftModel +import torch +import argparse +import accelerate + +from torch.utils.data import DataLoader +import torch.nn.functional as F +from accelerate import Accelerator +from tqdm import tqdm + +from models.qwen3_vl_embedding import Qwen3VLForEmbedding, Qwen3VLProcessor +from dataset.datasets_tuwen_qwen3vl_cot_append import TuwenQwenCotAppendEvalDataset +from collators.tuwen_qwen3vl_eval import TuwenQwenDataCollator +from eval.eval_utils import * + + +def load_json(path): + with open(path, 'r', encoding='utf-8') as f: + data = json.load(f) + return data + +def save_json(path, data): + with open(path, "w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False) + + +def pooling_last(hidden_state: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor: + flipped_tensor = attention_mask.flip(dims=[1]) + last_one_positions = flipped_tensor.argmax(dim=1) + col = attention_mask.shape[1] - last_one_positions - 1 + row = torch.arange(hidden_state.shape[0], device=hidden_state.device) + return hidden_state[row, col] + +def eval(args): + ## 模型加载 + model_path = args.model_id + model = Qwen3VLForEmbedding.from_pretrained( + model_path, trust_remote_code=True + ) + + if args.lora: + print("Loading lora ckpt.") + lora_config = LoraConfig.from_pretrained(args.lora_pth) + lora_model = PeftModel.from_pretrained(model, args.lora_pth, config=lora_config) + model = lora_model.merge_and_unload() + + model.eval() + model.requires_grad_(False) + + # 全参 checkpoint 目录里通常没有 tokenizer/processor 文件, + # 用 --processor_path 指定底座模型路径;不传则回退到 model_path + processor_path = args.processor_path or model_path + processor = Qwen3VLProcessor.from_pretrained( + processor_path, padding_side='right' + ) + tokenizer = processor.tokenizer + + accelerator = Accelerator(mixed_precision='bf16') + device = accelerator.device + is_main_process = accelerator.is_main_process + ## 数据集加载:query 文本后面追加离线 CoT + query_doc_dataset = TuwenQwenCotAppendEvalDataset(args) + query_doc_collator = TuwenQwenDataCollator(tokenizer=tokenizer, processor=processor) + query_doc_dataloader = DataLoader(query_doc_dataset, batch_size=args.batch_size, num_workers=4, shuffle=False, collate_fn=query_doc_collator, pin_memory=True) + ## 数据集加载 + def tensors_to_device(data, device, dtype=model.dtype): + for key in data.keys(): + if isinstance(data[key], torch.Tensor): + if 'pixel_values' in key: + data[key] = data[key].to(device).to(dtype) + else: + data[key] = data[key].to(device) + return data + + query_dic_all = {} + + emb_dim = args.emb_dim + out_dim = args.out_dim + + with torch.no_grad(): + model, query_doc_dataloader= accelerator.prepare(model, query_doc_dataloader) + + for query_batch, doc_batch, query_tfs, label_list, doc_tfs in tqdm(query_doc_dataloader): + doc_batch = tensors_to_device(doc_batch, device) + doc_outputs = model(**doc_batch) + candidate_embed = pooling_last(doc_outputs.last_hidden_state, doc_batch.get('attention_mask')) + candidate_embed = candidate_embed[..., :emb_dim] + candidate_embed = F.normalize(candidate_embed, p=2, dim=-1) + + candidate_embed = accelerator.gather_for_metrics(candidate_embed) + + query_batch = tensors_to_device(query_batch, device) + query_outputs = model(**query_batch) + query_embed = pooling_last(query_outputs.last_hidden_state, query_batch.get('attention_mask')) + query_embed = query_embed[..., :emb_dim] + query_embed = F.normalize(query_embed, p=2, dim=-1) + + query_embed = accelerator.gather_for_metrics(query_embed) + + cos_sim = (query_embed * candidate_embed).sum(1).reshape(-1).tolist() # shape=bs + query_tfs = accelerate.utils.gather_object(query_tfs)[:len(cos_sim)] + doc_tfs = accelerate.utils.gather_object(doc_tfs)[:len(cos_sim)] + label_list = accelerate.utils.gather_object(label_list)[:len(cos_sim)] + + if is_main_process: + for i in range(len(query_tfs)): + if query_tfs[i] not in query_dic_all: + query_dic_all[query_tfs[i]] = {} + query_dic_all[query_tfs[i]]['label'] = [label_list[i]] + else: + query_dic_all[query_tfs[i]]['label'].append(label_list[i]) + + for i in range(len(query_tfs)): + if 'sim' not in query_dic_all[query_tfs[i]]: + query_dic_all[query_tfs[i]]['sim'] = [cos_sim[i]] + else: + query_dic_all[query_tfs[i]]['sim'].append(cos_sim[i]) + + for i in range(len(query_tfs)): + if 'doc_tfs' not in query_dic_all[query_tfs[i]]: + query_dic_all[query_tfs[i]]['doc_tfs'] = [doc_tfs[i]] + else: + query_dic_all[query_tfs[i]]['doc_tfs'].append(doc_tfs[i]) + + accelerator.wait_for_everyone() + + if is_main_process: + results_all_dict = tongkuan_score_print(query_dic_all, sim_weight = [0.2, 0.2, 0.2, 0.2, 0.2]) + ckpt_tag = os.path.basename(os.path.normpath(args.lora_pth if args.lora else args.model_id)) + if args.all_eval: + data = {ckpt_tag: {"results": results_all_dict}} + with jsonlines.open(args.eval_json, mode='a') as writer: + writer.write(data) + if args.result_json: + result_path = args.result_json + if args.all_eval: + root, ext = os.path.splitext(result_path) + result_path = f"{root}_{ckpt_tag}{ext or '.json'}" + os.makedirs(os.path.dirname(result_path) or '.', exist_ok=True) + save_json(result_path, results_all_dict) + +""" +CUDA_VISIBLE_DEVICES=3 python eval/eval_tuwen_qwen3vl_cot_append.py --cot_json /path/to/cot.json +python -m pip install jsonlines accelerate peft qwen_vl_utils +python -m accelerate.commands.launch --num_processes 4 eval/eval_tuwen_qwen3vl_cot_append.py --cot_json /path/to/cot.json +""" +if __name__ == "__main__": + print("begin reading input parameters") + parser = argparse.ArgumentParser() + 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') + parser.add_argument('--cot_json', default="/data/oss_bucket_0/liqi/cot_embedding/nebula_train/bianji_lora128_lr1e-5_btz256_ep10_candidate8_cot0.1/train_qwen3vl_cot_lora_False_lmhead_True_epoch_10_lr1e-5_candidate8_cot0.1/eval_result/ckpt-6023/cot.json", type=str, help='离线 CoT json,按 (query_tfsid, query_text) 与 test_json 对齐') + parser.add_argument('--max_lines', default=10000000, type=int, help='Limit the data length') + parser.add_argument('--model_max_length', type=int, default=512) + parser.add_argument('--batch_size', type=int, default=128) + parser.add_argument('--model_id', type=str, default="/data/oss_bucket_0/liqi/cot_embedding/qwenvl_baseline_loraFalse/qwen_train_baseline_loraFalse/checkpoint-18069/") + parser.add_argument('--image_type', default="both",type=str) + parser.add_argument('--emb_dim', default=2048,type=int) + parser.add_argument('--out_dim', default=2048,type=int) + parser.add_argument('--query_text_require', type=str, default='True') + parser.add_argument('--doc_text_require', type=str, default='True') + parser.add_argument('--lora', type=str, default='False') + parser.add_argument('--lora_pth', type=str, default='') + parser.add_argument('--processor_path', type=str, default='/data/oss_bucket_0/peifeng/vlm2vec/models/qwen/Qwen3-VL-Embedding-2B/', help='processor/tokenizer 所在路径(通常是底座模型),全参 checkpoint 评测时必传') + parser.add_argument('--result_json', type=str, default='/data/oss_bucket_0/liqi/cot_embedding/qwenvl_baseline_loraFalse/qwen_train_baseline_loraFalse/eval_result/18069_cot_append.json', help='评测结果保存路径,不传则只打印') + parser.add_argument('--train_data_type', type=str, default='') + parser.add_argument('--test_data_type', type=str, default='') + parser.add_argument('--eval_json', type=str, default='') + parser.add_argument('--all_eval', type=str, default='False') + args = parser.parse_args() + args.query_text_require = args.query_text_require.lower() == 'true' + args.doc_text_require = args.doc_text_require.lower() == 'true' + args.lora = args.lora.lower() == 'true' + args.all_eval = args.all_eval.lower() == 'true' + if args.all_eval: + # lora 模式遍历 lora_pth 下的 checkpoint-*;全参模式遍历 model_id 下的 checkpoint-* + ckpt_root_path = args.lora_pth if args.lora else args.model_id + args.eval_json = os.path.join(ckpt_root_path, f"eval_cot_append_{args.test_data_type}.json") + checkpoint_dirs = [ + os.path.join(ckpt_root_path, d) + for d in os.listdir(ckpt_root_path) + if os.path.isdir(os.path.join(ckpt_root_path, d)) and re.match(r"checkpoint-\d+", d) + ] + checkpoint_dirs.sort(key=lambda x: int(re.search(r"checkpoint-(\d+)", x).group(1))) + for ckpt_dir in checkpoint_dirs: + if args.lora: + args.lora_pth = ckpt_dir + else: + args.model_id = ckpt_dir + eval(args) + else: + eval(args) diff --git a/code/multi_vlm2vec_train/eval/eval_tuwen_tbstars.py b/code/multi_vlm2vec_train/eval/eval_tuwen_tbstars.py new file mode 100644 index 0000000000000000000000000000000000000000..b4db2ed03ba2a98d1411cd523f5295e32fd78a14 --- /dev/null +++ b/code/multi_vlm2vec_train/eval/eval_tuwen_tbstars.py @@ -0,0 +1,201 @@ +import json +import jsonlines +import re +import sys +import os +current_file_path = os.path.dirname(os.path.abspath(__file__)) +module_path = os.path.join(current_file_path, "../") +sys.path.append(module_path) + +from openlm_hub import repo_download +from peft import LoraConfig, get_peft_model, PeftModel, TaskType +import torch +import argparse +from tqdm import tqdm + +from torch.utils.data import DataLoader +import torch.nn.functional as F +from accelerate import Accelerator +import accelerate + +from models.tbstars_ecom_emb.src.model.base_models import PROCESSOR_MAPPING, TOKENIZER_MAPPING +from models.tbstars_ecom_emb.src.model.biencoder_parscale_vl_dynamic.configuration_biencoder_parscale_vl import BiEncoderParscaleVLConfig +from models.tbstars_ecom_emb.src.model.biencoder_parscale_vl_dynamic.modeling_biencoder_parscale_vl import BiEncoderParscaleVLModel +from dataset.datasets_tuwen_tbstars import TuwenTBStarsEvalDataset +from collators.tuwen_tbstars_eval import TuwenTBStarsDataCollator +from eval.eval_utils import * + +def load_json(path): + with open(path, 'r', encoding='utf-8') as f: + data = json.load(f) # 将文件内容解析为Python字典或列表 + return data + +def save_json(path, data): + with open(path, "w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False) # 直接写入文件 + +def eval(args): + ## 模型加载 + if "oss_bucket_0" in args.model_id: + model_path = args.model_id + else: + model_id = args.model_id + model_path = repo_download(model_id, use_subprocess=True, local_dir="/data/oss_bucket_0/guijiang/hf_downloads/models/TBStars_VL_Ecom_EMB_3B_15000") + config = BiEncoderParscaleVLConfig.from_pretrained(model_path) + # emb_dim = Literal[128, 256, 512, 1024, 3072] + config.emb_dim = args.emb_dim + config.use_mrl = False + + config.bidirectional_attention = args.bidirectional_attention + config.inner_config.bidirectional_attention = args.bidirectional_attention + + # 增加par参数 + config.inner_config.parscale_n = 1 + config.inner_config.parscale_n_tokens = 20 + config.inner_config.parscale_attn_smooth = 0.01 + config.inner_config.parscale_layer = 0 + + model = BiEncoderParscaleVLModel.from_pretrained( + model_path, + config = config, + torch_dtype=torch.bfloat16, + low_cpu_mem_usage=True, + ignore_mismatched_sizes=True + ) + + if args.lora: + print("Loading lora ckpt.") + lora_config = LoraConfig.from_pretrained(args.lora_pth) + lora_config.task_type = TaskType.FEATURE_EXTRACTION + lora_model = PeftModel.from_pretrained(model, args.lora_pth, config=lora_config, is_trainable=False) + model = lora_model.merge_and_unload() + + model.eval() + model.requires_grad_(False) + + # processor is not changed so we still load from the original model repo + base_model_type = config.inner_config.model_type + tokenizer = TOKENIZER_MAPPING[base_model_type].from_pretrained(model_path, use_fast=True, split_special_tokens=False, padding_side="right", trust_remote_code=True) + processor = PROCESSOR_MAPPING[base_model_type].from_pretrained(model_path, trust_remote_code=True) + processor.tokenizer = tokenizer + processor.image_processor.image_aspect_ratio="square" + processor.image_processor.do_adaptive_crop=False + + accelerator = Accelerator(mixed_precision='bf16') + device = accelerator.device + is_main_process = accelerator.is_main_process + ## 数据集加载 + query_doc_dataset = TuwenTBStarsEvalDataset(args) + query_doc_collator = TuwenTBStarsDataCollator(tokenizer=tokenizer, processor=processor, image_type=args.image_type, query_text_require=args.query_text_require, doc_text_require=args.doc_text_require) + query_doc_dataloader = DataLoader(query_doc_dataset, batch_size=16, num_workers=4, shuffle=False, collate_fn=query_doc_collator, pin_memory=True) + ## 数据集加载 + def tensors_to_device(data, device, dtype=model.dtype): + for key in data.keys(): + if isinstance(data[key], torch.Tensor): + if 'pixel_values' in key: + data[key] = data[key].to(device).to(dtype) + else: + data[key] = data[key].to(device) + return data + + query_dic_all = {} + + out_dim = args.out_dim + + with torch.no_grad(): + model, query_doc_dataloader= accelerator.prepare(model, query_doc_dataloader) + + for query_batch, doc_batch, query_tfs, label_list, doc_tfs in tqdm(query_doc_dataloader): + doc_batch = tensors_to_device(doc_batch, device) + candidate_embed = model(**doc_batch) + b, dim = candidate_embed.shape + candidate_embed = candidate_embed.view(b, out_dim, dim // out_dim) # (batch_size, out_dim, n) + candidate_embed = candidate_embed.sum(dim=2) # sum over the grouped dimensions + candidate_embed = F.normalize(candidate_embed, p=2, dim=1) + candidate_embed = accelerator.gather_for_metrics(candidate_embed) + + query_batch = tensors_to_device(query_batch, device) + query_embed = model(**query_batch) + b, dim = query_embed.shape + query_embed = query_embed.view(b, out_dim, dim // out_dim) # (batch_size, out_dim, n) + query_embed = query_embed.sum(dim=2) # sum over the grouped dimensions + query_embed = F.normalize(query_embed, p=2, dim=1) + query_embed = accelerator.gather_for_metrics(query_embed) + + cos_sim = (query_embed * candidate_embed).sum(1).reshape(-1).tolist() # shape=bs + query_tfs = accelerate.utils.gather_object(query_tfs)[:len(cos_sim)] + doc_tfs = accelerate.utils.gather_object(doc_tfs)[:len(cos_sim)] + label_list = accelerate.utils.gather_object(label_list)[:len(cos_sim)] + + if is_main_process: + for i in range(len(query_tfs)): + if query_tfs[i] not in query_dic_all: + query_dic_all[query_tfs[i]] = {} + query_dic_all[query_tfs[i]]['label'] = [label_list[i]] + else: + query_dic_all[query_tfs[i]]['label'].append(label_list[i]) + + for i in range(len(query_tfs)): + if 'sim' not in query_dic_all[query_tfs[i]]: + query_dic_all[query_tfs[i]]['sim'] = [cos_sim[i]] + else: + query_dic_all[query_tfs[i]]['sim'].append(cos_sim[i]) + + for i in range(len(query_tfs)): + if 'doc_tfs' not in query_dic_all[query_tfs[i]]: + query_dic_all[query_tfs[i]]['doc_tfs'] = [doc_tfs[i]] + else: + query_dic_all[query_tfs[i]]['doc_tfs'].append(doc_tfs[i]) + + accelerator.wait_for_everyone() + + if is_main_process: + results_all_dict = tongkuan_score_print(query_dic_all, sim_weight = [0.2, 0.2, 0.2, 0.2, 0.2]) + if args.all_eval: + data = {os.path.basename(args.lora_pth): {"results": results_all_dict}} + with jsonlines.open(args.eval_json, mode='a') as writer: + writer.write(data) + save_json(f"/data/oss_bucket_0/peifeng/multi_vlm2vec/multi_vlm2vec_eval/eval_vis/tbstars_{args.train_data_type}_{args.test_data_type}_test_{os.path.basename(args.lora_pth)}.json", query_dic_all) + else: + save_json(f"/data/oss_bucket_0/peifeng/multi_vlm2vec/multi_vlm2vec_eval/eval_vis/tbstars_{args.train_data_type}_{args.test_data_type}_test.json", query_dic_all) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument('--tables', default="odps://pailitao_search_offline/tables/plt_lzy_rank_tuwen_zhaoxiangsi_test/ds=202606_test", type=str, help='ODPS input table names') + parser.add_argument('--max_lines', default=10000000, type=int, help='Limit the data length') + parser.add_argument('--model_max_length', type=int, default=512) + parser.add_argument('--model_id', type=str, default="/data/oss_bucket_0/peifeng/vlm2vec/models/tbstar/TBStars_VL_Ecom_EMB_3B/") + parser.add_argument('--inference_instruction', default="",type=str) + parser.add_argument('--image_type', default="both",type=str) + parser.add_argument('--emb_dim', default=3072,type=int) + parser.add_argument('--out_dim', default=512,type=int) + parser.add_argument('--query_text_require', type=str, default='True') + parser.add_argument('--doc_text_require', type=str, default='True') + parser.add_argument('--bidirectional_attention', type=str, default='True') + parser.add_argument('--lora', type=str, default='False') + parser.add_argument('--lora_pth', type=str, default='') + parser.add_argument('--train_data_type', type=str, default='') + parser.add_argument('--test_data_type', type=str, default='') + parser.add_argument('--eval_json', type=str, default='') + parser.add_argument('--all_eval', type=str, default='False') + args = parser.parse_args() + args.query_text_require = args.query_text_require.lower() == 'true' + args.doc_text_require = args.doc_text_require.lower() == 'true' + args.bidirectional_attention = args.bidirectional_attention.lower() == 'true' + args.lora = args.lora.lower() == 'true' + args.all_eval = args.all_eval.lower() == 'true' + if args.all_eval: + lora_root_path = args.lora_pth + args.eval_json = os.path.join(lora_root_path, f"eval_{args.test_data_type}.json") + checkpoint_dirs = [ + os.path.join(lora_root_path, d) + for d in os.listdir(lora_root_path) + if os.path.isdir(os.path.join(lora_root_path, d)) and re.match(r"checkpoint-\d+", d) + ] + checkpoint_dirs.sort(key=lambda x: int(re.search(r"checkpoint-(\d+)", x).group(1))) + for ckpt_dir in checkpoint_dirs: + args.lora_pth = ckpt_dir + eval(args) + else: + eval(args) \ No newline at end of file diff --git a/code/multi_vlm2vec_train/eval/eval_utils.py b/code/multi_vlm2vec_train/eval/eval_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b938fc469af37739fa641c59bf1331bc5a1eb19c --- /dev/null +++ b/code/multi_vlm2vec_train/eval/eval_utils.py @@ -0,0 +1,111 @@ +import sys +import os +import numpy as np +import torch + + +def get_topn_same_recall(score, labels, N, threshold = 0.0): + gt_num = list(labels).count(0) + hit = 0.0 + + for i in range(min(N, len(labels))): + if labels[i] == 0 and score[i] >= threshold: + hit += 1 + if gt_num == 0 or N == 0: + return 0.0 + + return hit / min(N, gt_num) + + + +def get_topn_hit_rate(labels, N): + """HR@N: Top-N中是否存在至少一个正样本(label==0),是则为1,否则为0""" + for i in range(min(N, len(labels))): + if labels[i] == 0: + return 1.0 + return 0.0 + + +def TopNHitRate(query_dic, TopN): + """计算所有query的平均HR@N""" + hr_sum = 0.0 + query_num = 0.0 + + for _, data in query_dic.items(): + query_score = np.array(data['score']) + query_label = np.array(data['label']) + + index_score = np.argsort(-query_score) + query_label_sort = query_label[index_score] + + if 0 in query_label: + hr_sum += get_topn_hit_rate(query_label_sort, TopN) + query_num += 1 + + if query_num == 0: + return 0.0 + return hr_sum / query_num + + +def TopNAcc(query_dic, TopN): + same_ap = 0.0 + same_query_num = 0.0 + + for _, data in query_dic.items(): + query_score = np.array(data['score']) + query_label = np.array(data['label']) + + index_score = np.argsort(-query_score) + query_score_sort = query_score[index_score] + query_label_sort = query_label[index_score] + + if 0 in query_label: + same_ap += get_topn_same_recall(query_score_sort, query_label_sort, TopN) + same_query_num += 1 + + if same_query_num == 0: + return 0.0 + return same_ap / same_query_num + + +def tongkuan_score_print(query_dic_all, sim_weight): + results_all = [] + results_all.append(['same_Top1','same_Top5','same_Top10', 'same_Top20','same_Top30','sim', 'HR@1', 'HR@5', 'HR@10', 'HR@20']) + + query_score_dic = {} + for query, value in query_dic_all.items(): + query_score_dic[query] = {} + query_score_dic[query]['score'] = value['sim'] + query_score_dic[query]['label'] = value['label'] + + # 基于上面的数据,去算相似率 + same_rate_Top1 = TopNAcc(query_score_dic, 1) + same_rate_Top5 = TopNAcc(query_score_dic, 5) + same_rate_Top10 = TopNAcc(query_score_dic, 10) + same_rate_Top20 = TopNAcc(query_score_dic, 20) + same_rate_Top30 = TopNAcc(query_score_dic, 30) + sim = sim_weight[0] * same_rate_Top1 + sim_weight[1] * same_rate_Top5 + sim_weight[2] * same_rate_Top10 + sim_weight[3] * same_rate_Top20 + sim_weight[4] * same_rate_Top30 + + hr_1 = TopNHitRate(query_score_dic, 1) + hr_5 = TopNHitRate(query_score_dic, 5) + hr_10 = TopNHitRate(query_score_dic, 10) + hr_20 = TopNHitRate(query_score_dic, 20) + + print ('##### wo margin #####') + print ('same_rate_Top1: ', same_rate_Top1) + print ('same_rate_Top5: ', same_rate_Top5) + print ('same_rate_Top10: ', same_rate_Top10) + print ('same_rate_Top20: ', same_rate_Top20) + print ('same_rate_Top30: ', same_rate_Top30) + print ('sim: ', sim) + print ('HR@1: ', hr_1) + print ('HR@5: ', hr_5) + print ('HR@10: ', hr_10) + print ('HR@20: ', hr_20) + + results_all.append([same_rate_Top1, same_rate_Top5, same_rate_Top10, same_rate_Top20, same_rate_Top30, sim, hr_1, hr_5, hr_10, hr_20]) + + results_all_dict = {} + for i in range(len(results_all[0])): + results_all_dict[results_all[0][i]] = results_all[1][i] + return results_all_dict \ No newline at end of file diff --git a/code/multi_vlm2vec_train/eval/merge_tbstars.py b/code/multi_vlm2vec_train/eval/merge_tbstars.py new file mode 100644 index 0000000000000000000000000000000000000000..2edc3777aa22288463c7d246049920d59fe0e3fd --- /dev/null +++ b/code/multi_vlm2vec_train/eval/merge_tbstars.py @@ -0,0 +1,69 @@ +## 进行merge,尝试tbstars + +import os +from transformers import AutoProcessor +import sys +current_file_path = os.path.dirname(os.path.abspath(__file__)) +module_path = os.path.join(current_file_path, "../") +sys.path.append(module_path) + +import torch +import argparse +import torch.nn.functional as F +from accelerate import Accelerator +import accelerate +from peft import LoraConfig, get_peft_model, PeftModel, TaskType +import shutil + +from models.tbstars_ecom_emb.src.model.biencoder_parscale_vl_dynamic.configuration_biencoder_parscale_vl import BiEncoderParscaleVLConfig +from models.tbstars_ecom_emb.src.model.biencoder_parscale_vl_dynamic.modeling_biencoder_parscale_vl import BiEncoderParscaleVLModel +from models.tbstars_ecom_emb.src.model.base_models import PROCESSOR_MAPPING, TOKENIZER_MAPPING + +def eval(args): + ## 模型加载 + model_path = args.model_id + config = BiEncoderParscaleVLConfig.from_pretrained(model_path) + config.emb_dim = 3072 + config.use_mrl = False + config.bidirectional_attention = True + config.inner_config.bidirectional_attention = True + + config.inner_config.parscale_n = 1 + config.inner_config.parscale_n_tokens = 20 + config.inner_config.parscale_attn_smooth = 0.01 + config.inner_config.parscale_layer = 0 + + model = BiEncoderParscaleVLModel.from_pretrained( + model_path, + config = config, + torch_dtype=torch.bfloat16, + low_cpu_mem_usage=True, + ignore_mismatched_sizes=True + ) + + print("Loading lora ckpt.") + lora_config = LoraConfig.from_pretrained(args.lora_pth) + lora_config.task_type = TaskType.FEATURE_EXTRACTION + lora_model = PeftModel.from_pretrained(model, args.lora_pth, config=lora_config, is_trainable=False) + merged_model = lora_model.merge_and_unload() + + # processor is not changed so we still load from the original model repo + base_model_type = config.inner_config.model_type + tokenizer = TOKENIZER_MAPPING[base_model_type].from_pretrained(model_path, use_fast=True, split_special_tokens=False, padding_side="right", trust_remote_code=True) + processor = PROCESSOR_MAPPING[base_model_type].from_pretrained(model_path, trust_remote_code=True) + processor.tokenizer = tokenizer + processor.image_processor.image_aspect_ratio="square" + processor.image_processor.do_adaptive_crop=False + + # merged_model.save_pretrained + merged_model.save_pretrained(args.save_path) + processor.save_pretrained(args.save_path) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description='') + parser.add_argument('--model_id', type=str, default="/data/oss_bucket_0/peifeng/vlm2vec/models/tbstar/TBStars_VL_Ecom_EMB_3B/") + parser.add_argument('--lora_pth', type=str, default="/data/oss_bucket_0/peifeng/multi_vlm2vec/multi_vlm2vec_train/test_train_2607_merge1/train_tbstars_infonce_merge1_gpus_16_vision_True_projector_True_llm_True_lora_True_batch_4_epoch_20/checkpoint-20000/") + parser.add_argument('--save_path', type=str, default="/data/oss_bucket_0/peifeng/multi_vlm2vec/multi_vlm2emb/tbstars_multi_vlm2emb/") + args = parser.parse_args() + eval(args) \ No newline at end of file diff --git a/code/multi_vlm2vec_train/loaders/.DS_Store b/code/multi_vlm2vec_train/loaders/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5008ddfcf53c02e82d7eee2e57c38e5672ef89f6 Binary files /dev/null and b/code/multi_vlm2vec_train/loaders/.DS_Store differ diff --git a/code/multi_vlm2vec_train/loaders/__init__.py b/code/multi_vlm2vec_train/loaders/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2d38cb979a22ca96b715cad4ac65335baed1aea6 --- /dev/null +++ b/code/multi_vlm2vec_train/loaders/__init__.py @@ -0,0 +1,17 @@ +LOADERS = {} +## 用来注册 +def register_loader(name): + def register_loader_cls(cls): + if name in LOADERS: + return LOADERS[name] + LOADERS[name] = cls + return cls + return register_loader_cls + +try: + from .tbstars_ecom_emb import TBStars_ecom_emb_ModelLoader +except ImportError as e: + import warnings + warnings.warn(f"tbstars_ecom_emb loader unavailable (skipped): {e}") +## 增加proj的loader +from .proj_models import load_mlp_projector, load_add_projector \ No newline at end of file diff --git a/code/multi_vlm2vec_train/loaders/__pycache__/__init__.cpython-313.pyc b/code/multi_vlm2vec_train/loaders/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c7044c185c08aba838126a372b35c1003e4e969 Binary files /dev/null and b/code/multi_vlm2vec_train/loaders/__pycache__/__init__.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/loaders/__pycache__/base.cpython-313.pyc b/code/multi_vlm2vec_train/loaders/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a39448d4cd8e88a9aae84d3fa1a34a66cd0e2ca Binary files /dev/null and b/code/multi_vlm2vec_train/loaders/__pycache__/base.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/loaders/__pycache__/proj_models.cpython-313.pyc b/code/multi_vlm2vec_train/loaders/__pycache__/proj_models.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f17c89ab4c84f690d5a703950e7e3500386ea2fd Binary files /dev/null and b/code/multi_vlm2vec_train/loaders/__pycache__/proj_models.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/loaders/__pycache__/tbstars_ecom_emb.cpython-313.pyc b/code/multi_vlm2vec_train/loaders/__pycache__/tbstars_ecom_emb.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e35bb17aca4b0d8fd812eeb938c11629492f3ed Binary files /dev/null and b/code/multi_vlm2vec_train/loaders/__pycache__/tbstars_ecom_emb.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/loaders/base.py b/code/multi_vlm2vec_train/loaders/base.py new file mode 100644 index 0000000000000000000000000000000000000000..07a371f19e12adcb0ddbb3e27fb60e15f629c893 --- /dev/null +++ b/code/multi_vlm2vec_train/loaders/base.py @@ -0,0 +1,31 @@ +from abc import ABC, abstractmethod +from typing import Dict, Tuple, Union, Optional + +import torch +from transformers import PreTrainedModel, PreTrainedTokenizer, AutoProcessor, BitsAndBytesConfig + + +class BaseModelLoader(ABC): + def __init__( + self, + model_hf_path: str, + model_local_path: str, + compute_dtype: torch.dtype, + bnb_config: Optional[BitsAndBytesConfig] = None, + use_flash_attn: bool = False, + device_map: Optional[Union[Dict, str]] = None, + ) -> None: + self.model_hf_path = model_hf_path + self.model_local_path = model_local_path + self.loading_kwargs = dict( + torch_dtype=compute_dtype, + quantization_config=bnb_config, + device_map=device_map, + ) + if use_flash_attn: + self.loading_kwargs["attn_implementation"] = "flash_attention_2" + + @abstractmethod + def load(self, load_model: bool = True) -> Tuple[ + PreTrainedModel, Union[None, PreTrainedTokenizer], Union[None, AutoProcessor] + ]: ... \ No newline at end of file diff --git a/code/multi_vlm2vec_train/loaders/proj_models.py b/code/multi_vlm2vec_train/loaders/proj_models.py new file mode 100644 index 0000000000000000000000000000000000000000..ee5c92ed3e7fc0c4e853e9da902b0e0c8e4b22cc --- /dev/null +++ b/code/multi_vlm2vec_train/loaders/proj_models.py @@ -0,0 +1,78 @@ +## TODO: 实现一个映射层,将输出得到的特征维度映射到embed空间当中 +from models.proj_models import LLM2EmbedProjector, LLM2EmbedAddProjector +from typing import Optional +from logger import get_logger +from transformers.modeling_utils import load_state_dict +from transformers.trainer_utils import get_last_checkpoint +import os +from . import register_loader +logger = get_logger(__name__) + + +@register_loader("load_mlp_projector") +def load_mlp_projector( + fc_args: "FCArguments", + in_dim = 3074, + is_trainable: Optional[bool] = False, + resume_from_checkpoint=None, + output_dir=None +): + if fc_args.stage == "classify": + mlp_model = LLM2EmbedProjector( + in_dim = in_dim, + out_dim = fc_args.embed_dim, + fp16=False + ) + + if resume_from_checkpoint: + if os.path.exists(output_dir): + new_model_name_or_path_proj = get_last_checkpoint(output_dir) + logger.info("start to load pfc not from: {}, but from {}".format( + fc_args.model_name_or_path_proj, new_model_name_or_path_proj + )) + else: + new_model_name_or_path_proj = None + logger.info('not exists (output_dir) for pfc {}, load pfc from {}'.format(output_dir, fc_args.model_name_or_path_proj)) + + if new_model_name_or_path_proj: + logger.info("(resume process) start to load pfc from: {}".format(new_model_name_or_path_proj)) + mlp_model.maybe_load_state_dict_from_path(new_model_name_or_path_proj) + else: + logger.info("(resume failed) still start to load pfc from: {}".format(fc_args.model_name_or_path_proj)) + mlp_model.maybe_load_state_dict_from_path(fc_args.model_name_or_path_proj) + else: + logger.info("start to load pfc from: {}".format(fc_args.model_name_or_path_proj)) + mlp_model.maybe_load_state_dict_from_path(fc_args.model_name_or_path_proj) + + + if is_trainable: + mlp_model.train() + else: + mlp_model.eval() + else: + mlp_model = None + return mlp_model + + +@register_loader("load_add_projector") +def load_add_projector( + fc_args: "FCArguments", + in_dim = 3074, + is_trainable: Optional[bool] = False, + resume_from_checkpoint=None, + output_dir=None +): + if fc_args.stage == "classify": + mlp_model = LLM2EmbedAddProjector( + in_dim = in_dim, + out_dim = fc_args.embed_dim, + fp16=False + ) + logger.info("No weights for LLM2EmbedAddProjector") + if is_trainable: + mlp_model.train() + else: + mlp_model.eval() + else: + mlp_model = None + return mlp_model \ No newline at end of file diff --git a/code/multi_vlm2vec_train/loaders/tbstars_ecom_emb.py b/code/multi_vlm2vec_train/loaders/tbstars_ecom_emb.py new file mode 100644 index 0000000000000000000000000000000000000000..fbc92eceac46a1846d410eaecb9ced8b14dc1d37 --- /dev/null +++ b/code/multi_vlm2vec_train/loaders/tbstars_ecom_emb.py @@ -0,0 +1,76 @@ +from typing import Tuple +import torch +from torch import nn + +from transformers import AutoTokenizer, AutoProcessor, AutoModelForCausalLM + +from . import register_loader +from .base import BaseModelLoader + +from models.tbstars_ecom_emb.src.model.base_models import PROCESSOR_MAPPING, TOKENIZER_MAPPING +from peft import LoraConfig, get_peft_model, PeftModel + +from models.tbstars_ecom_emb.src.model.biencoder_parscale_vl_dynamic.configuration_biencoder_parscale_vl import BiEncoderParscaleVLConfig +from models.tbstars_ecom_emb.src.model.biencoder_parscale_vl_dynamic.modeling_biencoder_parscale_vl import BiEncoderParscaleVLModel + +from openlm_hub import repo_download + + +## 输出的token基于图像进行生成结果 +@register_loader("tbstars_ecom_emb_3b") +class TBStars_ecom_emb_ModelLoader(BaseModelLoader): + def load(self, args=None, load_model: bool = True, emb_dim=512) -> Tuple[AutoModelForCausalLM, AutoTokenizer, None]: + # model_path = repo_download(self.model_local_path, use_subprocess=True, local_dir="/data/oss_bucket_0/guijiang/hf_downloads/models/TBStars_VL_Ecom_EMB_3B") + model_path = self.model_local_path + config = BiEncoderParscaleVLConfig.from_pretrained(model_path) + config.emb_dim = emb_dim + + # 增加par参数 + config.inner_config.parscale_n = args.parscale_n + config.inner_config.parscale_n_tokens = args.parscale_n_tokens + config.inner_config.parscale_attn_smooth = args.parscale_attn_smooth + config.inner_config.parscale_layer = args.parscale_layer + + # qformer改变token数量,从144改到16 + config.inner_config.vision_projector_config.perceiver_num_heads = args.perceiver_num_heads + config.inner_config.vision_projector_config.perceiver_num_queries = args.perceiver_num_queries + + base_model_type = config.inner_config.model_type + + if load_model: + model = BiEncoderParscaleVLModel.from_pretrained( + model_path, + config = config, + torch_dtype = torch.bfloat16, + ignore_mismatched_sizes=True + ) + + # 遍历所有模型参数 + for name, param in model.named_parameters(): + # 检查参数名是否匹配我们想要初始化的新参数 + if 'prefix_k' in name or 'prefix_v' in name: + print(f"Initializing {name} with std=0.02") + # 使用均值为0,标准差为0.02的正态分布进行初始化 + nn.init.normal_(param, mean=0.0, std=0.02) + # 你也可以在这里为 aggregate_layer 做同样的操作,如果需要的话 + elif 'aggregate_layer' in name: + # 比如,给权重用 normal_,给偏置用 zeros_ + if 'weight' in name: + nn.init.normal_(param, mean=0.0, std=0.02) + elif 'bias' in name: + nn.init.zeros_(param) + + if args.lora_load: + print(f"Loading lora ckpt from {args.lora_pth}") + lora_config = LoraConfig.from_pretrained(args.lora_pth) + lora_model = PeftModel.from_pretrained(model, args.lora_pth, config=lora_config) + model = lora_model.merge_and_unload() + + + tokenizer = TOKENIZER_MAPPING[base_model_type].from_pretrained(model_path, use_fast=True, split_special_tokens=False, padding_side="right", trust_remote_code=True) + processor = PROCESSOR_MAPPING[base_model_type].from_pretrained(model_path, trust_remote_code=True) + processor.tokenizer = tokenizer + processor.image_processor.image_aspect_ratio="square" + processor.image_processor.do_adaptive_crop=False + processor.image_processor.perceiver_num_queries = args.perceiver_num_queries + return model, tokenizer, processor \ No newline at end of file diff --git a/code/multi_vlm2vec_train/logger.py b/code/multi_vlm2vec_train/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..bb270776b3e2d473f84e4ad3ae9fa5465c022f55 --- /dev/null +++ b/code/multi_vlm2vec_train/logger.py @@ -0,0 +1,48 @@ +import logging +import sys + + +class LoggerHandler(logging.Handler): + r""" + Logger handler used in Web UI. + """ + + def __init__(self): + super().__init__() + self.log = "" + + def reset(self): + self.log = "" + + def emit(self, record): + if record.name == "httpx": + return + log_entry = self.format(record) + self.log += log_entry + self.log += "\n\n" + + +def get_logger(name: str) -> logging.Logger: + r""" + Gets a standard logger with a stream hander to stdout. + """ + formatter = logging.Formatter( + fmt="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S" + ) + handler = logging.StreamHandler(sys.stdout) + handler.setFormatter(formatter) + + logger = logging.getLogger(name) + logger.setLevel(logging.INFO) + logger.addHandler(handler) + + return logger + + +def reset_logging() -> None: + r""" + Removes basic config of root logger. (unused in script) + """ + root = logging.getLogger() + list(map(root.removeHandler, root.handlers)) + list(map(root.removeFilter, root.filters)) diff --git a/code/multi_vlm2vec_train/models/.DS_Store b/code/multi_vlm2vec_train/models/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..7c64530292f0dade919eecd851f31df2eb6409e7 Binary files /dev/null and b/code/multi_vlm2vec_train/models/.DS_Store differ diff --git a/code/multi_vlm2vec_train/models/__pycache__/proj_models.cpython-313.pyc b/code/multi_vlm2vec_train/models/__pycache__/proj_models.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d169520825ca70243f61a3be548f0131efecaf7 Binary files /dev/null and b/code/multi_vlm2vec_train/models/__pycache__/proj_models.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/models/__pycache__/qwen3_vl_embedding.cpython-310.pyc b/code/multi_vlm2vec_train/models/__pycache__/qwen3_vl_embedding.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3dec0af89d8ec434b5779b6551918d2b1e1fa12d Binary files /dev/null and b/code/multi_vlm2vec_train/models/__pycache__/qwen3_vl_embedding.cpython-310.pyc differ diff --git a/code/multi_vlm2vec_train/models/__pycache__/qwen3_vl_embedding.cpython-313.pyc b/code/multi_vlm2vec_train/models/__pycache__/qwen3_vl_embedding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..119f2e6ccc3c57dc6eb554fa7af3eeb75d6f0a29 Binary files /dev/null and b/code/multi_vlm2vec_train/models/__pycache__/qwen3_vl_embedding.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/models/proj_models.py b/code/multi_vlm2vec_train/models/proj_models.py new file mode 100644 index 0000000000000000000000000000000000000000..f2a3e154eb4f375ce9d4573b50ed6eac35e092ef --- /dev/null +++ b/code/multi_vlm2vec_train/models/proj_models.py @@ -0,0 +1,98 @@ +## TODO: MLP model,用来降低维度 + +import torch.nn as nn +import torch +import warnings +import math +import os + +MLP_NAME = "mlp_model.pt" +MLP_OPTIMIZER_NAME = "mlp_optimizer.pt" +MLP_SCHEDULER_NAME = "mlp_scheduler.pt" + +def _no_grad_trunc_normal_(tensor, mean, std, a, b): + # Cut & paste from PyTorch official master until it's in a few official releases - RW + # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf + def norm_cdf(x): + # Computes standard normal cumulative distribution function + return (1. + math.erf(x / math.sqrt(2.))) / 2. + + if (mean < a - 2 * std) or (mean > b + 2 * std): + warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. " + "The distribution of values may be incorrect.", + stacklevel=2) + + with torch.no_grad(): + # Values are generated by using a truncated uniform distribution and + # then using the inverse CDF for the normal distribution. + # Get upper and lower cdf values + l = norm_cdf((a - mean) / std) + u = norm_cdf((b - mean) / std) + + # Uniformly fill tensor with values from [l, u], then translate to + # [2l-1, 2u-1]. + tensor.uniform_(2 * l - 1, 2 * u - 1) + + # Use inverse cdf transform for normal distribution to get truncated + # standard normal + tensor.erfinv_() + + # Transform to proper mean, std + tensor.mul_(std * math.sqrt(2.)) + tensor.add_(mean) + + # Clamp to ensure it's in the proper range + tensor.clamp_(min=a, max=b) + return tensor + +def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.): + return _no_grad_trunc_normal_(tensor, mean, std, a, b) + +class LLM2EmbedProjector(nn.Module): + def __init__(self, in_dim, out_dim, fp16=False): + super().__init__() + self.fp16 = fp16 + self.mlp1 = nn.Sequential( + nn.Linear(in_dim, out_dim), + ) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + + def forward(self, x): + with torch.amp.autocast(device_type='cuda', enabled=self.fp16): + x = self.mlp1(x) + x = nn.functional.normalize(x, dim=-1, p=2) + return x + + def maybe_load_state_dict_from_path(self, ckpt_dir): + state_dict = None + ckpt_file = os.path.join(ckpt_dir, MLP_NAME) + if os.path.exists(ckpt_file): + state_dict = torch.load(ckpt_file, map_location='cpu') + if state_dict: + self.load_state_dict(state_dict) + +class LLM2EmbedAddProjector(nn.Module): + def __init__(self, in_dim, out_dim, fp16=False): + super().__init__() + self.fp16 = fp16 + assert in_dim % out_dim == 0, "in_dim must be divisible by out_dim" + self.out_dim = out_dim + self.in_dim = in_dim + self.n = in_dim // out_dim + + def forward(self, x): + # x shape: (batch_size, in_dim) + batch_size = x.size(0) + x_reshaped = x.view(batch_size, self.out_dim, self.n) # (batch_size, out_dim, n) + with torch.amp.autocast(device_type='cuda', enabled=self.fp16): + output = x_reshaped.sum(dim=2) # sum over the grouped dimensions + return output # shape: (batch_size, out_dim) + + def maybe_load_state_dict_from_path(self, ckpt_dir): + print("No weights for LLM2EmbedAddProjector") + diff --git a/code/multi_vlm2vec_train/models/qwen3_vl_embedding.py b/code/multi_vlm2vec_train/models/qwen3_vl_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..36d45865735be96a1278a21c132ff640e2ae68ca --- /dev/null +++ b/code/multi_vlm2vec_train/models/qwen3_vl_embedding.py @@ -0,0 +1,337 @@ +import torch +import torch.nn.functional as F +import unicodedata +import numpy as np +import logging + +from PIL import Image +from dataclasses import dataclass +from typing import Optional, List, Union, Dict, Any +from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLPreTrainedModel, Qwen3VLModel, Qwen3VLConfig +from transformers.models.qwen3_vl.processing_qwen3_vl import Qwen3VLProcessor +from transformers.modeling_outputs import ModelOutput +from transformers.processing_utils import Unpack +from transformers.utils import TransformersKwargs +from transformers.cache_utils import Cache +from transformers.utils.generic import check_model_inputs +from qwen_vl_utils.vision_process import process_vision_info + +logger = logging.getLogger(__name__) + +# Constants for configuration +MAX_LENGTH = 8192 +IMAGE_BASE_FACTOR = 16 +IMAGE_FACTOR = IMAGE_BASE_FACTOR * 2 +MIN_PIXELS = 4 * IMAGE_FACTOR * IMAGE_FACTOR +MAX_PIXELS = 1800 * IMAGE_FACTOR * IMAGE_FACTOR +FPS = 1 +MAX_FRAMES = 64 +FRAME_MAX_PIXELS = 768 * IMAGE_FACTOR * IMAGE_FACTOR +MAX_TOTAL_PIXELS = 10 * FRAME_MAX_PIXELS +PAD_TOKEN = "<|endoftext|>" + +# Define output structure for embeddings +@dataclass +class Qwen3VLForEmbeddingOutput(ModelOutput): + last_hidden_state: Optional[torch.FloatTensor] = None + attention_mask: Optional[torch.Tensor] = None + +# Define model class to compute embeddings +class Qwen3VLForEmbedding(Qwen3VLPreTrainedModel): + _checkpoint_conversion_mapping = {} + accepts_loss_kwargs = False + config: Qwen3VLConfig + + def __init__(self, config): + super().__init__(config) + self.model = Qwen3VLModel(config) + self.post_init() + + def get_input_embeddings(self): + return self.model.get_input_embeddings() + + def set_input_embeddings(self, value): + self.model.set_input_embeddings(value) + + def set_decoder(self, decoder): + self.model.set_decoder(decoder) + + def get_decoder(self): + return self.model.get_decoder() + + # Extract video features from model + def get_video_features(self, pixel_values_videos: torch.FloatTensor, + video_grid_thw: Optional[torch.LongTensor] = None): + return self.model.get_video_features(pixel_values_videos, video_grid_thw) + + # Extract image features from model + def get_image_features(self, pixel_values: torch.FloatTensor, + image_grid_thw: Optional[torch.LongTensor] = None): + return self.model.get_image_features(pixel_values, image_grid_thw) + + # Make modules accessible through properties + @property + def language_model(self): + return self.model.language_model + + @property + def visual(self): + return self.model.visual + + # Forward pass through model with input parameters + # @check_model_inputs + def forward(self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[Cache] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + pixel_values: Optional[torch.Tensor] = None, + pixel_values_videos: Optional[torch.FloatTensor] = None, + image_grid_thw: Optional[torch.LongTensor] = None, + video_grid_thw: Optional[torch.LongTensor] = None, + cache_position: Optional[torch.LongTensor] = None, + logits_to_keep: Union[int, torch.Tensor] = 0, + **kwargs: Unpack[TransformersKwargs], + ) -> Union[tuple, Qwen3VLForEmbeddingOutput]: + # Pass inputs through the model + outputs = self.model( + input_ids=input_ids, + pixel_values=pixel_values, + pixel_values_videos=pixel_values_videos, + image_grid_thw=image_grid_thw, + video_grid_thw=video_grid_thw, + position_ids=position_ids, + attention_mask=attention_mask, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + cache_position=cache_position, + **kwargs, + ) + # Return the model output + return Qwen3VLForEmbeddingOutput( + last_hidden_state=outputs.last_hidden_state, + attention_mask=attention_mask, + ) + +def sample_frames(frames: List[Union[str, Image.Image]], num_segments: int, max_segments: int) -> List[str]: + duration = len(frames) + frame_id_array = np.linspace(0, duration - 1, num_segments, dtype=int) + frame_id_list = frame_id_array.tolist() + last_frame_id = frame_id_list[-1] + + # Create a list of sampled frames + sampled_frames = [] + for frame_idx in frame_id_list: + try: + sampled_frames.append(frames[frame_idx]) + except: + break + # Ensure the sampled list meets the required segment count + while len(sampled_frames) < num_segments: + sampled_frames.append(frames[last_frame_id]) + return sampled_frames[:max_segments] + +# Define embedder class for processing inputs and generating embeddings +class Qwen3VLEmbedder(): + def __init__( + self, + model_name_or_path: str, + max_length: int = MAX_LENGTH, + min_pixels: int = MIN_PIXELS, + max_pixels: int = MAX_PIXELS, + total_pixels: int = MAX_TOTAL_PIXELS, + fps: float = FPS, + num_frames: int = MAX_FRAMES, + max_frames: int = MAX_FRAMES, + default_instruction: str = "Represent the user's input.", + **kwargs + ): + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + self.max_length = max_length + self.min_pixels = min_pixels + self.max_pixels = max_pixels + self.total_pixels = total_pixels + self.fps = fps + self.num_frames = num_frames + self.max_frames = max_frames + + self.default_instruction = default_instruction + + self.model = Qwen3VLForEmbedding.from_pretrained( + model_name_or_path, trust_remote_code=True, **kwargs + ).to(device) + self.processor = Qwen3VLProcessor.from_pretrained( + model_name_or_path, padding_side='right' + ) + self.model.eval() + + @torch.no_grad() + def forward(self, inputs: Dict[str, Any]) -> Dict[str, torch.Tensor]: + outputs = self.model(**inputs) + return { + 'last_hidden_state': outputs.last_hidden_state, + 'attention_mask': inputs.get('attention_mask') + } + + # Truncate token sequence to a specified max length + def _truncate_tokens(self, token_ids: List[int], max_length: int) -> List[int]: + if len(token_ids) <= max_length: + return token_ids + + special_token_ids = set(self.processor.tokenizer.all_special_ids) + num_special = sum(1 for token_idx in token_ids if token_idx in special_token_ids) + num_non_special_to_keep = max_length - num_special + + final_token_ids = [] + non_special_kept_count = 0 + # Ensure retention of special tokens while truncating the rest + for token_idx in token_ids: + if token_idx in special_token_ids: + final_token_ids.append(token_idx) + elif non_special_kept_count < num_non_special_to_keep: + final_token_ids.append(token_idx) + non_special_kept_count += 1 + return final_token_ids + + # Format input based on provided text, image, video, and instruction + def format_model_input( + self, text: Optional[str] = None, + image: Optional[Union[str, Image.Image]] = None, + video: Optional[Union[str, List[Union[str, Image.Image]]]] = None, + instruction: Optional[str] = None, + fps: Optional[float] = None, + max_frames: Optional[int] = None + ) -> List[Dict]: + + # Ensure instruction ends with punctuation + if instruction: + instruction = instruction.strip() + if instruction and not unicodedata.category(instruction[-1]).startswith('P'): + instruction = instruction + '.' + + # Initialize conversation with system prompts + content = [] + conversation = [ + {"role": "system", "content": [{"type": "text", "text": instruction or self.default_instruction}]}, + {"role": "user", "content": content} + ] + + # Add text, image, or video content to conversation + if not text and not image and not video: + content.append({'type': 'text', 'text': "NULL"}) + return conversation + + if video: + video_content = None + video_kwargs = { 'total_pixels': self.total_pixels } + if isinstance(video, list): + video_content = video + if self.num_frames is not None or self.max_frames is not None: + video_content = sample_frames(video_content, self.num_frames, self.max_frames) + video_content = [ + ('file://' + ele if isinstance(ele, str) else ele) + for ele in video_content + ] + elif isinstance(video, str): + video_content = video if video.startswith(('http://', 'https://')) else 'file://' + video + video_kwargs = {'fps': fps or self.fps, 'max_frames': max_frames or self.max_frames,} + else: + raise TypeError(f"Unrecognized video type: {type(video)}") + + # Add video input details to content + if video_content: + content.append({ + 'type': 'video', 'video': video_content, + **video_kwargs + }) + + if image: + image_content = None + if isinstance(image, Image.Image): + image_content = image + elif isinstance(image, str): + image_content = image if image.startswith(('http', 'oss')) else 'file://' + image + else: + raise TypeError(f"Unrecognized image type: {type(image)}") + + # Add image input details to content + if image_content: + content.append({ + 'type': 'image', 'image': image_content, + "min_pixels": self.min_pixels, + "max_pixels": self.max_pixels + }) + + if text: + content.append({'type': 'text', 'text': text}) + + return conversation + + # Preprocess input conversations for model consumption + def _preprocess_inputs(self, conversations: List[List[Dict]]) -> Dict[str, torch.Tensor]: + text = self.processor.apply_chat_template( + conversations, add_generation_prompt=True, tokenize=False + ) + + try: + images, video_inputs, video_kwargs = process_vision_info( + conversations, image_patch_size=16, + return_video_metadata=True, return_video_kwargs=True + ) + except Exception as e: + logger.error(f"Error in processing vision info: {e}") + images = None + video_inputs = None + video_kwargs = {'do_sample_frames': False} + text = self.processor.apply_chat_template( + [{'role': 'user', 'content': [{'type': 'text', 'text': 'NULL'}]}], + add_generation_prompt=True, tokenize=False + ) + + if video_inputs is not None: + videos, video_metadata = zip(*video_inputs) + videos = list(videos) + video_metadata = list(video_metadata) + else: + videos, video_metadata = None, None + + inputs = self.processor( + text=text, images=images, videos=videos, video_metadata=video_metadata, truncation=True, + max_length=self.max_length, padding=True, do_resize=False, return_tensors='pt', + **video_kwargs + ) + return inputs + + # Pool the last hidden state by attention mask for embeddings + @staticmethod + def _pooling_last(hidden_state: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor: + flipped_tensor = attention_mask.flip(dims=[1]) + last_one_positions = flipped_tensor.argmax(dim=1) + col = attention_mask.shape[1] - last_one_positions - 1 + row = torch.arange(hidden_state.shape[0], device=hidden_state.device) + return hidden_state[row, col] + + # Process inputs to generate normalized embeddings + def process(self, inputs: List[Dict[str, Any]], normalize: bool = True) -> tuple: + conversations = [self.format_model_input( + text=ele.get('text'), + image=ele.get('image'), + video=ele.get('video'), + instruction=ele.get('instruction'), + fps=ele.get('fps'), + max_frames=ele.get('max_frames') + ) for ele in inputs] + + processed_inputs = self._preprocess_inputs(conversations) + processed_inputs = {k: v.to(self.model.device) for k, v in processed_inputs.items()} + + outputs = self.forward(processed_inputs) + embeddings = self._pooling_last(outputs['last_hidden_state'], outputs['attention_mask']) + + # Normalize the embeddings if specified + if normalize: + embeddings = F.normalize(embeddings, p=2, dim=-1) + + return embeddings \ No newline at end of file diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/.DS_Store b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..9a874b5768f336915163bb88cd434575b859f936 Binary files /dev/null and b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/.DS_Store differ diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/__init__.py b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/__pycache__/__init__.cpython-310.pyc b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5981d5c146c03ce0b1ca5e06005562bbdbae68b Binary files /dev/null and b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/__pycache__/__init__.cpython-310.pyc differ diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/__pycache__/__init__.cpython-313.pyc b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2197f6fdb55725fa822f0c4ee18944298252ef1b Binary files /dev/null and b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/__pycache__/__init__.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/.DS_Store b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..aafe83cc3ec319d950e192d0a8b87b575319d663 Binary files /dev/null and b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/.DS_Store differ diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__init__.py b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__pycache__/__init__.cpython-310.pyc b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a608199dd09337725a48d72e161ca1dd472c1fd Binary files /dev/null and b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__pycache__/__init__.cpython-310.pyc differ diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__pycache__/__init__.cpython-313.pyc b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88d93a9da02b60c0d7116d3246333dcae5ae1a23 Binary files /dev/null and b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__pycache__/__init__.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__pycache__/mm_plugin.cpython-310.pyc b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__pycache__/mm_plugin.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80a071cbe03eca77192c2b53794124516f6d0f18 Binary files /dev/null and b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__pycache__/mm_plugin.cpython-310.pyc differ diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__pycache__/mm_plugin.cpython-313.pyc b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__pycache__/mm_plugin.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b64f12e2c3c93601e3d861fb5bd99f435d54027 Binary files /dev/null and b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__pycache__/mm_plugin.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__pycache__/template_guijiang.cpython-310.pyc b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__pycache__/template_guijiang.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d8333e08dd9523cd2c7b5fac487f6bb7e17995f Binary files /dev/null and b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__pycache__/template_guijiang.cpython-310.pyc differ diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__pycache__/template_guijiang.cpython-313.pyc b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__pycache__/template_guijiang.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c617e3100c62090327d31fca0705c234f28566a4 Binary files /dev/null and b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/__pycache__/template_guijiang.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/collator.py b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/collator.py new file mode 100644 index 0000000000000000000000000000000000000000..4b9b10ca3821394b4314d4123235033df6119111 --- /dev/null +++ b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/collator.py @@ -0,0 +1,281 @@ +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Sequence, Tuple, Union +from transformers.tokenization_utils_base import PreTrainedTokenizerBase +from transformers.utils import PaddingStrategy +import torch + +if TYPE_CHECKING: + from .template import Template + + +@dataclass +class VLTrainDataCollatorForRetrieval: + def __init__(self, + tokenizer: PreTrainedTokenizerBase=None, + template: "Template"=None, + model: Optional[Any] = None, + padding: Union[bool, str, PaddingStrategy] = True, + max_length: Optional[int] = None, + pad_to_multiple_of: Optional[int] = None, + return_tensors: str = "pt", + ): + self.tokenizer = tokenizer + self.template = template + self.model = model + self.padding = padding + self.max_length = max_length + self.pad_to_multiple_of = pad_to_multiple_of + self.return_tensors = return_tensors + + def __call__(self, features): + if "pos_item_features" in features[0].keys(): + query_input_ids = [fea["query_features"]["input_ids"] for fea in features] + pos_item_input_ids = [fea["pos_item_features"]["input_ids"] for fea in features] + neg_item_input_ids = [fea["neg_item_features"]["input_ids"] for fea in features] + ids = [fea["id"] for fea in features] + + query_input_ids_max_len = max([t.shape[-1] for t in query_input_ids]) + 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] + query_input_ids = torch.cat(pad_query_input_ids, dim=0) + query_attention_mask = (query_input_ids != self.tokenizer.pad_token_id).to(torch.long) + + pos_item_input_ids_max_len = max([t.shape[-1] for t in pos_item_input_ids]) + pad_pos_item_input_ids = [torch.cat([t, torch.full((1, pos_item_input_ids_max_len-t.shape[-1]), self.tokenizer.pad_token_id, dtype=torch.long)], dim=-1) for t in pos_item_input_ids] + pos_item_input_ids = torch.cat(pad_pos_item_input_ids, dim=0) + pos_item_attention_mask = (pos_item_input_ids != self.tokenizer.pad_token_id).to(torch.long) + + neg_item_input_ids_max_len = max([t.shape[-1] for t in neg_item_input_ids]) + pad_neg_item_input_ids = [torch.cat([t, torch.full((1, neg_item_input_ids_max_len-t.shape[-1]), self.tokenizer.pad_token_id, dtype=torch.long)], dim=-1) for t in neg_item_input_ids] + neg_item_input_ids = torch.cat(pad_neg_item_input_ids, dim=0) + neg_item_attention_mask = (neg_item_input_ids != self.tokenizer.pad_token_id).to(torch.long) + + pos_mm_features = [ + { + "pixel_values": fea["pos_item_features"]["pixel_values"], + "crop_positions": fea["pos_item_features"]["crop_positions"], + } + for fea in features + ] + + pos_mm_features = self.template.mm_plugin.collate_mm_inputs(pos_mm_features) + pos_mm_features = {f"pos_item_{k}": v for k, v in pos_mm_features.items()} + + + neg_mm_features = [ + { + "pixel_values": fea["neg_item_features"]["pixel_values"], + "crop_positions": fea["neg_item_features"]["crop_positions"], + } + for fea in features + ] + + neg_mm_features = self.template.mm_plugin.collate_mm_inputs(neg_mm_features) + neg_mm_features = {f"neg_item_{k}": v for k, v in neg_mm_features.items()} + + if "pixel_values" in features[0]["query_features"].keys(): + query_mm_features = [ + { + "pixel_values": fea["query_features"]["pixel_values"], + "crop_positions": fea["query_features"]["crop_positions"], + } + for fea in features + ] + query_mm_features = self.template.mm_plugin.collate_mm_inputs(query_mm_features) + query_mm_features = {f"query_{k}": v for k, v in query_mm_features.items()} + + return { + "ids": ids, + "query_input_ids": query_input_ids, + "query_attention_mask": query_attention_mask, + "pos_item_input_ids": pos_item_input_ids, + "pos_item_attention_mask": pos_item_attention_mask, + "neg_item_input_ids": neg_item_input_ids, + "neg_item_attention_mask": neg_item_attention_mask, + **query_mm_features, + **pos_mm_features, + **neg_mm_features + } + + else: + return { + "ids": ids, + "query_input_ids": query_input_ids, + "query_attention_mask": query_attention_mask, + "pos_item_input_ids": pos_item_input_ids, + "pos_item_attention_mask": pos_item_attention_mask, + "neg_item_input_ids": neg_item_input_ids, + "neg_item_attention_mask": neg_item_attention_mask, + **pos_mm_features, + **neg_mm_features + } + + + else: + query_input_ids = [fea["query_features"]["input_ids"] for fea in features] + item_input_ids = [fea["item_features"]["input_ids"] for fea in features] + ids = [fea["id"] for fea in features] + + query_input_ids_max_len = max([t.shape[-1] for t in query_input_ids]) + 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] + query_input_ids = torch.cat(pad_query_input_ids, dim=0) + query_attention_mask = (query_input_ids != self.tokenizer.pad_token_id).to(torch.long) + + item_input_ids_max_len = max([t.shape[-1] for t in item_input_ids]) + pad_item_input_ids = [torch.cat([t, torch.full((1, item_input_ids_max_len-t.shape[-1]), self.tokenizer.pad_token_id, dtype=torch.long)], dim=-1) for t in item_input_ids] + item_input_ids = torch.cat(pad_item_input_ids, dim=0) + item_attention_mask = (item_input_ids != self.tokenizer.pad_token_id).to(torch.long) + + mm_features = [ + { + "pixel_values": fea["item_features"]["pixel_values"], + "crop_positions": fea["item_features"]["crop_positions"], + } + for fea in features + ] + + mm_features = self.template.mm_plugin.collate_mm_inputs(mm_features) + mm_features = {f"item_{k}": v for k, v in mm_features.items()} + + if "pixel_values" in features[0]["query_features"].keys(): + query_mm_features = [ + { + "pixel_values": fea["query_features"]["pixel_values"], + "crop_positions": fea["query_features"]["crop_positions"], + } + for fea in features + ] + query_mm_features = self.template.mm_plugin.collate_mm_inputs(query_mm_features) + query_mm_features = {f"query_{k}": v for k, v in query_mm_features.items()} + + return { + "ids": ids, + "query_input_ids": query_input_ids, + "query_attention_mask": query_attention_mask, + "item_input_ids": item_input_ids, + "item_attention_mask": item_attention_mask, + **query_mm_features, + **mm_features + } + + else: + return { + "ids": ids, + "query_input_ids": query_input_ids, + "query_attention_mask": query_attention_mask, + "item_input_ids": item_input_ids, + "item_attention_mask": item_attention_mask, + **mm_features + } + + + +@dataclass +class VLInferQueryDataCollatorForRetrieval: + def __init__(self, + template: "Template"=None, + tokenizer: PreTrainedTokenizerBase=None, + model: Optional[Any] = None, + padding: Union[bool, str, PaddingStrategy] = True, + max_length: Optional[int] = None, + pad_to_multiple_of: Optional[int] = None, + return_tensors: str = "pt" + ): + self.template = template + self.tokenizer = tokenizer + self.model = model + self.padding = padding + self.max_length = max_length + self.pad_to_multiple_of = pad_to_multiple_of + self.return_tensors = return_tensors + + def __call__(self, features): + query_input_ids = [fea["query_features"]["input_ids"] for fea in features] + + query_input_ids_max_len = max([t.shape[-1] for t in query_input_ids]) + 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] + query_input_ids = torch.cat(pad_query_input_ids, dim=0) + query_attention_mask = (query_input_ids != self.tokenizer.pad_token_id).to(torch.long) + + query_record_id = [fea["record_id"] for fea in features] + query_text = [fea["query_text"] for fea in features] + query_img = [fea["query_img"] for fea in features] + + if "pixel_values" in features[0]["query_features"].keys(): + mm_features = [ + { + "pixel_values": fea["query_features"]["pixel_values"], + "crop_positions": fea["query_features"]["crop_positions"], + } + for fea in features + ] + + mm_features = self.template.mm_plugin.collate_mm_inputs(mm_features) + mm_features = {f"query_{k}": v for k, v in mm_features.items()} + + return { + "query_record_id": query_record_id, + "query_text": query_text, + "query_img": query_img, + "query_input_ids": query_input_ids, + "query_attention_mask": query_attention_mask, + **mm_features + } + else: + return { + "query_record_id": query_record_id, + "query_text": query_text, + "query_img": query_img, + "query_input_ids": query_input_ids, + "query_attention_mask": query_attention_mask + } + +@dataclass +class VLInferItemDataCollatorForRetrieval: + def __init__(self, + template: "Template"=None, + tokenizer: PreTrainedTokenizerBase=None, + model: Optional[Any] = None, + padding: Union[bool, str, PaddingStrategy] = True, + max_length: Optional[int] = None, + pad_to_multiple_of: Optional[int] = None, + return_tensors: str = "pt" + ): + self.template = template + self.tokenizer = tokenizer + self.model = model + self.padding = padding + self.max_length = max_length + self.pad_to_multiple_of = pad_to_multiple_of + self.return_tensors = return_tensors + + def __call__(self, features): + item_input_ids = [fea["item_features"]["input_ids"] for fea in features] + # 只取第一张overall图 + item_record_id = [fea["record_id"] for fea in features] + item_text = [fea["item_text"] for fea in features] + item_img = [fea["item_img"] for fea in features] + + + item_input_ids_max_len = max([t.shape[-1] for t in item_input_ids]) + pad_item_input_ids = [torch.cat([t, torch.full((1, item_input_ids_max_len-t.shape[-1]), self.tokenizer.pad_token_id, dtype=torch.long)], dim=-1) for t in item_input_ids] + item_input_ids = torch.cat(pad_item_input_ids, dim=0) + item_attention_mask = (item_input_ids != self.tokenizer.pad_token_id).to(torch.long) + + mm_features = [ + { + "pixel_values": fea["item_features"]["pixel_values"], + "crop_positions": fea["item_features"]["crop_positions"], + } + for fea in features + ] + + mm_features = self.template.mm_plugin.collate_mm_inputs(mm_features) + mm_features = {f"item_{k}": v for k, v in mm_features.items()} + return { + "item_record_id": item_record_id, + "item_text": item_text, + "item_img": item_img, + "item_input_ids": item_input_ids, + "item_attention_mask": item_attention_mask, + **mm_features, + } diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/dataset.py b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..7dec57297f124e113ce69decbbdc5f5cd91e958e --- /dev/null +++ b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/dataset.py @@ -0,0 +1,431 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- +# Date: 2024/06/12 22:00:00 +# Author: Ziming Wang +import torch +import json +import os +import oss2 +import shutil +import threading +from concurrent.futures import ThreadPoolExecutor +import numpy as np +from PIL import Image +from io import BytesIO +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Tuple, Union, Sequence, Iterator, Any +from copy import deepcopy +from extras.logger import get_logger +from multimodal.models.tbstars_vlm import ( + CONVERSATION_TEMPLATES, + SeparatorStyle, + preprocess_plain, + preprocess_chatml, + preprocess_turing_v1, + DEFAULT_IMAGE_TOKEN +) +import ast +logger = get_logger(__name__) + + +class OmniPreprocessFunc(object): + def __init__( + self, + training_args: Any, + image_processor: Any, + model_max_length: int = 4096, + default_image_path: str = "./multimodal/data/handlers/default_image.jpg", + vocab_size: int = 64000, + ignore_index: int = -100, + image_token_index: int = -200, + tokenizer: Any = None, + ): + self.training_args = training_args + self.image_processor = image_processor + self.model_max_length = model_max_length + self.default_image_path = default_image_path + self.vocab_size = vocab_size + self.ignore_index = ignore_index + self.image_token_index = image_token_index + self.tokenizer = tokenizer + self.oss2_bucket = oss2.Bucket( + oss2.Auth(training_args.oss2_access_id, training_args.oss2_access_key), + endpoint=training_args.oss2_endpoint, + bucket_name=training_args.oss2_bucket_name + ) if training_args.oss2_access_id is not None else None + + def __call__(self, sample: Tuple[Union[bytes, str]]) -> Dict[str, Any]: + # 1. Parse data record from specific odps data format + sample = [item.decode("utf-8") if isinstance(item, bytes) else item for item in sample] + input_ids, token_ids, labels, targets, sequence_length, full_token_lengths, loss_token_lengths = [None] * 7 + # print(sample) + if self.training_args.data_format_version == "pretrain_packing": + record_id, num_images, oss_images = sample[0], int(sample[4]), sample[1] + token_ids = list(map(int, sample[2].split(","))) + targets = list(map(int, sample[3].split(","))) + assert all(_ < self.vocab_size for _ in token_ids), \ + "Token id index out of model vocab range, check the special token indexes while tokenized text data." + + elif self.training_args.data_format_version == "multitask_packing": + record_id, num_images, oss_images = sample[0], int(sample[4]), sample[3] + token_ids = list(map(int, sample[1].split(","))) + targets = list(map(int, sample[2].split(","))) + if getattr(self.training_args, "reweight_token_wise_loss", False): + full_token_lengths = list(map(int, sample[5].split(","))) + loss_token_lengths = list(map(int, sample[6].split(","))) + assert all(_ < self.vocab_size for _ in token_ids) and all(_ < self.vocab_size for _ in targets), \ + "Token id index out of model vocab range, check the special token indexes while tokenized text data." + + # elif self.training_args.data_format_version == "llava": + elif 'llava' in self.training_args.data_format_version: + # record_id, num_images, oss_images = sample[0], int(sample[3]), sample[1] # for old odps table tbstars_vlm_sft_dataset + record_id, num_images, oss_images = sample[0], int(sample[3]), sample[2] # for new odps table tbstars_vlm_sft_dataset_niesheng + has_image = True if num_images > 0 else False + + try: + #! Notice + if self.training_args.data_format_version == "llava_new_sft": + if 'multitask' in record_id: # data type is a dict, from multitask odps table + sources = deepcopy([e["conversations"] for e in [json.loads(sample[1])]]) + else: + ss = f'{sample[1]}' + ss_new = ast.literal_eval(ss) # data type is a list, directly saved conversations, collected by niesheng + sources = deepcopy([ss_new]) + else: + sources = deepcopy([e["conversations"] for e in [json.loads(sample[1])]]) + except Exception as e: + logger.info(f"Error for sample: {record_id}") + logger.info(f"Error in json.loads: {str(e)}") + logger.info(f"Sample details: {sample}") + raise NotImplementedError + + use_llava_image_style = False + # original llava only accept single image and always set this single image to the start of prompt, + # see https://github.com/haotian-liu/LLaVA/blob/806cfe03d8419a28276065bd923274dbb11b66e2/llava/train/train.py#L316 + if use_llava_image_style and has_image: + for source in sources: + for sentence in source: + if DEFAULT_IMAGE_TOKEN in sentence["value"]: + sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "").strip() + sentence["value"] = DEFAULT_IMAGE_TOKEN + "\n" + sentence["value"] + sentence["value"] = sentence["value"].strip() + conv_template = CONVERSATION_TEMPLATES[self.training_args.conversation_template].copy() + if conv_template.sep_style == SeparatorStyle.PLAIN: + text_inputs = preprocess_plain(sources, self.tokenizer, conv_template, use_llava_image_style) + elif conv_template.version == "turing_v1": + text_inputs = preprocess_turing_v1(sources, self.tokenizer, conv_template, has_image=has_image) + elif conv_template.version == "chatml": + try: + text_inputs = preprocess_chatml(sources, self.tokenizer, conv_template, has_image=has_image) + except Exception as e: + logger.info(f"Error for sample: {record_id}") + logger.info(f"Error in preprocess_chatml: {str(e)}") + raise NotImplementedError + + else: + raise NotImplementedError + input_ids = text_inputs["input_ids"][0] + labels = text_inputs["labels"][0] + + else: + raise NotImplementedError() + + # 2. process text inputs + assert token_ids is not None or input_ids is not None + inputs = _process_text( + input_ids=input_ids, + labels=labels, + token_ids=token_ids, + targets=targets, + sequence_length=sequence_length, + model_max_length=self.model_max_length, + training_args=self.training_args, + ignore_index=self.ignore_index, + image_token_index=self.image_token_index, + full_token_lengths=full_token_lengths, + loss_token_lengths=loss_token_lengths, + ) + + # 3. process vision inputs + oss_images = [_ for _ in oss_images.split(self.training_args.image_path_separator) if _] + cache_dir = os.path.join("/tmp/temp_oss_download", record_id) if self.oss2_bucket is not None else None + + error_info = f'rank: {int(os.getenv("RANK", "0"))} record_id: {record_id}, images: {oss_images}; labels{inputs["labels"]}' + + assert num_images == len(oss_images) or (num_images == 0 and len(oss_images) == 1), RuntimeError(error_info) + assert inputs["input_ids"].eq(self.image_token_index).sum() == num_images, RuntimeError(error_info) + + assert torch.sum(inputs["labels"][1:] != self.ignore_index) > 0, RuntimeError(error_info) #FIXME by niesheng on 1011 + # if torch.sum(inputs["labels"][1:] != self.ignore_index) == 0: + # print(f'Labels: {inputs["labels"]}') + # print(f'Input_ids: {inputs["input_ids"]}') + # RuntimeError(error_info) + + vision_inputs = _process_images( + self.image_processor, + num_images=num_images, + image_filepaths=oss_images, + image_aspect_ratio=self.training_args.image_aspect_ratio, + default_image_path=self.default_image_path, + image_folder=self.training_args.image_folder, + oss2_bucket=self.oss2_bucket, + cache_dir=cache_dir, + ) + inputs.update(vision_inputs) + + return inputs + + +def _process_text( + input_ids: torch.Tensor = None, + labels: torch.Tensor = None, + token_ids: List[int] = None, + targets: List[int] = None, + sequence_length: int = None, + model_max_length: int = 4096, + training_args: Any = None, + pad_token_id: int = 0, + ignore_index: int = -100, + image_token_index: int = -200, + full_token_lengths: List[int] = None, + loss_token_lengths: List[int] = None, +): + if input_ids is None: + assert token_ids is not None + if targets is None: + targets = [] + for token_id in token_ids: + target_id = ignore_index if token_id == image_token_index else token_id + targets.append(target_id) + + token_ids = np.asarray(token_ids, dtype=np.int64) + targets = np.asarray(targets, dtype=np.int64) + + if training_args is not None and training_args.add_modality_start_end: + assert training_args.soi_token_id is not None and training_args.eoi_token_id is not None + for token_id, target_id in zip(token_ids, targets): + if token_id in (training_args.soi_token_id, image_token_index, training_args.eoi_token_id): + assert target_id == ignore_index + + assert targets.shape == token_ids.shape + input_ids = torch.from_numpy(token_ids) + labels = torch.from_numpy(targets) + + if sequence_length is not None and sequence_length < model_max_length: + diff = model_max_length - sequence_length + pad1 = torch.full((diff,), pad_token_id, dtype=torch.long) + pad2 = torch.full((diff,), ignore_index, dtype=torch.long) + input_ids = torch.cat([input_ids, pad1], dim=-1) + labels = torch.cat([labels, pad2], dim=-1) + + input_ids = input_ids[:model_max_length] + labels = labels[:model_max_length] + attention_mask = input_ids.ne(pad_token_id) + + inputs = dict(input_ids=input_ids, attention_mask=attention_mask, labels=labels) + + if full_token_lengths is not None and loss_token_lengths is not None: + assert torch.sum(labels != ignore_index) == np.sum(loss_token_lengths).item() + assert training_args.micro_train_batch_size == 1, NotImplementedError() + if np.sum(full_token_lengths) < labels.shape[0]: + rest_labels = labels[np.sum(full_token_lengths):] + assert torch.all(rest_labels == ignore_index) + full_token_lengths.append(rest_labels.shape[0]) + loss_token_lengths.append(1) + + stable_factor = training_args.global_train_batch_size / training_args.reweight_global_batch_size \ + if training_args.reweight_global_batch_size is not None else 1. + loss_weight = [torch.full((f_,), 1.0 / l_) for f_, l_ in zip(full_token_lengths, loss_token_lengths)] + loss_weight = stable_factor * torch.cat(loss_weight, dim=0) + loss_weight[labels == ignore_index] = 0.0 + inputs["loss_weight"] = loss_weight + + return inputs + + +def _process_images( + image_processor, + num_images: int = 1, + image_filepaths: List[str] = None, + base64_images: bytes = None, + base64_ids: str = None, + image_aspect_ratio: str = "adaptive_crop", + default_image_path: str = "./multimodal/data/handlers/default_image.jpg", + image_folder: str = "/data/oss_bucket_0", + oss2_bucket: oss2.Bucket = None, + cache_dir: str = None, +): + images = [] + if num_images <= 0: + image_paths = [default_image_path] + images.append(Image.open(default_image_path).convert("RGB")) + + elif image_filepaths is not None and oss2_bucket is None: + image_paths = [os.path.join(image_folder, _) for _ in image_filepaths] + for image_path in image_paths: + try: + image = Image.open(image_path).convert("RGB") + except Exception as e: + logger.info(f'Image.open() exception for image path: {image_path}, exception = {str(e)}') + image = Image.open(default_image_path).convert("RGB") + images.append(image) + + elif image_filepaths is not None and oss2_bucket is not None: + def _oss2_load_remote_image(filepath_map): + remote_filepath, local_filepath = filepath_map + try: + oss2_bucket.get_object_to_file(remote_filepath, filename=local_filepath) + return remote_filepath, Image.open(local_filepath).convert("RGB") + except Exception as e: + logger.info(f'Image.open() exception for image path: {filepath_map}, exception = {str(e)}') + return default_image_path, Image.open(default_image_path).convert("RGB") + + assert cache_dir is not None + image_paths = image_filepaths + if not os.path.exists(cache_dir): + os.makedirs(cache_dir, exist_ok=True) + filepath_maps = [(p_, os.path.join(cache_dir, str(i_))) for i_, p_ in enumerate(image_filepaths)] + with ThreadPoolExecutor(max_workers=8) as executor: + image_maps = executor.map(_oss2_load_remote_image, filepath_maps) + images.extend([image_map[-1] for image_map in image_maps]) + logger.info(f"PID: {os.getpid()}, threading id: {threading.get_native_id()}, Delete cache_dir: {cache_dir}") + shutil.rmtree(cache_dir, ignore_errors=True) + + elif base64_images is not None: + image_paths = base64_ids + base64_bytes_images = base64_images.split(b'---mdl_ailake_image_split_flags---') + try: + assert len(base64_bytes_images) == num_images + for base64_image in base64_bytes_images: + try: + image = Image.open(BytesIO(base64_image)).convert("RGB") + images.append(image) + except Exception as e: + logger.info(f'Image.open() exception for image path: {image_paths}, exception = {str(e)}') + image = Image.open(default_image_path).convert("RGB") + images.append(image) + except Exception as e: + logger.info(f'Base64 image split exception for image path: {base64_ids}, exception = {str(e)}') + for _ in range(num_images): + image = Image.open(default_image_path).convert("RGB") + images.append(image) + else: + raise ValueError("You have to specify either image_filepath or image_base64") + + assert num_images <= 0 or len(image_paths) == len(images) == num_images + + if image_aspect_ratio == "NaViT": + pixel_values, patch_attention_masks = list(), list() + for image, image_path in zip(images, image_paths): + try: + processor_output = image_processor.preprocess([image], return_tensors="pt") + except Exception as e: + logger.info(f'Image processor exception for file: {image_path}, exception = {str(e)}') + image = Image.open(default_image_path).convert("RGB") + processor_output = image_processor.preprocess([image], return_tensors="pt") + pixel_values.append(processor_output["pixel_values"][0]) + patch_attention_masks.append(processor_output["patch_attention_masks"][0]) + + i_h_max, i_w_max = np.max(np.asarray([_.shape for _ in pixel_values]), axis=0)[1:] + pixel_values = [ + torch.nn.functional.pad(_, (0, i_w_max - _.shape[2], 0, i_h_max - _.shape[1]), "constant", 0) + for _ in pixel_values + ] + p_h_max, p_w_max = np.max(np.asarray([_.shape for _ in patch_attention_masks]), axis=0) + patch_attention_masks = [ + torch.nn.functional.pad(_, (0, p_w_max - _.shape[1], 0, p_h_max - _.shape[0]), "constant", 0) + for _ in patch_attention_masks + ] + images_processed = { + "images": torch.stack(pixel_values, dim=0), + "patch_attention_mask": torch.stack(patch_attention_masks, dim=0).bool() + } + + elif "adaptive_crop" in image_aspect_ratio: + pixel_values, crop_positions = list(), list() + for image, image_path in zip(images, image_paths): + try: + processor_output = image_processor.preprocess([image], return_tensors="pt") + except Exception as e: + logger.info(f'Image processor exception for file: {image_path}, exception = {str(e)}') + image = Image.open(default_image_path).convert("RGB") + processor_output = image_processor.preprocess([image], return_tensors="pt") + pixel_values.append(processor_output["pixel_values"][0]) + crop_positions.append(processor_output["crop_positions"][0]) + + pixel_values = [crop_img for img in pixel_values for crop_img in img] + crop_positions = [crop_poi for img in crop_positions for crop_poi in img] + images_processed = { + "images": torch.stack(pixel_values, dim=0), + "crop_positions": torch.stack(crop_positions, dim=0) + } + + else: + pixel_values = list() + for image, image_path in zip(images, image_paths): + try: + processor_output = image_processor.preprocess([image], return_tensors="pt") + except Exception as e: + logger.info(f'Image processor exception for file: {image_path}, exception = {str(e)}') + image = Image.open(default_image_path).convert("RGB") + processor_output = image_processor.preprocess([image], return_tensors="pt") + pixel_values.append(processor_output["pixel_values"][0]) + images_processed = {"images": torch.stack(pixel_values, dim=0)} + logger.info(f'images_processed[images].shape: {images_processed["images"].shape}') + + return images_processed + + +@dataclass +class DataCollatorForOmniSupervisedDataset(object): + """Collate examples for supervised fine-tuning.""" + model_max_length: int + pad_token_id: int = 0 + ignore_index: int = -100 + + def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]: + + input_ids = [_["input_ids"] for _ in instances] + labels = [_["labels"] for _ in instances] + input_ids = torch.nn.utils.rnn.pad_sequence(input_ids, batch_first=True, padding_value=self.pad_token_id) + labels = torch.nn.utils.rnn.pad_sequence(labels, batch_first=True, padding_value=self.ignore_index) + input_ids = input_ids[:, :self.model_max_length] + attention_mask = input_ids.ne(self.pad_token_id) + labels = labels[:, :self.model_max_length] + batch = dict(input_ids=input_ids, attention_mask=attention_mask, labels=labels) + + if "loss_weight" in instances[0]: + loss_weight = [_["loss_weight"] for _ in instances] + loss_weight = torch.nn.utils.rnn.pad_sequence(loss_weight, batch_first=True, padding_value=0.) + loss_weight = loss_weight[:, :self.model_max_length] + assert loss_weight.shape == labels.shape + batch["loss_weight"] = loss_weight + + if "images" in instances[0]: + images = [image for _ in instances for image in _["images"]] + if "crop_positions" in instances[0] and instances[0]["crop_positions"] is not None: + crop_positions = [crop_poi for _ in instances for crop_poi in _["crop_positions"]] + batch["images"] = torch.stack(images, dim=0) + batch["crop_positions"] = torch.stack(crop_positions, dim=0) + elif "patch_attention_mask" in instances[0] and instances[0]["patch_attention_mask"] is not None: + i_h_max, i_w_max = np.max(np.asarray([_.shape for _ in images]), axis=0)[1:] + images = [ + torch.nn.functional.pad(_, (0, i_w_max - _.shape[2], 0, i_h_max - _.shape[1]), "constant", 0) + for _ in images + ] + patch_attention_masks = [ + patch_attention_mask for _ in instances for patch_attention_mask in _["patch_attention_mask"] + ] + p_h_max, p_w_max = np.max(np.asarray([_.shape for _ in patch_attention_masks]), axis=0) + patch_attention_masks = [ + torch.nn.functional.pad(_, (0, p_w_max - _.shape[1], 0, p_h_max - _.shape[0]), "constant", 0) + for _ in patch_attention_masks + ] + batch["images"] = torch.stack(images, dim=0) + batch["patch_attention_mask"] = torch.stack(patch_attention_masks, dim=0).bool() + elif all(x is not None and x.shape == images[0].shape for x in images): + batch["images"] = torch.stack(images, dim=0) + else: + batch["images"] = images + + return batch diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/loader.py b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..1ab0b1afd849132be410da660ea26d30b5f5e504 --- /dev/null +++ b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/loader.py @@ -0,0 +1,40 @@ +import inspect +import os +from typing import TYPE_CHECKING, List, Literal, Union + +from datasets import concatenate_datasets, interleave_datasets, load_dataset, load_from_disk +from transformers import ProcessorMixin + +from extras.constants import FILEEXT2TYPE +from extras.logger import get_logger +from .preprocess import get_preprocess_func +from mdl.distribute_dataset import DistributeDataset + + +if TYPE_CHECKING: + from datasets import Dataset, IterableDataset + from transformers import Seq2SeqTrainingArguments + from transformers.tokenization_utils import PreTrainedTokenizer + from .template import Template + + from hparams import DataArguments, ModelArguments + +def get_ditribute_dataset( + template: "Template", + data_args: "DataArguments", + training_args: "Seq2SeqTrainingArguments", + stage: Literal["retrieval", "reranker", "retrieval_infer_query", "retrieval_infer_item", "retrieval_distill"], + num_threads: int=4 + ): + preprocess_func = get_preprocess_func( + template, data_args, stage + ) + dataset = DistributeDataset( + data_args.file_name, + cols=data_args.select_cols, + num_threads=num_threads, + capacity=512, # 一般设置为:256= List[List[int]]: + r""" + Gets paligemma token type ids for computing loss. + + Returns: + batch_token_type_ids: shape (batch_size, sequence_length) + """ + batch_token_type_ids = [] + for imglen, seqlen in zip(imglens, seqlens): + image_seqlen = imglen * getattr(processor, "image_seqlen") + batch_token_type_ids.append([0] * image_seqlen + [1] * (seqlen - image_seqlen)) + + return batch_token_type_ids + + +class BasePlugin: + def __init__(self, image_token: Optional[str], video_token: Optional[str]) -> None: + self.image_token = image_token + self.video_token = video_token + self.expand_mm_tokens = True + + def _validate_input( + self, + images: Sequence["ImageInput"], + videos: Sequence["VideoInput"], + ) -> None: + r""" + Validates if this model accepts the input modalities. + """ + if len(images) != 0 and self.image_token is None: + raise ValueError("This model does not support image input.") + + if len(videos) != 0 and self.video_token is None: + raise ValueError("This model does not support video input.") + + def _preprocess_image(self, image: "ImageObject", **kwargs) -> "ImageObject": + r""" + Pre-processes a single image. + """ + image_resolution: int = kwargs.get("image_resolution") + if (image.width * image.height) > image_resolution: + resize_factor = math.sqrt(image_resolution / (image.width * image.height)) + width, height = int(image.width * resize_factor), int(image.height * resize_factor) + image = image.resize((width, height), resample=Image.NEAREST) + + if image.mode != "RGB": + image = image.convert("RGB") + + return image + + def _get_video_sample_frames(self, video_stream: "Stream", **kwargs) -> int: + r""" + Computes video sample frames according to fps. + """ + video_fps: float = kwargs.get("video_fps") + video_maxlen: int = kwargs.get("video_maxlen") + total_frames = video_stream.frames + sample_frames = float(video_stream.duration * video_stream.time_base) * video_fps + sample_frames = min(total_frames, video_maxlen, sample_frames) + return math.floor(sample_frames) + + def _regularize_images(self, images: Sequence["ImageInput"], **kwargs) -> List["ImageObject"]: + r""" + Regularizes images to avoid error. Including reading and pre-processing. + """ + results = [] + for image in images: + if isinstance(image, str): + image = Image.open(image) + elif isinstance(image, bytes): + image = Image.open(BytesIO(image)) + elif isinstance(image, dict): + if image["bytes"] is not None: + image = Image.open(BytesIO(image["bytes"])) + else: + image = Image.open(image["path"]) + + if not isinstance(image, ImageObject): + raise ValueError(f"Expect input is a list of Images, but got {type(image)}.") + + results.append(self._preprocess_image(image, **kwargs)) + + return results + + def _regularize_videos(self, videos: Sequence["VideoInput"], **kwargs) -> List[List["ImageObject"]]: + r""" + Regularizes videos to avoid error. Including reading, resizing and converting. + """ + results = [] + for video in videos: + container = av.open(video, "r") + video_stream = next(stream for stream in container.streams if stream.type == "video") + total_frames = video_stream.frames + sample_frames = self._get_video_sample_frames(video_stream, **kwargs) + sample_indices = np.linspace(0, total_frames - 1, sample_frames).astype(np.int32) + frames: List["ImageObject"] = [] + container.seek(0) + for frame_idx, frame in enumerate(container.decode(video_stream)): + if frame_idx in sample_indices: + frames.append(frame.to_image()) + + frames = self._regularize_images(frames, **kwargs) + results.append(frames) + + return results + + def _get_mm_inputs( + self, + images: Sequence["ImageInput"], + videos: Sequence["VideoInput"], + processor: "ProcessorMixin", + ) -> Dict[str, "torch.Tensor"]: + r""" + Processes visual inputs. + + Returns: (llava and paligemma) + pixel_values: tensor with shape (B, C, H, W) + + Returns: (qwen2-vl) + pixel_values: tensor with shape (num_patches, patch_dim) + image_grid_thw: tensor with shape (num_images, 3), where the three numbers are time, width, height + + It holds num_patches == torch.prod(image_grid_thw) + """ + image_processor: "BaseImageProcessor" = getattr(processor, "image_processor") + video_processor: "BaseImageProcessor" = getattr(processor, "video_processor", image_processor) + input_dict = {"images": None} # default key + if len(images) != 0: + images = self._regularize_images( + images, + image_resolution=getattr(processor, "image_resolution", 512 * 512), + ) + input_dict["images"] = images + + if len(videos) != 0: + videos = self._regularize_videos( + videos, + image_resolution=getattr(processor, "video_resolution", 128 * 128), + video_fps=getattr(processor, "video_fps", 2.0), + video_maxlen=getattr(processor, "video_maxlen", 64), + ) + input_dict["videos"] = videos + + mm_inputs = {} + if image_processor != video_processor: + if input_dict.get("images") is not None: + mm_inputs.update(image_processor(input_dict["images"], return_tensors="pt")) + if input_dict.get("videos") is not None: + mm_inputs.update(video_processor(input_dict["videos"], return_tensors="pt")) + elif input_dict.get("images") is not None or input_dict.get("videos") is not None: # same processor (qwen2-vl) + mm_inputs.update(image_processor(**input_dict, return_tensors="pt")) + + return mm_inputs + + def process_messages( + self, + text: str, + processor: Optional["ProcessorMixin"], + mm_inputs: Optional[Dict[str, "torch.Tensor"]], + ) -> List[Dict[str, str]]: + r""" + Pre-processes input messages before tokenization for VLMs. + """ + return text + + def process_token_ids( + self, + input_ids: List[int], + labels: Optional[List[int]], + images: Sequence["ImageInput"], + videos: Sequence["VideoInput"], + tokenizer: "PreTrainedTokenizer", + processor: Optional["ProcessorMixin"], + ) -> Tuple[List[int], Optional[List[int]]]: + r""" + Pre-processes token ids after tokenization for VLMs. + """ + self._validate_input(images, videos) + return input_ids, labels + + def get_mm_inputs( + self, + images: Sequence["ImageInput"], + videos: Sequence["VideoInput"], + processor: Optional["ProcessorMixin"], + ) -> Dict[str, Union[List[int], "torch.Tensor"]]: + r""" + Builds batched multimodal inputs for VLMs. + + Arguments: + images: a list of image inputs, shape (num_images,) + videos: a list of video inputs, shape (num_videos,) + imglens: number of images in each sample, shape (batch_size,) + vidlens: number of videos in each sample, shape (batch_size,) + batch_ids: token ids of input samples, shape (batch_size, seq_len) + processor: a processor for pre-processing images and videos + """ + self._validate_input(images, videos) + return {} + + def collate_mm_inputs( + self, + mm_features: List[Dict[str, Union[List[int], "torch.Tensor"]]], + ) -> Dict[str, Union[List[int], "torch.Tensor"]]: + batch = {} + for mm_feature in mm_features: + for k, v in mm_feature.items(): + if k not in batch: + batch[k] = [] + batch[k].append(v) + batch = {k: torch.concat(v) for k, v in batch.items()} + return batch + + +class TBStars008VLPlugin(BasePlugin): + def __init__(self, image_token, video_token): + super().__init__(image_token, video_token) + self.image_placeholder = "" + self.video_placeholder = "" + + @override + def _regularize_videos(self, videos: Sequence["VideoInput"], **kwargs) -> List[List["ImageObject"]]: + results = [] + for video in videos: + container = av.open(video, "r") + video_stream = next(stream for stream in container.streams if stream.type == "video") + total_frames = video_stream.frames + sample_frames = self._get_video_sample_frames(video_stream, **kwargs) + sample_indices = np.linspace(0, total_frames - 1, sample_frames).astype(np.int32) + frames: List["ImageObject"] = [] + container.seek(0) + for frame_idx, frame in enumerate(container.decode(video_stream)): + if frame_idx in sample_indices: + frames.append(frame.to_image()) + + if len(frames) % 2 != 0: # qwen2-vl requires even number of frames + frames.append(frames[-1]) + + frames = self._regularize_images(frames, **kwargs) + results.append(frames) + + return results + + @override + def process_messages( + self, + text: str, + processor: Optional["ProcessorMixin"], + mm_inputs: Optional[Dict[str, "torch.Tensor"]] = None, + visual_len = None + ) -> List[Dict[str, str]]: + crop_positions = mm_inputs.get("crop_positions", None) + if visual_len: + proj_len = visual_len + else: + proj_len = getattr(processor.image_processor, "perceiver_num_queries", 144) + if crop_positions is not None: + cumsum_positions = torch.tensor( + [torch.allclose(p, crop_positions[0]) for p in crop_positions] + [True] + ).nonzero().squeeze() + image_lens = cumsum_positions[1:] - cumsum_positions[:-1] + image_lens = (image_lens * proj_len).tolist() + else: + image_lens = [] + + video_chunk_sizes = mm_inputs.get("video_chunk_sizes", None) + if video_chunk_sizes is not None: + video_lens = (video_chunk_sizes * proj_len).tolist() + else: + video_lens = [] + + num_image_tokens, num_video_tokens = 0, 0 + text = text.replace(IMAGE_PLACEHOLDER, "") + while "" in text: + if num_image_tokens >= len(image_lens): + raise ValueError(f"`len(images)` is less than the number of {IMAGE_PLACEHOLDER} tokens.") + image_seqlen = image_lens[num_image_tokens] + text = text.replace("", f"{self.image_placeholder * image_seqlen}", 1) + num_image_tokens += 1 + + while VIDEO_PLACEHOLDER in text: + if num_video_tokens >= len(video_lens): + raise ValueError(f"`len(videos)` is less than the number of {VIDEO_PLACEHOLDER} tokens.") + video_seqlens = video_lens[num_video_tokens] + video_text = "" + for video_seqlen in video_seqlens: + video_text += f"{self.video_placeholder * video_seqlen}\n" + text = text.replace(VIDEO_PLACEHOLDER, video_text, 1) + num_video_tokens += 1 + + if len(image_lens) != num_image_tokens: + raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens.") + + if len(video_lens) != num_video_tokens: + raise ValueError(f"The number of videos does not match the number of {VIDEO_PLACEHOLDER} tokens.") + + return text + + @override + def get_mm_inputs( + self, + images: Sequence["ImageInput"], + videos: Sequence["VideoInput"], + processor: Optional["ProcessorMixin"], + ) -> Dict[str, Union[List[int], "torch.Tensor"]]: + return self._get_mm_inputs(images, videos, processor) + + @override + def collate_mm_inputs( + self, + mm_features: List[Dict[str, Union[List[int], "torch.Tensor"]]], + ) -> Dict[str, Union[List[int], "torch.Tensor"]]: + batch = {} + for mm_feature in mm_features: + for k, v in mm_feature.items(): + if k not in batch: + batch[k] = [] + batch[k].append(v) + batch.pop("video_chunk_sizes", None) + batch = {k: torch.concat(v) for k, v in batch.items()} + return batch + + +class Qwen2vlPlugin(BasePlugin): + @override + def _preprocess_image(self, image: "ImageObject", **kwargs) -> "ImageObject": + image = super()._preprocess_image(image, **kwargs) + if min(image.width, image.height) < 28: + width, height = max(image.width, 28), max(image.height, 28) + image = image.resize((width, height), resample=Image.NEAREST) + + if image.width / image.height > 200: + width, height = image.height * 180, image.height + image = image.resize((width, height), resample=Image.NEAREST) + + if image.height / image.width > 200: + width, height = image.width, image.width * 180 + image = image.resize((width, height), resample=Image.NEAREST) + + return image + + @override + def _regularize_videos(self, videos: Sequence["VideoInput"], **kwargs) -> List[List["ImageObject"]]: + results = [] + for video in videos: + container = av.open(video, "r") + video_stream = next(stream for stream in container.streams if stream.type == "video") + total_frames = video_stream.frames + sample_frames = self._get_video_sample_frames(video_stream, **kwargs) + sample_indices = np.linspace(0, total_frames - 1, sample_frames).astype(np.int32) + frames: List["ImageObject"] = [] + container.seek(0) + for frame_idx, frame in enumerate(container.decode(video_stream)): + if frame_idx in sample_indices: + frames.append(frame.to_image()) + + if len(frames) % 2 != 0: # qwen2-vl requires even number of frames + frames.append(frames[-1]) + + frames = self._regularize_images(frames, **kwargs) + results.append(frames) + + return results + + @override + def process_messages( + self, + text: str, + processor: Optional["ProcessorMixin"], + mm_inputs: Optional[Dict[str, "torch.Tensor"]] = None, + ) -> List[Dict[str, str]]: + image_grid_thw = mm_inputs.get("image_grid_thw", []) + video_grid_thw = mm_inputs.get("video_grid_thw", []) + image_processor: "BaseImageProcessor" = getattr(processor, "image_processor") + merge_length: int = getattr(image_processor, "merge_size") ** 2 + + num_image_tokens, num_video_tokens = 0, 0 + while IMAGE_PLACEHOLDER in text: + if num_image_tokens >= len(image_grid_thw): + raise ValueError(f"`len(images)` is less than the number of {IMAGE_PLACEHOLDER} tokens.") + + image_seqlen = image_grid_thw[num_image_tokens].prod() // merge_length if self.expand_mm_tokens else 1 + content = text.replace( + IMAGE_PLACEHOLDER, f"<|vision_start|>{self.image_token * image_seqlen}<|vision_end|>", 1 + ) + num_image_tokens += 1 + + while VIDEO_PLACEHOLDER in text: + if num_video_tokens >= len(video_grid_thw): + raise ValueError(f"`len(videos)` is less than the number of {VIDEO_PLACEHOLDER} tokens.") + + video_seqlen = video_grid_thw[num_video_tokens].prod() // merge_length if self.expand_mm_tokens else 1 + content = content.replace( + VIDEO_PLACEHOLDER, f"<|vision_start|>{self.video_token * video_seqlen}<|vision_end|>", 1 + ) + num_video_tokens += 1 + + if len(image_grid_thw) != num_image_tokens: + raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens.") + + if len(video_grid_thw) != num_video_tokens: + raise ValueError(f"The number of videos does not match the number of {VIDEO_PLACEHOLDER} tokens.") + + return text + + @override + def get_mm_inputs( + self, + images: Sequence["ImageInput"], + videos: Sequence["VideoInput"], + processor: Optional["ProcessorMixin"], + ) -> Dict[str, Union[List[int], "torch.Tensor"]]: + self._validate_input(images, videos) + return self._get_mm_inputs(images, videos, processor) + + +PLUGINS = { + "base": BasePlugin, + "qwen2_vl": Qwen2vlPlugin, + "tbstars008vl": TBStars008VLPlugin, +} + + +def get_mm_plugin( + name: str, + image_token: Optional[str] = None, + video_token: Optional[str] = None, +) -> "BasePlugin": + plugin_class = PLUGINS.get(name, None) + if plugin_class is None: + raise ValueError(f"Multimodal plugin `{name}` not found.") + + return plugin_class(image_token, video_token) diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/preprocess.py b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/preprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..19e85504717d07e7e551fd886c4629f976a85a3f --- /dev/null +++ b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/preprocess.py @@ -0,0 +1,159 @@ +from functools import partial +from itertools import chain +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Literal, Tuple +import random +# from extras.constants import IGNORE_INDEX +from logger import get_logger + + +if TYPE_CHECKING: + from transformers import Seq2SeqTrainingArguments, ProcessorMixin + from transformers.tokenization_utils import PreTrainedTokenizer + + from hparams import DataArguments + from .template import Template + + +logger = get_logger(__name__) + + +def preprocess_retrieval_dataset( + example: Tuple[Any], + template: "Template", + data_args: "DataArguments", +) -> Dict[str, List[List[int]]]: + """ + 0 id string + 1 query_text string + 2 query_image string + 3 item_text string + 4 item_image string + 5 task + """ + model_inputs = {} + + if "ailake" in data_args.file_name: + if example[10] == "text-item": + query_inputs = template.prepare_inputs(text=example[1], input_type="text-only", return_tensors="pt") + item_inputs = template.prepare_inputs(text=example[4], input_type="multi-model", pic_url=example[5], return_tensors="pt") + model_inputs["query_features"] = query_inputs + model_inputs["item_features"] = item_inputs + model_inputs["id"] = "nan" + elif example[10] == "image-item": + query_inputs = template.prepare_inputs(text="这是待匹配图像", input_type="multi-model", pic_url=example[2], return_tensors="pt") + item_inputs = template.prepare_inputs(text=example[4], input_type="multi-model", pic_url=example[5], return_tensors="pt") + model_inputs["query_features"] = query_inputs + model_inputs["item_features"] = item_inputs + model_inputs["id"] = "nan" + elif example[10] == "image-item-trip": + query_inputs = template.prepare_inputs(text="这是待匹配图像", input_type="multi-model", pic_url=example[2], return_tensors="pt") + pos_item_inputs = template.prepare_inputs(text=example[4], input_type="multi-model", pic_url=example[5], return_tensors="pt") + neg_item_inputs = template.prepare_inputs(text=example[7], input_type="multi-model", pic_url=example[8], return_tensors="pt") + model_inputs["query_features"] = query_inputs + model_inputs["pos_item_features"] = pos_item_inputs + model_inputs["neg_item_features"] = neg_item_inputs + model_inputs["id"] = "nan" + + elif "odps" in data_args.file_name: + example = tuple(item.decode('utf-8') if isinstance(item, bytes) else item for item in example) + + if example[10] == "text-item": + query_inputs = template.prepare_inputs(text=example[1], input_type="text-only", return_tensors="pt") + item_inputs = template.prepare_inputs(text=example[4], input_type="multi-model", pic_url=example[5], return_tensors="pt") + model_inputs["query_features"] = query_inputs + model_inputs["item_features"] = item_inputs + model_inputs["id"] = "nan" + elif example[10] == "image-item": + query_inputs = template.prepare_inputs(text="这是待匹配图像", input_type="multi-model", pic_url=example[2], return_tensors="pt") + item_inputs = template.prepare_inputs(text=example[4], input_type="multi-model", pic_url=example[5], return_tensors="pt") + model_inputs["query_features"] = query_inputs + model_inputs["item_features"] = item_inputs + model_inputs["id"] = "nan" + elif example[10] == "image-item-trip": + query_inputs = template.prepare_inputs(text="这是待匹配图像", input_type="multi-model", pic_url=example[2], return_tensors="pt") + pos_item_inputs = template.prepare_inputs(text=example[4], input_type="multi-model", pic_url=example[5], return_tensors="pt") + neg_item_inputs = template.prepare_inputs(text=example[7], input_type="multi-model", pic_url=example[8], return_tensors="pt") + model_inputs["query_features"] = query_inputs + model_inputs["pos_item_features"] = pos_item_inputs + model_inputs["neg_item_features"] = neg_item_inputs + model_inputs["id"] = "nan" + + + return model_inputs + + +def preprocess_retrieval_infer_query_dataset( + example: Tuple[Any], + template: "Template", + data_args: "DataArguments", +) -> Dict[str, List[List[int]]]: + """ + 0 id string + 1 query_text string + 2 query_img string + """ + model_inputs = {} + if "odps" in data_args.file_name: + example = tuple(item.decode('utf-8') if isinstance(item, bytes) else item for item in example) + + if example[3] == "text-item": + query_inputs = template.prepare_inputs(text=example[1], input_type="text-only", return_tensors="pt") + elif example[3] == "image-item": + query_inputs = template.prepare_inputs(text="这是待匹配图像", input_type="multi-model", pic_url=example[2], return_tensors="pt") + + model_inputs["query_features"] = query_inputs + model_inputs["record_id"] = example[0] + model_inputs["query_text"] = example[1] + model_inputs["query_img"] = example[2] + return model_inputs + + +def preprocess_retrieval_infer_item_dataset( + example: Tuple[Any], + template: "Template", + data_args: "DataArguments", +) -> Dict[str, List[List[int]]]: + """ + 0 id string + 1 item_text string + 2 item_img string + """ + model_inputs = {} + if "odps" in data_args.file_name: + example = tuple(item.decode('utf-8') if isinstance(item, bytes) else item for item in example) + + item_inputs = template.prepare_inputs(text=example[1], input_type="multi-model", pic_url=example[2], return_tensors="pt") + + model_inputs["item_features"] = item_inputs + model_inputs["record_id"] = example[0] + model_inputs["item_text"] = example[1] + if "odps" in data_args.file_name: + model_inputs["item_img"] = example[2] + else: + model_inputs["item_img"] = "nan" + return model_inputs + + + + +def get_preprocess_func( + template: "Template", + data_args: "DataArguments", + stage: Literal["retrieval", "retrieval_infer_query", "retrieval_infer_item"], +) -> Tuple[Callable, Callable]: + if stage == "retrieval": + preprocess_func = partial( + preprocess_retrieval_dataset, template=template, data_args=data_args + ) + elif stage == "retrieval_infer_query": + preprocess_func = partial( + preprocess_retrieval_infer_query_dataset, template=template, data_args=data_args + ) + elif stage == "retrieval_infer_item": + preprocess_func = partial( + preprocess_retrieval_infer_item_dataset, template=template, data_args=data_args + ) + else: + raise RuntimeError("Check stage!") + + return preprocess_func diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/template.py b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/template.py new file mode 100644 index 0000000000000000000000000000000000000000..e2c112791ec56b0583d46613f7cdf2af8523772d --- /dev/null +++ b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/template.py @@ -0,0 +1,114 @@ +import os +from io import BytesIO +from PIL import Image, ImageFilter, ImageOps +import os +from transformers import ProcessorMixin +import torch +import random +from typing import Optional +from transformers.image_utils import ChannelDimension, get_image_size, load_image, to_numpy_array +import numpy as np + + +from logger import get_logger + +from .mm_plugin import get_mm_plugin + + +logger = get_logger(__name__) + + +class Template: + def __init__( + self, + processor: "ProcessorMixin", + cutoff_len: int = 128, + media_dir: Optional[str] = None, + ) -> None: + self.processor = processor + self.tokenizer = processor.tokenizer + self.image_processor = processor.image_processor + self.cutoff_len = cutoff_len + self.media_dir = media_dir + self.mm_plugin = get_mm_plugin("tbstars008vl") + self.query_template_type = "<|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{}<|im_end|>\n<|im_start|>assistant\n<|im_end|>" + self.item_template_type = "<|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\n{}<|im_end|>\n<|im_start|>assistant\n<|im_end|>" + + def _load_single_image(self, image_path: str): + try: + image = load_image(image_path) + except Exception as e: + logger.warning(f"{image_path} pull fail because: \n{e}") + image_path = os.path.join(os.path.dirname(__file__), "default_image.jpg") + image = load_image(image_path) + return image, False + return image, True + + def _process_text(self, text_template, text, return_tensors): + pref, tail = text_template.split("{}") + tokenized_pref = self.tokenizer.encode(pref, add_special_tokens=False, return_tensors=return_tensors) + tokenized_text = self.tokenizer.encode(text, add_special_tokens=False, return_tensors=return_tensors) + tokenized_text = tokenized_text[:, :self.cutoff_len] + tokenized_tail = self.tokenizer.encode(tail, add_special_tokens=False, return_tensors=return_tensors) + res = torch.cat((tokenized_pref, tokenized_text, tokenized_tail), dim=1) + return res + + def _load_bytes_to_image(self, data): + try: + image = Image.open(BytesIO(data)) + except Exception as e: + logger.warning(f"image pull fail because: \n{e}") + image_path = os.path.join(os.path.dirname(__file__), "default_image.jpg") + image = load_image(image_path) + return image, False + return image, True + + def prepare_inputs(self, text:str, input_type:str="", pic_url:str=None, crop_position:str=None, return_tensors="pt"): + result = {} + if input_type == "multi-model": + if isinstance(pic_url, bytes): + ailake_bytes_data = pic_url + image, status = self._load_bytes_to_image(ailake_bytes_data) + else: + pic_url = "" if pic_url is None else pic_url + pic_url = f"http://webhost.tbgw.taobao.com/v1/35dc029c340da/{pic_url}" if "/data/oss_bucket_0/" not in pic_url else pic_url + + image, status = self._load_single_image(pic_url) + try: + if crop_position != None: + crop_roi = [] + pailitao_crop_list = crop_position.split(",") + for i in range(4): + crop_roi.append(int(pailitao_crop_list[i])) + image = image.crop((crop_roi[0],crop_roi[1],crop_roi[2],crop_roi[3])) + + mm_features = self.mm_plugin.get_mm_inputs(images=[image], videos=[], processor=self.processor) + except Exception as e: + logger.warning(f"{pic_url} pull fail because: \n{e}") + image_path = os.path.join(os.path.dirname(__file__), "default_image.jpg") + image = load_image(image_path) + mm_features = self.mm_plugin.get_mm_inputs( + images=[image], videos=[], processor=self.processor + ) + status = False + mm_item_template = self.mm_plugin.process_messages(self.item_template_type, processor=self.processor, mm_inputs=mm_features) + + text = self._process_text(mm_item_template, text, return_tensors=return_tensors) + + result["input_ids"] = text + result.update(mm_features) + + elif input_type == "text-only": + text = self._process_text(self.query_template_type, text, return_tensors=return_tensors) + result["input_ids"] = text + + image_path = os.path.join(os.path.dirname(__file__), "default_image.jpg") + image = load_image(image_path) + mm_features = self.mm_plugin.get_mm_inputs( + images=[image], videos=[], processor=self.processor + ) + result.update(mm_features) + + else: + raise RuntimeError("Check input_type, it should be query or item") + return result diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/template_guijiang.py b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/template_guijiang.py new file mode 100644 index 0000000000000000000000000000000000000000..4edc15e9ebf9da38a355e2e743366caa0b1a1535 --- /dev/null +++ b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/data/template_guijiang.py @@ -0,0 +1,138 @@ +## 自用template +## 用来支持template的输入 +import os +from io import BytesIO +from PIL import Image, ImageFilter, ImageOps +import os +from transformers import ProcessorMixin +import torch +import random +from typing import Optional, Literal +from transformers.image_utils import ChannelDimension, get_image_size, load_image, to_numpy_array +import numpy as np + + +from logger import get_logger + +from .mm_plugin import get_mm_plugin + + +logger = get_logger(__name__) + + +class Template: + def __init__( + self, + processor: "ProcessorMixin", + cutoff_len: int = 128, + media_dir: Optional[str] = None, + ) -> None: + self.processor = processor + self.tokenizer = processor.tokenizer + self.image_processor = processor.image_processor + self.cutoff_len = cutoff_len + self.media_dir = media_dir + self.mm_plugin = get_mm_plugin("tbstars008vl") + self.query_template_type = "<|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{}<|im_end|>\n<|im_start|>assistant\n<|im_end|>" + self.item_template_type = "<|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{}\n<|im_end|>\n<|im_start|>assistant\n<|im_end|>" + self.image_image_crop_template_type = "<|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{}\n\n<|im_end|>\n<|im_start|>assistant\n<|im_end|>" + + def _process_text(self, text_template, text, return_tensors): + pref, tail = text_template.split("{}") + tokenized_pref = self.tokenizer.encode(pref, add_special_tokens=False, return_tensors=return_tensors) + tokenized_text = self.tokenizer.encode(text, add_special_tokens=False, return_tensors=return_tensors) + tokenized_text = tokenized_text[:, :self.cutoff_len] + tokenized_tail = self.tokenizer.encode(tail, add_special_tokens=False, return_tensors=return_tensors) + res = torch.cat((tokenized_pref, tokenized_text, tokenized_tail), dim=1) + return res + + ## 根据输入的信息来进行格式设定 + def prepare_inputs_train(self, messages:list, image_type=Optional[Literal["full", "crop", "both", "swap"]], text_require=False, return_tensors="pt"): + message = messages[0] + result = {} + image_content = [] + text_content = [] + for content in message["content"]: + if content["type"] == "image": + image_content.append(content["image"]) + else: + text_content.append(content["text"]) + + ## 只有有两张图像输出这才有必要 + if len(image_content) == 2: + if image_type == "full": + image_content = image_content[:1] + elif image_type == "crop": + image_content = image_content[1:] + elif image_type == "swap": + image_content[0], image_content[1] = image_content[1], image_content[0] + + if len(image_content) == 2: + mm_features = self.mm_plugin.get_mm_inputs(images=image_content, videos=[], processor=self.processor) + mm_item_template = self.mm_plugin.process_messages(self.image_image_crop_template_type, processor=self.processor, mm_inputs=mm_features) + result.update(mm_features) + elif len(image_content) == 1: + mm_features = self.mm_plugin.get_mm_inputs(images=image_content, videos=[], processor=self.processor) + mm_item_template = self.mm_plugin.process_messages(self.item_template_type, processor=self.processor, mm_inputs=mm_features) + result.update(mm_features) + else: + mm_item_template = self.query_template_type + + ## 是否有文本输入 + if text_require: + text = self._process_text(mm_item_template, text_content[0], return_tensors=return_tensors) + result["input_ids"] = text + else: + text = self._process_text(mm_item_template, '', return_tensors=return_tensors) + result["input_ids"] = text + return result + + ## 测试的时候有不同的处理方式,但是训练的时候,只要按照dataset设定就好了 + def prepare_inputs(self, messages:list, image_type=Optional[Literal["full", "crop", "both", "swap"]], text_require=False, return_tensors="pt"): + message = messages[0] + result = {} + image_content = [] + text_content = [] + for content in message["content"]: + if content["type"] == "image": + image_content.append(content["image"]) + else: + text_content.append(content["text"]) + + ## 只有有两张图像输出这才有必要 + if len(image_content) == 2: + if image_type == "full": + image_content = image_content[:1] + elif image_type == "crop": + image_content = image_content[1:] + elif image_type == "swap": + image_content[0], image_content[1] = image_content[1], image_content[0] + # print(image_content) + + for i in range(len(image_content)): + width, height = image_content[i].size # 获取图像的宽和高 + if width == 1 or height == 1: + # 计算放大两倍后的尺寸 + new_size = (width * 2, height * 2) + # 使用 resize 方法放大图像,可选插值方式为 BILINEAR 或 BICUBIC + image_content[i] = image_content[i].resize(new_size, Image.BILINEAR) + if len(image_content) == 2: + # image_new = images[0][..., 0][..., np.newaxis] + mm_features = self.mm_plugin.get_mm_inputs(images=image_content, videos=[], processor=self.processor) + mm_item_template = self.mm_plugin.process_messages(self.image_image_crop_template_type, processor=self.processor, mm_inputs=mm_features) + result.update(mm_features) + elif len(image_content) == 1: + mm_features = self.mm_plugin.get_mm_inputs(images=image_content, videos=[], processor=self.processor) + mm_item_template = self.mm_plugin.process_messages(self.item_template_type, processor=self.processor, mm_inputs=mm_features) + result.update(mm_features) + else: + mm_item_template = self.query_template_type + + ## 是否有文本输入 + if text_require: + text = self._process_text(mm_item_template, text_content[0], return_tensors=return_tensors) + result["input_ids"] = text + else: + text = self._process_text(mm_item_template, '', return_tensors=return_tensors) + result["input_ids"] = text + return result \ No newline at end of file diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__init__.py b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__pycache__/__init__.cpython-310.pyc b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6df4d591048a0b04db7892a3e61e82431b6afea5 Binary files /dev/null and b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__pycache__/__init__.cpython-310.pyc differ diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__pycache__/__init__.cpython-313.pyc b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd83c7f2a5139a744bb7c30fbc70f0bd27f1e88c Binary files /dev/null and b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__pycache__/__init__.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__pycache__/constants.cpython-310.pyc b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__pycache__/constants.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..585588552587edd57231fb90775b2551d8099c16 Binary files /dev/null and b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__pycache__/constants.cpython-310.pyc differ diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__pycache__/constants.cpython-313.pyc b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__pycache__/constants.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de6d5f0786738d12bdeb4776fdbda0008c358e48 Binary files /dev/null and b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__pycache__/constants.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__pycache__/packages.cpython-310.pyc b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__pycache__/packages.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05e16ff76a3b566904e3077883b43ca5f89aaeab Binary files /dev/null and b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__pycache__/packages.cpython-310.pyc differ diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__pycache__/packages.cpython-313.pyc b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__pycache__/packages.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4379ce50cef071d2bd1b9c9e7aac00ee411d2d80 Binary files /dev/null and b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/__pycache__/packages.cpython-313.pyc differ diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/callbacks.py b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..f7498adfe8a08d86d249640abb24fa1f0f2a8adb --- /dev/null +++ b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/callbacks.py @@ -0,0 +1,139 @@ +import json +import os +import time +from datetime import timedelta +from typing import TYPE_CHECKING + +from transformers import TrainerCallback +from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR, has_length + +from .constants import LOG_FILE_NAME +from .logger import get_logger + + +if TYPE_CHECKING: + from transformers import TrainerControl, TrainerState, TrainingArguments + + +logger = get_logger(__name__) + + +class LogCallback(TrainerCallback): + def __init__(self, runner=None): + self.runner = runner + self.in_training = False + self.start_time = time.time() + self.cur_steps = 0 + self.max_steps = 0 + self.elapsed_time = "" + self.remaining_time = "" + + def timing(self): + cur_time = time.time() + elapsed_time = cur_time - self.start_time + avg_time_per_step = elapsed_time / self.cur_steps if self.cur_steps != 0 else 0 + remaining_time = (self.max_steps - self.cur_steps) * avg_time_per_step + self.elapsed_time = str(timedelta(seconds=int(elapsed_time))) + self.remaining_time = str(timedelta(seconds=int(remaining_time))) + + def on_train_begin(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs): + r""" + Event called at the beginning of training. + """ + if state.is_world_process_zero: + self.in_training = True + self.start_time = time.time() + self.max_steps = state.max_steps + if os.path.exists(os.path.join(args.output_dir, LOG_FILE_NAME)) and args.overwrite_output_dir: + logger.warning("Previous log file in this folder will be deleted.") + os.remove(os.path.join(args.output_dir, LOG_FILE_NAME)) + + def on_train_end(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs): + r""" + Event called at the end of training. + """ + if state.is_world_process_zero: + self.in_training = False + self.cur_steps = 0 + self.max_steps = 0 + + def on_substep_end(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs): + r""" + Event called at the end of an substep during gradient accumulation. + """ + if state.is_world_process_zero and self.runner is not None and self.runner.aborted: + control.should_epoch_stop = True + control.should_training_stop = True + + def on_step_end(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs): + r""" + Event called at the end of a training step. + """ + if state.is_world_process_zero: + self.cur_steps = state.global_step + self.timing() + if self.runner is not None and self.runner.aborted: + control.should_epoch_stop = True + control.should_training_stop = True + + def on_evaluate(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs): + r""" + Event called after an evaluation phase. + """ + if state.is_world_process_zero and not self.in_training: + self.cur_steps = 0 + self.max_steps = 0 + + def on_predict( + self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", *other, **kwargs + ): + r""" + Event called after a successful prediction. + """ + if state.is_world_process_zero and not self.in_training: + self.cur_steps = 0 + self.max_steps = 0 + + def on_log(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs) -> None: + r""" + Event called after logging the last logs. + """ + if not state.is_world_process_zero: + return + + logs = dict( + current_steps=self.cur_steps, + total_steps=self.max_steps, + loss=state.log_history[-1].get("loss", None), + eval_loss=state.log_history[-1].get("eval_loss", None), + predict_loss=state.log_history[-1].get("predict_loss", None), + reward=state.log_history[-1].get("reward", None), + learning_rate=state.log_history[-1].get("learning_rate", None), + epoch=state.log_history[-1].get("epoch", None), + percentage=round(self.cur_steps / self.max_steps * 100, 2) if self.max_steps != 0 else 100, + elapsed_time=self.elapsed_time, + remaining_time=self.remaining_time, + ) + if self.runner is not None: + logger.info( + "{{'loss': {:.4f}, 'learning_rate': {:2.4e}, 'epoch': {:.2f}}}".format( + logs["loss"] or 0, logs["learning_rate"] or 0, logs["epoch"] or 0 + ) + ) + + os.makedirs(args.output_dir, exist_ok=True) + with open(os.path.join(args.output_dir, "trainer_log.jsonl"), "a", encoding="utf-8") as f: + f.write(json.dumps(logs) + "\n") + + def on_prediction_step( + self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs + ): + r""" + Event called after a prediction step. + """ + eval_dataloader = kwargs.pop("eval_dataloader", None) + if state.is_world_process_zero and has_length(eval_dataloader) and not self.in_training: + if self.max_steps == 0: + self.max_steps = len(eval_dataloader) + self.cur_steps += 1 + self.timing() diff --git a/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/constants.py b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..9ec080718ec082620da1eba31f6788c53b360820 --- /dev/null +++ b/code/multi_vlm2vec_train/models/tbstars_ecom_emb/src/extras/constants.py @@ -0,0 +1,920 @@ +import os +from collections import OrderedDict, defaultdict +from enum import Enum +from typing import Dict, Optional + + +CHOICES = ["A", "B", "C", "D"] + +DATA_CONFIG = "dataset_info.json" + +DEFAULT_MODULE = defaultdict(str) + +DEFAULT_TEMPLATE = defaultdict(str) + +FILEEXT2TYPE = { + "arrow": "arrow", + "csv": "csv", + "json": "json", + "jsonl": "json", + "parquet": "parquet", + "txt": "text", +} + +IGNORE_INDEX = -100 + +IMAGE_PLACEHOLDER = os.environ.get("IMAGE_PLACEHOLDER", "") + +VIDEO_PLACEHOLDER = os.environ.get("VIDEO_PLACEHOLDER", "