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