KangHui2200 commited on
Commit
bab6333
·
1 Parent(s): 6b49fc0

Add PixelOne-Pro model cards and self-contained runtime

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +5 -0
  2. PixelOne-Pro-35B-A3B/.gitattributes +1 -0
  3. PixelOne-Pro-35B-A3B/README.md +71 -0
  4. PixelOne-Pro-35B-A3B/UPSTREAM_LICENSE +202 -0
  5. PixelOne-Pro-35B-A3B/UPSTREAM_NOTICE +4 -0
  6. PixelOne-Pro-35B-A3B/chat_template.jinja +154 -0
  7. PixelOne-Pro-35B-A3B/config.json +175 -0
  8. PixelOne-Pro-35B-A3B/evaluation.json +30 -0
  9. PixelOne-Pro-35B-A3B/model.safetensors.index.json +0 -0
  10. PixelOne-Pro-35B-A3B/pixelone.json +0 -0
  11. PixelOne-Pro-35B-A3B/processor_config.json +60 -0
  12. PixelOne-Pro-35B-A3B/runtime/THIRD_PARTY_NOTICES.md +9 -0
  13. PixelOne-Pro-35B-A3B/runtime/pyproject.toml +34 -0
  14. PixelOne-Pro-35B-A3B/runtime/src/jev_click_finetune/__init__.py +1 -0
  15. PixelOne-Pro-35B-A3B/runtime/src/jev_click_finetune/inputs.py +62 -0
  16. PixelOne-Pro-35B-A3B/runtime/src/jev_click_finetune/model.py +27 -0
  17. PixelOne-Pro-35B-A3B/runtime/src/jev_click_finetune/objective.py +39 -0
  18. PixelOne-Pro-35B-A3B/runtime/src/jev_fine_ablation/__init__.py +1 -0
  19. PixelOne-Pro-35B-A3B/runtime/src/jev_fine_ablation/distillation.py +142 -0
  20. PixelOne-Pro-35B-A3B/runtime/src/jev_fine_refine/__init__.py +1 -0
  21. PixelOne-Pro-35B-A3B/runtime/src/jev_fine_refine/objective.py +31 -0
  22. PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/__init__.py +1 -0
  23. PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/spatial_pointer/__init__.py +1 -0
  24. PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/spatial_pointer/data.py +1 -0
  25. PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/spatial_pointer/geometry.py +84 -0
  26. PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/spatial_pointer/model.py +80 -0
  27. PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/spatial_pointer/supervision.py +99 -0
  28. PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/t3/__init__.py +1 -0
  29. PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/t3/batching.py +58 -0
  30. PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/t3/common.py +2 -0
  31. PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/t3/model.py +142 -0
  32. PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/t3/states.py +101 -0
  33. PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/teacher_targets.py +42 -0
  34. PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/__init__.py +1 -0
  35. PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/attention.py +35 -0
  36. PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/full_training.py +133 -0
  37. PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/methods.py +3 -0
  38. PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/model.py +73 -0
  39. PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/objective.py +88 -0
  40. PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/portable_full.py +41 -0
  41. PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/speed_loss.py +29 -0
  42. PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/top100.py +42 -0
  43. PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/top20.py +51 -0
  44. PixelOne-Pro-35B-A3B/runtime/src/pixelone/__init__.py +8 -0
  45. PixelOne-Pro-35B-A3B/runtime/src/pixelone/assets/DejaVuSans-LICENSE.txt +78 -0
  46. PixelOne-Pro-35B-A3B/runtime/src/pixelone/assets/DejaVuSans.ttf +3 -0
  47. PixelOne-Pro-35B-A3B/runtime/src/pixelone/checkpoint.py +54 -0
  48. PixelOne-Pro-35B-A3B/runtime/src/pixelone/cli.py +74 -0
  49. PixelOne-Pro-35B-A3B/runtime/src/pixelone/data.py +131 -0
  50. PixelOne-Pro-35B-A3B/runtime/src/pixelone/export.py +85 -0
.gitattributes CHANGED
@@ -33,3 +33,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ PixelOne-Pro-35B-A3B/runtime/src/pixelone/assets/DejaVuSans.ttf filter=lfs diff=lfs merge=lfs -text
37
+ PixelOne-Pro-35B-A3B/tokenizer.json filter=lfs diff=lfs merge=lfs -text
38
+ PixelOne-Pro-4B/runtime/src/pixelone/assets/DejaVuSans.ttf filter=lfs diff=lfs merge=lfs -text
39
+ PixelOne-Pro-4B/tokenizer.json filter=lfs diff=lfs merge=lfs -text
40
+ assets/teaser.png filter=lfs diff=lfs merge=lfs -text
PixelOne-Pro-35B-A3B/.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
PixelOne-Pro-35B-A3B/README.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ language:
4
+ - en
5
+ tags:
6
+ - gui-grounding
7
+ - pixelone
8
+ - computer-use
9
+ - custom-code
10
+ - safetensors
11
+ ---
12
+
13
+ # PixelOne-Pro-35B-A3B
14
+
15
+ PixelOne-Pro-35B-A3B predicts an original-image click from a screenshot and an instruction in one visual encoding and one language-model forward. This is the final full-parameter 500K continuation from the PixelOne paper, with a trained visual encoder, native decision head and lightweight pixel head.
16
+
17
+ ## Use
18
+
19
+ This model is stored in the `PixelOne-Pro-35B-A3B` subfolder of [KangHui2200/PixleOne](https://huggingface.co/KangHui2200/PixleOne). The local-directory commands below remain supported. To load by repository ID, use `PixelOnePredictor.from_pretrained("KangHui2200/PixleOne", subfolder="PixelOne-Pro-35B-A3B", device="cuda:0")`, or add `--subfolder PixelOne-Pro-35B-A3B` to the CLI. Only the selected model is downloaded. Authenticate with Hugging Face if the repository is private.
20
+
21
+ The package is self-contained: all model weights and processor assets are included. No separate base-model weights, LoRA adapter or search teacher is needed at inference.
22
+
23
+ ```bash
24
+ python -m pip install ./runtime
25
+ python -m pip install flash-linear-attention==0.4.2 causal-conv1d==1.7.0 --no-build-isolation
26
+ pixelone infer --model . --image screenshot.png --instruction "Click the search button" --device cuda:0
27
+ ```
28
+
29
+ ```python
30
+ from PIL import Image
31
+ from pixelone import PixelOnePredictor
32
+
33
+ predictor = PixelOnePredictor.from_pretrained(".", device="cuda:0")
34
+ result = predictor.predict(Image.open("screenshot.png"), "Click the search button")
35
+ print(result["point"])
36
+ ```
37
+
38
+ Use the bundled `PixelOnePredictor`, not `AutoModelForCausalLM.generate` or a generic VideoJEV loader. The direct click head and its coarse-first decoder are essential parts of this checkpoint. `config.json` describes the native backbone; `pixelone.json` specifies the complete PixelOne inference contract and weight index.
39
+
40
+ ## Input and runtime
41
+
42
+ - Output: `[x, y]` in original screenshot pixels, with half-pixel centers.
43
+ - Image policy: pad to stride 32 without resizing; exclude padding from pixel selection. Inputs beyond the context budget fail rather than silently downsample.
44
+ - Attention: bidirectional masks in existing full-attention layers; native linear-attention computation; no autoregressive KV cache.
45
+ - Reference software: Python 3.12, PyTorch 2.11.0, Transformers 5.6.2, Triton 3.7.0, FLA 0.4.2 and causal-conv1d 1.7.0.
46
+ - Weights: approximately 68.7 GB across 80 safetensors shards, with the original BF16/FP32 partition. Activations require additional resolution-dependent memory. Do not cast the whole model to BF16/FP16.
47
+ - CUDA is required for the released mixed-precision weights. `kernel_backend="torch"` is an explicit diagnostic alternative, not the reported native-kernel latency configuration.
48
+
49
+ ## Evaluation
50
+
51
+ | Benchmark | Correct / targets | Accuracy (%) |
52
+ | --- | ---: | ---: |
53
+ | screenspot | 1166 / 1272 | 91.67 |
54
+ | screenspot-v2 | 1202 / 1272 | 94.50 |
55
+ | screenspot-pro | 1139 / 1581 | 72.04 |
56
+ | osworld-g | 392 / 510 | 76.86 |
57
+ | Equal-weight mean | — | 83.77 |
58
+
59
+ Scores use complete benchmark sets and original-image point-in-box correctness. `evaluation.json` retains the hit counts and unrounded accuracies. Weights come from update 1954; they were not reconstructed from adapters or quantized during packaging.
60
+
61
+ ## Training and limitations
62
+
63
+ The model inherits a 22K Top20+KD student, retains its learned pixel head, and continues on 500K targets. Full-parameter updates include the visual encoder. Spatial KD uses a frozen teacher's observed regions and is gated by teacher click correctness; every target still receives box supervision. The 200K PixelOne branch is separate and is not an intermediate stage of this Pro checkpoint.
64
+
65
+ This release includes weights, processor assets and executable source, but not upstream training screenshots, sampled target manifests, optimizer states or cached teacher traces. Native-resolution grounding remains limited by context length and available device memory. Applications must validate predicted actions and enforce user permissions before execution.
66
+
67
+ ## Verification and release status
68
+
69
+ All weight files were verified against the final research export, and the source evaluation matches the paper. Tiny dense/MoE CPU tests check the numerical readout, model round trip, training resume and export path. The packaging host has no working NVIDIA driver; full-scale CUDA smoke tests and latency have not been rerun there.
70
+
71
+ The model repository retains its existing MIT license metadata. Upstream Qwen/VideoJEV licenses and notices are retained in `UPSTREAM_LICENSE` and `UPSTREAM_NOTICE`; the bundled runtime and font include their upstream attribution. Repository visibility is controlled by the owner and was not changed during upload.
PixelOne-Pro-35B-A3B/UPSTREAM_LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Alibaba Cloud
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
PixelOne-Pro-35B-A3B/UPSTREAM_NOTICE ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ VideoJev uses native Qwen3.5 and Qwen3.5-MoE modules from Hugging Face Transformers.
2
+ Qwen3.5-4B and Qwen3.6-35B-A3B are provided by the Qwen team under Apache-2.0.
3
+ Training and optional grouped MoE inference use XTuner (InternLM), Apache-2.0.
4
+ VideoJev modifies the language readout and adds a trained cosine decision head.
PixelOne-Pro-35B-A3B/chat_template.jinja ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set image_count = namespace(value=0) %}
2
+ {%- set video_count = namespace(value=0) %}
3
+ {%- macro render_content(content, do_vision_count, is_system_content=false) %}
4
+ {%- if content is string %}
5
+ {{- content }}
6
+ {%- elif content is iterable and content is not mapping %}
7
+ {%- for item in content %}
8
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
9
+ {%- if is_system_content %}
10
+ {{- raise_exception('System message cannot contain images.') }}
11
+ {%- endif %}
12
+ {%- if do_vision_count %}
13
+ {%- set image_count.value = image_count.value + 1 %}
14
+ {%- endif %}
15
+ {%- if add_vision_id %}
16
+ {{- 'Picture ' ~ image_count.value ~ ': ' }}
17
+ {%- endif %}
18
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
19
+ {%- elif 'video' in item or item.type == 'video' %}
20
+ {%- if is_system_content %}
21
+ {{- raise_exception('System message cannot contain videos.') }}
22
+ {%- endif %}
23
+ {%- if do_vision_count %}
24
+ {%- set video_count.value = video_count.value + 1 %}
25
+ {%- endif %}
26
+ {%- if add_vision_id %}
27
+ {{- 'Video ' ~ video_count.value ~ ': ' }}
28
+ {%- endif %}
29
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
30
+ {%- elif 'text' in item %}
31
+ {{- item.text }}
32
+ {%- else %}
33
+ {{- raise_exception('Unexpected item type in content.') }}
34
+ {%- endif %}
35
+ {%- endfor %}
36
+ {%- elif content is none or content is undefined %}
37
+ {{- '' }}
38
+ {%- else %}
39
+ {{- raise_exception('Unexpected content type.') }}
40
+ {%- endif %}
41
+ {%- endmacro %}
42
+ {%- if not messages %}
43
+ {{- raise_exception('No messages provided.') }}
44
+ {%- endif %}
45
+ {%- if tools and tools is iterable and tools is not mapping %}
46
+ {{- '<|im_start|>system\n' }}
47
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
48
+ {%- for tool in tools %}
49
+ {{- "\n" }}
50
+ {{- tool | tojson }}
51
+ {%- endfor %}
52
+ {{- "\n</tools>" }}
53
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
54
+ {%- if messages[0].role == 'system' %}
55
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
56
+ {%- if content %}
57
+ {{- '\n\n' + content }}
58
+ {%- endif %}
59
+ {%- endif %}
60
+ {{- '<|im_end|>\n' }}
61
+ {%- else %}
62
+ {%- if messages[0].role == 'system' %}
63
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
64
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
65
+ {%- endif %}
66
+ {%- endif %}
67
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
68
+ {%- for message in messages[::-1] %}
69
+ {%- set index = (messages|length - 1) - loop.index0 %}
70
+ {%- if ns.multi_step_tool and message.role == "user" %}
71
+ {%- set content = render_content(message.content, false)|trim %}
72
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
73
+ {%- set ns.multi_step_tool = false %}
74
+ {%- set ns.last_query_index = index %}
75
+ {%- endif %}
76
+ {%- endif %}
77
+ {%- endfor %}
78
+ {%- if ns.multi_step_tool %}
79
+ {{- raise_exception('No user query found in messages.') }}
80
+ {%- endif %}
81
+ {%- for message in messages %}
82
+ {%- set content = render_content(message.content, true)|trim %}
83
+ {%- if message.role == "system" %}
84
+ {%- if not loop.first %}
85
+ {{- raise_exception('System message must be at the beginning.') }}
86
+ {%- endif %}
87
+ {%- elif message.role == "user" %}
88
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
89
+ {%- elif message.role == "assistant" %}
90
+ {%- set reasoning_content = '' %}
91
+ {%- if message.reasoning_content is string %}
92
+ {%- set reasoning_content = message.reasoning_content %}
93
+ {%- else %}
94
+ {%- if '</think>' in content %}
95
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
96
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
97
+ {%- endif %}
98
+ {%- endif %}
99
+ {%- set reasoning_content = reasoning_content|trim %}
100
+ {%- if (preserve_thinking is defined and preserve_thinking is true) or (loop.index0 > ns.last_query_index) %}
101
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
102
+ {%- else %}
103
+ {{- '<|im_start|>' + message.role + '\n' + content }}
104
+ {%- endif %}
105
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
106
+ {%- for tool_call in message.tool_calls %}
107
+ {%- if tool_call.function is defined %}
108
+ {%- set tool_call = tool_call.function %}
109
+ {%- endif %}
110
+ {%- if loop.first %}
111
+ {%- if content|trim %}
112
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
113
+ {%- else %}
114
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
115
+ {%- endif %}
116
+ {%- else %}
117
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
118
+ {%- endif %}
119
+ {%- if tool_call.arguments is defined %}
120
+ {%- for args_name, args_value in tool_call.arguments|items %}
121
+ {{- '<parameter=' + args_name + '>\n' }}
122
+ {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}
123
+ {{- args_value }}
124
+ {{- '\n</parameter>\n' }}
125
+ {%- endfor %}
126
+ {%- endif %}
127
+ {{- '</function>\n</tool_call>' }}
128
+ {%- endfor %}
129
+ {%- endif %}
130
+ {{- '<|im_end|>\n' }}
131
+ {%- elif message.role == "tool" %}
132
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
133
+ {{- '<|im_start|>user' }}
134
+ {%- endif %}
135
+ {{- '\n<tool_response>\n' }}
136
+ {{- content }}
137
+ {{- '\n</tool_response>' }}
138
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
139
+ {{- '<|im_end|>\n' }}
140
+ {%- elif loop.last %}
141
+ {{- '<|im_end|>\n' }}
142
+ {%- endif %}
143
+ {%- else %}
144
+ {{- raise_exception('Unexpected message role.') }}
145
+ {%- endif %}
146
+ {%- endfor %}
147
+ {%- if add_generation_prompt %}
148
+ {{- '<|im_start|>assistant\n' }}
149
+ {%- if enable_thinking is defined and enable_thinking is false %}
150
+ {{- '<think>\n\n</think>\n\n' }}
151
+ {%- else %}
152
+ {{- '<think>\n' }}
153
+ {%- endif %}
154
+ {%- endif %}
PixelOne-Pro-35B-A3B/config.json ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "VideoJevForVideoUnderstanding"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_videojev.VideoJevConfig",
7
+ "AutoModel": "modeling_videojev.VideoJevForVideoUnderstanding"
8
+ },
9
+ "backbone_config": {
10
+ "architectures": [
11
+ "Qwen3_5MoeForConditionalGeneration"
12
+ ],
13
+ "dtype": "bfloat16",
14
+ "image_token_id": 248056,
15
+ "model_type": "qwen3_5_moe",
16
+ "text_config": {
17
+ "_name_or_path": "",
18
+ "architectures": null,
19
+ "attention_bias": false,
20
+ "attention_dropout": 0.0,
21
+ "attn_output_gate": true,
22
+ "bos_token_id": 248044,
23
+ "chunk_size_feed_forward": 0,
24
+ "dtype": "bfloat16",
25
+ "eos_token_id": 248044,
26
+ "full_attention_interval": 4,
27
+ "head_dim": 256,
28
+ "hidden_act": "silu",
29
+ "hidden_size": 2048,
30
+ "id2label": {
31
+ "0": "LABEL_0",
32
+ "1": "LABEL_1"
33
+ },
34
+ "initializer_range": 0.02,
35
+ "is_encoder_decoder": false,
36
+ "label2id": {
37
+ "LABEL_0": 0,
38
+ "LABEL_1": 1
39
+ },
40
+ "layer_types": [
41
+ "linear_attention",
42
+ "linear_attention",
43
+ "linear_attention",
44
+ "full_attention",
45
+ "linear_attention",
46
+ "linear_attention",
47
+ "linear_attention",
48
+ "full_attention",
49
+ "linear_attention",
50
+ "linear_attention",
51
+ "linear_attention",
52
+ "full_attention",
53
+ "linear_attention",
54
+ "linear_attention",
55
+ "linear_attention",
56
+ "full_attention",
57
+ "linear_attention",
58
+ "linear_attention",
59
+ "linear_attention",
60
+ "full_attention",
61
+ "linear_attention",
62
+ "linear_attention",
63
+ "linear_attention",
64
+ "full_attention",
65
+ "linear_attention",
66
+ "linear_attention",
67
+ "linear_attention",
68
+ "full_attention",
69
+ "linear_attention",
70
+ "linear_attention",
71
+ "linear_attention",
72
+ "full_attention",
73
+ "linear_attention",
74
+ "linear_attention",
75
+ "linear_attention",
76
+ "full_attention",
77
+ "linear_attention",
78
+ "linear_attention",
79
+ "linear_attention",
80
+ "full_attention"
81
+ ],
82
+ "linear_conv_kernel_dim": 4,
83
+ "linear_key_head_dim": 128,
84
+ "linear_num_key_heads": 16,
85
+ "linear_num_value_heads": 32,
86
+ "linear_value_head_dim": 128,
87
+ "mamba_ssm_dtype": "float32",
88
+ "max_position_embeddings": 262144,
89
+ "model_type": "qwen3_5_moe_text",
90
+ "moe_intermediate_size": 512,
91
+ "mtp_num_hidden_layers": 1,
92
+ "mtp_use_dedicated_embeddings": false,
93
+ "num_attention_heads": 16,
94
+ "num_experts": 256,
95
+ "num_experts_per_tok": 8,
96
+ "num_hidden_layers": 40,
97
+ "num_key_value_heads": 2,
98
+ "output_attentions": false,
99
+ "output_hidden_states": false,
100
+ "output_router_logits": false,
101
+ "pad_token_id": null,
102
+ "partial_rotary_factor": 0.25,
103
+ "problem_type": null,
104
+ "return_dict": true,
105
+ "rms_norm_eps": 1e-06,
106
+ "rope_parameters": {
107
+ "mrope_interleaved": true,
108
+ "mrope_section": [
109
+ 11,
110
+ 11,
111
+ 10
112
+ ],
113
+ "partial_rotary_factor": 0.25,
114
+ "rope_theta": 10000000,
115
+ "rope_type": "default"
116
+ },
117
+ "router_aux_loss_coef": 0.001,
118
+ "shared_expert_intermediate_size": 512,
119
+ "tie_word_embeddings": false,
120
+ "use_cache": true,
121
+ "vocab_size": 248320
122
+ },
123
+ "tie_word_embeddings": false,
124
+ "video_token_id": 248057,
125
+ "vision_config": {
126
+ "_name_or_path": "",
127
+ "architectures": null,
128
+ "chunk_size_feed_forward": 0,
129
+ "deepstack_visual_indexes": [],
130
+ "depth": 27,
131
+ "dtype": "bfloat16",
132
+ "hidden_act": "gelu_pytorch_tanh",
133
+ "hidden_size": 1152,
134
+ "id2label": {
135
+ "0": "LABEL_0",
136
+ "1": "LABEL_1"
137
+ },
138
+ "in_channels": 3,
139
+ "initializer_range": 0.02,
140
+ "intermediate_size": 4304,
141
+ "is_encoder_decoder": false,
142
+ "label2id": {
143
+ "LABEL_0": 0,
144
+ "LABEL_1": 1
145
+ },
146
+ "model_type": "qwen3_5_moe_vision",
147
+ "num_heads": 16,
148
+ "num_position_embeddings": 2304,
149
+ "out_hidden_size": 2048,
150
+ "output_attentions": false,
151
+ "output_hidden_states": false,
152
+ "patch_size": 16,
153
+ "problem_type": null,
154
+ "return_dict": true,
155
+ "spatial_merge_size": 2,
156
+ "temporal_patch_size": 2
157
+ },
158
+ "vision_end_token_id": 248054,
159
+ "vision_start_token_id": 248053
160
+ },
161
+ "checkpoint_id": "89988f08-2a17-4f7e-99b6-6fff923806cf",
162
+ "decide_token_id": 248077,
163
+ "decoder": {
164
+ "postprocess": "round_repair_clamp_v1",
165
+ "smooth": 1,
166
+ "threshold": 0.25
167
+ },
168
+ "dtype": "bfloat16",
169
+ "head_dim": 512,
170
+ "head_logit_scale": 10.0,
171
+ "model_type": "videojev",
172
+ "option_end_token_id": 248078,
173
+ "tie_word_embeddings": false,
174
+ "transformers_version": "5.14.1"
175
+ }
PixelOne-Pro-35B-A3B/evaluation.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "results": [
3
+ {
4
+ "benchmark": "screenspot",
5
+ "count": 1272,
6
+ "hits": 1166,
7
+ "accuracy": 0.9166666666666666
8
+ },
9
+ {
10
+ "benchmark": "screenspot-v2",
11
+ "count": 1272,
12
+ "hits": 1202,
13
+ "accuracy": 0.9449685534591195
14
+ },
15
+ {
16
+ "benchmark": "screenspot-pro",
17
+ "count": 1581,
18
+ "hits": 1139,
19
+ "accuracy": 0.7204301075268817
20
+ },
21
+ {
22
+ "benchmark": "osworld-g",
23
+ "count": 510,
24
+ "hits": 392,
25
+ "accuracy": 0.7686274509803922
26
+ }
27
+ ],
28
+ "mean_accuracy": 0.837673194658265,
29
+ "aggregation": "Equal weight per benchmark, not pooled target accuracy"
30
+ }
PixelOne-Pro-35B-A3B/model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
PixelOne-Pro-35B-A3B/pixelone.json ADDED
The diff for this file is too large to render. See raw diff
 
PixelOne-Pro-35B-A3B/processor_config.json ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "image_processor": {
3
+ "do_convert_rgb": true,
4
+ "do_normalize": true,
5
+ "do_rescale": true,
6
+ "do_resize": true,
7
+ "image_mean": [
8
+ 0.5,
9
+ 0.5,
10
+ 0.5
11
+ ],
12
+ "image_processor_type": "Qwen2VLImageProcessor",
13
+ "image_std": [
14
+ 0.5,
15
+ 0.5,
16
+ 0.5
17
+ ],
18
+ "merge_size": 2,
19
+ "patch_size": 16,
20
+ "resample": 3,
21
+ "rescale_factor": 0.00392156862745098,
22
+ "size": {
23
+ "longest_edge": 16777216,
24
+ "shortest_edge": 65536
25
+ },
26
+ "temporal_patch_size": 2
27
+ },
28
+ "processor_class": "Qwen3VLProcessor",
29
+ "video_processor": {
30
+ "do_convert_rgb": true,
31
+ "do_normalize": true,
32
+ "do_rescale": true,
33
+ "do_resize": true,
34
+ "do_sample_frames": true,
35
+ "fps": 2,
36
+ "image_mean": [
37
+ 0.5,
38
+ 0.5,
39
+ 0.5
40
+ ],
41
+ "image_std": [
42
+ 0.5,
43
+ 0.5,
44
+ 0.5
45
+ ],
46
+ "max_frames": 768,
47
+ "merge_size": 2,
48
+ "min_frames": 4,
49
+ "patch_size": 16,
50
+ "resample": 3,
51
+ "rescale_factor": 0.00392156862745098,
52
+ "return_metadata": false,
53
+ "size": {
54
+ "longest_edge": 25165824,
55
+ "shortest_edge": 4096
56
+ },
57
+ "temporal_patch_size": 2,
58
+ "video_processor_type": "Qwen3VLVideoProcessor"
59
+ }
60
+ }
PixelOne-Pro-35B-A3B/runtime/THIRD_PARTY_NOTICES.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Third-party attribution
2
+
3
+ - VideoJEV model code and native decision interface are retained in `src/videojev_hf/`. The supplied upstream Apache-2.0 license and notice are in `third_party/VideoJev-LICENSE` and `third_party/VideoJev-NOTICE`.
4
+ - Qwen3.5-4B and Qwen3.6-35B-A3B provide the underlying dense/MoE architectures and base weights. Their upstream licenses remain applicable to derived models.
5
+ - Transformers, PyTorch, Accelerate, safetensors and optional FLA/causal-conv1d kernels are installed dependencies, not vendored replacements. Their respective licenses apply.
6
+ - DejaVuSans is included only for the teacher's labeled-grid rendering. Its license is bundled beside the font in `src/pixelone/assets/DejaVuSans-LICENSE.txt`.
7
+ - An optional historical XTuner expert path remains in the inherited VideoJEV source. The published Pro-35B recipe uses PyTorch `grouped_mm`, not that optional XTuner path.
8
+
9
+ The release license for new PixelOne code and derived model weights still requires maintainer confirmation. This notice preserves upstream attribution and does not itself grant a new license.
PixelOne-Pro-35B-A3B/runtime/pyproject.toml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pixelone-grounding"
7
+ version = "0.1.0"
8
+ description = "Native-resolution GUI grounding with search distillation and direct pixel prediction"
9
+ requires-python = ">=3.10"
10
+ dependencies = [
11
+ "torch>=2.11,<2.12", "transformers==5.6.2", "accelerate>=1.10",
12
+ "safetensors>=0.4", "huggingface-hub>=0.30", "numpy>=1.26,<3",
13
+ "Pillow>=10", "einops>=0.8", "scipy>=1.12", "packaging>=20",
14
+ ]
15
+
16
+ [project.optional-dependencies]
17
+ native = ["flash-linear-attention==0.4.2", "causal-conv1d==1.7.0"]
18
+ test = ["pytest>=8"]
19
+
20
+ [project.scripts]
21
+ pixelone = "pixelone.cli:main"
22
+
23
+ [project.urls]
24
+ Repository = "https://github.com/tiankanghui/PixleOne"
25
+
26
+ [tool.setuptools.packages.find]
27
+ where = ["src"]
28
+
29
+ [tool.setuptools.package-data]
30
+ pixelone = ["assets/*"]
31
+
32
+ [tool.pytest.ini_options]
33
+ testpaths = ["tests"]
34
+ pythonpath = ["src"]
PixelOne-Pro-35B-A3B/runtime/src/jev_click_finetune/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
PixelOne-Pro-35B-A3B/runtime/src/jev_click_finetune/inputs.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One static native screenshot, one query, spatial visual-token candidates."""
2
+
3
+ import hashlib
4
+
5
+ import numpy as np
6
+ import torch
7
+ from PIL import Image
8
+ from transformers.video_utils import VideoMetadata
9
+
10
+ from jev_spatial_distill.spatial_pointer.geometry import Layout
11
+
12
+
13
+ def render(image, subdivisions=32):
14
+ layout = Layout(*image.size, subdivisions=subdivisions)
15
+ canvas = Image.new('RGB', layout.canvas_size, 'white')
16
+ canvas.paste(image.convert('RGB'), (0,0))
17
+ return [canvas, canvas], layout
18
+
19
+
20
+ def query_group(processor, record, instruction):
21
+ from videojev_hf.processing_videojev import DECIDE
22
+ if not instruction.strip() or '<|' in instruction:
23
+ raise ValueError('Expected an instruction without model control tokens')
24
+ if record['grid_thw'][0] != 1:
25
+ raise ValueError('Spatial pointer uses exactly one static frame pair')
26
+ metadata = VideoMetadata(total_num_frames=2, fps=2., frames_indices=[0,1])
27
+ replacement = processor.replace_video_token(dict(video_grid_thw=np.asarray([[1,2,2]]),video_metadata=[metadata]),video_idx=0)
28
+ content = [dict(type='video',video='provided_in_memory'),dict(type='text',text=(
29
+ f'Locate the UI element for this instruction: "{instruction}". '
30
+ 'Select a valid click position inside that element in the screenshot.\n'+DECIDE))]
31
+ text = processor.apply_chat_template([dict(role='user',content=content)],tokenize=False,add_generation_prompt=False)
32
+ texts,_ = processor.get_text_with_replacements([text],[],[replacement],[])
33
+ encoded = processor(text=texts,return_tensors='pt')
34
+ ids,types = encoded['input_ids'],encoded['mm_token_type_ids']
35
+ slots = ids[0] == processor.video_token_id
36
+ if int(slots.sum()) != 1:raise ValueError('Expected one temporary video slot')
37
+ repeats = torch.ones(ids.shape[1],dtype=torch.long);repeats[slots] = record['tokens']
38
+ ids = torch.repeat_interleave(ids,repeats,dim=1)
39
+ types = torch.repeat_interleave(types,repeats,dim=1)
40
+ spatial = (ids[0] == processor.video_token_id).nonzero().flatten()
41
+ query = (ids[0] == processor.tokenizer.convert_tokens_to_ids(DECIDE)).nonzero().flatten()
42
+ if query.numel() != 1 or spatial.numel() != record['tokens'] or spatial[-1] >= query[0]:
43
+ raise ValueError('Spatial/query slots are not intact')
44
+ if (ids.shape[1]+63)//64*64 > record['context']:
45
+ raise ValueError('Native image and instruction exceed context; no silent resize')
46
+ return dict(input_ids=ids,mm_token_type_ids=types,video_grid_thw=torch.tensor([record['grid_thw']]),
47
+ pair_indices=spatial[None],query_indices=query,score_mask=torch.ones((1,len(spatial)),dtype=torch.bool),
48
+ decision_tasks=torch.ones(1,dtype=torch.long))
49
+
50
+
51
+ def prepare(model, processor, image, instruction, subdivisions=32):
52
+ from scripts.refine_spatial_jev import encode_views
53
+ views,layout = render(image,subdivisions)
54
+ features,record = encode_views(model.native,processor,views,'native')
55
+ if record['tokens'] != layout.count or record['grid_thw'] != [1,layout.rows*2,layout.cols*2]:
56
+ raise ValueError('Native visual grid does not match original-pixel support')
57
+ if features.is_inference() or not getattr(model.native,'train_vision',False):
58
+ with torch.inference_mode(False):features = features.detach().clone()
59
+ group = query_group(processor,record,instruction)
60
+ return group,features,layout,dict(visual_tokens=record['tokens'],input_tokens=group['input_ids'].shape[1],
61
+ frames=2,canvas_size=list(layout.canvas_size),original_size=list(image.size),padding_origin=[0,0],
62
+ frame_sha256=[hashlib.sha256(v.tobytes()).hexdigest() for v in views])
PixelOne-Pro-35B-A3B/runtime/src/jev_click_finetune/model.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Detached region routing after one shared native LM pass; unchanged parameters."""
2
+
3
+ import torch
4
+ from jev_spatial_distill.spatial_pointer.model import SpatialStudent
5
+
6
+
7
+ def route(coarse, required=None, positive=None, topk=4):
8
+ # Inference uses only coarse logits. Training adds GT/KD support, without
9
+ # inserting GT into the image, text or language-model attention.
10
+ if required is None:
11
+ return coarse.detach().argmax().reshape(1)
12
+ values = list(required)
13
+ values += coarse.detach().topk(min(topk, len(coarse))).indices.tolist()
14
+ if positive is not None:
15
+ pos = positive.to(coarse.device).nonzero().flatten()
16
+ if not len(pos):
17
+ raise ValueError('No valid GT regions to route')
18
+ values += pos[coarse.detach()[pos].topk(min(topk, len(pos))).indices].tolist()
19
+ return torch.tensor(list(dict.fromkeys(values)), device=coarse.device, dtype=torch.long)
20
+
21
+
22
+ class ClickStudent(SpatialStudent):
23
+ def forward(self, group, features, layout, required=None, positive=None, topk=4):
24
+ spatial, query = self.encode_readout(group, features)
25
+ coarse = self.native.head(spatial[None], query[None])[0]
26
+ parents = route(coarse, required, positive, topk)
27
+ return dict(coarse=coarse, fine=self.spatial(spatial, query, layout, parents), parents=parents)
PixelOne-Pro-35B-A3B/runtime/src/jev_click_finetune/objective.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Set likelihood for valid pixel-center clicks, with sparse fine supervision."""
2
+
3
+ import torch
4
+
5
+
6
+ def support(layout, box, device=None):
7
+ # Reuse strict GT validation; representability is checked against the full set.
8
+ layout.center_target(box)
9
+ xy = layout.positions(device)
10
+ valid = layout.valid(device)
11
+ positive = (valid & (xy[..., 0] >= box[0]) & (xy[..., 0] <= box[2])
12
+ & (xy[..., 1] >= box[1]) & (xy[..., 1] <= box[3]))
13
+ if not positive.any():
14
+ raise ValueError('GT box contains no representable pixel center')
15
+ return valid, positive
16
+
17
+
18
+ def set_nll(logits, valid, positive):
19
+ if logits.shape != valid.shape or valid.shape != positive.shape:
20
+ raise ValueError('Click support shapes differ')
21
+ if (positive & ~valid).any() or not positive.any(-1).all():
22
+ raise ValueError('Positive click support must be nonempty and valid')
23
+ logits = logits.float()
24
+ return (logits.masked_fill(~valid, -torch.inf).logsumexp(-1)
25
+ - logits.masked_fill(~positive, -torch.inf).logsumexp(-1))
26
+
27
+
28
+ def click_loss(output, valid, positive):
29
+ coarse = set_nll(output['coarse'], valid.any(-1), positive.any(-1))
30
+ parents = output['parents']
31
+ selected_positive = positive[parents]
32
+ keep = selected_positive.any(-1)
33
+ if not keep.any():
34
+ raise ValueError('Routing omitted every valid GT region')
35
+ # Never force a point into an incorrect predicted region. Those regions are
36
+ # suppressed by the coarse objective; fine labels exist only in region ∩ GT.
37
+ fine = set_nll(output['fine'][keep], valid[parents][keep], selected_positive[keep]).mean()
38
+ return coarse + fine, dict(coarse=float(coarse.detach()), fine=float(fine.detach()),
39
+ supervised_regions=int(keep.sum()))
PixelOne-Pro-35B-A3B/runtime/src/jev_fine_ablation/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
PixelOne-Pro-35B-A3B/runtime/src/jev_fine_ablation/distillation.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Keep teacher routing fixed; compare pixel, coarse-only and per-ROI region KD."""
2
+
3
+ import math
4
+ import torch
5
+ from torch.nn import functional as F
6
+ from jev_spatial_distill.spatial_pointer.supervision import kd_loss as pixel_kd_loss
7
+ from spatial_pro_experiments.fast import cell_candidates
8
+
9
+
10
+ def build_region_targets(prediction, layout, soft, temperature=2.):
11
+ """CPU geometry only, with the same trusted-teacher gate and parents as pixel KD.
12
+
13
+ Each actual pixel center belongs to exactly one half-open leaf in each ROI.
14
+ Overlapping ROIs are independent observations. Empty leaves/ROIs are reported,
15
+ never assigned a fabricated student probability or treated as negative targets.
16
+ """
17
+ if not math.isfinite(temperature) or temperature <= 0:
18
+ raise ValueError('Positive finite temperature required')
19
+ if not soft or not soft['enabled']:
20
+ return None
21
+ parents = soft['parents'].cpu()
22
+ local = torch.arange(layout.fine_count)
23
+ unit = layout.stride / layout.subdivisions
24
+ x = (parents[:, None] % layout.cols)*32 + (local % layout.subdivisions + .5)*unit
25
+ y = (parents[:, None] // layout.cols)*32 + (local // layout.subdivisions + .5)*unit
26
+ x, y = x.double(), y.double()
27
+ valid = (x < layout.width) & (y < layout.height)
28
+ # Normalize fine probabilities over every valid point in a parent, not only
29
+ # the part covered by a crop, before forming the joint student point measure.
30
+ result = dict(parents=parents, valid=valid, rois=[], temperature=temperature)
31
+ stage = prediction['stages'][-1]
32
+ cells = stage['cells_per_axis']
33
+ if not isinstance(cells, int) or cells < 1 or not stage['traces']:
34
+ raise ValueError('Invalid teacher region partition')
35
+ roi_scores = []
36
+ for trace in stage['traces']:
37
+ bounds = trace['crop_bounds']
38
+ left, top, right, bottom = bounds
39
+ if not all(math.isfinite(v) for v in bounds) or not (0 <= left < right <= layout.width and 0 <= top < bottom <= layout.height):
40
+ raise ValueError('Teacher ROI is outside the original image')
41
+ leaves = sorted(cell_candidates(bounds, trace['predictions'], cells, trace['parent_score']),
42
+ key=lambda c: (c['row'], c['column']))
43
+ scores = torch.tensor([c['score'] for c in leaves], dtype=torch.float64)
44
+ if not torch.isfinite(scores).all():
45
+ raise ValueError('Invalid teacher leaf scores')
46
+ q = (scores / temperature).softmax(0)
47
+ present = valid & (x >= left) & (x < right) & (y >= top) & (y < bottom)
48
+ flat = torch.nonzero(present.flatten(), as_tuple=False).flatten()
49
+ xx, yy = x.flatten()[flat], y.flatten()[flat]
50
+ edges_x = torch.tensor([left+(right-left)*k/cells for k in range(1, cells)], dtype=torch.float64)
51
+ edges_y = torch.tensor([top+(bottom-top)*k/cells for k in range(1, cells)], dtype=torch.float64)
52
+ leaf_ids = torch.bucketize(yy.contiguous(), edges_y, right=True)*cells + torch.bucketize(xx.contiguous(), edges_x, right=True)
53
+ # Independent geometric count catches missing parents in the retained
54
+ # original routing. No silent clipping of teacher support is allowed.
55
+ nx = max(0, min(layout.width, math.ceil(right/unit-.5))-max(0, math.ceil(left/unit-.5)))
56
+ ny = max(0, min(layout.height, math.ceil(bottom/unit-.5))-max(0, math.ceil(top/unit-.5)))
57
+ if flat.numel() != nx*ny:
58
+ raise ValueError('Original teacher routing omits representable ROI pixel centers')
59
+ represented = torch.bincount(leaf_ids, minlength=cells*cells) > 0
60
+ dropped = float(q[~represented].sum())
61
+ if represented.any():
62
+ truth = q[represented] / q[represented].sum()
63
+ else:
64
+ truth = torch.empty(0, dtype=torch.float64)
65
+ roi_scores.append(trace['parent_score'] + math.log(max(leaves[0]['presence_probability'], 1e-12)))
66
+ result['rois'].append(dict(flat=flat, leaf_ids=leaf_ids, represented=represented,
67
+ truth=truth.float(), cells=cells*cells, point_count=len(flat),
68
+ unrepresented_teacher_mass=dropped, bounds=list(bounds)))
69
+ weights = torch.tensor(roi_scores, dtype=torch.float64).softmax(0)
70
+ nonempty = torch.tensor([bool(r['point_count']) for r in result['rois']])
71
+ result['dropped_roi_weight'] = float(weights[~nonempty].sum())
72
+ result['unrepresented_teacher_mass'] = sum(float(w)*r['unrepresented_teacher_mass'] for w,r in zip(weights,result['rois']))
73
+ for i, roi in enumerate(result['rois']):
74
+ roi['weight'] = float(weights[i]/weights[nonempty].sum()) if nonempty[i] else 0.
75
+ return result
76
+
77
+
78
+ def segment_logsumexp(values, indices, size):
79
+ """Stable grouped sum; absent cells remain -inf and never enter KL."""
80
+ peak = torch.full((size,), -torch.inf, dtype=values.dtype, device=values.device)
81
+ peak.scatter_reduce_(0, indices, values.detach(), reduce='amax', include_self=True)
82
+ sums = torch.zeros_like(peak).scatter_add(0, indices, (values-peak[indices]).exp())
83
+ return peak + sums.clamp_min(torch.finfo(values.dtype).tiny).log()
84
+
85
+
86
+ def region_fine_kd(output, target, parent_order, temperature):
87
+ zero = output['fine'].float().sum()*0
88
+ if target is None:
89
+ return zero, dict(region_rois=0, region_points=0, region_cells=0,
90
+ unrepresented_teacher_mass=0., dropped_roi_weight=0.)
91
+ if target['temperature'] != temperature:
92
+ raise ValueError('Teacher and student KD temperatures differ')
93
+ lookup = {int(p):i for i,p in enumerate(parent_order)}
94
+ if len(lookup) != len(parent_order) or any(int(p) not in lookup for p in target['parents']):
95
+ raise ValueError('Region KD teacher parents were not routed exactly')
96
+ device = output['fine'].device
97
+ rows = torch.tensor([lookup[int(p)] for p in target['parents']], device=device)
98
+ parents = target['parents'].to(device)
99
+ valid = target['valid'].to(device)
100
+ log_fine = (output['fine'][rows].float()/temperature).masked_fill(~valid, -torch.inf).log_softmax(-1)
101
+ log_joint = (output['coarse'][parents].float()/temperature)[:, None] + log_fine
102
+ loss = zero
103
+ for roi in target['rois']:
104
+ if not roi['point_count']:
105
+ continue
106
+ values = log_joint.flatten()[roi['flat'].to(device)]
107
+ log_mass = segment_logsumexp(values, roi['leaf_ids'].to(device), roi['cells'])
108
+ log_probs = log_mass[roi['represented'].to(device)].log_softmax(0)
109
+ loss = loss + roi['weight']*F.kl_div(log_probs, roi['truth'].to(device), reduction='sum')*temperature**2
110
+ return loss, dict(region_rois=sum(r['point_count'] > 0 for r in target['rois']),
111
+ region_points=sum(r['point_count'] for r in target['rois']),
112
+ region_cells=sum(int(r['represented'].sum()) for r in target['rois']),
113
+ unrepresented_teacher_mass=target['unrepresented_teacher_mass'], dropped_roi_weight=target['dropped_roi_weight'])
114
+
115
+
116
+ def distillation_loss(output, soft, parent_order, mode, temperature=2., region_target=None):
117
+ if mode not in ('no_fine_kd', 'region_kd', 'interior'):
118
+ raise ValueError('Unknown fine KD ablation')
119
+ coarse, fine = output['coarse'].float(), output['fine'].float()
120
+ zero = coarse.sum()*0 + fine.sum()*0
121
+ if not soft or not soft['enabled']:
122
+ return zero, dict(kd_enabled=0, observed_parents=0, observed_pixels=0), dict(mode=mode, coarse=0., fine=0.)
123
+ parents = soft['parents'].to(coarse.device)
124
+ mass = soft['mass'].to(coarse.device)
125
+ coarse_mass = mass.sum(-1)
126
+ truth = coarse_mass.pow(1/temperature);truth = truth/truth.sum()
127
+ rank = F.kl_div(F.log_softmax(coarse[parents]/temperature, -1), truth, reduction='sum')*temperature**2
128
+ terms = dict(kd_enabled=1, observed_parents=len(parents), observed_pixels=int((mass > 0).sum()))
129
+ extra = {}
130
+ if mode == 'interior':
131
+ total, original_terms = pixel_kd_loss(output, soft, parent_order, temperature)
132
+ if original_terms != terms:
133
+ raise ValueError('Original KD support changed')
134
+ conditional = total-rank
135
+ elif mode == 'no_fine_kd':
136
+ conditional = zero;total = rank+zero
137
+ else:
138
+ if region_target is None:
139
+ raise ValueError('Enabled teacher requires region geometry')
140
+ conditional, extra = region_fine_kd(output, region_target, parent_order, temperature)
141
+ total = rank+conditional
142
+ return total, terms, dict(mode=mode, coarse=float(rank.detach()), fine=float(conditional.detach()), **extra)
PixelOne-Pro-35B-A3B/runtime/src/jev_fine_refine/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
PixelOne-Pro-35B-A3B/runtime/src/jev_fine_refine/objective.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A GT-valid maximum must beat outside candidates; padding is never negative."""
2
+
3
+ import torch
4
+ from torch.nn import functional as F
5
+ from jev_click_finetune.objective import set_nll
6
+
7
+
8
+ def winner_loss(logits,valid,positive):
9
+ if logits.ndim!=2 or logits.shape!=valid.shape or valid.shape!=positive.shape or valid.dtype!=torch.bool or positive.dtype!=torch.bool:
10
+ raise ValueError('Winner support shapes/types differ')
11
+ if not positive.any(-1).all() or (positive & ~valid).any():
12
+ raise ValueError('Every fine row needs nonempty valid GT support')
13
+ z=logits.float();negative=valid & ~positive;active=negative.any(-1)
14
+ # Fully GT-covered rows need no point constraint. Do not differentiate an
15
+ # all--inf logsumexp: it can create NaNs even when multiplied by zero.
16
+ zero=z.sum()*0
17
+ if not active.any():return zero
18
+ selected=z[active];pos=positive[active];neg=negative[active]
19
+ indices=selected.detach().masked_fill(~pos,-torch.inf).argmax(-1)
20
+ best=selected.gather(-1,indices[:,None]).squeeze(-1)
21
+ wrong=selected.masked_fill(~neg,-torch.inf).logsumexp(-1)
22
+ # Same denominator as the set-loss control, including zero-loss full rows.
23
+ return F.softplus(wrong-best).sum()/len(z)+zero
24
+
25
+
26
+ def fine_objective(output,valid,positive):
27
+ coarse=set_nll(output['coarse'],valid.any(-1),positive.any(-1))
28
+ parents=output['parents'];truth=positive[parents];keep=truth.any(-1)
29
+ if not keep.any():raise ValueError('No supervised positive region was routed')
30
+ fine=winner_loss(output['fine'][keep],valid[parents][keep],truth[keep])
31
+ return coarse+fine,dict(coarse=float(coarse.detach()),fine=float(fine.detach()),supervised_regions=int(keep.sum()))
PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/spatial_pointer/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/spatial_pointer/data.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from pixelone.io import file_sha256 as sha
PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/spatial_pointer/geometry.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Explicit original-pixel support, including padded-border masks."""
2
+
3
+ from dataclasses import dataclass
4
+ import math
5
+
6
+ import torch
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class Layout:
11
+ width: int
12
+ height: int
13
+ stride: int = 32
14
+ subdivisions: int = 32
15
+
16
+ def __post_init__(self):
17
+ if min(self.width, self.height) < 1 or self.stride != 32:
18
+ raise ValueError('Positive image dimensions and the native 32-pixel stride required')
19
+ if self.subdivisions < 1 or self.stride % self.subdivisions:
20
+ raise ValueError('Subdivisions must divide the native stride')
21
+
22
+ @property
23
+ def cols(self):return math.ceil(self.width / self.stride)
24
+
25
+ @property
26
+ def rows(self):return math.ceil(self.height / self.stride)
27
+
28
+ @property
29
+ def count(self):return self.rows * self.cols
30
+
31
+ @property
32
+ def canvas_size(self):return self.cols*self.stride, self.rows*self.stride
33
+
34
+ @property
35
+ def fine_count(self):return self.subdivisions**2
36
+
37
+ def positions(self, device=None):
38
+ parent = torch.arange(self.count, device=device)
39
+ fine = torch.arange(self.fine_count, device=device)
40
+ unit = self.stride / self.subdivisions
41
+ x = (parent[:, None] % self.cols)*self.stride + (fine[None] % self.subdivisions + .5)*unit
42
+ y = (parent[:, None] // self.cols)*self.stride + (fine[None] // self.subdivisions + .5)*unit
43
+ return torch.stack((x, y), -1)
44
+
45
+ def valid(self, device=None):
46
+ xy = self.positions(device)
47
+ return (xy[..., 0] < self.width) & (xy[..., 1] < self.height)
48
+
49
+ def center_target(self, box):
50
+ if len(box) != 4 or not all(math.isfinite(v) for v in box) or not (
51
+ 0 <= box[0] < box[2] <= self.width and 0 <= box[1] < box[3] <= self.height):
52
+ raise ValueError('Invalid original-pixel GT box')
53
+ x, y = (box[0]+box[2])/2, (box[1]+box[3])/2
54
+ col, row = int(x/self.stride), int(y/self.stride)
55
+ unit = self.stride/self.subdivisions
56
+ u, v = int((x-col*self.stride)/unit), int((y-row*self.stride)/unit)
57
+ parent, fine = row*self.cols+col, v*self.subdivisions+u
58
+ point = [(col*self.stride+(u+.5)*unit), (row*self.stride+(v+.5)*unit)]
59
+ representable = box[0] <= point[0] <= box[2] and box[1] <= point[1] <= box[3]
60
+ return dict(parent=parent, fine=fine, center=[x,y], quantized_point=point, representable=representable)
61
+
62
+
63
+ def joint_log_probs(coarse, fine, valid):
64
+ if fine.shape != valid.shape or coarse.shape != fine.shape[:1] or valid.dtype != torch.bool:
65
+ raise ValueError('Hierarchical readout shapes differ')
66
+ parents = valid.any(-1)
67
+ if not parents.any():raise ValueError('Empty spatial support')
68
+ # All-invalid padding parents would otherwise produce NaN in log_softmax.
69
+ safe_fine = fine.float().masked_fill(~valid, -torch.inf)
70
+ safe_fine = torch.where(parents[:,None], safe_fine, torch.zeros_like(safe_fine))
71
+ return (coarse.float().masked_fill(~parents, -torch.inf).log_softmax(-1)[:,None]
72
+ + safe_fine.log_softmax(-1)).masked_fill(~valid, -torch.inf)
73
+
74
+
75
+ def decode(coarse, fine, layout):
76
+ scores = joint_log_probs(coarse, fine, layout.valid(coarse.device))
77
+ flat = int(scores.flatten().argmax())
78
+ parent, local = divmod(flat, layout.fine_count)
79
+ point = layout.positions(coarse.device)[parent,local].tolist()
80
+ return dict(predicted_xy=point, parent=parent, fine=local)
81
+
82
+
83
+ def inside(point, box):
84
+ return box[0] <= point[0] <= box[2] and box[1] <= point[1] <= box[3]
PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/spatial_pointer/model.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Native JEV query/key spatial pointer and a query-conditioned 2D fine head."""
2
+
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ from jev_spatial_distill.t3.model import Teacher
8
+
9
+
10
+ class FineReadout(nn.Module):
11
+ def __init__(self, hidden, width=128, subdivisions=32):
12
+ super().__init__()
13
+ self.norm = nn.LayerNorm(hidden)
14
+ self.visual = nn.Linear(hidden,width)
15
+ self.query = nn.Linear(hidden,2*width)
16
+ self.local = nn.Conv2d(width,width,3,padding=1,groups=width)
17
+ self.mix = nn.Sequential(nn.Linear(width,width),nn.GELU(),nn.Linear(width,subdivisions**2))
18
+
19
+ def forward(self, spatial, query, layout, parents=None):
20
+ if spatial.shape[0] != layout.count:raise ValueError('Lost visual spatial layout')
21
+ v = self.visual(self.norm(spatial.float()))
22
+ scale,bias = self.query(self.norm(query.float())).chunk(2,-1)
23
+ v = v*(1+scale.tanh())+bias
24
+ image = v.T.reshape(1,-1,layout.rows,layout.cols)
25
+ v = v+self.local(image).reshape(v.shape[1],-1).T
26
+ if parents is not None:v = v[parents]
27
+ return self.mix(v)
28
+
29
+
30
+ class SpatialStudent(Teacher):
31
+ def __init__(self,native,recipe):
32
+ super().__init__(native,recipe)
33
+ self.spatial = FineReadout(native.head.q.in_features,recipe.get('readout_width',128),
34
+ recipe.get('subdivisions',32)).to(device=native.head.q.weight.device,dtype=torch.float32)
35
+
36
+ def encode_readout(self,group,features):
37
+ captured=[]
38
+ hook=self.native.head.register_forward_pre_hook(lambda _m,args:captured.append(args))
39
+ try:super().forward(group,features)
40
+ finally:hook.remove()
41
+ if len(captured)!=1:raise ValueError('Expected one native readout / LM forward')
42
+ pairs,query=captured[0]
43
+ if pairs.shape[0]!=1 or query.shape[0]!=1:raise ValueError('One target per native group required')
44
+ return pairs[0],query[0]
45
+
46
+ def readout(self,spatial,query,layout,parents=None):
47
+ coarse=self.native.head(spatial[None],query[None])[0]
48
+ fine=self.spatial(spatial,query,layout,parents)
49
+ return dict(coarse=coarse,fine=fine)
50
+
51
+ def forward(self,group,features,layout,parents=None,detach_backbone=False):
52
+ if detach_backbone:
53
+ with torch.no_grad():spatial,query=self.encode_readout(group,features)
54
+ else:spatial,query=self.encode_readout(group,features)
55
+ return self.readout(spatial,query,layout,parents)
56
+
57
+ def adapter_state(self):
58
+ return {n:p.detach().cpu().contiguous() for n,p in self.named_parameters()
59
+ if '.lora_' in n or n.startswith(('native.head.','spatial.'))}
60
+
61
+ def load_adapter(self,state):
62
+ if not any(n.startswith('spatial.') for n in state):return super().load_adapter(state)
63
+ expected={n:p for n,p in self.named_parameters() if '.lora_' in n or n.startswith(('native.head.','spatial.'))}
64
+ if expected.keys()!=state.keys():raise ValueError('Spatial student adapter keys differ')
65
+ with torch.no_grad():
66
+ for name,value in state.items():
67
+ if value.shape!=expected[name].shape or not torch.isfinite(value).all():raise ValueError('Invalid adapter tensor')
68
+ expected[name].copy_(value.to(expected[name]))
69
+
70
+
71
+ def gt_loss(output,target,layout,*,selected_parent=False):
72
+ if not target['representable']:raise ValueError('GT center is not represented inside its box at this resolution')
73
+ coarse,fine=output['coarse'].float(),output['fine'].float()
74
+ mask=layout.valid(coarse.device)
75
+ label=torch.tensor([target['parent']],device=coarse.device)
76
+ coarse_loss=F.cross_entropy(coarse.masked_fill(~mask.any(-1),-torch.inf)[None],label)
77
+ local=fine[0] if selected_parent else fine[target['parent']]
78
+ fine_loss=F.cross_entropy(local.masked_fill(~mask[target['parent']],-torch.inf)[None],
79
+ torch.tensor([target['fine']],device=coarse.device))
80
+ return coarse_loss+fine_loss,dict(coarse=float(coarse_loss.detach()),fine=float(fine_loss.detach()))
PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/spatial_pointer/supervision.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sparse projection of existing T3 traces and support-masked hierarchical KD."""
2
+
3
+ from functools import lru_cache
4
+ import json
5
+ import math
6
+ from pathlib import Path
7
+
8
+ import torch
9
+ from torch.nn import functional as F
10
+
11
+ from .data import sha
12
+ from .geometry import inside
13
+
14
+
15
+ def regions(prediction):
16
+ from spatial_pro_experiments.fast import cell_candidates
17
+ final=prediction['stages'][-1];leaves=[]
18
+ for trace in final['traces']:
19
+ leaves.extend(cell_candidates(trace['crop_bounds'],trace['predictions'],final['cells_per_axis'],trace['parent_score']))
20
+ if not leaves:raise ValueError('Teacher has no observed leaf cells')
21
+ peak=max(x['score'] for x in leaves)
22
+ return [(r['bounds'],math.exp(r['score']-peak)) for r in leaves]
23
+
24
+
25
+ def project_regions(bounds_and_weights,point,box,layout):
26
+ if not inside(point,box):return dict(enabled=False,parents=torch.empty(0,dtype=torch.long),mass=torch.empty(0,layout.fine_count))
27
+ unit=layout.stride/layout.subdivisions;indices=[];weights=[]
28
+ for bounds,weight in bounds_and_weights:
29
+ l,t,r,b=bounds
30
+ if not all(math.isfinite(v) for v in (*bounds,weight)) or r<=l or b<=t or weight<0:
31
+ raise ValueError('Invalid teacher leaf')
32
+ if weight==0:continue
33
+ x=torch.arange(max(0,math.floor(l/unit)),min(layout.cols*layout.subdivisions,math.ceil(r/unit)))
34
+ y=torch.arange(max(0,math.floor(t/unit)),min(layout.rows*layout.subdivisions,math.ceil(b/unit)))
35
+ x=x[(x+.5)*unit<layout.width];y=y[(y+.5)*unit<layout.height]
36
+ if not len(x) or not len(y):continue
37
+ xx,yy=torch.meshgrid(x,y,indexing='xy')
38
+ area=((torch.minimum((xx+1)*unit,torch.tensor(float(r)))-torch.maximum(xx*unit,torch.tensor(float(l)))).clamp_min(0)
39
+ *(torch.minimum((yy+1)*unit,torch.tensor(float(b)))-torch.maximum(yy*unit,torch.tensor(float(t)))).clamp_min(0))
40
+ parent=(yy//layout.subdivisions)*layout.cols+xx//layout.subdivisions
41
+ fine=(yy%layout.subdivisions)*layout.subdivisions+xx%layout.subdivisions
42
+ keep=area>0;indices.append((parent*layout.fine_count+fine)[keep]);weights.append((area*weight/((r-l)*(b-t)))[keep])
43
+ if not indices:raise ValueError('Teacher support is not represented at this pixel resolution')
44
+ flat=torch.cat(indices);values=torch.cat(weights).double()
45
+ parents,inverse=torch.unique(flat//layout.fine_count,sorted=True,return_inverse=True)
46
+ mass=torch.zeros(len(parents)*layout.fine_count,dtype=torch.float64)
47
+ mass.scatter_add_(0,inverse*layout.fine_count+flat%layout.fine_count,values)
48
+ mass=mass.reshape(len(parents),layout.fine_count);mass=mass/mass.sum()
49
+ if not torch.isfinite(mass).all():raise ValueError('Nonfinite projected teacher mass')
50
+ return dict(enabled=True,parents=parents,mass=mass.float(),point=list(point))
51
+
52
+
53
+ def project(prediction,box,layout):
54
+ return project_regions(regions(prediction),prediction['predicted_xy'],box,layout)
55
+
56
+
57
+ def selected_parents(target,soft):
58
+ return [target['parent']]+([int(v) for v in soft['parents'] if int(v)!=target['parent']] if soft and soft['enabled'] else [])
59
+
60
+
61
+ def kd_loss(output,soft,parent_order,temperature=2.):
62
+ coarse,fine=output['coarse'].float(),output['fine'].float()
63
+ zero=coarse.sum()*0+fine.sum()*0
64
+ if not soft or not soft['enabled']:return zero,dict(kd_enabled=0,observed_parents=0,observed_pixels=0)
65
+ parents=soft['parents'].to(coarse.device);mass=soft['mass'].to(coarse.device)
66
+ coarse_mass=mass.sum(-1);soft_coarse=coarse_mass.pow(1/temperature);soft_coarse/=soft_coarse.sum()
67
+ rank=F.kl_div(F.log_softmax(coarse[parents]/temperature,-1),soft_coarse,reduction='sum')*temperature**2
68
+ conditional=zero
69
+ lookup={int(p):i for i,p in enumerate(parent_order)}
70
+ for i,parent in enumerate(parents.tolist()):
71
+ mask=mass[i]>0;truth=mass[i,mask].pow(1/temperature);truth/=truth.sum()
72
+ values=fine[lookup[parent],mask]
73
+ conditional=conditional+coarse_mass[i]*F.kl_div(F.log_softmax(values/temperature,-1),truth,reduction='sum')*temperature**2
74
+ return rank+conditional,dict(kd_enabled=1,observed_parents=len(parents),observed_pixels=int((mass>0).sum()))
75
+
76
+
77
+ class TeacherCache:
78
+ """Byte index into an immutable existing cache; never materialize a pixel cache on disk."""
79
+ def __init__(self,path,expected_sha,targets):
80
+ self.path=Path(path)
81
+ if sha(self.path)!=expected_sha:raise ValueError('Teacher cache hash changed')
82
+ expected={str(r['id']):r for r in targets};self.offsets={}
83
+ with self.path.open('rb') as stream:
84
+ while True:
85
+ offset=stream.tell();line=stream.readline()
86
+ if not line:break
87
+ row=json.loads(line);ident=str(row['id'])
88
+ if ident in self.offsets:raise ValueError('Duplicate teacher target ID')
89
+ if ident not in expected:raise ValueError('Teacher cache contains a non-training target')
90
+ target=expected[ident]
91
+ if any(row[k]!=target[k] for k in ('instruction','bbox_xyxy','image_size')) or row['source_image_sha256']!=target['image_sha256']:
92
+ raise ValueError('Teacher and training input identity differ')
93
+ self.offsets[ident]=offset
94
+ if self.offsets.keys()!=expected.keys():raise ValueError('Teacher cache does not cover the training set')
95
+
96
+ @lru_cache(maxsize=128)
97
+ def get(self,ident):
98
+ with self.path.open('rb') as f:
99
+ f.seek(self.offsets[str(ident)]);return json.loads(f.readline())
PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/t3/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/t3/batching.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Differentiable padded native JEV scoring; each ROI keeps equal loss weight."""
2
+
3
+ from contextlib import nullcontext
4
+
5
+ import torch
6
+
7
+ from scripts.batch_spatial_jev import collate_query_groups
8
+
9
+
10
+ def forward_states(native, groups, features, labels=None):
11
+ from .model import choice_loss
12
+ if not groups or len(groups)!=len(features) or (labels is not None and len(labels)!=len(groups)):
13
+ raise ValueError('Each training state needs its own group, features and labels')
14
+ if any(value.is_inference() for value in features):
15
+ raise ValueError('Clone frozen visual features outside inference_mode before backward')
16
+ # Padding tokens never attend to or supply supervision for valid states.
17
+ batch=collate_query_groups(groups,0)
18
+ device=native.get_input_embeddings().weight.device
19
+ batch={key:value.to(device) for key,value in batch.items()}
20
+ amp=torch.autocast('cuda',dtype=torch.bfloat16) if device.type=='cuda' else nullcontext()
21
+ with amp:
22
+ embeds=native.get_input_embeddings()(batch['input_ids'])
23
+ if getattr(native,'full_parameter_training',False) and device.type=='cuda':embeds=embeds.to(torch.bfloat16)
24
+ video_token=native.config.backbone_config.video_token_id
25
+ all_slots=batch['input_ids']==video_token
26
+ for index,value in enumerate(features):
27
+ slots=all_slots[index]
28
+ if int(slots.sum())!=len(value):raise ValueError('Visual feature count differs from state tokens')
29
+ # Checkpointing can mark embedding outputs as leaf tensors requiring grad.
30
+ # Use the native out-of-place scatter, never mutate those leaves.
31
+ embeds=embeds.masked_scatter(all_slots[...,None].expand_as(embeds),torch.cat(features).to(embeds))
32
+ if native.is_moe:
33
+ positions,_=native.backbone.get_rope_index(input_ids=batch['input_ids'],
34
+ mm_token_type_ids=batch['mm_token_type_ids'],video_grid_thw=batch['video_grid_thw'],
35
+ attention_mask=batch['attention_mask'])
36
+ else:
37
+ positions=native.backbone.compute_3d_position_ids(input_ids=batch['input_ids'],inputs_embeds=embeds,
38
+ video_grid_thw=batch['video_grid_thw'],attention_mask=batch['attention_mask'],
39
+ mm_token_type_ids=batch['mm_token_type_ids'])
40
+ hidden=native.backbone.language_model(inputs_embeds=embeds,position_ids=positions,
41
+ attention_mask=batch['attention_mask'],use_cache=False).last_hidden_state
42
+ with torch.autocast(device_type=device.type,enabled=False):
43
+ indices=batch['sample_indices']
44
+ logits=native.head(hidden[indices[:,None],batch['pair_indices']],hidden[indices,batch['query_indices']])
45
+ mask=batch['score_mask']
46
+ probs=torch.where((batch['decision_tasks']==1)[:,None],
47
+ logits.masked_fill(~mask,-torch.inf).softmax(-1),logits.sigmoid())*mask
48
+ items=[];losses=[];offset=0
49
+ for index,group in enumerate(groups):
50
+ count=len(group['query_indices']);options=group['pair_indices'].shape[1]
51
+ item=dict(logits=logits[offset:offset+count,:options],
52
+ probabilities=probs[offset:offset+count,:options],score_mask=mask[offset:offset+count,:options])
53
+ if labels is not None:
54
+ losses.append(choice_loss(item['logits'],item['score_mask'],labels[index].to(device)))
55
+ items.append(item);offset+=count
56
+ result=dict(items=items)
57
+ if losses:result['loss']=torch.stack(losses).mean()
58
+ return result
PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/t3/common.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from pixelone.sampling import SampleStream
2
+ from pixelone.io import stable_hash
PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/t3/model.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Keep the released JEV head and expose a tested differentiable training path."""
2
+
3
+ import hashlib
4
+ import math
5
+ from contextlib import ExitStack,contextmanager
6
+ from importlib import import_module
7
+ from pathlib import Path
8
+
9
+ import torch
10
+ from torch import nn
11
+ from torch.nn import functional as F
12
+
13
+
14
+ @contextmanager
15
+ def native_runtime(backend='torch', required_model=None, attention_mode='causal'):
16
+ from qwen_spatial.kernels import qwen_kernel_backend
17
+ from jev_unified_student.attention import full_layer_attention
18
+ with ExitStack() as stack:
19
+ for name in ('qwen3_5','qwen3_5_moe'):
20
+ module=import_module(f'transformers.models.{name}.modeling_{name}')
21
+ stack.enter_context(full_layer_attention(module,attention_mode))
22
+ runtime=stack.enter_context(qwen_kernel_backend(backend,module))
23
+ if backend=='native' and (required_model is None or name==required_model):
24
+ missing=[key for key,enabled in runtime['optional_kernels_enabled'].items() if not enabled]
25
+ if missing:
26
+ raise RuntimeError('Native Qwen kernels unavailable: '+', '.join(missing)+
27
+ '. Install compatible flash-linear-attention and causal-conv1d in the active Python environment; '
28
+ 'use kernel_backend=torch only for an explicitly labelled baseline.')
29
+ cls=getattr(module,'Qwen3_5DecoderLayer' if name=='qwen3_5' else 'Qwen3_5MoeDecoderLayer')
30
+ if not hasattr(cls,'block_type'):cls.block_type=property(lambda layer:layer.layer_type)
31
+ yield
32
+
33
+
34
+ class LoRALinear(nn.Module):
35
+ def __init__(self,base,rank,alpha):
36
+ super().__init__();self.base=base.requires_grad_(False)
37
+ self.in_features,self.out_features=base.in_features,base.out_features;self.scale=alpha/rank
38
+ self.lora_A=nn.Parameter(torch.empty(rank,self.in_features,device=base.weight.device,dtype=torch.float32))
39
+ self.lora_B=nn.Parameter(torch.zeros(self.out_features,rank,device=base.weight.device,dtype=torch.float32))
40
+ nn.init.kaiming_uniform_(self.lora_A,a=math.sqrt(5))
41
+
42
+ @property
43
+ def weight(self):return self.base.weight
44
+
45
+ @property
46
+ def bias(self):return self.base.bias
47
+
48
+ def forward(self,x):
49
+ value=self.base(x)
50
+ delta=F.linear(F.linear(x.to(self.lora_A.dtype),self.lora_A),self.lora_B)
51
+ return value+self.scale*delta.to(value.dtype)
52
+
53
+
54
+ def install_lora(native,rank,alpha):
55
+ targets={'q_proj','k_proj','v_proj','o_proj','in_proj_qkv','in_proj_z','in_proj_b','in_proj_a','out_proj'}
56
+ language=native.backbone.language_model;names=[]
57
+ for name,module in list(language.named_modules()):
58
+ if isinstance(module,nn.Linear) and name.rsplit('.',1)[-1] in targets:
59
+ parent,leaf=name.rsplit('.',1)
60
+ language.get_submodule(parent).__setattr__(leaf,LoRALinear(module,rank,alpha));names.append(name)
61
+ for index,layer in enumerate(language.layers):
62
+ selected=[n.rsplit('.',1)[-1] for n in names if n.startswith(f'layers.{index}.')]
63
+ expected={'q_proj','k_proj','v_proj','o_proj'} if layer.layer_type=='full_attention' else targets-{'q_proj','k_proj','v_proj','o_proj'}
64
+ if set(selected)!=expected:raise ValueError(f'Incomplete LoRA coverage in {layer.layer_type} layer {index}: {selected}')
65
+ return names
66
+
67
+
68
+ def tensor_hash(values):
69
+ sha=hashlib.sha256()
70
+ for name,value in sorted(values.items()):
71
+ value=value.detach().float().cpu().contiguous();sha.update(name.encode());sha.update(str(list(value.shape)).encode())
72
+ sha.update(value.numpy().tobytes())
73
+ return sha.hexdigest()
74
+
75
+
76
+ def choice_loss(logits,mask,labels):
77
+ if logits.shape!=mask.shape or labels.shape!=(logits.shape[0],):raise ValueError('Choice loss shapes differ')
78
+ active=labels!=-100
79
+ if not active.any():raise ValueError('Training state has no unambiguous supervised question')
80
+ if not torch.isfinite(logits[mask]).all():raise ValueError('Nonfinite native JEV logits')
81
+ chosen=labels[active]
82
+ if (chosen<0).any() or (chosen>=logits.shape[1]).any() or not mask[active].gather(1,chosen[:,None]).all():
83
+ raise ValueError('Target refers to an invalid option')
84
+ return F.cross_entropy(logits.float()[active].masked_fill(~mask[active],-torch.inf),chosen)
85
+
86
+
87
+ class Teacher(nn.Module):
88
+ def __init__(self,native,recipe):
89
+ super().__init__();self.native=native;self.recipe=recipe
90
+ from scripts.smoke_videojev import legacy_unpadded_mask
91
+ native.prepare_for_inference()
92
+ self.initial_head_sha256=tensor_hash(native.head.state_dict())
93
+ ids=[native.config.decide_token_id,native.config.option_end_token_id]
94
+ embedding=native.get_input_embeddings()
95
+ self.initial_special_embeddings_sha256=tensor_hash({'special':embedding.weight[ids]})
96
+ self.lora_names=install_lora(native,recipe['lora_rank'],recipe['lora_alpha'])
97
+ native.head.requires_grad_(True)
98
+ # A shared additive bias cancels in categorical CE; preserve its grounding calibration.
99
+ native.head.bias.requires_grad_(False)
100
+ if recipe.get('gradient_checkpointing',True):
101
+ native.backbone.language_model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={'use_reentrant':False})
102
+ self.mask_hook=native.backbone.language_model.register_forward_pre_hook(legacy_unpadded_mask,with_kwargs=True)
103
+
104
+ def train(self,mode=True):
105
+ super().train(mode)
106
+ if not self.recipe.get('train_vision',False):self.native.backbone.visual.eval()
107
+ return self
108
+
109
+ def forward(self,group,features,labels=None):
110
+ if isinstance(group,(list,tuple)):
111
+ from .batching import forward_states
112
+ return forward_states(self.native,group,features,labels)
113
+ if features.is_inference():raise ValueError('Clone frozen visual features outside inference_mode before backward')
114
+ output=self.native(**group,visual_features=features)
115
+ result=dict(logits=output.logits,probabilities=output.probabilities,score_mask=output.score_mask)
116
+ if labels is not None:result['loss']=choice_loss(output.logits,output.score_mask,labels.to(output.logits.device))
117
+ return result
118
+
119
+ def adapter_state(self):
120
+ return {n:p.detach().cpu().contiguous() for n,p in self.named_parameters() if '.lora_' in n or n.startswith('native.head.')}
121
+
122
+ def load_adapter(self,state):
123
+ expected={n:p for n,p in self.named_parameters() if '.lora_' in n or n.startswith('native.head.')}
124
+ if set(state)!=set(expected):raise ValueError('Adapter keys differ from native JEV head/LoRA')
125
+ with torch.no_grad():
126
+ for name,value in state.items():
127
+ if value.shape!=expected[name].shape or not torch.isfinite(value).all():raise ValueError('Invalid adapter tensor')
128
+ expected[name].copy_(value.to(expected[name]))
129
+
130
+ def close(self):self.mask_hook.remove()
131
+
132
+
133
+ def load_teacher(checkpoint,recipe,device):
134
+ from transformers import AutoProcessor
135
+ from videojev_hf.modeling_videojev import VideoJevForVideoUnderstanding
136
+ from scripts.smoke_videojev import LegacyProcessorAdapter
137
+ native=VideoJevForVideoUnderstanding.from_pretrained(str(checkpoint),local_files_only=True,
138
+ dtype=torch.bfloat16,device_map={'':str(device)},attn_implementation='sdpa')
139
+ processor=LegacyProcessorAdapter(AutoProcessor.from_pretrained(str(checkpoint),local_files_only=True,trust_remote_code=True))
140
+ for token,expected in [('<|decide|>',native.config.decide_token_id),('<|option_end|>',native.config.option_end_token_id)]:
141
+ if processor.tokenizer.convert_tokens_to_ids(token)!=expected:raise ValueError('Native decision token IDs changed')
142
+ return Teacher(native,recipe),processor
PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/t3/states.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic multi-scale states and the exact existing rendering protocol."""
2
+
3
+ import hashlib
4
+ import io
5
+ import math
6
+ import random
7
+ from pathlib import Path
8
+
9
+ from PIL import Image
10
+
11
+ from jev_spatial_distill.teacher_targets import labels_for_roi
12
+ from .common import SampleStream,stable_hash
13
+
14
+
15
+ def read_image(row):
16
+ path=Path(row['image'][0]);raw=path.read_bytes()
17
+ if hashlib.sha256(raw).hexdigest()!=row['image_sha256']:raise ValueError('Prepared image changed')
18
+ with Image.open(io.BytesIO(raw)) as source:image=source.convert('RGB')
19
+ if list(image.size)!=row['image_size']:raise ValueError('Prepared image dimensions changed')
20
+ return image
21
+
22
+
23
+ def cell_for(box,roi,cells):
24
+ x,y=[(box[i]+box[i+2])/2 for i in (0,1)]
25
+ col=min(cells-1,max(0,int((x-roi[0])/(roi[2]-roi[0])*cells)))
26
+ row=min(cells-1,max(0,int((y-roi[1])/(roi[3]-roi[1])*cells)))
27
+ dx=(roi[2]-roi[0])/cells;dy=(roi[3]-roi[1])/cells
28
+ return [roi[0]+col*dx,roi[1]+row*dy,roi[0]+(col+1)*dx,roi[1]+(row+1)*dy]
29
+
30
+
31
+ def make_state(row,roi,depth,source,**extra):
32
+ roi=[int(v) for v in roi]
33
+ width,height=row['image_size']
34
+ if not (0<=roi[0]<roi[2]<=width and 0<=roi[1]<roi[3]<=height):raise ValueError('State ROI outside source screenshot')
35
+ cells=4 if depth==0 else 8
36
+ labels=labels_for_roi(row['bbox_xyxy'],roi,cells,local=depth>0)
37
+ return dict(target_id=row['id'],roi=roi,depth=depth,source=source,cells=cells,labels=labels,**extra)
38
+
39
+
40
+ def synthetic_state(row,position,seed):
41
+ from spatial_pro_experiments.core import expanded
42
+ rng=random.Random(int(stable_hash([seed,position,'roi'])[:16],16));width,height=row['image_size']
43
+ full=[0,0,width,height];kind=position%5
44
+ if kind==0:return make_state(row,full,0,'synthetic',sampling_kind='global')
45
+ first=expanded(cell_for(row['bbox_xyxy'],full,4),row['image_size'])
46
+ depth=1 if kind in (1,3) else 2
47
+ roi=first if depth==1 else expanded(cell_for(row['bbox_xyxy'],first,8),row['image_size'])
48
+ rw,rh=roi[2]-roi[0],roi[3]-roi[1]
49
+ if kind in (3,4):
50
+ for _ in range(32):
51
+ x=rng.randint(0,width-rw);y=rng.randint(0,height-rh)
52
+ trial=make_state(row,[x,y,x+rw,y+rh],depth,'synthetic',sampling_kind='negative')
53
+ if trial['labels']['visibility_status']=='absent':return trial
54
+ return make_state(row,roi,depth,'synthetic',sampling_kind='negative_unavailable_positive_fallback')
55
+ for _ in range(16):
56
+ x=max(0,min(width-rw,roi[0]+round(rng.uniform(-.12,.12)*rw)))
57
+ y=max(0,min(height-rh,roi[1]+round(rng.uniform(-.12,.12)*rh)))
58
+ trial=make_state(row,[x,y,x+rw,y+rh],depth,'synthetic',sampling_kind='positive_jitter')
59
+ if trial['labels']['center_inside_roi']:return trial
60
+ return make_state(row,roi,depth,'synthetic',sampling_kind='positive_unjittered')
61
+
62
+
63
+ class StateSampler:
64
+ def __init__(self,rows,recipe,rollout=None):
65
+ self.rows=rows;self.by_id={r['id']:r for r in rows};self.recipe=recipe
66
+ self.synthetic=SampleStream(len(rows),recipe['seed']);self.rollout=rollout or {}
67
+ self.rollout_ids=sorted(self.rollout)
68
+ self.real=SampleStream(len(self.rollout_ids),recipe['seed']) if self.rollout_ids else None
69
+
70
+ def at(self,position):
71
+ r=self.recipe
72
+ use_real=self.real is not None and int(stable_hash([r['seed'],position,'mix'])[:16],16)/16**16<r['rollout_fraction']
73
+ if use_real:
74
+ ident=self.rollout_ids[self.real.index(position)];states=self.rollout[ident]
75
+ index=int(stable_hash([r['seed'],position,'branch'])[:16],16)%len(states)
76
+ return self.by_id[ident],states[index]
77
+ row=self.rows[self.synthetic.index(position)]
78
+ return row,synthetic_state(row,position,r['seed'])
79
+
80
+
81
+ def prepare_state(model,processor,image,instruction,state,recipe):
82
+ import torch
83
+ from scripts import refine_spatial_jev as geometry
84
+ from spatial_pro_experiments.fast import contextual_views,grid_questions
85
+ from videojev_hf.processing_videojev import prepare_query_groups
86
+ local=state['depth']>0;size=recipe['crop_view_size'] if local else recipe['full_view_size']
87
+ views=(contextual_views(geometry,image,state['roi'],state['cells'],size) if local
88
+ else geometry.contextual_views(image,view_size=size))
89
+ # Encoding is frozen. Explicitly leave inference_mode and clone for autograd consumers.
90
+ features,record=geometry.encode_views(model.native,processor,views,view_size=size)
91
+ with torch.inference_mode(False):features=features.detach().clone()
92
+ questions=grid_questions(geometry,instruction,state['cells'],local=local)
93
+ groups=list(prepare_query_groups(processor,record,questions,record['context']))
94
+ if len(groups)!=1:raise ValueError('All state questions must share exactly one native forward')
95
+ group,actual=groups[0]
96
+ target_questions=state['labels']['questions']
97
+ if [q['id'] for q in actual]!=[q['id'] for q in target_questions]:raise ValueError('Labels do not match native question order')
98
+ labels=torch.tensor([q['label_index'] if q['enabled'] else -100 for q in target_questions],dtype=torch.long)
99
+ if not (labels!=-100).any():raise ValueError('Unsuitable training state; no supervised question')
100
+ frames=[hashlib.sha256(str(v.size).encode()+v.tobytes()).hexdigest() for v in views]
101
+ return group,features,labels,dict(frame_sha256=frames,visual_tokens=record['tokens'],input_tokens=group['input_ids'].shape[1])
PixelOne-Pro-35B-A3B/runtime/src/jev_spatial_distill/teacher_targets.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """GT geometry for the current JEV center-choice prompts; no model execution.
2
+
3
+ ROI coordinates must describe the actual rendered crop in original pixels.
4
+ These labels belong to the loss, not to the model's input questions.
5
+ """
6
+
7
+ import math
8
+
9
+
10
+ def xyxy(values):
11
+ if len(values)!=4 or any(type(v) not in (int,float) or not math.isfinite(v) for v in values):
12
+ raise ValueError('Expected four finite xyxy coordinates')
13
+ if values[0]>=values[2] or values[1]>=values[3]:raise ValueError('Degenerate box/ROI')
14
+ return [float(v) for v in values]
15
+
16
+
17
+ def labels_for_roi(box,roi,cells,*,local=True):
18
+ """Match CENTER questions and conservatively label geometric visibility.
19
+
20
+ Truncated boxes mask visibility: intersection alone does not establish
21
+ recognizability. Location is supervised only when the center is in the ROI.
22
+ """
23
+ if cells not in (4,8) or type(cells) is not int:raise ValueError('Current T3 uses 4/8 grids')
24
+ box,roi=xyxy(box),xyxy(roi)
25
+ overlap=[max(0.,min(box[i+2],roi[i+2])-max(box[i],roi[i])) for i in (0,1)]
26
+ overlap_area=overlap[0]*overlap[1]
27
+ coverage=overlap_area/((box[2]-box[0])*(box[3]-box[1]))
28
+ contained=all(roi[i]<=box[i] and box[i+2]<=roi[i+2] for i in (0,1))
29
+ visibility='inside' if contained else 'absent' if overlap_area==0 else 'truncated'
30
+ center=[(box[i]+box[i+2])/2 for i in (0,1)]
31
+ center_inside=all(roi[i]<=center[i]<roi[i+2] for i in (0,1))
32
+ normalized=[(center[i]-roi[i])/(roi[i+2]-roi[i]) for i in (0,1)]
33
+ indices=[min(cells-1,math.floor(v*cells)) for v in normalized] if center_inside else [None,None]
34
+ questions=[]
35
+ if local:
36
+ questions.append(dict(id='presence',enabled=visibility!='truncated',
37
+ label_index=0 if visibility=='inside' else 1 if visibility=='absent' else None))
38
+ questions.extend(dict(id=name,enabled=center_inside,label_index=index)
39
+ for name,index in zip(('horizontal','vertical'),indices))
40
+ return dict(cells_per_axis=cells,visibility_status=visibility,box_coverage=coverage,
41
+ center_inside_roi=center_inside,questions=questions,
42
+ label_convention='zero-based center bins; half-open ROI; truncated visibility masked')
PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/attention.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bidirectional masks for existing full-attention layers only."""
2
+
3
+ from contextlib import contextmanager
4
+ import torch
5
+
6
+
7
+ def bidirectional_mask(config, inputs_embeds, attention_mask=None, past_key_values=None, **kwargs):
8
+ if past_key_values is not None:
9
+ raise ValueError('Bidirectional spatial training does not support autoregressive KV caches')
10
+ if config._attn_implementation not in ('sdpa', 'eager'):
11
+ raise ValueError('Bidirectional full layers currently require SDPA or eager attention')
12
+ batch, length = inputs_embeds.shape[:2]
13
+ if attention_mask is None:
14
+ valid = torch.ones((batch, length), device=inputs_embeds.device, dtype=torch.bool)
15
+ else:
16
+ if attention_mask.shape != (batch, length):
17
+ raise ValueError('Expected independent per-sample 2D padding mask')
18
+ valid = attention_mask.to(device=inputs_embeds.device, dtype=torch.bool)
19
+ mask = torch.zeros((batch, 1, 1, length), device=inputs_embeds.device, dtype=inputs_embeds.dtype)
20
+ return mask.masked_fill(~valid[:, None, None, :], torch.finfo(inputs_embeds.dtype).min)
21
+
22
+
23
+ @contextmanager
24
+ def full_layer_attention(module, mode):
25
+ if mode == 'causal':
26
+ yield
27
+ return
28
+ if mode != 'bidirectional_full_layers':
29
+ raise ValueError('Unknown attention mode: ' + mode)
30
+ original = module.create_causal_mask
31
+ module.create_causal_mask = bidirectional_mask
32
+ try:
33
+ yield
34
+ finally:
35
+ module.create_causal_mask = original
PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/full_training.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Merge the continued student and shard full-parameter training with FSDP."""
2
+
3
+ from contextlib import nullcontext
4
+ import torch
5
+ from torch import nn
6
+
7
+ from jev_spatial_distill.t3.model import LoRALinear
8
+ from jev_click_finetune.inputs import prepare
9
+ from jev_click_finetune.objective import support
10
+
11
+
12
+ def enable_full_training(model, recipe):
13
+ experts_backend=recipe.get('experts_backend','eager')
14
+ if experts_backend not in ('eager','grouped_mm'):raise ValueError('Unknown experts backend')
15
+ if model.native.is_moe and experts_backend=='grouped_mm':
16
+ if not hasattr(torch.nn.functional,'grouped_mm'):
17
+ raise RuntimeError('Grouped experts require the image PyTorch grouped_mm implementation')
18
+ for module in model.native.backbone.language_model.modules():
19
+ if type(module).__name__=='Qwen3_5MoeExperts':module.config._experts_implementation='grouped_mm'
20
+ merged = []
21
+ for name, module in list(model.named_modules()):
22
+ if not isinstance(module, LoRALinear):
23
+ continue
24
+ with torch.no_grad():
25
+ weight = module.base.weight.float() + module.scale * (module.lora_B.float() @ module.lora_A.float())
26
+ module.base.weight = nn.Parameter(weight)
27
+ parent, leaf = name.rsplit('.', 1)
28
+ model.get_submodule(parent).__setattr__(leaf, module.base)
29
+ merged.append(name)
30
+ if not merged:
31
+ raise ValueError('Full training requires a loaded 22k LoRA student before merging')
32
+ model.native.head.bias=nn.Parameter(model.native.head.bias.detach().reshape(1).clone())
33
+ model.requires_grad_(True)
34
+ if not recipe['train_vision']:
35
+ model.native.backbone.visual.requires_grad_(False)
36
+ elif recipe.get('gradient_checkpointing',True):
37
+ model.native.backbone.visual.gradient_checkpointing_enable(gradient_checkpointing_kwargs={'use_reentrant':False})
38
+ model.native.train_vision = recipe['train_vision']
39
+ model.native.full_parameter_training = True
40
+ model.unified_initialization = dict(model.unified_initialization,
41
+ training_mode='full', lora_merge='FP32 B @ A * alpha/rank merged into base projections',
42
+ merged_lora_modules=merged, train_vision=recipe['train_vision'],
43
+ trainable_parameters_before_sharding=sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad))
44
+
45
+
46
+ class BatchPayload:
47
+ def __init__(self, records):
48
+ self.records = records
49
+
50
+
51
+ class FullBatchStudent(nn.Module):
52
+ def __init__(self, student, processor, device):
53
+ super().__init__()
54
+ self.student, self.processor, self.device = student, processor, device
55
+ self.timer = None
56
+
57
+ def forward(self, payload):
58
+ prepared = payload.records
59
+ phase = self.timer.phase if self.timer is not None else lambda name: nullcontext()
60
+ with phase('vision_and_processor'):
61
+ for value in prepared:
62
+ valid, positive = support(value['layout'], value['row']['bbox_xyxy'], self.device)
63
+ group, features, actual, encoding = prepare(self.student, self.processor, value.pop('image'),
64
+ value['row']['instruction'])
65
+ if actual != value['layout']:
66
+ raise ValueError('Full training changed the native image layout')
67
+ value.update(valid=valid, positive=positive, group=group, features=features, encoding=encoding)
68
+ with phase('language_forward'):
69
+ outputs = self.student([value['group'] for value in prepared], [value['features'] for value in prepared],
70
+ [value['layout'] for value in prepared], [value['required'] for value in prepared],
71
+ [value['positive'].any(-1) for value in prepared], self.student.recipe['routing_topk'])
72
+ return outputs, prepared
73
+
74
+
75
+ def wrap_full_training(model, processor, device, recipe, topology):
76
+ batch_model = FullBatchStudent(model, processor, device)
77
+ if device.type != 'cuda':
78
+ model.float()
79
+ return batch_model
80
+ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy
81
+ from torch.distributed.device_mesh import init_device_mesh
82
+ mode = recipe.get('sharding', 'full_shard')
83
+ arguments = dict(device_id=device, use_orig_params=True, limit_all_gathers=True)
84
+ if mode == 'hybrid_shard' and topology['nodes'] > 1:
85
+ arguments['sharding_strategy'] = ShardingStrategy.HYBRID_SHARD
86
+ arguments['device_mesh'] = init_device_mesh('cuda', (topology['nodes'], topology['processes']),
87
+ mesh_dim_names=('replicate', 'shard'))
88
+ elif mode in ('full_shard', 'hybrid_shard'):
89
+ arguments['sharding_strategy'] = ShardingStrategy.FULL_SHARD
90
+ else:
91
+ raise ValueError('Unknown full-parameter sharding strategy')
92
+ precision = MixedPrecision(param_dtype=torch.bfloat16, reduce_dtype=torch.float32,
93
+ buffer_dtype=torch.bfloat16, cast_forward_inputs=True)
94
+ language = model.native.backbone.language_model
95
+ for index, layer in enumerate(language.layers):
96
+ language.layers[index] = FSDP(layer.float(), mixed_precision=precision, **arguments)
97
+ visual = model.native.backbone.visual
98
+ if recipe['train_vision']:
99
+ for index, block in enumerate(visual.blocks):
100
+ visual.blocks[index] = FSDP(block.float(), mixed_precision=precision, **arguments)
101
+ for module in model.modules():
102
+ if not isinstance(module, FSDP):
103
+ for parameter in module.parameters(recurse=False):
104
+ if parameter.dtype == torch.bfloat16:
105
+ parameter.data = parameter.data.float()
106
+ return FSDP(batch_model, **arguments)
107
+
108
+
109
+ def parameter_groups(model, recipe):
110
+ groups = []
111
+ for name, prefix, learning_rate in [('language', 'native.backbone.language_model.', recipe['full_lr']),
112
+ ('vision', 'native.backbone.visual.', recipe['vision_lr']),
113
+ ('head', 'native.head.', recipe['head_lr']),
114
+ ('spatial', 'spatial.', recipe['spatial_lr'])]:
115
+ parameters = [parameter for key, parameter in model.named_parameters() if key.startswith(prefix) and parameter.requires_grad]
116
+ if parameters:
117
+ groups.append(dict(name=name, params=parameters, lr=learning_rate, base_lr=learning_rate))
118
+ selected = {id(parameter) for group in groups for parameter in group['params']}
119
+ expected = {id(parameter) for parameter in model.parameters() if parameter.requires_grad}
120
+ if selected != expected:
121
+ raise ValueError('Full optimizer groups do not cover every trainable parameter')
122
+ return groups
123
+
124
+
125
+ def clip_full_gradients(wrapped, parameters, clip):
126
+ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
127
+ if isinstance(wrapped, FSDP):
128
+ norm = wrapped.clip_grad_norm_(clip)
129
+ else:
130
+ norm = torch.nn.utils.clip_grad_norm_(parameters, clip, error_if_nonfinite=True)
131
+ if not bool(torch.isfinite(norm)):
132
+ raise ValueError('Nonfinite full-model gradient norm')
133
+ return float(norm), {}
PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/methods.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """Methods that must never read teacher predictions or use teacher KD support."""
2
+
3
+ GT_METHODS = ('gt', 'gt_set', 'gt_top20')
PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/model.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Identical teacher shared weights and independently seeded fine head in every arm."""
2
+ import torch
3
+ from jev_click_finetune.model import ClickStudent as SingleClickStudent,route
4
+ from jev_spatial_distill.spatial_pointer.model import FineReadout
5
+ from jev_spatial_distill.t3.model import tensor_hash,Teacher
6
+
7
+
8
+ class ClickStudent(SingleClickStudent):
9
+ """Keep single-image inference and support a real padded LM training batch."""
10
+ def forward(self,group,features,layout,required=None,positive=None,topk=4):
11
+ if not isinstance(group,(list,tuple)):
12
+ return super().forward(group,features,layout,required,positive,topk)
13
+ count=len(group)
14
+ if (not count or len(features)!=count or len(layout)!=count or
15
+ any(len(g['query_indices'])!=1 for g in group)):
16
+ raise ValueError('Each batch item requires one screenshot and one query')
17
+ required=[None]*count if required is None else required
18
+ positive=[None]*count if positive is None else positive
19
+ if len(required)!=count or len(positive)!=count:raise ValueError('Batched routes differ from targets')
20
+ captured=[]
21
+ hook=self.native.head.register_forward_pre_hook(lambda _m,args:captured.append(args))
22
+ try:Teacher.forward(self,group,features)
23
+ finally:hook.remove()
24
+ if len(captured)!=1:raise ValueError('Expected one batched native readout')
25
+ pairs,queries=captured[0]
26
+ if pairs.shape[0]!=count or queries.shape[0]!=count:raise ValueError('Lost batched sample identities')
27
+ result=[]
28
+ for i,current in enumerate(layout):
29
+ spatial=pairs[i,:current.count];query=queries[i]
30
+ if len(features[i])!=current.count:raise ValueError('Visual grid differs from spatial layout')
31
+ coarse=self.native.head(spatial[None],query[None])[0]
32
+ parents=route(coarse,required[i],positive[i],topk)
33
+ result.append(dict(coarse=coarse,fine=self.spatial(spatial,query,current,parents),parents=parents))
34
+ return result
35
+
36
+
37
+ def fresh_head(hidden,recipe):
38
+ with torch.random.fork_rng(devices=[]),torch.device('cpu'):
39
+ torch.random.default_generator.manual_seed(recipe['head_seed'])
40
+ return FineReadout(hidden,recipe['readout_width'],recipe['subdivisions'])
41
+
42
+
43
+ def initialize_student(native,recipe,teacher_state):
44
+ if any(n.startswith('spatial.') for n in teacher_state):raise ValueError('Initialization requires T3, not an already trained S1 checkpoint')
45
+ model=ClickStudent(native,recipe);model.load_adapter(teacher_state)
46
+ head=fresh_head(native.head.q.in_features,recipe)
47
+ model.spatial.load_state_dict(head.state_dict())
48
+ state=model.adapter_state();shared={n:v for n,v in state.items() if not n.startswith('spatial.')}
49
+ if tensor_hash(shared)!=tensor_hash(teacher_state):raise ValueError('Teacher shared initialization changed')
50
+ expected={n for n,p in model.named_parameters() if '.lora_' in n or n.startswith(('native.head.','spatial.'))}
51
+ for n,p in model.named_parameters():
52
+ should_train=n in expected and n!='native.head.bias'
53
+ if p.requires_grad!=should_train:raise ValueError('Unexpected frozen/trainable parameter: '+n)
54
+ initial=dict(shared_sha256=tensor_hash(shared),spatial_sha256=tensor_hash(head.state_dict()),
55
+ adapter_tensor_sha256=tensor_hash(state),head_seed=recipe['head_seed'],
56
+ scope='fresh T3 shared adapter plus fixed CPU-seeded fine head; no prior S1 checkpoint')
57
+ model.unified_initialization=initial
58
+ return model,initial
59
+
60
+
61
+ def initialize_continued_student(native,recipe,state,expected):
62
+ """Retain the trained pixel head; this is not a fresh-head teacher initialization."""
63
+ if not any(n.startswith('spatial.') for n in state):
64
+ raise ValueError('Continuation requires a trained pixel head')
65
+ model=ClickStudent(native,recipe);model.load_adapter(state)
66
+ loaded=model.adapter_state()
67
+ if tensor_hash(loaded)!=expected['adapter_tensor_sha256'] or tensor_hash(loaded)!=tensor_hash(state):
68
+ raise ValueError('Continued student weights were not loaded exactly')
69
+ fine={k.removeprefix('spatial.'):v for k,v in loaded.items() if k.startswith('spatial.')}
70
+ if tensor_hash(fine)!=expected['spatial_sha256']:
71
+ raise ValueError('Trained pixel head was reset')
72
+ model.unified_initialization=dict(expected)
73
+ return model,model.unified_initialization
PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/objective.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Matched GT routing with method-specific fine losses and optional teacher KD."""
2
+ import math
3
+ import torch
4
+ from torch.nn import functional as F
5
+ from jev_click_finetune.model import route
6
+ from jev_click_finetune.objective import set_nll
7
+ from jev_fine_refine.objective import fine_objective
8
+ from jev_spatial_distill.spatial_pointer.supervision import kd_loss
9
+ from jev_fine_ablation.distillation import distillation_loss
10
+ from .top20 import top20_winner_loss
11
+ from .top100 import top100_winner_loss
12
+ from .methods import GT_METHODS
13
+
14
+ TEACHER_METHODS=('pixel_kd','region_kd','hard_kd','pixel_kd_top20','pixel_kd_top100')
15
+
16
+
17
+ def gt_objective(output,valid,positive,target,layout,topk,fine_rule='winner'):
18
+ # KD reads additional teacher regions, but those regions must not silently
19
+ # add GT supervision or change the fine-GT mean denominator.
20
+ parents=route(output['coarse'],[target['parent']],positive.any(-1),topk)
21
+ lookup={int(p):i for i,p in enumerate(output['parents'].tolist())}
22
+ if any(int(p) not in lookup for p in parents):raise ValueError('GT routing is absent from the shared forward')
23
+ indices=torch.tensor([lookup[int(p)] for p in parents],device=output['fine'].device)
24
+ view=dict(coarse=output['coarse'],fine=output['fine'][indices],parents=parents)
25
+ if fine_rule=='winner':gt,terms=fine_objective(view,valid,positive)
26
+ elif fine_rule in ('set','top20','top100'):
27
+ # Same routed GT-valid rows and mean denominator as the winner rule.
28
+ coarse=set_nll(view['coarse'],valid.any(-1),positive.any(-1))
29
+ truth=positive[parents];keep=truth.any(-1)
30
+ if not keep.any():raise ValueError('No supervised positive region was routed')
31
+ if fine_rule=='set':
32
+ fine=set_nll(view['fine'][keep],valid[parents][keep],truth[keep]).mean()
33
+ elif fine_rule=='top20':
34
+ fine=top20_winner_loss(view['fine'][keep],valid[parents][keep],truth[keep])
35
+ else:
36
+ fine=top100_winner_loss(view['fine'][keep],valid[parents][keep],truth[keep])
37
+ gt=coarse+fine;terms=dict(coarse=float(coarse.detach()),fine=float(fine.detach()),supervised_regions=int(keep.sum()))
38
+ else:raise ValueError('Unknown fine GT rule')
39
+ return gt,terms,parents.tolist()
40
+
41
+
42
+ def hard_target(prediction,box,layout):
43
+ """Teacher final point as a one-pixel label, under the same hit gate as soft KD."""
44
+ x,y=prediction['predicted_xy']
45
+ if not (math.isfinite(x) and math.isfinite(y)):raise ValueError('Nonfinite teacher point')
46
+ if not (box[0]<=x<=box[2] and box[1]<=y<=box[3]):return dict(enabled=False,parents=torch.empty(0,dtype=torch.long))
47
+ unit=layout.stride/layout.subdivisions
48
+ gx=min(max(int(x/unit),0),math.ceil(layout.width/unit)-1)
49
+ gy=min(max(int(y/unit),0),math.ceil(layout.height/unit)-1)
50
+ parent=(gy//layout.subdivisions)*layout.cols+gx//layout.subdivisions
51
+ fine=(gy%layout.subdivisions)*layout.subdivisions+gx%layout.subdivisions
52
+ if not bool(layout.valid()[parent,fine]):raise ValueError('Teacher point maps to a padded pixel')
53
+ return dict(enabled=True,parents=torch.tensor([parent]),fine=fine,point=[x,y])
54
+
55
+
56
+ def hard_kd_loss(output,hard,valid):
57
+ coarse,fine=output['coarse'].float(),output['fine'].float()
58
+ zero=coarse.sum()*0+fine.sum()*0
59
+ if not hard['enabled']:return zero,dict(kd_enabled=0,observed_parents=0,observed_pixels=0)
60
+ parent=int(hard['parents'][0]);index=output['parents'].tolist().index(parent)
61
+ c=-coarse.masked_fill(~valid.any(-1),-torch.inf).log_softmax(-1)[parent]
62
+ f=F.cross_entropy(fine[index].masked_fill(~valid[parent],-torch.inf)[None],
63
+ torch.tensor([hard['fine']],device=fine.device))
64
+ return c+f+zero,dict(kd_enabled=1,observed_parents=1,observed_pixels=1)
65
+
66
+
67
+ def unified_loss(output,valid,positive,target,layout,method,soft,region,recipe,hard=None):
68
+ fine_rule={'gt_set':'set','gt_top20':'top20','pixel_kd_top20':'top20','pixel_kd_top100':'top100'}.get(method,'winner')
69
+ gt,terms,gt_parents=gt_objective(output,valid,positive,target,layout,recipe['routing_topk'],
70
+ fine_rule)
71
+ parents=output['parents'].tolist()
72
+ if method in GT_METHODS:
73
+ if soft is not None or region is not None or hard is not None:raise ValueError('GT-only must not use teacher prediction/support')
74
+ kd=output['coarse'].float().sum()*0+output['fine'].float().sum()*0
75
+ kd_terms=dict(kd_enabled=0,observed_parents=0,observed_pixels=0);details=dict(method=method,coarse=0.,fine=0.)
76
+ elif method in ('pixel_kd','pixel_kd_top20','pixel_kd_top100'):
77
+ implementation=kd_loss
78
+ if recipe.get('speed',{}).get('vectorized_kd',False):
79
+ from .speed_loss import pixel_kd_loss
80
+ implementation=pixel_kd_loss
81
+ kd,kd_terms=implementation(output,soft,parents,recipe['temperature']);details=dict(method='pixel_kd')
82
+ elif method=='region_kd':
83
+ kd,kd_terms,details=distillation_loss(output,soft,parents,'region_kd',recipe['temperature'],region)
84
+ elif method=='hard_kd':
85
+ kd,kd_terms=hard_kd_loss(output,hard,valid);details=dict(method='hard_kd')
86
+ else:raise ValueError('Unknown unified method')
87
+ loss=gt+recipe['kd_weight']*kd
88
+ return loss,gt,terms,kd,kd_terms,details,gt_parents
PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/portable_full.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from jev_unified_student.model import ClickStudent
3
+ from jev_spatial_distill.spatial_pointer.model import FineReadout
4
+
5
+ def cast_training_inputs(module, args, kwargs):
6
+ from torch.utils._pytree import tree_map
7
+ def cast(value):
8
+ return value.to(torch.bfloat16) if isinstance(value, torch.Tensor) and value.is_floating_point() else value
9
+ return tree_map(cast, args), tree_map(cast, kwargs)
10
+
11
+
12
+ def inference_precision(model, recipe, precision):
13
+ if precision != 'training_cuda':
14
+ return
15
+ blocks = list(model.native.backbone.language_model.layers)
16
+ if recipe['train_vision']:
17
+ blocks += list(model.native.backbone.visual.blocks)
18
+ for block in blocks:
19
+ block.register_forward_pre_hook(cast_training_inputs, with_kwargs=True)
20
+ for module in block.modules():
21
+ for name, buffer in module.named_buffers(recurse=False):
22
+ if buffer.is_floating_point():
23
+ setattr(module, name, buffer.to(torch.bfloat16))
24
+
25
+
26
+ class FullWeightStudent(ClickStudent):
27
+ def __init__(self, native, recipe):
28
+ torch.nn.Module.__init__(self)
29
+ self.native, self.recipe = native, recipe
30
+ self.native.head.bias = torch.nn.Parameter(torch.zeros(1))
31
+ self.spatial = FineReadout(native.head.q.in_features, recipe['readout_width'], recipe['subdivisions'])
32
+ self.native.full_parameter_training = True
33
+ self.native.train_vision = recipe['train_vision']
34
+
35
+ def forward(self, groups, features, layouts, required=None, positive=None, topk=4):
36
+ if not isinstance(groups, (tuple, list)):
37
+ raise ValueError('Full inference always uses the same batched path as training')
38
+ return super().forward(groups, features, layouts, required, positive, topk)
39
+
40
+ def close(self):
41
+ pass
PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/speed_loss.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vectorized observed-support pixel KD with the original teacher gate."""
2
+
3
+ import torch
4
+ from torch.nn import functional as functional
5
+
6
+
7
+ def pixel_kd_loss(output, soft, parent_order, temperature=2.):
8
+ coarse, fine = output['coarse'].float(), output['fine'].float()
9
+ zero = coarse.sum() * 0 + fine.sum() * 0
10
+ if not soft or not soft['enabled']:
11
+ return zero, dict(kd_enabled=0, observed_parents=0, observed_pixels=0)
12
+ parent_ids = soft['parents'].tolist()
13
+ lookup = {parent: index for index, parent in enumerate(parent_order)}
14
+ selected = torch.tensor([lookup[parent] for parent in parent_ids], device=fine.device)
15
+ parents = soft['parents'].to(coarse.device)
16
+ mass = soft['mass'].to(coarse.device)
17
+ coarse_mass = mass.sum(-1)
18
+ soft_coarse = coarse_mass.pow(1 / temperature)
19
+ soft_coarse = soft_coarse / soft_coarse.sum()
20
+ rank = functional.kl_div(functional.log_softmax(coarse[parents] / temperature, -1),
21
+ soft_coarse, reduction='sum') * temperature ** 2
22
+ mask = mass > 0
23
+ truth = mass.pow(1 / temperature)
24
+ truth = truth / truth.sum(-1, keepdim=True)
25
+ log_student = functional.log_softmax((fine[selected] / temperature).masked_fill(~mask, -torch.inf), -1)
26
+ terms = functional.kl_div(log_student.masked_fill(~mask, 0.), truth, reduction='none')
27
+ conditional = (terms.sum(-1) * coarse_mass).sum() * temperature ** 2
28
+ return rank + conditional + zero, dict(kd_enabled=1, observed_parents=len(parent_ids),
29
+ observed_pixels=int((soft['mass'] > 0).sum()))
PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/top100.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Equal-weight winner losses for all GT-valid pixels within each routed token."""
2
+
3
+ import torch
4
+ from torch.nn import functional as F
5
+
6
+
7
+ TOP100_SPEC = dict(
8
+ name='all_positive_winners',
9
+ fraction=1.0,
10
+ selection='all GT-valid pixels of each routed GT-valid token',
11
+ count='number of positive pixels; 100 percent, not a fixed count of 100',
12
+ negatives='all original-image pixels outside GT in the same token; padding excluded',
13
+ reduction='mean over all positives, then mean over the original GT-valid routed tokens',
14
+ full_positive_token='zero loss, included in the token mean denominator',
15
+ spatial_weighting='uniform; no center or interior preference',
16
+ )
17
+
18
+
19
+ def top100_winner_loss(logits, valid, positive):
20
+ """Every positive competes separately against the shared negative pool.
21
+
22
+ This averages per-positive classification losses; it does not collapse the
23
+ positive logits into a set likelihood or select only the weakest positive.
24
+ """
25
+ if (logits.ndim != 2 or logits.shape != valid.shape or valid.shape != positive.shape
26
+ or valid.dtype != torch.bool or positive.dtype != torch.bool):
27
+ raise ValueError('Top100 support shapes/types differ')
28
+ if not positive.any(-1).all() or (positive & ~valid).any():
29
+ raise ValueError('Every fine row needs nonempty valid GT support')
30
+ z = logits.float()
31
+ negative = valid & ~positive
32
+ active = negative.any(-1)
33
+ zero = z.sum() * 0
34
+ if not active.any():
35
+ return zero
36
+
37
+ selected, pos, neg = z[active], positive[active], negative[active]
38
+ wrong = selected.masked_fill(~neg, -torch.inf).logsumexp(-1)
39
+ positive_scores = selected.masked_fill(~pos, 0.)
40
+ per_positive = F.softplus(wrong[:, None] - positive_scores).masked_fill(~pos, 0.)
41
+ per_token = per_positive.sum(-1) / pos.sum(-1)
42
+ return per_token.sum() / len(z) + zero
PixelOne-Pro-35B-A3B/runtime/src/jev_unified_student/top20.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Equal-weight winner losses for the highest-scoring 20% of GT-valid pixels."""
2
+
3
+ import torch
4
+ from torch.nn import functional as F
5
+
6
+
7
+ TOP20_SPEC = dict(
8
+ name='top20_positive_winners',
9
+ fraction=0.2,
10
+ selection='detached scores within GT-valid pixels of each routed GT-valid token',
11
+ count='ceil(number of positive pixels / 5), at least one',
12
+ ties='ascending original within-token pixel index',
13
+ negatives='all original-image pixels outside GT in the same token; padding excluded',
14
+ reduction='mean over selected positives, then mean over the original GT-valid routed tokens',
15
+ full_positive_token='zero loss, included in the token mean denominator',
16
+ spatial_weighting='uniform; no center or interior preference',
17
+ )
18
+
19
+
20
+ def top20_winner_loss(logits, valid, positive):
21
+ """Keep the original negative pool and token weighting; expand positive winners.
22
+
23
+ Each selected positive competes separately against every negative. Selection
24
+ is detached, but gradients flow through every gathered positive score. The
25
+ final decoder remains the original token-first, one-pixel argmax.
26
+ """
27
+ if (logits.ndim != 2 or logits.shape != valid.shape or valid.shape != positive.shape
28
+ or valid.dtype != torch.bool or positive.dtype != torch.bool):
29
+ raise ValueError('Top20 support shapes/types differ')
30
+ if not positive.any(-1).all() or (positive & ~valid).any():
31
+ raise ValueError('Every fine row needs nonempty valid GT support')
32
+ z = logits.float()
33
+ negative = valid & ~positive
34
+ active = negative.any(-1)
35
+ zero = z.sum() * 0
36
+ if not active.any():
37
+ return zero
38
+
39
+ selected, pos, neg = z[active], positive[active], negative[active]
40
+ # Integer arithmetic gives exact ceil(20% * n_positive), including n < 5.
41
+ counts = (pos.sum(-1) + 4) // 5
42
+ max_count = int(counts.max())
43
+ order = selected.detach().masked_fill(~pos, -torch.inf).argsort(
44
+ dim=-1, descending=True, stable=True)[:, :max_count]
45
+ keep = torch.arange(max_count, device=z.device)[None] < counts[:, None]
46
+ best = selected.gather(-1, order).masked_fill(~keep, 0.)
47
+ wrong = selected.masked_fill(~neg, -torch.inf).logsumexp(-1)
48
+ per_positive = F.softplus(wrong[:, None] - best).masked_fill(~keep, 0.)
49
+ per_token = per_positive.sum(-1) / counts
50
+ # Fully GT-covered tokens retain their original zero-loss contribution.
51
+ return per_token.sum() / len(z) + zero
PixelOne-Pro-35B-A3B/runtime/src/pixelone/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ __version__ = '0.1.0'
2
+
3
+
4
+ def __getattr__(name):
5
+ if name == 'PixelOnePredictor':
6
+ from .inference import PixelOnePredictor
7
+ return PixelOnePredictor
8
+ raise AttributeError(name)
PixelOne-Pro-35B-A3B/runtime/src/pixelone/assets/DejaVuSans-LICENSE.txt ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2
+ Upstream-Name: DejaVu fonts
3
+ Upstream-Author: Stepan Roh <src@users.sourceforge.net> (original author),
4
+ see /usr/share/doc/fonts-dejavu-core/AUTHORS for full list
5
+ Source: https://dejavu-fonts.github.io/
6
+
7
+ Files: *
8
+ Copyright: Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved.
9
+ Bitstream Vera is a trademark of Bitstream, Inc.
10
+ DejaVu changes are in public domain.
11
+ License: bitstream-vera
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of the fonts accompanying this license ("Fonts") and associated
14
+ documentation files (the "Font Software"), to reproduce and distribute the
15
+ Font Software, including without limitation the rights to use, copy, merge,
16
+ publish, distribute, and/or sell copies of the Font Software, and to permit
17
+ persons to whom the Font Software is furnished to do so, subject to the
18
+ following conditions:
19
+ .
20
+ The above copyright and trademark notices and this permission notice shall
21
+ be included in all copies of one or more of the Font Software typefaces.
22
+ .
23
+ The Font Software may be modified, altered, or added to, and in particular
24
+ the designs of glyphs or characters in the Fonts may be modified and
25
+ additional glyphs or characters may be added to the Fonts, only if the fonts
26
+ are renamed to names not containing either the words "Bitstream" or the word
27
+ "Vera".
28
+ .
29
+ This License becomes null and void to the extent applicable to Fonts or Font
30
+ Software that has been modified and is distributed under the "Bitstream
31
+ Vera" names.
32
+ .
33
+ The Font Software may be sold as part of a larger software package but no
34
+ copy of one or more of the Font Software typefaces may be sold by itself.
35
+ .
36
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
37
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
38
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
39
+ TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
40
+ FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
41
+ ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
42
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
43
+ THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
44
+ FONT SOFTWARE.
45
+ .
46
+ Except as contained in this notice, the names of Gnome, the Gnome
47
+ Foundation, and Bitstream Inc., shall not be used in advertising or
48
+ otherwise to promote the sale, use or other dealings in this Font Software
49
+ without prior written authorization from the Gnome Foundation or Bitstream
50
+ Inc., respectively. For further information, contact: fonts at gnome dot
51
+ org.
52
+
53
+ Files: debian/*
54
+ Copyright: (C) 2005-2006 Peter Cernak <pce@users.sourceforge.net>
55
+ (C) 2006-2011 Davide Viti <zinosat@tiscali.it>
56
+ (C) 2011-2013 Christian Perrier <bubulle@debian.org>
57
+ (C) 2013 Fabian Greffrath <fabian+debian@greffrath.com>
58
+ License: GPL-2+
59
+ This program is free software; you can redistribute it
60
+ and/or modify it under the terms of the GNU General Public
61
+ License as published by the Free Software Foundation; either
62
+ version 2 of the License, or (at your option) any later
63
+ version.
64
+ .
65
+ This program is distributed in the hope that it will be
66
+ useful, but WITHOUT ANY WARRANTY; without even the implied
67
+ warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
68
+ PURPOSE. See the GNU General Public License for more
69
+ details.
70
+ .
71
+ You should have received a copy of the GNU General Public
72
+ License along with this package; if not, write to the Free
73
+ Software Foundation, Inc., 51 Franklin St, Fifth Floor,
74
+ Boston, MA 02110-1301 USA
75
+ .
76
+ On Debian systems, the full text of the GNU General Public
77
+ License version 2 can be found in the file
78
+ /usr/share/common-licenses/GPL-2'.
PixelOne-Pro-35B-A3B/runtime/src/pixelone/assets/DejaVuSans.ttf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae7b7855e115a5966d8b1b3f80f254ccc117ec86f9965e202ee2940453837280
3
+ size 759720
PixelOne-Pro-35B-A3B/runtime/src/pixelone/checkpoint.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ import torch
4
+ import torch.distributed as distributed
5
+ import torch.distributed.checkpoint as checkpoint
6
+ from torch.distributed.checkpoint.state_dict import StateDictOptions, get_state_dict, set_state_dict
7
+
8
+ from pixelone.io import atomic_json, stable_hash
9
+
10
+
11
+ def initialized():
12
+ return distributed.is_available() and distributed.is_initialized()
13
+
14
+
15
+ def save_checkpoint(directory, model, optimizer, step, identity):
16
+ directory = Path(directory)
17
+ rank = distributed.get_rank() if initialized() else 0
18
+ if rank == 0:
19
+ if directory.exists():
20
+ raise ValueError('Checkpoint destination already exists')
21
+ directory.mkdir(parents=True)
22
+ if initialized():
23
+ distributed.barrier()
24
+ model_state, optimizer_state = get_state_dict(model, optimizer, options=StateDictOptions(cpu_offload=True))
25
+ checkpoint.save({'model': model_state, 'optimizer': optimizer_state}, checkpoint_id=directory / 'state')
26
+ random_state = {'cpu': torch.get_rng_state()}
27
+ if torch.cuda.is_available():
28
+ random_state['cuda'] = torch.cuda.get_rng_state()
29
+ torch.save(random_state, directory / f'rng_rank_{rank:04d}.pt')
30
+ if initialized():
31
+ distributed.barrier()
32
+ if rank == 0:
33
+ atomic_json(directory / 'training.json', {'schema': 'pixelone-training-v1', 'step': step,
34
+ 'identity': identity, 'identity_sha256': stable_hash(identity), 'state': 'complete'})
35
+
36
+
37
+ def load_checkpoint(directory, model, optimizer, identity):
38
+ import json
39
+ directory = Path(directory)
40
+ metadata = json.loads((directory / 'training.json').read_text())
41
+ if metadata.get('state') != 'complete' or metadata['identity_sha256'] != stable_hash(identity):
42
+ raise ValueError('Checkpoint is incomplete or belongs to another training recipe/data/world size')
43
+ options = StateDictOptions(cpu_offload=True)
44
+ model_state, optimizer_state = get_state_dict(model, optimizer, options=options)
45
+ state = {'model': model_state, 'optimizer': optimizer_state}
46
+ checkpoint.load(state, checkpoint_id=directory / 'state')
47
+ set_state_dict(model, optimizer, model_state_dict=state['model'],
48
+ optim_state_dict=state['optimizer'], options=options)
49
+ rank = distributed.get_rank() if initialized() else 0
50
+ random_state = torch.load(directory / f'rng_rank_{rank:04d}.pt', map_location='cpu', weights_only=True)
51
+ torch.set_rng_state(random_state['cpu'])
52
+ if 'cuda' in random_state and torch.cuda.is_available():
53
+ torch.cuda.set_rng_state(random_state['cuda'])
54
+ return metadata['step']
PixelOne-Pro-35B-A3B/runtime/src/pixelone/cli.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+
4
+
5
+ def main():
6
+ parser = argparse.ArgumentParser(prog='pixelone')
7
+ commands = parser.add_subparsers(dest='command', required=True)
8
+ inference = commands.add_parser('infer', help='Predict an original-image click')
9
+ inference.add_argument('--model', required=True)
10
+ inference.add_argument('--image', required=True)
11
+ inference.add_argument('--instruction', required=True)
12
+ inference.add_argument('--device', default='cuda:0')
13
+ inference.add_argument('--revision')
14
+ inference.add_argument('--subfolder', help='Model directory within a Hugging Face collection or local path')
15
+ inference.add_argument('--kernel-backend', choices=['native', 'torch'])
16
+ training = commands.add_parser('train', help='Train a search teacher or a direct student')
17
+ training.add_argument('--config', required=True)
18
+ training.add_argument('--resume')
19
+ data = commands.add_parser('prepare-data', help='Validate original-pixel box annotations')
20
+ data.add_argument('--input', required=True)
21
+ data.add_argument('--output', required=True)
22
+ data.add_argument('--image-root')
23
+ cache = commands.add_parser('cache-teacher', help='Run T3 and cache teacher distributions')
24
+ cache.add_argument('--config', required=True)
25
+ cache.add_argument('--adapter', required=True)
26
+ cache.add_argument('--output', required=True)
27
+ export = commands.add_parser('export', help='Export a full student checkpoint without optimizer state')
28
+ export.add_argument('--checkpoint', required=True)
29
+ export.add_argument('--output', required=True)
30
+ export.add_argument('--precision', choices=['training_cuda', 'float32'], default='training_cuda')
31
+ arguments = parser.parse_args()
32
+ if arguments.command == 'infer':
33
+ from PIL import Image
34
+ from pixelone.inference import PixelOnePredictor
35
+ predictor = PixelOnePredictor.from_pretrained(arguments.model, device=arguments.device,
36
+ revision=arguments.revision, subfolder=arguments.subfolder, kernel_backend=arguments.kernel_backend)
37
+ with Image.open(arguments.image) as image:
38
+ result = predictor.predict(image, arguments.instruction)
39
+ print(json.dumps(result, ensure_ascii=False))
40
+ elif arguments.command == 'train':
41
+ from pathlib import Path
42
+ from pixelone.training import run_training
43
+ result = run_training(json.loads(Path(arguments.config).read_text()), resume=arguments.resume)
44
+ print(json.dumps(result))
45
+ elif arguments.command == 'prepare-data':
46
+ from pixelone.data import prepare_dataset
47
+ print(json.dumps(prepare_dataset(arguments.input, arguments.output, arguments.image_root)))
48
+ elif arguments.command == 'export':
49
+ from pixelone.export import export_checkpoint
50
+ print(json.dumps(export_checkpoint(arguments.checkpoint, arguments.output, precision=arguments.precision)))
51
+ elif arguments.command == 'cache-teacher':
52
+ from pathlib import Path
53
+ import torch
54
+ from safetensors.torch import load_file
55
+ from pixelone.training import load_native
56
+ from pixelone.data import GroundingDataset
57
+ from pixelone.teacher import SearchTeacher, cache_teacher
58
+ from jev_spatial_distill.t3.model import Teacher, native_runtime
59
+ config = json.loads(Path(arguments.config).read_text())
60
+ recipe = config['recipe']
61
+ device = torch.device(config.get('device', 'cuda:0'))
62
+ with native_runtime(recipe['kernel_backend']):
63
+ native, processor = load_native(config['base_model'], device)
64
+ model = Teacher(native, recipe)
65
+ try:
66
+ model.load_adapter(load_file(arguments.adapter, device='cpu'))
67
+ cache_teacher(SearchTeacher(model, processor, recipe),
68
+ GroundingDataset(config['data'], config.get('image_root')), arguments.output)
69
+ finally:
70
+ model.close()
71
+
72
+
73
+ if __name__ == '__main__':
74
+ main()
PixelOne-Pro-35B-A3B/runtime/src/pixelone/data.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ import sqlite3
4
+
5
+ from PIL import Image
6
+
7
+ from jev_spatial_distill.spatial_pointer.geometry import Layout
8
+ from jev_click_finetune.objective import support
9
+ from pixelone.io import file_sha256
10
+
11
+
12
+ def normalize_row(row, image_root, verify_image=True):
13
+ required = {'id', 'image', 'instruction', 'bbox_xyxy'}
14
+ if not required <= row.keys():
15
+ raise ValueError('Missing fields: ' + ', '.join(sorted(required - row.keys())))
16
+ if not isinstance(row['id'], str) or not row['id']:
17
+ raise ValueError('Target IDs must be nonempty strings')
18
+ if not isinstance(row['instruction'], str) or not row['instruction'].strip() or '<|' in row['instruction']:
19
+ raise ValueError('Expected a nonempty instruction without model control tokens')
20
+ image = row['image']
21
+ if isinstance(image, list):
22
+ if len(image) != 1:
23
+ raise ValueError('Each target must reference one screenshot')
24
+ image = image[0]
25
+ path = Path(image_root) / image
26
+ if verify_image or 'image_size' not in row or 'image_sha256' not in row:
27
+ with Image.open(path) as source:
28
+ dimensions = list(source.size)
29
+ digest = file_sha256(path)
30
+ if row.get('image_size', dimensions) != dimensions or row.get('image_sha256', digest) != digest:
31
+ raise ValueError('Screenshot identity changed: ' + row['id'])
32
+ else:
33
+ dimensions, digest = row['image_size'], row['image_sha256']
34
+ layout = Layout(*dimensions)
35
+ support(layout, row['bbox_xyxy'])
36
+ return {**row, 'image': [str(path)], 'image_size': dimensions, 'image_sha256': digest}
37
+
38
+
39
+ class GroundingDataset:
40
+ def __init__(self, path, image_root=None):
41
+ self.path = Path(path)
42
+ self.image_root = Path(image_root) if image_root else self.path.parent
43
+ self.offsets, identifiers = [], set()
44
+ with self.path.open('rb') as stream:
45
+ while True:
46
+ offset = stream.tell()
47
+ line = stream.readline()
48
+ if not line:
49
+ break
50
+ row = json.loads(line)
51
+ identifier = row['id']
52
+ if identifier in identifiers:
53
+ raise ValueError('Duplicate target ID: ' + identifier)
54
+ identifiers.add(identifier)
55
+ self.offsets.append(offset)
56
+ if not self.offsets:
57
+ raise ValueError('Empty grounding dataset')
58
+
59
+ def __len__(self):
60
+ return len(self.offsets)
61
+
62
+ def __getitem__(self, index):
63
+ with self.path.open('rb') as stream:
64
+ stream.seek(self.offsets[index])
65
+ row = json.loads(stream.readline())
66
+ return normalize_row(row, self.image_root)
67
+
68
+
69
+ def prepare_dataset(source, destination, image_root=None):
70
+ source, destination = Path(source), Path(destination)
71
+ root = Path(image_root) if image_root else source.parent
72
+ if destination.exists():
73
+ raise ValueError('Choose a new output path; datasets are not overwritten')
74
+ destination.parent.mkdir(parents=True, exist_ok=True)
75
+ identifiers = set()
76
+ with source.open() as inputs, destination.open('x') as outputs:
77
+ for line in inputs:
78
+ original = json.loads(line)
79
+ row = normalize_row(original, root)
80
+ if row['id'] in identifiers:
81
+ raise ValueError('Duplicate target ID: ' + row['id'])
82
+ identifiers.add(row['id'])
83
+ row['image'] = original['image']
84
+ outputs.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + '\n')
85
+ return {'targets': len(identifiers), 'sha256': file_sha256(destination)}
86
+
87
+
88
+ def index_teacher_cache(path, destination):
89
+ path, destination = Path(path), Path(destination)
90
+ if destination.exists():
91
+ raise ValueError('Choose a new index path')
92
+ connection = sqlite3.connect(destination)
93
+ try:
94
+ connection.execute('CREATE TABLE records (id TEXT PRIMARY KEY, offset INTEGER, length INTEGER)')
95
+ connection.execute('CREATE TABLE metadata (key TEXT PRIMARY KEY, value TEXT)')
96
+ with path.open('rb') as stream:
97
+ while True:
98
+ offset = stream.tell()
99
+ line = stream.readline()
100
+ if not line:
101
+ break
102
+ row = json.loads(line)
103
+ connection.execute('INSERT INTO records VALUES (?, ?, ?)', (row['id'], offset, len(line)))
104
+ connection.execute('INSERT INTO metadata VALUES (?, ?)', ('sha256', file_sha256(path)))
105
+ connection.commit()
106
+ finally:
107
+ connection.close()
108
+
109
+
110
+ class IndexedTeacherCache:
111
+ def __init__(self, path, index):
112
+ self.path = Path(path)
113
+ self.connection = sqlite3.connect(Path(index).resolve().as_uri() + '?mode=ro', uri=True)
114
+ expected = self.connection.execute('SELECT value FROM metadata WHERE key="sha256"').fetchone()
115
+ if expected is None or file_sha256(self.path) != expected[0]:
116
+ raise ValueError('Teacher cache does not match its index')
117
+
118
+ def get(self, target):
119
+ offset = self.connection.execute('SELECT offset, length FROM records WHERE id=?', (target['id'],)).fetchone()
120
+ if offset is None:
121
+ raise ValueError('No teacher trace for target: ' + target['id'])
122
+ with self.path.open('rb') as stream:
123
+ stream.seek(offset[0])
124
+ row = json.loads(stream.read(offset[1]))
125
+ if (any(row[key] != target[key] for key in ['id', 'instruction', 'bbox_xyxy', 'image_size'])
126
+ or row['source_image_sha256'] != target['image_sha256']):
127
+ raise ValueError('Teacher trace and training input identities differ')
128
+ return row
129
+
130
+ def close(self):
131
+ self.connection.close()
PixelOne-Pro-35B-A3B/runtime/src/pixelone/export.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from pathlib import Path
4
+ import shutil
5
+ import tempfile
6
+
7
+ import torch
8
+ import torch.distributed.checkpoint as checkpoint
9
+ from safetensors.torch import save_file
10
+
11
+ from pixelone.io import atomic_json, bundle_member, file_sha256
12
+
13
+
14
+ def export_checkpoint(source, destination, *, precision='training_cuda', shard_bytes=2 * 1024**3):
15
+ source, destination = Path(source), Path(destination)
16
+ metadata = json.loads((source / 'training.json').read_text())
17
+ identity = metadata['identity']
18
+ recipe = identity['recipe']
19
+ if metadata.get('state') != 'complete' or recipe.get('train_mode') != 'full':
20
+ raise ValueError('Export requires a complete full-parameter student checkpoint')
21
+ if precision not in ('training_cuda', 'float32') or shard_bytes < 1:
22
+ raise ValueError('Invalid export precision or shard budget')
23
+ if destination.exists():
24
+ raise ValueError('Choose a new model destination')
25
+ assets = source.parent / 'assets'
26
+ for name, expected in identity['assets'].items():
27
+ if file_sha256(bundle_member(assets, name)) != expected:
28
+ raise ValueError('Training processor/model configuration changed: ' + name)
29
+ destination.parent.mkdir(parents=True, exist_ok=True)
30
+ staging = Path(tempfile.mkdtemp(prefix='.' + destination.name + '-', dir=destination.parent))
31
+ reader = checkpoint.FileSystemReader(source / 'state')
32
+ entries = sorted((name, item) for name, item in reader.read_metadata().state_dict_metadata.items()
33
+ if name.startswith('model.student.'))
34
+ if not entries or any('.lora_' in name for name, item in entries):
35
+ raise ValueError('Expected merged full-student checkpoint tensors')
36
+ files, weight_map, tensors, pending = {}, {}, {}, {}
37
+ shard_number, pending_bytes, total_size = 0, 0, 0
38
+
39
+ def flush():
40
+ nonlocal shard_number, pending_bytes, total_size
41
+ if not pending:
42
+ return
43
+ values = {name.removeprefix('model.'): torch.empty(item.size, dtype=item.properties.dtype)
44
+ for name, item in pending.items()}
45
+ checkpoint.load({'model': values}, storage_reader=reader, no_dist=True)
46
+ exported = {}
47
+ for name, value in values.items():
48
+ name = name.removeprefix('student.')
49
+ if not bool(torch.isfinite(value).all()):
50
+ raise ValueError('Nonfinite model tensor: ' + name)
51
+ dtype = torch.float32
52
+ if precision == 'training_cuda' and (name.startswith('native.backbone.language_model.layers.')
53
+ or (recipe['train_vision'] and name.startswith('native.backbone.visual.blocks.'))):
54
+ dtype = torch.bfloat16
55
+ exported[name] = value.to(dtype).contiguous()
56
+ tensors[name] = {'shape': list(value.shape), 'dtype': str(dtype)}
57
+ total_size += exported[name].numel() * exported[name].element_size()
58
+ shard_number += 1
59
+ filename = f'weights-{shard_number:05d}.safetensors'
60
+ save_file(exported, str(staging / filename))
61
+ files[filename] = file_sha256(staging / filename)
62
+ weight_map.update({name: filename for name in exported})
63
+ pending.clear()
64
+ pending_bytes = 0
65
+
66
+ for name, item in entries:
67
+ if not isinstance(item, checkpoint.metadata.TensorStorageMetadata):
68
+ raise ValueError('Expected tensor-only model state')
69
+ size = torch.Size(item.size).numel() * torch.empty((), dtype=item.properties.dtype).element_size()
70
+ if pending and pending_bytes + size > shard_bytes:
71
+ flush()
72
+ pending[name] = item
73
+ pending_bytes += size
74
+ flush()
75
+ for name, expected in identity['assets'].items():
76
+ shutil.copyfile(bundle_member(assets, name), staging / name)
77
+ files[name] = expected
78
+ manifest = {'schema': 'pixelone-pro-v1', 'use_cache': False, 'precision': precision,
79
+ 'recipe': recipe, 'files': files, 'weight_map': weight_map, 'tensors': tensors,
80
+ 'source_step': metadata['step'], 'source_checkpoint_sha256': file_sha256(source / 'training.json'),
81
+ 'runtime_package': 'pixelone-grounding==0.1.0'}
82
+ atomic_json(staging / 'pixelone.json', manifest)
83
+ atomic_json(staging / 'model.safetensors.index.json', {'metadata': {'total_size': total_size}, 'weight_map': weight_map})
84
+ os.rename(staging, destination)
85
+ return {'destination': str(destination), 'shards': shard_number, 'tensor_bytes': total_size}