Image-Text-to-Text
Transformers
Safetensors
qwen3_vl
qwen3-vl
viss
streaming-video
visual-question-answering
causal-video
conversational
Run this model with HF Jobs
Run mis2/ViSS-8B on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/mis2/ViSS-8B. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/mis2/ViSS-8B on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/mis2/ViSS-8B. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/mis2/ViSS-8B. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use mis2/ViSS-8B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use mis2/ViSS-8B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="mis2/ViSS-8B") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] pipe(text=messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("mis2/ViSS-8B") model = AutoModelForMultimodalLM.from_pretrained("mis2/ViSS-8B", device_map="auto") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] inputs = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(processor.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use mis2/ViSS-8B with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "mis2/ViSS-8B" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "mis2/ViSS-8B", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker
docker model run hf.co/mis2/ViSS-8B
- SGLang
How to use mis2/ViSS-8B with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "mis2/ViSS-8B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "mis2/ViSS-8B", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "mis2/ViSS-8B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "mis2/ViSS-8B", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }' - Docker Model Runner
How to use mis2/ViSS-8B with Docker Model Runner:
docker model run hf.co/mis2/ViSS-8B
Release ViSS-8B weights, processors and source code
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+2
- CITATION.cffAdded+29
- LICENSEAdded+202
- README.mdAdded+113
- added_tokens.jsonAdded+28
- chat_template.jinjaAdded+120
- code/.gitignoreAdded+20
- code/LICENSEAdded+202
- code/NOTICEAdded+16
- code/README.mdAdded+135
- code/configs/evaluation/recent4.example.jsonAdded+74
- code/configs/training/deepspeed_zero3_bf16.jsonAdded+16
- code/data_pipeline/__init__.pyAdded+1
- code/data_pipeline/temporal_scope/__init__.pyAdded+1
- code/data_pipeline/temporal_scope/build_size_matched_generic_control.pyAdded+107
- code/data_pipeline/temporal_scope/build_source_aligned_sft_release.pyAdded+722
- code/data_pipeline/temporal_scope/build_vst_prefix32_semantic.pyAdded+525
- code/data_pipeline/temporal_scope/filter_semantic_release_by_blind_audit.pyAdded+329
- code/data_pipeline/temporal_scope/filter_semantic_release_by_option_consensus.pyAdded+298
- code/data_pipeline/temporal_scope/select_quality_capability_rows.pyAdded+420
- code/data_pipeline/temporal_scope/semantic_mcq.pyAdded+90
- code/docs/DATA.mdAdded+63
- code/docs/EVALUATION.mdAdded+114
- code/docs/INSTALL.mdAdded+59
- code/docs/TRAINING.mdAdded+50
- code/experiments/analyze_uncertainty_temporal_escalation.pyAdded+451
- code/experiments/evaluate_qwen3vl_recent4_full.pyAdded
- code/experiments/materialize_confidence_gated_third_view_agent.pyAdded+259
- code/experiments/materialize_third_view_disagreement_agent.pyAdded+203
- code/experiments/materialize_tvs_view_oracle.pyAdded+118
- code/experiments/materialize_uncertainty_temporal_agent.pyAdded+465
- code/experiments/select_uncertainty_escalation_uids.pyAdded+192
- code/experiments/train_qwen3vl_sft.pyAdded+1091
- code/experiments/tvs_correctness.pyAdded+80
- code/pyproject.tomlAdded+32
- code/scripts/__init__.pyAdded+1
- code/scripts/configure_evaluation_protocol.pyAdded+62
- code/scripts/merge_eval_shards.pyAdded+483
- code/scripts/run_recent4_single_benchmark.shAdded+380
- code/scripts/score_official_benchmark_predictions.pyAdded+348
- code/scripts/validate_evaluation_protocol.pyAdded+28
- code/tests/test_confidence_gated_third_view_agent.pyAdded+77
- code/tests/test_filter_semantic_release_by_option_consensus.pyAdded+84
- code/tests/test_materialize_uncertainty_temporal_agent.pyAdded+551
- code/tests/test_public_protocol.pyAdded+47
- code/tests/test_recent4_runner.pyAdded+893
- code/tests/test_semantic_answer_loss_mask.pyAdded+108
- code/tests/test_size_matched_generic_control.pyAdded+26
- code/tests/test_source_aligned_sft_release.pyAdded+125
- code/tests/test_third_view_disagreement_agent.pyAdded+78
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 lines333435363732 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 -textlocked_processor/tokenizer.json filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text
1234567891011121314151617181920212223242526272829cff-version: 1.2.0message: "Please cite the ViSS manuscript when using this model and code."title: "Supervising the Visible State: Separating Representation from View Selection in Streaming Video"type: softwareauthors: - family-names: Hu given-names: Yihao - family-names: Wang given-names: Pan - family-names: Lin given-names: Yitong - family-names: Wen given-names: Zhihao - family-names: Liu given-names: Deyuan - family-names: Wang given-names: Hang - family-names: Wan given-names: Mingda - family-names: Zhao given-names: Yiwen - family-names: Li given-names: Yutong - family-names: Mao given-names: Yuchen - family-names: Lin given-names: Taolicense: Apache-2.0url: "https://huggingface.co/mis2/ViSS-8B"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 [yyyy] [name of copyright owner]
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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113---license: apache-2.0base_model: Qwen/Qwen3-VL-8B-Instructlibrary_name: transformerspipeline_tag: image-text-to-texttags:- qwen3-vl- viss- streaming-video- visual-question-answering- causal-video---
# ViSS-8B
**Supervising the Visible State: Separating Representation from View Selection in Streaming Video**
Yihao Hu*, Pan Wang*, Yitong Lin*, Zhihao Wen†, Deyuan Liu, Hang Wang,Mingda Wan, Yiwen Zhao, Yutong Li, Yuchen Mao, Tao Lin†
*Equal contribution. †Corresponding author.*
[Collection](https://huggingface.co/collections/mis2/viss-6adc8caf041ae0c501c9a11b) ·[Source code](https://huggingface.co/mis2/ViSS-8B/tree/main/code) ·[Installation](code/docs/INSTALL.md) ·[Training](code/docs/TRAINING.md) ·[Evaluation](code/docs/EVALUATION.md)
## Overview
Visible-State Supervision (ViSS) trains a vision–language model onsource-grounded questions about event identity, order, accumulation,relation changes, and whether the available evidence suffices to answer.Test-Time Causal View Search (TVS) keeps the model fixed and acquirescomplementary recent, event, and compact-history views.
The model is initialized from Qwen3-VL-8B-Instruct and trained for one epochon 7,677 examples, with learning rate 2e-6 and global batch size 12.The vision tower is frozen; the language model and multimodal projectorare trainable. Model-only ViSS and TVS use the same checkpoint.
## Released files
- Four original BF16 safetensors shards (17.53 GB in total).- Model configuration, tokenizer, chat template, and native processor.- `locked_processor/`: the processor used for the recent-view evaluation.- `code/`: training, inference, TVS composition, evaluation adapters, public configuration templates, documentation, and synthetic tests.
The release contains no training annotations, raw media, company experimentrecords, prediction files, evaluation summaries, optimizer states, or internaltraining manifests. Training data are not being released in this version.
## Download
```bashhf download mis2/ViSS-8B --local-dir checkpoints/ViSS-8B```
## Load the model
Use a Transformers version supporting Qwen3-VL; the retained modelconfiguration specifies Transformers 4.57.3.
```pythonimport torchfrom transformers import AutoProcessor, Qwen3VLForConditionalGeneration
model_id = "mis2/ViSS-8B"processor = AutoProcessor.from_pretrained( model_id, subfolder="locked_processor")model = Qwen3VLForConditionalGeneration.from_pretrained( model_id, dtype=torch.bfloat16, device_map="auto",)```
The root processor is the native training processor. The`locked_processor/` subdirectory preserves the recent-view evaluationprocessor. The supplied evaluator implements causal sampling and benchmarkprompt conventions; loading the processor alone does not implement TVS.
## Use the code
```bashcd checkpoints/ViSS-8B/codepython -m pip install -e ".[inference,test]"python -m pytest -q tests```
See the evaluation guide to bind the public configuration template to yourown processor, benchmark query exports, and model. Benchmark media andofficial scoring installations must be obtained separately. TVS additionallyrequires calibration inputs prepared independently of benchmark evaluation.
## License
The source code follows the project's Apache-2.0 license. The model isderived from Qwen3-VL-8B-Instruct, which is also distributed under Apache-2.0.External benchmark and media terms remain with their respective providers.
## Citation
```bibtex@misc{hu2026viss, title={Supervising the Visible State: Separating Representation from View Selection in Streaming Video}, author={Yihao Hu and Pan Wang and Yitong Lin and Zhihao Wen and Deyuan Liu and Hang Wang and Mingda Wan and Yiwen Zhao and Yutong Li and Yuchen Mao and Tao Lin}, year={2026}, note={Manuscript}}```12345678910111213141516171819202122232425262728{ "</think>": 151668, "</tool_call>": 151658, "</tool_response>": 151666, "<think>": 151667, "<tool_call>": 151657, "<tool_response>": 151665, "<|box_end|>": 151649, "<|box_start|>": 151648, "<|endoftext|>": 151643, "<|file_sep|>": 151664, "<|fim_middle|>": 151660, "<|fim_pad|>": 151662, "<|fim_prefix|>": 151659, "<|fim_suffix|>": 151661, "<|im_end|>": 151645, "<|im_start|>": 151644, "<|image_pad|>": 151655, "<|object_ref_end|>": 151647, "<|object_ref_start|>": 151646, "<|quad_end|>": 151651, "<|quad_start|>": 151650, "<|repo_name|>": 151663, "<|video_pad|>": 151656, "<|vision_end|>": 151653, "<|vision_pad|>": 151654, "<|vision_start|>": 151652}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120{%- if tools %} {{- '<|im_start|>system\n' }} {%- if messages[0].role == 'system' %} {%- if messages[0].content is string %} {{- messages[0].content }} {%- else %} {%- for content in messages[0].content %} {%- if 'text' in content %} {{- content.text }} {%- endif %} {%- endfor %} {%- endif %} {{- '\n\n' }} {%- endif %} {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }} {%- for tool in tools %} {{- "\n" }} {{- tool | tojson }} {%- endfor %} {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}{%- else %} {%- if messages[0].role == 'system' %} {{- '<|im_start|>system\n' }} {%- if messages[0].content is string %} {{- messages[0].content }} {%- else %} {%- for content in messages[0].content %} {%- if 'text' in content %} {{- content.text }} {%- endif %} {%- endfor %} {%- endif %} {{- '<|im_end|>\n' }} {%- endif %}{%- endif %}{%- set image_count = namespace(value=0) %}{%- set video_count = namespace(value=0) %}{%- for message in messages %} {%- if message.role == "user" %} {{- '<|im_start|>' + message.role + '\n' }} {%- if message.content is string %} {{- message.content }} {%- else %} {%- for content in message.content %} {%- if content.type == 'image' or 'image' in content or 'image_url' in content %} {%- set image_count.value = image_count.value + 1 %} {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%} <|vision_start|><|image_pad|><|vision_end|> {%- elif content.type == 'video' or 'video' in content %} {%- set video_count.value = video_count.value + 1 %} {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%} <|vision_start|><|video_pad|><|vision_end|> {%- elif 'text' in content %} {{- content.text }} {%- endif %} {%- endfor %} {%- endif %} {{- '<|im_end|>\n' }} {%- elif message.role == "assistant" %} {{- '<|im_start|>' + message.role + '\n' }} {%- if message.content is string %} {{- message.content }} {%- else %} {%- for content_item in message.content %} {%- if 'text' in content_item %} {{- content_item.text }} {%- endif %} {%- endfor %} {%- endif %} {%- if message.tool_calls %} {%- for tool_call in message.tool_calls %} {%- if (loop.first and message.content) or (not loop.first) %} {{- '\n' }} {%- endif %} {%- if tool_call.function %} {%- set tool_call = tool_call.function %} {%- endif %} {{- '<tool_call>\n{"name": "' }} {{- tool_call.name }} {{- '", "arguments": ' }} {%- if tool_call.arguments is string %} {{- tool_call.arguments }} {%- else %} {{- tool_call.arguments | tojson }} {%- endif %} {{- '}\n</tool_call>' }} {%- endfor %} {%- endif %} {{- '<|im_end|>\n' }} {%- elif message.role == "tool" %} {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} {{- '<|im_start|>user' }} {%- endif %} {{- '\n<tool_response>\n' }} {%- if message.content is string %} {{- message.content }} {%- else %} {%- for content in message.content %} {%- if content.type == 'image' or 'image' in content or 'image_url' in content %} {%- set image_count.value = image_count.value + 1 %} {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%} <|vision_start|><|image_pad|><|vision_end|> {%- elif content.type == 'video' or 'video' in content %} {%- set video_count.value = video_count.value + 1 %} {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%} <|vision_start|><|video_pad|><|vision_end|> {%- elif 'text' in content %} {{- content.text }} {%- endif %} {%- endfor %} {%- endif %} {{- '\n</tool_response>' }} {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} {{- '<|im_end|>\n' }} {%- endif %} {%- endif %}{%- endfor %}{%- if add_generation_prompt %} {{- '<|im_start|>assistant\n' }}{%- endif %}1234567891011121314151617181920__pycache__/*.py[cod].pytest_cache/*.egg-info/build/dist/.venv/outputs/results/logs/checkpoints/data/records/runs/manifests/configs/evaluation/recent4_full_v1.jsonrelease_manifest.json*.log.env.env.*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 [yyyy] [name of copyright owner]
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.12345678910111213141516ViSS: Visible-State Supervision and Test-Time Causal View Search
This source release is derived from the ViSS research repository and carriesthat repository's Apache License 2.0, supplied in LICENSE.
The code uses external libraries including PyTorch, Transformers, Accelerate,DeepSpeed, qwen-vl-utils, Decord, NumPy, and Pillow. Those projects retaintheir own licenses. Qwen3-VL model weights, training media, benchmark data,and official benchmark scorers are not redistributed in this archive.
Evaluation adapters preserve the StreamingBench/SimpleStream prompt interfaceand OVO-Bench task interfaces described in the evaluation protocol.Users must obtain the corresponding resources under their original terms.
The README organization takes inspiration from the OneStreamer repository.No OneStreamer implementation, model weights, data, or figures are included.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135<div align="center">
# ViSS### Supervising the Visible State: Separating Representation from View Selection in Streaming Video
Yihao Hu*, Pan Wang*, Yitong Lin*, Zhihao Wen†, Deyuan Liu, Hang Wang, Mingda WAN, Yiwen Zhao, Yutong Li, Yuchen Mao, Tao Lin†
<sup>* Equal contribution. † Corresponding author.</sup>
[Overview](#overview) · [Codebase](#codebase) · [Quick start](#quick-start) ·[Models and data](#models-and-data) · [Training](docs/TRAINING.md) ·[Evaluation](docs/EVALUATION.md) · [Citation](#citation)
</div>
## Overview
**Visible-State Supervision (ViSS)** trains a vision–language model onsource-grounded questions about event identity, order, accumulation,relation changes, and whether the visible evidence is sufficient.
**Test-Time Causal View Search (TVS)** keeps the trained model fixed andacquires complementary causal views. It starts with recent frames, requestsan event view when needed, and consults compact history on disagreement.Acquisition and answer commitment use separately calibrated thresholds.
This release provides data construction, training, inference, policy replay,and scoring code. It contains no saved benchmark scores, prediction outputs,or training logs. Scoring utilities and synthetic unit tests are included.
## Codebase
| Directory | Purpose | Guide || --- | --- | --- || `data_pipeline/` | Build source-grounded probes and matched generic controls | [Training](docs/TRAINING.md) || `experiments/` | Train the model, generate causal-view proposals, and apply TVS | [Evaluation](docs/EVALUATION.md) || `viss_core/` | Record validation, media handling, and benchmark adapters | [Data preparation](docs/DATA.md) || `scripts/` | Evaluation launchers, shard merging, and official scoring | [Evaluation](docs/EVALUATION.md) || `configs/` | Evaluation protocol and DeepSpeed configuration | [Installation](docs/INSTALL.md) || `tests/` | CPU checks of data contracts, sampling, loss masks, and view policies | [Quick start](#quick-start) |
The repository contains no internal training manifests, run records, datainventories, calibration outputs, or file identities from company experiments.The evaluation configuration is a public template; each user binds it totheir own inputs. See [Data preparation](docs/DATA.md).
## Quick start
Run these commands from the extracted repository root.
### Install and check the source
```bashpython -m venv .venvsource .venv/bin/activatepython -m pip install --upgrade pippython -m pip install -e ".[test]"python -m pytest -q tests```
The unit tests use synthetic inputs and do not download model weights orbenchmark media. GPU inference and training require the additional setup in[Installation](docs/INSTALL.md).
### Generate predictions and score separately
After preparing your model, annotations, query exports, media, and[local evaluation protocol](docs/EVALUATION.md#1-generate-recent-view-proposals):
```bashpython -m experiments.evaluate_qwen3vl_recent4_full \ --benchmark streamingbench \ --annotation data/streamingbench/annotations.json \ --samples data/streamingbench/queries.jsonl \ --video-root data/streamingbench/videos \ --model checkpoints/viss \ --processor checkpoints/viss/locked_processor \ --protocol configs/evaluation/recent4_full_v1.json \ --frame-policy recent4 \ --visual-input-mode image-list \ --record-choice-confidence \ --output outputs/streamingbench_recent.json```
The paths above are placeholders for separately prepared assets. Bind theprocessor and query exports used in your evaluation before running inference.The [evaluation guide](docs/EVALUATION.md) explains modelidentity, TVS inputs, official scorers, and full-population checks.
## Models and data
| Resource | Included in this archive? | Preparation || --- | --- | --- || Source code, tests, and protocol | Yes | This repository || Qwen3-VL-8B-Instruct initialization | No | Obtain the official model || Trained ViSS weights and locked processor | No | Obtain separately or train ViSS || Accepted training records and media | No | Follow [data preparation](docs/DATA.md) || Benchmark annotations, videos, and official scorers | No | Obtain from the benchmark owners || TVS calibration and model-identity artifacts | No | Supply artifacts matching your evaluation |
No public download endpoint for ViSS-specific weights or training records isasserted by this source package.
## Training
The paper recipe is a fresh one-epoch run from Qwen3-VL-8B-Instruct.It freezes the vision tower and updates the language model and multimodalprojector. [Training](docs/TRAINING.md) gives the two-GPU command and explainsthe required sealed training release.
Some serialized records retain `streameva.*` schema identifiers. These arerecord-format identifiers; the corresponding implementation in this releaseis under `viss_core/`.
## License and acknowledgements
The project code uses the repository's [Apache-2.0 license](LICENSE).Third-party software, media, models, and benchmark assets retain theirrespective terms; see [NOTICE](NOTICE).
We acknowledge Qwen3-VL, StreamingBench, OVO-Bench, and SimpleStream.The documentation organization follows the separation of setup, inference,and evaluation used in [OneStreamer](https://github.com/MCG-NJU/OneStreamer).
## Citation
```bibtex@misc{hu2026viss, title={Supervising the Visible State: Separating Representation from View Selection in Streaming Video}, author={Yihao Hu and Pan Wang and Yitong Lin and Zhihao Wen and Deyuan Liu and Hang Wang and Mingda Wan and Yiwen Zhao and Yutong Li and Yuchen Mao and Tao Lin}, year={2026}, note={Manuscript}}```1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374{ "format": "iclr_video.locked_evaluation_protocol.v1", "protocol_id": "recent4_full_v1", "status": "template", "applies_to": "all baseline and candidate checkpoints", "inference": { "causal_prefix_only": true, "sampling_fps": 1.0, "context_policy": "recent_n", "recent_frames": 4, "timestamp_rule": "match the SimpleStream release: decode a four-second half-open causal prefix window [max(0,t-4),t) at nominal 1 FPS and retain exactly four independently encoded image frames; only prefixes shorter than two raw frames repeat frame zero", "allow_future_frames": false, "allow_global_frames": false, "allow_extra_frame_inspection": false, "allow_persistent_visual_or_text_memory": false, "visual_input_mode": "four independent image frames using qwen-vl-utils fetch_video (image_patch_size=14), never Qwen video tokens", "processor_contract": { "preprocessor_config_sha256": "", "image_processor_type": "Qwen2VLImageProcessorFast", "patch_size": 16, "merge_size": 2, "temporal_patch_size": 2, "shortest_edge": 65536, "longest_edge": 16777216, "reference_visual_tokens_per_frame": 576, "reason": "Bind the processor used by your evaluation before inference." }, "prompt_source": "StreamingBench SimpleStream release MCQ template; OVO backward/realtime SimpleStream release one-letter template; OVO forward frozen official task wrapper; no system message", "decode": { "do_sample": false, "temperature": 0.0 } }, "benchmarks": { "streamingbench": { "scope": "Real-Time full", "export": "data/streamingbench/queries.jsonl", "export_sha256": "", "expected_queries": 2495, "expected_groups": { "real_time_visual": 2495 }, "primary_metric": "official Real-Time accuracy" }, "ovo": { "scope": "all 12 tasks: Real-Time, Backward, and Forward", "export": "data/ovo/queries.jsonl", "export_sha256": "", "expected_queries": 3035, "expected_tasks": { "ACR": 109, "ASI": 148, "ATR": 116, "CRR": 240, "EPM": 297, "FPD": 101, "HLD": 186, "OCR": 149, "OJR": 184, "REC": 698, "SSR": 629, "STU": 178 }, "primary_metric": "official Total Avg", "secondary_metrics": [ "micro Overall", "Real-Time Avg", "Backward Avg", "Forward Avg", "RT/BT Avg" ] } }}12345678910111213141516{ "bf16": {"enabled": "auto"}, "train_micro_batch_size_per_gpu": "auto", "train_batch_size": "auto", "gradient_accumulation_steps": "auto", "gradient_clipping": "auto", "zero_optimization": { "stage": 3, "overlap_comm": true, "contiguous_gradients": true, "reduce_bucket_size": "auto", "stage3_prefetch_bucket_size": "auto", "stage3_param_persistence_threshold": "auto", "stage3_gather_16bit_weights_on_model_save": true }}1"""Stable, user-facing entry points for reproducing StreamEVA data."""1"""Deterministic semantic-SFT and public typed-contract compilers."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107#!/usr/bin/env python3"""Select a deterministic, source-stratified generic temporal SFT control."""
from __future__ import annotations
import argparseimport hashlibimport jsonfrom collections import defaultdictfrom pathlib import Pathfrom typing import Any
SUPPORTED_PARENT_KINDS = ( "source_semantic_row", "cited_nonbenchmark_refresh_projection",)
def _rank(seed: str, parent_id: str) -> str: return hashlib.sha256(f"{seed}\0{parent_id}".encode()).hexdigest()
def select_parent_ids( rows: list[dict[str, Any]], *, seed: str, quotas: dict[str, int]) -> tuple[list[str], dict[str, int]]: grouped: dict[str, list[str]] = defaultdict(list) seen: set[str] = set() for row in rows: parents = row.get("parents") or [] if len(parents) != 1: raise ValueError("generic control requires exactly one parent per row") parent_id = str(parents[0].get("id") or "") parent_kind = str(parents[0].get("kind") or "") if not parent_id or parent_kind not in SUPPORTED_PARENT_KINDS: raise ValueError("generic control parent provenance is malformed") if parent_id in seen: raise ValueError("generic control parent IDs must be unique") seen.add(parent_id) grouped[parent_kind].append(parent_id)
selected: list[str] = [] counts: dict[str, int] = {} for kind in SUPPORTED_PARENT_KINDS: quota = int(quotas.get(kind, 0)) candidates = grouped[kind] if quota <= 0 or quota > len(candidates): raise ValueError(f"invalid quota for {kind}: {quota}/{len(candidates)}") ranked = sorted(candidates, key=lambda value: (_rank(seed, value), value)) chosen = ranked[:quota] selected.extend(chosen) counts[kind] = len(chosen) return sorted(selected), counts
def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--source", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--seed", default="viss-generic-control-7677-v1") parser.add_argument("--source-semantic-rows", type=int, default=5903) parser.add_argument("--cited-refresh-rows", type=int, default=1774) args = parser.parse_args()
source = args.source.resolve(strict=True) trainer = source / "trainer/sft.jsonl" manifest = source / "manifest.json" if args.output.exists(): raise FileExistsError(args.output) rows = [json.loads(line) for line in trainer.read_text().splitlines() if line] selected, counts = select_parent_ids( rows, seed=args.seed, quotas={ "source_semantic_row": args.source_semantic_rows, "cited_nonbenchmark_refresh_projection": args.cited_refresh_rows, }, ) if len(selected) != args.source_semantic_rows + args.cited_refresh_rows: raise AssertionError("generic control selection size diverged")
payload = { "format": "iclr_video.capability_parent_selection.v1", "status": "sealed_deduplicated_union", "purpose": "size_matched_generic_temporal_sft_control", "seed": args.seed, "source_release": str(source), "source_release_id": json.loads(manifest.read_text()).get("release_id"), "parent_ids": selected, "profiles": list(SUPPORTED_PARENT_KINDS), "counts_by_profile": counts, "total_rows": len(selected), "contracts": { "benchmark_content_used_for_selection": False, "source_release_membership_verified": True, "model_predictions_used_for_selection": False, "task_labels_used_for_selection": False, "selection_is_sha256_ranked_within_source_kind": True, }, } args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") print(json.dumps({"output": str(args.output), "rows": len(selected), "counts": counts}))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722#!/usr/bin/env python3"""Compose one source-aligned, benchmark-firewalled pure-VLM SFT release.
The inputs are already sealed semantic releases built from non-benchmarktraining videos. This compiler keeps the original semantic labels, removesoverlap by cited source identity and exact pixel/question/answer identity,canonicalizes media paths by SHA256, and emits the only JSONL consumed by onejoint SFT run. Benchmark examples and auditor predictions are never labels."""
from __future__ import annotations
import argparseimport collectionsimport copyimport hashlibimport jsonimport mathimport osimport randomimport shutilimport tempfilefrom pathlib import Pathfrom typing import Any
from viss_core.data_v0.canonical import ( attach_content_sha256, canonical_json_bytes, canonical_json_line, file_sha256, read_jsonl, stable_id, write_jsonl,)from viss_core.data_v0.schema import validate_rowfrom viss_core.data_v0.semantic_release import ( EXPECTED_PUBLIC_UPSTREAM_MANIFEST_SHA256, FORMAT, validate_semantic_release,)
class SourceAlignedSFTError(ValueError): """Raised when source releases cannot be composed without leakage."""
def _target(row: dict[str, Any]) -> str: values = [ str(item.get("text") or "") for message in row.get("messages") or [] if message.get("role") == "assistant" and message.get("loss") is True for item in message.get("content") or [] if item.get("type") == "text" ] if len(values) != 1: raise SourceAlignedSFTError("semantic row has no unique target") return values[0]
def _question(row: dict[str, Any]) -> str: values = [ str(item.get("text") or "") for message in row.get("messages") or [] if message.get("role") == "user" for item in message.get("content") or [] if item.get("type") == "text" ] if len(values) != 1: raise SourceAlignedSFTError("semantic row has no unique public prompt") return " ".join(values[0].split())
def _images(row: dict[str, Any]) -> list[str]: return [ str(item["image"]) for message in row.get("messages") or [] for item in message.get("content") or [] if item.get("type") == "image" ]
def _cited_parents(row: dict[str, Any]) -> set[str]: return { str(parent["id"]) for parent in row.get("parents") or [] if parent.get("kind") == "cited_nonbenchmark_refresh_projection" and parent.get("id") }
def _semantic_identity( row: dict[str, Any], inventory: dict[str, dict[str, Any]]) -> str: try: image_sha256s = [str(inventory[path]["sha256"]) for path in _images(row)] except KeyError as exc: raise SourceAlignedSFTError("row references undeclared source media") from exc payload = { "answer": _target(row), "image_sha256s": image_sha256s, "question": _question(row), } return hashlib.sha256(canonical_json_bytes(payload)).hexdigest()
def _canonical_media_path(relative: str, digest: str) -> str: suffix = Path(relative).suffix.casefold() if not suffix or len(suffix) > 10: raise SourceAlignedSFTError("source media suffix is invalid") return (Path("media/sha256") / digest[:2] / f"{digest}{suffix}").as_posix()
def _materialize(source: Path, destination: Path, *, mode: str) -> None: if source.is_symlink() or not source.is_file(): raise SourceAlignedSFTError(f"unsafe source media: {source}") destination.parent.mkdir(parents=True, exist_ok=True) if mode in {"hardlink", "auto"}: try: os.link(source, destination) return except OSError: if mode == "hardlink": raise shutil.copy2(source, destination)
def _lineage_key(manifest: dict[str, Any]) -> tuple[str, str, str]: lineage = manifest.get("model_lineage") or {} return ( str(lineage.get("required_sha256s_sha256") or ""), str(lineage.get("upstream_repo") or ""), str(lineage.get("upstream_revision") or ""), )
def _teacher_used_for_labels(manifest: dict[str, Any]) -> bool: value = (manifest.get("contracts") or {}).get("teacher_used_for_labels") if not isinstance(value, bool): raise SourceAlignedSFTError( "source teacher-label provenance is absent or malformed" ) return value
def _load_legacy_v62di_source(root: Path, *, mode: str = "v62di_only"): raise SourceAlignedSFTError("Private legacy adapters are not distributed; supply a standard source release")
def _load_legacy_repcount_source(root: Path): raise SourceAlignedSFTError("Private legacy adapters are not distributed; supply a standard source release")
def build(args: argparse.Namespace) -> dict[str, Any]: sealed_source_count = ( len(args.source) + int(getattr(args, "legacy_v62di_source", None) is not None) + int(getattr(args, "legacy_repcount_source", None) is not None) ) # A hash-bound parent selection is also a legitimate one-source filtering # operation. Unfiltered releases remain compositions and therefore still # require at least two sealed inputs. if sealed_source_count < 2 and getattr(args, "include_parent_selection", None) is None: raise SourceAlignedSFTError( "at least two sealed sources are required unless a parent selection is supplied" ) if args.copy_mode not in {"copy", "hardlink", "auto"}: raise SourceAlignedSFTError("unsupported copy mode") sample_loss_weight_cap = float(args.sample_loss_weight_cap) if not math.isfinite(sample_loss_weight_cap) or sample_loss_weight_cap < 0: raise SourceAlignedSFTError( "sample loss weight cap must be finite and non-negative" ) excluded_parent_kinds = { str(kind).strip() for kind in getattr(args, "exclude_parent_kind", []) if str(kind).strip() } included_source_stage_release_ids = { str(release_id).strip() for release_id in getattr(args, "include_source_stage_release_id", []) if str(release_id).strip() } parent_selection_path = getattr(args, "include_parent_selection", None) selected_parent_ids: set[str] = set() parent_selection_record: dict[str, Any] | None = None if parent_selection_path is not None: parent_selection_path = parent_selection_path.resolve(strict=True) selection = json.loads(parent_selection_path.read_text(encoding="utf-8")) if selection.get("format") not in { "iclr_video.capability_parent_selection.v0", "iclr_video.capability_parent_selection.v1", }: raise SourceAlignedSFTError("parent selection format diverged") if selection.get("format").endswith(".v1") and ( selection.get("status") != "sealed_deduplicated_union" or (selection.get("contracts") or {}).get( "benchmark_content_used_for_selection" ) is not False or (selection.get("contracts") or {}).get( "source_release_membership_verified" ) is not True ): raise SourceAlignedSFTError("v1 parent selection contract diverged") parent_ids = selection.get("parent_ids") or [] if ( not isinstance(parent_ids, list) or not parent_ids or any(not isinstance(value, str) or not value for value in parent_ids) or len(set(parent_ids)) != len(parent_ids) ): raise SourceAlignedSFTError("parent selection IDs are malformed") selected_parent_ids = set(parent_ids) parent_selection_record = { "path": str(parent_selection_path), "sha256": file_sha256(parent_selection_path), "parent_ids": len(selected_parent_ids), "profiles": list( selection.get("profiles") or sorted((selection.get("counts_by_profile") or {}).keys()) ), } output = args.output.resolve() if output.exists(): raise FileExistsError(output)
ordered_curriculum = bool(getattr(args, "ordered_curriculum", False)) retain_semantic_exposures = bool( getattr(args, "retain_semantic_exposures", False) ) legacy_v62di_source = getattr(args, "legacy_v62di_source", None) legacy_v62di_mode = getattr(args, "legacy_v62di_mode", "v62di_only") legacy_repcount_source = getattr(args, "legacy_repcount_source", None) if legacy_v62di_source is not None and not ordered_curriculum: raise SourceAlignedSFTError( "legacy V62DI input is allowed only for ordered curriculum" ) if legacy_repcount_source is not None and not ordered_curriculum: raise SourceAlignedSFTError( "legacy RepCount input is allowed only for ordered curriculum" ) expected_lineage: tuple[str, str, str] | None = None seen_identity: set[str] = set() seen_cited_parent: dict[str, str] = {} accepted: list[tuple[dict[str, Any], Path, dict[str, dict[str, Any]], str]] = [] source_records = [] rejected: collections.Counter[str] = collections.Counter() observed_selected_parent_ids: set[str] = set()
if legacy_v62di_source is not None: legacy_root = legacy_v62di_source.resolve(strict=True) legacy_rows, legacy_inventory, legacy_record = _load_legacy_v62di_source( legacy_root, mode=legacy_v62di_mode ) for row in legacy_rows: identity = _semantic_identity(row, legacy_inventory) accepted.append((row, legacy_root, legacy_inventory, identity)) seen_identity.add(identity) source_records.append(legacy_record)
source_specs: list[tuple[str, Path]] = [] for source_index, raw_root in enumerate(args.source): source_specs.append(("semantic", raw_root)) if source_index == 0 and legacy_repcount_source is not None: source_specs.append(("legacy_repcount", legacy_repcount_source))
for source_kind, raw_root in source_specs: root = raw_root.resolve(strict=True) if source_kind == "legacy_repcount": rows, inventory, source_record = _load_legacy_repcount_source(root) manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8")) else: manifest = validate_semantic_release(root, verify_media_hashes=False) lineage_key = _lineage_key(manifest) if expected_lineage is None: expected_lineage = lineage_key elif lineage_key != expected_lineage: raise SourceAlignedSFTError("source model lineages diverged") if lineage_key[0] != EXPECTED_PUBLIC_UPSTREAM_MANIFEST_SHA256: raise SourceAlignedSFTError("source does not descend from pinned Instruct") if (manifest.get("contracts") or {}).get("benchmark_rows_or_labels_admitted", 0) != 0: raise SourceAlignedSFTError("source admits benchmark rows or labels") teacher_used_for_labels = _teacher_used_for_labels(manifest)
if source_kind == "semantic": inventory_rows = read_jsonl( root / "manifests/media_inventory.jsonl", require_canonical=True ) inventory = {str(item["path"]): item for item in inventory_rows} if len(inventory) != len(inventory_rows): raise SourceAlignedSFTError("source media inventory paths collide") rows = read_jsonl( root / "trainer/sft.jsonl", verify_content_hashes=True, require_canonical=True, ) if included_source_stage_release_ids: stages = (manifest.get("inputs") or {}).get("curriculum_stages") or [] selected_stages = [ stage for stage in stages if str(stage.get("release_id")) in included_source_stage_release_ids ] selected_ids = { str(stage["release_id"]) for stage in selected_stages } missing_ids = included_source_stage_release_ids - selected_ids if missing_ids: raise SourceAlignedSFTError( "requested source stages are absent: " + ",".join(sorted(missing_ids)) ) selected_rows = [] for stage in sorted( selected_stages, key=lambda item: int(item["start_row"]) ): start = int(stage["start_row"]) end = int(stage["end_row_exclusive"]) if start < 0 or end <= start or end > len(rows): raise SourceAlignedSFTError( "source curriculum stage range is invalid" ) if end - start != int(stage["rows"]): raise SourceAlignedSFTError( "source curriculum stage row count diverged" ) selected_rows.extend(rows[start:end]) rows = selected_rows accepted_before = len(accepted) for row in rows: row_parent_ids = { str(parent.get("id") or "") for parent in row.get("parents") or [] } selected_matches = row_parent_ids & selected_parent_ids if selected_parent_ids and not selected_matches: rejected["outside_parent_selection"] += 1 continue observed_selected_parent_ids.update(selected_matches) row_parent_kinds = { str(parent.get("kind") or "") for parent in row.get("parents") or [] } excluded = sorted(row_parent_kinds & excluded_parent_kinds) if excluded: for kind in excluded: rejected[f"excluded_parent_kind:{kind}"] += 1 continue identity = _semantic_identity(row, inventory) cited = _cited_parents(row) conflicts = { seen_cited_parent[parent] for parent in cited if parent in seen_cited_parent } if conflicts and conflicts != {identity}: raise SourceAlignedSFTError( "one cited source parent maps to conflicting semantic rows" ) retain_repeated_rows = ordered_curriculum or retain_semantic_exposures if identity in seen_identity and not retain_repeated_rows: rejected["duplicate_semantic_identity"] += 1 for parent in cited: seen_cited_parent.setdefault(parent, identity) continue if conflicts and not retain_repeated_rows: rejected["duplicate_cited_source_parent"] += 1 continue seen_identity.add(identity) for parent in cited: seen_cited_parent[parent] = identity accepted.append((row, root, inventory, identity)) record = ( source_record if source_kind == "legacy_repcount" else { "accepted_rows": len(accepted) - accepted_before, "manifest_sha256": file_sha256(root / "manifest.json"), "release_id": manifest["release_id"], "root": str(root), "source_rows": len(rows), "teacher_used_for_labels": teacher_used_for_labels, "trainer_sha256": file_sha256(root / "trainer/sft.jsonl"), } ) record["accepted_rows"] = len(accepted) - accepted_before source_records.append(record)
if selected_parent_ids: missing_selected_parent_ids = selected_parent_ids - observed_selected_parent_ids if missing_selected_parent_ids: raise SourceAlignedSFTError( f"{len(missing_selected_parent_ids)} selected parent IDs were absent" )
within_stage_shuffle_seed = int( getattr(args, "shuffle_within_stage_seed", -1) ) if within_stage_shuffle_seed >= 0: shuffled: list[ tuple[dict[str, Any], Path, dict[str, dict[str, Any]], str] ] = [] cursor = 0 for stage_index, record in enumerate(source_records): count = int(record["accepted_rows"]) stage = accepted[cursor : cursor + count] random.Random(within_stage_shuffle_seed + stage_index).shuffle(stage) shuffled.extend(stage) cursor += count if cursor != len(accepted): raise SourceAlignedSFTError("curriculum stage row accounting diverged") accepted = shuffled
assert expected_lineage is not None output.parent.mkdir(parents=True, exist_ok=True) scratch = Path(tempfile.mkdtemp(prefix=f".{output.name}.partial.", dir=output.parent)) try: output_inventory: dict[str, dict[str, Any]] = {} media_sources: dict[str, Path] = {} output_rows = [] by_source: collections.Counter[str] = collections.Counter() weights_before: collections.Counter[float] = collections.Counter() weights_after: collections.Counter[float] = collections.Counter() reweighted_rows = 0 source_stage = { item["root"]: index for index, item in enumerate(source_records) } source_row_index: collections.Counter[str] = collections.Counter() repeated_semantic_exposures = len(accepted) - len(seen_identity) stage_cursor = 0 curriculum_stages = [] for stage_index, record in enumerate(source_records): stage_rows = int(record["accepted_rows"]) curriculum_stages.append( { "end_row_exclusive": stage_cursor + stage_rows, "index": stage_index, "release_id": record["release_id"], "rows": stage_rows, "start_row": stage_cursor, } ) stage_cursor += stage_rows if stage_cursor != len(accepted): raise SourceAlignedSFTError("curriculum manifest row accounting diverged") for row, root, inventory, identity in accepted: messages = copy.deepcopy(row["messages"]) for message in messages: for item in message.get("content") or []: if item.get("type") != "image": continue source_relative = str(item["image"]) declaration = inventory[source_relative] digest = str(declaration["sha256"]) canonical_relative = _canonical_media_path(source_relative, digest) previous = output_inventory.get(canonical_relative) normalized = { "bytes": int(declaration["bytes"]), "path": canonical_relative, "sha256": digest, } if previous is not None and previous != normalized: raise SourceAlignedSFTError("canonical media declarations conflict") output_inventory.setdefault(canonical_relative, normalized) media_sources.setdefault(canonical_relative, root / source_relative) item["image"] = canonical_relative source_weight = float(row.get("sample_loss_weight", 1.0)) output_weight = ( min(source_weight, sample_loss_weight_cap) if sample_loss_weight_cap > 0 else source_weight ) weights_before[source_weight] += 1 weights_after[output_weight] += 1 reweighted_rows += int(output_weight != source_weight) stage_index = source_stage[str(root)] row_index = source_row_index[str(root)] source_row_index[str(root)] += 1 uid_parts: tuple[Any, ...] = (identity,) if ordered_curriculum or retain_semantic_exposures: uid_parts = (stage_index, row_index, identity) clean = attach_content_sha256( { "schema": "streameva.sft_row.v1", "uid": stable_id( "sourcealignedsft", *uid_parts, digest_length=24 ), "component": "preservation", "group_id": stable_id( "sourcealignedsftgroup", *uid_parts, digest_length=24 ), "split": "train", "messages": messages, "sample_loss_weight": output_weight, "parents": copy.deepcopy(row.get("parents") or []), } ) validate_row(clean) output_rows.append(clean) source_release = next( item["release_id"] for item in source_records if item["root"] == str(root) ) by_source[source_release] += 1
if not ordered_curriculum: output_rows.sort(key=lambda row: str(row["uid"])) if len({str(row["uid"]) for row in output_rows}) != len(output_rows): raise SourceAlignedSFTError("output UIDs collide") write_jsonl(output_rows, scratch / "trainer/sft.jsonl") inventory_rows = [output_inventory[path] for path in sorted(output_inventory)] write_jsonl(inventory_rows, scratch / "manifests/media_inventory.jsonl") for item in inventory_rows: relative = str(item["path"]) destination = scratch / relative _materialize(media_sources[relative], destination, mode=args.copy_mode) if ( destination.stat().st_size != int(item["bytes"]) or file_sha256(destination) != item["sha256"] ): raise SourceAlignedSFTError("materialized media hash diverged")
answers = collections.Counter(_target(row) for row in output_rows) frames = collections.Counter(str(len(_images(row))) for row in output_rows) manifest = { "artifacts": { "manifests/media_inventory.jsonl": file_sha256( scratch / "manifests/media_inventory.jsonl" ), "trainer/sft.jsonl": file_sha256(scratch / "trainer/sft.jsonl"), }, "contracts": { "agent_action_targets": 0, "assistant_targets_plain_semantic_only": True, "benchmark_examples_admitted": 0, "benchmark_firewall_inherited": True, "counterfactual_rows_admitted": 0, "environment_state_actor_targets": 0, "legacy_stage_metadata_admitted": 0, "loss_on_assistant_only": True, "policy_holdout_admitted": 0, "private_verifier_actor_targets": 0, "all_sample_loss_weights_one": set(weights_after) == {1.0}, "sample_loss_weight_cap": ( sample_loss_weight_cap if sample_loss_weight_cap > 0 else None ), "sample_loss_weight_rows_changed": reweighted_rows, "self_contained_media": True, "teacher_used_for_labels": any( bool(item["teacher_used_for_labels"]) for item in source_records ), "training_runs_required": 1, "ordered_curriculum": ordered_curriculum, "retain_semantic_exposures": retain_semantic_exposures, "repeated_semantic_exposures": repeated_semantic_exposures, "shuffle_within_stage_seed": ( within_stage_shuffle_seed if within_stage_shuffle_seed >= 0 else None ), }, "counts": { "media_bytes": sum(int(item["bytes"]) for item in inventory_rows), "media_files": len(inventory_rows), "trainer_rows": len(output_rows), }, "distributions": { "answer": dict(sorted(answers.items())), "frames_per_row": dict(sorted(frames.items())), "sample_loss_weight": { str(weight): count for weight, count in sorted(weights_after.items()) }, "source_release": dict(sorted(by_source.items())), }, "format": FORMAT, "inputs": { "benchmark_rows_or_labels_admitted": 0, "builder_sha256": file_sha256(Path(__file__).resolve(strict=True)), "deduplication": { "cited_source_parent": True, "exact_pixel_question_answer_identity": True, "retain_semantic_exposures": retain_semantic_exposures, "rejected": dict(sorted(rejected.items())), }, "excluded_parent_kinds": sorted(excluded_parent_kinds), "included_source_stage_release_ids": sorted( included_source_stage_release_ids ), "parent_selection": parent_selection_record, "final_release_must_restart_from": "Qwen/Qwen3-VL-8B-Instruct", "rows_relabelled": 0, "rows_reweighted": reweighted_rows, "sample_loss_weight_policy": { "cap": ( sample_loss_weight_cap if sample_loss_weight_cap > 0 else None ), "source_distribution": { str(weight): count for weight, count in sorted(weights_before.items()) }, "output_distribution": { str(weight): count for weight, count in sorted(weights_after.items()) }, }, "sources": source_records, "curriculum_stages": curriculum_stages, "trainer_row_order": ( "source_stage_then_source_row" if ordered_curriculum else "canonical_uid" ), }, "license": { "public_media_redistribution_claimed": False, "release_plan": "code_recipe_selection_and_source_checksums", "scope": "internal_noncommercial_research_only", }, "model_lineage": { "required_initialization": "Qwen/Qwen3-VL-8B-Instruct", "required_sha256s_sha256": expected_lineage[0], "upstream_repo": expected_lineage[1], "upstream_revision": expected_lineage[2], }, "public_release_allowed": False, "release_id": args.release_id, "status": "sealed_internal_training_release", "training_allowed": True, "training_scope": "pure_vlm_semantic_sft_only", } (scratch / "manifest.json").write_bytes(canonical_json_line(manifest)) validate_semantic_release(scratch, verify_media_hashes=True) os.replace(scratch, output) return manifest | {"output": str(output)} except BaseException: shutil.rmtree(scratch, ignore_errors=True) raise
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--source", type=Path, action="append", required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--release-id", required=True) parser.add_argument( "--copy-mode", choices=("copy", "hardlink", "auto"), default="hardlink" ) parser.add_argument( "--sample-loss-weight-cap", type=float, default=0.0, help="Cap inherited sample weights; zero preserves source weights.", ) parser.add_argument( "--exclude-parent-kind", action="append", default=[], help="Exclude rows carrying this exact parent kind; may be repeated.", ) parser.add_argument( "--include-source-stage-release-id", action="append", default=[], help=( "For a composite semantic source, admit only rows inside the " "named hash-bound curriculum stages; may be repeated." ), ) parser.add_argument( "--include-parent-selection", type=Path, help=( "Hash-bind a capability selection and admit only semantic rows " "whose cited parent ID is listed in it." ), ) parser.add_argument( "--ordered-curriculum", action="store_true", help="Preserve source-stage order and retain repeated stage exposures.", ) parser.add_argument( "--retain-semantic-exposures", action="store_true", help=( "Retain every source row as an intentional training exposure while " "keeping the normal globally canonicalized row order." ), ) parser.add_argument( "--legacy-v62di-source", type=Path, help="Pinned legacy release; admits only its 2,320 V62DI rows.", ) parser.add_argument( "--legacy-v62di-mode", choices=("v62di_only", "full"), default="v62di_only", help="Use only V62DI rows or the complete committed 3,594-row pool.", ) parser.add_argument( "--legacy-repcount-source", type=Path, help="Pinned 2,172-row legacy RepCount source, inserted after source 1.", ) parser.add_argument( "--shuffle-within-stage-seed", type=int, default=-1, help="Deterministically shuffle each stage while preserving stage order.", ) args = parser.parse_args() print(json.dumps(build(args), indent=2, sort_keys=True))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525#!/usr/bin/env python3"""Build a source-disjoint, pixel-grounded VST prefix-32 semantic pack.
The upstream VST metadata provides cumulative count states. A recent-onlywindow cannot in general support those labels, so this compiler exposes auniform causal prefix ending strictly before the query time. It emits onlyplain semantic answers (open integer and balanced MCQ); no agent action orprivate state is ever an actor target."""
from __future__ import annotations
import argparseimport collectionsimport concurrent.futuresimport hashlibimport ioimport jsonimport mathimport osimport shutilimport tempfilefrom collections.abc import Mapping, Sequencefrom pathlib import Pathfrom typing import Any
from PIL import Image
from data_pipeline.temporal_scope.semantic_mcq import ( DIRECT_PROMPT_PREFIX, DIRECT_PROMPT_SUFFIX, rebalance_answer_slot,)from viss_core.data_v0.canonical import ( attach_content_sha256, canonical_json_line, file_sha256, stable_id, write_jsonl,)from viss_core.data_v0.schema import validate_row
FORMAT = "streameva.vst_prefix32_semantic.v1"PREFLIGHT_FORMAT = "streameva.vst_count_metadata_preflight.v1"OPTION_LETTERS = "ABCD"TARGET_COUNTS = tuple(range(11))PREFIX_FRAME_MAX_PIXELS = 128 * 28 * 28PREFIX_FRAME_MAX_SIDE = 504
class VSTPrefixSemanticError(ValueError): """Raised when a prefix-32 semantic candidate violates its contract."""
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--selection", type=Path, required=True) parser.add_argument("--preflight", type=Path, required=True) parser.add_argument("--media-root", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--frames", type=int, default=32) parser.add_argument("--train-per-count", type=int, default=92) parser.add_argument("--holdout-per-count", type=int, default=5) parser.add_argument("--workers", type=int, default=16) parser.add_argument("--seed", type=int, default=173) args = parser.parse_args() print(json.dumps(materialize(args), indent=2, sort_keys=True))
def select_available_states( rows: Sequence[Mapping[str, Any]], *, media_root: Path, train_per_count: int, holdout_per_count: int, seed: int,) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: """Select balanced, source-disjoint train and holdout states."""
if train_per_count <= 0 or holdout_per_count <= 0: raise VSTPrefixSemanticError("train/holdout quotas must be positive") by_count: dict[int, list[dict[str, Any]]] = { value: [] for value in TARGET_COUNTS } seen_videos: set[str] = set() seen_ids: set[str] = set() for raw in rows: row = dict(raw) answer = int(row.get("answer", -1)) relative = Path(str(row.get("source_video_relative") or "")) candidate_id = str(row.get("candidate_id") or "") if ( answer not in by_count or not candidate_id or relative.is_absolute() or ".." in relative.parts or relative.suffix.casefold() != ".mp4" ): raise VSTPrefixSemanticError("selection row is malformed") if candidate_id in seen_ids or relative.as_posix() in seen_videos: raise VSTPrefixSemanticError("selection IDs/videos must be unique") seen_ids.add(candidate_id) seen_videos.add(relative.as_posix()) source = (media_root / relative).resolve() if not source.is_file() or source.is_symlink(): continue row["source_video"] = str(source) by_count[answer].append(row)
train: list[dict[str, Any]] = [] holdout: list[dict[str, Any]] = [] required = train_per_count + holdout_per_count for answer in TARGET_COUNTS: values = by_count[answer] values.sort( key=lambda row: hashlib.sha256( f"{seed}|{answer}|{row['candidate_id']}".encode() ).digest() ) if len(values) < required: raise VSTPrefixSemanticError( f"count {answer} has {len(values)} available videos; need {required}" ) for row in values[:holdout_per_count]: value = dict(row) value["split"] = "policy_holdout" holdout.append(value) for row in values[holdout_per_count:required]: value = dict(row) value["split"] = "train" train.append(value) return ( sorted(train, key=lambda row: str(row["candidate_id"])), sorted(holdout, key=lambda row: str(row["candidate_id"])), )
def uniform_causal_indices( *, source_total: int, source_fps: float, query_time: float, frames: int) -> tuple[list[int], list[float]]: """Return exactly ``frames`` uniform indices whose timestamps are causal."""
if ( source_total <= 0 or not math.isfinite(source_fps) or source_fps <= 0 or not math.isfinite(query_time) or query_time <= 0 or frames <= 1 ): raise VSTPrefixSemanticError("invalid video sampling metadata") # ceil(t * fps) - 1 is strictly earlier than t, including exact boundaries. last = min(source_total - 1, max(0, math.ceil(query_time * source_fps) - 1)) if last == 0: indices = [0] * frames else: indices = [ int(round(position * last / (frames - 1))) for position in range(frames) ] timestamps = [index / source_fps for index in indices] if any(timestamp >= query_time + 1e-9 for timestamp in timestamps): raise VSTPrefixSemanticError("prefix sampler exposed a future frame") return indices, timestamps
def project_semantic_rows( row: Mapping[str, Any], *, relative_paths: Sequence[str], frame_timestamps: Sequence[float], source_sha256: str, selection_sha256: str,) -> list[dict[str, Any]]: """Project one grounded count state into open and balanced-MCQ rows."""
if len(relative_paths) != 32 or len(frame_timestamps) != 32: raise VSTPrefixSemanticError("prefix projection requires exactly 32 frames") answer = int(row["answer"]) if answer not in TARGET_COUNTS: raise VSTPrefixSemanticError("count answer is outside 0--10") candidate_id = str(row["candidate_id"]) split = str(row["split"]) if split not in {"train", "policy_holdout"}: raise VSTPrefixSemanticError("invalid semantic split") images = [ { "type": "image", "image": path, "frame_id": stable_id( "vstprefixframe", candidate_id, index, timestamp, digest_length=20 ), } for index, (path, timestamp) in enumerate( zip(relative_paths, frame_timestamps, strict=True) ) ] parent = { "kind": "vst_count_metadata_state", "id": stable_id("vstprefixsource", candidate_id, digest_length=20), "sha256": selection_sha256, } group_id = stable_id("vstprefixgroup", candidate_id, digest_length=20) question = " ".join(str(row["question"]).split()) answer_text = str(answer) open_row = attach_content_sha256( { "schema": "streameva.sft_row.v1", "uid": stable_id("sftvstprefixopen", candidate_id, digest_length=20), "component": "preservation", "group_id": group_id, "split": split, "decision_loss_profile": "full", "messages": [ { "role": "user", "content": [ *images, { "type": "text", "text": ( f"{question}\nAnswer with one integer from 0 to 10 " "and no other text." ), }, ], "loss": False, }, { "role": "assistant", "content": [{"type": "text", "text": answer_text}], "loss": True, }, ], "sample_loss_weight": 1.0, "parents": [parent], } )
distractors = [value for value in TARGET_COUNTS if value != answer] distractors.sort( key=lambda value: ( abs(value - answer), hashlib.sha256(f"{candidate_id}|{value}".encode()).digest(), ) ) options, mcq_answer = rebalance_answer_slot( [answer_text, *[str(value) for value in distractors[:3]]], answer="A", answer_slot=int(hashlib.sha256(candidate_id.encode()).hexdigest(), 16) % 4, seed=f"{candidate_id}|prefix32-mcq-v1", ) option_text = "\n".join( f"{letter}. {value}" for letter, value in zip(OPTION_LETTERS, options, strict=True) ) mcq_prompt = ( f"{DIRECT_PROMPT_PREFIX}\n\nQuestion: {question}\n\n" f"Options:\n{option_text}\n\n{DIRECT_PROMPT_SUFFIX}" ) mcq_row = attach_content_sha256( { "schema": "streameva.sft_row.v1", "uid": stable_id("sftvstprefixmcq", candidate_id, digest_length=20), "component": "preservation", "group_id": group_id, "split": split, "decision_loss_profile": "full", "messages": [ { "role": "user", "content": [*images, {"type": "text", "text": mcq_prompt}], "loss": False, }, { "role": "assistant", "content": [{"type": "text", "text": mcq_answer}], "loss": True, }, ], "sample_loss_weight": 1.0, "parents": [parent], } ) for output in (open_row, mcq_row): validate_row(output) # Bind source pixels in the manifest-facing auxiliary state without leaking # an absolute path into the strict trainer row. del source_sha256 return [open_row, mcq_row]
def materialize(args: argparse.Namespace) -> dict[str, Any]: selection = args.selection.resolve() preflight_path = args.preflight.resolve() media_root = args.media_root.resolve() output = args.output.resolve() if output.exists(): raise FileExistsError(output) if args.frames != 32: raise VSTPrefixSemanticError("this release is frozen to exactly 32 frames") if not 1 <= args.workers <= 32: raise VSTPrefixSemanticError("workers must lie in [1, 32]") preflight = json.loads(preflight_path.read_text(encoding="utf-8")) declaration = preflight.get("selection_artifact", {}) if ( preflight.get("format") != PREFLIGHT_FORMAT or preflight.get("status") != "pass_metadata_firewall_and_selection" or preflight.get("contracts", {}).get("basename_hits_admitted") != 0 or preflight.get("contracts", {}).get("question_hits_admitted") != 0 or declaration.get("sha256") != file_sha256(selection) ): raise VSTPrefixSemanticError("metadata preflight is not valid or hash-bound") rows = [ json.loads(line) for line in selection.read_text(encoding="utf-8").splitlines() if line.strip() ] train, holdout = select_available_states( rows, media_root=media_root, train_per_count=args.train_per_count, holdout_per_count=args.holdout_per_count, seed=args.seed, ) selected = [*train, *holdout] output.parent.mkdir(parents=True, exist_ok=True) scratch = Path(tempfile.mkdtemp(prefix=f".{output.name}.partial.", dir=output.parent)) try: media_out = scratch / "media"
def decode(row: Mapping[str, Any]) -> tuple[str, dict[str, Any]]: return str(row["candidate_id"]), _decode_prefix(row, media_out, args.frames)
decoded: dict[str, dict[str, Any]] = {} errors: list[dict[str, str]] = [] with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) as pool: futures = {pool.submit(decode, row): row for row in selected} for future in concurrent.futures.as_completed(futures): row = futures[future] try: candidate_id, state = future.result() decoded[candidate_id] = state except Exception as exc: # pragma: no cover - remote media failures errors.append( { "candidate_id": str(row["candidate_id"]), "reason": f"{type(exc).__name__}: {exc}", } ) write_jsonl(errors, scratch / "decode_errors.jsonl") if errors or len(decoded) != len(selected): raise VSTPrefixSemanticError(f"prefix decode failed for {len(errors)} rows")
train_rows: list[dict[str, Any]] = [] holdout_rows: list[dict[str, Any]] = [] source_inventory = [] selection_sha = file_sha256(selection) for row in selected: state = decoded[str(row["candidate_id"])] source_sha = file_sha256(str(row["source_video"])) source_inventory.append( { "candidate_id": row["candidate_id"], "source_video_relative": row["source_video_relative"], "source_sha256": source_sha, "split": row["split"], "query_time": row["query_time"], "answer": row["answer"], "frame_indices": state["frame_indices"], "frame_timestamps": state["frame_timestamps"], } ) projected = project_semantic_rows( row, relative_paths=state["relative_paths"], frame_timestamps=state["frame_timestamps"], source_sha256=source_sha, selection_sha256=selection_sha, ) (train_rows if row["split"] == "train" else holdout_rows).extend(projected) write_jsonl(train_rows, scratch / "trainer/sft.jsonl", sort_key="uid") write_jsonl( holdout_rows, scratch / "holdout/policy_holdout.jsonl", sort_key="uid" ) write_jsonl( source_inventory, scratch / "source_inventory.jsonl", sort_key="candidate_id", ) media_files = sorted(path for path in media_out.rglob("*.jpg") if path.is_file()) manifest = { "format": FORMAT, "status": "materialized_internal_research_candidate", "training_allowed": True, "public_release_allowed": False, "protocol": { "causal_prefix_only": True, "frames": 32, "per_frame_max_pixels": PREFIX_FRAME_MAX_PIXELS, "sampling": "exact_uniform_indices_over_[0,query_time)", "visual_input_mode": "independent_image_frames", }, "counts": { "train_source_states": len(train), "holdout_source_states": len(holdout), "train_rows": len(train_rows), "holdout_rows": len(holdout_rows), "media_files": len(media_files), "train_by_answer": dict( sorted(collections.Counter(str(row["answer"]) for row in train).items()) ), "holdout_by_answer": dict( sorted( collections.Counter(str(row["answer"]) for row in holdout).items() ) ), }, "inputs": { "selection_sha256": selection_sha, "preflight_sha256": file_sha256(preflight_path), "builder_sha256": file_sha256(Path(__file__)), }, "artifacts": { "trainer/sft.jsonl": file_sha256(scratch / "trainer/sft.jsonl"), "holdout/policy_holdout.jsonl": file_sha256( scratch / "holdout/policy_holdout.jsonl" ), "source_inventory.jsonl": file_sha256( scratch / "source_inventory.jsonl" ), "decode_errors.jsonl": file_sha256(scratch / "decode_errors.jsonl"), }, "contracts": { "all_labels_metadata_derived": True, "all_pixels_strictly_before_query": True, "benchmark_firewall_inherited": True, "holdout_source_disjoint": True, "no_agent_actions": True, "no_private_state_actor_targets": True, "source_videos_globally_unique": True, "teacher_used_for_labels": False, }, "license": { "public_media_redistribution_claimed": False, "release_mode": "recipe_plus_source_checksums", }, } (scratch / "manifest.json").write_bytes(canonical_json_line(manifest)) os.replace(scratch, output) return {**manifest, "output": str(output)} except Exception: shutil.rmtree(scratch, ignore_errors=True) raise
def _decode_prefix( row: Mapping[str, Any], media_root: Path, frames: int) -> dict[str, Any]: from decord import VideoReader
source = Path(str(row["source_video"])) reader = VideoReader(str(source)) try: fps = float(reader.get_avg_fps()) total = len(reader) indices, timestamps = uniform_causal_indices( source_total=total, source_fps=fps, query_time=float(row["query_time"]), frames=frames, ) arrays = reader.get_batch(indices).asnumpy() finally: del reader relative_paths = [] for array in arrays: image = Image.fromarray(array) height, width = image.height, image.width resized_height, resized_width = _rounded_size(height, width) if (resized_height, resized_width) != (height, width): image = image.resize((resized_width, resized_height), Image.Resampling.LANCZOS) buffer = io.BytesIO() image.save(buffer, format="JPEG", quality=95, subsampling=0, optimize=False) payload = buffer.getvalue() digest = hashlib.sha256(payload).hexdigest() relative = Path("media") / digest[:2] / f"{digest}.jpg" destination = media_root.parent / relative destination.parent.mkdir(parents=True, exist_ok=True) try: with destination.open("xb") as handle: handle.write(payload) except FileExistsError: pass if file_sha256(destination) != digest: raise VSTPrefixSemanticError("decoded frame hash mismatch") relative_paths.append(relative.as_posix()) return { "relative_paths": relative_paths, "frame_indices": indices, "frame_timestamps": timestamps, }
def _rounded_size(height: int, width: int) -> tuple[int, int]: factor = 28 max_pixels = PREFIX_FRAME_MAX_PIXELS max_side = PREFIX_FRAME_MAX_SIDE scale = min(1.0, max_side / max(height, width)) if height * width * scale * scale > max_pixels: scale = min(scale, math.sqrt(max_pixels / (height * width))) new_height = max(factor, int(round(height * scale / factor)) * factor) new_width = max(factor, int(round(width * scale / factor)) * factor) while new_height * new_width > max_pixels: if new_height >= new_width and new_height > factor: new_height -= factor elif new_width > factor: new_width -= factor else: break return new_height, new_width
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329#!/usr/bin/env python3"""Seal the high-confidence agreement subset of a blind-audited SFT release.
The visual auditor never receives the source answer. This builder also neveruses the auditor prediction as a new label: it only admits an existing sourcerow when a complete, hash-bound audit independently recovered that row'sanswer. Partial audits are deliberately ineligible for materialization."""
from __future__ import annotations
import argparseimport collectionsimport hashlibimport jsonimport osimport shutilimport tempfilefrom pathlib import Pathfrom typing import Any
from viss_core.data_v0.canonical import ( canonical_json_line, file_sha256, read_jsonl, write_jsonl,)from viss_core.data_v0.semantic_release import ( FORMAT, validate_semantic_release,)
AUDIT_ROW_FORMAT = "streameva.semantic_release.blind_visual_audit_row.v0"AUDIT_SUMMARY_FORMAT = "streameva.semantic_release.blind_visual_audit.v0"FILTER_FORMAT = "streameva.semantic_release.blind_visual_filter.v0"
class BlindAuditFilterError(ValueError): """Raised when an audit is incomplete or not independent of its labels."""
def _target(row: dict[str, Any]) -> str: values = [ str(item.get("text") or "") for message in row.get("messages") or [] if message.get("role") == "assistant" and message.get("loss") is True for item in message.get("content") or [] if item.get("type") == "text" ] if len(values) != 1: raise BlindAuditFilterError("semantic row has no unique target") return values[0]
def _images(rows: list[dict[str, Any]]) -> set[str]: return { str(item["image"]) for row in rows for message in row["messages"] for item in message["content"] if item.get("type") == "image" }
def _answer_balanced_subset( rows: list[dict[str, Any]], *, count: int, seed: str) -> list[dict[str, Any]]: if count <= 0 or count > len(rows): raise BlindAuditFilterError("subset row count exceeds audited agreements") by_answer: dict[str, list[dict[str, Any]]] = collections.defaultdict(list) for row in rows: by_answer[_target(row)].append(row) if set(by_answer) != set("ABCD"): raise BlindAuditFilterError("answer-balanced subset requires A/B/C/D rows") base, remainder = divmod(count, 4) selected: list[dict[str, Any]] = [] for index, answer in enumerate("ABCD"): quota = base + int(index < remainder) ranked = sorted( by_answer[answer], key=lambda row: hashlib.sha256( f"blind-filter-subset:{seed}:{row['uid']}".encode() ).hexdigest(), ) if len(ranked) < quota: raise BlindAuditFilterError( f"answer {answer} has {len(ranked)} rows but needs {quota}" ) selected.extend(ranked[:quota]) return sorted(selected, key=lambda row: str(row["uid"]))
def _materialize(source: Path, destination: Path, *, mode: str) -> None: destination.parent.mkdir(parents=True, exist_ok=True) if source.is_symlink() or not source.is_file(): raise BlindAuditFilterError(f"unsafe source media: {source}") if mode in {"hardlink", "auto"}: try: os.link(source, destination) return except OSError: if mode == "hardlink": raise shutil.copy2(source, destination)
def build(args: argparse.Namespace) -> dict[str, Any]: source = args.source.resolve(strict=True) audit_path = args.audit.resolve(strict=True) summary_path = args.audit_summary.resolve(strict=True) output = args.output.resolve() if output.exists(): raise FileExistsError(output) if args.copy_mode not in {"copy", "hardlink", "auto"}: raise BlindAuditFilterError("unsupported copy mode") allowed_confidence = set(args.confidence) if not allowed_confidence or not allowed_confidence <= {"high", "medium"}: raise BlindAuditFilterError("confidence must be high and/or medium") if not 0.0 <= args.min_source_accuracy <= 1.0: raise BlindAuditFilterError("minimum source accuracy must lie in [0, 1]") if args.min_rows <= 0: raise BlindAuditFilterError("minimum retained rows must be positive")
source_manifest = validate_semantic_release(source, verify_media_hashes=False) source_trainer = source / "trainer/sft.jsonl" source_rows = read_jsonl( source_trainer, verify_content_hashes=True, require_canonical=True ) rows_by_uid = {str(row["uid"]): row for row in source_rows} if len(rows_by_uid) != len(source_rows): raise BlindAuditFilterError("source UIDs are not unique")
summary = json.loads(summary_path.read_text(encoding="utf-8")) required_summary = { "format": AUDIT_SUMMARY_FORMAT, "status": "admit_semantic_release", "admitted": True, "release_id": source_manifest["release_id"], "release_manifest_sha256": file_sha256(source / "manifest.json"), "trainer_sha256": file_sha256(source_trainer), "sample_rows": len(source_rows), "valid_rows": len(source_rows), "errors": 0, "expected_answers_sent_to_auditor": False, "auditor_outputs_admitted_to_training": False, "benchmark_rows_used": 0, "result_rows_sha256": file_sha256(audit_path), } if any(summary.get(key) != value for key, value in required_summary.items()): raise BlindAuditFilterError("audit summary is partial, rejected, or unbound") accuracy = float(summary.get("accuracy", -1.0)) if accuracy < args.min_source_accuracy: raise BlindAuditFilterError( f"blind source agreement {accuracy:.4f} is below " f"{args.min_source_accuracy:.4f}" )
audit_rows = read_jsonl(audit_path, require_canonical=True) audit_by_uid: dict[str, dict[str, Any]] = {} for item in audit_rows: uid = str(item.get("uid") or "") if ( item.get("format") != AUDIT_ROW_FORMAT or not uid or uid in audit_by_uid or uid not in rows_by_uid ): raise BlindAuditFilterError("audit row identity diverged") expected = _target(rows_by_uid[uid]) prediction = item.get("prediction") if ( item.get("expected") != expected or item.get("error") is not None or item.get("confidence") not in {"high", "medium", "low"} or item.get("correct") is not (prediction == expected) ): raise BlindAuditFilterError("audit decision is malformed") audit_by_uid[uid] = item if set(audit_by_uid) != set(rows_by_uid): raise BlindAuditFilterError("blind audit does not cover every source row")
selected = [ row for uid, row in rows_by_uid.items() if audit_by_uid[uid]["correct"] is True and audit_by_uid[uid]["confidence"] in allowed_confidence ] selected.sort(key=lambda row: str(row["uid"])) eligible_rows = len(selected) max_rows = getattr(args, "max_rows", None) selection_seed = str(getattr(args, "selection_seed", "blind-filter-subset-v0")) if max_rows is not None: selected = _answer_balanced_subset( selected, count=int(max_rows), seed=selection_seed ) if len(selected) < args.min_rows: raise BlindAuditFilterError( f"only {len(selected)} high-confidence rows survived; " f"requires {args.min_rows}" )
source_inventory_path = source / "manifests/media_inventory.jsonl" source_inventory = { str(item["path"]): item for item in read_jsonl(source_inventory_path, require_canonical=True) } referenced = _images(selected) if not referenced <= set(source_inventory): raise BlindAuditFilterError("selected media is absent from source inventory")
output.parent.mkdir(parents=True, exist_ok=True) scratch = Path(tempfile.mkdtemp(prefix=f".{output.name}.partial.", dir=output.parent)) try: write_jsonl(selected, scratch / "trainer/sft.jsonl") selected_inventory = [source_inventory[path] for path in sorted(referenced)] write_jsonl(selected_inventory, scratch / "manifests/media_inventory.jsonl") for item in selected_inventory: relative = Path(str(item["path"])) source_file = source / relative destination = scratch / relative _materialize(source_file, destination, mode=args.copy_mode) if ( destination.stat().st_size != int(item["bytes"]) or file_sha256(destination) != item["sha256"] ): raise BlindAuditFilterError("materialized media hash diverged")
answers = collections.Counter(_target(row) for row in selected) frames = collections.Counter( sum( item.get("type") == "image" for message in row["messages"] for item in message["content"] ) for row in selected ) confidence = collections.Counter( str(audit_by_uid[str(row["uid"])]["confidence"]) for row in selected ) manifest = { "artifacts": { "manifests/media_inventory.jsonl": file_sha256( scratch / "manifests/media_inventory.jsonl" ), "trainer/sft.jsonl": file_sha256(scratch / "trainer/sft.jsonl"), }, "contracts": source_manifest["contracts"], "counts": { "media_bytes": sum(int(item["bytes"]) for item in selected_inventory), "media_files": len(selected_inventory), "trainer_rows": len(selected), }, "distributions": { "answer": dict(sorted(answers.items())), "blind_auditor_confidence": dict(sorted(confidence.items())), "frames_per_row": { str(key): value for key, value in sorted(frames.items()) }, }, "format": FORMAT, "inputs": { **source_manifest["inputs"], "blind_visual_filter": { "format": FILTER_FORMAT, "source_release_id": source_manifest["release_id"], "source_manifest_sha256": file_sha256(source / "manifest.json"), "source_trainer_sha256": file_sha256(source_trainer), "audit_sha256": file_sha256(audit_path), "audit_summary_sha256": file_sha256(summary_path), "auditor_model": str(summary.get("auditor_model") or ""), "auditor_received_expected_answers": False, "auditor_predictions_used_as_labels": False, "complete_source_coverage_required": True, "eligible_rows_after_audit_filter": eligible_rows, "filter_builder_sha256": file_sha256(Path(__file__).resolve(strict=True)), "max_rows": max_rows, "source_agreement_accuracy": accuracy, "subset_selection_seed": selection_seed if max_rows is not None else None, "subset_selection_strategy": ( "answer_balanced_stable_hash" if max_rows is not None else "all" ), "allowed_confidence": sorted(allowed_confidence), "source_rows": len(source_rows), "selected_rows": len(selected), }, }, "license": source_manifest["license"], "model_lineage": source_manifest["model_lineage"], "public_release_allowed": False, "release_id": args.release_id, "status": "sealed_internal_training_release", "training_allowed": True, "training_scope": "pure_vlm_semantic_sft_only", } (scratch / "manifest.json").write_bytes(canonical_json_line(manifest)) validate_semantic_release(scratch, verify_media_hashes=True) os.replace(scratch, output) return manifest except Exception: shutil.rmtree(scratch, ignore_errors=True) raise
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--source", type=Path, required=True) parser.add_argument("--audit", type=Path, required=True) parser.add_argument("--audit-summary", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--release-id", required=True) parser.add_argument( "--confidence", action="append", choices=("high", "medium"), default=[] ) parser.add_argument("--min-source-accuracy", type=float, default=0.90) parser.add_argument("--min-rows", type=int, default=1) parser.add_argument("--max-rows", type=int) parser.add_argument("--selection-seed", default="blind-filter-subset-v0") parser.add_argument( "--copy-mode", choices=("copy", "hardlink", "auto"), default="hardlink" ) args = parser.parse_args() if not args.confidence: args.confidence = ["high"] print(json.dumps(build(args), indent=2, sort_keys=True))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298#!/usr/bin/env python3"""Seal source-labelled rows that survive an option-invariant visual audit.
The two-presentation auditor never receives the source answer. This builderalso never treats an auditor prediction as a replacement label: a source rowis eligible only when both option orders independently recover the unchangedsource answer with an allowed confidence level."""
from __future__ import annotations
import argparseimport collectionsimport jsonimport osimport shutilimport tempfilefrom pathlib import Pathfrom typing import Any
from data_pipeline.temporal_scope.filter_semantic_release_by_blind_audit import ( BlindAuditFilterError, _answer_balanced_subset, _images, _materialize, _target,)from viss_core.data_v0.canonical import ( canonical_json_line, file_sha256, read_jsonl, write_jsonl,)from viss_core.data_v0.semantic_release import FORMAT, validate_semantic_release
AUDIT_ROW_FORMAT = "streameva.semantic_release.option_consensus_audit_row.v0"AUDIT_SUMMARY_FORMAT = "streameva.semantic_release.option_consensus_audit.v0"FILTER_FORMAT = "streameva.semantic_release.option_consensus_filter.v0"
def _validate_presentations( *, source_rows: list[dict[str, Any]], audit_rows: list[dict[str, Any]], allowed_confidence: set[str],) -> tuple[list[dict[str, Any]], int]: rows_by_uid = {str(row["uid"]): row for row in source_rows} if len(rows_by_uid) != len(source_rows): raise BlindAuditFilterError("source UIDs are not unique") presentations: dict[str, dict[int, dict[str, Any]]] = collections.defaultdict(dict) for item in audit_rows: uid = str(item.get("uid") or "") presentation = item.get("presentation") if ( item.get("format") != AUDIT_ROW_FORMAT or uid not in rows_by_uid or presentation not in {0, 1} or presentation in presentations[uid] ): raise BlindAuditFilterError("option-consensus audit identity diverged") expected = _target(rows_by_uid[uid]) prediction = item.get("prediction_source") mapping = item.get("displayed_to_source") if ( item.get("expected_source") != expected or item.get("error") is not None or item.get("confidence") not in {"high", "medium", "low"} or item.get("correct_source") is not (prediction == expected) or not isinstance(mapping, list) or sorted(mapping) != list("ABCD") or (presentation == 0 and mapping != list("ABCD")) or (presentation == 1 and mapping == list("ABCD")) ): raise BlindAuditFilterError("option-consensus audit decision is malformed") presentations[uid][int(presentation)] = item if set(presentations) != set(rows_by_uid) or any( set(values) != {0, 1} for values in presentations.values() ): raise BlindAuditFilterError("option-consensus audit lacks complete two-order coverage")
stable_rows = 0 selected: list[dict[str, Any]] = [] for uid, source_row in rows_by_uid.items(): pair = [presentations[uid][0], presentations[uid][1]] predictions = {str(item["prediction_source"]) for item in pair} if ( len(predictions) == 1 and all(str(item["confidence"]) in allowed_confidence for item in pair) ): stable_rows += 1 if next(iter(predictions)) == _target(source_row): selected.append(source_row) selected.sort(key=lambda row: str(row["uid"])) return selected, stable_rows
def build(args: argparse.Namespace) -> dict[str, Any]: source = args.source.resolve(strict=True) audit_path = args.audit.resolve(strict=True) summary_path = args.audit_summary.resolve(strict=True) output = args.output.resolve() if output.exists(): raise FileExistsError(output) if args.copy_mode not in {"copy", "hardlink", "auto"}: raise BlindAuditFilterError("unsupported copy mode") allowed_confidence = set(args.confidence) if not allowed_confidence or not allowed_confidence <= {"high", "medium"}: raise BlindAuditFilterError("confidence must be high and/or medium") if not 0.0 <= args.min_consensus_source_accuracy <= 1.0: raise BlindAuditFilterError("minimum consensus accuracy must lie in [0, 1]") if args.min_rows <= 0: raise BlindAuditFilterError("minimum retained rows must be positive")
source_manifest = validate_semantic_release(source, verify_media_hashes=False) source_trainer = source / "trainer/sft.jsonl" source_rows = read_jsonl( source_trainer, verify_content_hashes=True, require_canonical=True ) summary = json.loads(summary_path.read_text(encoding="utf-8")) required_summary = { "format": AUDIT_SUMMARY_FORMAT, "status": "complete_option_consensus_audit", "release_id": source_manifest["release_id"], "release_manifest_sha256": file_sha256(source / "manifest.json"), "trainer_sha256": file_sha256(source_trainer), "sample_rows": len(source_rows), "presentations": 2 * len(source_rows), "errors": 0, "expected_answers_sent_to_auditor": False, "auditor_outputs_admitted_to_training": False, "benchmark_rows_used": 0, "result_rows_sha256": file_sha256(audit_path), } if any(summary.get(key) != value for key, value in required_summary.items()): raise BlindAuditFilterError("consensus audit is partial, unsafe, or unbound") request_contract = summary.get("request_contract") or {} if ( request_contract.get("presentations_per_row") != 2 or request_contract.get("second_option_order_non_identity") is not True or request_contract.get("temperature") != 0 ): raise BlindAuditFilterError("consensus request contract diverged")
audit_rows = read_jsonl(audit_path, require_canonical=True) selected, stable_rows = _validate_presentations( source_rows=source_rows, audit_rows=audit_rows, allowed_confidence=allowed_confidence, ) summary_stable = int(summary.get("high_confidence_option_consensus_rows", -1)) if allowed_confidence == {"high"} and stable_rows != summary_stable: raise BlindAuditFilterError("auditor summary stable-row count diverged") source_agreements = len(selected) consensus_accuracy = source_agreements / stable_rows if stable_rows else 0.0 if consensus_accuracy < args.min_consensus_source_accuracy: raise BlindAuditFilterError( f"stable consensus source agreement {consensus_accuracy:.4f} is below " f"{args.min_consensus_source_accuracy:.4f}" ) eligible_rows = len(selected) if args.max_rows is not None: selected = _answer_balanced_subset( selected, count=int(args.max_rows), seed=args.selection_seed ) if len(selected) < args.min_rows: raise BlindAuditFilterError( f"only {len(selected)} option-invariant source agreements survived; " f"requires {args.min_rows}" )
source_inventory_path = source / "manifests/media_inventory.jsonl" source_inventory = { str(item["path"]): item for item in read_jsonl(source_inventory_path, require_canonical=True) } referenced = _images(selected) if not referenced <= set(source_inventory): raise BlindAuditFilterError("selected media is absent from source inventory")
output.parent.mkdir(parents=True, exist_ok=True) scratch = Path(tempfile.mkdtemp(prefix=f".{output.name}.partial.", dir=output.parent)) try: write_jsonl(selected, scratch / "trainer/sft.jsonl") selected_inventory = [source_inventory[path] for path in sorted(referenced)] write_jsonl(selected_inventory, scratch / "manifests/media_inventory.jsonl") for item in selected_inventory: relative = Path(str(item["path"])) destination = scratch / relative _materialize(source / relative, destination, mode=args.copy_mode) if ( destination.stat().st_size != int(item["bytes"]) or file_sha256(destination) != item["sha256"] ): raise BlindAuditFilterError("materialized media hash diverged")
answers = collections.Counter(_target(row) for row in selected) frames = collections.Counter( sum( item.get("type") == "image" for message in row["messages"] for item in message["content"] ) for row in selected ) manifest = { "artifacts": { "manifests/media_inventory.jsonl": file_sha256( scratch / "manifests/media_inventory.jsonl" ), "trainer/sft.jsonl": file_sha256(scratch / "trainer/sft.jsonl"), }, "contracts": source_manifest["contracts"], "counts": { "media_bytes": sum(int(item["bytes"]) for item in selected_inventory), "media_files": len(selected_inventory), "trainer_rows": len(selected), }, "distributions": { "answer": dict(sorted(answers.items())), "frames_per_row": { str(key): value for key, value in sorted(frames.items()) }, }, "format": FORMAT, "inputs": { **source_manifest["inputs"], "option_consensus_filter": { "format": FILTER_FORMAT, "source_release_id": source_manifest["release_id"], "source_manifest_sha256": file_sha256(source / "manifest.json"), "source_trainer_sha256": file_sha256(source_trainer), "audit_sha256": file_sha256(audit_path), "audit_summary_sha256": file_sha256(summary_path), "auditor_model": str(summary.get("auditor_model") or ""), "auditor_received_expected_answers": False, "auditor_predictions_used_as_labels": False, "presentations_per_row": 2, "option_invariance_required": True, "source_agreement_required": True, "stable_consensus_rows": stable_rows, "stable_consensus_source_agreements": source_agreements, "stable_consensus_source_accuracy": consensus_accuracy, "eligible_rows_after_filter": eligible_rows, "allowed_confidence": sorted(allowed_confidence), "max_rows": args.max_rows, "subset_selection_seed": ( args.selection_seed if args.max_rows is not None else None ), "filter_builder_sha256": file_sha256(Path(__file__).resolve(strict=True)), "shared_filter_helpers_sha256": file_sha256( Path(__file__) .with_name("filter_semantic_release_by_blind_audit.py") .resolve(strict=True) ), }, }, "license": source_manifest["license"], "model_lineage": source_manifest["model_lineage"], "public_release_allowed": False, "release_id": args.release_id, "status": "sealed_internal_training_release", "training_allowed": True, "training_scope": "pure_vlm_semantic_sft_only", } (scratch / "manifest.json").write_bytes(canonical_json_line(manifest)) validate_semantic_release(scratch, verify_media_hashes=True) os.replace(scratch, output) return manifest except Exception: shutil.rmtree(scratch, ignore_errors=True) raise
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--source", type=Path, required=True) parser.add_argument("--audit", type=Path, required=True) parser.add_argument("--audit-summary", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--release-id", required=True) parser.add_argument( "--confidence", action="append", choices=("high", "medium"), default=[] ) parser.add_argument("--min-consensus-source-accuracy", type=float, default=0.80) parser.add_argument("--min-rows", type=int, default=1) parser.add_argument("--max-rows", type=int) parser.add_argument("--selection-seed", default="option-consensus-filter-v0") parser.add_argument( "--copy-mode", choices=("copy", "hardlink", "auto"), default="hardlink" ) args = parser.parse_args() manifest = build(args) print(json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420#!/usr/bin/env python3"""Freeze a source-disjoint holdout and a quality-ranked capability selection.
This selector never reads benchmark rows, labels, predictions, task IDs, orquestion templates. It joins an already sealed non-benchmark teacher releaseback to its generation evidence, removes nominal capability rows whose answerwas available too early, and reserves a policy holdout before selecting SFTrows. A final training selection additionally requires a complete studentscreen over the structural candidate set."""
from __future__ import annotations
import argparseimport collectionsimport hashlibimport jsonfrom pathlib import Pathfrom typing import Any, Iterable
from viss_core.data_v0.canonical import ( canonical_json_line, file_sha256, read_jsonl, stable_id,)from viss_core.data_v0.semantic_release import validate_semantic_release
SELECTION_FORMAT = "iclr_video.quality_capability_selection.v1"HOLDOUT_FORMAT = "iclr_video.nonbenchmark_policy_holdout.v1"STUDENT_SCREEN_FORMAT = "iclr_video.nonbenchmark_student_screen.v1"PROFILE_KIND = "nonbenchmark_capability_profile"PARENT_KIND = "teacher_generated_nonbenchmark_visual_mcq"PROFILES = ( "backward_epm", "backward_asi", "rec_counting", "sequence_crr", "sequence_ssr",)DEFAULT_HOLDOUT = {profile: 60 for profile in PROFILES}DEFAULT_TRAIN = {"backward_epm": 120, "backward_asi": 180}
class QualityCapabilitySelectionError(ValueError): pass
def _target(row: dict[str, Any]) -> str: values = [ str(item.get("text") or "").strip() for message in row.get("messages") or [] if message.get("role") == "assistant" and message.get("loss") is True for item in message.get("content") or [] if item.get("type") == "text" ] if len(values) != 1 or values[0] not in set("ABCD"): raise QualityCapabilitySelectionError("row lacks one A-D target") return values[0]
def _single_parent(row: dict[str, Any], kind: str) -> str: values = [ str(parent.get("id") or "") for parent in row.get("parents") or [] if parent.get("kind") == kind ] if len(values) != 1 or not values[0]: raise QualityCapabilitySelectionError(f"row lacks one {kind} parent") return values[0]
def _rank(seed: str, profile: str, answer: str, uid: str) -> str: return hashlib.sha256( f"quality-capability-v1:{seed}:{profile}:{answer}:{uid}".encode() ).hexdigest()
def _balanced_select( rows: Iterable[dict[str, Any]], *, quota: int, seed: str, profile: str,) -> list[dict[str, Any]]: if quota <= 0 or quota % 4: raise QualityCapabilitySelectionError("balanced quota must be positive / 4") by_answer: dict[str, list[dict[str, Any]]] = collections.defaultdict(list) for row in rows: by_answer[str(row["answer"])].append(row) per_answer = quota // 4 selected = [] for answer in "ABCD": values = sorted( by_answer.get(answer, []), key=lambda row: (_rank(seed, profile, answer, str(row["uid"])), str(row["uid"])), ) if len(values) < per_answer: raise QualityCapabilitySelectionError( f"{profile}/{answer} has {len(values)} rows; requires {per_answer}" ) selected.extend(values[:per_answer]) return sorted(selected, key=lambda row: str(row["uid"]))
def _image_paths(request: dict[str, Any]) -> list[str]: return [ str(image) for group in request.get("groups") or [] for image in group.get("images") or [] ]
def _structural_candidate( request: dict[str, Any], generation: dict[str, Any]) -> tuple[bool, dict[str, Any]]: profile = str(request.get("target_capability") or "") groups = [ tuple(str(image) for image in group.get("images") or []) for group in request.get("groups") or [] ] flattened = [image for group in groups for image in group] evidence_groups = generation.get("evidence_groups") or [] first_sufficient = generation.get("first_sufficient_group") minimum_sufficient = { "backward_epm": 1, "backward_asi": 2, "rec_counting": 1, "sequence_crr": 1, "sequence_ssr": 1, }.get(profile) diagnostics = { "first_sufficient_group": first_sufficient, "evidence_groups": len(evidence_groups), "observation_groups": len(groups), "distinct_observation_groups": len(set(groups)), "image_positions": len(flattened), "unique_images": len(set(flattened)), "duplicate_image_positions": len(flattened) - len(set(flattened)), } eligible = ( minimum_sufficient is not None and generation.get("decision") == "accept" and generation.get("confidence") == "high" and isinstance(first_sufficient, int) and first_sufficient >= minimum_sufficient and len(evidence_groups) >= 2 and len(set(groups)) >= 2 and len(set(flattened)) >= 6 ) return bool(eligible), diagnostics
def _student_keep(row: dict[str, Any], audit: dict[str, Any]) -> bool: if audit.get("error") is not None: return False target = str(row["answer"]) if str(audit.get("target") or "") != target: raise QualityCapabilitySelectionError("student audit target diverges") prediction = str(audit.get("prediction") or "") margin = float(audit.get("visible_option_margin")) if not 0.0 <= margin <= 1.0: raise QualityCapabilitySelectionError("student audit margin is outside [0,1]") return prediction != target or margin <= 0.25
def _parse_quota(value: str) -> tuple[str, int]: try: profile, raw = value.rsplit("=", 1) count = int(raw) except (TypeError, ValueError) as exc: raise argparse.ArgumentTypeError("quota must be PROFILE=COUNT") from exc if profile not in PROFILES or count <= 0 or count % 4: raise argparse.ArgumentTypeError("quota must use a known profile and be / 4") return profile, count
def _excluded_parent_ids(releases: list[Path]) -> set[str]: excluded: set[str] = set() for raw in releases: root = raw.resolve(strict=True) validate_semantic_release(root, verify_media_hashes=False) for row in read_jsonl( root / "trainer/sft.jsonl", verify_content_hashes=True, require_canonical=True, ): excluded.update( str(parent["id"]) for parent in row.get("parents") or [] if parent.get("kind") == PARENT_KIND and parent.get("id") ) return excluded
def build(args: argparse.Namespace) -> tuple[dict[str, Any], dict[str, Any]]: release = args.release.resolve(strict=True) pack = args.pack.resolve(strict=True) generation_path = args.generation.resolve(strict=True) release_manifest = validate_semantic_release(release, verify_media_hashes=False) pack_manifest_path = pack / "manifest.json" pack_manifest = json.loads(pack_manifest_path.read_text(encoding="utf-8")) if ( (release_manifest.get("inputs") or {}).get("pack_manifest_sha256") != file_sha256(pack_manifest_path) or (release_manifest.get("inputs") or {}).get("generation_sha256") != file_sha256(generation_path) ): raise QualityCapabilitySelectionError("release is not bound to pack/generation") requests = read_jsonl(pack / "requests.jsonl", require_canonical=True) generation_rows = read_jsonl(generation_path, require_canonical=True) trainer_rows = read_jsonl( release / "trainer/sft.jsonl", verify_content_hashes=True, require_canonical=True, ) request_by_uid = {str(row["uid"]): row for row in requests} generation_by_uid = {str(row["uid"]): row for row in generation_rows} trainer_by_uid = {str(row["uid"]): row for row in trainer_rows} if len(request_by_uid) != len(requests) or len(generation_by_uid) != len(generation_rows): raise QualityCapabilitySelectionError("request/generation UIDs collide")
excluded = _excluded_parent_ids(list(args.exclude_release or [])) joined = [] for request_uid, request in request_by_uid.items(): trainer_uid = stable_id("benchmarkdistillsft", request_uid, digest_length=24) trainer = trainer_by_uid.get(trainer_uid) generation = generation_by_uid.get(request_uid) if trainer is None: continue if generation is None: raise QualityCapabilitySelectionError("filtered row lacks generation record") parent_id = _single_parent(trainer, PARENT_KIND) profile = _single_parent(trainer, PROFILE_KIND) if profile != str(request.get("target_capability") or ""): raise QualityCapabilitySelectionError("request/trainer profile diverges") if parent_id in excluded: continue joined.append( { "uid": trainer_uid, "request_uid": request_uid, "parent_id": parent_id, "profile": profile, "answer": _target(trainer), "source_video_basename": str(request["source_video_basename"]), "request": request, "generation": generation, } )
holdout_quotas = dict(args.holdout_quota or DEFAULT_HOLDOUT) train_quotas = dict(args.train_quota or DEFAULT_TRAIN) holdout_rows = [] for profile, quota in sorted(holdout_quotas.items()): holdout_rows.extend( _balanced_select( (row for row in joined if row["profile"] == profile), quota=quota, seed=args.seed + ":holdout", profile=profile, ) ) holdout_uids = {str(row["uid"]) for row in holdout_rows} holdout_videos = {str(row["source_video_basename"]) for row in holdout_rows} if len(holdout_uids) != len(holdout_rows) or len(holdout_videos) != len(holdout_rows): raise QualityCapabilitySelectionError("policy holdout is not source-video unique")
structural = [] for row in joined: if row["uid"] in holdout_uids: continue eligible, diagnostics = _structural_candidate( row["request"], row["generation"] ) if eligible: structural.append({**row, "diagnostics": diagnostics})
audit_by_uid: dict[str, dict[str, Any]] | None = None audit_record = None if args.student_audit is not None: audit_path = args.student_audit.resolve(strict=True) audit_value = json.loads(audit_path.read_text(encoding="utf-8")) if ( audit_value.get("format") != STUDENT_SCREEN_FORMAT or audit_value.get("benchmark_rows_or_labels_used") is not False or audit_value.get("source_release_manifest_sha256") != file_sha256(release / "manifest.json") ): raise QualityCapabilitySelectionError("student screen contract diverges") audit_rows = list(audit_value.get("rows") or []) audit_by_uid = {str(row.get("uid") or ""): row for row in audit_rows} if set(audit_by_uid) != {str(row["uid"]) for row in structural}: raise QualityCapabilitySelectionError("student screen coverage diverges") audit_record = {"path": str(audit_path), "sha256": file_sha256(audit_path)}
selected_rows = [] if audit_by_uid is not None: hard = [row for row in structural if _student_keep(row, audit_by_uid[row["uid"]])] for profile, quota in sorted(train_quotas.items()): selected_rows.extend( _balanced_select( (row for row in hard if row["profile"] == profile), quota=quota, seed=args.seed + ":train", profile=profile, ) )
def public_row(row: dict[str, Any]) -> dict[str, Any]: return { key: row[key] for key in ( "uid", "request_uid", "parent_id", "profile", "answer", "source_video_basename", ) } | ({"diagnostics": row["diagnostics"]} if "diagnostics" in row else {})
holdout = { "format": HOLDOUT_FORMAT, "status": "sealed_before_training_selection", "source_release": str(release), "source_release_manifest_sha256": file_sha256(release / "manifest.json"), "selection_seed": args.seed + ":holdout", "quotas": holdout_quotas, "rows": [public_row(row) for row in sorted(holdout_rows, key=lambda row: row["uid"])], "parent_ids": sorted(row["parent_id"] for row in holdout_rows), "contracts": { "source_video_disjoint_from_sft_selection": True, "may_enter_sft_or_rl": False, "benchmark_rows_or_labels_used": False, }, } selection = { "format": SELECTION_FORMAT, "status": ( "sealed_nonbenchmark_quality_selection" if audit_by_uid is not None else "awaiting_complete_student_screen" ), "training_allowed": audit_by_uid is not None, "source_release": str(release), "source_release_manifest_sha256": file_sha256(release / "manifest.json"), "pack_manifest_sha256": file_sha256(pack_manifest_path), "generation_sha256": file_sha256(generation_path), "excluded_parent_ids": len(excluded), "holdout_parent_ids_sha256": hashlib.sha256( canonical_json_line(sorted(holdout["parent_ids"])) ).hexdigest(), "structural_candidates": [ public_row(row) for row in sorted(structural, key=lambda row: row["uid"]) ], "structural_counts_by_profile": dict( sorted(collections.Counter(row["profile"] for row in structural).items()) ), "student_screen": audit_record, "train_quotas": train_quotas, "selected_rows": [ public_row(row) for row in sorted(selected_rows, key=lambda row: row["uid"]) ], "parent_ids": sorted(row["parent_id"] for row in selected_rows), "transformation": "deduplicate_identical_images_keep_first_chronological_occurrence", "contracts": { "benchmark_rows_labels_predictions_or_tasks_used": False, "counterfactual_rows": 0, "holdout_overlap": 0, "already_trained_parent_overlap": 0, "teacher_confidence_high": True, "two_order_option_consensus_inherited": True, }, } return holdout, selection
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--release", type=Path, required=True) parser.add_argument("--pack", type=Path, required=True) parser.add_argument("--generation", type=Path, required=True) parser.add_argument("--exclude-release", type=Path, action="append", default=[]) parser.add_argument("--student-audit", type=Path) parser.add_argument("--holdout-quota", type=_parse_quota, action="append") parser.add_argument("--train-quota", type=_parse_quota, action="append") parser.add_argument("--seed", default="quality-capability-v1") parser.add_argument("--holdout-output", type=Path, required=True) parser.add_argument("--selection-output", type=Path, required=True) args = parser.parse_args() if args.holdout_quota: args.holdout_quota = dict(args.holdout_quota) if args.train_quota: args.train_quota = dict(args.train_quota) for path in (args.holdout_output, args.selection_output): if path.exists(): raise FileExistsError(path) holdout, selection = build(args) args.holdout_output.parent.mkdir(parents=True, exist_ok=True) args.selection_output.parent.mkdir(parents=True, exist_ok=True) args.holdout_output.write_bytes(canonical_json_line(holdout)) args.selection_output.write_bytes(canonical_json_line(selection)) print( json.dumps( { "holdout_rows": len(holdout["rows"]), "structural_counts_by_profile": selection["structural_counts_by_profile"], "selected_rows": len(selection["selected_rows"]), "training_allowed": selection["training_allowed"], }, indent=2, sort_keys=True, ) )
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""Shared pure-VLM prompt and deterministic MCQ utilities."""
from __future__ import annotations
import hashlibimport refrom collections.abc import Sequence
DIRECT_PROMPT_PREFIX = ( "You are an advanced video question-answering AI assistant. You have been " "provided with causal frames from the video and a multiple-choice question. " "Analyze only the visible frames and provide the best answer.")DIRECT_PROMPT_SUFFIX = "Only give the best option's letter (A, B, C, or D) directly."OPTION_LETTERS = "ABCD"DIRECT_PROMPT_RE = re.compile( r"(?:^|\n)Question:\s*(?P<question>.*?)\n+\s*Options:\s*\n" r"(?P<options>.*?)\n+\s*Only give the best option's letter", re.DOTALL,)OPTION_LINE_RE = re.compile(r"^\s*([A-D])[.):]\s*(.+?)\s*$")
class SemanticMCQError(ValueError): """Raised when a deterministic semantic MCQ cannot be constructed."""
def parse_direct_prompt(value: str) -> tuple[str, list[str]]: """Recover one canonical public question and its four visible options."""
match = DIRECT_PROMPT_RE.search(str(value)) if match is None: raise SemanticMCQError("canonical direct prompt is malformed") question = " ".join(match.group("question").split()) parsed: dict[str, str] = {} for line in match.group("options").splitlines(): option = OPTION_LINE_RE.fullmatch(line) if option is None: if line.strip(): raise SemanticMCQError("canonical option line is malformed") continue letter, text = option.groups() if letter in parsed: raise SemanticMCQError("canonical option letter is duplicated") parsed[letter] = " ".join(text.split()) if not question or list(parsed) != list(OPTION_LETTERS): raise SemanticMCQError("canonical prompt lacks one question and A--D options") options = [parsed[letter] for letter in OPTION_LETTERS] if any(not option for option in options) or len(set(options)) != len(options): raise SemanticMCQError("canonical prompt options are empty or duplicated") return question, options
def rebalance_answer_slot( options: Sequence[str], *, answer: str, answer_slot: int, seed: str,) -> tuple[list[str], str]: """Move the target to a fixed slot and hash-order the three distractors."""
if ( len(options) != len(OPTION_LETTERS) or answer not in OPTION_LETTERS or answer_slot not in range(len(OPTION_LETTERS)) or len(set(options)) != len(OPTION_LETTERS) ): raise SemanticMCQError("invalid four-option answer-space contract") target_index = OPTION_LETTERS.index(answer) target = str(options[target_index]) distractors = [ (index, str(option)) for index, option in enumerate(options) if index != target_index ] distractors.sort( key=lambda item: hashlib.sha256( f"{seed}|{item[0]}|{item[1]}".encode("utf-8") ).digest() ) balanced: list[str | None] = [None] * len(OPTION_LETTERS) balanced[answer_slot] = target remaining = [index for index, value in enumerate(balanced) if value is None] for slot, (_, option) in zip(remaining, distractors, strict=True): balanced[slot] = option if any(value is None for value in balanced): raise SemanticMCQError("balanced options are incomplete") return [str(value) for value in balanced], OPTION_LETTERS[answer_slot]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263# Data preparation
The code package distributes construction and validation code. Trainingrecords, source media, benchmark exports, and calibration artifacts areexternal inputs.
## Training records
The trainer consumes a sealed semantic release. Its validation checks themanifest, source inventory, user/assistant message schema, media identity,and permitted targets. See:
- `viss_core/data_v0/schema.py`- `viss_core/data_v0/semantic_release.py`- `viss_core/data_v0/trainer_adapter.py`
The source-aligned builder combines already prepared source releases:
```bashpython -m data_pipeline.temporal_scope.build_source_aligned_sft_release \ --source data/prepared_source_a \ --source data/prepared_source_b \ --output data/viss_release \ --release-id my_viss_release \ --copy-mode copy```
`prepared_source_a` and `prepared_source_b` are placeholders for validsource releases, not raw-video directories. This generic example does notreconstruct the paper's accepted training mixture by itself.
The paper describes the training mixture. Company training records and theirmanifests are not distributed. The training guide assumes users have preparedtheir own valid source releases, media, example weights, and ordering.
Set `VISS_UPSTREAM_MANIFEST_SHA256` to the trusted upstream identity for yourtraining inputs before starting the builder or trainer. The validator retainsthe identity check, but the code package embeds no company-specific digest.Private legacy source adapters are excluded; supply the standard semanticrelease format instead.
## Evaluation assets
For each benchmark, prepare:
1. Official annotations and authorized video files.2. A query export using the fields read by `viss_core/benchmarks.py`.3. The benchmark's official scoring installation.4. Model and processor files compatible with the locked evaluation protocol.
`configs/evaluation/recent4.example.json` describes the public sampling,query-count, prompt, and processor conventions. It contains no run dates,company file identities, or query records. Follow the evaluation guide tocreate a local configuration bound to your own query exports and processor.The generated configuration is excluded from publication.
## TVS calibration
The TVS policy consumes acquisition/commit calibration artifacts and alignedview predictions from one model. Calibrate on source-disjoint data, thenfreeze the thresholds for benchmark evaluation. The archive includes theselection and analysis implementation, but not the paper's calibrationrecords or precomputed predictions.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114# Inference, TVS, and scoring
Run from the repository root after [installation](INSTALL.md) and[data preparation](DATA.md). The code separates model inference, view-policycomposition, and official scoring.
## 1. Generate recent-view proposals
Create a local configuration from the public template and your own assets:
```bashpython -m scripts.configure_evaluation_protocol \ --streaming-samples data/streamingbench/queries.jsonl \ --ovo-samples data/ovo/queries.jsonl \ --processor-config checkpoints/viss/locked_processor/preprocessor_config.json \ --output configs/evaluation/recent4_full_v1.json```
The generated file contains local paths and file identities. It remainsprivate and is excluded from the source archive. Then validate coverage:
```bashpython -m scripts.validate_evaluation_protocol \ --protocol configs/evaluation/recent4_full_v1.json```
This check requires the external benchmark exports. It is not a data-freeinstallation test.
Use the command in the main README with the prepared checkpoint and lockedprocessor. The runner accepts `--benchmark streamingbench` or`--benchmark ovo`; annotations, query exports, and media must match.
Use `--record-choice-confidence` when the proposals will be passed to TVS.For a reproducibility run, supply `--model-manifest` with the matching modelidentity artifact. The same identity must be retained across all views.The runner also supports `--start-index` and `--end-index` for sharding.
The optional multi-GPU launcher is:
```textbash scripts/run_recent4_single_benchmark.sh \ REPO MODEL MODEL_MANIFEST OUTPUT PYTHON BENCHMARK GPU_CSV MODEL_ID```
It additionally requires the benchmark paths documented by its environmentvariable checks. Start with the Python entry point when preparing new assets.
## 2. Apply the TVS acquisition and commitment policy
The event policy is `causalbudget20`; the compact-history policy is`causalhybrid32`. Use the same checkpoint and the view encodings prescribedby your protocol. Selecting a policy name alone does not fix image resolutionor the processor configuration.
Given recent-view predictions and a frozen calibration artifact:
```bashpython -m experiments.select_uncertainty_escalation_uids \ --recent outputs/recent.json \ --threshold data/calibration/thresholds.json \ --samples data/benchmark/queries.jsonl \ --output-uids outputs/event_uids.json \ --output-samples outputs/event_queries.jsonl \ --output-audit outputs/selection.json```
Run event-view inference on the selected queries. Then compose the firsttwo stages:
```bashpython -m experiments.materialize_uncertainty_temporal_agent \ --recent outputs/recent.json \ --temporal outputs/event.json \ --selection-audit outputs/selection.json \ --threshold-audit data/calibration/thresholds.json \ --output outputs/two_view.json```
Once the required compact-history proposals are available:
```bashpython -m experiments.materialize_confidence_gated_third_view_agent \ --recent outputs/recent.json \ --event outputs/event.json \ --base-agent outputs/two_view.json \ --third-view outputs/history.json \ --threshold-audit data/calibration/thresholds.json \ --output outputs/tvs.json```
These commands name user-generated files; no prediction or score artifactsare shipped. Materialization combines existing proposals and does not callthe VLM. `materialize_tvs_view_oracle.py` uses reference correctness foranalysis and is not the deployed selection policy.
## 3. Score saved predictions
```bashpython -m scripts.score_official_benchmark_predictions \ --benchmark streamingbench \ --annotation data/streamingbench/annotations.json \ --predictions outputs/tvs.json \ --official-root external/StreamingBench \ --output-json outputs/streamingbench_score.json```
Use `--benchmark ovo` and the corresponding official assets for OVO-Bench.The adapter checks query coverage and invokes the original scorer. For OVO,the primary metric is the task-then-group macro average. The official scorermay have additional dependencies; install those from its own repository.
Generated predictions and scores are your run outputs. They are excludedfrom version control and from the source-release archive.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859# Installation
Use Python 3.10 or later. Run commands from the source root; editableinstallation keeps the configuration and script paths available.
## CPU source checks
```bashpython -m venv .venvsource .venv/bin/activatepython -m pip install --upgrade pippython -m pip install -e ".[test]"python -m pytest -q tests```
These tests exercise code contracts with synthetic inputs. They do notvalidate a trained checkpoint or execute a full benchmark.
## GPU inference
Install a CUDA-enabled PyTorch build appropriate for the machine first,then install the inference extras:
```bashpython -m pip install -e ".[inference]"```
The inference extras pin PyTorch 2.7.0 and Transformers 4.57.3.The PyTorch version follows the repository runtime requirements; theTransformers version follows the retained ViSS model configuration.The extras declare Accelerate, qwen-vl-utils, and Decord as well.They specify an installation recipe, not a claim that every GPU/drivercombination has been validated.
Install FFmpeg and ensure `ffprobe` is on `PATH`. Multi-GPU shell launchersalso use Bash 4 or newer, `jq`, `sha256sum`, and `nvidia-smi`.
## Training and attention
```bashpython -m pip install -e ".[inference,training]"python -m pip install flash-attn==2.7.4.post1 --no-build-isolation```
FlashAttention installation needs a compatible CUDA toolkit and compiler.The trainer defaults to `flash_attention_2`. Use `--attn-implementation sdpa`for a development run when FlashAttention is unavailable; this changes theruntime configuration.
The package includes no model weights. Before a GPU run, confirm that theselected checkpoint loads with `AutoModelForImageTextToText` and that theprocessor matches the intended evaluation contract.
## Environment records
Save the installed package versions and launch command alongside your ownruns. Generated outputs belong under `outputs/` or `checkpoints/` and areexcluded from the source archive. Do not commit credentials, benchmark media,or local machine paths.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950# Training ViSS
Install the training environment described in [Installation](INSTALL.md) andprepare a sealed training release as described in [Data preparation](DATA.md).
## Paper recipe
The manuscript specifies one epoch, learning rate `2e-6`, cosine scheduling,warmup ratio `0.03`, seed `59`, maximum length `8192`, maximum image pixels`200704`, and a global batch of `12`. The vision tower is frozen; the languagemodel and multimodal projector are trainable.
For two GPUs, a microbatch of one and six accumulation steps give the statedglobal batch:
```bashtorchrun --nproc_per_node=2 -m experiments.train_qwen3vl_sft \ --model checkpoints/Qwen3-VL-8B-Instruct \ --train data/viss_release/train.jsonl \ --output checkpoints/viss \ --epochs 1 \ --lr 2e-6 \ --lr-scheduler-type cosine \ --warmup-ratio 0.03 \ --per-device-batch-size 1 \ --gradient-accumulation-steps 6 \ --max-length 8192 \ --max-pixels 200704 \ --seed 59 \ --train-order sequential \ --freeze-vision-tower \ --train-vision-projector \ --attn-implementation flash_attention_2 \ --deepspeed configs/training/deepspeed_zero3_bf16.json```
Replace `train.jsonl` with the actual row file inside the sealed release.The sequential setting preserves prepared row order. The paper preparationuses a parent stage followed by capability rows, with stage shuffle seed 59;that ordering must already be reflected in the input release.
Changing the GPU count requires adjusting accumulation if the global batchis to remain fixed. Check the trainer's complete options with:
```bashpython -m experiments.train_qwen3vl_sft --help```
The training entry point requires Transformers even for `--help`. Trainingoutputs and logs are generated at runtime and are not part of this archive.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451#!/usr/bin/env python3"""Audit a task-agnostic recent-to-temporal escalation policy.
The online policy sees only the recent-view first-token generation margin. Gold labels areused offline to fit one global threshold on a deterministic calibration splitand to score the disjoint exploratory split. Task, group, benchmark identity,and answer-space semantics are never policy inputs."""
from __future__ import annotations
import argparseimport hashlibimport jsonfrom collections import defaultdictfrom pathlib import Pathfrom typing import Any
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--recent", type=Path, required=True) parser.add_argument("--temporal", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument( "--calibration-modulus", type=int, default=2, help="SHA256(uid) modulo this value; bucket zero fits the threshold.", ) return parser.parse_args()
def load_result(path: Path) -> dict[str, Any]: value = json.loads(path.read_text(encoding="utf-8")) if not isinstance(value, dict) or not isinstance(value.get("rows"), list): raise ValueError(f"{path}: expected benchmark result with rows") if int(value.get("num_errors", 0)) != 0: raise ValueError(f"{path}: result contains inference errors") return value
def index_rows(result: dict[str, Any]) -> dict[str, dict[str, Any]]: indexed = {str(row.get("uid")): row for row in result["rows"]} if "" in indexed or len(indexed) != len(result["rows"]): raise ValueError("result contains missing or duplicate UIDs") return indexed
def index_scores(result: dict[str, Any]) -> dict[str, dict[str, Any]]: rows = (result.get("score") or {}).get("rows") if not isinstance(rows, list): raise ValueError("result is missing score.rows") indexed = {str(row.get("query_id")): row for row in rows} if "" in indexed or len(indexed) != len(rows): raise ValueError("score rows contain missing or duplicate query IDs") return indexed
def index_temporal_scores(result: dict[str, Any]) -> dict[str, dict[str, Any]]: score_rows = (result.get("score") or {}).get("rows") if isinstance(score_rows, list): return index_scores(result) rows = result.get("rows") if not isinstance(rows, list) or any("correct" not in row for row in rows): raise ValueError("temporal result lacks official or inherited correctness") indexed = {str(row.get("uid")): row for row in rows} if "" in indexed or len(indexed) != len(rows): raise ValueError("temporal score rows contain missing or duplicate UIDs") return indexed
def calibration_bucket(uid: str, modulus: int) -> int: if modulus < 2: raise ValueError("calibration modulus must be at least two") return int(hashlib.sha256(uid.encode("utf-8")).hexdigest(), 16) % modulus
def choice_margin(row: dict[str, Any]) -> float: # New confirmatory runs use the same full-vocabulary first-token margin for # MCQ and open-ended questions. Older exploratory artifacts contain only # the option-letter diagnostic and remain readable for historical audits. confidence = row.get("generation_confidence") or row.get("choice_confidence") if not isinstance(confidence, dict): raise ValueError(f"{row.get('uid')}: missing generation confidence") if confidence.get("task_or_group_used") is not False: raise ValueError(f"{row.get('uid')}: confidence provenance is not task blind") value = float(confidence.get("top2_margin")) if not 0.0 <= value <= 1.0: raise ValueError(f"{row.get('uid')}: invalid generation margin") return value
def select_prediction( recent_row: dict[str, Any], temporal_row: dict[str, Any], threshold: float) -> tuple[str, bool]: escalate = choice_margin(recent_row) <= threshold source = temporal_row if escalate else recent_row return str( source.get("prediction") or source.get("selected_prediction") or "" ), escalate
def confidence_gain( recent_row: dict[str, Any], temporal_row: dict[str, Any]) -> float: """Return the task-blind confidence change after acquiring the temporal view."""
return choice_margin(temporal_row) - choice_margin(recent_row)
def select_acquire_commit_prediction( recent_row: dict[str, Any], temporal_row: dict[str, Any], acquire_threshold: float, commit_threshold: float,) -> tuple[str, bool, bool, float]: """Apply one shared acquire threshold and one shared safe-commit threshold."""
acquired = choice_margin(recent_row) <= acquire_threshold recent_prediction = str( recent_row.get("prediction") or recent_row.get("selected_prediction") or "" ) temporal_prediction = str( temporal_row.get("prediction") or temporal_row.get("selected_prediction") or "" ) gain = confidence_gain(recent_row, temporal_row) committed = bool( acquired and temporal_prediction != recent_prediction and gain > commit_threshold ) return ( temporal_prediction if committed else recent_prediction, acquired, committed, gain, )
def evaluate_threshold( uids: list[str], *, recent: dict[str, dict[str, Any]], temporal: dict[str, dict[str, Any]], recent_scores: dict[str, dict[str, Any]], temporal_scores: dict[str, dict[str, Any]], threshold: float,) -> tuple[int, int]: correct = 0 escalated = 0 for uid in uids: _, did_escalate = select_prediction( recent[uid], temporal[uid], threshold ) official = temporal_scores[uid] if did_escalate else recent_scores[uid] correct += int(bool(official["correct"])) escalated += int(did_escalate) return correct, escalated
def fit_threshold( calibration_uids: list[str], *, recent: dict[str, dict[str, Any]], temporal: dict[str, dict[str, Any]], recent_scores: dict[str, dict[str, Any]], temporal_scores: dict[str, dict[str, Any]],) -> tuple[float, list[dict[str, Any]]]: margins = sorted({choice_margin(recent[uid]) for uid in calibration_uids}) candidates = [-1.0, *margins, 1.0] sweep = [] for threshold in candidates: correct, escalated = evaluate_threshold( calibration_uids, recent=recent, temporal=temporal, recent_scores=recent_scores, temporal_scores=temporal_scores, threshold=threshold, ) sweep.append( { "threshold": threshold, "correct": correct, "total": len(calibration_uids), "accuracy": correct / len(calibration_uids), "escalated": escalated, } ) best = max( sweep, key=lambda row: ( int(row["correct"]), -int(row["escalated"]), -float(row["threshold"]), ), ) return float(best["threshold"]), sweep
def evaluate_acquire_commit_thresholds( uids: list[str], *, recent: dict[str, dict[str, Any]], temporal: dict[str, dict[str, Any]], recent_scores: dict[str, dict[str, Any]], temporal_scores: dict[str, dict[str, Any]], acquire_threshold: float, commit_threshold: float,) -> tuple[int, int, int]: correct = 0 acquired = 0 committed = 0 for uid in uids: _, did_acquire, did_commit, _ = select_acquire_commit_prediction( recent[uid], temporal[uid], acquire_threshold, commit_threshold, ) official = temporal_scores[uid] if did_commit else recent_scores[uid] correct += int(bool(official["correct"])) acquired += int(did_acquire) committed += int(did_commit) return correct, acquired, committed
def fit_acquire_commit_thresholds( calibration_uids: list[str], *, recent: dict[str, dict[str, Any]], temporal: dict[str, dict[str, Any]], recent_scores: dict[str, dict[str, Any]], temporal_scores: dict[str, dict[str, Any]],) -> tuple[float, float, list[dict[str, Any]]]: acquire_candidates = [ -1.000001, *sorted({choice_margin(recent[uid]) for uid in calibration_uids}), 1.000001, ] commit_candidates = [ -1.000001, *sorted( {confidence_gain(recent[uid], temporal[uid]) for uid in calibration_uids} ), 1.000001, ] sweep = [] for acquire_threshold in acquire_candidates: for commit_threshold in commit_candidates: correct, acquired, committed = evaluate_acquire_commit_thresholds( calibration_uids, recent=recent, temporal=temporal, recent_scores=recent_scores, temporal_scores=temporal_scores, acquire_threshold=acquire_threshold, commit_threshold=commit_threshold, ) sweep.append( { "acquire_threshold": acquire_threshold, "commit_threshold": commit_threshold, "correct": correct, "total": len(calibration_uids), "accuracy": correct / len(calibration_uids), "acquired": acquired, "committed": committed, } ) best = max( sweep, key=lambda row: ( int(row["correct"]), -int(row["acquired"]), -int(row["committed"]), -float(row["acquire_threshold"]), float(row["commit_threshold"]), ), ) return ( float(best["acquire_threshold"]), float(best["commit_threshold"]), sweep, )
def main() -> None: args = parse_args() recent_result = load_result(args.recent) temporal_result = load_result(args.temporal) for field in ("benchmark", "model_manifest_sha256", "samples_sha256"): if recent_result.get(field) != temporal_result.get(field): raise ValueError(f"recent/temporal identity mismatch: {field}")
recent = index_rows(recent_result) temporal = index_rows(temporal_result) recent_scores = index_scores(recent_result) temporal_scores = index_temporal_scores(temporal_result) if ( set(recent) != set(temporal) or set(recent) != set(recent_scores) or set(recent) != set(temporal_scores) ): raise ValueError("recent, temporal, and score UID sets must match exactly") if any(row.get("task") is None for row in recent_scores.values()): raise ValueError("score rows require task labels for reporting only")
ordered_uids = [str(row["uid"]) for row in recent_result["rows"]] calibration_uids = [ uid for uid in ordered_uids if calibration_bucket(uid, args.calibration_modulus) == 0 ] evaluation_uids = [uid for uid in ordered_uids if uid not in calibration_uids] if not calibration_uids or not evaluation_uids: raise ValueError("deterministic split produced an empty partition")
acquire_threshold, commit_threshold, sweep = fit_acquire_commit_thresholds( calibration_uids, recent=recent, temporal=temporal, recent_scores=recent_scores, temporal_scores=temporal_scores, ) rows = [] calibration_set = set(calibration_uids) by_task: dict[str, list[int]] = defaultdict(lambda: [0, 0]) for uid in ordered_uids: prediction, escalated, committed, gain = select_acquire_commit_prediction( recent[uid], temporal[uid], acquire_threshold, commit_threshold ) official = temporal_scores[uid] if committed else recent_scores[uid] correct = bool(official["correct"]) partition = "calibration" if uid in calibration_set else "evaluation" task = str(recent_scores[uid]["task"]) if partition == "evaluation": by_task[task][0] += int(correct) by_task[task][1] += 1 rows.append( { "uid": uid, "partition": partition, "margin": choice_margin(recent[uid]), "temporal_margin": choice_margin(temporal[uid]), "confidence_gain": gain, "acquire_threshold": acquire_threshold, "commit_threshold": commit_threshold, "escalated": escalated, "committed": committed, "joint_required_after_escalation": bool( escalated and temporal[uid].get("joint_required", False) ), "prediction": prediction, "correct": correct, "task": task, "task_used_by_policy": False, } )
def partition_summary(partition: str) -> dict[str, Any]: chosen = [row for row in rows if row["partition"] == partition] correct = sum(int(row["correct"]) for row in chosen) escalated = sum(int(row["escalated"]) for row in chosen) committed = sum(int(row["committed"]) for row in chosen) joint_calls = sum( int(row["joint_required_after_escalation"]) for row in chosen ) return { "correct": correct, "total": len(chosen), "accuracy": correct / len(chosen), "escalated": escalated, "escalation_rate": escalated / len(chosen), "committed": committed, "commit_rate": committed / len(chosen), "joint_calls": joint_calls, "mean_model_calls": (len(chosen) + escalated + joint_calls) / len(chosen), }
internal_calibration = ( recent_result.get("benchmark") == "internal_policy_holdout" and recent_result.get("status") == "source_disjoint_internal_controller_calibration" and temporal_result.get("status") == "source_disjoint_internal_controller_calibration" ) output = { "format": "streameva.uncertainty_temporal_escalation_audit.v0", "status": ( "source_disjoint_internal_threshold_calibration" if internal_calibration else "benchmark_selected_exploratory_not_confirmatory" ), "eligible_as_frozen_benchmark_controller_config": internal_calibration, "benchmark": recent_result.get("benchmark"), "model_manifest_sha256": recent_result.get("model_manifest_sha256"), "policy": { "first_view": ( "recorded_initial_causal_view" if internal_calibration else "recent" ), "second_view": ( "all_recorded_causal_views" if internal_calibration else temporal_result.get("inference_policy") ), "trigger": "recent_first_step_generation_top2_margin_leq_global_threshold", "threshold": acquire_threshold, "acquire_threshold": acquire_threshold, "commit_threshold": commit_threshold, "commit_signal": "temporal_minus_recent_full_vocabulary_top2_margin", "commit_rule": "changed_answer_and_confidence_gain_gt_global_threshold", "task_group_or_question_router": False, "gold_available_at_runtime": False, }, "split": { "method": "sha256(uid) modulo calibration_modulus", "calibration_modulus": args.calibration_modulus, "calibration_bucket": 0, }, "calibration": partition_summary("calibration"), "evaluation": partition_summary("evaluation"), "evaluation_by_task_reporting_only": { task: {"correct": values[0], "total": values[1], "accuracy": values[0] / values[1]} for task, values in sorted(by_task.items()) }, "calibration_sweep": sweep, "rows": rows, } args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text( json.dumps(output, indent=2, sort_keys=True) + "\n", encoding="utf-8" ) print( json.dumps( { "acquire_threshold": acquire_threshold, "commit_threshold": commit_threshold, **output["evaluation"], }, sort_keys=True, ) )
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259#!/usr/bin/env python3"""Materialize a task-blind confidence-gated third-view temporal agent.
The third view is acquired on the same answer-disagreement cohort as the directthird-view agent. Its proposal is committed only when its first-token marginimproves over the margin of the view that supplied the current answer by morethan one source-disjoint, globally frozen threshold. Runtime policy inputs donot include task, benchmark identity, or gold labels."""
from __future__ import annotations
import argparseimport copyimport jsonfrom pathlib import Pathfrom statistics import fmeanfrom typing import Any
from experiments.analyze_uncertainty_temporal_escalation import choice_marginfrom experiments.materialize_third_view_disagreement_agent import ( IDENTITY_FIELDS, _frame_indices, _index,)
def materialize( recent: dict[str, Any], event: dict[str, Any], base_agent: dict[str, Any], third: dict[str, Any], threshold: dict[str, Any],) -> dict[str, Any]: for field in IDENTITY_FIELDS: values = {value.get(field) for value in (recent, event, base_agent, third)} if len(values) != 1: raise ValueError(f"view identity mismatch: {field}") if ( threshold.get("status") != "source_disjoint_internal_threshold_calibration" or threshold.get("eligible_as_frozen_benchmark_controller_config") is not True or threshold.get("model_manifest_sha256") != recent.get("model_manifest_sha256") ): raise ValueError("threshold is not an identity-aligned internal calibration") commit_threshold = float(threshold["policy"]["commit_threshold"])
recent_rows, event_rows, base_rows, third_rows = map( _index, (recent, event, base_agent, third) ) if set(base_rows) != set(recent_rows) or not set(event_rows) <= set(recent_rows): raise ValueError("base/recent/event UID coverage diverged") disagreements = { uid for uid, row in event_rows.items() if str(row.get("prediction") or "") != str(recent_rows[uid].get("prediction") or "") } if not disagreements <= set(third_rows): raise ValueError("third-view coverage must include the event disagreement cohort")
output_rows: list[dict[str, Any]] = [] committed_count = 0 for recent_row in recent.get("rows") or []: uid = str(recent_row["uid"]) base = copy.deepcopy(base_rows[uid]) if uid not in disagreements: base["third_view_policy"] = { "triggered": False, "reason": "no_acquired_event_disagreement", "question_task_group_or_benchmark_router": False, } output_rows.append(base) continue
event_row = event_rows[uid] third_row = third_rows[uid] if event_row.get("error") or third_row.get("error"): raise ValueError(f"{uid}: acquired view contains an error") if not bool((base.get("agent_policy") or {}).get("escalated")): raise ValueError(f"{uid}: third view was triggered outside acquired cohort") timestamps = (third_row.get("sampling") or {}).get("frame_timestamps") or [] if timestamps and max(map(float, timestamps)) > float(third_row["query_time"]) + 1e-3: raise ValueError(f"{uid}: third view crosses the causal frontier")
recent_prediction = str(recent_row.get("prediction") or "") event_prediction = str(event_row.get("prediction") or "") current_prediction = str(base.get("prediction") or "") third_prediction = str(third_row.get("prediction") or "") if not all((recent_prediction, event_prediction, current_prediction, third_prediction)): raise ValueError(f"{uid}: an agent proposal is empty") if recent_prediction == event_prediction: raise ValueError(f"{uid}: third view lacks a disagreement trigger") if current_prediction == recent_prediction: current_source = recent_row current_view = "recent4" elif current_prediction == event_prediction: current_source = event_row current_view = "causalbudget20" else: raise ValueError(f"{uid}: current answer is not supplied by recent or event view")
confidence_gain = choice_margin(third_row) - choice_margin(current_source) committed = bool( third_prediction != current_prediction and confidence_gain > commit_threshold ) if committed: committed_count += 1 base["prediction"] = third_prediction base["raw_response"] = third_row.get("raw_response") unique_indices = _frame_indices(event_row) | _frame_indices(third_row) base.update( { "current_prediction": current_prediction, "third_view_prediction": third_prediction, "third_view_policy": { "triggered": True, "trigger": "acquired_event_prediction_differs_from_recent_prediction", "commit": "global_source_disjoint_confidence_gain", "current_view": current_view, "current_margin": choice_margin(current_source), "third_margin": choice_margin(third_row), "confidence_gain": confidence_gain, "commit_threshold": commit_threshold, "committed": committed, "question_task_group_or_benchmark_router": False, "gold_available_to_policy": False, }, "media_calls": int(base.get("media_calls") or 2) + 1, "num_turns": int(base.get("num_turns") or 2) + 1, "model_processed_frames": int(base.get("model_processed_frames") or 24) + int(third_row.get("frames_observed") or 32), "unique_frames": len(unique_indices) if unique_indices else 32, "latency_seconds": float(base.get("latency_seconds") or 0.0) + float(third_row.get("latency_seconds") or 0.0), "visual_tokens": int(recent_row.get("visual_tokens") or 0) + int(event_row.get("visual_tokens") or 0) + int(third_row.get("visual_tokens") or 0), } ) output_rows.append(base)
if any(not str(row.get("prediction") or "") for row in output_rows): raise ValueError("materialized agent contains an empty prediction") triggered = len(disagreements) return { **{ key: base_agent.get(key) for key in ( "annotation", "annotation_sha256", "benchmark", "evaluation_protocol", "evaluation_protocol_sha256", "model", "model_manifest_sha256", "processor", ) }, "format": "streameva.confidence_gated_third_view_agent.v0", "status": "benchmark_selected_router_free_development_agent", "classification": "benchmark_selected_development_not_confirmatory", "comparable_under_locked_recent4_protocol": False, "policy": { "first_view": "recent4", "second_view": "frozen_uncertainty_triggered_causalbudget20", "third_view": "causalbudget32r8_on_acquired_answer_disagreement", "third_view_commit": "global_source_disjoint_confidence_gain", "commit_threshold": commit_threshold, "question_task_group_or_benchmark_router": False, "benchmark_identity_available_to_policy": False, "gold_available_to_policy": False, }, "num_samples": len(output_rows), "num_errors": 0, "third_view_triggered": triggered, "third_view_input_rows": len(third_rows), "third_view_unused_precomputed_rows": len(set(third_rows) - disagreements), "third_view_committed": committed_count, "third_view_trigger_rate": triggered / len(output_rows), "third_view_commit_rate": committed_count / triggered if triggered else 0.0, "mean_model_calls": fmean(int(row.get("media_calls") or 1) for row in output_rows), "mean_unique_frames": fmean(int(row.get("unique_frames") or 4) for row in output_rows), "mean_model_processed_frames": fmean( int(row.get("model_processed_frames") or 4) for row in output_rows ), "rows": output_rows, }
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--recent", type=Path, required=True) parser.add_argument("--event", type=Path, required=True) parser.add_argument("--base-agent", type=Path, required=True) parser.add_argument("--third-view", type=Path, required=True) parser.add_argument("--threshold-audit", type=Path, required=True) parser.add_argument("--third-view-model-identity-sha256") parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() if args.output.exists(): raise FileExistsError(args.output) values = [ json.loads(path.read_text(encoding="utf-8")) for path in ( args.recent, args.event, args.base_agent, args.third_view, args.threshold_audit, ) ] identity_override = None if args.third_view_model_identity_sha256: if len(args.third_view_model_identity_sha256) != 64 or any( value not in "0123456789abcdef" for value in args.third_view_model_identity_sha256 ): raise ValueError("third-view model identity is malformed") third = values[3] if third.get("model_manifest_sha256") not in { None, args.third_view_model_identity_sha256, }: raise ValueError("third-view model identity override diverges") if third.get("model_manifest_sha256") is None: third["model_manifest_sha256"] = args.third_view_model_identity_sha256 identity_override = { "field": "model_manifest_sha256", "source": "previously_sealed_checkpoint_identity", "value": args.third_view_model_identity_sha256, } result = materialize(*values) result["third_view_identity_override"] = identity_override result["artifacts"] = { "recent": str(args.recent.resolve()), "event": str(args.event.resolve()), "base_agent": str(args.base_agent.resolve()), "third_view": str(args.third_view.resolve()), "threshold_audit": str(args.threshold_audit.resolve()), } args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n") print( json.dumps( { "output": str(args.output), "num_samples": result["num_samples"], "triggered": result["third_view_triggered"], "committed": result["third_view_committed"], }, sort_keys=True, ) )
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203#!/usr/bin/env python3"""Materialize a router-free third-view agent on event-view disagreements.
The frozen first stage decides whether to acquire the event view. A third32-frame view is acquired only when that event proposal disagrees with therecent proposal, and its answer is committed directly. Runtime decisions usepredictions and acquisition state only; task names, benchmark identity, andgold labels are never inputs to the policy."""
from __future__ import annotations
import argparseimport copyimport jsonfrom pathlib import Pathfrom statistics import fmeanfrom typing import Any
IDENTITY_FIELDS = ( "benchmark", "model_manifest_sha256", "annotation_sha256", "evaluation_protocol_sha256",)
def _index(value: dict[str, Any]) -> dict[str, dict[str, Any]]: rows = value.get("rows") or [] indexed = {str(row.get("uid") or ""): row for row in rows} if "" in indexed or len(indexed) != len(rows): raise ValueError("result rows contain empty or duplicate UIDs") return indexed
def _frame_indices(row: dict[str, Any]) -> set[int]: return {int(value) for value in (row.get("sampling") or {}).get("frame_indices") or []}
def materialize( recent: dict[str, Any], event: dict[str, Any], base_agent: dict[str, Any], third: dict[str, Any],) -> dict[str, Any]: for field in IDENTITY_FIELDS: values = {value.get(field) for value in (recent, event, base_agent, third)} if len(values) != 1: raise ValueError(f"view identity mismatch: {field}") recent_rows, event_rows, base_rows, third_rows = map( _index, (recent, event, base_agent, third) ) if set(base_rows) != set(recent_rows) or not set(event_rows) <= set(recent_rows): raise ValueError("base/recent/event UID coverage diverged") disagreements = { uid for uid, row in event_rows.items() if str(row.get("prediction") or "") != str(recent_rows[uid].get("prediction") or "") } if set(third_rows) != disagreements: raise ValueError("third-view coverage must equal the event disagreement cohort")
output_rows = [] for recent_row in recent.get("rows") or []: uid = str(recent_row["uid"]) base = copy.deepcopy(base_rows[uid]) if uid not in third_rows: base["third_view_policy"] = { "triggered": False, "reason": "no_acquired_event_disagreement", "question_task_group_or_benchmark_router": False, } output_rows.append(base) continue
proposal = event_rows[uid] adjudicator = third_rows[uid] if proposal.get("error") or adjudicator.get("error"): raise ValueError(f"{uid}: acquired view contains an error") if not bool((base.get("agent_policy") or {}).get("escalated")): raise ValueError(f"{uid}: third view was triggered outside the acquired cohort") timestamps = (adjudicator.get("sampling") or {}).get("frame_timestamps") or [] if timestamps and max(map(float, timestamps)) > float(adjudicator["query_time"]) + 1e-3: raise ValueError(f"{uid}: third view crosses the causal frontier") recent_prediction = str(recent_row.get("prediction") or "") event_prediction = str(proposal.get("prediction") or "") third_prediction = str(adjudicator.get("prediction") or "") if not recent_prediction or not event_prediction or not third_prediction: raise ValueError(f"{uid}: an agent proposal is empty") if recent_prediction == event_prediction: raise ValueError(f"{uid}: third view lacks a disagreement trigger")
unique_indices = _frame_indices(proposal) | _frame_indices(adjudicator) base.update( { "prediction": third_prediction, "raw_response": adjudicator.get("raw_response"), "third_view_prediction": third_prediction, "third_view_policy": { "triggered": True, "trigger": "acquired_event_prediction_differs_from_recent_prediction", "commit": "direct_third_view_prediction", "recent_prediction": recent_prediction, "event_prediction": event_prediction, "question_task_group_or_benchmark_router": False, "gold_available_to_policy": False, }, "media_calls": int(base.get("media_calls") or 2) + 1, "num_turns": int(base.get("num_turns") or 2) + 1, "model_processed_frames": int(base.get("model_processed_frames") or 24) + int(adjudicator.get("frames_observed") or 32), "unique_frames": len(unique_indices) if unique_indices else 32, "latency_seconds": float(base.get("latency_seconds") or 0.0) + float(adjudicator.get("latency_seconds") or 0.0), "visual_tokens": int(recent_row.get("visual_tokens") or 0) + int(proposal.get("visual_tokens") or 0) + int(adjudicator.get("visual_tokens") or 0), } ) output_rows.append(base) if any(not str(row.get("prediction") or "") for row in output_rows): raise ValueError("materialized agent contains an empty prediction")
triggered = len(third_rows) return { **{ key: base_agent.get(key) for key in ( "annotation", "annotation_sha256", "benchmark", "evaluation_protocol", "evaluation_protocol_sha256", "model", "model_manifest_sha256", "processor", ) }, "format": "streameva.third_view_disagreement_agent.v0", "status": "benchmark_selected_router_free_development_agent", "classification": "benchmark_selected_development_not_confirmatory", "comparable_under_locked_recent4_protocol": False, "policy": { "first_view": "recent4", "second_view": "frozen_uncertainty_triggered_causalbudget20", "third_view": "causalbudget32r8_on_acquired_answer_disagreement", "third_view_commit": "direct_prediction", "question_task_group_or_benchmark_router": False, "benchmark_identity_available_to_policy": False, "gold_available_to_policy": False, }, "num_samples": len(output_rows), "num_errors": 0, "third_view_triggered": triggered, "third_view_trigger_rate": triggered / len(output_rows), "mean_model_calls": fmean(int(row.get("media_calls") or 1) for row in output_rows), "mean_unique_frames": fmean(int(row.get("unique_frames") or 4) for row in output_rows), "mean_model_processed_frames": fmean( int(row.get("model_processed_frames") or 4) for row in output_rows ), "rows": output_rows, }
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--recent", type=Path, required=True) parser.add_argument("--event", type=Path, required=True) parser.add_argument("--base-agent", type=Path, required=True) parser.add_argument("--third-view", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() if args.output.exists(): raise FileExistsError(args.output) values = [ json.loads(path.read_text(encoding="utf-8")) for path in (args.recent, args.event, args.base_agent, args.third_view) ] result = materialize(*values) result["artifacts"] = { "recent": str(args.recent.resolve()), "event": str(args.event.resolve()), "base_agent": str(args.base_agent.resolve()), "third_view": str(args.third_view.resolve()), } args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n") print( json.dumps( { "output": str(args.output), "num_samples": result["num_samples"], "third_view_triggered": result["third_view_triggered"], }, sort_keys=True, ) )
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118#!/usr/bin/env python3"""Materialize a strict post-hoc oracle over three complete causal views."""
from __future__ import annotations
import argparseimport copyimport jsonfrom pathlib import Pathfrom statistics import fmeanfrom typing import Any
try: from experiments.tvs_correctness import is_correct, load_goldexcept ModuleNotFoundError: # Direct script execution without repository PYTHONPATH. from tvs_correctness import is_correct, load_gold
IDENTITY_FIELDS = ( "benchmark", "model_manifest_sha256", "annotation_sha256", "evaluation_protocol_sha256",)
def _index(value: dict[str, Any]) -> dict[str, dict[str, Any]]: rows = value.get("rows") or [] result = {str(row["uid"]): row for row in rows} if len(result) != len(rows): raise ValueError("duplicate view UID") return result
def materialize( recent: dict[str, Any], event: dict[str, Any], history: dict[str, Any], gold: dict[str, dict[str, Any]],) -> dict[str, Any]: views = [_index(value) for value in (recent, event, history)] uid_set = set(views[0]) if any(set(view) != uid_set for view in views[1:]) or set(gold) != uid_set: raise ValueError("strict oracle requires exact three-view and gold coverage") for field in IDENTITY_FIELDS: expected = recent.get(field) if expected in (None, ""): raise ValueError(f"recent view lacks identity: {field}") for value in (event, history): observed = value.get(field) if observed not in (None, "", expected): raise ValueError(f"view identity mismatch: {field}")
rows = [] chosen_counts = [0, 0, 0] for source in recent.get("rows") or []: uid = str(source["uid"]) candidates = [view[uid] for view in views] correct = [is_correct(row.get("prediction"), gold[uid]) for row in candidates] chosen_index = next((i for i, value in enumerate(correct) if value), 0) chosen_counts[chosen_index] += 1 output = copy.deepcopy(candidates[chosen_index]) output.update( { "uid": uid, "prediction": str(candidates[chosen_index].get("prediction") or ""), "media_calls": 3, "model_processed_frames": sum( int(row.get("frames_observed") or fallback) for row, fallback in zip(candidates, (4, 20, 32), strict=True) ), "tvs_oracle": { "analysis_only": True, "gold_available_to_selector": True, "correct_proposals": correct, "chosen_view": ("recent", "event", "history")[chosen_index], }, } ) rows.append(output) return { **{field: recent.get(field) for field in IDENTITY_FIELDS}, "format": "iclr_video.strict_three_view_oracle.v1", "status": "complete", "analysis_only": True, "num_samples": len(rows), "num_errors": 0, "mean_model_calls": 3.0, "mean_processed_frames": fmean(row["model_processed_frames"] for row in rows), "chosen_view_counts": dict(zip(("recent", "event", "history"), chosen_counts, strict=True)), "rows": rows, }
def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--benchmark", choices=("streamingbench", "ovo"), required=True) parser.add_argument("--annotation", type=Path, required=True) parser.add_argument("--recent", type=Path, required=True) parser.add_argument("--event", type=Path, required=True) parser.add_argument("--history", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() if args.output.exists(): raise FileExistsError(args.output) values = [json.loads(path.read_text()) for path in (args.recent, args.event, args.history)] result = materialize(*values, load_gold(args.benchmark, args.annotation)) args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n") print(json.dumps({ "rows": result["num_samples"], "mean_model_calls": result["mean_model_calls"], "mean_processed_frames": result["mean_processed_frames"], }, sort_keys=True))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465#!/usr/bin/env python3"""Materialize one full prediction set from recent and triggered temporal calls."""
from __future__ import annotations
import argparseimport jsonfrom pathlib import Pathfrom statistics import fmeanfrom typing import Any
from experiments.evaluate_qwen3vl_recent4_full import atomic_writefrom experiments.analyze_uncertainty_temporal_escalation import choice_margin
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--recent", type=Path, required=True) parser.add_argument("--temporal", type=Path, required=True) parser.add_argument("--selection-audit", type=Path, required=True) parser.add_argument("--threshold-audit", type=Path) parser.add_argument( "--temporal-model-identity-sha256", help=( "Previously sealed model identity to attach when the temporal result " "was launched without embedding it; avoids rehashing the model." ), ) parser.add_argument( "--commit-threshold", type=float, help=( "Optional fixed proposal-minus-current margin threshold. This is " "required for an unlabeled fixed-budget selection and overrides " "the commit threshold stored in an internal calibration." ), ) parser.add_argument( "--fallback-recent-on-temporal-error", action="store_true", help=( "Fail closed to the aligned recent4 prediction when a preselected " "temporal call has a recorded runtime error. The fallback is fixed " "before scoring and never reads benchmark labels." ), ) parser.add_argument("--output", type=Path, required=True) return parser.parse_args()
def selected_view_name(policy: str, mode: str, *, escalated: bool) -> str: if not escalated: return "recent4" if policy in {"causalbudget20", "causalbudget32r8"}: suffix = "32_recent8" if policy == "causalbudget32r8" else "20" mode_name = { "native-video": "native_video", "image-list": "image_list", "hybrid-history-video-recent-images": ( "hybrid_history_video_recent_images" ), "lowres-history-recent-images": "lowres_history_recent_images", }[mode] return f"causal_temporal{suffix}_{mode_name}" if policy in {"causalhybrid32", "causalhybrid32r8"}: recent_frames = 8 if policy == "causalhybrid32r8" else 4 history_frames = 32 - recent_frames if mode == "image-list": return ( f"causal_uniform_history{history_frames}_plus_recent" f"{recent_frames}_image_list" ) return f"causal_hybrid_history{history_frames}_plus_recent{recent_frames}" if policy == "prefix32": return "causal_prefix32" raise ValueError(f"unsupported second-view policy: {policy}")
def second_view_policy_name(policy: str, mode: str) -> str: if policy in {"causalbudget20", "causalbudget32r8"}: suffix = "32_recent8" if policy == "causalbudget32r8" else "20" prefix = { "native-video": "native_video", "image-list": "image_list", "hybrid-history-video-recent-images": ( "hybrid_history_video_recent_images" ), "lowres-history-recent-images": "lowres_history_recent_images", }[mode] return f"{prefix}_causal_temporal{suffix}" if policy in {"causalhybrid32", "causalhybrid32r8"}: if mode == "hybrid-history-video-recent-images": return ( "hybrid_history_video_recent_images_causal_hybrid32r8" if policy == "causalhybrid32r8" else "hybrid_history_video_recent_images_causal_hybrid32" ) return ( "image_list_uniform_history24_plus_recent8" if policy == "causalhybrid32r8" else "image_list_uniform_history28_plus_recent4" ) if policy == "prefix32": return "image_list_causal_prefix32" raise ValueError(f"unsupported second-view policy: {policy}")
def materialize( recent: dict[str, Any], temporal: dict[str, Any], selection: dict[str, Any], threshold: dict[str, Any] | None, *, commit_threshold_override: float | None = None, fallback_recent_on_temporal_error: bool = False,) -> dict[str, Any]: for field in ( "benchmark", "model_manifest_sha256", "annotation_sha256", "evaluation_protocol_sha256", ): if recent.get(field) != temporal.get(field): raise ValueError(f"recent/temporal identity mismatch: {field}") selection_format = selection.get("format") fixed_quantile = None frozen_threshold = None if threshold is not None: if ( threshold.get("status") != "source_disjoint_internal_threshold_calibration" or threshold.get("eligible_as_frozen_benchmark_controller_config") is not True or threshold.get("model_manifest_sha256") != recent.get("model_manifest_sha256") ): raise ValueError("threshold is not an eligible internal calibration") frozen_threshold = float(threshold["policy"]["threshold"]) commit_threshold = threshold["policy"].get("commit_threshold") if selection_format not in (None, "streameva.internal_threshold_uid_selection.v0"): raise ValueError("threshold calibration and selection mode diverge") else: if selection_format != "streameva.unlabeled_budget_uid_selection.v0": raise ValueError("selection is not an unlabeled fixed-budget audit") fixed_quantile = float(selection.get("quantile")) if not 0.0 < fixed_quantile <= 1.0: raise ValueError("fixed uncertainty quantile is invalid") if selection.get("benchmark_identity_used_for_policy_parameters") is not False: raise ValueError("fixed-budget acquisition used benchmark identity") if selection.get("cohort_labels_read_for_selection") is not False: raise ValueError("fixed-budget acquisition used cohort labels") if commit_threshold_override is None: raise ValueError("fixed-budget selection requires a commit threshold") commit_threshold = commit_threshold_override if commit_threshold_override is not None: commit_threshold = commit_threshold_override if commit_threshold is not None: commit_threshold = float(commit_threshold) if ( selection.get("status") != "frozen_before_benchmark_temporal_inference" or selection.get("benchmark") != recent.get("benchmark") or selection.get("model_manifest_sha256") != recent.get("model_manifest_sha256") or selection.get("score_or_gold_fields_read_for_selection") is not False ): raise ValueError("selection audit is not frozen or identity-aligned") if threshold is not None and float(selection.get("threshold")) != frozen_threshold: raise ValueError("selection threshold diverges from internal calibration")
recent_rows = {str(row["uid"]): row for row in recent.get("rows") or []} temporal_rows = {str(row["uid"]): row for row in temporal.get("rows") or []} decisions = {str(row["uid"]): row for row in selection.get("rows") or []} if ( len(recent_rows) != len(recent.get("rows") or []) or len(temporal_rows) != len(temporal.get("rows") or []) or len(decisions) != len(selection.get("rows") or []) ): raise ValueError("duplicate UID in input artifacts") if set(decisions) != set(recent_rows): raise ValueError("selection audit does not cover the recent result") selected = {uid for uid, row in decisions.items() if bool(row["escalated"])} temporal_input_count = len(temporal_rows) if not selected.issubset(temporal_rows): missing = sorted(selected - set(temporal_rows)) raise ValueError( f"temporal inference is missing {len(missing)} selected UIDs" ) temporal_rows = {uid: temporal_rows[uid] for uid in selected} temporal_error_uids = { uid for uid, row in temporal_rows.items() if bool(row.get("error")) } if temporal_error_uids and not fallback_recent_on_temporal_error: raise ValueError( f"{len(temporal_error_uids)} selected temporal rows contain errors" ) valid_temporal_rows = { uid: row for uid, row in temporal_rows.items() if uid not in temporal_error_uids } if not valid_temporal_rows: raise ValueError("no valid temporal row remains to establish the second-view policy") second_view_policies = { str((row.get("sampling") or {}).get("frame_policy") or "") for row in valid_temporal_rows.values() } if second_view_policies not in ( {"causalbudget20"}, {"causalbudget32r8"}, {"prefix32"}, {"causalhybrid32"}, {"causalhybrid32r8"}, ): raise ValueError( "second-view rows must share causalbudget20, causalbudget32r8, prefix32, or " "causalhybrid32*" ) second_view_policy = next(iter(second_view_policies)) second_view_modes = { str(row.get("visual_input_mode") or "") for row in valid_temporal_rows.values() } if len(second_view_modes) != 1: raise ValueError("second-view rows do not share one visual input mode") second_view_mode = next(iter(second_view_modes)) if second_view_mode not in { "native-video", "hybrid-history-video-recent-images", "lowres-history-recent-images", "image-list", }: raise ValueError("second-view visual input mode is missing or unsupported")
rows = [] for recent_row in recent.get("rows") or []: uid = str(recent_row["uid"]) decision = decisions[uid] escalated = bool(decision["escalated"]) temporal_error_fallback = escalated and uid in temporal_error_uids proposal = ( recent_row if temporal_error_fallback or not escalated else temporal_rows[uid] ) sampling = proposal.get("sampling") or {} if sampling.get("frame_timestamps") and max(sampling["frame_timestamps"]) > float( proposal["query_time"] ) + 1e-3: raise ValueError(f"{uid}: selected inference crosses the causal frontier") recent_frames = int(recent_row.get("frames_observed") or 4) chosen_frames = int(proposal.get("frames_observed") or recent_frames) probe_frames = 0 extra_probe_frames = 0 if escalated and not temporal_error_fallback: if sampling.get("frame_policy") != second_view_policy: raise ValueError(f"{uid}: second-view policy diverged") if second_view_policy in {"causalbudget20", "causalbudget32r8"}: candidate_indices = sampling.get("candidate_frame_indices") if not isinstance(candidate_indices, list) or not candidate_indices: raise ValueError(f"{uid}: temporal row lacks probe-frame audit") probe_frames = len(candidate_indices) extra_probe_frames = int(sampling.get("extra_frames_inspected", -1)) if extra_probe_frames != max(0, probe_frames - chosen_frames): raise ValueError(f"{uid}: temporal probe accounting diverged") elif second_view_policy == "prefix32" and chosen_frames != 32: raise ValueError(f"{uid}: prefix32 row does not expose 32 frames") elif second_view_policy in { "causalhybrid32", "causalhybrid32r8", } and not ( 1 <= chosen_frames <= 32 ): raise ValueError(f"{uid}: causalhybrid32* frame budget is invalid") recent_prediction = str(recent_row.get("prediction") or "") proposal_prediction = str(proposal.get("prediction") or "") confidence_gain = None committed = escalated and not temporal_error_fallback if escalated and not temporal_error_fallback and commit_threshold is not None: confidence_gain = choice_margin(proposal) - choice_margin(recent_row) committed = bool( proposal_prediction != recent_prediction and confidence_gain > commit_threshold ) final_prediction = proposal_prediction if committed else recent_prediction rows.append( { **proposal, "uid": uid, "prediction": final_prediction, "current_prediction": recent_prediction, "proposal_prediction": proposal_prediction if escalated else None, "agent_policy": { "margin": float(decision["margin"]), "threshold": frozen_threshold, "uncertainty_quantile": fixed_quantile, "uncertainty_rank": decision.get("uncertainty_rank"), "escalated": escalated, "temporal_error_fallback": temporal_error_fallback, "temporal_error": ( str(temporal_rows[uid].get("error")) if temporal_error_fallback else None ), "commit_threshold": commit_threshold, "confidence_gain": confidence_gain, "committed": committed, "selected_view": ( "recent4_temporal_error_fallback" if temporal_error_fallback else selected_view_name( second_view_policy, second_view_mode, escalated=escalated ) ), "question_task_group_or_benchmark_router": False, }, "unique_frames": chosen_frames, "model_processed_frames": ( recent_frames + chosen_frames if escalated and not temporal_error_fallback else recent_frames ), "low_resolution_probe_frames": probe_frames, "extra_probe_frames_not_visible_to_vlm": extra_probe_frames, "total_decoded_frame_instances": ( recent_frames + probe_frames + chosen_frames if escalated and not temporal_error_fallback else recent_frames ), "media_calls": 2 if escalated else 1, "num_turns": 2 if escalated else 1, "latency_seconds": float(recent_row.get("latency_seconds") or 0.0) + ( float(temporal_rows[uid].get("latency_seconds") or 0.0) if escalated else 0.0 ), } ) if any(not row["prediction"] for row in rows): raise ValueError("materialized agent contains an empty prediction") escalated_count = len(selected) return { "format": "streameva.uncertainty_temporal_agent_eval.v0", "status": ( "internally_calibrated_router_free_agent" if threshold is not None else "fixed_budget_router_free_agent" ), "benchmark": recent.get("benchmark"), "model": recent.get("model"), "model_manifest_sha256": recent.get("model_manifest_sha256"), "processor": recent.get("processor"), "annotation": recent.get("annotation"), "annotation_sha256": recent.get("annotation_sha256"), "evaluation_protocol": recent.get("evaluation_protocol"), "evaluation_protocol_sha256": recent.get("evaluation_protocol_sha256"), "comparable_under_locked_recent4_protocol": False, "policy": { "first_view": "recent4", "uncertainty": "first_step_full_vocabulary_top2_margin", "threshold": frozen_threshold, "uncertainty_quantile": fixed_quantile, "commit_threshold": commit_threshold, "second_view": second_view_policy_name( second_view_policy, second_view_mode ), "commit_rule": ( "changed_answer_and_confidence_gain_gt_global_threshold" if commit_threshold is not None else "legacy_always_accept_temporal_proposal" ), "question_task_group_or_benchmark_router": False, "benchmark_identity_available_to_policy": False, "gold_available_to_policy": False, "temporal_error_policy": ( "fail_closed_to_recent4" if fallback_recent_on_temporal_error else "reject_materialization" ), }, "num_samples": len(rows), "num_errors": 0, "escalated": escalated_count, "temporal_input_num_rows": temporal_input_count, "temporal_unused_num_rows": temporal_input_count - escalated_count, "temporal_error_fallback_count": len(temporal_error_uids), "escalation_rate": escalated_count / len(rows), "mean_model_calls": 1.0 + escalated_count / len(rows), "mean_unique_frames": fmean(row["unique_frames"] for row in rows), "mean_model_processed_frames": fmean( row["model_processed_frames"] for row in rows ), "mean_low_resolution_probe_frames": fmean( row["low_resolution_probe_frames"] for row in rows ), "mean_extra_probe_frames_not_visible_to_vlm": fmean( row["extra_probe_frames_not_visible_to_vlm"] for row in rows ), "mean_total_decoded_frame_instances": fmean( row["total_decoded_frame_instances"] for row in rows ), "rows": rows, }
def main() -> None: args = parse_args() recent = json.loads(args.recent.read_text(encoding="utf-8")) temporal = json.loads(args.temporal.read_text(encoding="utf-8")) identity_override_applied = False if args.temporal_model_identity_sha256 is not None: identity = args.temporal_model_identity_sha256.strip().lower() if len(identity) != 64 or any( character not in "0123456789abcdef" for character in identity ): raise ValueError("temporal model identity must be a 64-character SHA-256") embedded_identity = temporal.get("model_manifest_sha256") if embedded_identity not in (None, "", identity): raise ValueError("temporal model identity override conflicts with artifact") if embedded_identity in (None, ""): temporal["model_manifest_sha256"] = identity identity_override_applied = True selection = json.loads(args.selection_audit.read_text(encoding="utf-8")) threshold = ( json.loads(args.threshold_audit.read_text(encoding="utf-8")) if args.threshold_audit is not None else None ) output = materialize( recent, temporal, selection, threshold, commit_threshold_override=args.commit_threshold, fallback_recent_on_temporal_error=args.fallback_recent_on_temporal_error, ) output["artifacts"] = { "recent": {"path": str(args.recent.resolve())}, "temporal": {"path": str(args.temporal.resolve())}, "selection_audit": {"path": str(args.selection_audit.resolve())}, } if args.threshold_audit is not None: output["artifacts"]["threshold_audit"] = { "path": str(args.threshold_audit.resolve()), } output["artifact_checksums_skipped"] = True output["artifact_checksum_skip_reason"] = ( "native artifacts succeeded and identities are embedded in their manifests" ) output["temporal_model_identity_override_applied"] = identity_override_applied atomic_write(args.output, output) print( json.dumps( { "benchmark": output["benchmark"], "num_samples": output["num_samples"], "escalated": output["escalated"], "mean_model_calls": output["mean_model_calls"], }, sort_keys=True, ) )
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192#!/usr/bin/env python3"""Select temporal-view calls using a threshold or fixed uncertainty budget."""
from __future__ import annotations
import argparseimport jsonimport mathfrom pathlib import Pathfrom typing import Any
from experiments.analyze_uncertainty_temporal_escalation import choice_marginfrom experiments.evaluate_qwen3vl_recent4_full import atomic_write, sha256_file
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--recent", type=Path, required=True) policy = parser.add_mutually_exclusive_group(required=True) policy.add_argument("--threshold", type=Path) policy.add_argument( "--quantile", type=float, help="Acquire the lowest-margin fraction without reading cohort labels.", ) parser.add_argument("--samples", type=Path, required=True) parser.add_argument("--output-uids", type=Path, required=True) parser.add_argument("--output-samples", type=Path, required=True) parser.add_argument("--output-audit", type=Path, required=True) return parser.parse_args()
def load_frozen_threshold(path: Path, model_manifest_sha256: str | None) -> float: value = json.loads(path.read_text(encoding="utf-8")) if ( value.get("status") != "source_disjoint_internal_threshold_calibration" or value.get("eligible_as_frozen_benchmark_controller_config") is not True or value.get("benchmark") != "internal_policy_holdout" or value.get("model_manifest_sha256") != model_manifest_sha256 ): raise ValueError("threshold is not an eligible source-disjoint calibration") threshold = float(value["policy"]["threshold"]) if not 0.0 <= threshold <= 1.0: raise ValueError("invalid calibrated threshold") return threshold
def select_rows( recent: dict[str, Any], *, threshold: float) -> tuple[list[str], list[dict[str, Any]]]: selected = [] audit_rows = [] for row in recent.get("rows") or []: uid = str(row.get("uid") or "") if not uid: raise ValueError("recent result has a row without uid") margin = choice_margin(row) escalated = margin <= threshold if escalated: selected.append(uid) audit_rows.append( { "uid": uid, "margin": margin, "threshold": threshold, "escalated": escalated, } ) if len(audit_rows) != int(recent.get("num_samples", -1)): raise ValueError("recent result sample count diverged") if int(recent.get("num_errors", -1)) != 0: raise ValueError("recent result contains inference errors") if len({row["uid"] for row in audit_rows}) != len(audit_rows): raise ValueError("recent result contains duplicate uids") return selected, audit_rows
def select_rows_by_quantile( recent: dict[str, Any], *, quantile: float) -> tuple[list[str], list[dict[str, Any]], float]: """Select an exact bottom-margin budget with deterministic UID tie-breaking."""
if not 0.0 < quantile <= 1.0: raise ValueError("quantile must be in (0, 1]") rows = list(recent.get("rows") or []) if len(rows) != int(recent.get("num_samples", -1)): raise ValueError("recent result sample count diverged") if int(recent.get("num_errors", -1)) != 0: raise ValueError("recent result contains inference errors") values = [] for row in rows: uid = str(row.get("uid") or "") if not uid: raise ValueError("recent result has a row without uid") values.append((choice_margin(row), uid)) if len({uid for _, uid in values}) != len(values): raise ValueError("recent result contains duplicate uids") budget = max(1, math.ceil(len(values) * quantile)) ranked = sorted(values, key=lambda item: (item[0], item[1])) selected_set = {uid for _, uid in ranked[:budget]} cutoff = float(ranked[budget - 1][0]) selected = [str(row["uid"]) for row in rows if str(row["uid"]) in selected_set] rank_by_uid = {uid: rank for rank, (_, uid) in enumerate(ranked, 1)} audit_rows = [ { "uid": str(row["uid"]), "margin": choice_margin(row), "uncertainty_rank": rank_by_uid[str(row["uid"])], "quantile": quantile, "escalated": str(row["uid"]) in selected_set, } for row in rows ] return selected, audit_rows, cutoff
def main() -> None: args = parse_args() recent = json.loads(args.recent.read_text(encoding="utf-8")) threshold = None quantile = None cutoff = None if args.threshold is not None: threshold = load_frozen_threshold( args.threshold, recent.get("model_manifest_sha256") ) selected, audit_rows = select_rows(recent, threshold=threshold) else: quantile = float(args.quantile) selected, audit_rows, cutoff = select_rows_by_quantile( recent, quantile=quantile ) selected_set = set(selected) sample_rows = [ json.loads(line) for line in args.samples.read_text(encoding="utf-8").splitlines() if line.strip() ] ordered_uids = [str(row.get("uid") or "") for row in sample_rows] recent_uids = [str(row["uid"]) for row in recent["rows"]] if ordered_uids != recent_uids: raise ValueError("recent result does not follow the frozen sample order") selected_samples = [row for row in sample_rows if str(row["uid"]) in selected_set] if [str(row["uid"]) for row in selected_samples] != selected: raise ValueError("selected UID ordering diverged") args.output_uids.parent.mkdir(parents=True, exist_ok=True) args.output_uids.write_text("\n".join(selected) + "\n", encoding="utf-8") args.output_samples.write_text( "".join( json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n" for row in selected_samples ), encoding="utf-8", ) atomic_write( args.output_audit, { "format": ( "streameva.internal_threshold_uid_selection.v0" if threshold is not None else "streameva.unlabeled_budget_uid_selection.v0" ), "status": "frozen_before_benchmark_temporal_inference", "benchmark": recent.get("benchmark"), "model_manifest_sha256": recent.get("model_manifest_sha256"), "threshold": threshold, "quantile": quantile, "empirical_margin_cutoff": cutoff, "threshold_audit": ( str(args.threshold.resolve()) if args.threshold is not None else None ), "threshold_audit_sha256": ( sha256_file(args.threshold) if args.threshold is not None else None ), "recent_result": str(args.recent.resolve()), "recent_result_sha256": sha256_file(args.recent), "samples_sha256": sha256_file(args.samples), "question_task_group_or_benchmark_router": False, "score_or_gold_fields_read_for_selection": False, "benchmark_identity_used_for_policy_parameters": False, "cohort_labels_read_for_selection": False, "total": len(audit_rows), "selected": len(selected), "selection_rate": len(selected) / len(audit_rows), "rows": audit_rows, }, ) print(json.dumps({"total": len(audit_rows), "selected": len(selected)}))
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091#!/usr/bin/env python3"""Audited full-parameter Qwen3-VL trainer for the pure-VLM backbone."""
from __future__ import annotations
import argparseimport inspectimport jsonimport mathimport osimport shutilfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Dict, List
import torchfrom PIL import Imagefrom torch.utils.data import Dataset, SequentialSampler
try: from transformers import ( AutoModelForImageTextToText, AutoProcessor, Trainer, TrainingArguments, set_seed, )except ModuleNotFoundError: AutoModelForImageTextToText = None AutoProcessor = None TrainingArguments = None set_seed = None
class Trainer: # type: ignore[no-redef] """Import-only fallback for dependency-light contract tests."""
pass
from viss_core.data_v0.trainer_adapter import ( infer_release_root, load_training_rows, normalize_messages,)class MediaSemanticDataset(Dataset): """Load only a sealed pure-semantic JSONL release."""
def __init__( self, path: Path, processor: Any, *, max_samples: int = 0, media_root: Path | None = None, development_unsealed_overlay: bool = False, ) -> None: self.development_unsealed_overlay = development_unsealed_overlay if development_unsealed_overlay: self.rows = [ json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip() ] else: self.rows = _load_training_rows(path) if max_samples > 0: self.rows = self.rows[:max_samples] self.processor = processor inferred_root = _infer_release_root(path) if development_unsealed_overlay: if media_root is None: raise RuntimeError("development overlay requires --media-root") self.media_root = media_root.resolve(strict=True) else: if inferred_root is None: raise RuntimeError("semantic release root could not be inferred") if media_root is not None and media_root.resolve() != inferred_root: raise RuntimeError("--media-root may not override sealed release media") self.media_root = inferred_root
def __len__(self) -> int: return len(self.rows)
def __getitem__(self, index: int) -> Dict[str, Any]: row = self.rows[index] raw_weight = row.get("sample_loss_weight") sample_loss_weight = float(1.0 if raw_weight is None else raw_weight) if not math.isfinite(sample_loss_weight) or sample_loss_weight <= 0: raise RuntimeError( "train-ready contract violated: " f"uid={row.get('uid') or f'row_{index}'} " f"sample_loss_weight={sample_loss_weight}" ) return { "uid": str(row.get("uid") or f"row_{index}"), "messages": ( _normalize_development_messages(row["messages"]) if self.development_unsealed_overlay else _normalize_messages(row["messages"], media_root=self.media_root) ), "sample_loss_weight": sample_loss_weight, }
@dataclassclass MediaSemanticCollator: processor: Any max_length: int
def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, torch.Tensor]: encoded = [] labels_list = [] weights_list = [] for feature in features: messages = feature["messages"] item = _encode_processor_item(self.processor, messages) if item["input_ids"].numel() > self.max_length: raise RuntimeError( f"train-ready contract violated: uid={feature['uid']} " f"tokens={item['input_ids'].numel()} max_length={self.max_length}" ) labels, loss_weights = _assistant_only_labels_and_weights( getattr(self.processor, "tokenizer", self.processor), item["input_ids"], messages, ) if not torch.any(labels != -100): raise RuntimeError( f"train-ready contract violated: uid={feature['uid']} " "has no assistant labels" ) encoded.append(item) labels_list.append(labels) weights_list.append(loss_weights)
tokenizer = getattr(self.processor, "tokenizer", self.processor) if tokenizer.pad_token_id is None: raise RuntimeError("tokenizer has no pad token") maximum = max(item["input_ids"].numel() for item in encoded) batch: Dict[str, list[torch.Tensor]] = { "input_ids": [], "attention_mask": [], "labels": [], "loss_weights": [], "sample_loss_weight": [], } pixel_values = [] image_grid_thw = [] for item, labels, loss_weights, feature in zip( encoded, labels_list, weights_list, features, strict=True ): pad = maximum - item["input_ids"].numel() batch["input_ids"].append( torch.nn.functional.pad( item["input_ids"], (0, pad), value=tokenizer.pad_token_id ) ) batch["attention_mask"].append( torch.nn.functional.pad(item["attention_mask"], (0, pad), value=0) ) batch["labels"].append( torch.nn.functional.pad(labels, (0, pad), value=-100) ) batch["loss_weights"].append( torch.nn.functional.pad(loss_weights, (0, pad), value=0.0) ) batch["sample_loss_weight"].append( torch.tensor( float(feature["sample_loss_weight"]), dtype=torch.float32 ) ) if "pixel_values" in item: pixel_values.append(item["pixel_values"]) if "image_grid_thw" in item: image_grid_thw.append(item["image_grid_thw"]) output = {key: torch.stack(value) for key, value in batch.items()} if pixel_values: output["pixel_values"] = torch.cat(pixel_values, dim=0) if image_grid_thw: output["image_grid_thw"] = torch.cat(image_grid_thw, dim=0) return output
def main() -> None: if any( value is None for value in ( AutoModelForImageTextToText, AutoProcessor, TrainingArguments, set_seed, ) ): raise RuntimeError( "training requires transformers; the dependency-light import path " "supports only data and loss-mask contract tests" ) parser = argparse.ArgumentParser( description="Full-parameter Qwen3-VL pure-semantic SFT." ) parser.add_argument("--model", type=Path, required=True) parser.add_argument("--train", type=Path, required=True) parser.add_argument("--val", type=Path) parser.add_argument("--media-root", type=Path) parser.add_argument("--val-media-root", type=Path) parser.add_argument( "--development-unsealed-overlay", action="store_true", help="Development only: read an unsealed JSONL overlay with absolute media paths.", ) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--max-length", type=int, default=8192) parser.add_argument("--max-pixels", type=int, default=0) parser.add_argument("--per-device-batch-size", type=int, default=1) parser.add_argument("--gradient-accumulation-steps", type=int, default=8) parser.add_argument("--epochs", type=float, default=1.0) parser.add_argument("--lr", type=float, default=1e-4) parser.add_argument( "--vision-projector-lr-scale", type=float, default=1.0, help=( "Multiply the optimizer learning rate for trainable visual " "merger/deepstack projector parameters." ), ) parser.add_argument( "--lr-scheduler-type", choices=("cosine", "constant_with_warmup"), default="cosine", ) parser.add_argument( "--train-order", choices=("shuffled", "sequential"), default="shuffled" ) parser.add_argument( "--stage-lr-plan", type=Path, help="Audited row-boundary learning-rate plan for one ordered run.", ) parser.add_argument("--warmup-ratio", type=float, default=0.03) parser.add_argument("--deepspeed", type=Path, required=True) parser.add_argument("--freeze-vision-tower", action="store_true") parser.add_argument("--train-vision-projector", action="store_true") parser.add_argument("--logging-steps", type=int, default=10) parser.add_argument("--save-steps", type=int, default=250) parser.add_argument("--save-total-limit", type=int, default=2) parser.add_argument("--skip-final-save", action="store_true") parser.add_argument("--max-train-samples", type=int, default=0) parser.add_argument("--max-val-samples", type=int, default=0) parser.add_argument("--max-steps", type=int, default=-1) parser.add_argument("--seed", type=int, default=42) parser.add_argument("--attn-implementation", default="flash_attention_2") parser.add_argument("--dataloader-num-workers", type=int, default=0) args = parser.parse_args()
if args.max_length <= 0 or args.max_pixels < 0: raise ValueError("length must be positive and max-pixels non-negative") if ( not math.isfinite(args.vision_projector_lr_scale) or args.vision_projector_lr_scale <= 0 ): raise ValueError("vision-projector-lr-scale must be finite and positive") if args.train_vision_projector and not args.freeze_vision_tower: raise ValueError("--train-vision-projector requires --freeze-vision-tower") if args.vision_projector_lr_scale != 1.0 and not args.train_vision_projector: raise ValueError( "a non-default vision-projector LR scale requires a trainable projector" ) if not args.deepspeed.is_file(): raise FileNotFoundError(args.deepspeed)
set_seed(args.seed) has_eval = args.val is not None and args.val.exists() training_args = _training_args(args, has_eval) processor = AutoProcessor.from_pretrained(args.model, trust_remote_code=True) _configure_processor_pixel_budget(processor, args.max_pixels) tokenizer = getattr(processor, "tokenizer", processor) if tokenizer.pad_token_id is None: tokenizer.pad_token = tokenizer.eos_token model = AutoModelForImageTextToText.from_pretrained( args.model, dtype=torch.bfloat16, trust_remote_code=True, attn_implementation=args.attn_implementation, ) model.config.use_cache = False model.gradient_checkpointing_enable() if args.freeze_vision_tower: model.visual.requires_grad_(False) if args.train_vision_projector: for name in ("merger", "deepstack_merger_list"): module = getattr(model.visual, name, None) if module is None: raise RuntimeError( f"Qwen3-VL visual module lacks projector component {name!r}" ) module.requires_grad_(True) _audit_trainable_parameters(model, args)
if _is_main_process(): trainable = sum( _logical_parameter_numel(parameter) for parameter in model.parameters() if parameter.requires_grad ) total = sum( _logical_parameter_numel(parameter) for parameter in model.parameters() ) if total <= 0: raise RuntimeError("could not determine logical parameter count") print( { "training_mode": "full_parameter_no_adapter", "vision_tower_frozen": args.freeze_vision_tower, "trainable_parameters": trainable, "total_parameters": total, "trainable_fraction": trainable / total, }, flush=True, )
train_dataset = MediaSemanticDataset( args.train, processor, max_samples=args.max_train_samples, media_root=args.media_root, development_unsealed_overlay=args.development_unsealed_overlay, ) global_batch = ( args.per_device_batch_size * args.gradient_accumulation_steps * int(os.environ.get("WORLD_SIZE", "1")) ) stage_lr_plan = ( _load_stage_lr_plan( args.stage_lr_plan, release_manifest=inferred_root_manifest(train_dataset.media_root), dataset_rows=len(train_dataset), global_batch=global_batch, optimizer_learning_rate=args.lr, warmup_ratio=args.warmup_ratio, ) if args.stage_lr_plan is not None else None ) eval_dataset = ( MediaSemanticDataset( args.val, processor, max_samples=args.max_val_samples, media_root=args.val_media_root, ) if has_eval else None ) trainer = SemanticTokenTrainer( model=model, args=training_args, train_dataset=train_dataset, eval_dataset=eval_dataset, data_collator=MediaSemanticCollator(processor, args.max_length), train_order=args.train_order, stage_lr_plan=stage_lr_plan, vision_projector_lr_scale=args.vision_projector_lr_scale, vision_projector_parameter_ids={ id(parameter) for name in ("merger", "deepstack_merger_list") for parameter in getattr(model.visual, name).parameters() } if args.train_vision_projector else set(), ) trainer.train() if args.skip_final_save: if _is_main_process(): print( { "output": str(args.output), "training_mode": "full_parameter_no_adapter", "final_model": None, "systems_smoke_skipped_final_save": True, }, flush=True, ) return _release_save_reserve() final_dir = args.output / "final_model" trainer.save_model(final_dir) processor.save_pretrained(final_dir) if _is_main_process(): print( { "output": str(args.output), "training_mode": "full_parameter_no_adapter", "final_model": str(final_dir), }, flush=True, )
def _release_save_reserve() -> None: raw = os.environ.get("STREAMEVA_SAVE_RESERVE_PATH") if raw and _is_main_process(): path = Path(raw).resolve() if ( path.name != "save_reserve.bin" or path.parent.parent != Path("/tmp") or not path.parent.name.startswith("streameva_") ): raise RuntimeError("save reserve path is outside the short runtime root") path.unlink(missing_ok=True) os.sync() print( { "save_reserve_released": str(path), "free_bytes": shutil.disk_usage(path.parent).free, }, flush=True, ) if torch.distributed.is_available() and torch.distributed.is_initialized(): torch.distributed.barrier()
def _audit_trainable_parameters(model: Any, args: argparse.Namespace) -> None: if not all( parameter.requires_grad for parameter in model.language_model.parameters() ): raise RuntimeError("full-parameter contract froze a language parameter") if not all(parameter.requires_grad for parameter in model.lm_head.parameters()): raise RuntimeError("full-parameter contract froze an LM-head parameter") if not args.freeze_vision_tower: return projector_ids: set[int] = set() if args.train_vision_projector: for name in ("merger", "deepstack_merger_list"): projector_ids.update( id(parameter) for parameter in getattr(model.visual, name).parameters() ) for parameter in model.visual.parameters(): if parameter.requires_grad != (id(parameter) in projector_ids): raise RuntimeError("frozen-vision/trainable-projector contract violated")
def _load_training_rows( path: Path, *, training_schema: str = "semantic") -> List[Dict[str, Any]]: if training_schema != "semantic": raise ValueError(f"unsupported training schema: {training_schema}") return load_training_rows(path)
def _normalize_development_messages(messages: Any) -> List[Dict[str, Any]]: """Normalize an explicit development overlay without weakening release loading.""" if not isinstance(messages, list): raise TypeError("development messages must be a list") roles = [message.get("role") for message in messages] if roles != ["user", "assistant"]: raise ValueError("development overlay accepts pure-VLM rows only") output: List[Dict[str, Any]] = [] for message in messages: content: List[Dict[str, Any]] = [] for item in message.get("content") or []: if item.get("type") == "text": content.append({"type": "text", "text": str(item.get("text") or "")}) continue if item.get("type") != "image" or message["role"] != "user": raise ValueError("development overlay contains unsupported content") image_path = Path(str(item.get("image") or "")) if not image_path.is_absolute() or not image_path.is_file(): raise RuntimeError("development overlay image must be an existing absolute path") content.append( {"type": "image", "image": Image.open(image_path).convert("RGB")} ) if not content: raise ValueError("development overlay message content is empty") output.append( { "role": str(message["role"]), "content": content, "loss": bool(message.get("loss")), } ) return output
def _infer_release_root( path: Path, *, training_schema: str = "semantic") -> Path | None: if training_schema != "semantic": raise ValueError(f"unsupported training schema: {training_schema}") return infer_release_root(path)
def _normalize_messages( messages: Any, *, media_root: Path | None = None, training_schema: str = "semantic",) -> List[Dict[str, Any]]: if training_schema != "semantic": raise ValueError(f"unsupported training schema: {training_schema}") return normalize_messages(messages, media_root=media_root)
def _load_images(messages: List[Dict[str, Any]]) -> List[Image.Image]: images = [] for message in messages: for item in message.get("content", []): if not isinstance(item, dict) or item.get("type") != "image": continue image = item.get("image") if isinstance(image, Image.Image): images.append(image) elif image: images.append(Image.open(image).convert("RGB")) return images
def _configure_processor_pixel_budget( processor: Any, max_pixels: int) -> Dict[str, int]: image_processor = getattr(processor, "image_processor", None) size = getattr(image_processor, "size", None) if image_processor is None or not isinstance(size, dict): raise RuntimeError("processor has no configurable image size contract") shortest = int(size.get("shortest_edge", 0)) longest = int(size.get("longest_edge", 0)) if shortest <= 0 or longest <= 0 or shortest > longest: raise RuntimeError("processor image size contract is invalid") requested = longest if max_pixels == 0 else int(max_pixels) if requested < shortest: raise ValueError(f"max_pixels={requested} is below shortest_edge={shortest}") image_processor.size = { "shortest_edge": shortest, "longest_edge": requested, } return dict(image_processor.size)
def _encode_processor_item( processor: Any, messages: List[Dict[str, Any]]) -> Dict[str, torch.Tensor]: rendered = processor.apply_chat_template( messages, tokenize=False, add_generation_prompt=False, ) images = _load_images(messages) if rendered.count("<|image_pad|>") != len(images): raise RuntimeError("chat-template image slots and message images differ") kwargs: Dict[str, Any] = { "text": rendered, "return_dict": True, "return_tensors": "pt", } if images: kwargs["images"] = images item = processor(**kwargs) return { key: ( value.squeeze(0) if hasattr(value, "dim") and value.dim() > 1 and key in {"input_ids", "attention_mask"} else value ) for key, value in item.items() }
def _locate_rendered_text_token_positions( tokenizer: Any, input_ids: torch.Tensor, messages: List[Dict[str, Any]],) -> Dict[tuple[int, int], List[int]] | None: """Align message text spans through chat rendering and visual expansion."""
if not hasattr(tokenizer, "apply_chat_template"): return None try: rendered = tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=False, ) encoded = tokenizer( rendered, add_special_tokens=False, return_offsets_mapping=True, ) except (KeyError, NotImplementedError, TypeError, ValueError): return None template_ids = encoded.get("input_ids") offsets = encoded.get("offset_mapping") if template_ids is None or offsets is None: return None if hasattr(template_ids, "tolist"): template_ids = template_ids.tolist() if hasattr(offsets, "tolist"): offsets = offsets.tolist() if template_ids and isinstance(template_ids[0], list): template_ids = template_ids[0] if offsets and isinstance(offsets[0][0], list): offsets = offsets[0]
actual_ids = input_ids.tolist() visual_pad_ids = { token_id for token in ("<|image_pad|>", "<|video_pad|>") for token_id in [tokenizer.convert_tokens_to_ids(token)] if isinstance(token_id, int) and token_id >= 0 } template_to_actual: Dict[int, int] = {} actual_index = 0 for template_index, token_id in enumerate(template_ids): if actual_index >= len(actual_ids) or actual_ids[actual_index] != token_id: raise RuntimeError("rendered template and processor input IDs diverged") template_to_actual[template_index] = actual_index actual_index += 1 if token_id in visual_pad_ids: while actual_index < len(actual_ids) and actual_ids[actual_index] == token_id: actual_index += 1 if actual_index != len(actual_ids): raise RuntimeError("processor input IDs contain non-template tokens")
output: Dict[tuple[int, int], List[int]] = {} character_cursor = 0 for message_index, message in enumerate(messages): text_items = [ item for item in message.get("content", []) if isinstance(item, dict) and item.get("type") == "text" ] for text_index, item in enumerate(text_items): text = str(item.get("text", "")) start = rendered.find(text, character_cursor) if start < 0: raise RuntimeError("message text is absent from the rendered template") end = start + len(text) positions = [ template_to_actual[index] for index, pair in enumerate(offsets) if int(pair[0]) < end and int(pair[1]) > start ] if text and not positions: raise RuntimeError("rendered message text has no token positions") output[(message_index, text_index)] = positions character_cursor = end return output
def _assistant_only_labels( tokenizer: Any, input_ids: torch.Tensor, messages: List[Dict[str, Any]],) -> torch.Tensor: labels, _ = _assistant_only_labels_and_weights(tokenizer, input_ids, messages) return labels
def _assistant_only_labels_and_weights( tokenizer: Any, input_ids: torch.Tensor, messages: List[Dict[str, Any]],) -> tuple[torch.Tensor, torch.Tensor]: """Supervise assistant semantic text and its turn terminator only."""
labels = torch.full_like(input_ids, -100) weights = torch.zeros_like(input_ids, dtype=torch.float32) ids = input_ids.tolist() cursor = 0 rendered_positions = _locate_rendered_text_token_positions( tokenizer, input_ids, messages ) for message_index, message in enumerate(messages): is_assistant = message.get("role") == "assistant" supervise = is_assistant and message.get("loss", True) is not False text_items = [ item for item in message.get("content", []) if isinstance(item, dict) and item.get("type") == "text" ] for text_index, item in enumerate(text_items): text = str(item.get("text", "")) if rendered_positions is not None: positions = rendered_positions[(message_index, text_index)] start = positions[0] if positions else cursor semantic_end = positions[-1] + 1 if positions else cursor else: target = tokenizer(text, add_special_tokens=False)["input_ids"] start = _find_subsequence(ids, target, cursor) if start < 0: raise RuntimeError("could not locate message text in role order") semantic_end = min(start + len(target), labels.numel()) end = semantic_end im_end_id = tokenizer.convert_tokens_to_ids("<|im_end|>") if ( is_assistant and text_index == len(text_items) - 1 and im_end_id is not None and end < labels.numel() and ids[end] == im_end_id ): end += 1 cursor = end if supervise: labels[start:end] = input_ids[start:end] weights[start:end] = 1.0 return labels, weights
def _find_subsequence(haystack: List[int], needle: List[int], start: int) -> int: if not needle: return -1 for index in range(max(start, 0), len(haystack) - len(needle) + 1): if haystack[index : index + len(needle)] == needle: return index return -1
def _split_optimizer_groups_for_projector( param_groups: list[dict[str, Any]], *, projector_parameter_ids: set[int], learning_rate_scale: float,) -> tuple[list[dict[str, Any]], int]: """Preserve group options while isolating/scaling projector parameters."""
replacement_groups: list[dict[str, Any]] = [] projector_parameters = 0 for original in param_groups: projector = [ parameter for parameter in original["params"] if id(parameter) in projector_parameter_ids ] backbone = [ parameter for parameter in original["params"] if id(parameter) not in projector_parameter_ids ] if backbone: group = dict(original) group["params"] = backbone replacement_groups.append(group) if projector: group = dict(original) group["params"] = projector group["lr"] = float(group["lr"]) * learning_rate_scale if "initial_lr" in group: group["initial_lr"] = ( float(group["initial_lr"]) * learning_rate_scale ) replacement_groups.append(group) projector_parameters += len(projector) return replacement_groups, projector_parameters
class SemanticTokenTrainer(Trainer): def __init__( self, *args: Any, train_order: str = "shuffled", stage_lr_plan: dict[str, Any] | None = None, vision_projector_lr_scale: float = 1.0, vision_projector_parameter_ids: set[int] | None = None, **kwargs: Any, ) -> None: if train_order not in {"shuffled", "sequential"}: raise ValueError("unsupported train order") if stage_lr_plan is not None and train_order != "sequential": raise ValueError("stage learning-rate plan requires sequential stage order") self.train_order = train_order self.stage_lr_plan = stage_lr_plan self.vision_projector_lr_scale = float(vision_projector_lr_scale) self.vision_projector_parameter_ids = set( vision_projector_parameter_ids or set() ) self._projector_lr_groups_applied = False if ( self.vision_projector_lr_scale != 1.0 and not self.vision_projector_parameter_ids ): raise ValueError("projector LR scaling requires projector parameters") super().__init__(*args, **kwargs)
def create_optimizer(self) -> Any: """Split Trainer's established decay groups and scale projector LR only."""
optimizer = super().create_optimizer() if self.vision_projector_lr_scale == 1.0: return optimizer if self._projector_lr_groups_applied: return optimizer if optimizer is None: raise RuntimeError("optimizer is absent while applying projector LR")
replacement_groups, projector_parameters = ( _split_optimizer_groups_for_projector( list(optimizer.param_groups), projector_parameter_ids=self.vision_projector_parameter_ids, learning_rate_scale=self.vision_projector_lr_scale, ) ) if projector_parameters != len(self.vision_projector_parameter_ids): raise RuntimeError( "optimizer projector parameter coverage diverged: " f"{projector_parameters} != " f"{len(self.vision_projector_parameter_ids)}" ) optimizer.param_groups[:] = replacement_groups self._projector_lr_groups_applied = True if _is_main_process(): print( { "optimizer_lr_policy": "split_visual_projector", "base_learning_rate": self.args.learning_rate, "vision_projector_lr_scale": self.vision_projector_lr_scale, "vision_projector_learning_rate": ( self.args.learning_rate * self.vision_projector_lr_scale ), "projector_parameter_tensors": projector_parameters, "optimizer_parameter_groups": len(replacement_groups), }, flush=True, ) return optimizer
def create_scheduler( self, num_training_steps: int, optimizer: Any = None ) -> Any: if self.stage_lr_plan is None: try: return super().create_scheduler(num_training_steps, optimizer) except TypeError: return super().create_scheduler(num_training_steps) if num_training_steps != int(self.stage_lr_plan["total_steps"]): raise RuntimeError( "stage LR plan and Trainer optimization steps diverged: " f"{self.stage_lr_plan['total_steps']} != {num_training_steps}" ) if self.lr_scheduler is None: active_optimizer = self.optimizer if optimizer is None else optimizer if active_optimizer is None: raise RuntimeError("optimizer is absent while creating stage scheduler") self.lr_scheduler = torch.optim.lr_scheduler.LambdaLR( active_optimizer, lr_lambda=lambda step: _stage_lr_multiplier( self.stage_lr_plan, int(step) ), ) return self.lr_scheduler
def _get_train_sampler(self, train_dataset: Any = None) -> Any: dataset = self.train_dataset if train_dataset is None else train_dataset if self.train_order == "sequential": return SequentialSampler(dataset) try: return super()._get_train_sampler(train_dataset) except TypeError: return super()._get_train_sampler()
def compute_loss( self, model: Any, inputs: Dict[str, Any], return_outputs: bool = False, num_items_in_batch: Any = None, ) -> Any: del num_items_in_batch labels = inputs.pop("labels") loss_weights = inputs.pop("loss_weights") sample_loss_weight = inputs.pop("sample_loss_weight").float() outputs = model(**inputs) shift_logits = outputs.logits[..., :-1, :] shift_labels = labels[..., 1:].contiguous() shift_weights = loss_weights[..., 1:].contiguous().float() loss = _sparse_weighted_token_loss( shift_logits, shift_labels, shift_weights, sample_loss_weight ) return (loss, outputs) if return_outputs else loss
def _sparse_weighted_token_loss( logits: torch.Tensor, labels: torch.Tensor, loss_weights: torch.Tensor, sample_loss_weight: torch.Tensor,) -> torch.Tensor: """Compute the same weighted CE without densifying every prompt token.
Qwen emits logits for the visual tokens, prompt and assistant answer, while the semantic SFT contract supervises only assistant answer positions. The previous implementation cast the complete ``batch x sequence x vocab`` tensor to fp32 and then discarded all ignored positions. Selecting active positions first is mathematically equivalent and avoids the transient 13--20 GiB allocation seen on long examples. """
if logits.ndim != 3 or labels.shape != logits.shape[:2]: raise RuntimeError("logits and labels do not align") if loss_weights.shape != labels.shape: raise RuntimeError("token loss weights do not align with labels") if sample_loss_weight.shape != (logits.shape[0],): raise RuntimeError("sample loss weights do not align with the batch")
active = labels.ne(-100) & loss_weights.gt(0) active_batch, _ = torch.nonzero(active, as_tuple=True) if active_batch.numel() == 0: raise RuntimeError("batch has no positively weighted assistant labels") active_logits = logits[active].float() active_labels = labels[active] active_weights = loss_weights[active].float() token_loss = torch.nn.functional.cross_entropy( active_logits, active_labels, reduction="none" ) numerator = torch.zeros( logits.shape[0], device=logits.device, dtype=torch.float32 ).scatter_add_(0, active_batch, token_loss * active_weights) denominator = torch.zeros_like(numerator).scatter_add_( 0, active_batch, active_weights ) per_sample_loss = numerator / denominator.clamp_min(1e-8) return (per_sample_loss * sample_loss_weight.float()).mean()
def inferred_root_manifest(release_root: Path) -> dict[str, Any]: path = release_root / "manifest.json" if not path.is_file(): raise RuntimeError("sealed release manifest is absent") return json.loads(path.read_text(encoding="utf-8"))
def _load_stage_lr_plan( path: Path, *, release_manifest: dict[str, Any], dataset_rows: int, global_batch: int, optimizer_learning_rate: float, warmup_ratio: float,) -> dict[str, Any]: """Validate and compile row boundaries into optimizer-step boundaries."""
raw = json.loads(path.read_text(encoding="utf-8")) if raw.get("format") != "iclr_video.stage_lr_plan.v1": raise RuntimeError("unsupported stage LR plan format") if int(raw.get("dataset_rows", -1)) != dataset_rows or global_batch <= 0: raise RuntimeError("stage LR plan dataset/global-batch contract diverged") if int(raw.get("global_batch", -1)) != global_batch: raise RuntimeError("stage LR plan global batch diverged") manifest_stages = (release_manifest.get("inputs") or {}).get( "curriculum_stages" ) stages = raw.get("stages") if not isinstance(stages, list) or not stages or not isinstance(manifest_stages, list): raise RuntimeError("stage LR plan or release stages are absent") if len(stages) != len(manifest_stages): raise RuntimeError("stage LR plan count diverged from release") compiled = [] previous_row = 0 previous_step = 0 maximum_lr = 0.0 for index, (stage, manifest_stage) in enumerate( zip(stages, manifest_stages, strict=True) ): end_row = int(stage.get("end_row_exclusive", -1)) learning_rate = float(stage.get("learning_rate", 0.0)) if ( int(stage.get("index", -1)) != index or int(manifest_stage.get("index", -1)) != index or str(stage.get("release_id")) != str(manifest_stage.get("release_id")) or end_row != int(manifest_stage.get("end_row_exclusive", -1)) or end_row <= previous_row or not math.isfinite(learning_rate) or learning_rate <= 0 ): raise RuntimeError("stage LR entry diverged from release manifest") end_step = math.ceil(end_row / global_batch) if end_step <= previous_step: raise RuntimeError("stage has no optimizer steps") stage_steps = end_step - previous_step warmup_steps = math.ceil(stage_steps * warmup_ratio) compiled.append( { "end_step_exclusive": end_step, "index": index, "learning_rate": learning_rate, "release_id": str(stage["release_id"]), "start_step": previous_step, "warmup_steps": warmup_steps, } ) maximum_lr = max(maximum_lr, learning_rate) previous_row = end_row previous_step = end_step if previous_row != dataset_rows: raise RuntimeError("stage LR plan does not cover the complete dataset") if not math.isclose( maximum_lr, optimizer_learning_rate, rel_tol=1e-9, abs_tol=0.0 ): raise RuntimeError("optimizer LR must equal the maximum stage LR") return { "base_learning_rate": optimizer_learning_rate, "format": raw["format"], "stages": compiled, "total_steps": previous_step, }
def _stage_lr_multiplier(plan: dict[str, Any], step: int) -> float: """Return a per-stage warmup/cosine multiplier for one optimizer step."""
base_lr = float(plan["base_learning_rate"]) for stage in plan["stages"]: start = int(stage["start_step"]) end = int(stage["end_step_exclusive"]) if step >= end: continue offset = max(step - start, 0) duration = end - start warmup = int(stage["warmup_steps"]) scale = float(stage["learning_rate"]) / base_lr if warmup > 0 and offset < warmup: return scale * (offset / warmup) decay_steps = max(duration - warmup, 1) progress = min(max((offset - warmup) / decay_steps, 0.0), 1.0) return scale * 0.5 * (1.0 + math.cos(math.pi * progress)) return 0.0
def _training_args(args: argparse.Namespace, has_eval: bool) -> Any: kwargs: Dict[str, Any] = { "output_dir": str(args.output), "num_train_epochs": args.epochs, "per_device_train_batch_size": args.per_device_batch_size, "gradient_accumulation_steps": args.gradient_accumulation_steps, "learning_rate": args.lr, "warmup_ratio": args.warmup_ratio, "bf16": True, "logging_steps": args.logging_steps, "save_steps": args.save_steps, "save_total_limit": args.save_total_limit, "max_steps": args.max_steps, "gradient_checkpointing": True, "lr_scheduler_type": args.lr_scheduler_type, "optim": "adamw_torch", "weight_decay": 0.0, "max_grad_norm": 1.0, "tf32": True, "save_only_model": True, "report_to": "none", "remove_unused_columns": False, "ddp_find_unused_parameters": False, "dataloader_num_workers": args.dataloader_num_workers, "dataloader_pin_memory": True, "seed": args.seed, "deepspeed": str(args.deepspeed), } signature = inspect.signature(TrainingArguments.__init__) if args.save_steps >= 999999 and "save_strategy" in signature.parameters: kwargs["save_strategy"] = "no" if args.dataloader_num_workers > 0: if "dataloader_persistent_workers" in signature.parameters: kwargs["dataloader_persistent_workers"] = True if "dataloader_prefetch_factor" in signature.parameters: kwargs["dataloader_prefetch_factor"] = 2 if "data_seed" in signature.parameters: kwargs["data_seed"] = args.seed evaluation_key = ( "eval_strategy" if "eval_strategy" in signature.parameters else "evaluation_strategy" ) kwargs[evaluation_key] = "steps" if has_eval else "no" if has_eval: kwargs["eval_steps"] = max(args.save_steps, args.logging_steps) return TrainingArguments(**kwargs)
def _is_main_process() -> bool: return int(os.environ.get("RANK", "0")) == 0
def _logical_parameter_numel(parameter: torch.nn.Parameter) -> int: return int(getattr(parameter, "ds_numel", parameter.numel()))
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980"""Official-protocol per-query correctness helpers for TVS analyses."""
from __future__ import annotations
import jsonimport refrom pathlib import Pathfrom typing import Any
OVO_FORWARD_TASKS = {"REC", "SSR", "CRR"}
def _mcq_letter(value: Any) -> str | None: text = str(value or "").strip() match = re.match(r"^[\(\[]?([A-D])(?:[\)\].:\s-]|$)", text, re.IGNORECASE) return match.group(1).upper() if match else None
def load_gold(benchmark: str, annotation: Path) -> dict[str, dict[str, Any]]: data = json.loads(annotation.read_text()) gold: dict[str, dict[str, Any]] = {} if benchmark == "streamingbench": for video_index, entry in enumerate(data): for question_index, question in enumerate(entry.get("questions") or []): uid = f"streaming_{video_index}_{question_index}" gold[uid] = { "kind": "streaming_mcq", "answer": str(question["answer"]), "task": str(question.get("task_type") or ""), } return gold if benchmark != "ovo": raise ValueError(f"unsupported benchmark: {benchmark}") for item in data: task = str(item.get("task") or "").upper() if task not in OVO_FORWARD_TASKS: uid = f"ovo_{item['id']}" gold[uid] = { "kind": "ovo_mcq", "answer": chr(ord("A") + int(item["gt"])), "task": task, } continue for index, test_info in enumerate(item.get("test_info") or []): uid = f"ovo_{item['id']}_{index}" if task == "REC": gold[uid] = { "kind": "ovo_rec", "answer": str(test_info["count"]), "task": task, } else: gold[uid] = { "kind": "ovo_binary", "answer": int(test_info["type"]), "task": task, } return gold
def is_correct(prediction: Any, gold: dict[str, Any]) -> bool: text = str(prediction or "") kind = gold["kind"] if kind == "streaming_mcq": letter = _mcq_letter(text) response = letter if letter is not None else text return response == str(gold["answer"]) if kind == "ovo_mcq": letter = _mcq_letter(text) response = letter if letter is not None else text return str(gold["answer"]) in response if kind == "ovo_rec": return "".join(re.findall(r"\d+", text)) == str(gold["answer"]) if kind == "ovo_binary": positive = int(gold["answer"]) == 1 if (text == "Y" and positive) or (text == "N" and not positive): return True return ("Yes" if positive else "No") in text raise ValueError(f"unknown gold kind: {kind}")1234567891011121314151617181920212223242526272829303132[build-system]requires = ["setuptools>=61", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "viss-code"version = "0.3.1"description = "Visible-State Supervision and Test-Time Causal View Search"readme = "README.md"requires-python = ">=3.10"license = {file = "LICENSE"}dependencies = ["numpy>=1.24,<3", "Pillow>=10,<12"]
[project.optional-dependencies]test = ["pytest>=8,<10", "torch>=2.7,<3"]inference = [ "torch==2.7.0", "transformers==4.57.3", "accelerate==1.8.1", "qwen-vl-utils>=0.0.11,<0.1", "decord==0.6.0",]training = ["deepspeed>=0.16,<0.18"]
[tool.setuptools.packages.find]where = ["."]include = ["viss_core*", "experiments*", "data_pipeline*", "scripts*"]namespaces = true
[tool.pytest.ini_options]testpaths = ["tests"]pythonpath = ["."]1"""Version-neutral command-line helpers for the Data V0 release."""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""Bind the public protocol template to the user's own evaluation assets."""
from __future__ import annotations
import argparseimport jsonfrom pathlib import Path
from experiments.evaluate_qwen3vl_recent4_full import ( sha256_file, validate_processor_contract,)
def configure( *, template: Path, streaming_samples: Path, ovo_samples: Path, processor_config: Path, output: Path,) -> None: protocol = json.loads(template.read_text(encoding="utf-8")) for benchmark, path in ( ("streamingbench", streaming_samples), ("ovo", ovo_samples), ): path = path.resolve(strict=True) protocol["benchmarks"][benchmark]["export"] = str(path) protocol["benchmarks"][benchmark]["export_sha256"] = sha256_file(path) processor_config = processor_config.resolve(strict=True) if processor_config.name != "preprocessor_config.json": raise ValueError("Pass the processor's preprocessor_config.json") protocol["inference"]["processor_contract"]["preprocessor_config_sha256"] = ( sha256_file(processor_config) ) validate_processor_contract(processor_config.parent, protocol) protocol["status"] = "locked" output.parent.mkdir(parents=True, exist_ok=True) with output.open("x", encoding="utf-8") as handle: json.dump(protocol, handle, indent=2) handle.write("\n")
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--template", type=Path, default=Path("configs/evaluation/recent4.example.json"), ) parser.add_argument("--streaming-samples", type=Path, required=True) parser.add_argument("--ovo-samples", type=Path, required=True) parser.add_argument("--processor-config", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() configure(**vars(args)) print(f"Created local evaluation protocol: {args.output}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483#!/usr/bin/env python3"""Merge disjoint agent-evaluation shards into canonical official UID order."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport osfrom collections import defaultdictfrom pathlib import Pathfrom statistics import fmeanfrom typing import Any
IDENTITY_FIELDS = ( "format", "classification", "benchmark_selected", "source_policy_gate_admitted", "schema_version", "benchmark", "model", "model_config_sha256", "model_manifest_sha256", "processor", "processor_sha256", "processor_contract", "controller_processor", "controller_processor_sha256", "answer_processor", "answer_processor_contract", "processor_geometry", "adapter", "evaluator", "evaluation_protocol", "evaluation_protocol_sha256", "protocol_validation", "policy_hash", "policy_head", "policy_head_sha256", "policy_report_sha256", "policy_calibration_sha256", "global_action_threshold", "policy_inputs", "budget", "policy_training_report", "one_shared_commit_policy", "benchmark_task_or_group_router", "question_keyword_router", "answer_space_router", "gold_answer_available_to_commit_policy", "commit_policy", "unparseable_or_error_policy", "maximum_unique_frames", "direct_prediction_cache", "direct_prediction_cache_sha256", "source_gate", "source_gate_sha256", "global_action_thresholds", "acquisition_identity", "action_abi_schema_sha256", "inference_policy_hash", "inference_policy", "policy_config", "comparable_under_locked_recent4_protocol", "generation_config", "execution_optimization", "system_prompt_sha256", "prompt_contract_sha256", "launch_marker", "launch_marker_sha256", "annotation", "annotation_sha256", "samples", "samples_sha256", "runner_sha256", "software", "policy", "identity_hash", "protocol_sha256", "evaluator_sha256", "generation",)
def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for block in iter(lambda: handle.read(8 << 20), b""): digest.update(block) return digest.hexdigest()
def load_expected_uids(path: Path) -> list[str]: uids: list[str] = [] for line_number, line in enumerate( path.read_text(encoding="utf-8").splitlines(), start=1 ): if not line.strip(): continue uid = str(json.loads(line).get("uid") or "") if not uid: raise ValueError(f"{path}:{line_number} has no uid") uids.append(uid) if len(uids) != len(set(uids)): raise ValueError(f"{path} contains duplicate uids") return uids
def grouped_accuracy(rows: list[dict[str, Any]], field: str) -> dict[str, Any]: grouped: dict[str, list[dict[str, Any]]] = defaultdict(list) for row in rows: grouped[str(row.get(field) or "unknown")].append(row) result: dict[str, Any] = {} for name in sorted(grouped): group_rows = grouped[name] correct = sum(int(row.get("correct") or 0) for row in group_rows) total = len(group_rows) result[name] = { "accuracy": correct / total if total else 0.0, "correct": correct, "total": total, } return result
def aggregate_score( score_rows: list[dict[str, Any]], benchmark: str) -> dict[str, Any]: correct = sum(int(row.get("correct") or 0) for row in score_rows) total = len(score_rows) by_task = grouped_accuracy(score_rows, "task") by_group = grouped_accuracy(score_rows, "group") score: dict[str, Any] = { "accuracy": correct / total if total else 0.0, "by_group": by_group, "by_task": by_task, "num_queries": total, "rows": score_rows, } if benchmark == "ovo": tasks_by_group: dict[str, set[str]] = defaultdict(set) for row in score_rows: tasks_by_group[str(row.get("group") or "unknown")].add( str(row.get("task") or "unknown") ) official_groups: dict[str, Any] = {} for group in sorted(tasks_by_group): task_names = sorted(tasks_by_group[group]) official_groups[group] = { "accuracy": fmean(by_task[name]["accuracy"] for name in task_names), "num_tasks": len(task_names), } score["ovo_official"] = { "accuracy": fmean( value["accuracy"] for value in official_groups.values() ), "by_group": official_groups, } return score
def aggregate_efficiency(rows: list[dict[str, Any]]) -> dict[str, float]: def mean(field: str, *fallbacks: str) -> float: def value(row: dict[str, Any]) -> float: for name in (field, *fallbacks): if row.get(name) is not None: return float(row[name]) return 0.0
return fmean(value(row) for row in rows) if rows else 0.0
result = { "avg_frames_observed": mean( "frames_observed", "unique_frames_acquired", "unique_frames" ), "avg_model_processed_frames": mean( "model_processed_frames", "processed_frames" ), "avg_media_calls": mean("media_calls"), "avg_total_tokens": ( mean("total_tokens") if any(row.get("total_tokens") is not None for row in rows) else mean("input_tokens") + mean("output_tokens") ), "avg_turns": mean("num_turns"), } if any(row.get("commit_latency_seconds") is not None for row in rows): result["avg_commit_latency_seconds"] = mean("commit_latency_seconds") if any(row.get("commit_visual_tokens") is not None for row in rows): result["avg_commit_visual_tokens"] = mean("commit_visual_tokens") if any(row.get("latency_seconds") is not None for row in rows): result["avg_latency_seconds"] = mean("latency_seconds") return result
def aggregate_agent_behavior(rows: list[dict[str, Any]]) -> dict[str, Any]: terminal_counts: dict[str, int] = defaultdict(int) for row in rows: terminal_counts[str(row.get("policy_terminal_event") or "unknown")] += 1 total = len(rows) failures = sum( terminal_counts[event] for event in ("malformed_action", "illegal_observe", "missing_answer") ) return { "terminal_counts": dict(sorted(terminal_counts.items())), "num_policy_failures": failures, "strict_terminal_answer_rate": ( terminal_counts["answered"] / total if total else 0.0 ), "malformed_action_rate": ( terminal_counts["malformed_action"] / total if total else 0.0 ), "illegal_observe_rate": ( terminal_counts["illegal_observe"] / total if total else 0.0 ), "missing_answer_rate": ( terminal_counts["missing_answer"] / total if total else 0.0 ), }
def aggregate_execution_statistics( shard_statistics: list[dict[str, Any]],) -> dict[str, Any]: """Sum disjoint-shard cache counters and per-row stage timings."""
counter_fields = ( "decode_window_cache_hits", "decode_window_cache_misses", "decode_window_singleflight_hits", "temporal_budget_cache_hits", "temporal_budget_cache_misses", "video_reader_cache_hits", "video_reader_cache_misses", "stage_timing_samples", ) stage_totals: dict[str, float] = defaultdict(float) result = { field: sum(int(stats.get(field) or 0) for stats in shard_statistics) for field in counter_fields } for stats in shard_statistics: for name, seconds in (stats.get("stage_seconds_total") or {}).items(): stage_totals[str(name)] += float(seconds or 0.0) result["stage_seconds_total"] = { name: round(seconds, 6) for name, seconds in sorted(stage_totals.items()) } return result
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--inputs", nargs="+", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--expected-count", type=int, default=-1) parser.add_argument( "--expected-uids", type=Path, help="Official JSONL export whose UID order becomes the canonical order.", ) args = parser.parse_args()
rows_by_uid: dict[str, dict[str, Any]] = {} score_by_uid: dict[str, dict[str, Any]] = {} seen_in: dict[str, str] = {} metadata: list[dict[str, Any]] = [] execution_statistics: list[dict[str, Any]] = [] row_repairs: list[dict[str, Any]] = [] identity: dict[str, Any] | None = None benchmark: str | None = None
for path in args.inputs: data = json.loads(path.read_text(encoding="utf-8")) # A sharded run intentionally records a different ``samples`` JSONL # path (and therefore a different samples hash) in every shard. When # a frozen full-export is supplied via --expected-uids, that export is # the canonical merged sample manifest; all other identity fields # must still match exactly. comparable_identity_fields = tuple( field for field in IDENTITY_FIELDS if args.expected_uids is None or field not in {"samples", "samples_sha256"} ) current_identity = { field: data.get(field) for field in comparable_identity_fields } if identity is None: identity = current_identity benchmark = str(data.get("benchmark") or "") or None elif current_identity != identity: changed = [ field for field in comparable_identity_fields if current_identity.get(field) != identity.get(field) ] # Annotation files are frequently remounted from a volatile # location (for example /dev/shm) to persistent storage when an # evaluation is resumed. The absolute path is not part of the # benchmark identity when both shards carry the same non-empty # content hash. Keep the hash itself in the frozen identity so # different annotation contents remain a hard failure. if ( "annotation" in changed and current_identity.get("annotation_sha256") and current_identity.get("annotation_sha256") == identity.get("annotation_sha256") ): changed.remove("annotation") if not changed: current_identity = identity else: raise ValueError( f"{path} does not match the frozen shard identity: {changed}" ) shard_rows = data.get("rows") if not isinstance(shard_rows, list): raise ValueError(f"{path} has no rows list") for row in shard_rows: uid = str(row.get("uid") or "") if not uid: raise ValueError(f"{path} contains a row without uid") if uid in rows_by_uid: raise ValueError(f"duplicate uid {uid!r} in {seen_in[uid]} and {path}") rows_by_uid[uid] = row seen_in[uid] = str(path) row_benchmark = str(row.get("benchmark") or "") if row_benchmark: if benchmark is None: benchmark = row_benchmark elif row_benchmark != benchmark: raise ValueError( f"mixed benchmarks in shards: {benchmark!r} and {row_benchmark!r}" ) shard_score_rows = (data.get("score") or {}).get("rows") or [] if not isinstance(shard_score_rows, list): raise ValueError(f"{path} score.rows is not a list") for score_row in shard_score_rows: uid = str(score_row.get("query_id") or "") if not uid: raise ValueError(f"{path} contains a score row without query_id") if uid in score_by_uid: raise ValueError(f"duplicate score query_id {uid!r}") score_by_uid[uid] = score_row metadata.append( { "path": str(path), "sha256": sha256(path), "num_samples": len(shard_rows), "sample_slice": data.get("sample_slice"), "samples": data.get("samples"), "samples_sha256": data.get("samples_sha256"), "annotation": data.get("annotation"), "annotation_sha256": data.get("annotation_sha256"), } ) if isinstance(data.get("execution_statistics"), dict): execution_statistics.append(data["execution_statistics"]) row_repairs.extend(data.get("row_repairs") or [])
if args.expected_count >= 0 and len(rows_by_uid) != args.expected_count: raise ValueError( f"merged {len(rows_by_uid)} rows, expected {args.expected_count}" )
expected_uids = ( load_expected_uids(args.expected_uids) if args.expected_uids is not None else list(rows_by_uid) ) expected_set = set(expected_uids) actual_set = set(rows_by_uid) if actual_set != expected_set: missing = [uid for uid in expected_uids if uid not in actual_set] extra = sorted(actual_set - expected_set) raise ValueError( f"official UID mismatch: missing={missing[:20]} extra={extra[:20]}" ) if set(score_by_uid) != expected_set: missing = [uid for uid in expected_uids if uid not in score_by_uid] extra = sorted(set(score_by_uid) - expected_set) raise ValueError( f"score UID mismatch: missing={missing[:20]} extra={extra[:20]}" )
rows = [rows_by_uid[uid] for uid in expected_uids] score_rows = [score_by_uid[uid] for uid in expected_uids] empty_predictions = [ str(row.get("uid")) for row in rows if not str(row.get("prediction") or "").strip() ] errors = [ row for row in rows if row.get("error") or row.get("commit_error") ] merged_identity = dict(identity or {}) if args.expected_uids is not None: merged_identity["samples"] = str(args.expected_uids) merged_identity["samples_sha256"] = sha256(args.expected_uids) result = { "benchmark": benchmark, **merged_identity, "canonical_official_uid_order": args.expected_uids is not None, "efficiency": aggregate_efficiency(rows), "empty_prediction_uids": empty_predictions, "num_empty_predictions": len(empty_predictions), "num_errors": len(errors), "num_future_frame_violations": sum( bool(row.get("future_frame_violation")) for row in rows ), "num_samples": len(rows), "strict_terminal_answer_rate": ( sum(bool(row.get("strict_terminal_answer")) for row in rows) / len(rows) if rows else 0.0 ), "score": aggregate_score(score_rows, benchmark or ""), "row_repairs": row_repairs, "source_shards": metadata, "expected_uid_source": ( { "path": str(args.expected_uids), "sha256": sha256(args.expected_uids), } if args.expected_uids is not None else None ), "rows": rows, } if execution_statistics: result["execution_statistics"] = aggregate_execution_statistics( execution_statistics ) if any("policy_terminal_event" in row for row in rows): result["agent_behavior"] = aggregate_agent_behavior(rows) result["strict_terminal_answer_rate"] = result["agent_behavior"][ "strict_terminal_answer_rate" ] if any("commit_action" in row for row in rows): result.update( { "num_commit_errors": sum( bool(row.get("commit_error")) for row in rows ), "num_unparsed": sum( row.get("commit_parsed") is False for row in rows ), "decision_counts": { action: sum(row.get("commit_action") == action for row in rows) for action in ( "not_applicable", "unchanged", "retain", "commit", ) }, } ) args.output.parent.mkdir(parents=True, exist_ok=True) temporary = args.output.with_suffix(args.output.suffix + f".tmp.{os.getpid()}") temporary.write_text( json.dumps(result, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8", ) temporary.replace(args.output) print( json.dumps( { "output": str(args.output), "num_samples": len(rows), "num_errors": len(errors), "num_empty_predictions": len(empty_predictions), "canonical_official_uid_order": args.expected_uids is not None, }, sort_keys=True, ) )
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380#!/usr/bin/env bashset -euo pipefail
# Run one half of the locked recent4_full_v1 evaluation. Two independent# invocations may therefore evaluate StreamingBench and OVO concurrently on# disjoint GPU sets while retaining the exact common runner and official# scorers used by the serial baseline launcher.
if [[ $# -ne 8 ]]; then echo "usage: $0 REPO MODEL MODEL_MANIFEST OUTPUT PYTHON BENCHMARK GPU_CSV MODEL_ID" >&2 exit 2fi
REPO=$1MODEL=$2MODEL_MANIFEST=$3OUTPUT=$4PYTHON=$5BENCHMARK=$6GPU_CSV=$7MODEL_ID=$8PROCESSOR=${STREAMEVA_PROCESSOR:-$MODEL}EVAL_BATCH_SIZE=${STREAMEVA_EVAL_BATCH_SIZE:-16}DECODE_PREFETCH_BATCHES=${STREAMEVA_DECODE_PREFETCH_BATCHES:-2}FLUSH_EVERY_BATCHES=${STREAMEVA_EVAL_FLUSH_EVERY_BATCHES:-16}RECORD_CHOICE_CONFIDENCE=${STREAMEVA_RECORD_CHOICE_CONFIDENCE:-1}FRAME_POLICY=${STREAMEVA_FRAME_POLICY:-recent4}VISUAL_INPUT_MODE=${STREAMEVA_VISUAL_INPUT_MODE:-image-list}ALLOW_SHARED_GPU=${STREAMEVA_ALLOW_SHARED_GPU:-0}MIN_FREE_MIB=${STREAMEVA_MIN_FREE_MIB:-35840}PROTOCOL=$REPO/configs/evaluation/recent4_full_v1.jsonRUNNER=${STREAMEVA_EVALUATOR_ENTRYPOINT:-$REPO/experiments/evaluate_qwen3vl_recent4_full.py}MODEL_IDENTITY_SHA256=${STREAMEVA_MODEL_IDENTITY_SHA256:-}
# Keep non-login tmux jobs aligned with the CUDA wheel runtime used by# training. In particular, libcusparse from the wheel requires the matching# bundled nvJitLink library to precede system CUDA libraries.PYTHON_SITE=$($PYTHON -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])')NVIDIA_LIB_DIRS=$(find "$PYTHON_SITE/nvidia" -mindepth 2 -maxdepth 2 \ -type d -name lib -print 2>/dev/null | LC_ALL=C sort | paste -sd: -)if [[ -n $NVIDIA_LIB_DIRS ]]; then export LD_LIBRARY_PATH="$NVIDIA_LIB_DIRS${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"fi[[ $EVAL_BATCH_SIZE =~ ^[1-9][0-9]*$ ]][[ $DECODE_PREFETCH_BATCHES =~ ^[0-9]+$ ]][[ $FLUSH_EVERY_BATCHES =~ ^[1-9][0-9]*$ ]][[ $RECORD_CHOICE_CONFIDENCE =~ ^[01]$ ]][[ $FRAME_POLICY =~ ^(recent4|wide8|wide12|wide16|prefix8|prefix16|prefix32|prefix64|causalbudget20)$ ]][[ $VISUAL_INPUT_MODE =~ ^(image-list|native-video|hybrid-history-video-recent-images)$ ]][[ $ALLOW_SHARED_GPU =~ ^[01]$ ]][[ $MIN_FREE_MIB =~ ^[1-9][0-9]*$ ]]
case "$BENCHMARK" in streamingbench) ANNOTATION=${STREAM_ANNOTATION:?Set STREAM_ANNOTATION to the StreamingBench annotation file} SAMPLES=${STREAM_SAMPLES:?Set STREAM_SAMPLES to the frozen StreamingBench query export} VIDEO_ROOT=${STREAM_VIDEO_ROOT:?Set STREAM_VIDEO_ROOT to authorized benchmark media} OFFICIAL_ROOT=${STREAM_OFFICIAL_ROOT:?Set STREAM_OFFICIAL_ROOT to the official scorer} EXPECTED=2495 SMOKE_UIDS=(streaming_0_0 streaming_8_0 streaming_61_4) ;; ovo) OVO_ROOT=${OVO_ROOT:?Set OVO_ROOT to authorized OVO runtime assets} ANNOTATION=${OVO_ANNOTATION:-$OVO_ROOT/data/ovo_bench_new.json} OVO_RUNTIME_REPORT=${OVO_RUNTIME_REPORT:-$OVO_ROOT/data/runtime_assets.json} SAMPLES=${OVO_SAMPLES:?Set OVO_SAMPLES to the frozen OVO query export} VIDEO_ROOT=${OVO_VIDEO_ROOT:-$OVO_ROOT} OFFICIAL_ROOT=${OVO_OFFICIAL_ROOT:-$OVO_ROOT} EXPECTED=3035 SMOKE_UIDS=(ovo_0 ovo_1117 ovo_1468_0 ovo_1516_0 ovo_1558_0) ;; *) echo "BENCHMARK must be streamingbench or ovo" >&2; exit 2 ;;esac
IFS=, read -r -a GPUS <<<"$GPU_CSV"[[ ${#GPUS[@]} -gt 0 ]] || exit 2declare -A SEEN=()for gpu in "${GPUS[@]}"; do [[ $gpu =~ ^[0-7]$ || $gpu =~ ^GPU-[0-9A-Fa-f-]{36}$ ]] || { echo "GPU_CSV must contain local indices or GPU UUIDs" >&2 exit 2 } if [[ -n ${SEEN[$gpu]:-} && $ALLOW_SHARED_GPU -eq 0 ]]; then echo "GPU_CSV may repeat an index only with STREAMEVA_ALLOW_SHARED_GPU=1" >&2 exit 2 fi SEEN[$gpu]=1done[[ $MODEL_ID =~ ^[A-Za-z0-9._-]+$ ]] || exit 2for path in "$MODEL/config.json" \ "$PROCESSOR/preprocessor_config.json" "$PROTOCOL" "$RUNNER" \ "$ANNOTATION" "$SAMPLES" "$VIDEO_ROOT" "$OFFICIAL_ROOT"; do test -e "$path"doneif [[ $MODEL_MANIFEST == none ]]; then [[ $MODEL_IDENTITY_SHA256 =~ ^[0-9a-f]{64}$ ]] || { echo "manifest-free evaluation requires STREAMEVA_MODEL_IDENTITY_SHA256" >&2 exit 2 } MODEL_IDENTITY_ARGS=(--model-identity-sha256 "$MODEL_IDENTITY_SHA256")else test -s "$MODEL_MANIFEST" MODEL_IDENTITY_ARGS=(--model-manifest "$MODEL_MANIFEST")fiif [[ $BENCHMARK == ovo ]]; then test -s "$OVO_RUNTIME_REPORT" ANNOTATION_SHA256=$(sha256sum "$ANNOTATION" | cut -d' ' -f1) FROZEN_EXPORT_SHA256=$(sha256sum "$SAMPLES" | cut -d' ' -f1) jq -e --arg annotation_sha256 "$ANNOTATION_SHA256" \ --arg frozen_export_sha256 "$FROZEN_EXPORT_SHA256" ' .status == "pass" and .expanded_queries == 3035 and .covered_queries == 3035 and .coverage == 1 and .missing_videos == 0 and .annotation_sha256 == $annotation_sha256 and .frozen_export_sha256 == $frozen_export_sha256 ' "$OVO_RUNTIME_REPORT" >/dev/nullfitest -x "$PYTHON"export PYTHONPATH=$REPO${PYTHONPATH:+:$PYTHONPATH}
if [[ ${PREFLIGHT_ONLY:-0} == 1 ]]; then "$PYTHON" -c 'import PIL, qwen_vl_utils, torch, transformers' printf '{"status":"cpu_preflight_pass","benchmark":"%s","protocol":"recent4_full_v1","batch_size":%s,"decode_prefetch_batches":%s}\n' \ "$BENCHMARK" "$EVAL_BATCH_SIZE" "$DECODE_PREFETCH_BATCHES" exit 0fi
mkdir -p "$OUTPUT/logs" "$OUTPUT/$BENCHMARK"if [[ -e $OUTPUT/$BENCHMARK/complete ]]; then echo "$BENCHMARK is already complete" exit 0fiif [[ $MODEL_MANIFEST == none ]]; then :elif [[ -n ${PREVERIFIED_MODEL_MANIFEST_SHA256:-} ]]; then [[ $PREVERIFIED_MODEL_MANIFEST_SHA256 =~ ^[0-9a-f]{64}$ ]] || exit 2 [[ $(sha256sum "$MODEL_MANIFEST" | cut -d' ' -f1) == \ "$PREVERIFIED_MODEL_MANIFEST_SHA256" ]] || { echo "preverified model manifest hash mismatch" >&2 exit 3 }else (cd "$MODEL" && sha256sum --quiet -c SHA256SUMS)fiif [[ $MODEL_MANIFEST != none ]]; then MODEL_IDENTITY_SHA256=$(sha256sum "$MODEL_MANIFEST" | cut -d' ' -f1)fi"$PYTHON" "$REPO/scripts/validate_evaluation_protocol.py" --protocol "$PROTOCOL" \ >"$OUTPUT/$BENCHMARK/protocol_validation.json"
wait_gpu_free() { local gpu=$1 pids used free while true; do pids=$(nvidia-smi -i "$gpu" --query-compute-apps=pid \ --format=csv,noheader,nounits 2>/dev/null | tr -d '[:space:]') used=$(nvidia-smi -i "$gpu" --query-gpu=memory.used \ --format=csv,noheader,nounits 2>/dev/null | tr -d '[:space:]') free=$(nvidia-smi -i "$gpu" --query-gpu=memory.free \ --format=csv,noheader,nounits 2>/dev/null | tr -d '[:space:]') if [[ $ALLOW_SHARED_GPU -eq 0 ]]; then if [[ -z $pids && ${used:-999999} -le 16 ]]; then return 0; fi elif [[ ${free:-0} -ge $MIN_FREE_MIB ]]; then return 0 fi echo "$(date -u +%FT%TZ) waiting for GPU $gpu (used=${used:-unknown} MiB free=${free:-unknown} MiB shared=$ALLOW_SHARED_GPU minimum_free=$MIN_FREE_MIB MiB)" sleep 20 done}
validate_result() { "$PYTHON" - "$1" "$2" "$FRAME_POLICY" "$VISUAL_INPUT_MODE" "$RECORD_CHOICE_CONFIDENCE" <<'PY'import json, sysx = json.load(open(sys.argv[1], encoding="utf-8"))assert x["evaluation_protocol"] == "recent4_full_v1"assert x["num_samples"] == int(sys.argv[2])assert x["num_errors"] == 0assert all(str(row.get("prediction") or "").strip() for row in x["rows"])requested_policy = sys.argv[3]visual_input_mode = sys.argv[4]record_choice_confidence = bool(int(sys.argv[5]))assert x["processor_geometry"]["visual_input_mode"] == visual_input_modeassert x["comparable_under_locked_recent4_protocol"] == ( requested_policy == "recent4" and visual_input_mode == "image-list")for row in x["rows"]: sampling = row["sampling"] if requested_policy == "prefix8": assert sampling["num_sampled_frames"] == 8 elif requested_policy == "prefix16": assert sampling["num_sampled_frames"] == 16 elif requested_policy == "prefix32": assert sampling["num_sampled_frames"] == 32 elif requested_policy == "prefix64": assert sampling["num_sampled_frames"] == 64 elif requested_policy == "causalbudget20": assert 1 <= sampling["num_sampled_frames"] <= 20 assert sampling["controller"]["benchmark_task_or_group_router"] is False assert sampling["controller"]["future_frame_violations"] == 0 else: assert sampling["num_sampled_frames"] == 4 assert max(sampling["frame_timestamps"]) <= row["query_time"] + 1e-3 assert row["visual_input_mode"] == visual_input_mode assert bool(row.get("generation_confidence")) == record_choice_confidence assert bool(row["video_grid_thw"]) == ( visual_input_mode in {"native-video", "hybrid-history-video-recent-images"} and bool(row.get("native_video_metadata")) )PY}
CONFIDENCE_ARGS=()if [[ $RECORD_CHOICE_CONFIDENCE -eq 1 ]]; then CONFIDENCE_ARGS+=(--record-choice-confidence)fi
SMOKE_OUTPUT=$OUTPUT/$BENCHMARK/smoke.jsonif ! test -s "$SMOKE_OUTPUT" \ || ! validate_result "$SMOKE_OUTPUT" "${#SMOKE_UIDS[@]}"; then wait_gpu_free "${GPUS[0]}" smoke_batch=$EVAL_BATCH_SIZE smoke_rc=1 for smoke_attempt in 1 2 3; do smoke_rc=0 CUDA_VISIBLE_DEVICES=${GPUS[0]} PYTHONPATH=$REPO PYTHONUNBUFFERED=1 \ TOKENIZERS_PARALLELISM=false OMP_NUM_THREADS=1 \ PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \ "$PYTHON" "$RUNNER" --benchmark "$BENCHMARK" \ --annotation "$ANNOTATION" --samples "$SAMPLES" \ --video-root "$VIDEO_ROOT" --model "$MODEL" --processor "$PROCESSOR" \ "${MODEL_IDENTITY_ARGS[@]}" --protocol "$PROTOCOL" \ --output "$SMOKE_OUTPUT" --uids "${SMOKE_UIDS[@]}" \ --frame-policy "$FRAME_POLICY" \ --visual-input-mode "$VISUAL_INPUT_MODE" \ --batch-size "$smoke_batch" \ --decode-prefetch-batches "$DECODE_PREFETCH_BATCHES" \ --flush-every-batches "$FLUSH_EVERY_BATCHES" \ "${CONFIDENCE_ARGS[@]}" \ --resume --retry-errors >>"$OUTPUT/logs/${BENCHMARK}_smoke.log" 2>&1 || smoke_rc=$? if validate_result "$SMOKE_OUTPUT" "${#SMOKE_UIDS[@]}"; then break; fi echo "warning: $BENCHMARK smoke attempt=$smoke_attempt batch=$smoke_batch failed rc=$smoke_rc" >&2 if (( smoke_batch > 1 )); then smoke_batch=$(( (smoke_batch + 1) / 2 )); fi done if validate_result "$SMOKE_OUTPUT" "${#SMOKE_UIDS[@]}"; then if [[ $smoke_rc -ne 0 ]]; then echo "warning: $BENCHMARK smoke exited rc=$smoke_rc after writing a complete validated result" >&2 fi else echo "$BENCHMARK smoke failed validation after runner rc=$smoke_rc" >&2 if [[ $smoke_rc -eq 0 ]]; then smoke_rc=1; fi exit "$smoke_rc" fifi
SHARD_UID_ROOT=$OUTPUT/$BENCHMARK/shard_uidsmkdir -p "$SHARD_UID_ROOT""$PYTHON" - "$SAMPLES" "$SHARD_UID_ROOT" "${#GPUS[@]}" <<'PY'import json, sysfrom pathlib import Pathsource, output, count = Path(sys.argv[1]), Path(sys.argv[2]), int(sys.argv[3])uids = [str(json.loads(line)["uid"]) for line in source.read_text().splitlines() if line]assert len(uids) == len(set(uids))for index in range(count): shard = uids[index::count] (output / f"shard{index}.uids").write_text("\n".join(shard) + "\n")assert sum(1 for path in output.glob("shard*.uids") for line in path.read_text().splitlines() if line) == len(uids)PY
run_shard() { local index=$1 gpu=$2 uid_file=$3 expected=$4 output log attempt runner_rc attempt_batch output=$OUTPUT/$BENCHMARK/shard${index}.json log=$OUTPUT/logs/${BENCHMARK}_shard${index}.log wait_gpu_free "$gpu" attempt_batch=$EVAL_BATCH_SIZE for attempt in 1 2 3; do runner_rc=0 CUDA_VISIBLE_DEVICES=$gpu PYTHONPATH=$REPO PYTHONUNBUFFERED=1 \ TOKENIZERS_PARALLELISM=false OMP_NUM_THREADS=1 \ PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \ "$PYTHON" "$RUNNER" --benchmark "$BENCHMARK" \ --annotation "$ANNOTATION" --samples "$SAMPLES" \ --video-root "$VIDEO_ROOT" --model "$MODEL" --processor "$PROCESSOR" \ "${MODEL_IDENTITY_ARGS[@]}" --protocol "$PROTOCOL" \ --output "$output" --uids-file "$uid_file" \ --frame-policy "$FRAME_POLICY" \ --visual-input-mode "$VISUAL_INPUT_MODE" \ --batch-size "$attempt_batch" \ --decode-prefetch-batches "$DECODE_PREFETCH_BATCHES" \ --flush-every-batches "$FLUSH_EVERY_BATCHES" \ "${CONFIDENCE_ARGS[@]}" \ --resume --retry-errors >>"$log" 2>&1 || runner_rc=$? if validate_result "$output" "$expected"; then if [[ $runner_rc -ne 0 ]]; then echo "warning: $BENCHMARK shard$index exited rc=$runner_rc after writing a complete validated result" >&2 fi return 0 fi echo "warning: $BENCHMARK shard$index attempt=$attempt batch=$attempt_batch failed validation after runner rc=$runner_rc" >&2 if (( attempt_batch > 1 )); then attempt_batch=$(( (attempt_batch + 1) / 2 )); fi done return 1}
pids=()shards=()for index in "${!GPUS[@]}"; do uid_file=$SHARD_UID_ROOT/shard${index}.uids expected=$(awk 'NF {count++} END {print count+0}' "$uid_file") shards+=("$OUTPUT/$BENCHMARK/shard${index}.json") run_shard "$index" "${GPUS[$index]}" "$uid_file" "$expected" & pids+=("$!")donefailed=0for index in "${!pids[@]}"; do pid=${pids[$index]} if wait "$pid"; then echo "$(date -u +%FT%TZ) $BENCHMARK shard$index exited rc=0" else rc=$? echo "$(date -u +%FT%TZ) $BENCHMARK shard$index exited rc=$rc" >&2 failed=1 fidone[[ $failed -eq 0 ]]
"$PYTHON" "$REPO/scripts/merge_eval_shards.py" --inputs "${shards[@]}" \ --output "$OUTPUT/$BENCHMARK/full.json" --expected-count "$EXPECTED" \ --expected-uids "$SAMPLES"validate_result "$OUTPUT/$BENCHMARK/full.json" "$EXPECTED""$PYTHON" "$REPO/scripts/score_official_benchmark_predictions.py" \ --benchmark "$BENCHMARK" --official-root "$OFFICIAL_ROOT" \ --annotation "$ANNOTATION" --predictions "$OUTPUT/$BENCHMARK/full.json" \ --output-json "$OUTPUT/$BENCHMARK/official_score.json" \ --official-input-json "$OUTPUT/$BENCHMARK/official_input.json" \ >"$OUTPUT/logs/${BENCHMARK}_official_score.log" 2>&1
RUNTIME_REPORT_ARG=${OVO_RUNTIME_REPORT:-}"$PYTHON" - "$OUTPUT/$BENCHMARK" "$MODEL_IDENTITY_SHA256" "$PROTOCOL" \ "$MODEL_ID" "$BENCHMARK" "$PROCESSOR" "$RUNTIME_REPORT_ARG" <<'PY'import hashlib, json, sysfrom datetime import datetime, timezonefrom pathlib import Pathout, model_identity, protocol = Path(sys.argv[1]), sys.argv[2], Path(sys.argv[3])model_id, benchmark, processor = sys.argv[4:7]processor = Path(processor)runtime_report = Path(sys.argv[7]) if sys.argv[7] else Nonescore = json.loads((out / "official_score.json").read_text())full = json.loads((out / "full.json").read_text())sha = lambda p: hashlib.sha256(Path(p).read_bytes()).hexdigest()summary = { "format": "iclr_video.single_benchmark.v2", "benchmark": benchmark, "model_id": model_id, "protocol_id": "recent4_full_v1", "inference_policy": full["inference_policy"], "inference_policy_hash": full["inference_policy_hash"], "policy_config": full["policy_config"], "comparable_under_locked_recent4_protocol": full.get( "comparable_under_locked_recent4_protocol" ), "model_identity_sha256": model_identity, "processor_path": str(processor), "processor_config_sha256": sha(processor / "preprocessor_config.json"), "processor_manifest_sha256": ( sha(processor / "SHA256SUMS") if (processor / "SHA256SUMS").is_file() else None ), "protocol_sha256": sha(protocol), "benchmark_runtime_assets_sha256": ( sha(runtime_report) if runtime_report is not None else None ), "completed_at": datetime.now(timezone.utc).isoformat(), "official_score": score,}(out / "summary.json").write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n")PYtouch "$OUTPUT/$BENCHMARK/complete"echo "$(date -u +%FT%TZ) completed $BENCHMARK for $MODEL_ID"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348#!/usr/bin/env python3from __future__ import annotations
import argparseimport copyimport hashlibimport importlib.utilimport ioimport jsonimport reimport subprocessimport sysimport tempfilefrom contextlib import redirect_stdoutfrom pathlib import Pathfrom statistics import meanfrom types import SimpleNamespacefrom typing import Any
PROJECT_ROOT = Path(__file__).resolve().parents[1]
from viss_core.benchmarks import load_prediction_file
OVO_GROUP_TASKS = { "backward": ("EPM", "ASI", "HLD"), "realtime": ("OCR", "ACR", "ATR", "STU", "FPD", "OJR"), "forward": ("REC", "SSR", "CRR"),}
INVALID_EMPTY_MODEL_RESPONSE = "__INVALID_EMPTY_MODEL_RESPONSE__"
def main() -> None: parser = argparse.ArgumentParser( description="Adapt agent predictions to the original benchmark formats and invoke their scorers." ) parser.add_argument("--benchmark", required=True, choices=("streamingbench", "ovo")) parser.add_argument("--official-root", type=Path, required=True) parser.add_argument("--annotation", type=Path, required=True) parser.add_argument("--predictions", type=Path, required=True) parser.add_argument("--output-json", type=Path, required=True) parser.add_argument("--official-input-json", type=Path, default=None) args = parser.parse_args()
if args.benchmark == "streamingbench": report, official_input = score_streamingbench( args.official_root, args.annotation, args.predictions ) else: report, official_input = score_ovo(args.official_root, args.annotation, args.predictions)
args.output_json.parent.mkdir(parents=True, exist_ok=True) args.output_json.write_text( json.dumps(report, indent=2, ensure_ascii=False, sort_keys=True) + "\n", encoding="utf-8", ) if args.official_input_json: args.official_input_json.parent.mkdir(parents=True, exist_ok=True) args.official_input_json.write_text( json.dumps(official_input, indent=2, ensure_ascii=False, sort_keys=True) + "\n", encoding="utf-8", ) print(json.dumps(report, indent=2, ensure_ascii=False, sort_keys=True))
def score_streamingbench( official_root: Path, annotation: Path, predictions_path: Path) -> tuple[dict[str, Any], Any]: predictions = load_prediction_file(predictions_path) data = json.loads(annotation.read_text(encoding="utf-8")) model_key = "AgenticSFT" expected_ids: list[str] = [] empty_model_response_ids: list[str] = [] for video_index, entry in enumerate(data): for question_index, question in enumerate(entry.get("questions") or []): query_id = f"streaming_{video_index}_{question_index}" expected_ids.append(query_id) raw = predictions.get(query_id) letter = _mcq_letter(raw, question.get("options") or []) response = letter if letter is not None else str(raw or "") if not response: # The original scorer skips false-y responses instead of counting # them as incorrect. Preserve the model failure without imputing an # answer by passing an explicit invalid value through the scorer. empty_model_response_ids.append(query_id) response = INVALID_EMPTY_MODEL_RESPONSE question[model_key] = [response] _require_exact_coverage(predictions, expected_ids, "StreamingBench")
count_script = official_root / "src" / "data" / "count.py" if not count_script.is_file(): raise FileNotFoundError(count_script) with tempfile.TemporaryDirectory(prefix="streamingbench_official_score_") as tmp: tmp_path = Path(tmp) official_input = tmp_path / "predictions.json" official_input.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8") completed = subprocess.run( [ sys.executable, str(count_script), "--model", model_key, "--task", "real", "--src", str(official_input), ], cwd=tmp_path, check=True, text=True, capture_output=True, ) stats = json.loads((tmp_path / f"{model_key}_stats.json").read_text(encoding="utf-8"))
total = stats.get("total") or {} by_task = { task: { "accuracy": float(values["accuracy"]), "correct": float(values["correct"]), "total": int(values["total"]), } for task, values in stats.items() if task != "total" } if int(total.get("total", 0)) != len(expected_ids): raise RuntimeError( f"official StreamingBench scorer counted {total.get('total')} of {len(expected_ids)} queries" ) report = { "benchmark": "streamingbench", "official_scorer": str(count_script), "official_scorer_sha256": _sha256(count_script), "official_repository_commit": _git_commit(official_root), "official_stdout": completed.stdout.strip(), "num_queries": len(expected_ids), "num_predictions": len(expected_ids), "coverage": 1.0, "num_empty_model_responses": len(empty_model_response_ids), "empty_model_response_ids": empty_model_response_ids, "empty_response_scoring": "counted_as_incorrect_without_answer_imputation", "accuracy": float(total["accuracy"]), "correct": float(total["correct"]), "total": int(total["total"]), "by_task": by_task, } return report, data
def score_ovo( official_root: Path, annotation: Path, predictions_path: Path) -> tuple[dict[str, Any], Any]: predictions = load_prediction_file(predictions_path) annotations = json.loads(annotation.read_text(encoding="utf-8")) results: dict[str, list[dict[str, Any]]] = {key: [] for key in OVO_GROUP_TASKS} expected_ids: list[str] = [] empty_model_response_ids: list[str] = [] for source in annotations: item = copy.deepcopy(source) task = str(item.get("task") or "").upper() group = next((name for name, tasks in OVO_GROUP_TASKS.items() if task in tasks), None) if group is None: raise ValueError(f"unknown OVO task: {task}") if group == "forward": for index, test_info in enumerate(item.get("test_info") or []): query_id = f"ovo_{item['id']}_{index}" expected_ids.append(query_id) response = str(predictions.get(query_id) or "") if not response: empty_model_response_ids.append(query_id) test_info["response"] = response else: query_id = f"ovo_{item['id']}" expected_ids.append(query_id) letter = _mcq_letter(predictions.get(query_id), item.get("options") or []) response = letter if letter is not None else str(predictions.get(query_id) or "") if not response: empty_model_response_ids.append(query_id) item["response"] = response item["ground_truth"] = chr(ord("A") + int(item["gt"])) results[group].append(item) _require_exact_coverage(predictions, expected_ids, "OVO-Bench")
score_module_path = official_root / "utils" / "OVOBenchScore.py" if not score_module_path.is_file(): raise FileNotFoundError(score_module_path) spec = importlib.util.spec_from_file_location("official_ovo_score", score_module_path) if spec is None or spec.loader is None: raise ImportError(score_module_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) scorer = module.OVOBenchOfflineScore(SimpleNamespace(model="AgenticSFT"), copy.deepcopy(results))
_, backward_scores = scorer.calculate_score_backward_realtime(copy.deepcopy(results["backward"])) _, realtime_scores = scorer.calculate_score_backward_realtime(copy.deepcopy(results["realtime"])) _, forward_scores = scorer.calculate_score_forward(copy.deepcopy(results["forward"])) score_maps = { "backward": backward_scores, "realtime": realtime_scores, "forward": forward_scores, } by_task: dict[str, dict[str, Any]] = {} official_by_group: dict[str, dict[str, Any]] = {} for group, expected_tasks in OVO_GROUP_TASKS.items(): scores = score_maps[group] if set(scores) != set(expected_tasks): raise RuntimeError(f"official OVO scorer tasks for {group}: {sorted(scores)}") task_accuracies = [] for task in expected_tasks: values = scores[task] accuracy = sum(values) / len(values) by_task[task] = { "accuracy": accuracy, "correct": float(sum(values)), "total": len(values), } task_accuracies.append(accuracy) official_by_group[group] = { "accuracy": mean(task_accuracies), "num_tasks": len(task_accuracies), } official_overall = mean(value["accuracy"] for value in official_by_group.values()) derived_metrics = _ovo_derived_metrics(by_task, official_by_group)
stdout_buffer = io.StringIO() with redirect_stdout(stdout_buffer): module.OVOBenchOfflineScore( SimpleNamespace(model="AgenticSFT"), copy.deepcopy(results) ).score() official_stdout = stdout_buffer.getvalue().strip() _verify_ovo_stdout(official_stdout, by_task, official_by_group, official_overall)
report = { "benchmark": "ovo", "official_scorer": str(score_module_path), "official_scorer_sha256": _sha256(score_module_path), "official_repository_commit": _git_commit(official_root), "official_stdout": official_stdout, "num_queries": len(expected_ids), "num_predictions": len(expected_ids), "coverage": 1.0, "num_empty_model_responses": len(empty_model_response_ids), "empty_model_response_ids": empty_model_response_ids, "empty_response_scoring": "passed_unchanged_to_original_scorer_without_answer_imputation", "by_task": by_task, "ovo_official": { "name": "Total Avg", "aggregation": "mean of Real-Time, Backward, and Forward task-macro averages", "accuracy": official_overall, "by_group": official_by_group, }, **derived_metrics, } return report, results
def _ovo_derived_metrics( by_task: dict[str, dict[str, Any]], by_group: dict[str, dict[str, Any]],) -> dict[str, dict[str, Any]]: micro_correct = sum(float(value["correct"]) for value in by_task.values()) micro_total = sum(int(value["total"]) for value in by_task.values()) if micro_total <= 0: raise RuntimeError("OVO-Bench has no scored predictions") rt_bt_accuracy = mean( float(by_group[group]["accuracy"]) for group in ("realtime", "backward") ) return { "ovo_micro_overall": { "name": "Overall", "aggregation": "micro average over all expanded OVO queries", "accuracy": micro_correct / micro_total, "correct": micro_correct, "total": micro_total, }, "ovo_rt_bt_avg": { "name": "RT/BT Avg", "aggregation": "mean of Real-Time and Backward task-macro averages", "accuracy": rt_bt_accuracy, }, }
def _require_exact_coverage( predictions: dict[str, Any], expected_ids: list[str], benchmark: str) -> None: expected = set(expected_ids) missing = sorted(expected - set(predictions)) if missing: raise RuntimeError(f"{benchmark} missing {len(missing)} predictions: {missing[:10]}") if len(expected_ids) != len(expected): raise RuntimeError(f"{benchmark} contains duplicate query IDs")
def _mcq_letter(prediction: Any, _options: list[Any]) -> str | None: text = str(prediction or "").strip() match = re.match(r"^[\(\[]?([A-D])(?:[\)\].:\s-]|$)", text, flags=re.IGNORECASE) if match: return match.group(1).upper() return None
def _verify_ovo_stdout( stdout: str, by_task: dict[str, dict[str, Any]], by_group: dict[str, dict[str, Any]], overall: float,) -> None: printed_tasks = { task: float(value) for task, value in re.findall(r"Task:\s*(\w+),\s*Acc:\s*([0-9.]+)", stdout) } for task, values in by_task.items(): if printed_tasks.get(task) != round(values["accuracy"] * 100, 2): raise RuntimeError(f"official OVO stdout mismatch for {task}") labels = {"backward": "Backward", "realtime": "Realtime", "forward": "Forward"} for group, label in labels.items(): match = re.search(rf"{label} Avg\.:\s*([0-9.]+)", stdout) if match is None or float(match.group(1)) != round(by_group[group]["accuracy"] * 100, 2): raise RuntimeError(f"official OVO stdout mismatch for {group} Avg") match = re.search(r"Total Avg\.:\s*([0-9.]+)", stdout) if match is None or float(match.group(1)) != round(overall * 100, 2): raise RuntimeError("official OVO stdout mismatch for Total Avg")
def _sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for block in iter(lambda: handle.read(8 << 20), b""): digest.update(block) return digest.hexdigest()
def _git_commit(root: Path) -> str | None: completed = subprocess.run( ["git", "-C", str(root), "rev-parse", "HEAD"], text=True, capture_output=True, check=False, ) if completed.returncode != 0: return None commit = completed.stdout.strip() return commit or None
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728#!/usr/bin/env python3from __future__ import annotations
import argparseimport jsonfrom pathlib import Path
from viss_core.evaluation_protocol import LOCKED_PROTOCOL, validate_locked_protocol
def main() -> None: parser = argparse.ArgumentParser( description="Validate the immutable exports and rules of the locked evaluation protocol." ) parser.add_argument("--protocol", type=Path, default=LOCKED_PROTOCOL) args = parser.parse_args() print( json.dumps( validate_locked_protocol(args.protocol), indent=2, ensure_ascii=False, sort_keys=True, ) )
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677from experiments.materialize_confidence_gated_third_view_agent import materialize
def _confidence(margin): return {"top2_margin": margin, "task_or_group_used": False}
def _row(uid, prediction, margin, *, escalated=True): return { "uid": uid, "prediction": prediction, "generation_confidence": _confidence(margin), "sampling": {"frame_indices": [1], "frame_timestamps": [0.0]}, "query_time": 1.0, "frames_observed": 1, "agent_policy": {"escalated": escalated}, }
def _value(rows): return { "benchmark": "streamingbench", "model_manifest_sha256": "model", "annotation_sha256": "annotation", "evaluation_protocol_sha256": "protocol", "rows": rows, }
def _threshold(commit=-0.1): return { "status": "source_disjoint_internal_threshold_calibration", "eligible_as_frozen_benchmark_controller_config": True, "model_manifest_sha256": "model", "policy": {"commit_threshold": commit}, }
def test_third_view_uses_current_answer_source_margin() -> None: recent = _value([_row("x", "A", 0.8), _row("y", "A", 0.2)]) event = _value([_row("x", "B", 0.5), _row("y", "B", 0.8)]) base = _value([_row("x", "A", 0.5), _row("y", "B", 0.8)]) third = _value([_row("x", "C", 0.4), _row("y", "C", 0.6)]) result = materialize(recent, event, base, third, _threshold(-0.3)) rows = {row["uid"]: row for row in result["rows"]} assert rows["x"]["prediction"] == "A" assert rows["x"]["third_view_policy"]["current_view"] == "recent4" assert rows["x"]["third_view_policy"]["committed"] is False assert rows["y"]["prediction"] == "C" assert rows["y"]["third_view_policy"]["current_view"] == "causalbudget20" assert rows["y"]["third_view_policy"]["committed"] is True assert result["third_view_committed"] == 1
def test_unchanged_third_answer_never_counts_as_commit() -> None: recent = _value([_row("x", "A", 0.2)]) event = _value([_row("x", "B", 0.3)]) base = _value([_row("x", "B", 0.3)]) third = _value([_row("x", "B", 0.9)]) result = materialize(recent, event, base, third, _threshold()) assert result["rows"][0]["prediction"] == "B" assert result["rows"][0]["third_view_policy"]["committed"] is False
def test_full_precomputed_third_view_only_triggers_on_event_disagreement() -> None: recent = _value([_row("x", "A", 0.2), _row("z", "A", 0.4)]) event = _value([_row("x", "B", 0.3), _row("z", "A", 0.5)]) base = _value([_row("x", "B", 0.3), _row("z", "A", 0.5)]) third = _value([_row("x", "C", 0.9), _row("z", "C", 0.9)]) result = materialize(recent, event, base, third, _threshold()) rows = {row["uid"]: row for row in result["rows"]} assert rows["x"]["prediction"] == "C" assert rows["z"]["prediction"] == "A" assert rows["z"]["third_view_policy"]["triggered"] is False assert result["third_view_triggered"] == 1 assert result["third_view_input_rows"] == 2 assert result["third_view_unused_precomputed_rows"] == 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384from copy import deepcopy
import pytest
from data_pipeline.temporal_scope.filter_semantic_release_by_blind_audit import ( BlindAuditFilterError,)from data_pipeline.temporal_scope.filter_semantic_release_by_option_consensus import ( _validate_presentations,)
def _source(uid: str, answer: str) -> dict: return { "uid": uid, "messages": [ {"role": "user", "content": [{"type": "text", "text": "q"}]}, { "role": "assistant", "loss": True, "content": [{"type": "text", "text": answer}], }, ], }
def _audit(uid: str, presentation: int, answer: str, *, confidence: str = "high") -> dict: mapping = list("ABCD") if presentation == 0 else list("BCDA") return { "format": "streameva.semantic_release.option_consensus_audit_row.v0", "uid": uid, "presentation": presentation, "displayed_to_source": mapping, "expected_source": "B", "prediction_source": answer, "confidence": confidence, "error": None, "correct_source": answer == "B", }
def test_option_consensus_selects_only_stable_source_agreements() -> None: sources = [_source("kept", "B"), _source("wrong", "B"), _source("unstable", "B")] audits = [ _audit("kept", 0, "B"), _audit("kept", 1, "B"), _audit("wrong", 0, "C"), _audit("wrong", 1, "C"), _audit("unstable", 0, "B"), _audit("unstable", 1, "C"), ] selected, stable = _validate_presentations( source_rows=sources, audit_rows=audits, allowed_confidence={"high"} ) assert [row["uid"] for row in selected] == ["kept"] assert stable == 2
def test_option_consensus_rejects_missing_or_identity_second_order() -> None: source = _source("u", "B") first = _audit("u", 0, "B") with pytest.raises(BlindAuditFilterError, match="complete two-order"): _validate_presentations( source_rows=[source], audit_rows=[first], allowed_confidence={"high"} ) second = _audit("u", 1, "B") second["displayed_to_source"] = list("ABCD") with pytest.raises(BlindAuditFilterError, match="malformed"): _validate_presentations( source_rows=[source], audit_rows=[first, second], allowed_confidence={"high"}, )
def test_option_consensus_rejects_tampered_correctness_flag() -> None: source = _source("u", "B") rows = [_audit("u", 0, "B"), _audit("u", 1, "B")] tampered = deepcopy(rows) tampered[1]["correct_source"] = False with pytest.raises(BlindAuditFilterError, match="malformed"): _validate_presentations( source_rows=[source], audit_rows=tampered, allowed_confidence={"high"} )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551from experiments.materialize_uncertainty_temporal_agent import materialize
def _result(rows: list[dict]) -> dict: return { "benchmark": "x", "model_manifest_sha256": "m", "annotation_sha256": "a", "evaluation_protocol_sha256": "p", "rows": rows, }
def test_materializer_uses_temporal_only_for_preselected_uids() -> None: recent = _result( [ {"uid": "a", "prediction": "A", "query_time": 10, "frames_observed": 4}, {"uid": "b", "prediction": "B", "query_time": 10, "frames_observed": 4}, ] ) temporal = _result( [ { "uid": "a", "prediction": "C", "query_time": 10, "frames_observed": 20, "sampling": { "frame_policy": "causalbudget20", "frame_timestamps": [0, 10], "candidate_frame_indices": list(range(64)), "extra_frames_inspected": 44, }, "visual_input_mode": "native-video", } ] ) selection = { "status": "frozen_before_benchmark_temporal_inference", "threshold": 0.3, "benchmark": "x", "model_manifest_sha256": "m", "score_or_gold_fields_read_for_selection": False, "rows": [ {"uid": "a", "margin": 0.2, "escalated": True}, {"uid": "b", "margin": 0.8, "escalated": False}, ], } threshold = { "status": "source_disjoint_internal_threshold_calibration", "eligible_as_frozen_benchmark_controller_config": True, "model_manifest_sha256": "m", "policy": {"threshold": 0.3}, } output = materialize(recent, temporal, selection, threshold) assert [row["prediction"] for row in output["rows"]] == ["C", "B"] assert output["escalated"] == 1 assert output["mean_model_calls"] == 1.5 assert output["mean_low_resolution_probe_frames"] == 32 assert output["mean_extra_probe_frames_not_visible_to_vlm"] == 22 assert output["mean_model_processed_frames"] == 14 assert output["mean_total_decoded_frame_instances"] == 46 assert output["rows"][0]["total_decoded_frame_instances"] == 88 assert output["rows"][1]["total_decoded_frame_instances"] == 4
def test_materializer_rejects_lower_confidence_changed_proposal() -> None: recent = _result( [ { "uid": "a", "prediction": "A", "query_time": 10, "frames_observed": 4, "generation_confidence": { "top2_margin": 0.3, "task_or_group_used": False, }, } ] ) temporal = _result( [ { "uid": "a", "prediction": "C", "query_time": 10, "frames_observed": 20, "generation_confidence": { "top2_margin": 0.2, "task_or_group_used": False, }, "sampling": { "frame_policy": "causalbudget20", "frame_timestamps": [0, 10], "candidate_frame_indices": list(range(20)), "extra_frames_inspected": 0, }, "visual_input_mode": "native-video", } ] ) selection = { "status": "frozen_before_benchmark_temporal_inference", "threshold": 0.4, "benchmark": "x", "model_manifest_sha256": "m", "score_or_gold_fields_read_for_selection": False, "rows": [{"uid": "a", "margin": 0.3, "escalated": True}], } threshold = { "status": "source_disjoint_internal_threshold_calibration", "eligible_as_frozen_benchmark_controller_config": True, "model_manifest_sha256": "m", "policy": {"threshold": 0.4, "commit_threshold": 0.0}, } output = materialize(recent, temporal, selection, threshold) assert output["rows"][0]["prediction"] == "A" assert output["rows"][0]["proposal_prediction"] == "C" assert output["rows"][0]["agent_policy"]["committed"] is False
def test_materializer_names_image_list_event20_interface() -> None: recent = _result( [{ "uid": "a", "prediction": "A", "query_time": 10, "frames_observed": 4, "generation_confidence": {"top2_margin": 0.1, "task_or_group_used": False}, }] ) temporal = _result( [{ "uid": "a", "prediction": "C", "query_time": 10, "frames_observed": 20, "generation_confidence": {"top2_margin": 0.4, "task_or_group_used": False}, "sampling": { "frame_policy": "causalbudget20", "frame_timestamps": [0, 10], "candidate_frame_indices": list(range(20)), "extra_frames_inspected": 0, }, "visual_input_mode": "image-list", }] ) selection = { "status": "frozen_before_benchmark_temporal_inference", "threshold": 0.5, "benchmark": "x", "model_manifest_sha256": "m", "score_or_gold_fields_read_for_selection": False, "rows": [{"uid": "a", "margin": 0.1, "escalated": True}], } threshold = { "status": "source_disjoint_internal_threshold_calibration", "eligible_as_frozen_benchmark_controller_config": True, "model_manifest_sha256": "m", "policy": {"threshold": 0.5, "commit_threshold": 0.0}, } output = materialize(recent, temporal, selection, threshold) assert output["policy"]["second_view"] == "image_list_causal_temporal20" assert output["rows"][0]["agent_policy"]["selected_view"] == ( "causal_temporal20_image_list" )
def test_materializer_names_image_list_event32_recent8_interface() -> None: recent = _result( [{ "uid": "a", "prediction": "A", "query_time": 10, "frames_observed": 4, "generation_confidence": {"top2_margin": 0.1, "task_or_group_used": False}, }] ) temporal = _result( [{ "uid": "a", "prediction": "C", "query_time": 10, "frames_observed": 32, "generation_confidence": {"top2_margin": 0.4, "task_or_group_used": False}, "sampling": { "frame_policy": "causalbudget32r8", "frame_timestamps": [0, 10], "candidate_frame_indices": list(range(64)), "extra_frames_inspected": 32, }, "visual_input_mode": "image-list", }] ) selection = { "status": "frozen_before_benchmark_temporal_inference", "threshold": 0.5, "benchmark": "x", "model_manifest_sha256": "m", "score_or_gold_fields_read_for_selection": False, "rows": [{"uid": "a", "margin": 0.1, "escalated": True}], } threshold = { "status": "source_disjoint_internal_threshold_calibration", "eligible_as_frozen_benchmark_controller_config": True, "model_manifest_sha256": "m", "policy": {"threshold": 0.5, "commit_threshold": 0.0}, } output = materialize(recent, temporal, selection, threshold) assert output["policy"]["second_view"] == ( "image_list_causal_temporal32_recent8" ) assert output["rows"][0]["agent_policy"]["selected_view"] == ( "causal_temporal32_recent8_image_list" )
def test_materializer_accepts_full_lowres_temporal_superset() -> None: recent = _result( [ {"uid": "a", "prediction": "A", "query_time": 10, "frames_observed": 4}, {"uid": "b", "prediction": "B", "query_time": 10, "frames_observed": 4}, ] ) temporal_rows = [] for uid, prediction in (("a", "C"), ("b", "D")): temporal_rows.append( { "uid": uid, "prediction": prediction, "query_time": 10, "frames_observed": 32, "sampling": { "frame_policy": "causalbudget32r8", "frame_timestamps": [0, 10], "candidate_frame_indices": list(range(64)), "extra_frames_inspected": 32, }, "visual_input_mode": "lowres-history-recent-images", } ) temporal = _result(temporal_rows) selection = { "status": "frozen_before_benchmark_temporal_inference", "threshold": 0.3, "benchmark": "x", "model_manifest_sha256": "m", "score_or_gold_fields_read_for_selection": False, "rows": [ {"uid": "a", "margin": 0.2, "escalated": True}, {"uid": "b", "margin": 0.8, "escalated": False}, ], } threshold = { "status": "source_disjoint_internal_threshold_calibration", "eligible_as_frozen_benchmark_controller_config": True, "model_manifest_sha256": "m", "policy": {"threshold": 0.3}, } output = materialize(recent, temporal, selection, threshold) assert [row["prediction"] for row in output["rows"]] == ["C", "B"] assert output["temporal_input_num_rows"] == 2 assert output["temporal_unused_num_rows"] == 1 assert output["policy"]["second_view"] == ( "lowres_history_recent_images_causal_temporal32_recent8" ) assert output["rows"][0]["agent_policy"]["selected_view"] == ( "causal_temporal32_recent8_lowres_history_recent_images" )
def test_materializer_names_uniform32_image_list_interface() -> None: recent = _result( [{ "uid": "a", "prediction": "A", "query_time": 10, "frames_observed": 4, "generation_confidence": {"top2_margin": 0.1, "task_or_group_used": False}, }] ) temporal = _result( [{ "uid": "a", "prediction": "C", "query_time": 10, "frames_observed": 32, "generation_confidence": {"top2_margin": 0.4, "task_or_group_used": False}, "sampling": { "frame_policy": "causalhybrid32", "frame_timestamps": [0, 10], }, "visual_input_mode": "image-list", }] ) selection = { "status": "frozen_before_benchmark_temporal_inference", "threshold": 0.5, "benchmark": "x", "model_manifest_sha256": "m", "score_or_gold_fields_read_for_selection": False, "rows": [{"uid": "a", "margin": 0.1, "escalated": True}], } threshold = { "status": "source_disjoint_internal_threshold_calibration", "eligible_as_frozen_benchmark_controller_config": True, "model_manifest_sha256": "m", "policy": {"threshold": 0.5, "commit_threshold": 0.0}, } output = materialize(recent, temporal, selection, threshold) assert output["policy"]["second_view"] == ( "image_list_uniform_history28_plus_recent4" ) assert output["rows"][0]["agent_policy"]["selected_view"] == ( "causal_uniform_history28_plus_recent4_image_list" )
def test_materializer_names_hybrid32_recent8_interface() -> None: recent = _result( [{ "uid": "a", "prediction": "A", "query_time": 10, "frames_observed": 4, "generation_confidence": {"top2_margin": 0.1, "task_or_group_used": False}, }] ) temporal = _result( [{ "uid": "a", "prediction": "C", "query_time": 10, "frames_observed": 32, "generation_confidence": {"top2_margin": 0.4, "task_or_group_used": False}, "sampling": { "frame_policy": "causalhybrid32r8", "frame_timestamps": [0, 10], }, "visual_input_mode": "hybrid-history-video-recent-images", }] ) selection = { "status": "frozen_before_benchmark_temporal_inference", "threshold": 0.5, "benchmark": "x", "model_manifest_sha256": "m", "score_or_gold_fields_read_for_selection": False, "rows": [{"uid": "a", "margin": 0.1, "escalated": True}], } threshold = { "status": "source_disjoint_internal_threshold_calibration", "eligible_as_frozen_benchmark_controller_config": True, "model_manifest_sha256": "m", "policy": {"threshold": 0.5, "commit_threshold": 0.0}, } output = materialize(recent, temporal, selection, threshold) assert output["policy"]["second_view"] == ( "hybrid_history_video_recent_images_causal_hybrid32r8" ) assert output["rows"][0]["agent_policy"]["selected_view"] == ( "causal_hybrid_history24_plus_recent8" )
def test_materializer_accepts_task_blind_fixed_budget_selection() -> None: recent = _result( [ { "uid": "a", "prediction": "A", "query_time": 10, "frames_observed": 4, "generation_confidence": { "top2_margin": 0.1, "task_or_group_used": False, }, }, { "uid": "b", "prediction": "B", "query_time": 10, "frames_observed": 4, }, ] ) temporal = _result( [ { "uid": "a", "prediction": "C", "query_time": 10, "frames_observed": 20, "generation_confidence": { "top2_margin": 0.3, "task_or_group_used": False, }, "sampling": { "frame_policy": "causalbudget20", "frame_timestamps": [0, 10], "candidate_frame_indices": list(range(64)), "extra_frames_inspected": 44, }, "visual_input_mode": "native-video", } ] ) selection = { "format": "streameva.unlabeled_budget_uid_selection.v0", "status": "frozen_before_benchmark_temporal_inference", "benchmark": "x", "model_manifest_sha256": "m", "quantile": 0.5, "score_or_gold_fields_read_for_selection": False, "benchmark_identity_used_for_policy_parameters": False, "cohort_labels_read_for_selection": False, "rows": [ { "uid": "a", "margin": 0.1, "uncertainty_rank": 1, "escalated": True, }, { "uid": "b", "margin": 0.7, "uncertainty_rank": 2, "escalated": False, }, ], } output = materialize( recent, temporal, selection, None, commit_threshold_override=0.0, ) assert [row["prediction"] for row in output["rows"]] == ["C", "B"] assert output["status"] == "fixed_budget_router_free_agent" assert output["policy"]["uncertainty_quantile"] == 0.5 assert output["rows"][0]["agent_policy"]["uncertainty_rank"] == 1
def test_materializer_accounts_for_prefix32_without_hidden_probe() -> None: recent = _result( [ { "uid": "a", "prediction": "A", "query_time": 10, "frames_observed": 4, "generation_confidence": { "top2_margin": 0.1, "task_or_group_used": False, }, } ] ) temporal = _result( [ { "uid": "a", "prediction": "B", "query_time": 10, "frames_observed": 32, "generation_confidence": { "top2_margin": 0.5, "task_or_group_used": False, }, "sampling": { "frame_policy": "prefix32", "frame_timestamps": [0, 10], }, "visual_input_mode": "image-list", } ] ) selection = { "format": "streameva.unlabeled_budget_uid_selection.v0", "status": "frozen_before_benchmark_temporal_inference", "benchmark": "x", "model_manifest_sha256": "m", "quantile": 1.0, "score_or_gold_fields_read_for_selection": False, "benchmark_identity_used_for_policy_parameters": False, "cohort_labels_read_for_selection": False, "rows": [ {"uid": "a", "margin": 0.1, "uncertainty_rank": 1, "escalated": True} ], } output = materialize( recent, temporal, selection, None, commit_threshold_override=-1.0, ) row = output["rows"][0] assert row["prediction"] == "B" assert row["agent_policy"]["selected_view"] == "causal_prefix32" assert row["low_resolution_probe_frames"] == 0 assert row["model_processed_frames"] == 36 assert row["total_decoded_frame_instances"] == 36
def test_materializer_can_fail_closed_to_recent_on_temporal_error() -> None: recent = _result( [ { "uid": "a", "prediction": "A", "query_time": 10, "frames_observed": 4, }, { "uid": "b", "prediction": "B", "query_time": 10, "frames_observed": 4, }, ] ) temporal = _result( [ { "uid": "a", "prediction": "", "error": "OutOfMemoryError", "query_time": 10, "frames_observed": 0, }, { "uid": "b", "prediction": "C", "query_time": 10, "frames_observed": 20, "sampling": { "frame_policy": "causalbudget20", "frame_timestamps": [0, 10], "candidate_frame_indices": list(range(20)), "extra_frames_inspected": 0, }, "visual_input_mode": "image-list", }, ] ) selection = { "status": "frozen_before_benchmark_temporal_inference", "threshold": 0.3, "benchmark": "x", "model_manifest_sha256": "m", "score_or_gold_fields_read_for_selection": False, "rows": [ {"uid": "a", "margin": 0.1, "escalated": True}, {"uid": "b", "margin": 0.2, "escalated": True}, ], } threshold = { "status": "source_disjoint_internal_threshold_calibration", "eligible_as_frozen_benchmark_controller_config": True, "model_manifest_sha256": "m", "policy": {"threshold": 0.3}, } output = materialize( recent, temporal, selection, threshold, fallback_recent_on_temporal_error=True, ) assert [row["prediction"] for row in output["rows"]] == ["A", "C"] assert output["temporal_error_fallback_count"] == 1 assert output["policy"]["temporal_error_policy"] == "fail_closed_to_recent4" assert output["rows"][0]["agent_policy"]["temporal_error_fallback"] is True assert output["rows"][0]["agent_policy"]["committed"] is False assert output["rows"][0]["agent_policy"]["selected_view"] == ( "recent4_temporal_error_fallback" )1234567891011121314151617181920212223242526272829303132333435363738394041424344454647import jsonfrom pathlib import Path
import pytest
from experiments.evaluate_qwen3vl_recent4_full import validate_processor_contractfrom scripts.configure_evaluation_protocol import configurefrom viss_core.evaluation_protocol import ProtocolValidationError, load_locked_protocol
TEMPLATE = Path(__file__).resolve().parents[1] / "configs/evaluation/recent4.example.json"
def test_unconfigured_template_cannot_be_used_as_a_locked_protocol(): with pytest.raises(ProtocolValidationError, match="not locked"): load_locked_protocol(TEMPLATE)
def test_user_configured_protocol_preserves_processor_identity_check(tmp_path): template = json.loads(TEMPLATE.read_text()) contract = template["inference"]["processor_contract"] processor = tmp_path / "processor" processor.mkdir() config = processor / "preprocessor_config.json" config.write_text(json.dumps({ key: contract[key] for key in ["image_processor_type", "patch_size", "merge_size", "temporal_patch_size"] } | {"size": { key: contract[key] for key in ["shortest_edge", "longest_edge"] }})) streaming = tmp_path / "streaming.jsonl" ovo = tmp_path / "ovo.jsonl" for path in (streaming, ovo): path.write_text('{"uid": "synthetic-query"}\n') output = tmp_path / "configured.json" configure( template=TEMPLATE, streaming_samples=streaming, ovo_samples=ovo, processor_config=config, output=output, ) protocol = load_locked_protocol(output) validate_processor_contract(processor, protocol) config.write_text(config.read_text() + " ") with pytest.raises(ValueError, match="SHA-256 diverged"): validate_processor_contract(processor, protocol)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893import concurrent.futuresimport timeimport unittestfrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import patch
from experiments.evaluate_qwen3vl_recent4_full import ( CausalTemporalBudgetCache, DecordReaderPool, RecentWindowCache, _qwen_video_resize_limits, frame_policy_sampling_fps, resolve_frame_policy, clamp_visible_until_to_source, normalize_answer, probe_source_video, recent_window_bounds, render_question, render_semantic_revisit_prompt, selected_uids, build_visual_messages, compose_temporal_storyboard, downscale_temporal_history, parse_semantic_revisit_positions, native_video_metadata_payload, partition_hybrid_frames, render_anonymous_candidate_prompt, render_candidate_binary_verification_prompt, render_candidate_rejection_verification_prompt, render_candidate_pairwise_verification_prompt, render_candidate_revisit_prompt, choose_binary_verified_candidate, render_temporal_review_prompt, render_temporal_deliberation_prompt, render_candidate_evidence_deliberation_prompt, decode_causal_temporal_budget, decode_causal_hybrid_prefix, load_causalbudget_index_plan, load_anonymous_candidate_proposals, uniform_prefix_indices,)
class Recent4RunnerTest(unittest.TestCase): def test_anonymous_candidate_sources_may_be_sparse(self) -> None: import json import tempfile
with tempfile.TemporaryDirectory() as directory: path = Path(directory) / "partial.json" path.write_text( json.dumps( { "benchmark": "streamingbench", "annotation_sha256": "annotation", "model_manifest_sha256": "model", "num_errors": 0, "rows": [{"uid": "q0", "prediction": "A"}], } ) ) proposals, inputs = load_anonymous_candidate_proposals( paths=[path], wanted=["q0", "q1"], benchmark="streamingbench", annotation_sha256="annotation", model_manifest_sha256="model", ) self.assertEqual(proposals, [{"q0": "A"}]) self.assertEqual(inputs[0]["covered_rows"], 1) self.assertEqual(inputs[0]["requested_rows"], 2) self.assertTrue(inputs[0]["sparse_candidate_source"])
def test_semantic_revisit_parser_is_bounded_and_fills_deterministically(self): self.assertEqual( parse_semantic_revisit_positions( "Frames: 7, 2, 7, 99", history_count=8, revisit_count=4, fallback_positions=[8, 6, 4, 2], ), [2, 6, 7, 8], )
def test_semantic_revisit_instruction_overrides_answer_format(self): prompt = render_semantic_revisit_prompt( "Question\nOnly give the best option's letter directly.", history_count=24, revisit_count=8, ) self.assertTrue(prompt.endswith("`Frames: i,j,...` and nothing else."))
def test_semantic_revisit_storyboard_instruction_has_global_labels(self): prompt = render_semantic_revisit_prompt( "Question", history_count=24, revisit_count=8, planner_mode="storyboard16", ) self.assertIn("global frame number", prompt) self.assertIn("numbered 1 through 24", prompt)
def test_storyboard_preserves_chronology_and_fixed_geometry(self) -> None: from PIL import Image
frames = [Image.new("RGB", (32, 16), color) for color in ("red", "green", "blue")] sheet = compose_temporal_storyboard( frames, [0.0, 1.0, 2.0], columns=2, tile_width=40, tile_height=20 ) self.assertEqual(sheet.size, (80, 80)) self.assertEqual(sheet.getpixel((20, 10)), (255, 0, 0)) self.assertEqual(sheet.getpixel((60, 10)), (0, 128, 0)) self.assertEqual(sheet.getpixel((20, 50)), (0, 0, 255))
offset_sheet = compose_temporal_storyboard( frames[:2], [3.0, 4.0], columns=2, label_start=17 ) self.assertEqual(offset_sheet.size[0], 448)
def test_lowres_history_keeps_recent_frames_exact(self) -> None: from PIL import Image
frames = [Image.new("RGB", (640, 360), color) for color in ("red", "blue")] output = downscale_temporal_history(frames, [3, 4], {4}, max_edge=224) self.assertEqual(output[0].size, (224, 126)) self.assertIs(output[1], frames[1]) self.assertEqual(frames[0].size, (640, 360))
def test_deliberation_replaces_conflicting_direct_only_instruction(self) -> None: prompt = render_temporal_deliberation_prompt( "Question\nOnly give the best option's letter (A, B, C, or D) directly." ) self.assertNotIn("Only give", prompt) self.assertIn("Analyze the visible causal sequence", prompt) self.assertIn("Answer: X", prompt)
def test_anonymous_candidates_can_be_verified_with_one_deliberation_contract( self, ) -> None: prompt, ordered = render_anonymous_candidate_prompt( "Question\nOnly give the best option's letter directly.", predictions=["A", "C", "A"], uid="q0", ) prompt = render_temporal_deliberation_prompt(prompt) self.assertEqual(sorted(ordered), ["A", "C"]) self.assertIn("Candidate 1", prompt) self.assertIn("Answer: X", prompt)
def test_candidate_evidence_deliberation_requires_pixel_cited_elimination( self, ) -> None: prompt, ordered = render_anonymous_candidate_prompt( "Question\nOnly give the best option's letter directly.", predictions=["B", "D", "B"], uid="q1", ) prompt = render_candidate_evidence_deliberation_prompt(prompt) self.assertEqual(sorted(ordered), ["B", "D"]) self.assertNotIn("Only give", prompt) self.assertIn("untrusted hypothesis", prompt) self.assertIn("at most ten words per candidate", prompt) self.assertIn("do not narrate", prompt) self.assertIn("Answer: X", prompt)
def test_binary_candidate_verifier_is_isolated_and_removes_direct_contract(self): prompt = render_candidate_binary_verification_prompt( "Question: Where is it?\nOptions:\nA. left\nB. right\n" "Only give the best option's letter directly.", candidate="B", options=["A. left", "B. right"], ) self.assertNotIn("Only give", prompt) self.assertIn("Candidate answer under isolated verification: B. right", prompt) self.assertTrue(prompt.endswith("Answer exactly Yes or No."))
def test_binary_candidate_commit_is_source_order_invariant(self): first = choose_binary_verified_candidate( uid="q0", candidate_probabilities={"A": 0.3, "C": 0.8} ) second = choose_binary_verified_candidate( uid="q0", candidate_probabilities={"C": 0.8, "A": 0.3} ) self.assertEqual(first, "C") self.assertEqual(first, second)
def test_antipodal_candidate_prompt_reverses_only_the_decision_polarity(self): prompt = render_candidate_rejection_verification_prompt( "Question: Where is it?\nOptions:\nA. left\nB. right\n" "Only give the best option's letter directly.", candidate="B", options=["A. left", "B. right"], ) self.assertNotIn("Only give", prompt) self.assertIn("isolated rejection check: B. right", prompt) self.assertIn("should be rejected as the best answer", prompt) self.assertTrue(prompt.endswith("Answer exactly Yes or No."))
def test_pairwise_candidate_prompt_is_source_anonymous_and_order_explicit(self): prompt = render_candidate_pairwise_verification_prompt( "Question: Where is it?\nOptions:\nA. left\nB. right\n" "Only give the best option's letter directly.", first_candidate="B", second_candidate="A", options=["A. left", "B. right"], ) self.assertNotIn("Only give", prompt) self.assertIn("Choice A: B. right", prompt) self.assertIn("Choice B: A. left", prompt) self.assertTrue(prompt.endswith("Answer exactly A or B."))
def test_candidate_conditioned_revisit_is_bounded_and_answer_free(self): prompt = render_candidate_revisit_prompt( "Question: What happened?\nOptions:\nA. left\nB. right\n" "Only give the best option's letter directly.", candidate="A", options=["A. left", "B. right"], history_count=24, revisit_count=4, ) self.assertNotIn("Only give", prompt) self.assertIn("Candidate answer under isolated verification: A. left", prompt) self.assertIn("Return exactly 4 distinct frame numbers", prompt) self.assertTrue(prompt.endswith("and nothing else."))
def test_deliberative_explicit_answer_has_priority_for_open_outputs(self) -> None: self.assertEqual( normalize_answer( "There are 2 early events, then one more. Answer: 3", "Answer with a single number indicating the total count.", [], ), "3", ) self.assertEqual( normalize_answer( "The first condition suggests no, but the final state does. Answer: Yes", 'Please answer only with "Yes" or "No".', [], ), "Yes", )
def test_causalbudget_index_plan_requires_question_blind_complete_coverage( self, ) -> None: import json import tempfile
with tempfile.TemporaryDirectory() as directory: path = Path(directory) / "plan.json" path.write_text( json.dumps( { "format": "iclr_video.causalbudget20_index_plan.v0", "status": "complete_query_independent_execution_cache", "benchmark": "ovo", "contracts": { "question_text_read_for_plan": False, "task_or_group_read_for_plan": False, "model_prediction_read_for_plan": False, "gold_answer_read": False, "future_frames_read": False, }, "rows": [{"uid": "u1", "sampling": {}}], } ) ) rows, artifact = load_causalbudget_index_plan( path, benchmark="ovo", wanted=["u1"] ) self.assertEqual(set(rows), {"u1"}) self.assertEqual(artifact["path"], str(path.resolve()))
value = json.loads(path.read_text()) value.update( { "format": "iclr_video.causalbudget_index_plan.v1", "model_frames": 32, "recent_frames": 8, } ) path.write_text(json.dumps(value)) rows, _ = load_causalbudget_index_plan( path, benchmark="ovo", wanted=["u1"], model_frames=32, recent_frames=8, ) self.assertEqual(set(rows), {"u1"})
def test_temporal_budget_cache_reuses_exact_query_independent_prefix(self) -> None: decoder_path = ( "experiments.evaluate_qwen3vl_recent4_full." "decode_causal_temporal_budget" ) with patch( decoder_path, return_value=([{"pixels": [1]}], {"frame_indices": [3]}), ) as decoder: cache = CausalTemporalBudgetCache(2) frames, sampling, hit = cache.get(Path("v.mp4"), visible_until=4.0) self.assertFalse(hit) frames[0]["pixels"] = [2] sampling["frame_indices"].append(4) frames2, sampling2, hit2 = cache.get( Path("v.mp4"), visible_until=4.0 ) self.assertTrue(hit2) self.assertEqual(frames2, [{"pixels": [1]}]) self.assertEqual(sampling2, {"frame_indices": [3]}) cache.get(Path("v.mp4"), visible_until=5.0) self.assertEqual(decoder.call_count, 2)
def test_native_video_turn_has_one_video_placeholder_and_no_route(self) -> None: frames = [object(), object(), object(), object()] messages = build_visual_messages( frames=frames, prompt="question", visual_input_mode="native-video", ) self.assertEqual(messages[0]["content"][0], {"type": "video"}) self.assertEqual(messages[0]["content"][1]["text"], "question")
def test_hybrid_turn_keeps_history_as_video_and_recent_as_images(self) -> None: history = [object(), object()] recent = [object(), object(), object(), object()] messages = build_visual_messages( frames=[*history, *recent], history_frames=history, recent_frames=recent, prompt="question", visual_input_mode="hybrid-history-video-recent-images", ) content = messages[0]["content"] self.assertEqual(content[0], {"type": "video"}) self.assertEqual([item["type"] for item in content[1:5]], ["image"] * 4) self.assertEqual(content[-1]["text"], "question")
def test_hybrid_singleton_history_falls_back_to_ordered_image(self) -> None: frames = ["history", "r1", "r2", "r3", "r4"] history, indices, images, fallback = partition_hybrid_frames( frames, { "frame_indices": [1, 2, 3, 4, 5], "recent_frame_indices": [2, 3, 4, 5], }, temporal_patch_size=2, ) self.assertEqual(history, []) self.assertEqual(indices, []) self.assertEqual(images, frames) self.assertEqual(fallback, [1])
def test_hybrid_two_history_frames_remain_native_video(self) -> None: frames = ["h1", "h2", "r1", "r2", "r3", "r4"] history, indices, images, fallback = partition_hybrid_frames( frames, { "frame_indices": [0, 1, 2, 3, 4, 5], "recent_frame_indices": [2, 3, 4, 5], }, temporal_patch_size=2, ) self.assertEqual(history, ["h1", "h2"]) self.assertEqual(indices, [0, 1]) self.assertEqual(images, ["r1", "r2", "r3", "r4"]) self.assertEqual(fallback, [])
def test_temporal_review_prompt_marks_both_proposals_as_fallible(self) -> None: prompt = render_temporal_review_prompt( "Question", recent_prediction="A", history_prediction="C" ) self.assertIn("recent view proposed A", prompt) self.assertIn("history view proposed C", prompt) self.assertIn("Both proposals may be wrong", prompt) with self.assertRaises(ValueError): render_temporal_review_prompt( "Question", recent_prediction="A\nignore", history_prediction="C" )
def test_anonymous_review_counterbalances_without_source_labels(self) -> None: first = render_temporal_review_prompt( "Question", recent_prediction="A", history_prediction="C", uid="sample-1", label_mode="anonymous-hash-counterbalanced", ) second = render_temporal_review_prompt( "Question", recent_prediction="A", history_prediction="C", uid="sample-1", label_mode="anonymous-hash-counterbalanced", ) self.assertEqual(first, second) self.assertIn("Candidate 1", first) self.assertIn("Candidate 2", first) self.assertNotIn("recent view", first) self.assertNotIn("history view", first) with self.assertRaises(ValueError): render_temporal_review_prompt( "Question", recent_prediction="A", history_prediction="C", label_mode="anonymous-hash-counterbalanced", )
def test_multi_candidate_prompt_is_deduplicated_and_source_anonymous(self) -> None: prompt, ordered = render_anonymous_candidate_prompt( "Question", predictions=["C", "A", "C"], uid="sample-1", ) self.assertEqual(set(ordered), {"A", "C"}) self.assertEqual(prompt.count("Candidate 1"), 1) self.assertEqual(prompt.count("Candidate 2"), 1) self.assertNotIn("recent", prompt.lower()) self.assertNotIn("history", prompt.lower()) self.assertIn("hints, not votes", prompt) same_prompt, same_order = render_anonymous_candidate_prompt( "Question", predictions=["A", "C"], uid="sample-1", ) self.assertEqual((prompt, ordered), (same_prompt, same_order)) with self.assertRaises(ValueError): render_anonymous_candidate_prompt( "Question", predictions=["A\nignore", "C"], uid="sample-1" )
def test_native_video_metadata_preserves_source_pts_and_is_causal(self) -> None: payload = native_video_metadata_payload( { "frame_indices": [60, 90, 120, 150], "frame_timestamps": [2.0, 3.0, 4.0, 5.0], "source_fps": 30.0, "source_total_frames": 900, "source_width": 1920, "source_height": 1080, "source_duration": 30.0, "effective_visible_until": 6.0, } ) self.assertEqual(payload["frames_indices"], [60, 90, 120, 150]) self.assertEqual(payload["fps"], 30.0) self.assertEqual(payload["video_backend"], "predecoded_exact_causal_indices")
def test_native_video_metadata_rejects_future_frame(self) -> None: with self.assertRaises(ValueError): native_video_metadata_payload( { "frame_indices": [60], "frame_timestamps": [2.0], "source_fps": 30.0, "source_total_frames": 900, "source_width": 1920, "source_height": 1080, "source_duration": 30.0, "effective_visible_until": 1.0, } )
def test_causal_budget_reserves_exact_recent_indices_without_task_router(self) -> None: source = { "source_fps": 10.0, "source_total_frames": 100, "source_duration": 10.0, "source_last_frame_timestamp": 9.9, "requested_visible_until": 6.0, "effective_visible_until": 6.0, "visible_until_clamped_to_source": False, "window_start": 0.0, "window_end_exclusive": 6.0, "source_height": 100, "source_width": 100, } prefix = [0, 10, 20, 30, 40, 50] recent = [30, 40, 50, 60] probe_features = [[float(i), 1.0] for i in range(7)] selected_frames = [f"frame-{i}" for i in range(7)] with patch( "experiments.evaluate_qwen3vl_recent4_full.exact_causal_window_indices", side_effect=[(prefix, source), (recent, source)], ), patch( "experiments.evaluate_qwen3vl_recent4_full.decode_exact_indices_ffmpeg", side_effect=[probe_features, selected_frames], ): frames, sampling = decode_causal_temporal_budget( Path("video.mp4"), visible_until=6.0 ) self.assertEqual(frames, selected_frames) self.assertTrue({30, 40, 50, 60}.issubset(sampling["frame_indices"])) self.assertFalse( sampling["controller"]["benchmark_task_or_group_router"] ) self.assertEqual( sampling["controller"]["policy_config"]["query_weight"], 0.0 ) self.assertEqual(sampling["controller"]["future_frame_violations"], 0)
def test_uniform_history_has_unique_indices_and_no_padding(self) -> None: self.assertEqual(uniform_prefix_indices(-1, 28), []) self.assertEqual(uniform_prefix_indices(2, 28), [0, 1, 2]) values = uniform_prefix_indices(99, 28) self.assertEqual(len(values), 28) self.assertEqual(values, sorted(set(values))) self.assertEqual((values[0], values[-1]), (0, 99))
def test_hybrid32_preserves_recent4_as_separate_exact_indices(self) -> None: source = { "source_fps": 10.0, "source_total_frames": 100, "source_duration": 10.0, "source_last_frame_timestamp": 9.9, "requested_visible_until": 6.0, "effective_visible_until": 6.0, "visible_until_clamped_to_source": False, "window_start": 2.0, "window_end_exclusive": 6.0, "source_height": 100, "source_width": 100, } recent = [30, 40, 50, 60] with patch( "experiments.evaluate_qwen3vl_recent4_full.exact_causal_window_indices", return_value=(recent, source), ), patch( "experiments.evaluate_qwen3vl_recent4_full.decode_exact_indices_ffmpeg", side_effect=lambda _path, indices: [f"frame-{value}" for value in indices], ): frames, sampling = decode_causal_hybrid_prefix( Path("video.mp4"), visible_until=6.0 ) self.assertEqual(sampling["recent_frame_indices"], recent) self.assertEqual(len(sampling["history_frame_indices"]), 28) self.assertEqual(len(sampling["frame_indices"]), 32) self.assertEqual(sampling["frame_indices"], sorted(set(sampling["frame_indices"]))) self.assertEqual(len(frames), 32) self.assertFalse(sampling["controller"]["benchmark_task_or_group_router"]) self.assertFalse(sampling["controller"]["question_keyword_router"])
def test_qwen_video_resize_limits_supports_pixel_api(self) -> None: module = SimpleNamespace( IMAGE_FACTOR=28, VIDEO_MIN_PIXELS=100_352, VIDEO_MAX_PIXELS=602_112, VIDEO_TOTAL_PIXELS=90_316_800, FRAME_FACTOR=2, ) self.assertEqual( _qwen_video_resize_limits(module, 32), (28, 100_352, 602_112), )
def test_qwen_video_resize_limits_supports_token_api(self) -> None: module = SimpleNamespace( SPATIAL_MERGE_SIZE=2, VIDEO_MIN_TOKEN_NUM=128, VIDEO_MAX_TOKEN_NUM=768, MODEL_SEQ_LEN=128_000, FRAME_FACTOR=2, ) factor, minimum, maximum = _qwen_video_resize_limits(module, 32) self.assertEqual((factor, minimum), (28, 100_352)) self.assertEqual(maximum, 602_112)
def test_training_free_active4_policies_only_change_official_sampling_fps(self) -> None: self.assertEqual(frame_policy_sampling_fps("recent4"), 1.0) self.assertEqual(frame_policy_sampling_fps("wide8"), 0.5) self.assertAlmostEqual(frame_policy_sampling_fps("wide12"), 1.0 / 3.0) self.assertEqual(frame_policy_sampling_fps("wide16"), 0.25)
def test_modelonly_frame_policy_is_question_independent(self) -> None: self.assertEqual(resolve_frame_policy("recent4"), "recent4") self.assertEqual(resolve_frame_policy("wide12"), "wide12") self.assertEqual(resolve_frame_policy("prefix8"), "prefix8") self.assertEqual(resolve_frame_policy("prefix32"), "prefix32") self.assertEqual(resolve_frame_policy("causalbudget20"), "causalbudget20") self.assertEqual( resolve_frame_policy("causalbudget32r8"), "causalbudget32r8" ) self.assertEqual(resolve_frame_policy("causalhybrid32"), "causalhybrid32") self.assertEqual( resolve_frame_policy("causalhybrid32r8"), "causalhybrid32r8" ) with self.assertRaises(ValueError): resolve_frame_policy("adaptive_query_budget32")
def test_source_probe_has_small_bounded_cache(self) -> None: self.assertEqual(probe_source_video.cache_parameters()["maxsize"], 8)
def test_decord_reader_pool_bounds_native_decoder_threads(self) -> None: calls = []
class Reader: pass
def video_reader(path, *, num_threads): calls.append((path, num_threads)) return Reader()
pool = DecordReaderPool(2, num_threads=3) with patch.dict( "sys.modules", {"decord": SimpleNamespace(VideoReader=video_reader)} ): first, first_hit = pool.reader("a.mp4") second, second_hit = pool.reader("a.mp4")
self.assertIs(first, second) self.assertFalse(first_hit) self.assertTrue(second_hit) self.assertEqual(calls, [("a.mp4", 3)])
def test_decord_reader_pool_serializes_same_video_prefetch(self) -> None: state_lock = __import__("threading").Lock() active = 0 peak = 0 instances = 0
class Frame: shape = (16, 32, 3)
class Reader: def get_avg_fps(self): nonlocal active, peak with state_lock: active += 1 peak = max(peak, active) time.sleep(0.01) with state_lock: active -= 1 return 30.0
def __len__(self): return 10
def __getitem__(self, index): return Frame()
def video_reader(path, *, num_threads): nonlocal instances instances += 1 return Reader()
pool = DecordReaderPool(2, num_threads=3) with patch.dict( "sys.modules", {"decord": SimpleNamespace(VideoReader=video_reader)} ): with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor: values = list(executor.map(pool.metadata, ["a.mp4"] * 8))
self.assertEqual(values, [(30.0, 10, 16, 32)] * 8) self.assertEqual(instances, 1) self.assertEqual(peak, 1)
def test_exact_decode_cache_reuses_only_matching_sampling_request(self) -> None: from pathlib import Path
class Frame: def __init__(self, value: int) -> None: self.value = value
def copy(self): return Frame(self.value)
calls = []
def decoder(path, **kwargs): calls.append((path, kwargs)) return [Frame(len(calls))], {"frame_indices": [len(calls)]}
cache = RecentWindowCache(2, decoder=decoder) first_frames, first_sampling, first_hit = cache.get( Path("video.mp4"), visible_until=10.0, recent_frames=4, sampling_fps=1.0, ) first_frames[0].value = 99 first_sampling["frame_indices"][0] = 99 second_frames, second_sampling, second_hit = cache.get( Path("video.mp4"), visible_until=10.0, recent_frames=4, sampling_fps=1.0, ) _, _, third_hit = cache.get( Path("video.mp4"), visible_until=11.0, recent_frames=4, sampling_fps=1.0, )
self.assertFalse(first_hit) self.assertTrue(second_hit) self.assertFalse(third_hit) self.assertEqual(len(calls), 2) self.assertEqual(second_frames[0].value, 1) self.assertEqual(second_sampling["frame_indices"], [1]) self.assertEqual(second_sampling["frame_policy"], "recent4") self.assertEqual(second_sampling["policy_sampling_fps"], 1.0) self.assertEqual((cache.hits, cache.misses), (1, 2))
def test_prefix_policy_uses_dedicated_sequential_decoder(self) -> None: cache = RecentWindowCache(0) decoded = ([object()], {"frame_indices": [0]}) with patch( "experiments.evaluate_qwen3vl_recent4_full.decode_prefix_window_ffmpeg", return_value=decoded, ) as decoder: frames, sampling, hit = cache.get( Path("video.mp4"), visible_until=10.0, recent_frames=4, sampling_fps=1.0, frame_policy="prefix32", )
self.assertIs(frames, decoded[0]) self.assertFalse(hit) self.assertEqual(sampling["frame_policy"], "prefix32") decoder.assert_called_once_with( Path("video.mp4"), visible_until=10.0, recent_frames=32, sampling_fps=3.2, )
def test_exact_decode_cache_is_safe_for_parallel_prefix_misses(self) -> None: class Frame: def __init__(self, value: str) -> None: self.value = value
def copy(self): return Frame(self.value)
def decoder(path, **kwargs): time.sleep(0.01) return [Frame(str(path))], {"frame_indices": [str(path)]}
cache = RecentWindowCache(8, decoder=decoder) paths = [Path(f"video-{index}.mp4") for index in range(8)] with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor: values = list( executor.map( lambda path: cache.get( path, visible_until=10.0, recent_frames=32, sampling_fps=3.2, frame_policy="prefix32", ), paths, ) ) self.assertEqual([value[0][0].value for value in values], list(map(str, paths))) self.assertEqual(cache.misses, 8)
def test_exact_decode_cache_singleflights_matching_parallel_requests(self) -> None: class Frame: def copy(self): return Frame()
calls = []
def decoder(path, **kwargs): calls.append((path, kwargs)) time.sleep(0.05) return [Frame()], {"frame_indices": [1]}
cache = RecentWindowCache(8, decoder=decoder)
def request(_): return cache.get( Path("same-video.mp4"), visible_until=10.0, recent_frames=4, sampling_fps=1.0, )
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor: values = list(executor.map(request, range(16)))
self.assertEqual(len(calls), 1) self.assertEqual(cache.misses, 1) self.assertEqual(cache.hits, 15) self.assertGreaterEqual(cache.singleflight_hits, 1) self.assertEqual(sum(bool(value[2]) for value in values), 15)
def test_visible_prefix_is_clamped_to_last_real_frame(self) -> None: effective, clamped = clamp_visible_until_to_source(10.0, 2.0, 9) self.assertEqual(effective, 4.0) self.assertTrue(clamped) effective, clamped = clamp_visible_until_to_source(3.0, 2.0, 9) self.assertEqual(effective, 3.0) self.assertFalse(clamped)
def test_explicit_uid_subset_keeps_export_order(self) -> None: import tempfile from pathlib import Path
with tempfile.TemporaryDirectory() as directory: path = Path(directory) / "samples.jsonl" path.write_text( '{"uid":"a"}\n{"uid":"b"}\n{"uid":"c"}\n', encoding="utf-8", ) self.assertEqual( selected_uids(path, 0, -1, ["c", "a"]), ["a", "c"], )
def test_batched_runner_keeps_auditable_resume_controls(self) -> None: source = Path("experiments/evaluate_qwen3vl_recent4_full.py").read_text( encoding="utf-8" ) launcher = Path("scripts/run_recent4_single_benchmark.sh").read_text( encoding="utf-8" ) self.assertIn('processor.tokenizer.padding_side = "left"', source) self.assertIn("validate_processor_contract(processor_path, protocol)", source) self.assertIn('"inference_batch_size": args.batch_size', source) self.assertIn('"execution_optimization",', source) self.assertIn('--uids-file "$uid_file"', launcher) self.assertIn('uids[index::count]', launcher) self.assertIn('--batch-size "$attempt_batch"', launcher) self.assertIn('attempt_batch=$EVAL_BATCH_SIZE', launcher) self.assertIn('|| smoke_rc=$?', launcher) self.assertIn('|| runner_rc=$?', launcher) self.assertIn( 'after writing a complete validated result', launcher, )
def test_recent_window_is_half_open_and_causal(self) -> None: self.assertEqual(recent_window_bounds(10.0, 4, 1.0), (6.0, 10.0)) self.assertEqual(recent_window_bounds(1.0, 4, 1.0), (0.0, 1.0))
def test_answer_normalization(self) -> None: options = ["A. first", "B. second", "C. third", "D. fourth"] self.assertEqual(normalize_answer("(C) third", "question", options), "C") self.assertEqual(normalize_answer("second", "question", options), "B") self.assertEqual(normalize_answer("A map", "question", ["A. compass", "B. A map", "C. sky", "D. radar"]), "B") self.assertEqual( normalize_answer( "Yes", "Answer only with “Yes” or “No”.", [], ), "Yes", )
def test_streaming_prompt_matches_release_contract(self) -> None: prompt = render_question( "streamingbench", "What is visible?", ["A. first", "B. second", "C. third", "D. fourth"], ) self.assertIn("advanced video question-answering AI assistant", prompt) self.assertTrue(prompt.endswith( "Only give the best option's letter (A, B, C, or D) directly." ))
def test_ovo_mcq_prompt_matches_release_contract(self) -> None: prompt = render_question( "ovo", "What happened?", ["one", "two", "three", "four"], ) self.assertEqual( prompt, "What happened?\nOptions: A. one; B. two; C. three; D. four;" "\nOnly give the best option's letter directly.", )
def test_ovo_requires_full_runtime_asset_attestation(self) -> None: launcher = Path("scripts/run_recent4_single_benchmark.sh").read_text( encoding="utf-8" ) self.assertIn("OVO_RUNTIME_REPORT", launcher) self.assertIn(".expanded_queries == 3035", launcher) self.assertIn(".covered_queries == 3035", launcher) self.assertIn(".missing_videos == 0", launcher) self.assertIn(".annotation_sha256 == $annotation_sha256", launcher) self.assertIn(".frozen_export_sha256 == $frozen_export_sha256", launcher)
if __name__ == "__main__": unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108from __future__ import annotations
import torch
from experiments.train_qwen3vl_sft import _assistant_only_labels_and_weights
class _CharacterTokenizer: im_end_id = 1
def __call__( self, text: str, *, add_special_tokens: bool = False, return_offsets_mapping: bool = False, ) -> dict[str, object]: del add_special_tokens value: dict[str, object] = { "input_ids": [ord(character) + 10 for character in text] } if return_offsets_mapping: value["offset_mapping"] = [ (index, index + 1) for index in range(len(text)) ] return value
def convert_tokens_to_ids(self, token: str) -> int | None: return self.im_end_id if token == "<|im_end|>" else None
class _BoundaryMergingTokenizer: def apply_chat_template( self, messages: list[dict], *, tokenize: bool, add_generation_prompt: bool, ) -> str: assert tokenize is False and add_generation_prompt is False return "".join( item["text"] for message in messages for item in message["content"] if item["type"] == "text" )
def __call__( self, text: str, *, add_special_tokens: bool = False, return_offsets_mapping: bool = False, ) -> dict[str, object]: assert add_special_tokens is False if text == "ABC": value: dict[str, object] = {"input_ids": [100, 101]} if return_offsets_mapping: value["offset_mapping"] = [(0, 2), (2, 3)] return value return {"input_ids": [200 + ord(character) for character in text]}
def convert_tokens_to_ids(self, token: str) -> None: del token return None
def test_only_assistant_semantic_answer_and_terminator_receive_loss() -> None: tokenizer = _CharacterTokenizer() question = "A" answer = "B" input_ids = torch.tensor( tokenizer(question)["input_ids"] + tokenizer(answer)["input_ids"] + [tokenizer.im_end_id], dtype=torch.long, ) messages = [ { "role": "user", "content": [{"type": "text", "text": question}], "loss": False, }, { "role": "assistant", "content": [{"type": "text", "text": answer}], "loss": True, }, ] labels, weights = _assistant_only_labels_and_weights( tokenizer, input_ids, messages ) assert labels.tolist() == [-100, ord("B") + 10, tokenizer.im_end_id] assert weights.tolist() == [0.0, 1.0, 1.0]
def test_rendered_offsets_handle_tokens_crossing_message_boundaries() -> None: tokenizer = _BoundaryMergingTokenizer() messages = [ {"role": "user", "content": [{"type": "text", "text": "A"}]}, {"role": "assistant", "content": [{"type": "text", "text": "B"}]}, {"role": "user", "content": [{"type": "text", "text": "C"}]}, ] labels, weights = _assistant_only_labels_and_weights( tokenizer, torch.tensor([100, 101]), messages ) assert labels.tolist() == [100, -100] assert weights.tolist() == [1.0, 0.0]1234567891011121314151617181920212223242526from data_pipeline.temporal_scope.build_size_matched_generic_control import ( select_parent_ids,)
def _row(parent_id: str, kind: str) -> dict: return {"parents": [{"id": parent_id, "kind": kind}]}
def test_selection_is_deterministic_and_stratified() -> None: rows = [ *[_row(f"source-{i}", "source_semantic_row") for i in range(8)], *[ _row(f"cited-{i}", "cited_nonbenchmark_refresh_projection") for i in range(5) ], ] quotas = { "source_semantic_row": 4, "cited_nonbenchmark_refresh_projection": 2, } first, counts = select_parent_ids(rows, seed="control-v1", quotas=quotas) second, _ = select_parent_ids(list(reversed(rows)), seed="control-v1", quotas=quotas) assert first == second assert len(first) == 6 assert counts == quotas123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125from pathlib import Path
from data_pipeline.temporal_scope.build_source_aligned_sft_release import ( SourceAlignedSFTError, _canonical_media_path, _semantic_identity, _teacher_used_for_labels,)import pytest
def _row(image: str = "media/one.jpg", question: str = "Which one?") -> dict: return { "messages": [ { "role": "user", "loss": False, "content": [ {"type": "image", "image": image}, {"type": "text", "text": question}, ], }, { "role": "assistant", "loss": True, "content": [{"type": "text", "text": "A"}], }, ] }
def test_semantic_identity_binds_pixels_question_and_answer() -> None: inventory = {"media/one.jpg": {"sha256": "a" * 64}} baseline = _semantic_identity(_row(), inventory) assert baseline == _semantic_identity(_row(question=" Which one? "), inventory) assert baseline != _semantic_identity(_row(question="Which event?"), inventory) changed = {"media/one.jpg": {"sha256": "b" * 64}} assert baseline != _semantic_identity(_row(), changed)
def test_canonical_media_path_is_content_addressed() -> None: digest = "ab" + "1" * 62 assert _canonical_media_path("legacy/frame.JPG", digest) == ( f"media/sha256/ab/{digest}.jpg" )
def test_teacher_label_provenance_is_strict_and_propagatable() -> None: assert _teacher_used_for_labels( {"contracts": {"teacher_used_for_labels": True}} ) assert not _teacher_used_for_labels( {"contracts": {"teacher_used_for_labels": False}} ) with pytest.raises(SourceAlignedSFTError): _teacher_used_for_labels({"contracts": {}})
def test_legacy_v62di_loader_defaults_narrow_but_supports_committed_full_pool() -> None: from data_pipeline.temporal_scope.build_source_aligned_sft_release import _load_legacy_v62di_source with pytest.raises(SourceAlignedSFTError, match="Private legacy adapters"): _load_legacy_v62di_source(Path("synthetic-unused-source"))
def test_legacy_repcount_normalization_is_hash_pinned_and_field_narrow() -> None: from data_pipeline.temporal_scope.build_source_aligned_sft_release import _load_legacy_repcount_source with pytest.raises(SourceAlignedSFTError, match="Private legacy adapters"): _load_legacy_repcount_source(Path("synthetic-unused-source"))
def test_pinned_legacy_inputs_count_as_sealed_sources() -> None: text = Path( "data_pipeline/temporal_scope/build_source_aligned_sft_release.py" ).read_text() assert "sealed_source_count" in text assert 'getattr(args, "legacy_v62di_source", None)' in text assert 'getattr(args, "legacy_repcount_source", None)' in text
def test_hash_bound_parent_selection_allows_one_source_filtering_only() -> None: text = Path( "data_pipeline/temporal_scope/build_source_aligned_sft_release.py" ).read_text() assert 'getattr(args, "include_parent_selection", None) is None' in text assert "unless a parent selection is supplied" in text
def test_composite_source_stage_filter_is_range_and_manifest_bound() -> None: text = Path( "data_pipeline/temporal_scope/build_source_aligned_sft_release.py" ).read_text() assert "--include-source-stage-release-id" in text assert "requested source stages are absent" in text assert "source curriculum stage row count diverged" in text assert '"included_source_stage_release_ids"' in text
def test_capability_parent_selection_is_hash_bound_and_fail_closed() -> None: text = Path( "data_pipeline/temporal_scope/build_source_aligned_sft_release.py" ).read_text() assert "--include-parent-selection" in text assert "iclr_video.capability_parent_selection.v0" in text assert "iclr_video.capability_parent_selection.v1" in text assert "source_release_membership_verified" in text assert "selected parent IDs were absent" in text assert '"parent_selection": parent_selection_record' in text
def test_ordered_curriculum_is_one_run_and_preserves_source_order() -> None: text = Path( "data_pipeline/temporal_scope/build_source_aligned_sft_release.py" ).read_text() assert '"training_runs_required": 1' in text assert '"source_stage_then_source_row"' in text assert "if not ordered_curriculum" in text
def test_additive_composition_can_retain_exposures_without_curriculum_order() -> None: text = Path( "data_pipeline/temporal_scope/build_source_aligned_sft_release.py" ).read_text() assert "--retain-semantic-exposures" in text assert "ordered_curriculum or retain_semantic_exposures" in text assert '"retain_semantic_exposures": retain_semantic_exposures' in text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778from experiments.materialize_third_view_disagreement_agent import materialize
IDENTITY = { "benchmark": "demo", "model_manifest_sha256": "m", "annotation_sha256": "a", "evaluation_protocol_sha256": "p", "annotation": "annotation.json", "evaluation_protocol": {}, "model": "model", "processor": "processor",}
def _result(rows: list[dict]) -> dict: return {**IDENTITY, "rows": rows}
def test_third_view_commits_only_on_acquired_disagreement() -> None: recent = _result( [ {"uid": "u0", "prediction": "A", "visual_tokens": 10}, {"uid": "u1", "prediction": "D", "visual_tokens": 10}, ] ) event = _result( [ { "uid": "u0", "prediction": "B", "error": None, "visual_tokens": 20, "sampling": {"frame_indices": list(range(20))}, } ] ) base = _result( [ { "uid": "u0", "prediction": "A", "agent_policy": {"escalated": True}, "media_calls": 2, "num_turns": 2, "model_processed_frames": 24, "sampling": {"frame_indices": list(range(20))}, }, {"uid": "u1", "prediction": "D", "media_calls": 1}, ] ) third = _result( [ { "uid": "u0", "prediction": "C", "raw_response": "C", "error": None, "query_time": 31.0, "frames_observed": 32, "visual_tokens": 30, "sampling": { "frame_indices": list(range(32)), "frame_timestamps": list(map(float, range(32))), }, } ] ) result = materialize(recent, event, base, third) rows = {row["uid"]: row for row in result["rows"]} assert rows["u0"]["prediction"] == "C" assert rows["u0"]["media_calls"] == 3 assert rows["u0"]["model_processed_frames"] == 56 assert rows["u0"]["unique_frames"] == 32 assert rows["u0"]["visual_tokens"] == 60 assert rows["u1"]["prediction"] == "D" assert rows["u1"]["third_view_policy"]["triggered"] is False assert result["policy"]["question_task_group_or_benchmark_router"] is False.gitattributes+2
CITATION.cffAdded+29
LICENSEAdded+202
README.mdAdded+113
added_tokens.jsonAdded+28
chat_template.jinjaAdded+120
code/.gitignoreAdded+20
code/LICENSEAdded+202
code/NOTICEAdded+16
code/README.mdAdded+135
code/configs/evaluation/recent4.example.jsonAdded+74
code/configs/training/deepspeed_zero3_bf16.jsonAdded+16
code/data_pipeline/__init__.pyAdded+1
code/data_pipeline/temporal_scope/__init__.pyAdded+1
code/data_pipeline/temporal_scope/build_size_matched_generic_control.pyAdded+107
code/data_pipeline/temporal_scope/build_source_aligned_sft_release.pyAdded+722
code/data_pipeline/temporal_scope/build_vst_prefix32_semantic.pyAdded+525
code/data_pipeline/temporal_scope/filter_semantic_release_by_blind_audit.pyAdded+329
code/data_pipeline/temporal_scope/filter_semantic_release_by_option_consensus.pyAdded+298
code/data_pipeline/temporal_scope/select_quality_capability_rows.pyAdded+420
code/data_pipeline/temporal_scope/semantic_mcq.pyAdded+90
code/docs/DATA.mdAdded+63
code/docs/EVALUATION.mdAdded+114
code/docs/INSTALL.mdAdded+59
code/docs/TRAINING.mdAdded+50
code/experiments/analyze_uncertainty_temporal_escalation.pyAdded+451
code/experiments/evaluate_qwen3vl_recent4_full.pyAdded
code/experiments/materialize_confidence_gated_third_view_agent.pyAdded+259
code/experiments/materialize_third_view_disagreement_agent.pyAdded+203
code/experiments/materialize_tvs_view_oracle.pyAdded+118
code/experiments/materialize_uncertainty_temporal_agent.pyAdded+465
code/experiments/select_uncertainty_escalation_uids.pyAdded+192
code/experiments/train_qwen3vl_sft.pyAdded+1091
code/experiments/tvs_correctness.pyAdded+80
code/pyproject.tomlAdded+32
code/scripts/__init__.pyAdded+1
code/scripts/configure_evaluation_protocol.pyAdded+62
code/scripts/merge_eval_shards.pyAdded+483
code/scripts/run_recent4_single_benchmark.shAdded+380
code/scripts/score_official_benchmark_predictions.pyAdded+348
code/scripts/validate_evaluation_protocol.pyAdded+28
code/tests/test_confidence_gated_third_view_agent.pyAdded+77
code/tests/test_filter_semantic_release_by_option_consensus.pyAdded+84
code/tests/test_materialize_uncertainty_temporal_agent.pyAdded+551
code/tests/test_public_protocol.pyAdded+47
code/tests/test_recent4_runner.pyAdded+893
code/tests/test_semantic_answer_loss_mask.pyAdded+108
code/tests/test_size_matched_generic_control.pyAdded+26
code/tests/test_source_aligned_sft_release.pyAdded+125
code/tests/test_third_view_disagreement_agent.pyAdded+78