enmingzhangzz commited on
Commit
a47010e
·
verified ·
1 Parent(s): f847595

Publish evaluation-and-model-card

Browse files
NOTICE CHANGED
@@ -1,7 +1,8 @@
1
  SCOPD / SCOPD+ model release
2
 
3
  The weights derive from Qwen/Qwen2.5-VL-7B-Instruct, revision
4
- cc594898137f460bfe9f0759e9844b3ce807cfb5. Its model card specifies Apache-2.0.
 
5
  Only fine-tuning LoRA adapter weights are redistributed; base weights are not included.
6
  Evaluation and pruning sources include local patches recorded in evaluation_files.json.
7
  Transformers: see evaluation/runtime/TRANSFORMERS_LICENSE.
 
1
  SCOPD / SCOPD+ model release
2
 
3
  The weights derive from Qwen/Qwen2.5-VL-7B-Instruct, revision
4
+ cc594898137f460bfe9f0759e9844b3ce807cfb5, and Qwen/Qwen3-VL-4B-Instruct, revision
5
+ ebb281ec70b05090aa6165b016eac8ec08e71b17. Both model cards specify Apache-2.0.
6
  Only fine-tuning LoRA adapter weights are redistributed; base weights are not included.
7
  Evaluation and pruning sources include local patches recorded in evaluation_files.json.
8
  Transformers: see evaluation/runtime/TRANSFORMERS_LICENSE.
README.md CHANGED
@@ -1,10 +1,13 @@
1
  ---
2
  license: apache-2.0
3
- base_model: Qwen/Qwen2.5-VL-7B-Instruct
 
 
4
  library_name: transformers
5
  pipeline_tag: image-text-to-text
6
  tags:
7
  - qwen2_5_vl
 
8
  - vision-language
9
  - visual-token-pruning
10
  - visionzip
@@ -13,7 +16,7 @@ tags:
13
 
14
  # SCOPD / SCOPD+ Checkpoints
15
 
16
- LoRA adapters for Qwen2.5-VL-7B-Instruct with visual-token-pruned inference.
17
  This repository provides **adapter weights only** and evaluation instructions.
18
  The pinned base model is required separately. No full/merged model weights,
19
  teacher weights, optimizer state, or training data are included.
@@ -33,10 +36,13 @@ teacher weights, optimizer state, or training data are included.
33
  | SCOPD Off-Policy | forward KL on teacher-generated responses | all response tokens | [Download](https://huggingface.co/enmingzhangzz/SCOPD/tree/main/models/scopd-offpolicy) |
34
  | SCOPD+ Reverse KL | reverse KL: KL(student \|\| teacher) | top 10% budget-JSD response tokens | [Download](https://huggingface.co/enmingzhangzz/SCOPD/tree/main/models/scopd-plus-reverse-kl) |
35
  | SCOPD+ JSD | symmetric JSD(teacher, student) | top 10% budget-JSD response tokens | [Download](https://huggingface.co/enmingzhangzz/SCOPD/tree/main/models/scopd-plus-jsd) |
 
 
36
 
37
  Each subfolder contains `adapter_model.safetensors`, `adapter_config.json`,
38
- and provenance. Each adapter is approximately **154 MiB**; all 11 adapters
39
- total approximately **1.65 GiB**. Their tensors retain the saved FP32 precision.
 
40
  Inference uses a BF16 base model. All adapters use rank 16, alpha 32,
41
  zero dropout, and language-decoder attention/MLP projections only.
42
 
@@ -45,7 +51,9 @@ The SCOPD+ variants use a native VisionZip intervention from 10% to 11%
45
  visual retention to select tokens. The released checkpoints support evaluation
46
  at 10%, 20%, 30%, and no pruning using the same runner.
47
 
48
- The base revision is `cc594898137f460bfe9f0759e9844b3ce807cfb5`.
 
 
49
  The JSD and reverse-KL variants here are **LoRA adapters**, not full-parameter
50
  fine-tuning variants. The GRPO checkpoint is the final policy at 2560 optimizer
51
  updates after 10240 processed questions; these units are not interchangeable.
@@ -90,12 +98,17 @@ python -m pip install -r requirements.txt
90
  python -m pip install -r third_party/VLMEvalKit/requirements.txt
91
  python -m pip install -r requirements.txt
92
  python -m pip install 'flash-attn==2.8.3' --no-build-isolation
93
- python runtime/prepare.py --mode eval
94
- source runtime/activate.sh eval
 
95
  ```
96
 
97
- Installing an unmodified `transformers==4.57.0` alone is not sufficient for
98
- VisionZip. The preparer verifies the wheel and overlay hashes. A different
 
 
 
 
99
  Pillow implementation can change image preprocessing: consult
100
  [environment details](evaluation/docs/ENVIRONMENT.md) before a numerical
101
  reproduction attempt. The listed environment is a source-version specification,
@@ -107,7 +120,7 @@ First download the pinned base model and merge the adapter **locally for
107
  evaluation**. This preparation step is not training, and does not upload a
108
  merged model. The default CPU merge needs enough host RAM for the base model
109
  and merge buffers; use `--device cuda` only on an available GPU with sufficient
110
- memory. Allow approximately 16 GiB of disk for the locally merged model.
111
 
112
  ```bash
113
  export MERGED_MODEL="$RELEASE_DIR/local-merged/$VARIANT"
@@ -116,8 +129,9 @@ python scripts/merge_adapter.py \
116
  --output "$MERGED_MODEL"
117
  ```
118
 
119
- Alternatively, `--base-model` can point to an already downloaded Hub snapshot
120
- directory named `cc594898137f460bfe9f0759e9844b3ce807cfb5`.
 
121
  For direct PEFT inference, the same adapter can be loaded onto that base using
122
  `PeftModel.from_pretrained`; the benchmark runner below uses a merged model.
123
 
@@ -133,9 +147,21 @@ python -m scopd_eval.infer \
133
 
134
  Use `--retention 0.20` or `0.30` for milder pruning, and `--retention 1`
135
  for no pruning. The argument is **retention**, not the backend's
136
- `visionzip_ratio` parameter. Greedy inference uses the reasoning format
137
- `<think>...</think><answer>...</answer>`, at most 2048 generated tokens,
138
- and image bounds of 1280 to 4096 nominal visual tokens.
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
  Supported image tasks include MME, MMStar, MathVista-MINI,
141
  MathVerse-MINI-Vision-Only, MMMU-Pro-4c, HallusionBench, CVBench,
@@ -201,7 +227,8 @@ research evaluation, not high-stakes decisions.
201
  ## License
202
 
203
  The weights are derivatives of
204
- [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct),
205
- whose pinned model card specifies Apache-2.0. See [LICENSE](LICENSE) and
 
206
  [NOTICE](NOTICE). Third-party evaluation and pruning implementations retain
207
  their individual licenses and source notices.
 
1
  ---
2
  license: apache-2.0
3
+ base_model:
4
+ - Qwen/Qwen2.5-VL-7B-Instruct
5
+ - Qwen/Qwen3-VL-4B-Instruct
6
  library_name: transformers
7
  pipeline_tag: image-text-to-text
8
  tags:
9
  - qwen2_5_vl
10
+ - qwen3_vl
11
  - vision-language
12
  - visual-token-pruning
13
  - visionzip
 
16
 
17
  # SCOPD / SCOPD+ Checkpoints
18
 
19
+ LoRA adapters for Qwen2.5-VL-7B-Instruct and Qwen3-VL-4B-Instruct with visual-token-pruned inference.
20
  This repository provides **adapter weights only** and evaluation instructions.
21
  The pinned base model is required separately. No full/merged model weights,
22
  teacher weights, optimizer state, or training data are included.
 
36
  | SCOPD Off-Policy | forward KL on teacher-generated responses | all response tokens | [Download](https://huggingface.co/enmingzhangzz/SCOPD/tree/main/models/scopd-offpolicy) |
37
  | SCOPD+ Reverse KL | reverse KL: KL(student \|\| teacher) | top 10% budget-JSD response tokens | [Download](https://huggingface.co/enmingzhangzz/SCOPD/tree/main/models/scopd-plus-reverse-kl) |
38
  | SCOPD+ JSD | symmetric JSD(teacher, student) | top 10% budget-JSD response tokens | [Download](https://huggingface.co/enmingzhangzz/SCOPD/tree/main/models/scopd-plus-jsd) |
39
+ | Qwen3-VL-4B SCOPD | forward KL: KL(teacher \|\| student) | all response tokens | [Download](https://huggingface.co/enmingzhangzz/SCOPD/tree/main/models/qwen3-vl-4b-scopd) |
40
+ | Qwen3-VL-4B SCOPD+ | forward KL: KL(teacher \|\| student) | top 10% budget-JSD response tokens | [Download](https://huggingface.co/enmingzhangzz/SCOPD/tree/main/models/qwen3-vl-4b-scopd-plus) |
41
 
42
  Each subfolder contains `adapter_model.safetensors`, `adapter_config.json`,
43
+ and provenance. Qwen2.5 adapters are approximately **154 MiB** each; Qwen3
44
+ adapters are approximately **126 MiB** each. All 13 adapters total approximately
45
+ **1.90 GiB**. Their tensors retain the saved FP32 precision.
46
  Inference uses a BF16 base model. All adapters use rank 16, alpha 32,
47
  zero dropout, and language-decoder attention/MLP projections only.
48
 
 
51
  visual retention to select tokens. The released checkpoints support evaluation
52
  at 10%, 20%, 30%, and no pruning using the same runner.
53
 
54
+ The Qwen2.5 base revision is `cc594898137f460bfe9f0759e9844b3ce807cfb5`.
55
+ The Qwen3 base revision is `ebb281ec70b05090aa6165b016eac8ec08e71b17`.
56
+ Qwen3 adapters must not be loaded onto Qwen2.5 models or vice versa.
57
  The JSD and reverse-KL variants here are **LoRA adapters**, not full-parameter
58
  fine-tuning variants. The GRPO checkpoint is the final policy at 2560 optimizer
59
  updates after 10240 processed questions; these units are not interchangeable.
 
98
  python -m pip install -r third_party/VLMEvalKit/requirements.txt
99
  python -m pip install -r requirements.txt
100
  python -m pip install 'flash-attn==2.8.3' --no-build-isolation
101
+ export RUNTIME=eval # Use qwen3 for qwen3-vl-4b-scopd or qwen3-vl-4b-scopd-plus
102
+ python runtime/prepare.py --mode "$RUNTIME"
103
+ source runtime/activate.sh "$RUNTIME"
104
  ```
105
 
106
+ For Qwen2.5, installing an unmodified `transformers==4.57.0` alone is not sufficient
107
+ for VisionZip: the preparer verifies and applies the evaluation overlays.
108
+ For Qwen3, it builds an **isolated stock** Transformers 4.57.0 tree; the included
109
+ Qwen3 VisionZip wrapper handles token selection, contextual merging, DeepStack
110
+ features and position IDs without Qwen2.5 overlays. Do not mix these runtimes
111
+ within one Python process. A different
112
  Pillow implementation can change image preprocessing: consult
113
  [environment details](evaluation/docs/ENVIRONMENT.md) before a numerical
114
  reproduction attempt. The listed environment is a source-version specification,
 
120
  evaluation**. This preparation step is not training, and does not upload a
121
  merged model. The default CPU merge needs enough host RAM for the base model
122
  and merge buffers; use `--device cuda` only on an available GPU with sufficient
123
+ memory. Allow approximately 16 GiB of disk for Qwen2.5 or 9 GiB for Qwen3.
124
 
125
  ```bash
126
  export MERGED_MODEL="$RELEASE_DIR/local-merged/$VARIANT"
 
129
  --output "$MERGED_MODEL"
130
  ```
131
 
132
+ The helper reads the correct base model and revision from the adapter's
133
+ provenance automatically. Alternatively, `--base-model` can point to an already
134
+ downloaded Hub snapshot directory named by that base model's pinned revision.
135
  For direct PEFT inference, the same adapter can be loaded onto that base using
136
  `PeftModel.from_pretrained`; the benchmark runner below uses a merged model.
137
 
 
147
 
148
  Use `--retention 0.20` or `0.30` for milder pruning, and `--retention 1`
149
  for no pruning. The argument is **retention**, not the backend's
150
+ `visionzip_ratio` parameter. The runner detects the model family from
151
+ `config.json`. Greedy inference uses `<think>...</think><answer>...</answer>`
152
+ for Qwen2.5 and **`<analysis>...</analysis><answer>...</answer>` for Qwen3**,
153
+ at most 2048 generated tokens, and image bounds of 1280 to 4096 nominal visual
154
+ tokens. A nominal token corresponds to 28x28 input pixels for Qwen2.5 and
155
+ 32x32 for Qwen3; these budgets are not interchangeable pixel counts.
156
+
157
+ For Qwen3, choose `VARIANT=qwen3-vl-4b-scopd` or
158
+ `VARIANT=qwen3-vl-4b-scopd-plus` in the download command and `RUNTIME=qwen3`
159
+ in the environment command. All other merge, inference and judging commands
160
+ are unchanged. The Qwen3 checkpoints are the final student adapters after
161
+ 10240 processed questions (320 optimizer updates), not teacher/EMA weights.
162
+ Their original rollout cap was 512; the evaluation cap above is 2048.
163
+ The included Qwen3 runner supports images, including multi-image questions,
164
+ but does not support video pruning.
165
 
166
  Supported image tasks include MME, MMStar, MathVista-MINI,
167
  MathVerse-MINI-Vision-Only, MMMU-Pro-4c, HallusionBench, CVBench,
 
227
  ## License
228
 
229
  The weights are derivatives of
230
+ [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) and
231
+ [Qwen3-VL-4B-Instruct](https://huggingface.co/Qwen/Qwen3-VL-4B-Instruct),
232
+ whose pinned model cards specify Apache-2.0. See [LICENSE](LICENSE) and
233
  [NOTICE](NOTICE). Third-party evaluation and pruning implementations retain
234
  their individual licenses and source notices.
checksums.sha256 CHANGED
@@ -1,14 +1,14 @@
1
  ee05350c7fda0af4da116020dd7b976d731de3beed4f5e717d5bcc95ead24550 .gitattributes
2
  cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 LICENSE
3
- 535b5b80a45db2234137dd7f5a181b836bf31cb30e4713441787e35001ab079e NOTICE
4
- 5765cd5570891a6c6f226b352844939e63c492dadfeb75bc0e8b8b4f9d8fa308 README.md
5
- 9efc63737203452d1c0901f88712f87ff427012d79c5ac4032e0a078d4481c04 evaluation/docs/ENVIRONMENT.md
6
  f8d94e39b5322630beec7a0ec4ff016cd53ff2f7b6571adf074ebb8531f2a077 evaluation/docs/EVALUATION.md
7
- a3a80ce62dd8cb734cbae860ac95f16543655429eb1a2971da6b62ee8f601f1c evaluation/evaluation_files.json
8
  1635705d53c8f42923a9ff5611dbaef58bce99e76f9efc6f78408679d8798167 evaluation/requirements-judge.txt
9
  b244b1d0e7e81eb0c22b21e6fe9d933fe1e5383ad624a79254efff26126ca25b evaluation/requirements.txt
10
  77fd4710def9ec3c0f6225800e0235f15a425abd4a8b03559127fcd782612049 evaluation/runtime/TRANSFORMERS_LICENSE
11
- cfd538bb9491cb09e8e80d2c6fa5ac9c4b8da136eb111ab8619ddbbe5c2182c4 evaluation/runtime/activate.sh
12
  56022bcfa60a56d3b161cfbe05da6df8c82fe504be4298424d5b2d4807cf714e evaluation/runtime/manifest.json
13
  9acc5ad5be42eec3661c899a5ef1b37d076f3f2c64eb992998ce5198862e05fc evaluation/runtime/overlays/eval/transformers/generation/utils.py
14
  274a6a261437673efcb4ba76f4a78304ed6245e3a1f200376137090bdcb9c8de evaluation/runtime/overlays/eval/transformers/integrations/flash_attention.py
@@ -16,21 +16,26 @@ cfd538bb9491cb09e8e80d2c6fa5ac9c4b8da136eb111ab8619ddbbe5c2182c4 evaluation/run
16
  81e1e76eff4d476bf7a56fe57295cd4cfb8b826a8b7d1ed4ab8ee49e5757dc8f evaluation/runtime/overlays/eval/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py
17
  96ac412e70cfe2d883a6741884ab550d31c45fbdc5cd7e4af3e29cff1cb9c5e3 evaluation/runtime/overlays/eval/transformers/models/qwen3/modeling_qwen3.py
18
  e0186fd3a226eed289e29ea0d993d3e7ab9eb4c5f83a2c1b02c67b0260964203 evaluation/runtime/overlays/eval/transformers/models/qwen3_vl/modeling_qwen3_vl.py
19
- 3c9f5e7ea885fc5ce541661c00ca55895af5268befe651d28b128e7d49581dde evaluation/runtime/prepare.py
20
  83acfb0a675e508ba26f75db1d2b54d9d44ff070d508164e7d6db745b5835186 evaluation/scopd_eval/__init__.py
21
  50748efd441c4444379ce202a2a0603704d4dd206a8220a0616638972fea07d4 evaluation/scopd_eval/datasets.py
22
  a75d3fc461a0001be51705766de8e12ab40f8f09aec20f1154e3f7e3bcb33fcb evaluation/scopd_eval/import_results.py
23
- 211cb7a8613314142f14f8b29239ecac01b385df04827f478b982a836ba3d005 evaluation/scopd_eval/infer.py
24
  d2e53fc11205ec901d7db118c1ef07d65ac73ed651a962b2462ff3b33a218923 evaluation/scopd_eval/merge_shards.py
25
  70f77ae60dfdf2b0bd685aad0a8e9b61f1a28bb71e249e8d54bbc8d9f69687dc evaluation/scopd_eval/postprocess.py
26
  55a5d90cbd4691caa6111b543f64359c8eda9e2f7c2e069b1f655cd559577052 evaluation/scopd_eval/protocol.py
 
 
 
 
27
  9e13bd023c283bb9b7450cf3786fce053f644bc4e35f466801c419dcfd332067 evaluation/scopd_eval/runtime.py
28
  2798e75251f7af9d2bc76b1e44a62e59af663d940b0d3cf847c1c0dda6bdc287 evaluation/scopd_eval/runtime_fixes.py
29
  02ab55377f918383106e8070d87ac9ed6d42973281ff60aa7ce07dc1cc12cffe evaluation/scopd_eval/scoring.py
30
  1a8dd36e9c84c9b35fd1bfb278d9bd03d4ad8f7b207490ead92a36dab73d21e3 evaluation/scopd_eval/visionzip_memory.py
31
- 0943ea820dc8ca33d8e7f55bd02accd8f105d0f8f8d19f0fed6ad5841d4fbdb2 evaluation/scripts/merge_adapter.py
32
  6e4105783d0b3f91850e8fccadf644d0758704afb93284bc84228ccee0f3fa9e evaluation/scripts/serve_judge.sh
33
  830f58b7aa581f0aba7250dbef9e69ad03aaff7cc21ddd639c0f21611f172989 evaluation/tests/test_merge_shards.py
 
34
  84441752e5beaa454abd28d28c0b7c4b553a2354c4a699de488f42ab88f769cb evaluation/tests/test_unified_postprocess.py
35
  5f0538b314b13e062d1fed3991ec1868cc71c49d0838cd7bc6ef563be06a5ad3 evaluation/third_party/VLMEvalKit/LICENSE
36
  e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 evaluation/third_party/VLMEvalKit/internvl/__init__.py
@@ -634,6 +639,14 @@ fa6ea8ec1a8ce4b0bc33ae553ece32ea9463e6aa8d96e1dfc8cea0ec8e0922d0 models/grpo/RE
634
  2dfbb58879d248ccdcb2fd1bb973d5eb27684b79e39efe18ea493c76482389ed models/grpo/adapter_config.json
635
  c38704d69eb2e1ac0164d9ec1be644d42449ff80eb130175855550c94745bcf4 models/grpo/adapter_model.safetensors
636
  8040d0f259ea6ba67b2e17b010592d80905aa431690456aadb768b0a3af5c64d models/grpo/provenance.json
 
 
 
 
 
 
 
 
637
  26ad07ef327929b6499b45f1ea646151bba4ae400cf3a003f919305a5637416e models/scopd/README.md
638
  8d012710233093a920bdb40f6dd9b4b7b9945886fe9786883497e272c3392a6d models/scopd/adapter_config.json
639
  0f882974e3e8565c7d9a99494e11289736c384e0d60fb9ba9e20ed5417a7b6a9 models/scopd/adapter_model.safetensors
@@ -670,4 +683,4 @@ c02297cfe2fcd3ab01d769d0aca53cb4a3bb43dba6892895ecc282f23b053b3a models/scopd-p
670
  d351288f33412329d8a889e2422e5150cbc8c2077e746635547c793f28713699 models/sft/adapter_config.json
671
  9463250e17a196055c2f54e205587c7e727c3b5b6b7a30eb3158c5967ccb9f8e models/sft/adapter_model.safetensors
672
  bbb618f71b051db4a0bdef4bb2b6e2bf04d2be588a8347665dca1a62661beb62 models/sft/provenance.json
673
- 1c32cf7ff5d6e9402b127c95bea01d4b016ed2cfed0bb04b13c77d07fbd627a4 models.json
 
1
  ee05350c7fda0af4da116020dd7b976d731de3beed4f5e717d5bcc95ead24550 .gitattributes
2
  cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 LICENSE
3
+ b1211bce16e9e14d263d50fd792174b547ea9b617623ca50dfba617a15ee75d8 NOTICE
4
+ 52684b301366310b1fd39b00b58d715a98e0b44131446c303bbdb1678ebc348b README.md
5
+ 6e175bf5c51e905079778c75b51c47bce42842025d7badb1e569af4e76f68d77 evaluation/docs/ENVIRONMENT.md
6
  f8d94e39b5322630beec7a0ec4ff016cd53ff2f7b6571adf074ebb8531f2a077 evaluation/docs/EVALUATION.md
7
+ 267eb3fb2f84f1a552df9f95149347642c3c3ef40b39cc059b61be53f61d617c evaluation/evaluation_files.json
8
  1635705d53c8f42923a9ff5611dbaef58bce99e76f9efc6f78408679d8798167 evaluation/requirements-judge.txt
9
  b244b1d0e7e81eb0c22b21e6fe9d933fe1e5383ad624a79254efff26126ca25b evaluation/requirements.txt
10
  77fd4710def9ec3c0f6225800e0235f15a425abd4a8b03559127fcd782612049 evaluation/runtime/TRANSFORMERS_LICENSE
11
+ 0b5ca4aa076a961a49a455ca5a3c7b4069918bc49952aeb05f249cee4f32ff75 evaluation/runtime/activate.sh
12
  56022bcfa60a56d3b161cfbe05da6df8c82fe504be4298424d5b2d4807cf714e evaluation/runtime/manifest.json
13
  9acc5ad5be42eec3661c899a5ef1b37d076f3f2c64eb992998ce5198862e05fc evaluation/runtime/overlays/eval/transformers/generation/utils.py
14
  274a6a261437673efcb4ba76f4a78304ed6245e3a1f200376137090bdcb9c8de evaluation/runtime/overlays/eval/transformers/integrations/flash_attention.py
 
16
  81e1e76eff4d476bf7a56fe57295cd4cfb8b826a8b7d1ed4ab8ee49e5757dc8f evaluation/runtime/overlays/eval/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py
17
  96ac412e70cfe2d883a6741884ab550d31c45fbdc5cd7e4af3e29cff1cb9c5e3 evaluation/runtime/overlays/eval/transformers/models/qwen3/modeling_qwen3.py
18
  e0186fd3a226eed289e29ea0d993d3e7ab9eb4c5f83a2c1b02c67b0260964203 evaluation/runtime/overlays/eval/transformers/models/qwen3_vl/modeling_qwen3_vl.py
19
+ 423a00c3d6f693d3589632c65687767bac17936c32782143a2c7fd8078329436 evaluation/runtime/prepare.py
20
  83acfb0a675e508ba26f75db1d2b54d9d44ff070d508164e7d6db745b5835186 evaluation/scopd_eval/__init__.py
21
  50748efd441c4444379ce202a2a0603704d4dd206a8220a0616638972fea07d4 evaluation/scopd_eval/datasets.py
22
  a75d3fc461a0001be51705766de8e12ab40f8f09aec20f1154e3f7e3bcb33fcb evaluation/scopd_eval/import_results.py
23
+ 79c9db6faf179b3666d47665ee2a34eb9d90b5dcf9e023cc3cd7538277b6b521 evaluation/scopd_eval/infer.py
24
  d2e53fc11205ec901d7db118c1ef07d65ac73ed651a962b2462ff3b33a218923 evaluation/scopd_eval/merge_shards.py
25
  70f77ae60dfdf2b0bd685aad0a8e9b61f1a28bb71e249e8d54bbc8d9f69687dc evaluation/scopd_eval/postprocess.py
26
  55a5d90cbd4691caa6111b543f64359c8eda9e2f7c2e069b1f655cd559577052 evaluation/scopd_eval/protocol.py
27
+ 39a2d06deedada40e4c1237151e92d150f7b1f8cabe04278fa59b5e87b260c6b evaluation/scopd_eval/qwen3_helpers.py
28
+ e010746c793dc0a3df1c68c192de6c7891384526346bc6e458587aaf15bb8539 evaluation/scopd_eval/qwen3_runtime.py
29
+ d29fd96ef58b9c0bf12866a5f300c9563077b7b842fad24db7c0c51d39286a5e evaluation/scopd_eval/qwen3_visionzip.py
30
+ ecd26b10e973c1b05f7737dad022405bd76ec121694f5c08203bd488326f07e1 evaluation/scopd_eval/qwen3_wrapper.py
31
  9e13bd023c283bb9b7450cf3786fce053f644bc4e35f466801c419dcfd332067 evaluation/scopd_eval/runtime.py
32
  2798e75251f7af9d2bc76b1e44a62e59af663d940b0d3cf847c1c0dda6bdc287 evaluation/scopd_eval/runtime_fixes.py
33
  02ab55377f918383106e8070d87ac9ed6d42973281ff60aa7ce07dc1cc12cffe evaluation/scopd_eval/scoring.py
34
  1a8dd36e9c84c9b35fd1bfb278d9bd03d4ad8f7b207490ead92a36dab73d21e3 evaluation/scopd_eval/visionzip_memory.py
35
+ db17b84ba74b42cc1decc3721766e8fc3afaed5c1c810335c0edb25791911911 evaluation/scripts/merge_adapter.py
36
  6e4105783d0b3f91850e8fccadf644d0758704afb93284bc84228ccee0f3fa9e evaluation/scripts/serve_judge.sh
37
  830f58b7aa581f0aba7250dbef9e69ad03aaff7cc21ddd639c0f21611f172989 evaluation/tests/test_merge_shards.py
38
+ 72116c1989c853d7131b3cb7141e5dd04f8d2d19f5d4c5736639a676cebb58c3 evaluation/tests/test_qwen3_release.py
39
  84441752e5beaa454abd28d28c0b7c4b553a2354c4a699de488f42ab88f769cb evaluation/tests/test_unified_postprocess.py
40
  5f0538b314b13e062d1fed3991ec1868cc71c49d0838cd7bc6ef563be06a5ad3 evaluation/third_party/VLMEvalKit/LICENSE
41
  e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 evaluation/third_party/VLMEvalKit/internvl/__init__.py
 
639
  2dfbb58879d248ccdcb2fd1bb973d5eb27684b79e39efe18ea493c76482389ed models/grpo/adapter_config.json
640
  c38704d69eb2e1ac0164d9ec1be644d42449ff80eb130175855550c94745bcf4 models/grpo/adapter_model.safetensors
641
  8040d0f259ea6ba67b2e17b010592d80905aa431690456aadb768b0a3af5c64d models/grpo/provenance.json
642
+ 58228a06633d4edb621e42d92d3e7d3178d7d8de1808cbd20bdab772211cfe8d models/qwen3-vl-4b-scopd/README.md
643
+ 1ab144e6d1bef280eb631857163ef118bd1f75f0d6659a1bf4ae122404ed31f7 models/qwen3-vl-4b-scopd/adapter_config.json
644
+ 6aec6fba5176359d4d1a3d906d3722a51b9f7f21c79d5d5989120b075915102f models/qwen3-vl-4b-scopd/adapter_model.safetensors
645
+ 873530c48f2adb851bc9e3832338192cbb482df3ef8289d6c762cef2c9816f17 models/qwen3-vl-4b-scopd/provenance.json
646
+ fa8a0a1e2f2c31e3b640bf8a7dd3cbf89d2f1e805c6f92c29bfd88603f1eaefe models/qwen3-vl-4b-scopd-plus/README.md
647
+ 6976ea2058017a628bdef3fddd771bc4b235f104e9d1eb26baec20bc4fd9f9f6 models/qwen3-vl-4b-scopd-plus/adapter_config.json
648
+ febccb411829f5c314d421038c1cd89dcc543df074978778771504ab1dc91a0e models/qwen3-vl-4b-scopd-plus/adapter_model.safetensors
649
+ 8c79926410dbb58b5c503b49d75a4cd32d53a985b31cb7c7d15e91aad238ff6a models/qwen3-vl-4b-scopd-plus/provenance.json
650
  26ad07ef327929b6499b45f1ea646151bba4ae400cf3a003f919305a5637416e models/scopd/README.md
651
  8d012710233093a920bdb40f6dd9b4b7b9945886fe9786883497e272c3392a6d models/scopd/adapter_config.json
652
  0f882974e3e8565c7d9a99494e11289736c384e0d60fb9ba9e20ed5417a7b6a9 models/scopd/adapter_model.safetensors
 
683
  d351288f33412329d8a889e2422e5150cbc8c2077e746635547c793f28713699 models/sft/adapter_config.json
684
  9463250e17a196055c2f54e205587c7e727c3b5b6b7a30eb3158c5967ccb9f8e models/sft/adapter_model.safetensors
685
  bbb618f71b051db4a0bdef4bb2b6e2bf04d2be588a8347665dca1a62661beb62 models/sft/provenance.json
686
+ 68d1699f0aab3aae6fc10b0c06a548b06dc8640f5ec56f415d5713aead128514 models.json
evaluation/docs/ENVIRONMENT.md CHANGED
@@ -6,7 +6,7 @@ Use Python 3.11 and Linux with an allocated CUDA GPU.
6
  |---|---|
7
  | torch | 2.9.1, CUDA 12.6 |
8
  | torchvision | 0.24.1 |
9
- | Transformers | 4.57.0 plus the included evaluation overlays |
10
  | tokenizers | 0.22.2 |
11
  | huggingface-hub | 0.34.3 |
12
  | peft | 0.18.1 |
@@ -27,7 +27,15 @@ not redistributed as a portable wheel.
27
  `runtime/prepare.py --mode eval` reconstructs the patched Transformers tree
28
  from a SHA256-pinned wheel and six overlays. The exact version is intentionally
29
  pinned even though that upstream version was yanked. Do not substitute stock
30
- Transformers for the patched runtime when evaluating VisionZip.
 
 
 
 
 
 
 
 
31
 
32
  The judge uses a **separate** environment: vLLM 0.25.1 with torch 2.11.0+cu130
33
  and Qwen3.6-27B-FP8. Do not activate the evaluation source override in that
 
6
  |---|---|
7
  | torch | 2.9.1, CUDA 12.6 |
8
  | torchvision | 0.24.1 |
9
+ | Transformers | 4.57.0; Qwen2.5 uses evaluation overlays, Qwen3 uses an isolated stock tree |
10
  | tokenizers | 0.22.2 |
11
  | huggingface-hub | 0.34.3 |
12
  | peft | 0.18.1 |
 
27
  `runtime/prepare.py --mode eval` reconstructs the patched Transformers tree
28
  from a SHA256-pinned wheel and six overlays. The exact version is intentionally
29
  pinned even though that upstream version was yanked. Do not substitute stock
30
+ Transformers for the patched Qwen2.5 runtime when evaluating VisionZip.
31
+
32
+ For Qwen3, use `runtime/prepare.py --mode qwen3` and
33
+ `source runtime/activate.sh qwen3`. This extracts the same pinned wheel without
34
+ applying the Qwen2.5 overlays. Qwen3's native VisionZip wrapper is exported from
35
+ the evaluated implementation, including synchronized DeepStack feature pruning.
36
+ Use a fresh Python process when switching model families. Qwen3 inference uses
37
+ `<analysis>` tags and 32x32 pixels per nominal visual token, rather than the
38
+ Qwen2.5 `<think>` tags and 28x28 pixel unit.
39
 
40
  The judge uses a **separate** environment: vLLM 0.25.1 with torch 2.11.0+cu130
41
  and Qwen3.6-27B-FP8. Do not activate the evaluation source override in that
evaluation/evaluation_files.json CHANGED
@@ -1,12 +1,12 @@
1
  {
2
  "source_revision": "8c42b34e4798a61f8c7cfb5e079fd4963acb734a",
3
  "files": {
4
- "docs/ENVIRONMENT.md": "9efc63737203452d1c0901f88712f87ff427012d79c5ac4032e0a078d4481c04",
5
  "docs/EVALUATION.md": "f8d94e39b5322630beec7a0ec4ff016cd53ff2f7b6571adf074ebb8531f2a077",
6
  "requirements-judge.txt": "1635705d53c8f42923a9ff5611dbaef58bce99e76f9efc6f78408679d8798167",
7
  "requirements.txt": "b244b1d0e7e81eb0c22b21e6fe9d933fe1e5383ad624a79254efff26126ca25b",
8
  "runtime/TRANSFORMERS_LICENSE": "77fd4710def9ec3c0f6225800e0235f15a425abd4a8b03559127fcd782612049",
9
- "runtime/activate.sh": "cfd538bb9491cb09e8e80d2c6fa5ac9c4b8da136eb111ab8619ddbbe5c2182c4",
10
  "runtime/manifest.json": "56022bcfa60a56d3b161cfbe05da6df8c82fe504be4298424d5b2d4807cf714e",
11
  "runtime/overlays/eval/transformers/generation/utils.py": "9acc5ad5be42eec3661c899a5ef1b37d076f3f2c64eb992998ce5198862e05fc",
12
  "runtime/overlays/eval/transformers/integrations/flash_attention.py": "274a6a261437673efcb4ba76f4a78304ed6245e3a1f200376137090bdcb9c8de",
@@ -14,21 +14,26 @@
14
  "runtime/overlays/eval/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py": "81e1e76eff4d476bf7a56fe57295cd4cfb8b826a8b7d1ed4ab8ee49e5757dc8f",
15
  "runtime/overlays/eval/transformers/models/qwen3/modeling_qwen3.py": "96ac412e70cfe2d883a6741884ab550d31c45fbdc5cd7e4af3e29cff1cb9c5e3",
16
  "runtime/overlays/eval/transformers/models/qwen3_vl/modeling_qwen3_vl.py": "e0186fd3a226eed289e29ea0d993d3e7ab9eb4c5f83a2c1b02c67b0260964203",
17
- "runtime/prepare.py": "3c9f5e7ea885fc5ce541661c00ca55895af5268befe651d28b128e7d49581dde",
18
  "scopd_eval/__init__.py": "83acfb0a675e508ba26f75db1d2b54d9d44ff070d508164e7d6db745b5835186",
19
  "scopd_eval/datasets.py": "50748efd441c4444379ce202a2a0603704d4dd206a8220a0616638972fea07d4",
20
  "scopd_eval/import_results.py": "a75d3fc461a0001be51705766de8e12ab40f8f09aec20f1154e3f7e3bcb33fcb",
21
- "scopd_eval/infer.py": "211cb7a8613314142f14f8b29239ecac01b385df04827f478b982a836ba3d005",
22
  "scopd_eval/merge_shards.py": "d2e53fc11205ec901d7db118c1ef07d65ac73ed651a962b2462ff3b33a218923",
23
  "scopd_eval/postprocess.py": "70f77ae60dfdf2b0bd685aad0a8e9b61f1a28bb71e249e8d54bbc8d9f69687dc",
24
  "scopd_eval/protocol.py": "55a5d90cbd4691caa6111b543f64359c8eda9e2f7c2e069b1f655cd559577052",
 
 
 
 
25
  "scopd_eval/runtime.py": "9e13bd023c283bb9b7450cf3786fce053f644bc4e35f466801c419dcfd332067",
26
  "scopd_eval/runtime_fixes.py": "2798e75251f7af9d2bc76b1e44a62e59af663d940b0d3cf847c1c0dda6bdc287",
27
  "scopd_eval/scoring.py": "02ab55377f918383106e8070d87ac9ed6d42973281ff60aa7ce07dc1cc12cffe",
28
  "scopd_eval/visionzip_memory.py": "1a8dd36e9c84c9b35fd1bfb278d9bd03d4ad8f7b207490ead92a36dab73d21e3",
29
- "scripts/merge_adapter.py": "0943ea820dc8ca33d8e7f55bd02accd8f105d0f8f8d19f0fed6ad5841d4fbdb2",
30
  "scripts/serve_judge.sh": "6e4105783d0b3f91850e8fccadf644d0758704afb93284bc84228ccee0f3fa9e",
31
  "tests/test_merge_shards.py": "830f58b7aa581f0aba7250dbef9e69ad03aaff7cc21ddd639c0f21611f172989",
 
32
  "tests/test_unified_postprocess.py": "84441752e5beaa454abd28d28c0b7c4b553a2354c4a699de488f42ab88f769cb",
33
  "third_party/VLMEvalKit/LICENSE": "5f0538b314b13e062d1fed3991ec1868cc71c49d0838cd7bc6ef563be06a5ad3",
34
  "third_party/VLMEvalKit/internvl/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
 
1
  {
2
  "source_revision": "8c42b34e4798a61f8c7cfb5e079fd4963acb734a",
3
  "files": {
4
+ "docs/ENVIRONMENT.md": "6e175bf5c51e905079778c75b51c47bce42842025d7badb1e569af4e76f68d77",
5
  "docs/EVALUATION.md": "f8d94e39b5322630beec7a0ec4ff016cd53ff2f7b6571adf074ebb8531f2a077",
6
  "requirements-judge.txt": "1635705d53c8f42923a9ff5611dbaef58bce99e76f9efc6f78408679d8798167",
7
  "requirements.txt": "b244b1d0e7e81eb0c22b21e6fe9d933fe1e5383ad624a79254efff26126ca25b",
8
  "runtime/TRANSFORMERS_LICENSE": "77fd4710def9ec3c0f6225800e0235f15a425abd4a8b03559127fcd782612049",
9
+ "runtime/activate.sh": "0b5ca4aa076a961a49a455ca5a3c7b4069918bc49952aeb05f249cee4f32ff75",
10
  "runtime/manifest.json": "56022bcfa60a56d3b161cfbe05da6df8c82fe504be4298424d5b2d4807cf714e",
11
  "runtime/overlays/eval/transformers/generation/utils.py": "9acc5ad5be42eec3661c899a5ef1b37d076f3f2c64eb992998ce5198862e05fc",
12
  "runtime/overlays/eval/transformers/integrations/flash_attention.py": "274a6a261437673efcb4ba76f4a78304ed6245e3a1f200376137090bdcb9c8de",
 
14
  "runtime/overlays/eval/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py": "81e1e76eff4d476bf7a56fe57295cd4cfb8b826a8b7d1ed4ab8ee49e5757dc8f",
15
  "runtime/overlays/eval/transformers/models/qwen3/modeling_qwen3.py": "96ac412e70cfe2d883a6741884ab550d31c45fbdc5cd7e4af3e29cff1cb9c5e3",
16
  "runtime/overlays/eval/transformers/models/qwen3_vl/modeling_qwen3_vl.py": "e0186fd3a226eed289e29ea0d993d3e7ab9eb4c5f83a2c1b02c67b0260964203",
17
+ "runtime/prepare.py": "423a00c3d6f693d3589632c65687767bac17936c32782143a2c7fd8078329436",
18
  "scopd_eval/__init__.py": "83acfb0a675e508ba26f75db1d2b54d9d44ff070d508164e7d6db745b5835186",
19
  "scopd_eval/datasets.py": "50748efd441c4444379ce202a2a0603704d4dd206a8220a0616638972fea07d4",
20
  "scopd_eval/import_results.py": "a75d3fc461a0001be51705766de8e12ab40f8f09aec20f1154e3f7e3bcb33fcb",
21
+ "scopd_eval/infer.py": "79c9db6faf179b3666d47665ee2a34eb9d90b5dcf9e023cc3cd7538277b6b521",
22
  "scopd_eval/merge_shards.py": "d2e53fc11205ec901d7db118c1ef07d65ac73ed651a962b2462ff3b33a218923",
23
  "scopd_eval/postprocess.py": "70f77ae60dfdf2b0bd685aad0a8e9b61f1a28bb71e249e8d54bbc8d9f69687dc",
24
  "scopd_eval/protocol.py": "55a5d90cbd4691caa6111b543f64359c8eda9e2f7c2e069b1f655cd559577052",
25
+ "scopd_eval/qwen3_helpers.py": "39a2d06deedada40e4c1237151e92d150f7b1f8cabe04278fa59b5e87b260c6b",
26
+ "scopd_eval/qwen3_runtime.py": "e010746c793dc0a3df1c68c192de6c7891384526346bc6e458587aaf15bb8539",
27
+ "scopd_eval/qwen3_visionzip.py": "d29fd96ef58b9c0bf12866a5f300c9563077b7b842fad24db7c0c51d39286a5e",
28
+ "scopd_eval/qwen3_wrapper.py": "ecd26b10e973c1b05f7737dad022405bd76ec121694f5c08203bd488326f07e1",
29
  "scopd_eval/runtime.py": "9e13bd023c283bb9b7450cf3786fce053f644bc4e35f466801c419dcfd332067",
30
  "scopd_eval/runtime_fixes.py": "2798e75251f7af9d2bc76b1e44a62e59af663d940b0d3cf847c1c0dda6bdc287",
31
  "scopd_eval/scoring.py": "02ab55377f918383106e8070d87ac9ed6d42973281ff60aa7ce07dc1cc12cffe",
32
  "scopd_eval/visionzip_memory.py": "1a8dd36e9c84c9b35fd1bfb278d9bd03d4ad8f7b207490ead92a36dab73d21e3",
33
+ "scripts/merge_adapter.py": "db17b84ba74b42cc1decc3721766e8fc3afaed5c1c810335c0edb25791911911",
34
  "scripts/serve_judge.sh": "6e4105783d0b3f91850e8fccadf644d0758704afb93284bc84228ccee0f3fa9e",
35
  "tests/test_merge_shards.py": "830f58b7aa581f0aba7250dbef9e69ad03aaff7cc21ddd639c0f21611f172989",
36
+ "tests/test_qwen3_release.py": "72116c1989c853d7131b3cb7141e5dd04f8d2d19f5d4c5736639a676cebb58c3",
37
  "tests/test_unified_postprocess.py": "84441752e5beaa454abd28d28c0b7c4b553a2354c4a699de488f42ab88f769cb",
38
  "third_party/VLMEvalKit/LICENSE": "5f0538b314b13e062d1fed3991ec1868cc71c49d0838cd7bc6ef563be06a5ad3",
39
  "third_party/VLMEvalKit/internvl/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
evaluation/runtime/activate.sh CHANGED
@@ -1,15 +1,16 @@
1
  #!/usr/bin/env bash
2
  # Source this file from an activated evaluation environment.
3
  _scopd_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
4
- if [[ "${1:-eval}" != eval ]]; then
5
- printf 'This release provides the eval runtime only\n' >&2
 
6
  return 2
7
  fi
8
- if [[ ! -f "$_scopd_root/.runtime/eval/src/transformers/__init__.py" ]]; then
9
- printf 'Run python runtime/prepare.py --mode eval first\n' >&2
10
  return 1
11
  fi
12
- export PATCHED_TRANSFORMERS_SRC="$_scopd_root/.runtime/eval/src"
13
  export VISIONZIP_QWEN25VL_ROOT="$_scopd_root/third_party/VisionZip/Qwen2_5_VL"
14
  export PYTHONPATH="$_scopd_root:$PATCHED_TRANSFORMERS_SRC:$_scopd_root/third_party/VLMEvalKit:$_scopd_root/third_party/VLMEvalKit/internvl${PYTHONPATH:+:$PYTHONPATH}"
15
  export TOKENIZERS_PARALLELISM=false PYTHONNOUSERSITE=1
@@ -18,4 +19,4 @@ export TMPDIR="${TMPDIR:-${SCRATCH:-$_scopd_root/.cache}/scopd/tmp}"
18
  export LMUData="${LMUData:-${SCRATCH:-$_scopd_root/.cache}/scopd/benchmarks}"
19
  export MMSTAR_QWEN_JUDGE=0 VLMEVAL_SAVE_RAW_PREDICTION=1 VLMEVAL_STRICT_ERRORS=1
20
  mkdir -p "$HF_HOME" "$TMPDIR" "$LMUData"
21
- unset _scopd_root
 
1
  #!/usr/bin/env bash
2
  # Source this file from an activated evaluation environment.
3
  _scopd_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
4
+ _scopd_mode=${1:-eval}
5
+ if [[ "$_scopd_mode" != eval && "$_scopd_mode" != qwen3 ]]; then
6
+ printf 'Choose eval (Qwen2.5) or qwen3\n' >&2
7
  return 2
8
  fi
9
+ if [[ ! -f "$_scopd_root/.runtime/$_scopd_mode/src/transformers/__init__.py" ]]; then
10
+ printf 'Run python runtime/prepare.py --mode %s first\n' "$_scopd_mode" >&2
11
  return 1
12
  fi
13
+ export PATCHED_TRANSFORMERS_SRC="$_scopd_root/.runtime/$_scopd_mode/src"
14
  export VISIONZIP_QWEN25VL_ROOT="$_scopd_root/third_party/VisionZip/Qwen2_5_VL"
15
  export PYTHONPATH="$_scopd_root:$PATCHED_TRANSFORMERS_SRC:$_scopd_root/third_party/VLMEvalKit:$_scopd_root/third_party/VLMEvalKit/internvl${PYTHONPATH:+:$PYTHONPATH}"
16
  export TOKENIZERS_PARALLELISM=false PYTHONNOUSERSITE=1
 
19
  export LMUData="${LMUData:-${SCRATCH:-$_scopd_root/.cache}/scopd/benchmarks}"
20
  export MMSTAR_QWEN_JUDGE=0 VLMEVAL_SAVE_RAW_PREDICTION=1 VLMEVAL_STRICT_ERRORS=1
21
  mkdir -p "$HF_HOME" "$TMPDIR" "$LMUData"
22
+ unset _scopd_root _scopd_mode
evaluation/runtime/prepare.py CHANGED
@@ -13,7 +13,7 @@ ROOT = Path(__file__).resolve().parents[1]
13
 
14
  def main():
15
  parser = argparse.ArgumentParser(description=__doc__)
16
- parser.add_argument('--mode', choices=['eval'], default='eval')
17
  parser.add_argument('--wheel', type=Path)
18
  args = parser.parse_args()
19
  manifest = json.loads((ROOT / 'runtime/manifest.json').read_text())
@@ -25,7 +25,8 @@ def main():
25
  '--dest', str(cache), 'transformers==4.57.0'], check=True)
26
  if hashlib.sha256(wheel.read_bytes()).hexdigest() != manifest['wheel_sha256']:
27
  raise ValueError('Transformers wheel hash mismatch')
28
- target = ROOT / '.runtime/eval/src'
 
29
  with ZipFile(wheel) as archive:
30
  for member in archive.infolist():
31
  if member.filename.startswith('transformers/') and not member.is_dir():
@@ -34,7 +35,12 @@ def main():
34
  dest = target / member.filename
35
  dest.parent.mkdir(parents=True, exist_ok=True)
36
  dest.write_bytes(archive.read(member))
37
- for relative, expected in manifest['overlays']['eval'].items():
 
 
 
 
 
38
  src = ROOT / 'runtime/overlays/eval' / relative
39
  if hashlib.sha256(src.read_bytes()).hexdigest() != expected:
40
  raise ValueError(f'Overlay hash mismatch: {relative}')
 
13
 
14
  def main():
15
  parser = argparse.ArgumentParser(description=__doc__)
16
+ parser.add_argument('--mode', choices=['eval', 'qwen3'], default='eval')
17
  parser.add_argument('--wheel', type=Path)
18
  args = parser.parse_args()
19
  manifest = json.loads((ROOT / 'runtime/manifest.json').read_text())
 
25
  '--dest', str(cache), 'transformers==4.57.0'], check=True)
26
  if hashlib.sha256(wheel.read_bytes()).hexdigest() != manifest['wheel_sha256']:
27
  raise ValueError('Transformers wheel hash mismatch')
28
+ target = ROOT / f'.runtime/{args.mode}/src'
29
+ source_hashes = {}
30
  with ZipFile(wheel) as archive:
31
  for member in archive.infolist():
32
  if member.filename.startswith('transformers/') and not member.is_dir():
 
35
  dest = target / member.filename
36
  dest.parent.mkdir(parents=True, exist_ok=True)
37
  dest.write_bytes(archive.read(member))
38
+ if args.mode == 'qwen3' and member.filename.endswith('.py'):
39
+ source_hashes[member.filename] = hashlib.sha256(archive.read(member)).hexdigest()
40
+ if args.mode == 'qwen3':
41
+ (target.parent / 'source_manifest.json').write_text(json.dumps({
42
+ 'wheel_sha256': manifest['wheel_sha256'], 'files': source_hashes}, indent=2) + '\n')
43
+ for relative, expected in (manifest['overlays']['eval'] if args.mode == 'eval' else {}).items():
44
  src = ROOT / 'runtime/overlays/eval' / relative
45
  if hashlib.sha256(src.read_bytes()).hexdigest() != expected:
46
  raise ValueError(f'Overlay hash mismatch: {relative}')
evaluation/scopd_eval/infer.py CHANGED
@@ -47,15 +47,28 @@ def main():
47
  if not (model_path / 'config.json').exists() or (model_path / 'adapter_config.json').exists():
48
  p.error('Supply a local pinned base or merged checkpoint, not an adapter')
49
  budget = visionzip_settings(a.retention)
50
- activate()
 
 
 
 
 
 
 
 
 
 
51
  import torch
52
  if not torch.cuda.is_available():
53
  raise RuntimeError('An allocated GPU is required for inference')
54
- from .runtime_fixes import install_wrapper
55
- from .visionzip_memory import install
56
- install_wrapper(video_timing=False)
57
- install()
58
- from vlmeval.vlm.qwen2_vl.model import Qwen2VLChat
 
 
 
59
  dataset = load(a.dataset)
60
  selected = dataset.data.iloc[a.shard::a.shards]
61
  if a.limit:
@@ -65,10 +78,13 @@ def main():
65
  'model_revision': a.model_revision, 'dataset': DATASETS[a.dataset],
66
  'retention': a.retention, **budget, 'sample_ids': ids,
67
  'shard': a.shard, 'shards': a.shards, 'limit': a.limit,
68
- 'max_new_tokens': a.max_new_tokens, 'min_pixels': a.min_image_tokens * 784,
69
- 'max_pixels': a.max_image_tokens * 784, 'greedy': True,
70
  'metadata_sha256': digest(selected.drop(columns=['image'], errors='ignore').astype(str).to_dict('records'))}
71
- work = a.output_dir / f'shard_{a.shard:03d}'
 
 
 
72
  work.mkdir(parents=True, exist_ok=True)
73
  with (work / '.infer.lock').open('w') as lock:
74
  fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
@@ -92,9 +108,15 @@ def main():
92
  torch.backends.cuda.matmul.allow_tf32 = True
93
  torch.backends.cudnn.allow_tf32 = True
94
  torch.manual_seed(42)
95
- model = Qwen2VLChat(model_path=str(model_path), temperature=0., enable_thinking=True,
96
- max_new_tokens=a.max_new_tokens, min_pixels=a.min_image_tokens * 784,
97
- max_pixels=a.max_image_tokens * 784, **budget)
 
 
 
 
 
 
98
  model.set_dump_image(dataset.dump_image)
99
  with path.open('a') as handle:
100
  for _, row in selected.iterrows():
 
47
  if not (model_path / 'config.json').exists() or (model_path / 'adapter_config.json').exists():
48
  p.error('Supply a local pinned base or merged checkpoint, not an adapter')
49
  budget = visionzip_settings(a.retention)
50
+ model_type = json.loads((model_path / 'config.json').read_text()).get('model_type')
51
+ if model_type not in {'qwen2_5_vl', 'qwen3_vl'}:
52
+ p.error('Only Qwen2.5-VL and Qwen3-VL image checkpoints are supported')
53
+ qwen3 = model_type == 'qwen3_vl'
54
+ if qwen3:
55
+ from .qwen3_runtime import activate as activate_qwen3
56
+ activate_qwen3()
57
+ budget = {'retention_ratio': a.retention}
58
+ else:
59
+ activate()
60
+ pixel_unit = 1024 if qwen3 else 784
61
  import torch
62
  if not torch.cuda.is_available():
63
  raise RuntimeError('An allocated GPU is required for inference')
64
+ if qwen3:
65
+ from .qwen3_wrapper import Qwen3VisionZipReasoning
66
+ else:
67
+ from .runtime_fixes import install_wrapper
68
+ from .visionzip_memory import install
69
+ install_wrapper(video_timing=False)
70
+ install()
71
+ from vlmeval.vlm.qwen2_vl.model import Qwen2VLChat
72
  dataset = load(a.dataset)
73
  selected = dataset.data.iloc[a.shard::a.shards]
74
  if a.limit:
 
78
  'model_revision': a.model_revision, 'dataset': DATASETS[a.dataset],
79
  'retention': a.retention, **budget, 'sample_ids': ids,
80
  'shard': a.shard, 'shards': a.shards, 'limit': a.limit,
81
+ 'max_new_tokens': a.max_new_tokens, 'min_pixels': a.min_image_tokens * pixel_unit,
82
+ 'max_pixels': a.max_image_tokens * pixel_unit, 'greedy': True,
83
  'metadata_sha256': digest(selected.drop(columns=['image'], errors='ignore').astype(str).to_dict('records'))}
84
+ if qwen3:
85
+ contract.update(model_family='qwen3_vl', reasoning_tag='analysis',
86
+ runtime='official-transformers-4.57.0-qwen3')
87
+ work = a.output_dir / f'shard_{a.shard:03d}'
88
  work.mkdir(parents=True, exist_ok=True)
89
  with (work / '.infer.lock').open('w') as lock:
90
  fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
 
108
  torch.backends.cuda.matmul.allow_tf32 = True
109
  torch.backends.cudnn.allow_tf32 = True
110
  torch.manual_seed(42)
111
+ if qwen3:
112
+ model = Qwen3VisionZipReasoning(
113
+ model_path=str(model_path), retention_ratio=a.retention,
114
+ min_visual_tokens=a.min_image_tokens, max_visual_tokens=a.max_image_tokens,
115
+ max_new_tokens=a.max_new_tokens, reasoning_prompt=True, reasoning_tag='analysis')
116
+ else:
117
+ model = Qwen2VLChat(model_path=str(model_path), temperature=0., enable_thinking=True,
118
+ max_new_tokens=a.max_new_tokens, min_pixels=a.min_image_tokens * pixel_unit,
119
+ max_pixels=a.max_image_tokens * pixel_unit, **budget)
120
  model.set_dump_image(dataset.dump_image)
121
  with path.open('a') as handle:
122
  for _, row in selected.iterrows():
evaluation/scopd_eval/qwen3_helpers.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import inspect
3
+ import re
4
+ from typing import Any
5
+ import torch
6
+
7
+ def _unwrap_qwen_model(model: Any) -> Any:
8
+ """Return the underlying Qwen2.5-VL module when wrapped by PEFT."""
9
+ candidates = [model]
10
+ seen: set[int] = set()
11
+ for candidate in candidates:
12
+ if id(candidate) in seen:
13
+ continue
14
+ seen.add(id(candidate))
15
+ config = getattr(candidate, 'config', None)
16
+ has_image_token = config is not None and hasattr(config, 'image_token_id')
17
+ has_visual = hasattr(candidate, 'visual') or hasattr(getattr(candidate, 'model', None), 'visual')
18
+ if has_image_token and (has_visual or hasattr(candidate, 'get_rope_index')):
19
+ return candidate
20
+ if hasattr(candidate, 'get_base_model'):
21
+ try:
22
+ child = candidate.get_base_model()
23
+ if child is not None:
24
+ candidates.append(child)
25
+ except TypeError:
26
+ pass
27
+ for attr in ('module', 'base_model', 'model'):
28
+ child = getattr(candidate, attr, None)
29
+ if child is not None:
30
+ candidates.append(child)
31
+ return model
32
+
33
+ def compute_full_position_ids(model: Any, input_ids: torch.Tensor, image_grid_thw: torch.Tensor | None, video_grid_thw: torch.Tensor | None, attention_mask: torch.Tensor | None, second_per_grid_ts: torch.Tensor | None=None, mm_token_type_ids: torch.Tensor | None=None) -> torch.Tensor:
34
+ """Compute full-token Qwen2.5-VL MRoPE position ids."""
35
+ qwen = _unwrap_qwen_model(model)
36
+ get_rope_index = getattr(qwen, 'get_rope_index', None)
37
+ if get_rope_index is None:
38
+ get_rope_index = getattr(getattr(qwen, 'model', None), 'get_rope_index', None)
39
+ if get_rope_index is None:
40
+ if attention_mask is None:
41
+ batch, seq_len = input_ids.shape
42
+ return torch.arange(seq_len, device=input_ids.device).view(1, 1, -1).expand(3, batch, -1)
43
+ position_ids = attention_mask.long().cumsum(-1) - 1
44
+ position_ids.masked_fill_(attention_mask == 0, 1)
45
+ return position_ids.unsqueeze(0).expand(3, -1, -1)
46
+ signature = inspect.signature(get_rope_index)
47
+ if 'mm_token_type_ids' in signature.parameters:
48
+ if mm_token_type_ids is None:
49
+ mm_token_type_ids = torch.zeros_like(input_ids)
50
+ image_token_id = getattr(getattr(qwen, 'config', None), 'image_token_id', None)
51
+ video_token_id = getattr(getattr(qwen, 'config', None), 'video_token_id', None)
52
+ if image_token_id is not None:
53
+ mm_token_type_ids = mm_token_type_ids.masked_fill(input_ids == int(image_token_id), 1)
54
+ if video_token_id is not None:
55
+ mm_token_type_ids = mm_token_type_ids.masked_fill(input_ids == int(video_token_id), 2)
56
+ position_ids, _ = get_rope_index(input_ids=input_ids, mm_token_type_ids=mm_token_type_ids.to(device=input_ids.device), image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, second_per_grid_ts=second_per_grid_ts, attention_mask=attention_mask)
57
+ return position_ids
58
+ try:
59
+ position_ids, _ = get_rope_index(input_ids=input_ids, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, second_per_grid_ts=second_per_grid_ts, attention_mask=attention_mask)
60
+ except TypeError:
61
+ try:
62
+ position_ids, _ = get_rope_index(input_ids, image_grid_thw, video_grid_thw, second_per_grid_ts, attention_mask)
63
+ except TypeError:
64
+ position_ids, _ = get_rope_index(input_ids, image_grid_thw, video_grid_thw, attention_mask)
65
+ return position_ids
66
+
67
+ def primary_device(model: Any) -> torch.device:
68
+ try:
69
+ return next(model.parameters()).device
70
+ except StopIteration:
71
+ return torch.device('cuda' if torch.cuda.is_available() else 'cpu')
72
+
73
+ def model_input_subset(inputs: dict[str, Any]) -> dict[str, Any]:
74
+ keep = {'input_ids', 'attention_mask', 'pixel_values', 'image_grid_thw', 'pixel_values_videos', 'video_grid_thw', 'second_per_grid_ts', 'mm_token_type_ids'}
75
+ return {key: value for key, value in inputs.items() if key in keep and value is not None}
76
+
77
+ def decode_new_tokens(processor: Any, output_ids: torch.Tensor, prompt_len: int) -> str:
78
+ new_ids = output_ids[:, int(prompt_len):]
79
+ return processor.batch_decode(new_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0].strip()
80
+
81
+ def decode_token_ids(processor: Any, token_ids: torch.Tensor) -> str:
82
+ return processor.batch_decode(token_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0].strip()
83
+
84
+ def _sample_next_token(logits: torch.Tensor, do_sample: bool, temperature: float, top_p: float, top_k: int | None=None) -> torch.Tensor:
85
+ if not do_sample:
86
+ return torch.argmax(logits, dim=-1, keepdim=True)
87
+ temperature = max(float(temperature), 1e-06)
88
+ probs = torch.softmax(logits.float() / temperature, dim=-1)
89
+ if top_k is not None and int(top_k) > 0:
90
+ k = min(int(top_k), int(probs.shape[-1]))
91
+ values, indices = torch.topk(probs, k=k, dim=-1)
92
+ filtered = torch.zeros_like(probs)
93
+ filtered.scatter_(dim=-1, index=indices, src=values)
94
+ probs = filtered / filtered.sum(dim=-1, keepdim=True).clamp_min(1e-12)
95
+ top_p = float(top_p)
96
+ if 0.0 < top_p < 1.0:
97
+ sorted_probs, sorted_indices = torch.sort(probs, descending=True, dim=-1)
98
+ cumulative = sorted_probs.cumsum(dim=-1)
99
+ remove = cumulative > top_p
100
+ remove[..., 0] = False
101
+ sorted_probs = sorted_probs.masked_fill(remove, 0.0)
102
+ sorted_probs = sorted_probs / sorted_probs.sum(dim=-1, keepdim=True).clamp_min(1e-12)
103
+ sampled = torch.multinomial(sorted_probs, num_samples=1)
104
+ return sorted_indices.gather(dim=-1, index=sampled)
105
+ return torch.multinomial(probs, num_samples=1)
106
+
107
+ def full_token_metadata(model: Any, inputs: dict[str, torch.Tensor], prompt_len: int | None) -> dict[str, Any]:
108
+ qwen = _unwrap_qwen_model(model)
109
+ image_token_id = int(qwen.config.image_token_id)
110
+ full_input_ids = inputs['input_ids']
111
+ num_full = int((full_input_ids == image_token_id).sum().item())
112
+ return {'student_prompt_len': int(prompt_len) if prompt_len is not None else None, 'num_full_visual_tokens': num_full, 'num_kept_visual_tokens': num_full, 'visionzip_exact_metrics': True, 'visionzip_metric_source': 'full_token_no_prune', 'visionzip_target_tokens': num_full, 'visionzip_dominant_tokens': num_full, 'visionzip_contextual_tokens': 0, 'visionzip_merged_tokens': 0, 'visionzip_contextual_fraction': 0.0, 'visionzip_dominant_ratio': 1.0, 'visionzip_contextual_ratio': 0.0, 'visionzip_disabled': True}
113
+ ANSWER_TAG_PATTERN = re.compile('<answer>\\s*(.*?)\\s*</answer>', re.IGNORECASE | re.DOTALL)
114
+ OPEN_ANSWER_TAG_PATTERN = re.compile('<answer>\\s*([^<\\n\\r]+)', re.IGNORECASE)
115
+ FINAL_ANSWER_PATTERNS = (re.compile('final\\s+answer\\s*[:\\-]\\s*([ABCD])\\b', re.IGNORECASE), re.compile('the\\s+final\\s+answer\\s+is\\s+([ABCD])\\b', re.IGNORECASE), re.compile('answer\\s*[:\\-]\\s*([ABCD])\\b', re.IGNORECASE))
116
+
117
+ def _extract_option_letter(value: str) -> str | None:
118
+ for pattern in FINAL_ANSWER_PATTERNS:
119
+ match = pattern.search(value)
120
+ if match:
121
+ return match.group(1).upper()
122
+ match = re.search('\\b([ABCD])\\b', value, flags=re.IGNORECASE)
123
+ if match:
124
+ return match.group(1).upper()
125
+ return None
126
+
127
+ def parse_final_answer(text: str) -> str | None:
128
+ """Extract A/B/C/D from the requested final-answer format and close variants."""
129
+ value = str(text or '')
130
+ answer_tag = ANSWER_TAG_PATTERN.search(value)
131
+ if answer_tag:
132
+ parsed = _extract_option_letter(answer_tag.group(1))
133
+ if parsed:
134
+ return parsed
135
+ open_answer_tag = OPEN_ANSWER_TAG_PATTERN.search(value)
136
+ if open_answer_tag:
137
+ parsed = _extract_option_letter(open_answer_tag.group(1))
138
+ if parsed:
139
+ return parsed
140
+ for pattern in FINAL_ANSWER_PATTERNS:
141
+ match = pattern.search(value)
142
+ if match:
143
+ return match.group(1).upper()
144
+ lines = [line.strip() for line in value.splitlines() if line.strip()]
145
+ if lines:
146
+ tail = lines[-1]
147
+ match = re.search('\\b([ABCD])\\b', tail, flags=re.IGNORECASE)
148
+ if match and 'final' in tail.lower():
149
+ return match.group(1).upper()
150
+ return None
evaluation/scopd_eval/qwen3_runtime.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Use isolated stock Transformers for Qwen3, never the Qwen2.5 overlays."""
2
+ import hashlib
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import sys
7
+
8
+ ROOT = Path(__file__).resolve().parents[1]
9
+
10
+
11
+ def activate():
12
+ src = ROOT / '.runtime/qwen3/src'
13
+ stamp = src.parent / 'source_manifest.json'
14
+ if not stamp.exists():
15
+ raise RuntimeError('Run python runtime/prepare.py --mode qwen3 first')
16
+ manifest = json.loads(stamp.read_text())
17
+ pinned = json.loads((ROOT / 'runtime/manifest.json').read_text())
18
+ if manifest['wheel_sha256'] != pinned['wheel_sha256']:
19
+ raise RuntimeError('Wrong Qwen3 Transformers wheel')
20
+ for relative, expected in manifest['files'].items():
21
+ path = src / relative
22
+ if not path.is_file() or hashlib.sha256(path.read_bytes()).hexdigest() != expected:
23
+ raise RuntimeError(f'Qwen3 runtime source changed: {relative}')
24
+ if 'transformers' in sys.modules:
25
+ loaded = Path(sys.modules['transformers'].__file__).resolve()
26
+ if not loaded.is_relative_to(src):
27
+ raise RuntimeError('A different Transformers is already imported; use a fresh process')
28
+ vlm = ROOT / 'third_party/VLMEvalKit'
29
+ for path in reversed((ROOT, src, vlm, vlm / 'internvl')):
30
+ sys.path.insert(0, str(path))
31
+ os.environ['MMSTAR_QWEN_JUDGE'] = '0'
32
+ os.environ['VLMEVAL_SAVE_RAW_PREDICTION'] = '1'
33
+ os.environ['VLMEVAL_STRICT_ERRORS'] = '1'
evaluation/scopd_eval/qwen3_visionzip.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from .qwen3_helpers import compute_full_position_ids, parse_final_answer, _sample_next_token, decode_new_tokens, decode_token_ids, full_token_metadata, model_input_subset, primary_device
3
+ import hashlib
4
+ import math
5
+ import os
6
+ import types
7
+ from pathlib import Path
8
+ from typing import Any
9
+ import torch
10
+ import torch.nn.functional as F
11
+ OFFICIAL_MODEL_REVISIONS = {'Qwen/Qwen3-VL-4B-Instruct': 'ebb281ec70b05090aa6165b016eac8ec08e71b17', 'Qwen/Qwen3-VL-8B-Instruct': '0c351dd01ed87e9c1b53cbc748cba10e6187ff3b'}
12
+ OFFICIAL_TRANSFORMERS_ROOT = Path(__file__).resolve().parents[1] / '.runtime/qwen3/src'
13
+ VISIONZIP_CONTEXTUAL_RATIO = 0.05
14
+ VISION_ATTENTION_QUERY_CHUNK = 64
15
+
16
+ def _unwrap_qwen3(model: Any) -> Any:
17
+ queue = [model]
18
+ seen: set[int] = set()
19
+ while queue:
20
+ candidate = queue.pop(0)
21
+ if candidate is None or id(candidate) in seen:
22
+ continue
23
+ seen.add(id(candidate))
24
+ config = getattr(candidate, 'config', None)
25
+ if config is not None and getattr(config, 'model_type', None) == 'qwen3_vl' and hasattr(candidate, 'lm_head') and hasattr(candidate, 'visual'):
26
+ return candidate
27
+ if hasattr(candidate, 'get_base_model'):
28
+ try:
29
+ queue.append(candidate.get_base_model())
30
+ except TypeError:
31
+ pass
32
+ for attr in ('module', 'base_model', 'model'):
33
+ queue.append(getattr(candidate, attr, None))
34
+ raise TypeError('Could not find Qwen3VLForConditionalGeneration under the supplied wrappers.')
35
+
36
+ def _stable_mask_hash(indices: torch.Tensor) -> str:
37
+ payload = ','.join((str(int(value)) for value in indices.detach().cpu().tolist()))
38
+ return hashlib.sha256(payload.encode('ascii')).hexdigest()
39
+
40
+ def _assert_official_transformers() -> None:
41
+ import transformers
42
+ loaded = Path(transformers.__file__).resolve()
43
+ expected = OFFICIAL_TRANSFORMERS_ROOT.resolve()
44
+ if expected not in loaded.parents:
45
+ raise RuntimeError(f'Qwen3 must use the isolated official Transformers wheel; loaded={loaded}, expected_under={expected}.')
46
+ source = Path(transformers.models.qwen3_vl.modeling_qwen3_vl.__file__).read_text(encoding='utf-8')
47
+ forbidden = ('kdvz_ratio = 0.75', 'if select_pixel:')
48
+ leaked = [needle for needle in forbidden if needle in source]
49
+ if leaked:
50
+ raise RuntimeError(f'The Qwen3 runtime contains experimental pruning code: {leaked}.')
51
+
52
+ def _validate_qwen3_image_inputs(inputs: dict[str, Any], model: Any) -> None:
53
+ input_ids = inputs.get('input_ids')
54
+ if input_ids is None or input_ids.ndim != 2 or int(input_ids.shape[0]) != 1:
55
+ raise NotImplementedError('Qwen3 VisionZip supports one text sequence per process.')
56
+ if inputs.get('video_grid_thw') is not None or inputs.get('pixel_values_videos') is not None:
57
+ raise NotImplementedError('Qwen3 VisionZip evaluation currently supports images, not video.')
58
+ image_grid_thw = inputs.get('image_grid_thw')
59
+ pixel_values = inputs.get('pixel_values')
60
+ if image_grid_thw is None or pixel_values is None:
61
+ raise ValueError('Qwen3 image inputs require pixel_values and image_grid_thw.')
62
+ if image_grid_thw.ndim != 2 or int(image_grid_thw.shape[1]) != 3 or int(image_grid_thw.shape[0]) < 1:
63
+ raise ValueError(f'Invalid Qwen3 image_grid_thw shape: {tuple(image_grid_thw.shape)}')
64
+ qwen = _unwrap_qwen3(model)
65
+ placeholders = int((input_ids == int(qwen.config.image_token_id)).sum().item())
66
+ if placeholders <= 0:
67
+ raise ValueError('Qwen3 prompt contains no image-token placeholders.')
68
+
69
+ def load_qwen3_model_and_processor(model_name_or_path: str, bf16: bool=True, attn_implementation: str='flash_attention_2', device_map: str | dict[str, int] | None='auto', min_pixels: int | None=None, max_pixels: int | None=None, visionzip_official: bool=True):
70
+ del visionzip_official
71
+ _assert_official_transformers()
72
+ from transformers import AutoProcessor, Qwen3VLForConditionalGeneration
73
+ model_id = str(model_name_or_path)
74
+ model_path = Path(model_id)
75
+ revision = OFFICIAL_MODEL_REVISIONS.get(model_id)
76
+ if revision is None and (not model_path.exists()):
77
+ raise ValueError(f'Unexpected Qwen3 model: {model_name_or_path}')
78
+ processor_kwargs: dict[str, Any] = {}
79
+ if revision is not None:
80
+ processor_kwargs['revision'] = revision
81
+ if min_pixels is not None:
82
+ processor_kwargs['min_pixels'] = int(min_pixels)
83
+ if max_pixels is not None:
84
+ processor_kwargs['max_pixels'] = int(max_pixels)
85
+ processor = AutoProcessor.from_pretrained(model_name_or_path, **processor_kwargs)
86
+ if processor.tokenizer.pad_token_id is None:
87
+ processor.tokenizer.pad_token = processor.tokenizer.eos_token
88
+ load_kwargs: dict[str, Any] = {'torch_dtype': torch.bfloat16 if bf16 else torch.float16, 'attn_implementation': attn_implementation, 'low_cpu_mem_usage': True}
89
+ if revision is not None:
90
+ load_kwargs['revision'] = revision
91
+ if device_map is not None:
92
+ load_kwargs['device_map'] = device_map
93
+ model = Qwen3VLForConditionalGeneration.from_pretrained(model_name_or_path, **load_kwargs)
94
+ install_qwen3_pruned_forward(model)
95
+ return (model, processor)
96
+
97
+ def _capture_last_visual_qk(qwen: Any, pixel_values: torch.Tensor, image_grid_thw: torch.Tensor):
98
+ from transformers.models.qwen3_vl.modeling_qwen3_vl import apply_rotary_pos_emb_vision
99
+ captured: dict[str, torch.Tensor] = {}
100
+ attention = qwen.visual.blocks[-1].attn
101
+
102
+ def hook(module: Any, args: tuple[Any, ...], kwargs: dict[str, Any]):
103
+ hidden_states = kwargs.get('hidden_states', args[0] if args else None)
104
+ position_embeddings = kwargs.get('position_embeddings')
105
+ if hidden_states is None or position_embeddings is None:
106
+ raise RuntimeError('Could not capture Qwen3 final visual-attention inputs.')
107
+ with torch.no_grad():
108
+ seq_len = int(hidden_states.shape[0])
109
+ query, key, _ = module.qkv(hidden_states).reshape(seq_len, 3, module.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
110
+ cos, sin = position_embeddings
111
+ query, key = apply_rotary_pos_emb_vision(query, key, cos, sin)
112
+ captured['query'] = query.detach()
113
+ captured['key'] = key.detach()
114
+ handle = attention.register_forward_pre_hook(hook, with_kwargs=True)
115
+ try:
116
+ output = qwen.get_image_features(pixel_values, image_grid_thw)
117
+ finally:
118
+ handle.remove()
119
+ if not isinstance(output, (tuple, list)) or len(output) != 2:
120
+ raise RuntimeError(f'Official Qwen3 get_image_features returned unexpected type: {type(output)!r}')
121
+ image_embeds, deepstack_embeds = output
122
+ if len(image_embeds) != int(image_grid_thw.shape[0]):
123
+ raise RuntimeError('Qwen3 image-feature split count does not match image_grid_thw.')
124
+ if 'query' not in captured or 'key' not in captured:
125
+ raise RuntimeError('Final visual-attention hook did not run.')
126
+ merge_unit = int(qwen.visual.spatial_merge_unit)
127
+ raw_split_sizes = image_grid_thw.prod(dim=-1).to(dtype=torch.long)
128
+ if bool((raw_split_sizes % merge_unit != 0).any()):
129
+ raise RuntimeError('Qwen3 raw image-patch counts are not divisible by the spatial merge unit.')
130
+ merged_split_sizes = raw_split_sizes // merge_unit
131
+ image_bank = torch.cat(list(image_embeds), dim=0)
132
+ if int(image_bank.shape[0]) != int(merged_split_sizes.sum().item()):
133
+ raise RuntimeError('Qwen3 merged image-bank size does not match image_grid_thw.')
134
+ return (image_bank, list(deepstack_embeds), captured['query'], captured['key'], raw_split_sizes, merged_split_sizes)
135
+
136
+ def _incoming_attention_and_keys(query: torch.Tensor, key: torch.Tensor, merge_unit: int, query_chunk: int=VISION_ATTENTION_QUERY_CHUNK) -> tuple[torch.Tensor, torch.Tensor]:
137
+ if query.shape != key.shape or query.ndim != 3:
138
+ raise ValueError(f'Expected matching [patch, head, dim] Q/K tensors, got {query.shape} and {key.shape}.')
139
+ raw_tokens, heads, head_dim = map(int, query.shape)
140
+ if raw_tokens % int(merge_unit) != 0:
141
+ raise ValueError(f'Raw visual-token count {raw_tokens} is not divisible by merge unit {merge_unit}.')
142
+ incoming = torch.zeros(raw_tokens, dtype=torch.float32, device=query.device)
143
+ key_float = key.float()
144
+ scale = float(head_dim) ** (-0.5)
145
+ for start in range(0, raw_tokens, int(query_chunk)):
146
+ q_chunk = query[start:start + int(query_chunk)].float()
147
+ logits = torch.einsum('qhd,khd->hqk', q_chunk, key_float) * scale
148
+ incoming.add_(torch.softmax(logits, dim=-1).sum(dim=(0, 1)))
149
+ del logits
150
+ incoming = incoming.reshape(-1, int(merge_unit)).mean(dim=1)
151
+ contextual_keys = key_float.reshape(-1, int(merge_unit), heads, head_dim).mean(dim=1).mean(dim=1)
152
+ return (incoming, contextual_keys)
153
+
154
+ def _merge_one_bank(bank: torch.Tensor, candidate_indices: torch.Tensor, target_positions: torch.Tensor, assignment: torch.Tensor, contextual_count: int) -> torch.Tensor:
155
+ output = bank.clone()
156
+ target_indices = candidate_indices[target_positions]
157
+ non_target_mask = torch.ones(candidate_indices.numel(), dtype=torch.bool, device=bank.device)
158
+ non_target_mask[target_positions] = False
159
+ non_target_indices = candidate_indices[non_target_mask]
160
+ if non_target_indices.numel() == 0:
161
+ return output
162
+ source = bank[non_target_indices]
163
+ one_hot = F.one_hot(assignment, num_classes=int(contextual_count)).to(dtype=bank.dtype)
164
+ counts = one_hot.sum(dim=0).clamp_min(1).unsqueeze(-1)
165
+ aggregate = one_hot.transpose(0, 1) @ source
166
+ output[target_indices] = bank[target_indices] + aggregate / counts
167
+ return output
168
+
169
+ def build_qwen3_visionzip_context(model: Any, inputs: dict[str, torch.Tensor], retention_ratio: float, prompt_len: int | None) -> dict[str, Any]:
170
+ _validate_qwen3_image_inputs(inputs, model=model)
171
+ qwen = _unwrap_qwen3(model)
172
+ device = primary_device(qwen)
173
+ input_ids = inputs['input_ids'].to(device)
174
+ attention_mask = inputs['attention_mask'].to(device)
175
+ pixel_values = inputs['pixel_values'].to(device=device, dtype=qwen.visual.dtype)
176
+ image_grid_thw = inputs['image_grid_thw'].to(device)
177
+ retention = float(retention_ratio)
178
+ if not 0.0 < retention < 1.0:
179
+ raise ValueError(f'VisionZip context requires 0 < retention < 1, got {retention}.')
180
+ with torch.no_grad():
181
+ image_bank, deepstack_banks, query, key, raw_split_sizes, merged_split_sizes = _capture_last_visual_qk(qwen, pixel_values, image_grid_thw)
182
+ merge_unit = int(qwen.visual.spatial_merge_unit)
183
+ num_full = int(image_bank.shape[0])
184
+ if any((int(bank.shape[0]) != num_full for bank in deepstack_banks)):
185
+ raise RuntimeError('Qwen3 main and DeepStack visual-token banks are not aligned.')
186
+ contextual_ratio = min(VISIONZIP_CONTEXTUAL_RATIO, retention)
187
+ dominant_ratio = max(0.0, retention - contextual_ratio)
188
+ raw_offset = 0
189
+ merged_offset = 0
190
+ dominant_indices_parts: list[torch.Tensor] = []
191
+ contextual_indices_parts: list[torch.Tensor] = []
192
+ dominant_counts: list[int] = []
193
+ contextual_counts: list[int] = []
194
+ for raw_size_tensor, merged_size_tensor in zip(raw_split_sizes, merged_split_sizes):
195
+ raw_size = int(raw_size_tensor.item())
196
+ merged_size = int(merged_size_tensor.item())
197
+ importance, contextual_keys = _incoming_attention_and_keys(query[raw_offset:raw_offset + raw_size], key[raw_offset:raw_offset + raw_size], merge_unit)
198
+ dominant_count_i = min(merged_size, max(0, int(dominant_ratio * merged_size)))
199
+ contextual_count_i = max(0, int(contextual_ratio * merged_size))
200
+ if contextual_ratio > 0.0 and dominant_count_i < merged_size:
201
+ contextual_count_i = max(contextual_count_i, 1)
202
+ contextual_count_i = min(contextual_count_i, merged_size - dominant_count_i)
203
+ if dominant_count_i + contextual_count_i <= 0:
204
+ raise RuntimeError('VisionZip selected zero tokens for an image.')
205
+ local_dominant = torch.topk(importance, k=dominant_count_i, largest=True).indices if dominant_count_i else importance.new_empty((0,), dtype=torch.long)
206
+ local_dominant_mask = torch.zeros(merged_size, dtype=torch.bool, device=device)
207
+ local_dominant_mask[local_dominant] = True
208
+ local_candidates = torch.where(~local_dominant_mask)[0]
209
+ global_candidates = local_candidates + merged_offset
210
+ if contextual_count_i:
211
+ step = max(1, int(local_candidates.numel()) // contextual_count_i)
212
+ target_positions = torch.arange(0, int(local_candidates.numel()), step, device=device)[:contextual_count_i]
213
+ candidate_keys = F.normalize(contextual_keys[local_candidates], p=2, dim=-1, eps=1e-12)
214
+ target_keys = candidate_keys[target_positions]
215
+ non_target_mask = torch.ones(local_candidates.numel(), dtype=torch.bool, device=device)
216
+ non_target_mask[target_positions] = False
217
+ assignment = (candidate_keys[non_target_mask] @ target_keys.transpose(0, 1)).argmax(dim=-1)
218
+ image_bank = _merge_one_bank(image_bank, global_candidates, target_positions, assignment, contextual_count_i)
219
+ deepstack_banks = [_merge_one_bank(bank, global_candidates, target_positions, assignment, contextual_count_i) for bank in deepstack_banks]
220
+ contextual_indices_parts.append(global_candidates[target_positions])
221
+ dominant_indices_parts.append(local_dominant + merged_offset)
222
+ dominant_counts.append(dominant_count_i)
223
+ contextual_counts.append(contextual_count_i)
224
+ raw_offset += raw_size
225
+ merged_offset += merged_size
226
+ dominant_indices = torch.cat(dominant_indices_parts)
227
+ contextual_indices = torch.cat(contextual_indices_parts) if contextual_indices_parts else dominant_indices.new_empty((0,))
228
+ dominant_count = sum(dominant_counts)
229
+ contextual_count = sum(contextual_counts)
230
+ keep_indices = torch.cat([dominant_indices, contextual_indices]).unique(sorted=True)
231
+ if int(keep_indices.numel()) != dominant_count + contextual_count:
232
+ raise RuntimeError('VisionZip dominant/contextual indices overlap unexpectedly.')
233
+ full_position_ids = compute_full_position_ids(qwen, input_ids, image_grid_thw, inputs.get('video_grid_thw'), attention_mask, inputs.get('second_per_grid_ts'), inputs.get('mm_token_type_ids')).to(device)
234
+ image_positions = torch.where(input_ids[0] == int(qwen.config.image_token_id))[0]
235
+ if int(image_positions.numel()) != num_full:
236
+ raise RuntimeError(f'Qwen3 image placeholders/features mismatch: placeholders={image_positions.numel()}, features={num_full}.')
237
+ token_embeddings = qwen.get_input_embeddings()(input_ids)
238
+ token_embeddings = token_embeddings.clone()
239
+ token_embeddings[0, image_positions] = image_bank.to(token_embeddings.dtype)
240
+ seq_keep = torch.ones(input_ids.shape[1], dtype=torch.bool, device=device)
241
+ seq_keep[image_positions] = False
242
+ seq_keep[image_positions[keep_indices]] = True
243
+ pruned_ids = input_ids[:, seq_keep]
244
+ pruned_embeds = token_embeddings[:, seq_keep]
245
+ pruned_attention = attention_mask[:, seq_keep]
246
+ pruned_positions = full_position_ids[:, :, seq_keep]
247
+ visual_pos_mask = pruned_ids == int(qwen.config.image_token_id)
248
+ selected_deepstack = [bank[keep_indices].to(pruned_embeds.dtype) for bank in deepstack_banks]
249
+ student_prompt_len = None
250
+ if prompt_len is not None:
251
+ full_prompt_visual = int((input_ids[:, :int(prompt_len)] == int(qwen.config.image_token_id)).sum().item())
252
+ student_prompt_len = int(prompt_len) - full_prompt_visual + int(keep_indices.numel())
253
+ metadata = {'student_prompt_len': student_prompt_len, 'num_full_visual_tokens': num_full, 'num_kept_visual_tokens': int(keep_indices.numel()), 'pruning_method': 'visionzip', 'visionzip_metric_source': 'qwen3_final_visual_attention_incoming_mass', 'visionzip_deepstack_synchronized': True, 'visionzip_image_count': int(image_grid_thw.shape[0]), 'visionzip_per_image_full_tokens': [int(value) for value in merged_split_sizes.tolist()], 'visionzip_per_image_dominant_tokens': dominant_counts, 'visionzip_per_image_contextual_tokens': contextual_counts, 'visionzip_target_tokens': int(keep_indices.numel()), 'visionzip_dominant_tokens': dominant_count, 'visionzip_contextual_tokens': contextual_count, 'visionzip_merged_tokens': num_full - dominant_count - contextual_count, 'visionzip_dominant_ratio': dominant_ratio, 'visionzip_contextual_ratio': contextual_ratio, 'visionzip_retention_ratio': retention, 'visionzip_keep_indices_hash': _stable_mask_hash(keep_indices)}
254
+ return {'input_ids': pruned_ids, 'inputs_embeds': pruned_embeds, 'attention_mask': pruned_attention, 'position_ids': pruned_positions, 'visual_pos_masks': visual_pos_mask, 'deepstack_visual_embeds': selected_deepstack, 'metadata': metadata, 'keep_indices': keep_indices.detach().cpu()}
255
+
256
+ def install_qwen3_pruned_forward(model: Any) -> None:
257
+ qwen = _unwrap_qwen3(model)
258
+ if getattr(qwen, '_scopd_qwen3_pruned_forward_installed', False):
259
+ return
260
+ original_forward = qwen.forward
261
+
262
+ def patched_forward(self: Any, *args: Any, scopd_qwen3_pruned_context: dict[str, Any] | None=None, use_cache: bool | None=None, return_dict: bool | None=None, past_key_values: Any=None, cache_position: torch.Tensor | None=None, logits_to_keep: int | torch.Tensor=0, **kwargs: Any):
263
+ if scopd_qwen3_pruned_context is None:
264
+ return original_forward(*args, use_cache=use_cache, return_dict=return_dict, past_key_values=past_key_values, cache_position=cache_position, logits_to_keep=logits_to_keep, **kwargs)
265
+ from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLCausalLMOutputWithPast
266
+ context = scopd_qwen3_pruned_context
267
+ outputs = self.model.language_model(input_ids=None, position_ids=context['position_ids'], attention_mask=context['attention_mask'], past_key_values=past_key_values, inputs_embeds=context['inputs_embeds'], cache_position=cache_position, visual_pos_masks=context['visual_pos_masks'], deepstack_visual_embeds=context['deepstack_visual_embeds'], use_cache=use_cache, return_dict=True)
268
+ hidden = outputs.last_hidden_state
269
+ selection = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
270
+ logits = self.lm_head(hidden[:, selection, :])
271
+ return Qwen3VLCausalLMOutputWithPast(logits=logits, past_key_values=outputs.past_key_values, rope_deltas=None)
272
+ qwen.forward = types.MethodType(patched_forward, qwen)
273
+ qwen._scopd_qwen3_original_forward = original_forward
274
+ qwen._scopd_qwen3_pruned_forward_installed = True
275
+
276
+ def forward_qwen3_visionzip(model: Any, inputs: dict[str, torch.Tensor], retention_ratio: float, prompt_len: int | None=None, mode: str='drop_tokens', allow_embedding_fallback: bool=False, sample_id: str | None=None, question: str | None=None, **forward_kwargs: Any):
277
+ del mode, sample_id, question
278
+ if allow_embedding_fallback:
279
+ raise ValueError('Qwen3 VisionZip has no embedding fallback.')
280
+ pruning_method = str(forward_kwargs.pop('pruning_method', 'visionzip') or 'visionzip').lower()
281
+ if pruning_method not in {'visionzip', 'official_visionzip', 'vz'}:
282
+ raise ValueError(f'Qwen3 campaign only supports VisionZip, got {pruning_method}.')
283
+ if float(retention_ratio) >= 1.0:
284
+ output = model(**model_input_subset(inputs), use_cache=False, **forward_kwargs)
285
+ metadata = full_token_metadata(model, inputs, prompt_len)
286
+ metadata['pruning_method'] = 'visionzip'
287
+ return (output, {'metadata': metadata})
288
+ context = build_qwen3_visionzip_context(model, inputs, retention_ratio, prompt_len)
289
+ output = model(scopd_qwen3_pruned_context=context, use_cache=False, **forward_kwargs)
290
+ return (output, context)
291
+
292
+ def _cached_generate_from_context(model: Any, processor: Any, context: dict[str, Any], max_new_tokens: int, do_sample: bool, temperature: float, top_p: float, top_k: int | None, stop_on_parse: bool, max_unparseable_tokens: int | None) -> tuple[torch.Tensor, str]:
293
+ eos_token_id = processor.tokenizer.eos_token_id
294
+ attention_mask = context['attention_mask']
295
+ position_ids = context['position_ids']
296
+ generated: list[torch.Tensor] = []
297
+ with torch.inference_mode():
298
+ prefill = model(scopd_qwen3_pruned_context=context, use_cache=True, return_dict=True)
299
+ cache = prefill.past_key_values
300
+ if cache is None or not hasattr(cache, 'get_seq_length'):
301
+ raise RuntimeError('Qwen3 pruned prefill did not return a dynamic KV cache.')
302
+ if int(cache.get_seq_length()) != int(attention_mask.shape[1]):
303
+ raise RuntimeError('Qwen3 pruned prefix and KV-cache lengths differ.')
304
+ next_logits = prefill.logits[:, -1]
305
+ next_position = position_ids[:, :, -1:] + 1
306
+ for _ in range(int(max_new_tokens)):
307
+ token = _sample_next_token(next_logits, do_sample, temperature, top_p, top_k)
308
+ generated.append(token)
309
+ if eos_token_id is not None and int(token.item()) == int(eos_token_id):
310
+ break
311
+ if len(generated) % 4 == 0 and (stop_on_parse or max_unparseable_tokens is not None):
312
+ partial = decode_token_ids(processor, torch.cat(generated, dim=1))
313
+ if stop_on_parse and parse_final_answer(partial) is not None:
314
+ break
315
+ if max_unparseable_tokens is not None and len(generated) >= int(max_unparseable_tokens):
316
+ break
317
+ attention_mask = torch.cat([attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=1)
318
+ cache_position = torch.tensor([cache.get_seq_length()], device=token.device, dtype=torch.long)
319
+ decoded = model(input_ids=token, attention_mask=attention_mask, position_ids=next_position, past_key_values=cache, cache_position=cache_position, use_cache=True, return_dict=True)
320
+ cache = decoded.past_key_values
321
+ next_logits = decoded.logits[:, -1]
322
+ next_position = next_position + 1
323
+ if not generated:
324
+ return (context['input_ids'].new_empty((1, 0)), '')
325
+ ids = torch.cat(generated, dim=1)
326
+ return (ids, decode_token_ids(processor, ids))
327
+
328
+ def generate_qwen3_visionzip(model: Any, processor: Any, prompt_inputs: dict[str, torch.Tensor], retention_ratio: float, max_new_tokens: int=128, do_sample: bool=False, temperature: float=0.7, top_p: float=0.9, top_k: int | None=None, allow_embedding_fallback: bool=False, manual_decode: bool=False, max_unparseable_tokens: int | None=None, stop_on_parse: bool=True, sample_id: str | None=None, question: str | None=None):
329
+ del sample_id, question
330
+ if allow_embedding_fallback:
331
+ raise ValueError('Qwen3 VisionZip has no embedding fallback.')
332
+ prompt_len = int(prompt_inputs['input_ids'].shape[1])
333
+ if float(retention_ratio) >= 1.0:
334
+ eos = processor.tokenizer.eos_token_id
335
+ generation_kwargs: dict[str, Any] = {'max_new_tokens': int(max_new_tokens), 'do_sample': bool(do_sample), 'use_cache': True, 'eos_token_id': eos, 'pad_token_id': processor.tokenizer.pad_token_id or eos}
336
+ if do_sample:
337
+ generation_kwargs.update(temperature=float(temperature), top_p=float(top_p))
338
+ if top_k:
339
+ generation_kwargs['top_k'] = int(top_k)
340
+ output = model.generate(**model_input_subset(prompt_inputs), **generation_kwargs)
341
+ metadata = full_token_metadata(model, prompt_inputs, prompt_len)
342
+ metadata.update({'pruning_method': 'visionzip', 'rollout_decoder': 'hf_generate_kv_cache'})
343
+ return (output[:, prompt_len:], decode_new_tokens(processor, output, prompt_len), metadata)
344
+ if manual_decode:
345
+ raise ValueError('Qwen3 OPSD requires cached pruned rollout generation.')
346
+ context = build_qwen3_visionzip_context(model, prompt_inputs, retention_ratio, prompt_len)
347
+ ids, text = _cached_generate_from_context(model, processor, context, max_new_tokens, do_sample, temperature, top_p, top_k, stop_on_parse, max_unparseable_tokens)
348
+ context['metadata']['rollout_decoder'] = 'qwen3_deepstack_pruned_prefill_kv_decode'
349
+ return (ids, text, context['metadata'])
evaluation/scopd_eval/qwen3_wrapper.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import copy
3
+ import re
4
+ import time
5
+ from pathlib import Path
6
+ from typing import Any
7
+ import torch
8
+ from .qwen3_visionzip import generate_qwen3_visionzip, load_qwen3_model_and_processor
9
+ from vlmeval.vlm.base import BaseModel
10
+ from vlmeval.vlm.qwen3_vl.prompt import Qwen3VLPromptMixin
11
+ ANSWER_PATTERN = re.compile('<answer>(.*?)</answer>', flags=re.IGNORECASE | re.DOTALL)
12
+
13
+ def reasoning_suffix(tag: str) -> str:
14
+ if tag not in {'think', 'analysis'}:
15
+ raise ValueError(f'Unsupported reasoning tag: {tag!r}')
16
+ return f'\nFirst output the reasoning process in <{tag}> </{tag}> tags and then output the final answer in <answer> </answer> tags.'
17
+
18
+ def _image_url(path: str) -> str:
19
+ if path.startswith(('http://', 'https://', 'file://', 'data:image')):
20
+ return path
21
+ if Path(path).exists():
22
+ return f'file://{path}'
23
+ raise FileNotFoundError(path)
24
+
25
+ def _round_budget(tokens: int) -> int:
26
+ return max(1, int(tokens)) * 32 * 32
27
+
28
+ class Qwen3VisionZipReasoning(Qwen3VLPromptMixin, BaseModel):
29
+ INSTALL_REQ = False
30
+ INTERLEAVE = True
31
+ VIDEO_LLM = False
32
+
33
+ def __init__(self, model_path: str, retention_ratio: float=1.0, min_visual_tokens: int=1280, max_visual_tokens: int=4096, max_new_tokens: int=2048, reasoning_prompt: bool=True, reasoning_tag: str='think', use_custom_prompt: bool=False, **_: Any) -> None:
34
+ super().__init__(use_custom_prompt=use_custom_prompt)
35
+ self.model_path = str(model_path)
36
+ self.retention_ratio = float(retention_ratio)
37
+ self.min_visual_tokens = int(min_visual_tokens)
38
+ self.max_visual_tokens = int(max_visual_tokens)
39
+ self.max_new_tokens = int(max_new_tokens)
40
+ self.reasoning_prompt = bool(reasoning_prompt)
41
+ self.reasoning_tag = str(reasoning_tag).strip().lower()
42
+ reasoning_suffix(self.reasoning_tag)
43
+ self.num_total_dataset_generated_tokens = 0
44
+ self.total_inference_time_in_seconds = 0.0
45
+ self.total_initial_input_visual_tokens = 0
46
+ self.total_input_text_tokens = 0
47
+ self.model, self.processor = load_qwen3_model_and_processor(self.model_path, bf16=True, attn_implementation='flash_attention_2', device_map='auto', min_pixels=None, max_pixels=None)
48
+ self.model.eval()
49
+
50
+ def _messages(self, message: list[dict[str, str]]) -> list[dict[str, Any]]:
51
+ message = copy.deepcopy(message)
52
+ text_items = [item for item in message if item['type'] == 'text']
53
+ if not text_items:
54
+ raise ValueError('VLMEvalKit message contains no question text.')
55
+ text_items[0]['value'] = text_items[0]['value'].replace('\nAnswer:', '')
56
+ if self.reasoning_prompt:
57
+ text_items[0]['value'] += reasoning_suffix(self.reasoning_tag)
58
+ image_count = sum((item['type'] == 'image' for item in message))
59
+ if image_count < 1:
60
+ raise ValueError('Qwen3-VL evaluation requires at least one image.')
61
+ per_image_max = max(1, self.max_visual_tokens // image_count)
62
+ per_image_min = min(per_image_max, max(1, self.min_visual_tokens // image_count))
63
+ content: list[dict[str, Any]] = []
64
+ for item in message:
65
+ if item['type'] == 'image':
66
+ content.append({'type': 'image', 'image': _image_url(item['value']), 'min_pixels': _round_budget(per_image_min), 'max_pixels': _round_budget(per_image_max)})
67
+ elif item['type'] == 'text':
68
+ content.append({'type': 'text', 'text': item['value']})
69
+ else:
70
+ raise NotImplementedError(f"Unsupported Qwen3 evaluation item: {item['type']}")
71
+ return [{'role': 'user', 'content': content}]
72
+
73
+ def generate_inner(self, message: list[dict[str, str]], dataset: str | None=None):
74
+ del dataset
75
+ from qwen_vl_utils import process_vision_info
76
+ messages = self._messages(message)
77
+ text = self.processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
78
+ images, videos, video_kwargs = process_vision_info(messages, image_patch_size=16, return_video_kwargs=True, return_video_metadata=True)
79
+ if videos:
80
+ raise NotImplementedError('The five-benchmark Qwen3 campaign is image-only.')
81
+ inputs = dict(self.processor(text=[text], images=images, videos=None, do_resize=False, return_tensors='pt', **video_kwargs or {}))
82
+ device = next(self.model.parameters()).device
83
+ inputs = {key: value.to(device=device, dtype=self.model.dtype) if isinstance(value, torch.Tensor) and value.is_floating_point() else value.to(device=device) if isinstance(value, torch.Tensor) else value for key, value in inputs.items()}
84
+ started = time.perf_counter()
85
+ token_ids, raw_response, metadata = generate_qwen3_visionzip(self.model, self.processor, inputs, retention_ratio=self.retention_ratio, max_new_tokens=self.max_new_tokens, do_sample=False, temperature=0.0, top_p=1.0, top_k=None, stop_on_parse=False, max_unparseable_tokens=None)
86
+ self.total_inference_time_in_seconds += time.perf_counter() - started
87
+ self.num_total_dataset_generated_tokens += int(token_ids.numel())
88
+ self.total_initial_input_visual_tokens += int(metadata['num_full_visual_tokens'])
89
+ self.total_input_text_tokens += int(inputs['input_ids'].shape[1] - metadata['num_full_visual_tokens'])
90
+ matches = ANSWER_PATTERN.findall(raw_response)
91
+ parsed = ''.join(matches) if matches else raw_response
92
+ parsed = parsed.replace('\n', ' ').strip()
93
+ return {'prediction': parsed, 'extra_records': {'raw_prediction': raw_response, 'parsed_prediction': parsed, 'generated_token_len': int(token_ids.numel()), 'retention_ratio': self.retention_ratio, 'num_full_visual_tokens': int(metadata['num_full_visual_tokens']), 'num_kept_visual_tokens': int(metadata['num_kept_visual_tokens']), 'visionzip_keep_indices_hash': metadata.get('visionzip_keep_indices_hash'), 'rollout_decoder': metadata['rollout_decoder']}}
evaluation/scripts/merge_adapter.py CHANGED
@@ -14,32 +14,44 @@ sys.path.insert(0, str(ROOT))
14
  def main():
15
  parser = argparse.ArgumentParser(description=__doc__)
16
  parser.add_argument('--adapter', type=Path, required=True)
17
- parser.add_argument('--base-model', default='Qwen/Qwen2.5-VL-7B-Instruct')
18
- parser.add_argument('--base-revision', default='cc594898137f460bfe9f0759e9844b3ce807cfb5')
19
  parser.add_argument('--output', type=Path, required=True)
20
  parser.add_argument('--device', choices=['cpu', 'cuda'], default='cpu')
21
  args = parser.parse_args()
22
  if args.output.exists() and any(args.output.iterdir()):
23
  raise FileExistsError('Refusing to overwrite an existing model')
24
  provenance = json.loads((args.adapter / 'provenance.json').read_text())
 
 
25
  digest = hashlib.sha256((args.adapter / 'adapter_model.safetensors').read_bytes()).hexdigest()
26
  if digest != provenance['adapter_sha256']:
27
  raise ValueError('Adapter SHA256 mismatch')
28
  if args.base_revision != provenance['base_revision']:
29
  raise ValueError('Base revision differs from adapter provenance')
30
- from scopd_eval.runtime import activate
 
 
 
 
31
  activate()
32
  from huggingface_hub import snapshot_download
33
  import torch
34
  from peft import PeftModel
35
- from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration
 
 
 
 
36
  base = Path(args.base_model)
37
  if not base.is_dir():
 
 
38
  base = Path(snapshot_download(args.base_model, revision=args.base_revision,
39
  allow_patterns=['*.json', '*.safetensors', '*.txt', '*.jinja']))
40
  elif base.name != args.base_revision:
41
  raise ValueError('Local base must be the pinned Hub snapshot directory named by its revision')
42
- model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
43
  base, torch_dtype=torch.bfloat16, attn_implementation='eager',
44
  device_map={'': args.device}, local_files_only=True)
45
  model = PeftModel.from_pretrained(model, args.adapter, is_trainable=False)
 
14
  def main():
15
  parser = argparse.ArgumentParser(description=__doc__)
16
  parser.add_argument('--adapter', type=Path, required=True)
17
+ parser.add_argument('--base-model', help='Override with the matching pinned local Hub snapshot')
18
+ parser.add_argument('--base-revision', help='Defaults to the adapter provenance revision')
19
  parser.add_argument('--output', type=Path, required=True)
20
  parser.add_argument('--device', choices=['cpu', 'cuda'], default='cpu')
21
  args = parser.parse_args()
22
  if args.output.exists() and any(args.output.iterdir()):
23
  raise FileExistsError('Refusing to overwrite an existing model')
24
  provenance = json.loads((args.adapter / 'provenance.json').read_text())
25
+ args.base_model = args.base_model or provenance['base_model']
26
+ args.base_revision = args.base_revision or provenance['base_revision']
27
  digest = hashlib.sha256((args.adapter / 'adapter_model.safetensors').read_bytes()).hexdigest()
28
  if digest != provenance['adapter_sha256']:
29
  raise ValueError('Adapter SHA256 mismatch')
30
  if args.base_revision != provenance['base_revision']:
31
  raise ValueError('Base revision differs from adapter provenance')
32
+ qwen3 = provenance['base_model'] == 'Qwen/Qwen3-VL-4B-Instruct'
33
+ if qwen3:
34
+ from scopd_eval.qwen3_runtime import activate
35
+ else:
36
+ from scopd_eval.runtime import activate
37
  activate()
38
  from huggingface_hub import snapshot_download
39
  import torch
40
  from peft import PeftModel
41
+ from transformers import AutoProcessor
42
+ if qwen3:
43
+ from transformers import Qwen3VLForConditionalGeneration as Model
44
+ else:
45
+ from transformers import Qwen2_5_VLForConditionalGeneration as Model
46
  base = Path(args.base_model)
47
  if not base.is_dir():
48
+ if args.base_model != provenance['base_model']:
49
+ raise ValueError('Base model differs from adapter provenance')
50
  base = Path(snapshot_download(args.base_model, revision=args.base_revision,
51
  allow_patterns=['*.json', '*.safetensors', '*.txt', '*.jinja']))
52
  elif base.name != args.base_revision:
53
  raise ValueError('Local base must be the pinned Hub snapshot directory named by its revision')
54
+ model = Model.from_pretrained(
55
  base, torch_dtype=torch.bfloat16, attn_implementation='eager',
56
  device_map={'': args.device}, local_files_only=True)
57
  model = PeftModel.from_pretrained(model, args.adapter, is_trainable=False)
evaluation/tests/test_qwen3_release.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CPU checks for Qwen3 native pruning and inference packaging."""
2
+ import ast
3
+ from pathlib import Path
4
+ from types import SimpleNamespace
5
+ from unittest.mock import patch
6
+
7
+ import torch
8
+
9
+ from scopd_eval import qwen3_visionzip as native
10
+ from scopd_eval.qwen3_helpers import compute_full_position_ids, _sample_next_token
11
+
12
+
13
+ def test_greedy_decoder_does_not_sample():
14
+ logits = torch.tensor([[0., 2., 1.]])
15
+ with patch('torch.multinomial', side_effect=AssertionError('Greedy must not sample')):
16
+ result = _sample_next_token(logits, False, 0., 1., None)
17
+ assert result.item() == 1
18
+
19
+
20
+ def test_deepstack_pruning_and_position_alignment():
21
+ class Model(torch.nn.Module):
22
+ def __init__(self):
23
+ super().__init__()
24
+ self.embeddings = torch.nn.Embedding(256, 8)
25
+ self.config = SimpleNamespace(image_token_id=200, model_type='qwen3_vl')
26
+ self.visual = SimpleNamespace(dtype=torch.float32, spatial_merge_unit=4)
27
+ self.lm_head = torch.nn.Identity()
28
+
29
+ def get_input_embeddings(self):
30
+ return self.embeddings
31
+
32
+ torch.manual_seed(7)
33
+ model = Model()
34
+ ids = torch.tensor([[1] + [200] * 100 + [2, 3]])
35
+ inputs = dict(input_ids=ids, attention_mask=torch.ones_like(ids),
36
+ pixel_values=torch.ones(400, 4), image_grid_thw=torch.tensor([[1, 20, 20]]))
37
+ image_bank = torch.randn(100, 8)
38
+ q, k = torch.randn(400, 2, 4), torch.randn(400, 2, 4)
39
+ banks = [image_bank * scale for scale in (2, 3, 4)]
40
+ capture = (image_bank, banks, q, k, torch.tensor([400]), torch.tensor([100]))
41
+ with patch.object(native, '_capture_last_visual_qk', return_value=capture):
42
+ result = native.build_qwen3_visionzip_context(model, inputs, .10, prompt_len=103)
43
+ assert result['metadata']['num_full_visual_tokens'] == 100
44
+ assert result['metadata']['num_kept_visual_tokens'] == 10
45
+ assert result['metadata']['visionzip_dominant_tokens'] == 5
46
+ assert result['metadata']['visionzip_contextual_tokens'] == 5
47
+ assert result['metadata']['visionzip_deepstack_synchronized']
48
+ mask = result['visual_pos_masks'][0]
49
+ selected = result['inputs_embeds'][0, mask]
50
+ for scale, bank in zip((2, 3, 4), result['deepstack_visual_embeds']):
51
+ torch.testing.assert_close(bank, selected * scale)
52
+ expected = torch.cat((torch.tensor([0]), result['keep_indices'] + 1, torch.tensor([101, 102])))
53
+ assert torch.equal(result['position_ids'][0, 0], expected)
54
+ assert result['keep_indices'].unique().numel() == 10
55
+
56
+
57
+ def test_qwen3_mrope_receives_image_token_types():
58
+ class Model:
59
+ config = SimpleNamespace(image_token_id=9, video_token_id=10)
60
+
61
+ def get_rope_index(self, input_ids, mm_token_type_ids, image_grid_thw=None,
62
+ video_grid_thw=None, attention_mask=None, second_per_grid_ts=None):
63
+ assert mm_token_type_ids.tolist() == [[0, 1, 1, 0]]
64
+ return torch.zeros(3, 1, 4, dtype=torch.long), torch.zeros(1, 1)
65
+
66
+ result = compute_full_position_ids(Model(), torch.tensor([[1, 9, 9, 2]]),
67
+ torch.tensor([[1, 2, 4]]), None, torch.ones(1, 4))
68
+ assert result.shape == (3, 1, 4)
69
+
70
+
71
+ def test_stock_qwen3_rope_signature():
72
+ class Model:
73
+ config = SimpleNamespace(image_token_id=9)
74
+
75
+ def get_rope_index(self, input_ids=None, image_grid_thw=None,
76
+ video_grid_thw=None, attention_mask=None):
77
+ assert torch.equal(attention_mask, torch.ones(1, 4))
78
+ assert image_grid_thw.tolist() == [[1, 2, 4]]
79
+ return torch.ones(3, 1, 4, dtype=torch.long), torch.zeros(1, 1)
80
+
81
+ result = compute_full_position_ids(Model(), torch.tensor([[1, 9, 9, 2]]),
82
+ torch.tensor([[1, 2, 4]]), None, torch.ones(1, 4))
83
+ assert result.sum().item() == 12
84
+
85
+
86
+ def test_export_has_no_training_dependency():
87
+ root = Path(__file__).resolve().parents[1]
88
+ for name in ('qwen3_helpers', 'qwen3_visionzip', 'qwen3_wrapper'):
89
+ source = (root / 'scopd_eval' / f'{name}.py').read_text()
90
+ assert '/' + 'scratch/' not in source and '/' + 'project/' not in source
91
+ for node in ast.walk(ast.parse(source)):
92
+ if isinstance(node, ast.ImportFrom):
93
+ assert not (node.module or '').startswith('opsd.')
94
+
95
+
96
+ def test_reasoning_prompt_and_pixel_units_without_loading_model():
97
+ root = Path(__file__).resolve().parents[1]
98
+ source = ast.parse((root / 'scopd_eval/qwen3_wrapper.py').read_text())
99
+ functions = [n for n in source.body if isinstance(n, ast.FunctionDef)
100
+ and n.name in {'reasoning_suffix', '_round_budget'}]
101
+ namespace = {}
102
+ exec(compile(ast.Module(body=functions, type_ignores=[]), '<wrapper>', 'exec'), namespace)
103
+ assert '<analysis> </analysis>' in namespace['reasoning_suffix']('analysis')
104
+ assert namespace['_round_budget'](1280) == 1280 * 32 * 32
105
+ infer = (root / 'scopd_eval/infer.py').read_text()
106
+ assert "reasoning_tag='analysis'" in infer
107
+ assert "budget = {'retention_ratio': a.retention}" in infer
models.json CHANGED
@@ -251,6 +251,52 @@
251
  "lora_rank": 16,
252
  "lora_alpha": 32,
253
  "lora_dropout": 0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  }
255
  ]
256
  }
 
251
  "lora_rank": 16,
252
  "lora_alpha": 32,
253
  "lora_dropout": 0.0
254
+ },
255
+ {
256
+ "id": "qwen3-vl-4b-scopd",
257
+ "label": "Qwen3-VL-4B SCOPD",
258
+ "objective": "forward KL: KL(teacher || student)",
259
+ "selection": "all response tokens",
260
+ "adapter_sha256": "6aec6fba5176359d4d1a3d906d3722a51b9f7f21c79d5d5989120b075915102f",
261
+ "optimizer_updates": 320,
262
+ "base_model": "Qwen/Qwen3-VL-4B-Instruct",
263
+ "base_revision": "ebb281ec70b05090aa6165b016eac8ec08e71b17",
264
+ "merged": false,
265
+ "format": "peft_lora",
266
+ "dtype": "float32",
267
+ "inference_dtype": "bfloat16",
268
+ "questions_processed": 10240,
269
+ "path": "models/qwen3-vl-4b-scopd",
270
+ "tensor_count": 504,
271
+ "parameter_count": 33030144,
272
+ "weight_bytes": 132120576,
273
+ "lora_rank": 16,
274
+ "lora_alpha": 32,
275
+ "lora_dropout": 0.0
276
+ },
277
+ {
278
+ "id": "qwen3-vl-4b-scopd-plus",
279
+ "label": "Qwen3-VL-4B SCOPD+",
280
+ "objective": "forward KL: KL(teacher || student)",
281
+ "selection": "top 10% budget-JSD response tokens",
282
+ "selection_fraction": 0.1,
283
+ "budget_delta": 0.01,
284
+ "adapter_sha256": "febccb411829f5c314d421038c1cd89dcc543df074978778771504ab1dc91a0e",
285
+ "optimizer_updates": 320,
286
+ "base_model": "Qwen/Qwen3-VL-4B-Instruct",
287
+ "base_revision": "ebb281ec70b05090aa6165b016eac8ec08e71b17",
288
+ "merged": false,
289
+ "format": "peft_lora",
290
+ "dtype": "float32",
291
+ "inference_dtype": "bfloat16",
292
+ "questions_processed": 10240,
293
+ "path": "models/qwen3-vl-4b-scopd-plus",
294
+ "tensor_count": 504,
295
+ "parameter_count": 33030144,
296
+ "weight_bytes": 132120576,
297
+ "lora_rank": 16,
298
+ "lora_alpha": 32,
299
+ "lora_dropout": 0.0
300
  }
301
  ]
302
  }