simit 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. simit-0.1.0/LICENSE +202 -0
  2. simit-0.1.0/PKG-INFO +388 -0
  3. simit-0.1.0/README.md +346 -0
  4. simit-0.1.0/pyproject.toml +57 -0
  5. simit-0.1.0/setup.cfg +4 -0
  6. simit-0.1.0/src/simit/__init__.py +39 -0
  7. simit-0.1.0/src/simit/api.py +258 -0
  8. simit-0.1.0/src/simit/backends/__init__.py +112 -0
  9. simit-0.1.0/src/simit/backends/bagel.py +359 -0
  10. simit-0.1.0/src/simit/backends/base.py +114 -0
  11. simit-0.1.0/src/simit/backends/hf.py +336 -0
  12. simit-0.1.0/src/simit/backends/imagegen.py +136 -0
  13. simit-0.1.0/src/simit/backends/lance.py +338 -0
  14. simit-0.1.0/src/simit/backends/mot/engine.py +844 -0
  15. simit-0.1.0/src/simit/backends/mot/kernels.py +130 -0
  16. simit-0.1.0/src/simit/backends/mot/modeling.py +514 -0
  17. simit-0.1.0/src/simit/backends/mot/wan_vae.py +872 -0
  18. simit-0.1.0/src/simit/backends/vllm.py +204 -0
  19. simit-0.1.0/src/simit/config.py +112 -0
  20. simit-0.1.0/src/simit/metrics.py +113 -0
  21. simit-0.1.0/src/simit/pipeline/core.py +586 -0
  22. simit-0.1.0/src/simit/pipeline/prompts.py +167 -0
  23. simit-0.1.0/src/simit/skills/__init__.py +6 -0
  24. simit-0.1.0/src/simit/skills/assets/MERMAID_LICENSE +21 -0
  25. simit-0.1.0/src/simit/skills/assets/mermaid.min.js +3587 -0
  26. simit-0.1.0/src/simit/skills/base.py +172 -0
  27. simit-0.1.0/src/simit/skills/builtin.py +614 -0
  28. simit-0.1.0/src/simit/skills/helpers.py +197 -0
  29. simit-0.1.0/src/simit/skills/pool.py +262 -0
  30. simit-0.1.0/src/simit/skills/prompts.py +2374 -0
  31. simit-0.1.0/src/simit/skills/renderers.py +1292 -0
  32. simit-0.1.0/src/simit/skills/routing.py +89 -0
  33. simit-0.1.0/src/simit/skills/sandbox.py +188 -0
  34. simit-0.1.0/src/simit/skills/web.py +253 -0
  35. simit-0.1.0/src/simit/tune.py +323 -0
  36. simit-0.1.0/src/simit/types.py +96 -0
  37. simit-0.1.0/src/simit/utils.py +67 -0
  38. simit-0.1.0/src/simit.egg-info/PKG-INFO +388 -0
  39. simit-0.1.0/src/simit.egg-info/SOURCES.txt +43 -0
  40. simit-0.1.0/src/simit.egg-info/dependency_links.txt +1 -0
  41. simit-0.1.0/src/simit.egg-info/requires.txt +28 -0
  42. simit-0.1.0/src/simit.egg-info/top_level.txt +1 -0
  43. simit-0.1.0/tests/test_core.py +242 -0
  44. simit-0.1.0/tests/test_kernels.py +52 -0
  45. simit-0.1.0/tests/test_skills.py +219 -0
simit-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
simit-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,388 @@
1
+ Metadata-Version: 2.4
2
+ Name: simit
3
+ Version: 0.1.0
4
+ Summary: SIMIT-ICL: vision-language models that imagine their own in-context demonstrations at test time
5
+ Author: monurcan
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/monurcan/simit
8
+ Project-URL: Repository, https://github.com/monurcan/simit
9
+ Project-URL: Issues, https://github.com/monurcan/simit/issues
10
+ Keywords: vision-language models,in-context learning,test-time adaptation,unified multimodal models
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ License-File: src/simit/skills/assets/MERMAID_LICENSE
17
+ Requires-Dist: torch>=2.12
18
+ Requires-Dist: torchvision
19
+ Requires-Dist: transformers>=4.57
20
+ Requires-Dist: accelerate
21
+ Requires-Dist: safetensors
22
+ Requires-Dist: einops
23
+ Requires-Dist: huggingface_hub
24
+ Requires-Dist: diffusers>=0.36
25
+ Requires-Dist: kernels
26
+ Requires-Dist: flash-linear-attention; platform_system == "Linux"
27
+ Requires-Dist: pillow
28
+ Requires-Dist: numpy
29
+ Requires-Dist: matplotlib
30
+ Requires-Dist: networkx
31
+ Requires-Dist: rdkit
32
+ Requires-Dist: schemdraw
33
+ Requires-Dist: vl-convert-python
34
+ Requires-Dist: playwright
35
+ Requires-Dist: optuna
36
+ Provides-Extra: vllm
37
+ Requires-Dist: vllm>=0.11; extra == "vllm"
38
+ Provides-Extra: dev
39
+ Requires-Dist: pytest; extra == "dev"
40
+ Requires-Dist: datasets; extra == "dev"
41
+ Dynamic: license-file
42
+
43
+ # SIMIT-ICL
44
+
45
+ **Vision-language models that imagine their own in-context demonstrations at test time.**
46
+
47
+ Given an unlabeled query `(image, question)`, SIMIT-ICL has the model synthesize a few similar
48
+ `(image, question, answer)` examples, verifies them, keeps only the useful ones, and answers the query
49
+ with them in context. No labels, no extra training, and one model does all the work (or a standard VLM
50
+ plus a text-to-image tool).
51
+
52
+ ```python
53
+ from simit import SIMIT
54
+
55
+ model = SIMIT.from_pretrained("ByteDance-Seed/BAGEL-7B-MoT")
56
+
57
+ demos = model.imagine(image, question) # imagined (image, question, answer) demos
58
+ answer = model.answer(image, question, demos) # SIMIT-ICL answer
59
+ greedy = model.greedy(image, question) # standard zero-shot answer, for comparison
60
+ ```
61
+
62
+ How one query is processed (paper, Sec. 3 / App. G):
63
+
64
+ 1. **Zero-shot pass:** greedy answer + confidence `p0` (geometric-mean token probability).
65
+ 2. **Adaptive budget (ABA):** `K*(p0)` demos, 0 for queries the model is already sure about.
66
+ 3. **Triplet synthesis:** the model proposes `(description, question, answer)` triplets similar to the query.
67
+ 4. **Realization:** a router picks one of 17 *skills*. Natural images come from the model's own image
68
+ head (BAGEL, Lance) or an image-generator tool (standard VLMs). Charts, diagrams, molecules,
69
+ circuits, tables, flowcharts, etc. are written as code/specs by the model and rendered
70
+ deterministically, with parse/render errors fed back for repair.
71
+ 5. **Critic:** the model scores each image against its description (0-100). Failures are revised and regenerated.
72
+ 6. **Difficulty filter (DF):** keep demos whose teacher-forced answer confidence lies in `[t_low, t_high]`.
73
+ 7. **ICL answer** with the kept demos in context.
74
+
75
+ ## Installation
76
+
77
+ ```bash
78
+ pip install simit # BAGEL, Lance, any transformers VLM
79
+ pip install "simit[vllm]" # + the vLLM engine for standard VLMs (much faster than plain transformers)
80
+
81
+ # or from source
82
+ git clone https://github.com/monurcan/simit && cd simit && pip install -e .
83
+ ```
84
+
85
+ Every skill dependency is a pip wheel: there is no Node.js, Mermaid CLI, cairo or manual browser
86
+ setup. HTML and Mermaid skills render in headless Chromium through Playwright, with the following
87
+ fallbacks:
88
+ 1. Playwright's own browser, if one is installed.
89
+ 2. A system `chromium`/`chrome`.
90
+ 3. Otherwise SIMIT downloads Playwright's headless Chromium once on first use (~100 MB, file-locked
91
+ so parallel processes don't race). If Playwright's downloader fails, as it does behind some HPC
92
+ networks, it fetches the same build with plain Python (proxy environment variables are honored).
93
+
94
+ Mermaid itself ships inside the package.
95
+
96
+ Requirements: Python ≥ 3.10, PyTorch ≥ 2.12 (BAGEL/Lance use `torch.nn.attention.varlen`, so no
97
+ flash-attn build is needed), one CUDA GPU (H100/A100 80GB for the 27B example; BAGEL-7B and Lance
98
+ fit on smaller cards).
99
+
100
+ ## Supported models
101
+
102
+ | model | how images are made | engine |
103
+ |---|---|---|
104
+ | `ByteDance-Seed/BAGEL-7B-MoT` | native image head + 17 skills, critic in thinking mode (as in the paper) | built-in MoT engine |
105
+ | `bytedance-research/Lance` | native image head; defaults to decomposed synthesis, natural images, no critic (its instruction following is weaker) | built-in MoT engine |
106
+ | any `transformers` VLM, e.g. `Qwen/Qwen3.8-27B` | `image_generator=` tool (e.g. `black-forest-labs/FLUX.2-klein-4B`) + 17 skills; omit the tool for skills only | vLLM if installed, else transformers |
107
+
108
+ ```python
109
+ # a standard VLM + a text-to-image tool
110
+ model = SIMIT.from_pretrained("Qwen/Qwen3.8-27B", image_generator="black-forest-labs/FLUX.2-klein-4B")
111
+
112
+ # force an engine
113
+ model = SIMIT.from_pretrained("Qwen/Qwen3.8-27B", engine="transformers") # or "vllm"
114
+
115
+ # wrap a model you already loaded with the standard HF interface
116
+ from transformers import AutoProcessor, AutoModelForMultimodalLM
117
+ processor = AutoProcessor.from_pretrained("Qwen/Qwen3.8-27B")
118
+ hf_model = AutoModelForMultimodalLM.from_pretrained("Qwen/Qwen3.8-27B", device_map="auto")
119
+ model = SIMIT.from_pretrained(hf_model, processor=processor, image_generator="black-forest-labs/FLUX.2-klein-4B")
120
+ ```
121
+
122
+ `image_generator` can be a diffusers model id, a loaded diffusers pipeline, or any callable
123
+ `(prompt, width, height) -> PIL.Image`. On one GPU it is loaded first and the VLM engine sizes its
124
+ memory around it. With several GPUs it goes on the last one.
125
+
126
+ ## Usage
127
+
128
+ ```python
129
+ from simit import SIMIT, save_demos
130
+
131
+ model = SIMIT.from_pretrained("ByteDance-Seed/BAGEL-7B-MoT")
132
+
133
+ # 1) fit ABA + DF on a small labeled validation set (synthesis runs once and is cached)
134
+ model.tune(val_set, metric="vqa_accuracy", max_runtime_ratio=25)
135
+
136
+ # 2) test time
137
+ for image, question in test_set:
138
+ demos = model.imagine(image, question)
139
+ improved = model.answer(image, question, demos)
140
+ ```
141
+
142
+ Main methods:
143
+
144
+ | method | what it does |
145
+ |---|---|
146
+ | `imagine(image, question, k=None, return_details=False, time_limit=None, on_demo=None, on_progress=None)` | adaptive number of demos (ABA + DF); `k=n` forces exactly `n` verified demos; `return_details=True` returns an `Imagination` with the zero-shot answer, `p0`, the budget, every candidate and stats. `time_limit` (seconds) stops and returns the demos accepted so far; `on_demo(demo)` / `on_progress(stage)` stream progress, e.g. to a UI |
147
+ | `zero_shot(image, question)` | the greedy answer with its confidence `p0`; `model.config.budget(zs.confidence)` is the number of demos ABA will ask for. Reused by a following `imagine` |
148
+ | `answer(image, question, demos)` | answer with the demos in context (no demos: zero-shot) |
149
+ | `greedy(image, question)` | the standard zero-shot greedy answer (cached and shared with `imagine`) |
150
+ | `model(image, question)` | `imagine` then `answer` |
151
+ | `imagine_batch(queries)` / `answer_batch(queries, demos)` | many queries at once; their model calls are batched together on the GPU (much faster than a loop) |
152
+ | `tune(val_set, metric, n_trials=100, max_runtime_ratio=None, max_candidates=None, cache_dir=None, k_max_choices=None)` | hyperparameter search (below) |
153
+ | `add_skill(skill)` / `remove_skill(name)` | change the skill library |
154
+
155
+ `val_set` items are `(image, question, answer_or_answers)` tuples or dicts with
156
+ `image`/`question`/`answer(s)` (and optionally their own `metric`, for validation sets that mix benchmarks). `metric` is one of `exact_match`, `vqa_accuracy`, `contains`,
157
+ `anls`, `relaxed_accuracy`, `multiple_choice`, or any `fn(prediction, references) -> float`.
158
+ Images can be PIL images, file paths or raw bytes.
159
+
160
+ ### Saving demos for fine-tuning (SIMIT-FT)
161
+
162
+ ```python
163
+ from simit import save_demos, load_demos
164
+ save_demos(demos, "imagined/query_0") # PNGs + demos.jsonl (with LLaVA-style "conversations")
165
+ ```
166
+
167
+ The JSONL has `image`, `question`, `answer`, `description`, `skill`, `confidence`,
168
+ `verify_score` and a `conversations` field, ready for LLaVA-format fine-tuning scripts. SIMIT-FT
169
+ itself (fine-tuning on the imagined test-set data) is out of scope for this package.
170
+
171
+ ### Hyperparameter tuning
172
+
173
+ `tune` follows App. G. For each validation query it runs synthesis **once** and caches the
174
+ zero-shot answer, `p0`, and `K_max` verified candidates with their confidences (to `cache_dir` too,
175
+ if given). Each Optuna TPE trial only re-selects demos from the cache with the trial's ABA/DF rule
176
+ and re-answers. Answers are memoized per (query, selected subset), so later trials are almost free.
177
+ Only a few demo subsets per query are reachable under any ABA/DF setting (≤ 15 for `K_max=4`); they are
178
+ answered in one batch up front, so trials are lookups and hundreds of them take seconds. The search
179
+ covers `epsilon, A0, A1, B, t_low, t_high` (and `k_max` with `k_max_choices`, e.g. `[4, 6]` as in the
180
+ paper). The paper defaults and plain `K_max`-shot ICL are evaluated first. If no configuration beats
181
+ zero-shot on the validation set, the tuned config never imagines (zero-shot answers, no extra cost).
182
+ The paper uses 50 validation examples per benchmark.
183
+
184
+ Runtime budget, which matters because synthesis dominates runtime:
185
+ - `max_runtime_ratio=25` caps the *estimated* batched runtime relative to zero-shot. The estimate
186
+ comes from three timings measured on your machine during tuning: the batched zero-shot time per
187
+ query, the batched synthesis time per candidate (saved as `cost.json` in `cache_dir` for later
188
+ runs), and the ICL answer time. In our runs the measured test-time ratio was within about ±25% of
189
+ the estimate, so leave some margin.
190
+ - `max_candidates` caps the mean number of candidates synthesized per query. `1.0` with `K_max=4` is
191
+ the paper's operating point (ABA synthesizes ~23% of `K_max`).
192
+ - With neither, the search maximizes accuracy alone and usually spends the whole budget.
193
+
194
+ How much one candidate costs relative to a zero-shot answer depends heavily on the model and task.
195
+ With BAGEL, a candidate needs ~1.3-1.9 generated images (critic retries), each taking ~2 s on an H100.
196
+ A short VQA answer takes ~0.1 s.
197
+
198
+ ```python
199
+ result = model.tune(val, metric="vqa_accuracy", n_trials=300, max_runtime_ratio=25, cache_dir="cache/vizwiz")
200
+ print(result) # best/zero-shot score, gain, candidates/demos per query, est. runtime, params
201
+ model.config.save("vizwiz.json")
202
+ model.config = SIMITConfig.load("vizwiz.json")
203
+ ```
204
+
205
+ ## Custom skills
206
+
207
+ A skill turns a text description into an image through a model-written spec. Subclass
208
+ `simit.Skill`: the router learns the new category from `route_hint` and `examples`. If `parse` or
209
+ `render` raises `SpecError(msg)`, `msg` is shown to the model so it can repair its spec.
210
+
211
+ ```python
212
+ import simit
213
+ from simit import SpecError
214
+
215
+ class SheetMusic(simit.Skill):
216
+ name = "sheet_music"
217
+ route_hint = "musical notation: staves, notes, chords"
218
+ examples = [ # (description, spec) few-shot pairs for the spec prompt
219
+ ("A C major scale in quarter notes.", "X:1\nK:C\nL:1/4\nCDEF GABc|"),
220
+ ("A G major chord held for a whole note.", "X:1\nK:G\nL:1\n[GBd]|"),
221
+ ]
222
+
223
+ def parse(self, text):
224
+ abc = simit.extract_fenced_block(text) or text
225
+ if "K:" not in abc:
226
+ raise SpecError("the ABC spec needs a key line such as 'K:C'")
227
+ return abc
228
+
229
+ def render(self, abc) -> "PIL.Image.Image":
230
+ return my_abc_renderer(abc) # any deterministic renderer
231
+
232
+ model.add_skill(SheetMusic())
233
+ ```
234
+
235
+ Optional attributes and hooks:
236
+ - `route_examples`: example descriptions for the router (default: the descriptions in `examples`).
237
+ - `prompt`: a full spec prompt with `{request}` to replace the one built from `examples`.
238
+ - `max_new_tokens`, `first_temperature`, `retry_temperature`.
239
+ - `verify_rubric = "strict" | "structured"`.
240
+ - `render_in_subprocess`: renders run in a crash- and timeout-isolated worker pool. Skills defined in
241
+ `__main__` or holding unpicklable state run in a thread instead.
242
+ - `shortcut(request)`: render without a model call.
243
+ - `clean(text)`.
244
+
245
+ The 17 built-in skills: natural, diagram, graph, molecule, circuit, vector, venn, table, scene,
246
+ puzzle, geometry, figure (sandboxed matplotlib), mermaid, svg, vegalite, html, html_composite
247
+ (multi-panel layouts whose panels are realized recursively).
248
+
249
+ ### Loading once, running per request (e.g. Hugging Face ZeroGPU)
250
+
251
+ Model weights can be loaded once and wrapped in a fresh engine per request, which is what a
252
+ ZeroGPU Space needs (it forks the process for every GPU call, so no engine threads may exist in
253
+ the main process, and the main process must not initialize CUDA):
254
+
255
+ ```python
256
+ from simit import SIMIT, SIMITConfig
257
+ from simit.backends.bagel import BagelBackend, BagelModel
258
+
259
+ weights = BagelModel.load("ByteDance-Seed/BAGEL-7B-MoT", device="cpu") # at startup
260
+
261
+ @spaces.GPU(duration=90)
262
+ def run(image, question):
263
+ sim = SIMIT(BagelBackend(weights, device="cuda", use_cuda_graphs=False), config=SIMITConfig(k_max=2))
264
+ try:
265
+ demos = sim.imagine(image, question, time_limit=60)
266
+ return sim.greedy(image, question), sim.answer(image, question, demos)
267
+ finally:
268
+ sim.close()
269
+ ```
270
+
271
+ `LanceModel.load` / `LanceBackend` work the same way. For a transformers model, pass the loaded
272
+ model and processor to `HFBackend`. The SIMIT demo Space (three models, per-budget presets, a
273
+ streaming UI) is built this way.
274
+
275
+ ### New model families
276
+
277
+ `simit.backends.register_backend(name, detect, factory)` adds a backend. It subclasses
278
+ `simit.backends.Backend` and implements `submit_generate`, `submit_score` and, for native image
279
+ generation, `submit_image`. `pipeline_defaults` can change synthesis defaults for that model
280
+ (see `LanceBackend`).
281
+
282
+ ## Configuration
283
+
284
+ `SIMITConfig` (`model.config`, or `from_pretrained(..., config=...)`). `None` means the backend's default.
285
+
286
+ | field | default | meaning |
287
+ |---|---|---|
288
+ | `k_max` | 4 | max demos per query |
289
+ | `use_aba`, `epsilon`, `A0`, `A1`, `B` | True, 0.14, 0.35, 0.60, 0.2 | adaptive budget allocation (App. D) |
290
+ | `use_df`, `t_low`, `t_high` | True, 0.2, 0.9 | difficulty-filter confidence band |
291
+ | `synthesis` | `"batch"` (Lance: `"decomposed"`) | one call for all triplets vs. three short calls per triplet |
292
+ | `diversity_prompt` | True | the paper's diversity-encouraging triplet prompt |
293
+ | `use_skills` | True (Lance: False) | structured skill library vs. natural images only |
294
+ | `verify`, `verify_threshold`, `verify_think` | True (Lance: False), 50, BAGEL: True | critic |
295
+ | `attempts_per_slot`, `repair_retries`, `verify_rounds` | 4, 2, 5 | breadth-first slot-filling budget |
296
+ | `image_size` | 400 | natively generated image side |
297
+ | `speculative` | on for `imagine`, off for `imagine_batch`/`tune` | start all remaining candidate attempts at once (lower latency for a lone query; wasted work when the GPU is busy) |
298
+ | `answer_max_new_tokens` | 128 | answer length (also per call: `max_new_tokens=`) |
299
+ | `seed` | None | image-generation seed |
300
+
301
+ Environment variables:
302
+ - `SIMIT_CHROMIUM`: path to a Chromium/Chrome binary.
303
+ - `PLAYWRIGHT_BROWSERS_PATH`: where Playwright's browsers live.
304
+ - `SIMIT_RENDER_WORKERS`: number of render processes. The default is derived from the CPUs
305
+ available to the job (LSF/SLURM aware).
306
+
307
+ ## Performance
308
+
309
+ Everything that can overlap does:
310
+
311
+ - **Built-in engine for BAGEL/Lance**, running both the understanding and generation experts:
312
+ - continuous batching of decode, prefill and diffusion steps from all concurrent requests
313
+ - automatic prefix caching of shared prompt prefixes (the long router and skill few-shot prompts
314
+ are prefilled once)
315
+ - CUDA graphs for decode
316
+ - experts run on contiguous token slices, with fused Triton kernels for RMSNorm, RoPE and SwiGLU
317
+ (bit-exact with the eager ops up to reduction order)
318
+ - separate high-priority text and image streams, so diffusion doesn't stall decoding
319
+ - **vLLM** for standard VLMs (transformers fallback batches concurrent requests).
320
+ - **Pipeline:**
321
+ - triplets are streamed into realization as they are decoded, and synthesis stops once enough are kept
322
+ - breadth-first slot filling: every triplet gets one cheap attempt before failures get repairs
323
+ - the online ABA/DF rule stops as soon as `K*` demos pass. A lone `imagine` call runs the
324
+ remaining candidate attempts in parallel (`speculative`), since an idle GPU makes that nearly free
325
+ - renders run in a process pool (warm matplotlib zygote, one shared headless browser)
326
+ - **`imagine_batch`/`tune`** run many queries concurrently so their calls share GPU batches.
327
+
328
+ Measured on one H100 with `tests/bench.py`: LMMs-Eval-Lite slices, tuned on 60 validation queries
329
+ (300 trials), tested on 60 different queries. Runtime is the batched wall time relative to batched
330
+ zero-shot answering. With 60 test queries, differences of a few points are within noise.
331
+
332
+ Tuned with `max_runtime_ratio=25`:
333
+
334
+ | model | task | test zero-shot → SIMIT-ICL | runtime (estimated) |
335
+ |---|---|---|---|
336
+ | BAGEL-7B-MoT | VizWiz | 0.494 → **0.556** (+12.4%) | 25.0× (22.0×) |
337
+ | BAGEL-7B-MoT | OK-VQA | 0.650 → 0.650 (nothing beat zero-shot on validation) | 1.0× |
338
+ | Lance | VizWiz | 0.106 → 0.089 | 27.0× (21.3×) |
339
+ | Lance | OK-VQA | 0.483 → 0.489 (+1.1%) | 17.4× (23.3×) |
340
+
341
+ Tuned with `max_candidates=1.0`:
342
+
343
+ | model | task | test zero-shot → SIMIT-ICL | runtime |
344
+ |---|---|---|---|
345
+ | BAGEL-7B-MoT | VizWiz | 0.494 → **0.567** (+14.6%) | 29.3× |
346
+ | BAGEL-7B-MoT | OK-VQA | 0.650 → 0.661 (+1.7%) | 64.6× |
347
+ | BAGEL-7B-MoT | ChartQA | 0.817 → 0.817 (zero-shot chosen) | 1.0× |
348
+ | BAGEL-7B-MoT | AI2D | 0.950 → 0.933 | 12.1× |
349
+ | Qwen3.8-27B + FLUX.2-klein-4B (vLLM) | VizWiz | 0.522 → 0.522 | 12.0× |
350
+ | Qwen3.8-27B + FLUX.2-klein-4B (vLLM) | OK-VQA / ChartQA | unchanged (zero-shot chosen) | 0.9× |
351
+ | Qwen3.8-27B + FLUX.2-klein-4B (vLLM) | AI2D | 0.900 → 0.900 | 49.7× |
352
+
353
+ What the numbers show:
354
+ - BAGEL's VizWiz gain reproduces the paper's direction.
355
+ - Lance matches the research implementation's VizWiz behavior. Its zero-shot answers are mostly
356
+ "No", which gives a very low baseline.
357
+ - Qwen3.8-27B gains little from imagined demos on these tasks.
358
+ - The OK-VQA and AI2D rows at 50-65× show why a runtime cap beats a candidate cap. One BAGEL
359
+ candidate needs ~1.3-1.9 generated images at ~2 s each (50 steps, CFG), while a short answer
360
+ takes ~0.1 s.
361
+
362
+ Single-query latency, i.e. what one demo request feels like:
363
+ - **BAGEL:** 13.9 s on average on VizWiz (16 s for queries that get demos), with speculative attempts.
364
+ Greedy takes 0.29 s.
365
+ - **Qwen3.8-27B + FLUX:** ~20 s for `imagine(k=2)`.
366
+ - **Lance:** ~1-2 s.
367
+
368
+ The BAGEL/Lance engine matches the research implementation: 17/18 (BAGEL) and 15/18 (Lance)
369
+ identical greedy answers on reference samples, with the rest near-ties.
370
+
371
+ ## Differences from the research code
372
+
373
+ - The tuner caches `K_max` candidates and memoizes answers per demo subset (as in App. G), with an
374
+ optional synthesis budget (`max_candidates`).
375
+ - Fixed a cleanup bug that stripped valid CSS after CJK characters in HTML specs.
376
+ - Duplicate questions within a query's demos are dropped, and a `[...]` copied from the triplet
377
+ template around a whole field (`Answer: [3]`) is removed, as are chat preambles ("Sure, here's
378
+ the first one: ...") in decomposed questions.
379
+ - Triplet synthesis is streamed and stops early.
380
+ - When the critic's reasoning hits the token limit before its `SCORE:` line, a short follow-up asks
381
+ for the score instead of discarding the candidate.
382
+ - Prompts (triplet, router, skills, critic, revision, ICL format) are the research prompts verbatim;
383
+ the triplet prompt is question-free, as in the code.
384
+
385
+ ## License
386
+
387
+ Apache-2.0. `simit/backends/mot/wan_vae.py` is adapted from vllm-omni (Apache-2.0). Mermaid
388
+ (MIT) is bundled under `simit/skills/assets/`.