Publish Shiftedx Bench v0.1.0
Browse files- .gitignore +10 -0
- LICENSE +189 -0
- README.md +167 -0
- SECURITY.md +7 -0
- configs/context-release-v1.json +32 -0
- configs/context-smoke-v1.json +32 -0
- configs/mtplx-parity-v1.json +38 -0
- configs/suites-release-v1.json +20 -0
- configs/suites-smoke-v1.json +20 -0
- docs/leaderboard-policy.md +34 -0
- docs/methodology.md +69 -0
- pyproject.toml +29 -0
- schemas/context-config-v1.schema.json +30 -0
- schemas/result-v1.schema.json +27 -0
- src/shiftedx_bench/__init__.py +7 -0
- src/shiftedx_bench/agentic.py +263 -0
- src/shiftedx_bench/api.py +130 -0
- src/shiftedx_bench/boundary.py +65 -0
- src/shiftedx_bench/cli.py +301 -0
- src/shiftedx_bench/context.py +340 -0
- src/shiftedx_bench/holdout.py +29 -0
- src/shiftedx_bench/models.py +46 -0
- src/shiftedx_bench/provenance.py +47 -0
- src/shiftedx_bench/quality.py +215 -0
- src/shiftedx_bench/release.py +30 -0
- src/shiftedx_bench/runner.py +153 -0
- src/shiftedx_bench/sandbox.py +74 -0
- src/shiftedx_bench/scoring.py +74 -0
- src/shiftedx_bench/summary.py +145 -0
- src/shiftedx_bench/tokenizer.py +93 -0
- src/shiftedx_bench/tools.py +98 -0
- src/shiftedx_bench/util.py +57 -0
- src/shiftedx_bench/vision.py +117 -0
- tests/conftest.py +9 -0
- tests/test_context.py +95 -0
- tests/test_quality_tools_vision.py +36 -0
- tests/test_runner_summary_release.py +63 -0
- tests/test_scoring_and_sandbox.py +40 -0
.gitignore
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.py[cod]
|
| 3 |
+
.pytest_cache/
|
| 4 |
+
.venv/
|
| 5 |
+
dist/
|
| 6 |
+
build/
|
| 7 |
+
*.egg-info/
|
| 8 |
+
results/
|
| 9 |
+
vision-fixtures/
|
| 10 |
+
.DS_Store
|
LICENSE
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
https://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work.
|
| 38 |
+
|
| 39 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 40 |
+
form, that is based on (or derived from) the Work and for which the
|
| 41 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 42 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 43 |
+
of this License, Derivative Works shall not include works that remain
|
| 44 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 45 |
+
the Work and Derivative Works thereof.
|
| 46 |
+
|
| 47 |
+
"Contribution" shall mean any work of authorship, including
|
| 48 |
+
the original version of the Work and any modifications or additions
|
| 49 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 50 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 51 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 52 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 53 |
+
means any form of electronic, verbal, or written communication sent
|
| 54 |
+
to the Licensor or its representatives, including but not limited to
|
| 55 |
+
communication on electronic mailing lists, source code control systems,
|
| 56 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 57 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 58 |
+
excluding communication that is conspicuously marked or otherwise
|
| 59 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 60 |
+
|
| 61 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 62 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 63 |
+
subsequently incorporated within the Work.
|
| 64 |
+
|
| 65 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 66 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 67 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 68 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 69 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 70 |
+
Work and such Derivative Works in Source or Object form.
|
| 71 |
+
|
| 72 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 73 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 74 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 75 |
+
(except as stated in this section) patent license to make, have made,
|
| 76 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 77 |
+
where such license applies only to those patent claims licensable
|
| 78 |
+
by such Contributor that are necessarily infringed by their
|
| 79 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 80 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 81 |
+
institute patent litigation against any entity (including a
|
| 82 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 83 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 84 |
+
or contributory patent infringement, then any patent licenses
|
| 85 |
+
granted to You under this License for that Work shall terminate
|
| 86 |
+
as of the date such litigation is filed.
|
| 87 |
+
|
| 88 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 89 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 90 |
+
modifications, and in Source or Object form, provided that You
|
| 91 |
+
meet the following conditions:
|
| 92 |
+
|
| 93 |
+
(a) You must give any other recipients of the Work or
|
| 94 |
+
Derivative Works a copy of this License; and
|
| 95 |
+
|
| 96 |
+
(b) You must cause any modified files to carry prominent notices
|
| 97 |
+
stating that You changed the files; and
|
| 98 |
+
|
| 99 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 100 |
+
that You distribute, all copyright, patent, trademark, and
|
| 101 |
+
attribution notices from the Source form of the Work,
|
| 102 |
+
excluding those notices that do not pertain to any part of
|
| 103 |
+
the Derivative Works; and
|
| 104 |
+
|
| 105 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 106 |
+
distribution, then any Derivative Works that You distribute must
|
| 107 |
+
include a readable copy of the attribution notices contained
|
| 108 |
+
within such NOTICE file, excluding those notices that do not
|
| 109 |
+
pertain to any part of the Derivative Works, in at least one
|
| 110 |
+
of the following places: within a NOTICE text file distributed
|
| 111 |
+
as part of the Derivative Works; within the Source form or
|
| 112 |
+
documentation, if provided along with the Derivative Works; or,
|
| 113 |
+
within a display generated by the Derivative Works, if and
|
| 114 |
+
wherever such third-party notices normally appear. The contents
|
| 115 |
+
of the NOTICE file are for informational purposes only and
|
| 116 |
+
do not modify the License. You may add Your own attribution
|
| 117 |
+
notices within Derivative Works that You distribute, alongside
|
| 118 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 119 |
+
that such additional attribution notices cannot be construed
|
| 120 |
+
as modifying the License.
|
| 121 |
+
|
| 122 |
+
You may add Your own copyright statement to Your modifications and
|
| 123 |
+
may provide additional or different license terms and conditions
|
| 124 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 125 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 126 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 127 |
+
the conditions stated in this License.
|
| 128 |
+
|
| 129 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 130 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 131 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 132 |
+
this License, without any additional terms or conditions.
|
| 133 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 134 |
+
the terms of any separate license agreement you may have executed
|
| 135 |
+
with Licensor regarding such Contributions.
|
| 136 |
+
|
| 137 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 138 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 139 |
+
except as required for reasonable and customary use in describing the
|
| 140 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 141 |
+
|
| 142 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 143 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 144 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 145 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 146 |
+
implied, including, without limitation, any warranties or conditions
|
| 147 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 148 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 149 |
+
appropriateness of using or redistributing the Work and assume any
|
| 150 |
+
risks associated with Your exercise of permissions under this License.
|
| 151 |
+
|
| 152 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 153 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 154 |
+
unless required by applicable law (such as deliberate and grossly
|
| 155 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 156 |
+
liable to You for damages, including any direct, indirect, special,
|
| 157 |
+
incidental, or consequential damages of any character arising as a
|
| 158 |
+
result of this License or out of the use or inability to use the
|
| 159 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 160 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 161 |
+
other commercial damages or losses), even if such Contributor
|
| 162 |
+
has been advised of the possibility of such damages.
|
| 163 |
+
|
| 164 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 165 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 166 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 167 |
+
or other liability obligations and/or rights consistent with this
|
| 168 |
+
License. However, in accepting such obligations, You may act only
|
| 169 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 170 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 171 |
+
defend, and hold each Contributor harmless for any liability
|
| 172 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 173 |
+
of your accepting any such warranty or additional liability.
|
| 174 |
+
|
| 175 |
+
END OF TERMS AND CONDITIONS
|
| 176 |
+
|
| 177 |
+
Copyright 2026 Shiftedx
|
| 178 |
+
|
| 179 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 180 |
+
you may not use this file except in compliance with the License.
|
| 181 |
+
You may obtain a copy of the License at
|
| 182 |
+
|
| 183 |
+
https://www.apache.org/licenses/LICENSE-2.0
|
| 184 |
+
|
| 185 |
+
Unless required by applicable law or agreed to in writing, software
|
| 186 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 187 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 188 |
+
See the License for the specific language governing permissions and
|
| 189 |
+
limitations under the License.
|
README.md
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
pretty_name: Shiftedx Bench
|
| 4 |
+
task_categories:
|
| 5 |
+
- text-generation
|
| 6 |
+
- question-answering
|
| 7 |
+
- visual-question-answering
|
| 8 |
+
tags:
|
| 9 |
+
- evaluation
|
| 10 |
+
- long-context
|
| 11 |
+
- mlx
|
| 12 |
+
- mtplx
|
| 13 |
+
- tool-calling
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
# Shiftedx Bench
|
| 17 |
+
|
| 18 |
+
Shiftedx Bench is a reproducible qualification suite for local language-model deployments. It measures model quality, effective long-context use, tool protocol reliability, multi-turn agent behavior, vision, and runtime performance without collapsing them into a single “intelligence” score.
|
| 19 |
+
|
| 20 |
+
The project is designed for quantization and speculative-decoding decisions on Apple Silicon, but its API runner works with any OpenAI-compatible chat endpoint.
|
| 21 |
+
|
| 22 |
+
## What it evaluates
|
| 23 |
+
|
| 24 |
+
- **Quality:** 50 procedurally varied reasoning, transformation, algorithm, and executable-code cases in the release configuration.
|
| 25 |
+
- **Long context:** exact rendered-token prompts from 4,096 through 260,096 tokens, seven evidence positions, multiple seeds, before/after query placement, and six task families.
|
| 26 |
+
- **Tools:** 30 procedurally varied release cases with strict protocol-level function and argument comparison, including parallel calls and correct refusal to perform underspecified destructive actions.
|
| 27 |
+
- **Agentic behavior:** multi-turn inspect/patch/test, failed-search recovery, false-error handling, and repair loops with deterministic tool environments.
|
| 28 |
+
- **Vision:** deterministic OCR, chart, spatial, and multi-image fixtures.
|
| 29 |
+
- **MTPLX parity:** paired AR, D1, D2, and D3 runs with quality deltas, throughput, and native acceptance telemetry.
|
| 30 |
+
|
| 31 |
+
Every long-context prompt is built against the model's own tokenizer and chat template. The runner refuses to count a result if the server-reported prompt length differs from the requested rendered-token count.
|
| 32 |
+
|
| 33 |
+
## Status
|
| 34 |
+
|
| 35 |
+
Version `0.1.0` is the first public methodology release. It is suitable for local regression and qualification. Public leaderboard claims additionally require the release suite, rotating holdout seeds, raw result publication, and the policy in [docs/leaderboard-policy.md](docs/leaderboard-policy.md).
|
| 36 |
+
|
| 37 |
+
This benchmark does not claim to replace RULER, HELM Long Context, NoLiMa, LiveCodeBench, BFCL, SWE-bench, or broad academic evaluations. Its distinctive purpose is paired local-deployment qualification across quality, context, multimodality, and runtime acceleration.
|
| 38 |
+
|
| 39 |
+
## Install
|
| 40 |
+
|
| 41 |
+
```bash
|
| 42 |
+
python -m venv .venv
|
| 43 |
+
.venv/bin/pip install -e '.[tokenizers,vision,test]'
|
| 44 |
+
.venv/bin/pytest
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
## Inspect the workload
|
| 48 |
+
|
| 49 |
+
```bash
|
| 50 |
+
.venv/bin/shiftedx-bench plan-context \
|
| 51 |
+
--config configs/context-smoke-v1.json \
|
| 52 |
+
--output context-plan.json
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
The smoke context suite contains 19 cases and approximately 1.51 million requested input tokens. The release context suite contains 312 cases and approximately 39.53 million requested input tokens per model variant.
|
| 56 |
+
|
| 57 |
+
After the release grid, verify that the runtime rejects an input beyond its declared boundary instead of silently truncating it:
|
| 58 |
+
|
| 59 |
+
```bash
|
| 60 |
+
.venv/bin/shiftedx-bench probe-boundary \
|
| 61 |
+
--tokenizer '<local-model-or-tokenizer-directory>' \
|
| 62 |
+
--base-url '<openai-compatible-base-url>/v1' \
|
| 63 |
+
--model '<served-model-id>' \
|
| 64 |
+
--output results/context-boundary.json
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
Add `--include-positive` to repeat the maximum usable prompt as part of the boundary probe.
|
| 68 |
+
|
| 69 |
+
## Run a context smoke test
|
| 70 |
+
|
| 71 |
+
```bash
|
| 72 |
+
.venv/bin/shiftedx-bench run-context \
|
| 73 |
+
--config configs/context-smoke-v1.json \
|
| 74 |
+
--tokenizer '<local-model-or-tokenizer-directory>' \
|
| 75 |
+
--base-url '<openai-compatible-base-url>/v1' \
|
| 76 |
+
--model '<served-model-id>' \
|
| 77 |
+
--output results/context-smoke.jsonl \
|
| 78 |
+
--stream
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
The context generator defaults to thinking enabled with medium reasoning effort. Set `--thinking off` or change `--reasoning-effort` only when the same fields are applied to the server request; these template controls are part of the token-count contract.
|
| 82 |
+
|
| 83 |
+
Results are appended as JSONL and resume by `(case_id, variant)`. API keys are read only from a named environment variable using `--api-key-env`; token values are never accepted as command-line arguments.
|
| 84 |
+
|
| 85 |
+
## Run qualification lanes
|
| 86 |
+
|
| 87 |
+
```bash
|
| 88 |
+
.venv/bin/shiftedx-bench run-suite \
|
| 89 |
+
--suite quality \
|
| 90 |
+
--config configs/suites-smoke-v1.json \
|
| 91 |
+
--base-url '<openai-compatible-base-url>/v1' \
|
| 92 |
+
--model '<served-model-id>' \
|
| 93 |
+
--output results/quality.jsonl
|
| 94 |
+
|
| 95 |
+
.venv/bin/shiftedx-bench run-suite \
|
| 96 |
+
--suite tools \
|
| 97 |
+
--config configs/suites-smoke-v1.json \
|
| 98 |
+
--base-url '<openai-compatible-base-url>/v1' \
|
| 99 |
+
--model '<served-model-id>' \
|
| 100 |
+
--output results/tools.jsonl
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
The other suite names are `agentic` and `vision`.
|
| 104 |
+
|
| 105 |
+
## Compare AR with MTPLX depths
|
| 106 |
+
|
| 107 |
+
Pass the frozen variant file to the quality, context, tool, or vision runner:
|
| 108 |
+
|
| 109 |
+
```bash
|
| 110 |
+
.venv/bin/shiftedx-bench run-suite \
|
| 111 |
+
--suite quality \
|
| 112 |
+
--config configs/suites-release-v1.json \
|
| 113 |
+
--variants configs/mtplx-parity-v1.json \
|
| 114 |
+
--base-url '<openai-compatible-base-url>/v1' \
|
| 115 |
+
--model '<served-model-id>' \
|
| 116 |
+
--output results/quality-parity.jsonl
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
AR is the parent lane. D1, D2, or D3 is promotable only when it has no critical regression and meets a speed threshold declared before the run.
|
| 120 |
+
|
| 121 |
+
For a context parity run using `configs/mtplx-parity-v1.json`, also pass `--thinking off`. The runner rejects a tokenizer-template mode that disagrees with the variant request rather than accepting a shifted token grid.
|
| 122 |
+
|
| 123 |
+
## Summarize
|
| 124 |
+
|
| 125 |
+
```bash
|
| 126 |
+
.venv/bin/shiftedx-bench summarize \
|
| 127 |
+
results/context-smoke.jsonl results/quality.jsonl results/tools.jsonl \
|
| 128 |
+
--output results/summary.json
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
The summary contains category scorecards, bootstrap confidence intervals, length/position heatmap cells, worst-cell context accuracy, effective context length, and paired variant deltas.
|
| 132 |
+
|
| 133 |
+
## Public-release check
|
| 134 |
+
|
| 135 |
+
```bash
|
| 136 |
+
.venv/bin/shiftedx-bench validate-release --root .
|
| 137 |
+
```
|
| 138 |
+
|
| 139 |
+
The check rejects access-token patterns, private keys, user-specific absolute paths, and loopback URLs accidentally captured in public artifacts. Raw outputs must be copied into a clean release tree and scanned before publication.
|
| 140 |
+
|
| 141 |
+
For an official comparison, derive rotating holdout seeds from a private environment value rather than checking them into source:
|
| 142 |
+
|
| 143 |
+
```bash
|
| 144 |
+
.venv/bin/shiftedx-bench make-holdout \
|
| 145 |
+
--template configs/context-release-v1.json \
|
| 146 |
+
--release-id '<release-id>' \
|
| 147 |
+
--master-key-env SHIFTEDX_BENCH_HOLDOUT_KEY \
|
| 148 |
+
--output '<private-output-directory>/context-holdout.json'
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
## Repository map
|
| 152 |
+
|
| 153 |
+
```text
|
| 154 |
+
configs/ frozen smoke, release, and MTPLX contracts
|
| 155 |
+
docs/ methodology and leaderboard policy
|
| 156 |
+
schemas/ versioned result and context schemas
|
| 157 |
+
src/shiftedx_bench/ generators, runner, scorers, sandbox, summaries
|
| 158 |
+
tests/ generator, scorer, mutation, resume, and privacy tests
|
| 159 |
+
```
|
| 160 |
+
|
| 161 |
+
## Methodology influences
|
| 162 |
+
|
| 163 |
+
The context design incorporates position sensitivity demonstrated by [Lost in the Middle](https://arxiv.org/abs/2307.03172), task diversity from [RULER](https://github.com/NVIDIA/RULER), and non-literal retrieval motivation from [NoLiMa](https://github.com/adobe-research/NoLiMa). Tool evaluation uses strict structured-call comparison in the spirit of [BFCL](https://gorilla.cs.berkeley.edu/leaderboard). These external datasets are not redistributed here; consult their licenses before combining them with Shiftedx Bench.
|
| 164 |
+
|
| 165 |
+
## License
|
| 166 |
+
|
| 167 |
+
Shiftedx Bench's original code, configurations, and procedurally generated fixtures are licensed under Apache-2.0. Model outputs retain any rights or restrictions imposed by the evaluated model and its source license.
|
SECURITY.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Security
|
| 2 |
+
|
| 3 |
+
Do not put API keys in commands, configurations, result files, examples, issues, or model responses. Supply credentials only through a named environment variable and run the public-release scanner before publishing.
|
| 4 |
+
|
| 5 |
+
Generated Python is screened and executed in a limited subprocess. This reduces accidental risk but is not a hardened boundary for hostile submissions. Any hosted evaluator must additionally use an ephemeral container or virtual machine, disable networking, mount no credentials, cap CPU/memory/files/output, and destroy the environment after each case.
|
| 6 |
+
|
| 7 |
+
Report vulnerabilities privately to the repository maintainers before public disclosure.
|
configs/context-release-v1.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"suite_id": "shiftedx-context-v1-release",
|
| 3 |
+
"context_window": 262144,
|
| 4 |
+
"reserved_output_tokens": 2048,
|
| 5 |
+
"matrices": [
|
| 6 |
+
{
|
| 7 |
+
"name": "position-grid",
|
| 8 |
+
"families": ["single_key"],
|
| 9 |
+
"lengths": [4096, 8192, 16384, 32768, 65536, 131072, 196608, 229376, 245760, 260096],
|
| 10 |
+
"positions": [0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99],
|
| 11 |
+
"seeds": [7319, 42017, 99041],
|
| 12 |
+
"query_placements": ["after"]
|
| 13 |
+
},
|
| 14 |
+
{
|
| 15 |
+
"name": "challenge-grid",
|
| 16 |
+
"families": ["binding", "latest_record", "multi_hop", "semantic", "state_tracking"],
|
| 17 |
+
"lengths": [32768, 131072, 260096],
|
| 18 |
+
"positions": [0.25, 0.5, 0.75],
|
| 19 |
+
"seeds": [173, 811],
|
| 20 |
+
"query_placements": ["after"]
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"name": "query-position",
|
| 24 |
+
"families": ["latest_record"],
|
| 25 |
+
"lengths": [65536, 131072, 260096],
|
| 26 |
+
"positions": [0.5],
|
| 27 |
+
"seeds": [127, 4099],
|
| 28 |
+
"query_placements": ["before", "after"]
|
| 29 |
+
}
|
| 30 |
+
]
|
| 31 |
+
}
|
| 32 |
+
|
configs/context-smoke-v1.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"suite_id": "shiftedx-context-v1-smoke",
|
| 3 |
+
"context_window": 262144,
|
| 4 |
+
"reserved_output_tokens": 2048,
|
| 5 |
+
"matrices": [
|
| 6 |
+
{
|
| 7 |
+
"name": "position-grid",
|
| 8 |
+
"families": ["single_key"],
|
| 9 |
+
"lengths": [4096, 32768, 131072, 260096],
|
| 10 |
+
"positions": [0.1, 0.5, 0.9],
|
| 11 |
+
"seeds": [7319],
|
| 12 |
+
"query_placements": ["after"]
|
| 13 |
+
},
|
| 14 |
+
{
|
| 15 |
+
"name": "challenge-grid",
|
| 16 |
+
"families": ["binding", "latest_record", "multi_hop", "semantic", "state_tracking"],
|
| 17 |
+
"lengths": [32768],
|
| 18 |
+
"positions": [0.5],
|
| 19 |
+
"seeds": [7319],
|
| 20 |
+
"query_placements": ["after"]
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"name": "query-position",
|
| 24 |
+
"families": ["latest_record"],
|
| 25 |
+
"lengths": [32768],
|
| 26 |
+
"positions": [0.5],
|
| 27 |
+
"seeds": [42017],
|
| 28 |
+
"query_placements": ["before", "after"]
|
| 29 |
+
}
|
| 30 |
+
]
|
| 31 |
+
}
|
| 32 |
+
|
configs/mtplx-parity-v1.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"label": "ar",
|
| 4 |
+
"request_overrides": {
|
| 5 |
+
"generation_mode": "ar",
|
| 6 |
+
"thinking": {"enabled": false},
|
| 7 |
+
"mtplx_stats": true
|
| 8 |
+
}
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"label": "d1",
|
| 12 |
+
"request_overrides": {
|
| 13 |
+
"generation_mode": "mtp",
|
| 14 |
+
"depth": 1,
|
| 15 |
+
"thinking": {"enabled": false},
|
| 16 |
+
"mtplx_stats": true
|
| 17 |
+
}
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"label": "d2",
|
| 21 |
+
"request_overrides": {
|
| 22 |
+
"generation_mode": "mtp",
|
| 23 |
+
"depth": 2,
|
| 24 |
+
"thinking": {"enabled": false},
|
| 25 |
+
"mtplx_stats": true
|
| 26 |
+
}
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"label": "d3",
|
| 30 |
+
"request_overrides": {
|
| 31 |
+
"generation_mode": "mtp",
|
| 32 |
+
"depth": 3,
|
| 33 |
+
"thinking": {"enabled": false},
|
| 34 |
+
"mtplx_stats": true
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
]
|
| 38 |
+
|
configs/suites-release-v1.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"suite_id": "shiftedx-qualification-v1-release",
|
| 3 |
+
"quality": {
|
| 4 |
+
"seeds": [173, 811, 4099, 7319, 42017],
|
| 5 |
+
"families": [
|
| 6 |
+
"ledger",
|
| 7 |
+
"shortest_path",
|
| 8 |
+
"interval_schedule",
|
| 9 |
+
"table_join",
|
| 10 |
+
"event_state",
|
| 11 |
+
"instruction_order",
|
| 12 |
+
"code_chunks",
|
| 13 |
+
"code_window",
|
| 14 |
+
"code_normalize",
|
| 15 |
+
"code_percentile"
|
| 16 |
+
]
|
| 17 |
+
},
|
| 18 |
+
"tools": {"seeds": [173, 811, 4099, 7319, 42017]},
|
| 19 |
+
"vision": {"seeds": [173, 811, 4099, 7319, 42017]}
|
| 20 |
+
}
|
configs/suites-smoke-v1.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"suite_id": "shiftedx-qualification-v1-smoke",
|
| 3 |
+
"quality": {
|
| 4 |
+
"seeds": [7319],
|
| 5 |
+
"families": [
|
| 6 |
+
"ledger",
|
| 7 |
+
"shortest_path",
|
| 8 |
+
"interval_schedule",
|
| 9 |
+
"table_join",
|
| 10 |
+
"event_state",
|
| 11 |
+
"instruction_order",
|
| 12 |
+
"code_chunks",
|
| 13 |
+
"code_window",
|
| 14 |
+
"code_normalize",
|
| 15 |
+
"code_percentile"
|
| 16 |
+
]
|
| 17 |
+
},
|
| 18 |
+
"tools": {"seeds": [7319]},
|
| 19 |
+
"vision": {"seeds": [7319]}
|
| 20 |
+
}
|
docs/leaderboard-policy.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Leaderboard and claim policy
|
| 2 |
+
|
| 3 |
+
## Eligible results
|
| 4 |
+
|
| 5 |
+
A public result must include the run manifest, raw JSONL results, summary, benchmark version, configuration hash, model revision, tokenizer fingerprint, runtime version, hardware, and all request variants. Failed requests and timeouts remain in the denominator.
|
| 6 |
+
|
| 7 |
+
The evaluated model must be publicly identifiable or accompanied by an immutable artifact hash. Submitters must disclose quantization, mixed-precision overrides, context scaling, KV-cache quantization, speculative decoding, tool template, and reasoning mode.
|
| 8 |
+
|
| 9 |
+
## Required lanes
|
| 10 |
+
|
| 11 |
+
“Shiftedx Bench qualified” requires quality, context, tools, agentic, vision when advertised, and AR-versus-acceleration parity. A text-only model may omit vision only when labeled text-only.
|
| 12 |
+
|
| 13 |
+
Scores are published by lane. There is no official combined intelligence score.
|
| 14 |
+
|
| 15 |
+
## Repeats and uncertainty
|
| 16 |
+
|
| 17 |
+
Deterministic lanes use temperature zero and procedural seeds. Stochastic operational settings require at least three trials. Publish paired confidence intervals when comparing a quant, runtime, or decoding depth with its parent.
|
| 18 |
+
|
| 19 |
+
## Long-context claims
|
| 20 |
+
|
| 21 |
+
Advertised context size and effective context size are distinct. Effective context length is the greatest evaluated prompt length meeting the declared accuracy threshold; the threshold and aggregation must accompany the number. Also publish the complete length/position heatmap and worst cell.
|
| 22 |
+
|
| 23 |
+
## Performance claims
|
| 24 |
+
|
| 25 |
+
Performance comparisons require the same host, power mode, runtime, prompt, output, cache condition, and sampling settings. Report time to first token, prefill telemetry when available, decode/end-to-end throughput, and memory. Cold and warm-prefix results must be labeled separately.
|
| 26 |
+
|
| 27 |
+
## Contamination and holdouts
|
| 28 |
+
|
| 29 |
+
Public development cases are expected to become contaminated over time. Official comparisons use a frozen rotating seed set whose commitment is recorded before evaluation and whose concrete cases are disclosed afterward. Changes to generators create a new benchmark version.
|
| 30 |
+
|
| 31 |
+
## Corrections
|
| 32 |
+
|
| 33 |
+
Results with missing provenance, silent truncation, changed validators, excluded failures, private prompt modifications, or unreported runtime-specific optimizations are ineligible. Material errors remain visible with a correction note rather than being silently replaced.
|
| 34 |
+
|
docs/methodology.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Methodology
|
| 2 |
+
|
| 3 |
+
## Measurement contract
|
| 4 |
+
|
| 5 |
+
Freeze the following before comparing candidates:
|
| 6 |
+
|
| 7 |
+
- model artifact and revision;
|
| 8 |
+
- tokenizer and chat-template hashes;
|
| 9 |
+
- runtime version and request adapter;
|
| 10 |
+
- context window and output reserve;
|
| 11 |
+
- sampler, reasoning mode, stop behavior, and seed;
|
| 12 |
+
- task configuration and holdout policy;
|
| 13 |
+
- critical zero-regression cases;
|
| 14 |
+
- minimum performance improvement;
|
| 15 |
+
- hardware and cache condition.
|
| 16 |
+
|
| 17 |
+
Change one declared variable at a time. Compare a quantized candidate with its exact higher-precision parent, and compare MTPLX depths with AR using paired cases.
|
| 18 |
+
|
| 19 |
+
## Long-context construction
|
| 20 |
+
|
| 21 |
+
Lengths in the frozen release grid are 4,096, 8,192, 16,384, 32,768, 65,536, 131,072, 196,608, 229,376, 245,760, and 260,096 rendered prompt tokens. The last length reserves 2,048 tokens inside a 262,144-token model context.
|
| 22 |
+
|
| 23 |
+
Evidence centers are placed at 1%, 10%, 25%, 50%, 75%, 90%, and 99% of the context body. Each prompt records requested and actual evidence positions. Start and end sentinels must both appear in the answer, causing silent front or tail truncation to fail.
|
| 24 |
+
|
| 25 |
+
The task families are:
|
| 26 |
+
|
| 27 |
+
1. exact single-key retrieval;
|
| 28 |
+
2. key/value binding among similar identifiers;
|
| 29 |
+
3. current-record selection among stale and test-only records;
|
| 30 |
+
4. multi-hop resolution across distant evidence;
|
| 31 |
+
5. semantic retrieval with reduced lexical overlap;
|
| 32 |
+
6. ordered state updates.
|
| 33 |
+
|
| 34 |
+
The release configuration also compares queries placed before and after the context. Filler is procedurally generated synthetic telemetry with unique traces and semantically similar records, not a tiny repeated word vocabulary.
|
| 35 |
+
|
| 36 |
+
## Scoring
|
| 37 |
+
|
| 38 |
+
Structured tasks require bare, fully parseable JSON. Markdown fences and trailing prose fail. Tool cases compare the emitted protocol calls, names, arguments, order, and no-call behavior. Executable Python is statically screened and evaluated in a resource-limited isolated subprocess.
|
| 39 |
+
|
| 40 |
+
The Python evaluator is appropriate for trusted local benchmark output, not hostile multi-tenant code. A public submission service must add an operating-system or container sandbox with networking disabled.
|
| 41 |
+
|
| 42 |
+
## Statistical reporting
|
| 43 |
+
|
| 44 |
+
Report each lane separately. Required outputs include:
|
| 45 |
+
|
| 46 |
+
- accuracy and a bootstrap 95% confidence interval;
|
| 47 |
+
- context accuracy by length, position, and family;
|
| 48 |
+
- worst context cell and effective context length at a declared threshold;
|
| 49 |
+
- wall time, time to first token when streaming is supported, and end-to-end token rate;
|
| 50 |
+
- server-reported cached tokens and MTPLX acceptance telemetry when available;
|
| 51 |
+
- paired quality delta and speed ratio for every runtime variant.
|
| 52 |
+
|
| 53 |
+
Do not infer an intelligence improvement from one or two task changes. Do not combine hardware-dependent throughput with model quality in a single score.
|
| 54 |
+
|
| 55 |
+
## Public and rotating sets
|
| 56 |
+
|
| 57 |
+
The checked-in configurations are reproducible development contracts. For a leaderboard release, derive a rotating seed configuration from a private master key, freeze its hash before evaluation, and publish the concrete seeds only after submissions close. Keep calibration prompts, development seeds, and holdout seeds disjoint.
|
| 58 |
+
|
| 59 |
+
## Sanity controls
|
| 60 |
+
|
| 61 |
+
Before accepting a new suite version, verify:
|
| 62 |
+
|
| 63 |
+
- an oracle response passes every case;
|
| 64 |
+
- empty, echo, random, stale-decoy, and truncated responses fail;
|
| 65 |
+
- deliberately mutated code fails hidden tests;
|
| 66 |
+
- duplicate case identifiers are rejected;
|
| 67 |
+
- prompt counts and evidence positions are exact under a real target tokenizer;
|
| 68 |
+
- a server/tokenizer mismatch fails rather than silently changing the score.
|
| 69 |
+
|
pyproject.toml
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["hatchling>=1.27"]
|
| 3 |
+
build-backend = "hatchling.build"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "shiftedx-bench"
|
| 7 |
+
version = "0.1.0"
|
| 8 |
+
description = "Reproducible quality, long-context, tool, vision, and MTPLX qualification for local language models"
|
| 9 |
+
readme = "README.md"
|
| 10 |
+
requires-python = ">=3.11"
|
| 11 |
+
license = {text = "Apache-2.0"}
|
| 12 |
+
authors = [{name = "Shiftedx"}]
|
| 13 |
+
dependencies = []
|
| 14 |
+
|
| 15 |
+
[project.optional-dependencies]
|
| 16 |
+
tokenizers = ["transformers>=5.0"]
|
| 17 |
+
vision = ["Pillow>=11.0"]
|
| 18 |
+
test = ["pytest>=8.0"]
|
| 19 |
+
|
| 20 |
+
[project.scripts]
|
| 21 |
+
shiftedx-bench = "shiftedx_bench.cli:main"
|
| 22 |
+
|
| 23 |
+
[tool.hatch.build.targets.wheel]
|
| 24 |
+
packages = ["src/shiftedx_bench"]
|
| 25 |
+
|
| 26 |
+
[tool.pytest.ini_options]
|
| 27 |
+
testpaths = ["tests"]
|
| 28 |
+
addopts = "-q"
|
| 29 |
+
|
schemas/context-config-v1.schema.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
| 3 |
+
"$id": "https://huggingface.co/datasets/Shiftedx/shiftedx-bench/raw/main/schemas/context-config-v1.schema.json",
|
| 4 |
+
"title": "Shiftedx Bench context matrix",
|
| 5 |
+
"type": "object",
|
| 6 |
+
"required": ["suite_id", "context_window", "reserved_output_tokens", "matrices"],
|
| 7 |
+
"properties": {
|
| 8 |
+
"suite_id": {"type": "string"},
|
| 9 |
+
"context_window": {"type": "integer", "minimum": 4096},
|
| 10 |
+
"reserved_output_tokens": {"type": "integer", "minimum": 1},
|
| 11 |
+
"matrices": {
|
| 12 |
+
"type": "array",
|
| 13 |
+
"minItems": 1,
|
| 14 |
+
"items": {
|
| 15 |
+
"type": "object",
|
| 16 |
+
"required": ["name", "families", "lengths", "positions", "seeds"],
|
| 17 |
+
"properties": {
|
| 18 |
+
"name": {"type": "string"},
|
| 19 |
+
"families": {"type": "array", "items": {"type": "string"}},
|
| 20 |
+
"lengths": {"type": "array", "items": {"type": "integer", "minimum": 1}},
|
| 21 |
+
"positions": {"type": "array", "items": {"type": "number", "exclusiveMinimum": 0, "exclusiveMaximum": 1}},
|
| 22 |
+
"seeds": {"type": "array", "items": {"type": "integer"}},
|
| 23 |
+
"query_placements": {"type": "array", "items": {"enum": ["before", "after"]}}
|
| 24 |
+
},
|
| 25 |
+
"additionalProperties": false
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
},
|
| 29 |
+
"additionalProperties": false
|
| 30 |
+
}
|
schemas/result-v1.schema.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
| 3 |
+
"$id": "https://huggingface.co/datasets/Shiftedx/shiftedx-bench/raw/main/schemas/result-v1.schema.json",
|
| 4 |
+
"title": "Shiftedx Bench case result",
|
| 5 |
+
"type": "object",
|
| 6 |
+
"required": [
|
| 7 |
+
"schema_version", "run_id", "suite_id", "case_id", "lane", "variant",
|
| 8 |
+
"passed", "score", "score_max", "response", "telemetry", "metadata", "request_hash"
|
| 9 |
+
],
|
| 10 |
+
"properties": {
|
| 11 |
+
"schema_version": {"const": "1.0"},
|
| 12 |
+
"run_id": {"type": "string"},
|
| 13 |
+
"suite_id": {"type": "string"},
|
| 14 |
+
"case_id": {"type": "string"},
|
| 15 |
+
"lane": {"enum": ["quality", "long-context", "tools", "agentic", "vision"]},
|
| 16 |
+
"variant": {"type": "string"},
|
| 17 |
+
"passed": {"type": "boolean"},
|
| 18 |
+
"score": {"type": "number"},
|
| 19 |
+
"score_max": {"type": "number"},
|
| 20 |
+
"error": {"type": ["string", "null"]},
|
| 21 |
+
"response": {"type": "object"},
|
| 22 |
+
"telemetry": {"type": "object"},
|
| 23 |
+
"metadata": {"type": "object"},
|
| 24 |
+
"request_hash": {"type": "string", "pattern": "^[a-f0-9]{64}$"}
|
| 25 |
+
},
|
| 26 |
+
"additionalProperties": false
|
| 27 |
+
}
|
src/shiftedx_bench/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shiftedx local-model qualification benchmark."""
|
| 2 |
+
|
| 3 |
+
from .models import BenchCase, CaseResult
|
| 4 |
+
|
| 5 |
+
__all__ = ["BenchCase", "CaseResult"]
|
| 6 |
+
__version__ = "0.1.0"
|
| 7 |
+
|
src/shiftedx_bench/agentic.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import uuid
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any, Callable
|
| 8 |
+
|
| 9 |
+
from .api import OpenAIClient
|
| 10 |
+
from .scoring import score_response
|
| 11 |
+
from .tools import function_tool
|
| 12 |
+
from .util import append_jsonl, sha256_json
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
READ = function_tool("read_file", {"path": {"type": "string"}}, ["path"])
|
| 16 |
+
SEARCH = function_tool("file_search", {"query": {"type": "string"}}, ["query"])
|
| 17 |
+
SESSION = function_tool("session_search", {"query": {"type": "string"}}, ["query"])
|
| 18 |
+
TESTS = function_tool("run_tests", {}, [])
|
| 19 |
+
PATCH = function_tool("apply_patch", {"path": {"type": "string"}, "patch": {"type": "string"}}, ["path", "patch"])
|
| 20 |
+
LOGS = function_tool("read_logs", {"service": {"type": "string"}}, ["service"])
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@dataclass
|
| 24 |
+
class AgentScenario:
|
| 25 |
+
case_id: str
|
| 26 |
+
prompt: str
|
| 27 |
+
tools: list[dict[str, Any]]
|
| 28 |
+
required_calls: set[str]
|
| 29 |
+
expected_final: dict[str, Any]
|
| 30 |
+
dispatch: Callable[[str, dict[str, Any], dict[str, Any]], str]
|
| 31 |
+
max_turns: int = 8
|
| 32 |
+
max_tool_calls: int = 8
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _bugfix(name: str, args: dict[str, Any], state: dict[str, Any]) -> str:
|
| 36 |
+
if name == "file_search": return "/repo/path_utils.py\n/repo/test_path_utils.py"
|
| 37 |
+
if name == "read_file":
|
| 38 |
+
if str(args.get("path", "")).endswith("test_path_utils.py"):
|
| 39 |
+
return "assert parent('') == '.'\nassert parent('a/b') == 'a'\n"
|
| 40 |
+
if str(args.get("path", "")).endswith("path_utils.py"):
|
| 41 |
+
return "def parent(path):\n parts = path.split('/')\n parts.pop()\n return '/'.join(parts) or '.'\n"
|
| 42 |
+
return "FileNotFoundError"
|
| 43 |
+
if name == "apply_patch":
|
| 44 |
+
patch = str(args.get("patch", ""))
|
| 45 |
+
state["patched"] = "if" in patch and "path" in patch
|
| 46 |
+
return "Patch applied." if state["patched"] else "Patch rejected: empty-path guard absent."
|
| 47 |
+
if name == "run_tests": return "2 passed" if state.get("patched") else "1 failed: IndexError"
|
| 48 |
+
return "Unknown tool"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _recovery(name: str, args: dict[str, Any], state: dict[str, Any]) -> str:
|
| 52 |
+
if name == "session_search": return '{"error":"index unavailable","retryable":false}'
|
| 53 |
+
if name == "file_search": return "/configs/staging/deploy.yaml: endpoint: https://staging.example:7443"
|
| 54 |
+
if name == "read_file": return "service: atlas\nendpoint: https://staging.example:7443\n"
|
| 55 |
+
return "Unknown tool"
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _false_error(name: str, args: dict[str, Any], state: dict[str, Any]) -> str:
|
| 59 |
+
if name == "read_logs":
|
| 60 |
+
return json.dumps({"status": "healthy", "message": "No errors detected", "error_budget": "99.9%"})
|
| 61 |
+
return "Unknown tool"
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _repair(name: str, args: dict[str, Any], state: dict[str, Any]) -> str:
|
| 65 |
+
if name == "run_tests": return "12 passed" if state.get("patched") else "11 passed, 1 failed: backoff"
|
| 66 |
+
if name == "file_search": return "/repo/retry.py\n/repo/test_retry.py"
|
| 67 |
+
if name == "read_file":
|
| 68 |
+
return "def retry_delays(n): return list(range(1,n+1))" if str(args.get("path", "")).endswith("retry.py") else "assert retry_delays(3)==[1,2,4]"
|
| 69 |
+
if name == "apply_patch":
|
| 70 |
+
patch = str(args.get("patch", ""))
|
| 71 |
+
state["patched"] = "2 **" in patch or "2**" in patch or "1 <<" in patch
|
| 72 |
+
return "Patch applied." if state["patched"] else "Patch does not implement exponential backoff."
|
| 73 |
+
return "Unknown tool"
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _parallel_config(name: str, args: dict[str, Any], state: dict[str, Any]) -> str:
|
| 77 |
+
if name != "read_file": return "Unknown tool"
|
| 78 |
+
path = str(args.get("path", ""))
|
| 79 |
+
if path == "/configs/app.yaml": return "api_version: v3\ntimeout_seconds: 30"
|
| 80 |
+
if path == "/configs/worker.yaml": return "api_version: v2\ntimeout_seconds: 30"
|
| 81 |
+
return "FileNotFoundError"
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _wrong_path(name: str, args: dict[str, Any], state: dict[str, Any]) -> str:
|
| 85 |
+
if name == "read_file":
|
| 86 |
+
path = str(args.get("path", ""))
|
| 87 |
+
if path == "/repo/config/prod.toml": return "FileNotFoundError"
|
| 88 |
+
if path == "/repo/configs/prod.toml": return 'database_host = "prod-db"\npool_size = 20'
|
| 89 |
+
return "FileNotFoundError"
|
| 90 |
+
if name == "file_search": return "/repo/configs/prod.toml"
|
| 91 |
+
return "Unknown tool"
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def scenarios() -> list[AgentScenario]:
|
| 95 |
+
final = "When complete, return bare JSON only."
|
| 96 |
+
return [
|
| 97 |
+
AgentScenario(
|
| 98 |
+
"inspect_patch_test",
|
| 99 |
+
"Fix the empty-path bug in path_utils.parent. Inspect source and tests, patch it, and run tests. " + final,
|
| 100 |
+
[SEARCH, READ, PATCH, TESTS],
|
| 101 |
+
{"read_file", "apply_patch", "run_tests"},
|
| 102 |
+
{"status": "passed"},
|
| 103 |
+
_bugfix,
|
| 104 |
+
),
|
| 105 |
+
AgentScenario(
|
| 106 |
+
"failed_search_recovery",
|
| 107 |
+
"Find the staging endpoint. Search prior sessions first, recover with repository tools if unavailable, and verify the file. " + final,
|
| 108 |
+
[SESSION, SEARCH, READ],
|
| 109 |
+
{"session_search", "file_search", "read_file"},
|
| 110 |
+
{"endpoint": "https://staging.example:7443"},
|
| 111 |
+
_recovery,
|
| 112 |
+
max_tool_calls=4,
|
| 113 |
+
),
|
| 114 |
+
AgentScenario(
|
| 115 |
+
"false_error_payload",
|
| 116 |
+
"Check payments health. Do not retry a successful result whose text merely contains the word error. " + final,
|
| 117 |
+
[LOGS],
|
| 118 |
+
{"read_logs"},
|
| 119 |
+
{"status": "healthy", "error_budget": "99.9%"},
|
| 120 |
+
_false_error,
|
| 121 |
+
max_turns=4,
|
| 122 |
+
max_tool_calls=1,
|
| 123 |
+
),
|
| 124 |
+
AgentScenario(
|
| 125 |
+
"repair_loop",
|
| 126 |
+
"Run tests, diagnose the backoff failure, make the smallest source fix, rerun tests, and stop only when green. " + final,
|
| 127 |
+
[TESTS, SEARCH, READ, PATCH],
|
| 128 |
+
{"run_tests", "read_file", "apply_patch"},
|
| 129 |
+
{"status": "passed", "tests": 12},
|
| 130 |
+
_repair,
|
| 131 |
+
max_tool_calls=7,
|
| 132 |
+
),
|
| 133 |
+
AgentScenario(
|
| 134 |
+
"parallel_config_review",
|
| 135 |
+
"Read /configs/app.yaml and /configs/worker.yaml, preferably in parallel. Report both API versions. " + final,
|
| 136 |
+
[READ],
|
| 137 |
+
{"read_file"},
|
| 138 |
+
{"app_version": "v3", "worker_version": "v2"},
|
| 139 |
+
_parallel_config,
|
| 140 |
+
max_turns=5,
|
| 141 |
+
max_tool_calls=2,
|
| 142 |
+
),
|
| 143 |
+
AgentScenario(
|
| 144 |
+
"wrong_path_recovery",
|
| 145 |
+
"Read /repo/config/prod.toml and report database host and pool size. If missing, locate the real file. " + final,
|
| 146 |
+
[READ, SEARCH],
|
| 147 |
+
{"read_file", "file_search"},
|
| 148 |
+
{"database_host": "prod-db", "pool_size": 20},
|
| 149 |
+
_wrong_path,
|
| 150 |
+
max_turns=6,
|
| 151 |
+
max_tool_calls=3,
|
| 152 |
+
),
|
| 153 |
+
]
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def _arguments(call: dict[str, Any]) -> dict[str, Any]:
|
| 157 |
+
raw = (call.get("function") or {}).get("arguments", {})
|
| 158 |
+
return json.loads(raw) if isinstance(raw, str) else raw
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def run_agentic_cases(
|
| 162 |
+
*,
|
| 163 |
+
client: OpenAIClient,
|
| 164 |
+
model: str,
|
| 165 |
+
output_path: Path,
|
| 166 |
+
request_overrides: dict[str, Any] | None = None,
|
| 167 |
+
limit: int | None = None,
|
| 168 |
+
) -> list[dict[str, Any]]:
|
| 169 |
+
rows = []
|
| 170 |
+
run_id = str(uuid.uuid4())
|
| 171 |
+
system = (
|
| 172 |
+
"You are an autonomous coding agent in a deterministic sandbox. Use supplied tools, never invent "
|
| 173 |
+
"results, recover from failures, verify completion, and obey the requested final JSON format."
|
| 174 |
+
)
|
| 175 |
+
selected = scenarios()
|
| 176 |
+
if limit is not None:
|
| 177 |
+
selected = selected[:limit]
|
| 178 |
+
for scenario in selected:
|
| 179 |
+
messages: list[dict[str, Any]] = [
|
| 180 |
+
{"role": "system", "content": system},
|
| 181 |
+
{"role": "user", "content": scenario.prompt},
|
| 182 |
+
]
|
| 183 |
+
state: dict[str, Any] = {}
|
| 184 |
+
call_names: list[str] = []
|
| 185 |
+
turn_telemetry: list[dict[str, Any]] = []
|
| 186 |
+
response: dict[str, Any] = {}
|
| 187 |
+
error = None
|
| 188 |
+
for _ in range(scenario.max_turns):
|
| 189 |
+
payload = {
|
| 190 |
+
"model": model,
|
| 191 |
+
"messages": messages,
|
| 192 |
+
"tools": scenario.tools,
|
| 193 |
+
"tool_choice": "auto",
|
| 194 |
+
"temperature": 0,
|
| 195 |
+
"max_tokens": 500,
|
| 196 |
+
}
|
| 197 |
+
payload.update(request_overrides or {})
|
| 198 |
+
response = client.complete(payload)
|
| 199 |
+
turn_telemetry.append({
|
| 200 |
+
"wall_s": response.get("wall_s"),
|
| 201 |
+
"prompt_tokens": response.get("prompt_tokens"),
|
| 202 |
+
"completion_tokens": response.get("completion_tokens"),
|
| 203 |
+
"ttft_s": response.get("ttft_s"),
|
| 204 |
+
"mtplx_stats": response.get("mtplx_stats") or {},
|
| 205 |
+
})
|
| 206 |
+
calls = response.get("tool_calls") or []
|
| 207 |
+
if not calls:
|
| 208 |
+
break
|
| 209 |
+
assistant = {"role": "assistant", "content": response.get("content") or "", "tool_calls": calls}
|
| 210 |
+
messages.append(assistant)
|
| 211 |
+
for index, call in enumerate(calls):
|
| 212 |
+
name = str((call.get("function") or {}).get("name"))
|
| 213 |
+
call_names.append(name)
|
| 214 |
+
if len(call_names) > scenario.max_tool_calls:
|
| 215 |
+
error = "tool-call budget exceeded"
|
| 216 |
+
break
|
| 217 |
+
try:
|
| 218 |
+
result = scenario.dispatch(name, _arguments(call), state)
|
| 219 |
+
except Exception as exc:
|
| 220 |
+
result = json.dumps({"error": f"dispatcher failure: {exc}"})
|
| 221 |
+
messages.append(
|
| 222 |
+
{
|
| 223 |
+
"role": "tool",
|
| 224 |
+
"tool_call_id": call.get("id") or f"call-{index}",
|
| 225 |
+
"content": result,
|
| 226 |
+
}
|
| 227 |
+
)
|
| 228 |
+
if error:
|
| 229 |
+
break
|
| 230 |
+
score = score_response("strict_json_subset", scenario.expected_final, response)
|
| 231 |
+
required_ok = scenario.required_calls.issubset(call_names)
|
| 232 |
+
passed = score.passed and required_ok and error is None
|
| 233 |
+
if not required_ok:
|
| 234 |
+
error = f"missing required calls: {sorted(scenario.required_calls - set(call_names))}"
|
| 235 |
+
elif not score.passed:
|
| 236 |
+
error = score.error
|
| 237 |
+
row = {
|
| 238 |
+
"schema_version": "1.0",
|
| 239 |
+
"run_id": run_id,
|
| 240 |
+
"suite_id": "shiftedx-agentic-v1",
|
| 241 |
+
"case_id": scenario.case_id,
|
| 242 |
+
"lane": "agentic",
|
| 243 |
+
"variant": "default",
|
| 244 |
+
"passed": passed,
|
| 245 |
+
"score": float(passed),
|
| 246 |
+
"score_max": 1.0,
|
| 247 |
+
"error": error,
|
| 248 |
+
"response": {**response, "transcript": messages},
|
| 249 |
+
"telemetry": {
|
| 250 |
+
"tool_call_count": len(call_names),
|
| 251 |
+
"tool_calls": call_names,
|
| 252 |
+
"turns": turn_telemetry,
|
| 253 |
+
"wall_s": sum(float(item.get("wall_s") or 0) for item in turn_telemetry),
|
| 254 |
+
"prompt_tokens": sum(int(item.get("prompt_tokens") or 0) for item in turn_telemetry),
|
| 255 |
+
"completion_tokens": sum(int(item.get("completion_tokens") or 0) for item in turn_telemetry),
|
| 256 |
+
"ttft_s": next((item.get("ttft_s") for item in turn_telemetry if item.get("ttft_s") is not None), None),
|
| 257 |
+
},
|
| 258 |
+
"metadata": {"max_turns": scenario.max_turns, "max_tool_calls": scenario.max_tool_calls},
|
| 259 |
+
"request_hash": sha256_json({"messages": messages[:2], "tools": scenario.tools}),
|
| 260 |
+
}
|
| 261 |
+
append_jsonl(output_path, [row])
|
| 262 |
+
rows.append(row)
|
| 263 |
+
return rows
|
src/shiftedx_bench/api.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
import urllib.error
|
| 6 |
+
import urllib.request
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@dataclass
|
| 12 |
+
class OpenAIClient:
|
| 13 |
+
base_url: str
|
| 14 |
+
api_key: str | None = None
|
| 15 |
+
timeout_s: float = 600.0
|
| 16 |
+
|
| 17 |
+
def _request(self, payload: dict[str, Any]):
|
| 18 |
+
headers = {"Content-Type": "application/json"}
|
| 19 |
+
if self.api_key:
|
| 20 |
+
headers["Authorization"] = f"Bearer {self.api_key}"
|
| 21 |
+
return urllib.request.Request(
|
| 22 |
+
self.base_url.rstrip("/") + "/chat/completions",
|
| 23 |
+
data=json.dumps(payload).encode("utf-8"),
|
| 24 |
+
headers=headers,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
def complete(self, payload: dict[str, Any], *, stream: bool = False) -> dict[str, Any]:
|
| 28 |
+
body = dict(payload)
|
| 29 |
+
body["stream"] = bool(stream)
|
| 30 |
+
request = self._request(body)
|
| 31 |
+
started = time.perf_counter()
|
| 32 |
+
try:
|
| 33 |
+
with urllib.request.urlopen(request, timeout=self.timeout_s) as response:
|
| 34 |
+
if stream:
|
| 35 |
+
value = self._read_stream(response, started)
|
| 36 |
+
else:
|
| 37 |
+
value = json.loads(response.read().decode("utf-8"))
|
| 38 |
+
except urllib.error.HTTPError as exc:
|
| 39 |
+
detail = exc.read().decode("utf-8", errors="replace")[-4000:]
|
| 40 |
+
raise RuntimeError(f"HTTP {exc.code}: {detail}") from exc
|
| 41 |
+
wall_s = time.perf_counter() - started
|
| 42 |
+
return self._normalize(value, wall_s=wall_s, ttft_s=value.pop("_ttft_s", None))
|
| 43 |
+
|
| 44 |
+
@staticmethod
|
| 45 |
+
def _read_stream(response: Any, started: float) -> dict[str, Any]:
|
| 46 |
+
content: list[str] = []
|
| 47 |
+
reasoning: list[str] = []
|
| 48 |
+
usage: dict[str, Any] = {}
|
| 49 |
+
stats: dict[str, Any] = {}
|
| 50 |
+
finish_reason = None
|
| 51 |
+
first_token_at = None
|
| 52 |
+
model = None
|
| 53 |
+
for raw_line in response:
|
| 54 |
+
line = raw_line.decode("utf-8", errors="replace").strip()
|
| 55 |
+
if not line.startswith("data:"):
|
| 56 |
+
continue
|
| 57 |
+
data = line[5:].strip()
|
| 58 |
+
if data == "[DONE]":
|
| 59 |
+
break
|
| 60 |
+
chunk = json.loads(data)
|
| 61 |
+
model = chunk.get("model") or model
|
| 62 |
+
usage = chunk.get("usage") or usage
|
| 63 |
+
stats = chunk.get("mtplx_stats") or stats
|
| 64 |
+
choice = (chunk.get("choices") or [{}])[0]
|
| 65 |
+
delta = choice.get("delta") or {}
|
| 66 |
+
text = delta.get("content") or ""
|
| 67 |
+
thought = delta.get("reasoning_content") or ""
|
| 68 |
+
if first_token_at is None and (text or thought):
|
| 69 |
+
first_token_at = time.perf_counter()
|
| 70 |
+
content.append(text)
|
| 71 |
+
reasoning.append(thought)
|
| 72 |
+
finish_reason = choice.get("finish_reason") or finish_reason
|
| 73 |
+
return {
|
| 74 |
+
"model": model,
|
| 75 |
+
"choices": [
|
| 76 |
+
{
|
| 77 |
+
"finish_reason": finish_reason,
|
| 78 |
+
"message": {
|
| 79 |
+
"role": "assistant",
|
| 80 |
+
"content": "".join(content),
|
| 81 |
+
"reasoning_content": "".join(reasoning),
|
| 82 |
+
},
|
| 83 |
+
}
|
| 84 |
+
],
|
| 85 |
+
"usage": usage,
|
| 86 |
+
"mtplx_stats": stats,
|
| 87 |
+
"_ttft_s": None if first_token_at is None else first_token_at - started,
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
@staticmethod
|
| 91 |
+
def _normalize(value: dict[str, Any], *, wall_s: float, ttft_s: float | None) -> dict[str, Any]:
|
| 92 |
+
choice = (value.get("choices") or [{}])[0]
|
| 93 |
+
message = choice.get("message") or {}
|
| 94 |
+
usage = value.get("usage") or {}
|
| 95 |
+
stats = value.get("mtplx_stats") or usage.get("mtplx_stats") or {}
|
| 96 |
+
if ttft_s is None and isinstance(stats.get("ttft_s"), (int, float)):
|
| 97 |
+
ttft_s = float(stats["ttft_s"])
|
| 98 |
+
completion_tokens = usage.get("completion_tokens")
|
| 99 |
+
prompt_tokens = usage.get("prompt_tokens")
|
| 100 |
+
return {
|
| 101 |
+
"model": value.get("model"),
|
| 102 |
+
"content": message.get("content") or "",
|
| 103 |
+
"reasoning_content": message.get("reasoning_content") or "",
|
| 104 |
+
"tool_calls": message.get("tool_calls") or [],
|
| 105 |
+
"finish_reason": choice.get("finish_reason"),
|
| 106 |
+
"usage": usage,
|
| 107 |
+
"mtplx_stats": stats,
|
| 108 |
+
"wall_s": wall_s,
|
| 109 |
+
"ttft_s": ttft_s,
|
| 110 |
+
"prompt_tokens": prompt_tokens,
|
| 111 |
+
"completion_tokens": completion_tokens,
|
| 112 |
+
"end_to_end_tokens_per_second": (
|
| 113 |
+
completion_tokens / wall_s
|
| 114 |
+
if isinstance(completion_tokens, int) and wall_s > 0
|
| 115 |
+
else None
|
| 116 |
+
),
|
| 117 |
+
"prefill_tokens_per_second": (
|
| 118 |
+
stats.get("prefill_tok_s")
|
| 119 |
+
or (
|
| 120 |
+
stats.get("new_prefill_tokens") / stats.get("prefill_elapsed_s")
|
| 121 |
+
if isinstance(stats.get("new_prefill_tokens"), (int, float))
|
| 122 |
+
and isinstance(stats.get("prefill_elapsed_s"), (int, float))
|
| 123 |
+
and stats.get("prefill_elapsed_s")
|
| 124 |
+
else None
|
| 125 |
+
)
|
| 126 |
+
),
|
| 127 |
+
"decode_tokens_per_second": stats.get("decode_tok_s") or stats.get("tok_s"),
|
| 128 |
+
"active_memory_bytes": stats.get("active_memory_bytes"),
|
| 129 |
+
"cache_memory_bytes": stats.get("cache_memory_bytes"),
|
| 130 |
+
}
|
src/shiftedx_bench/boundary.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
from dataclasses import replace
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
from .api import OpenAIClient
|
| 8 |
+
from .context import ContextSpec, build_context_case
|
| 9 |
+
from .runner import build_payload
|
| 10 |
+
from .tokenizer import TokenizerProtocol
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
EXPECTED_REJECTION = re.compile(r"HTTP (?:400|413|422):")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def probe_context_boundary(
|
| 17 |
+
*,
|
| 18 |
+
client: OpenAIClient,
|
| 19 |
+
tokenizer: TokenizerProtocol,
|
| 20 |
+
model: str,
|
| 21 |
+
context_window: int,
|
| 22 |
+
reserved_output_tokens: int,
|
| 23 |
+
include_positive: bool = False,
|
| 24 |
+
) -> dict[str, Any]:
|
| 25 |
+
report: dict[str, Any] = {
|
| 26 |
+
"schema_version": "1.0",
|
| 27 |
+
"context_window": context_window,
|
| 28 |
+
"reserved_output_tokens": reserved_output_tokens,
|
| 29 |
+
"maximum_usable_prompt_tokens": context_window - reserved_output_tokens,
|
| 30 |
+
}
|
| 31 |
+
if include_positive:
|
| 32 |
+
spec = ContextSpec(
|
| 33 |
+
"shiftedx-context-boundary-v1", "positive", "single_key",
|
| 34 |
+
context_window - reserved_output_tokens, 0.5, 7319,
|
| 35 |
+
)
|
| 36 |
+
case = build_context_case(spec, tokenizer)
|
| 37 |
+
response = client.complete(build_payload(case, model, {"label": "positive"}), stream=True)
|
| 38 |
+
report["positive"] = {
|
| 39 |
+
"passed": response.get("prompt_tokens") == spec.target_tokens,
|
| 40 |
+
"reported_prompt_tokens": response.get("prompt_tokens"),
|
| 41 |
+
"finish_reason": response.get("finish_reason"),
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
oversize = context_window + 1
|
| 45 |
+
spec = ContextSpec("shiftedx-context-boundary-v1", "negative", "single_key", oversize, 0.5, 99041)
|
| 46 |
+
case = replace(build_context_case(spec, tokenizer), max_output_tokens=1)
|
| 47 |
+
try:
|
| 48 |
+
response = client.complete(build_payload(case, model, {"label": "negative"}))
|
| 49 |
+
report["negative"] = {
|
| 50 |
+
"passed": False,
|
| 51 |
+
"error": "server accepted an oversized rendered prompt",
|
| 52 |
+
"reported_prompt_tokens": response.get("prompt_tokens"),
|
| 53 |
+
}
|
| 54 |
+
except Exception as exc:
|
| 55 |
+
error = f"{type(exc).__name__}: {exc}"
|
| 56 |
+
report["negative"] = {
|
| 57 |
+
"passed": bool(EXPECTED_REJECTION.search(error)),
|
| 58 |
+
"error": error,
|
| 59 |
+
"reported_prompt_tokens": None,
|
| 60 |
+
}
|
| 61 |
+
report["passed"] = report["negative"]["passed"] and (
|
| 62 |
+
not include_positive or report.get("positive", {}).get("passed", False)
|
| 63 |
+
)
|
| 64 |
+
return report
|
| 65 |
+
|
src/shiftedx_bench/cli.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import uuid
|
| 6 |
+
from dataclasses import replace
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
from .agentic import run_agentic_cases
|
| 11 |
+
from .api import OpenAIClient
|
| 12 |
+
from .boundary import probe_context_boundary
|
| 13 |
+
from .context import build_context_case, expand_context_config
|
| 14 |
+
from .holdout import derive_holdout_config
|
| 15 |
+
from .provenance import make_run_manifest, write_manifest
|
| 16 |
+
from .quality import generate_quality_cases
|
| 17 |
+
from .release import scan_public_tree
|
| 18 |
+
from .runner import api_key_from_env, run_cases
|
| 19 |
+
from .summary import summarize_results
|
| 20 |
+
from .tokenizer import TransformersTokenizer
|
| 21 |
+
from .tools import generate_tool_cases
|
| 22 |
+
from .util import read_json, read_jsonl, write_json
|
| 23 |
+
from .vision import generate_vision_cases
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _variants(path: Path | None) -> list[dict[str, Any]]:
|
| 27 |
+
if path is None:
|
| 28 |
+
return [{"label": "default", "request_overrides": {}}]
|
| 29 |
+
value = read_json(path)
|
| 30 |
+
if not isinstance(value, list) or not value:
|
| 31 |
+
raise ValueError("Variant file must contain a non-empty JSON array")
|
| 32 |
+
return value
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _client(args: argparse.Namespace) -> OpenAIClient:
|
| 36 |
+
return OpenAIClient(
|
| 37 |
+
base_url=args.base_url,
|
| 38 |
+
api_key=api_key_from_env(args.api_key_env),
|
| 39 |
+
timeout_s=args.timeout,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def plan_context(args: argparse.Namespace) -> None:
|
| 44 |
+
config = read_json(args.config)
|
| 45 |
+
specs = expand_context_config(config)
|
| 46 |
+
value = {
|
| 47 |
+
"schema_version": "1.0",
|
| 48 |
+
"suite_id": config["suite_id"],
|
| 49 |
+
"cases": len(specs),
|
| 50 |
+
"total_requested_prompt_tokens": sum(item.target_tokens for item in specs),
|
| 51 |
+
"by_matrix": {},
|
| 52 |
+
"specs": [item.__dict__ | {"case_id": item.case_id} for item in specs],
|
| 53 |
+
}
|
| 54 |
+
for spec in specs:
|
| 55 |
+
value["by_matrix"][spec.matrix] = value["by_matrix"].get(spec.matrix, 0) + 1
|
| 56 |
+
write_json(args.output, value)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _tokenizer(args: argparse.Namespace) -> TransformersTokenizer:
|
| 60 |
+
return TransformersTokenizer(
|
| 61 |
+
args.tokenizer,
|
| 62 |
+
enable_thinking=args.thinking == "on",
|
| 63 |
+
reasoning_effort=args.reasoning_effort,
|
| 64 |
+
preserve_thinking=True,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _reasoning_request_overrides(args: argparse.Namespace) -> dict[str, Any]:
|
| 69 |
+
value: dict[str, Any] = {"thinking": {"enabled": args.thinking == "on"}}
|
| 70 |
+
if args.reasoning_effort:
|
| 71 |
+
value["reasoning_effort"] = args.reasoning_effort
|
| 72 |
+
return value
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _validate_context_variant_profile(args: argparse.Namespace, variants: list[dict[str, Any]]) -> None:
|
| 76 |
+
declared = {
|
| 77 |
+
bool((variant.get("request_overrides", {}).get("thinking") or {}).get("enabled"))
|
| 78 |
+
for variant in variants
|
| 79 |
+
if "thinking" in (variant.get("request_overrides") or {})
|
| 80 |
+
}
|
| 81 |
+
if len(declared) > 1:
|
| 82 |
+
raise ValueError("All variants in one exact-token context run must use the same thinking mode")
|
| 83 |
+
if declared and declared != {args.thinking == "on"}:
|
| 84 |
+
raise ValueError("--thinking must match the variant file so local and server templates are identical")
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def inspect_context(args: argparse.Namespace) -> None:
|
| 88 |
+
config = read_json(args.config)
|
| 89 |
+
specs = expand_context_config(config)
|
| 90 |
+
selected = next((item for item in specs if item.case_id == args.case_id), None)
|
| 91 |
+
if selected is None:
|
| 92 |
+
raise ValueError(f"Unknown case identifier: {args.case_id}")
|
| 93 |
+
tokenizer = _tokenizer(args)
|
| 94 |
+
case = build_context_case(selected, tokenizer)
|
| 95 |
+
value = case.to_dict(include_expected=True)
|
| 96 |
+
if not args.include_prompt:
|
| 97 |
+
value["messages"] = [{"role": item["role"], "content": "<omitted>"} for item in case.messages]
|
| 98 |
+
write_json(args.output, value)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def run_context(args: argparse.Namespace) -> None:
|
| 102 |
+
config = read_json(args.config)
|
| 103 |
+
specs = expand_context_config(config)
|
| 104 |
+
if args.matrix:
|
| 105 |
+
specs = [item for item in specs if item.matrix == args.matrix]
|
| 106 |
+
if args.limit is not None:
|
| 107 |
+
specs = specs[: args.limit]
|
| 108 |
+
tokenizer = _tokenizer(args)
|
| 109 |
+
variants = _variants(args.variants)
|
| 110 |
+
_validate_context_variant_profile(args, variants)
|
| 111 |
+
run_id = str(uuid.uuid4())
|
| 112 |
+
manifest = make_run_manifest(
|
| 113 |
+
run_id=run_id,
|
| 114 |
+
suite_id=config["suite_id"],
|
| 115 |
+
model=args.model,
|
| 116 |
+
config_path=args.config,
|
| 117 |
+
tokenizer_fingerprint=tokenizer.fingerprint,
|
| 118 |
+
variants=variants,
|
| 119 |
+
)
|
| 120 |
+
manifest["planned_cases"] = len(specs)
|
| 121 |
+
manifest["requested_prompt_tokens"] = sum(item.target_tokens for item in specs)
|
| 122 |
+
write_manifest(args.output.with_suffix(".manifest.json"), manifest)
|
| 123 |
+
reasoning_overrides = _reasoning_request_overrides(args)
|
| 124 |
+
cases = (
|
| 125 |
+
replace(build_context_case(spec, tokenizer), request_overrides=reasoning_overrides)
|
| 126 |
+
for spec in specs
|
| 127 |
+
)
|
| 128 |
+
run_cases(
|
| 129 |
+
cases,
|
| 130 |
+
client=_client(args),
|
| 131 |
+
model=args.model,
|
| 132 |
+
output_path=args.output,
|
| 133 |
+
variants=variants,
|
| 134 |
+
run_id=run_id,
|
| 135 |
+
stream=args.stream,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def run_suite(args: argparse.Namespace) -> None:
|
| 140 |
+
config = read_json(args.config)
|
| 141 |
+
variants = _variants(args.variants)
|
| 142 |
+
if args.suite == "quality":
|
| 143 |
+
cases = generate_quality_cases(config["quality"]["seeds"], config["quality"].get("families"))
|
| 144 |
+
suite_id = "shiftedx-quality-v1"
|
| 145 |
+
elif args.suite == "tools":
|
| 146 |
+
cases = generate_tool_cases(config["tools"]["seeds"])
|
| 147 |
+
suite_id = "shiftedx-tools-v1"
|
| 148 |
+
elif args.suite == "vision":
|
| 149 |
+
cases = generate_vision_cases(args.output.parent / "vision-fixtures", config["vision"]["seeds"])
|
| 150 |
+
suite_id = "shiftedx-vision-v1"
|
| 151 |
+
elif args.suite == "agentic":
|
| 152 |
+
if len(variants) != 1:
|
| 153 |
+
raise ValueError("Agentic runner currently accepts one request variant per invocation")
|
| 154 |
+
run_agentic_cases(
|
| 155 |
+
client=_client(args), model=args.model, output_path=args.output,
|
| 156 |
+
request_overrides=variants[0].get("request_overrides") or {},
|
| 157 |
+
limit=args.limit,
|
| 158 |
+
)
|
| 159 |
+
return
|
| 160 |
+
else:
|
| 161 |
+
raise ValueError(args.suite)
|
| 162 |
+
if args.limit is not None:
|
| 163 |
+
cases = cases[: args.limit]
|
| 164 |
+
run_id = str(uuid.uuid4())
|
| 165 |
+
write_manifest(
|
| 166 |
+
args.output.with_suffix(".manifest.json"),
|
| 167 |
+
make_run_manifest(
|
| 168 |
+
run_id=run_id, suite_id=suite_id, model=args.model, config_path=args.config,
|
| 169 |
+
tokenizer_fingerprint=None, variants=variants,
|
| 170 |
+
),
|
| 171 |
+
)
|
| 172 |
+
run_cases(
|
| 173 |
+
cases,
|
| 174 |
+
client=_client(args), model=args.model, output_path=args.output,
|
| 175 |
+
variants=variants, run_id=run_id, stream=args.stream,
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def summarize(args: argparse.Namespace) -> None:
|
| 180 |
+
rows = []
|
| 181 |
+
for path in args.inputs:
|
| 182 |
+
rows.extend(read_jsonl(path))
|
| 183 |
+
write_json(args.output, summarize_results(rows, args.effective_threshold))
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def validate_release(args: argparse.Namespace) -> None:
|
| 187 |
+
result = scan_public_tree(args.root)
|
| 188 |
+
if args.output:
|
| 189 |
+
write_json(args.output, result)
|
| 190 |
+
else:
|
| 191 |
+
print(json.dumps(result, indent=2, sort_keys=True))
|
| 192 |
+
if not result["ok"]:
|
| 193 |
+
raise SystemExit(1)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def make_holdout(args: argparse.Namespace) -> None:
|
| 197 |
+
master_key = api_key_from_env(args.master_key_env)
|
| 198 |
+
if master_key is None:
|
| 199 |
+
raise RuntimeError("Holdout master key is required")
|
| 200 |
+
config = derive_holdout_config(read_json(args.template), master_key, args.release_id)
|
| 201 |
+
write_json(args.output, config)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def probe_boundary(args: argparse.Namespace) -> None:
|
| 205 |
+
tokenizer = _tokenizer(args)
|
| 206 |
+
result = probe_context_boundary(
|
| 207 |
+
client=_client(args), tokenizer=tokenizer, model=args.model,
|
| 208 |
+
context_window=args.context_window, reserved_output_tokens=args.reserved_output_tokens,
|
| 209 |
+
include_positive=args.include_positive,
|
| 210 |
+
)
|
| 211 |
+
write_json(args.output, result)
|
| 212 |
+
if not result["passed"]:
|
| 213 |
+
raise SystemExit(1)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def add_runtime_arguments(parser: argparse.ArgumentParser) -> None:
|
| 217 |
+
parser.add_argument("--base-url", required=True, help="OpenAI-compatible base URL ending in /v1")
|
| 218 |
+
parser.add_argument("--model", required=True)
|
| 219 |
+
parser.add_argument("--output", required=True, type=Path)
|
| 220 |
+
parser.add_argument("--api-key-env", help="Environment-variable name containing the API key")
|
| 221 |
+
parser.add_argument("--timeout", type=float, default=900)
|
| 222 |
+
parser.add_argument("--variants", type=Path)
|
| 223 |
+
parser.add_argument("--limit", type=int)
|
| 224 |
+
parser.add_argument("--stream", action="store_true")
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def add_tokenizer_profile_arguments(parser: argparse.ArgumentParser) -> None:
|
| 228 |
+
parser.add_argument("--tokenizer", required=True, type=Path)
|
| 229 |
+
parser.add_argument("--thinking", choices=["on", "off"], default="on")
|
| 230 |
+
parser.add_argument("--reasoning-effort", default="medium")
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def make_parser() -> argparse.ArgumentParser:
|
| 234 |
+
parser = argparse.ArgumentParser(prog="shiftedx-bench")
|
| 235 |
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
| 236 |
+
|
| 237 |
+
command = subparsers.add_parser("plan-context")
|
| 238 |
+
command.add_argument("--config", required=True, type=Path)
|
| 239 |
+
command.add_argument("--output", required=True, type=Path)
|
| 240 |
+
command.set_defaults(func=plan_context)
|
| 241 |
+
|
| 242 |
+
command = subparsers.add_parser("inspect-context")
|
| 243 |
+
command.add_argument("--config", required=True, type=Path)
|
| 244 |
+
add_tokenizer_profile_arguments(command)
|
| 245 |
+
command.add_argument("--case-id", required=True)
|
| 246 |
+
command.add_argument("--output", required=True, type=Path)
|
| 247 |
+
command.add_argument("--include-prompt", action="store_true")
|
| 248 |
+
command.set_defaults(func=inspect_context)
|
| 249 |
+
|
| 250 |
+
command = subparsers.add_parser("run-context")
|
| 251 |
+
add_runtime_arguments(command)
|
| 252 |
+
command.add_argument("--config", required=True, type=Path)
|
| 253 |
+
add_tokenizer_profile_arguments(command)
|
| 254 |
+
command.add_argument("--matrix")
|
| 255 |
+
command.set_defaults(func=run_context)
|
| 256 |
+
|
| 257 |
+
command = subparsers.add_parser("run-suite")
|
| 258 |
+
add_runtime_arguments(command)
|
| 259 |
+
command.add_argument("--config", required=True, type=Path)
|
| 260 |
+
command.add_argument("--suite", required=True, choices=["quality", "tools", "agentic", "vision"])
|
| 261 |
+
command.set_defaults(func=run_suite)
|
| 262 |
+
|
| 263 |
+
command = subparsers.add_parser("summarize")
|
| 264 |
+
command.add_argument("inputs", nargs="+", type=Path)
|
| 265 |
+
command.add_argument("--output", required=True, type=Path)
|
| 266 |
+
command.add_argument("--effective-threshold", type=float, default=0.90)
|
| 267 |
+
command.set_defaults(func=summarize)
|
| 268 |
+
|
| 269 |
+
command = subparsers.add_parser("validate-release")
|
| 270 |
+
command.add_argument("--root", required=True, type=Path)
|
| 271 |
+
command.add_argument("--output", type=Path)
|
| 272 |
+
command.set_defaults(func=validate_release)
|
| 273 |
+
|
| 274 |
+
command = subparsers.add_parser("make-holdout")
|
| 275 |
+
command.add_argument("--template", required=True, type=Path)
|
| 276 |
+
command.add_argument("--release-id", required=True)
|
| 277 |
+
command.add_argument("--master-key-env", required=True)
|
| 278 |
+
command.add_argument("--output", required=True, type=Path)
|
| 279 |
+
command.set_defaults(func=make_holdout)
|
| 280 |
+
|
| 281 |
+
command = subparsers.add_parser("probe-boundary")
|
| 282 |
+
command.add_argument("--base-url", required=True)
|
| 283 |
+
command.add_argument("--model", required=True)
|
| 284 |
+
add_tokenizer_profile_arguments(command)
|
| 285 |
+
command.add_argument("--context-window", type=int, default=262144)
|
| 286 |
+
command.add_argument("--reserved-output-tokens", type=int, default=2048)
|
| 287 |
+
command.add_argument("--include-positive", action="store_true")
|
| 288 |
+
command.add_argument("--api-key-env")
|
| 289 |
+
command.add_argument("--timeout", type=float, default=900)
|
| 290 |
+
command.add_argument("--output", required=True, type=Path)
|
| 291 |
+
command.set_defaults(func=probe_boundary)
|
| 292 |
+
return parser
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def main() -> None:
|
| 296 |
+
args = make_parser().parse_args()
|
| 297 |
+
args.func(args)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
if __name__ == "__main__":
|
| 301 |
+
main()
|
src/shiftedx_bench/context.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import itertools
|
| 4 |
+
import random
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
from .models import BenchCase
|
| 9 |
+
from .tokenizer import TokenizerProtocol
|
| 10 |
+
from .util import sha256_json
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
SYSTEM_PROMPT = (
|
| 14 |
+
"You are running a deterministic long-context evaluation. Read the complete "
|
| 15 |
+
"context, ignore stale or decoy records, and return only the requested bare JSON."
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass(frozen=True)
|
| 20 |
+
class ContextSpec:
|
| 21 |
+
suite_id: str
|
| 22 |
+
matrix: str
|
| 23 |
+
family: str
|
| 24 |
+
target_tokens: int
|
| 25 |
+
position: float
|
| 26 |
+
seed: int
|
| 27 |
+
query_placement: str = "after"
|
| 28 |
+
|
| 29 |
+
@property
|
| 30 |
+
def case_id(self) -> str:
|
| 31 |
+
position = f"p{round(self.position * 100):02d}"
|
| 32 |
+
return (
|
| 33 |
+
f"{self.matrix}__{self.family}__t{self.target_tokens}__{position}"
|
| 34 |
+
f"__s{self.seed}__q{self.query_placement}"
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def expand_context_config(config: dict[str, Any]) -> list[ContextSpec]:
|
| 39 |
+
suite_id = str(config["suite_id"])
|
| 40 |
+
context_window = int(config.get("context_window") or 0)
|
| 41 |
+
reserved_output = int(config.get("reserved_output_tokens") or 0)
|
| 42 |
+
maximum_prompt = context_window - reserved_output if context_window and reserved_output else None
|
| 43 |
+
specs: list[ContextSpec] = []
|
| 44 |
+
for matrix in config["matrices"]:
|
| 45 |
+
values = itertools.product(
|
| 46 |
+
matrix["families"],
|
| 47 |
+
matrix["lengths"],
|
| 48 |
+
matrix["positions"],
|
| 49 |
+
matrix["seeds"],
|
| 50 |
+
matrix.get("query_placements", ["after"]),
|
| 51 |
+
)
|
| 52 |
+
for family, length, position, seed, placement in values:
|
| 53 |
+
if not 0 < float(position) < 1:
|
| 54 |
+
raise ValueError(f"Position must be between zero and one: {position}")
|
| 55 |
+
if placement not in {"before", "after"}:
|
| 56 |
+
raise ValueError(f"Unsupported query placement: {placement}")
|
| 57 |
+
if maximum_prompt is not None and int(length) > maximum_prompt:
|
| 58 |
+
raise ValueError(
|
| 59 |
+
f"Prompt length {length} exceeds context-minus-output budget {maximum_prompt}"
|
| 60 |
+
)
|
| 61 |
+
specs.append(
|
| 62 |
+
ContextSpec(
|
| 63 |
+
suite_id=suite_id,
|
| 64 |
+
matrix=str(matrix["name"]),
|
| 65 |
+
family=str(family),
|
| 66 |
+
target_tokens=int(length),
|
| 67 |
+
position=float(position),
|
| 68 |
+
seed=int(seed),
|
| 69 |
+
query_placement=str(placement),
|
| 70 |
+
)
|
| 71 |
+
)
|
| 72 |
+
identifiers = [item.case_id for item in specs]
|
| 73 |
+
if len(identifiers) != len(set(identifiers)):
|
| 74 |
+
raise ValueError("Context configuration produces duplicate case identifiers")
|
| 75 |
+
return specs
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _secret(seed: int, label: str) -> str:
|
| 79 |
+
rng = random.Random(f"{seed}:{label}")
|
| 80 |
+
left = ["amber", "cedar", "indigo", "marble", "opal", "quartz", "saffron"]
|
| 81 |
+
right = ["falcon", "harbor", "lighthouse", "otter", "raven", "willow"]
|
| 82 |
+
return f"{rng.choice(left)}-{rng.randrange(100000, 999999)}-{rng.choice(right)}"
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _task_payload(spec: ContextSpec) -> tuple[list[tuple[float, str, str]], str, dict[str, Any]]:
|
| 86 |
+
target = _secret(spec.seed, spec.family)
|
| 87 |
+
decoy_a = _secret(spec.seed + 101, "decoy-a")
|
| 88 |
+
decoy_b = _secret(spec.seed + 202, "decoy-b")
|
| 89 |
+
marker = f"<<SX_PRIMARY_{spec.seed}_{spec.family.upper()}>>"
|
| 90 |
+
common: dict[str, Any] = {"record": target}
|
| 91 |
+
insertions: list[tuple[float, str, str]] = [
|
| 92 |
+
(0.08, "decoy-a", f"STALE RECORD record={decoy_a} status=revoked revision=2"),
|
| 93 |
+
(0.92, "decoy-b", f"DECOY RECORD record={decoy_b} status=simulation revision=99"),
|
| 94 |
+
]
|
| 95 |
+
|
| 96 |
+
if spec.family == "single_key":
|
| 97 |
+
primary = f"{marker} CANONICAL RECORD record={target} status=active"
|
| 98 |
+
query = "Return the active canonical record."
|
| 99 |
+
elif spec.family == "binding":
|
| 100 |
+
key = f"device-{(spec.seed % 83) + 10}"
|
| 101 |
+
primary = (
|
| 102 |
+
f"{marker} AUTHORITATIVE BINDING device={key} record={target} "
|
| 103 |
+
"status=active; similar device identifiers are unrelated."
|
| 104 |
+
)
|
| 105 |
+
common["device"] = key
|
| 106 |
+
query = f"Return the active record bound specifically to device {key}."
|
| 107 |
+
elif spec.family == "latest_record":
|
| 108 |
+
primary = f"{marker} CHANGELOG record={target} revision=12 state=current"
|
| 109 |
+
insertions.extend(
|
| 110 |
+
[
|
| 111 |
+
(0.19, "older", f"CHANGELOG record={decoy_a} revision=10 state=superseded"),
|
| 112 |
+
(0.77, "newer-decoy", f"CHANGELOG record={decoy_b} revision=13 state=test-only"),
|
| 113 |
+
]
|
| 114 |
+
)
|
| 115 |
+
common["revision"] = 12
|
| 116 |
+
query = "Return the highest production revision marked current, excluding test-only entries."
|
| 117 |
+
elif spec.family == "multi_hop":
|
| 118 |
+
relay = f"relay-{(spec.seed % 71) + 20}"
|
| 119 |
+
zone = ["north", "south", "east", "west"][spec.seed % 4]
|
| 120 |
+
primary = f"{marker} ROUTE MAP record={target} uses_relay={relay}"
|
| 121 |
+
insertions.append(
|
| 122 |
+
(1.0 - spec.position, "hop-two", f"RELAY DIRECTORY relay={relay} final_zone={zone}"),
|
| 123 |
+
)
|
| 124 |
+
common.update({"relay": relay, "zone": zone})
|
| 125 |
+
query = "Follow the route map through the relay directory and return record, relay, and final zone."
|
| 126 |
+
elif spec.family == "semantic":
|
| 127 |
+
callsign = f"unit-{(spec.seed % 89) + 10}"
|
| 128 |
+
primary = (
|
| 129 |
+
f"{marker} The only solar-powered courier approved for silent night delivery "
|
| 130 |
+
f"has registry value {target} and operational callsign {callsign}."
|
| 131 |
+
)
|
| 132 |
+
common["callsign"] = callsign
|
| 133 |
+
query = (
|
| 134 |
+
"Identify the registry value and callsign of the emission-free messenger "
|
| 135 |
+
"authorized to work after dark."
|
| 136 |
+
)
|
| 137 |
+
elif spec.family == "state_tracking":
|
| 138 |
+
counter = 10 + spec.seed % 7
|
| 139 |
+
add_a = 3 + spec.seed % 5
|
| 140 |
+
subtract = 1 + spec.seed % 3
|
| 141 |
+
final = counter + add_a - subtract
|
| 142 |
+
primary = f"{marker} STATE stream={target} value={counter} sequence=1"
|
| 143 |
+
insertions.extend(
|
| 144 |
+
[
|
| 145 |
+
(min(0.95, spec.position + 0.18), "update-a", f"UPDATE stream={target} add={add_a} sequence=2"),
|
| 146 |
+
(min(0.98, spec.position + 0.34), "update-b", f"UPDATE stream={target} subtract={subtract} sequence=3"),
|
| 147 |
+
]
|
| 148 |
+
)
|
| 149 |
+
common["final_value"] = final
|
| 150 |
+
query = "Apply the ordered updates and return the stream record and final value."
|
| 151 |
+
else:
|
| 152 |
+
raise ValueError(f"Unknown context family: {spec.family}")
|
| 153 |
+
|
| 154 |
+
primary_end_marker = f"<<SX_PRIMARY_END_{spec.seed}_{spec.family.upper()}>>"
|
| 155 |
+
insertions.append((spec.position, "primary", primary + " " + primary_end_marker))
|
| 156 |
+
return sorted(insertions, key=lambda item: (item[0], item[1])), query, common
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _filler_pool(tokenizer: TokenizerProtocol, seed: int) -> list[int]:
|
| 160 |
+
rng = random.Random(seed)
|
| 161 |
+
services = ["atlas", "beacon", "cinder", "delta", "ember", "fjord", "garnet", "helios"]
|
| 162 |
+
states = ["nominal", "queued", "retrying", "stable", "verified", "warming"]
|
| 163 |
+
regions = ["north-ridge", "west-field", "central-bay", "east-grove"]
|
| 164 |
+
lines = []
|
| 165 |
+
for index in range(5000):
|
| 166 |
+
service = rng.choice(services)
|
| 167 |
+
state = rng.choice(states)
|
| 168 |
+
region = rng.choice(regions)
|
| 169 |
+
trace = f"{rng.getrandbits(48):012x}"
|
| 170 |
+
lines.append(
|
| 171 |
+
f"event {index:05d}: service={service} region={region} state={state} "
|
| 172 |
+
f"latency_ms={rng.randrange(3, 997)} trace={trace}; routine telemetry only."
|
| 173 |
+
)
|
| 174 |
+
token_ids = tokenizer.encode("\n" + "\n".join(lines) + "\n")
|
| 175 |
+
if len(token_ids) < 1000:
|
| 176 |
+
raise ValueError("Tokenizer produced an unexpectedly small filler pool")
|
| 177 |
+
return token_ids
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _take(pool: list[int], count: int, offset: int) -> list[int]:
|
| 181 |
+
if count <= 0:
|
| 182 |
+
return []
|
| 183 |
+
start = offset % len(pool)
|
| 184 |
+
rotated = pool[start:] + pool[:start]
|
| 185 |
+
repeats, remainder = divmod(count, len(rotated))
|
| 186 |
+
return rotated * repeats + rotated[:remainder]
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _allocate_filler(total: int, insertion_positions: list[float]) -> list[int]:
|
| 190 |
+
gaps = []
|
| 191 |
+
previous = 0.0
|
| 192 |
+
for position in insertion_positions:
|
| 193 |
+
gaps.append(max(0.0, position - previous))
|
| 194 |
+
previous = position
|
| 195 |
+
gaps.append(max(0.0, 1.0 - previous))
|
| 196 |
+
raw = [total * gap for gap in gaps]
|
| 197 |
+
values = [int(value) for value in raw]
|
| 198 |
+
for index in sorted(range(len(raw)), key=lambda item: raw[item] - values[item], reverse=True):
|
| 199 |
+
if sum(values) >= total:
|
| 200 |
+
break
|
| 201 |
+
values[index] += 1
|
| 202 |
+
return values
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def build_context_case(spec: ContextSpec, tokenizer: TokenizerProtocol) -> BenchCase:
|
| 206 |
+
insertions, query, expected = _task_payload(spec)
|
| 207 |
+
start_sentinel = f"SX_START_{spec.seed}_{spec.family}"
|
| 208 |
+
end_sentinel = f"SX_END_{spec.seed}_{spec.family}"
|
| 209 |
+
expected = {"start_sentinel": start_sentinel, **expected, "end_sentinel": end_sentinel}
|
| 210 |
+
keys = ", ".join(expected)
|
| 211 |
+
query_text = f"{query} Return exactly one JSON object with keys: {keys}."
|
| 212 |
+
prefix_query = query_text + "\n\n" if spec.query_placement == "before" else ""
|
| 213 |
+
suffix_query = "\n\n" + query_text if spec.query_placement == "after" else ""
|
| 214 |
+
|
| 215 |
+
fixed_user = (
|
| 216 |
+
prefix_query
|
| 217 |
+
+ f"BEGIN CONTEXT\nSTART SENTINEL: {start_sentinel}\n"
|
| 218 |
+
+ "\n".join(text for _, _, text in insertions)
|
| 219 |
+
+ f"\nEND SENTINEL: {end_sentinel}\nEND CONTEXT"
|
| 220 |
+
+ suffix_query
|
| 221 |
+
)
|
| 222 |
+
fixed_messages = [
|
| 223 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 224 |
+
{"role": "user", "content": fixed_user},
|
| 225 |
+
]
|
| 226 |
+
fixed_tokens = len(tokenizer.encode(tokenizer.render_chat(fixed_messages)))
|
| 227 |
+
available = spec.target_tokens - fixed_tokens
|
| 228 |
+
if available < 512:
|
| 229 |
+
raise ValueError(
|
| 230 |
+
f"Target {spec.target_tokens} is too small for {spec.family}; only {available} filler tokens remain"
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
pool = _filler_pool(tokenizer, spec.seed)
|
| 234 |
+
allocations = _allocate_filler(available, [item[0] for item in insertions])
|
| 235 |
+
segments = [_take(pool, size, spec.seed * 97 + index * 7919) for index, size in enumerate(allocations)]
|
| 236 |
+
primary_index = next(index for index, item in enumerate(insertions) if item[1] == "primary")
|
| 237 |
+
primary_marker = insertions[primary_index][2].split(" ", 1)[0]
|
| 238 |
+
primary_end_marker = f"<<SX_PRIMARY_END_{spec.seed}_{spec.family.upper()}>>"
|
| 239 |
+
|
| 240 |
+
def make_messages() -> list[dict[str, Any]]:
|
| 241 |
+
context_parts = [f"START SENTINEL: {start_sentinel}\n"]
|
| 242 |
+
for index, (_, _, insertion) in enumerate(insertions):
|
| 243 |
+
context_parts.append(tokenizer.decode(segments[index]))
|
| 244 |
+
context_parts.append("\n" + insertion + "\n")
|
| 245 |
+
context_parts.append(tokenizer.decode(segments[-1]))
|
| 246 |
+
context_parts.append(f"\nEND SENTINEL: {end_sentinel}")
|
| 247 |
+
user = prefix_query + "BEGIN CONTEXT\n" + "".join(context_parts) + "\nEND CONTEXT" + suffix_query
|
| 248 |
+
return [
|
| 249 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 250 |
+
{"role": "user", "content": user},
|
| 251 |
+
]
|
| 252 |
+
|
| 253 |
+
diagnostics: list[tuple[int, int, int]] = []
|
| 254 |
+
for iteration in range(24):
|
| 255 |
+
messages = make_messages()
|
| 256 |
+
rendered = tokenizer.render_chat(messages)
|
| 257 |
+
actual_total = len(tokenizer.encode(rendered))
|
| 258 |
+
total_delta = spec.target_tokens - actual_total
|
| 259 |
+
primary_start = tokenizer.token_offset(rendered, primary_marker)
|
| 260 |
+
primary_end = tokenizer.token_offset(rendered, primary_end_marker)
|
| 261 |
+
actual_offset = round((primary_start + primary_end) / 2)
|
| 262 |
+
context_start = tokenizer.token_offset(rendered, "START SENTINEL:")
|
| 263 |
+
context_end = tokenizer.token_offset(rendered, "END SENTINEL:")
|
| 264 |
+
diagnostics.append((actual_total, actual_offset, total_delta))
|
| 265 |
+
if total_delta:
|
| 266 |
+
if total_delta > 0:
|
| 267 |
+
segments[-1].extend(_take(pool, total_delta, spec.seed + iteration * 3571))
|
| 268 |
+
else:
|
| 269 |
+
remaining = -total_delta
|
| 270 |
+
for segment in reversed(segments):
|
| 271 |
+
removed = min(remaining, len(segment))
|
| 272 |
+
if removed:
|
| 273 |
+
del segment[-removed:]
|
| 274 |
+
remaining -= removed
|
| 275 |
+
if remaining == 0:
|
| 276 |
+
break
|
| 277 |
+
if remaining:
|
| 278 |
+
raise ValueError("Unable to trim context to requested token count")
|
| 279 |
+
continue
|
| 280 |
+
|
| 281 |
+
desired_offset = context_start + round((context_end - context_start) * spec.position)
|
| 282 |
+
position_delta = desired_offset - actual_offset
|
| 283 |
+
tolerance = max(4, round(spec.target_tokens * 0.0025))
|
| 284 |
+
if abs(position_delta) <= tolerance:
|
| 285 |
+
break
|
| 286 |
+
before = segments[primary_index]
|
| 287 |
+
after = segments[primary_index + 1]
|
| 288 |
+
if position_delta > 0:
|
| 289 |
+
movement = min(position_delta, len(after))
|
| 290 |
+
before.extend(_take(pool, movement, spec.seed + iteration * 1237))
|
| 291 |
+
del after[:movement]
|
| 292 |
+
else:
|
| 293 |
+
movement = min(-position_delta, len(before))
|
| 294 |
+
del before[-movement:]
|
| 295 |
+
after[:0] = _take(pool, movement, spec.seed + iteration * 1237)
|
| 296 |
+
else:
|
| 297 |
+
raise RuntimeError(
|
| 298 |
+
f"Exact context construction did not converge for {spec.case_id}; "
|
| 299 |
+
f"last iterations={diagnostics[-6:]}"
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
messages = make_messages()
|
| 303 |
+
rendered = tokenizer.render_chat(messages)
|
| 304 |
+
actual_total = len(tokenizer.encode(rendered))
|
| 305 |
+
primary_start = tokenizer.token_offset(rendered, primary_marker)
|
| 306 |
+
primary_end = tokenizer.token_offset(rendered, primary_end_marker)
|
| 307 |
+
actual_offset = round((primary_start + primary_end) / 2)
|
| 308 |
+
context_start = tokenizer.token_offset(rendered, "START SENTINEL:")
|
| 309 |
+
context_end = tokenizer.token_offset(rendered, "END SENTINEL:")
|
| 310 |
+
if actual_total != spec.target_tokens:
|
| 311 |
+
raise AssertionError(f"Requested {spec.target_tokens} rendered tokens, produced {actual_total}")
|
| 312 |
+
actual_position = (actual_offset - context_start) / (context_end - context_start)
|
| 313 |
+
metadata = {
|
| 314 |
+
"matrix": spec.matrix,
|
| 315 |
+
"family": spec.family,
|
| 316 |
+
"seed": spec.seed,
|
| 317 |
+
"target_prompt_tokens": spec.target_tokens,
|
| 318 |
+
"actual_rendered_tokens": actual_total,
|
| 319 |
+
"requested_position": spec.position,
|
| 320 |
+
"actual_primary_token_offset": actual_offset,
|
| 321 |
+
"actual_primary_start_token_offset": primary_start,
|
| 322 |
+
"actual_primary_end_token_offset": primary_end,
|
| 323 |
+
"actual_primary_position": actual_position,
|
| 324 |
+
"context_start_token_offset": context_start,
|
| 325 |
+
"context_end_token_offset": context_end,
|
| 326 |
+
"query_placement": spec.query_placement,
|
| 327 |
+
"tokenizer_fingerprint": tokenizer.fingerprint,
|
| 328 |
+
"prompt_hash": sha256_json(messages),
|
| 329 |
+
"truncation_sentinels": [start_sentinel, end_sentinel],
|
| 330 |
+
}
|
| 331 |
+
return BenchCase(
|
| 332 |
+
case_id=spec.case_id,
|
| 333 |
+
suite_id=spec.suite_id,
|
| 334 |
+
lane="long-context",
|
| 335 |
+
messages=messages,
|
| 336 |
+
scorer="strict_json_exact",
|
| 337 |
+
expected=expected,
|
| 338 |
+
max_output_tokens=2048,
|
| 339 |
+
metadata=metadata,
|
| 340 |
+
)
|
src/shiftedx_bench/holdout.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import hmac
|
| 5 |
+
import json
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def derive_holdout_config(template: dict[str, Any], master_key: str, release_id: str) -> dict[str, Any]:
|
| 10 |
+
if len(master_key) < 16:
|
| 11 |
+
raise ValueError("Holdout master key must contain at least 16 characters")
|
| 12 |
+
value = json.loads(json.dumps(template))
|
| 13 |
+
value["suite_id"] = f"{template['suite_id']}-holdout-{release_id}"
|
| 14 |
+
for matrix in value["matrices"]:
|
| 15 |
+
count = len(matrix.get("seeds") or [])
|
| 16 |
+
seeds = []
|
| 17 |
+
for index in range(count):
|
| 18 |
+
message = f"{release_id}:{matrix['name']}:{index}".encode()
|
| 19 |
+
digest = hmac.new(master_key.encode(), message, hashlib.sha256).digest()
|
| 20 |
+
seeds.append(int.from_bytes(digest[:4], "big") & 0x7FFFFFFF)
|
| 21 |
+
matrix["seeds"] = seeds
|
| 22 |
+
value["holdout"] = {
|
| 23 |
+
"release_id": release_id,
|
| 24 |
+
"derivation": "HMAC-SHA256",
|
| 25 |
+
"master_key_recorded": False,
|
| 26 |
+
"publish_after_evaluation": True,
|
| 27 |
+
}
|
| 28 |
+
return value
|
| 29 |
+
|
src/shiftedx_bench/models.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import asdict, dataclass, field
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@dataclass(frozen=True)
|
| 8 |
+
class BenchCase:
|
| 9 |
+
case_id: str
|
| 10 |
+
suite_id: str
|
| 11 |
+
lane: str
|
| 12 |
+
messages: list[dict[str, Any]]
|
| 13 |
+
scorer: str
|
| 14 |
+
expected: Any
|
| 15 |
+
max_output_tokens: int = 256
|
| 16 |
+
tools: list[dict[str, Any]] | None = None
|
| 17 |
+
request_overrides: dict[str, Any] = field(default_factory=dict)
|
| 18 |
+
metadata: dict[str, Any] = field(default_factory=dict)
|
| 19 |
+
|
| 20 |
+
def to_dict(self, *, include_expected: bool = True) -> dict[str, Any]:
|
| 21 |
+
value = asdict(self)
|
| 22 |
+
if not include_expected:
|
| 23 |
+
value.pop("expected", None)
|
| 24 |
+
return value
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclass
|
| 28 |
+
class CaseResult:
|
| 29 |
+
schema_version: str
|
| 30 |
+
run_id: str
|
| 31 |
+
suite_id: str
|
| 32 |
+
case_id: str
|
| 33 |
+
lane: str
|
| 34 |
+
variant: str
|
| 35 |
+
passed: bool
|
| 36 |
+
score: float
|
| 37 |
+
score_max: float
|
| 38 |
+
error: str | None
|
| 39 |
+
response: dict[str, Any]
|
| 40 |
+
telemetry: dict[str, Any]
|
| 41 |
+
metadata: dict[str, Any]
|
| 42 |
+
request_hash: str
|
| 43 |
+
|
| 44 |
+
def to_dict(self) -> dict[str, Any]:
|
| 45 |
+
return asdict(self)
|
| 46 |
+
|
src/shiftedx_bench/provenance.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import platform
|
| 4 |
+
import sys
|
| 5 |
+
from datetime import UTC, datetime
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
from . import __version__
|
| 10 |
+
from .util import sha256_file, write_json
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def make_run_manifest(
|
| 14 |
+
*,
|
| 15 |
+
run_id: str,
|
| 16 |
+
suite_id: str,
|
| 17 |
+
model: str,
|
| 18 |
+
config_path: Path | None,
|
| 19 |
+
tokenizer_fingerprint: str | None,
|
| 20 |
+
variants: list[dict[str, Any]],
|
| 21 |
+
) -> dict[str, Any]:
|
| 22 |
+
return {
|
| 23 |
+
"schema_version": "1.0",
|
| 24 |
+
"run_id": run_id,
|
| 25 |
+
"created_at": datetime.now(UTC).isoformat(),
|
| 26 |
+
"suite_id": suite_id,
|
| 27 |
+
"model": model,
|
| 28 |
+
"benchmark_version": __version__,
|
| 29 |
+
"config_sha256": sha256_file(config_path) if config_path else None,
|
| 30 |
+
"tokenizer_fingerprint": tokenizer_fingerprint,
|
| 31 |
+
"variants": variants,
|
| 32 |
+
"environment": {
|
| 33 |
+
"python": sys.version.split()[0],
|
| 34 |
+
"platform": platform.platform(),
|
| 35 |
+
"machine": platform.machine(),
|
| 36 |
+
},
|
| 37 |
+
"claim_policy": {
|
| 38 |
+
"quality_and_performance_separate": True,
|
| 39 |
+
"raw_requests_retained": True,
|
| 40 |
+
"single_aggregate_intelligence_score": False,
|
| 41 |
+
},
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def write_manifest(path: Path, value: dict[str, Any]) -> None:
|
| 46 |
+
write_json(path, value)
|
| 47 |
+
|
src/shiftedx_bench/quality.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import heapq
|
| 4 |
+
import json
|
| 5 |
+
import random
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
from .models import BenchCase
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
DEFAULT_FAMILIES = [
|
| 12 |
+
"ledger",
|
| 13 |
+
"shortest_path",
|
| 14 |
+
"interval_schedule",
|
| 15 |
+
"table_join",
|
| 16 |
+
"event_state",
|
| 17 |
+
"instruction_order",
|
| 18 |
+
"code_chunks",
|
| 19 |
+
"code_window",
|
| 20 |
+
"code_normalize",
|
| 21 |
+
"code_percentile",
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
SYSTEM = (
|
| 26 |
+
"You are being evaluated by a deterministic harness. Follow the requested format "
|
| 27 |
+
"exactly and return no explanation or hidden reasoning."
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _case(case_id: str, family: str, prompt: str, expected: Any, scorer: str = "strict_json_exact") -> BenchCase:
|
| 32 |
+
return BenchCase(
|
| 33 |
+
case_id=case_id,
|
| 34 |
+
suite_id="shiftedx-quality-v1",
|
| 35 |
+
lane="quality",
|
| 36 |
+
messages=[{"role": "system", "content": SYSTEM}, {"role": "user", "content": prompt}],
|
| 37 |
+
scorer=scorer,
|
| 38 |
+
expected=expected,
|
| 39 |
+
max_output_tokens=4096 if scorer == "python_code" else 2048,
|
| 40 |
+
metadata={"family": family, "procedural": True},
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _shortest_path(graph: dict[str, dict[str, int]], source: str, target: str) -> tuple[int, list[str]]:
|
| 45 |
+
queue: list[tuple[int, list[str], str]] = [(0, [source], source)]
|
| 46 |
+
best: dict[str, tuple[int, list[str]]] = {}
|
| 47 |
+
while queue:
|
| 48 |
+
distance, path, node = heapq.heappop(queue)
|
| 49 |
+
if node in best and best[node] <= (distance, path):
|
| 50 |
+
continue
|
| 51 |
+
best[node] = (distance, path)
|
| 52 |
+
if node == target:
|
| 53 |
+
return distance, path
|
| 54 |
+
for neighbor, weight in graph[node].items():
|
| 55 |
+
heapq.heappush(queue, (distance + weight, path + [neighbor], neighbor))
|
| 56 |
+
raise ValueError("unreachable")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _interval_solution(jobs: list[tuple[int, int, int]]) -> tuple[int, list[int]]:
|
| 60 |
+
best_weight = -1
|
| 61 |
+
best_indices: list[int] = []
|
| 62 |
+
for mask in range(1 << len(jobs)):
|
| 63 |
+
indices = [index for index in range(len(jobs)) if mask & (1 << index)]
|
| 64 |
+
selected = sorted((jobs[index][0], jobs[index][1], index) for index in indices)
|
| 65 |
+
if any(selected[index][1] > selected[index + 1][0] for index in range(len(selected) - 1)):
|
| 66 |
+
continue
|
| 67 |
+
weight = sum(jobs[index][2] for index in indices)
|
| 68 |
+
if weight > best_weight or (weight == best_weight and indices < best_indices):
|
| 69 |
+
best_weight, best_indices = weight, indices
|
| 70 |
+
return best_weight, best_indices
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def generate_quality_cases(seeds: list[int], families: list[str] | None = None) -> list[BenchCase]:
|
| 74 |
+
families = families or DEFAULT_FAMILIES
|
| 75 |
+
cases: list[BenchCase] = []
|
| 76 |
+
for seed in seeds:
|
| 77 |
+
rng = random.Random(seed)
|
| 78 |
+
for family in families:
|
| 79 |
+
case_id = f"{family}__s{seed}"
|
| 80 |
+
if family == "ledger":
|
| 81 |
+
values = [rng.randrange(-90, 160) for _ in range(14)]
|
| 82 |
+
expected = {"net": sum(values), "credits": sum(value > 0 for value in values)}
|
| 83 |
+
prompt = (
|
| 84 |
+
f"Transactions: {values}. Return bare JSON with exactly two keys: "
|
| 85 |
+
"net and credits. credits is the number of positive transactions."
|
| 86 |
+
)
|
| 87 |
+
cases.append(_case(case_id, family, prompt, expected))
|
| 88 |
+
elif family == "shortest_path":
|
| 89 |
+
graph = {
|
| 90 |
+
"A": {"B": rng.randrange(1, 7), "C": rng.randrange(4, 10)},
|
| 91 |
+
"B": {"C": rng.randrange(1, 5), "D": rng.randrange(3, 9)},
|
| 92 |
+
"C": {"D": rng.randrange(1, 5), "E": rng.randrange(4, 9)},
|
| 93 |
+
"D": {"E": rng.randrange(1, 5)},
|
| 94 |
+
"E": {},
|
| 95 |
+
}
|
| 96 |
+
distance, path = _shortest_path(graph, "A", "E")
|
| 97 |
+
prompt = (
|
| 98 |
+
f"Directed weighted graph: {json.dumps(graph, sort_keys=True)}. "
|
| 99 |
+
"Return bare JSON with the shortest distance and lexicographically smallest path from A to E."
|
| 100 |
+
)
|
| 101 |
+
cases.append(_case(case_id, family, prompt, {"distance": distance, "path": path}))
|
| 102 |
+
elif family == "interval_schedule":
|
| 103 |
+
jobs = []
|
| 104 |
+
for index in range(8):
|
| 105 |
+
start = rng.randrange(0, 14)
|
| 106 |
+
jobs.append((start, start + rng.randrange(1, 6), rng.randrange(1, 20)))
|
| 107 |
+
weight, indices = _interval_solution(jobs)
|
| 108 |
+
prompt = (
|
| 109 |
+
f"Jobs as [start,end,weight]: {jobs}. Select non-overlapping jobs where end <= next start. "
|
| 110 |
+
"Return bare JSON with max_weight and selected original indices; break ties lexicographically."
|
| 111 |
+
)
|
| 112 |
+
cases.append(_case(case_id, family, prompt, {"max_weight": weight, "indices": indices}))
|
| 113 |
+
elif family == "table_join":
|
| 114 |
+
items = [f"sku-{index}" for index in range(6)]
|
| 115 |
+
quantities = {item: rng.randrange(0, 9) for item in items}
|
| 116 |
+
prices = {item: rng.randrange(3, 30) for item in reversed(items)}
|
| 117 |
+
total = sum(quantities[item] * prices[item] for item in items)
|
| 118 |
+
prompt = (
|
| 119 |
+
f"Quantities={json.dumps(quantities)}; unit_prices={json.dumps(prices)}. "
|
| 120 |
+
"Join by SKU and return bare JSON with total_value and zero_stock SKUs in sorted order."
|
| 121 |
+
)
|
| 122 |
+
expected = {"total_value": total, "zero_stock": sorted(k for k, v in quantities.items() if v == 0)}
|
| 123 |
+
cases.append(_case(case_id, family, prompt, expected))
|
| 124 |
+
elif family == "event_state":
|
| 125 |
+
value = rng.randrange(10, 30)
|
| 126 |
+
events = []
|
| 127 |
+
for _ in range(9):
|
| 128 |
+
operation = rng.choice(["add", "subtract", "double", "ignore"])
|
| 129 |
+
amount = rng.randrange(1, 6)
|
| 130 |
+
events.append([operation, amount])
|
| 131 |
+
if operation == "add":
|
| 132 |
+
value += amount
|
| 133 |
+
elif operation == "subtract":
|
| 134 |
+
value -= amount
|
| 135 |
+
elif operation == "double":
|
| 136 |
+
value *= 2
|
| 137 |
+
initial = rng.randrange(10, 30)
|
| 138 |
+
value = initial
|
| 139 |
+
for operation, amount in events:
|
| 140 |
+
if operation == "add": value += amount
|
| 141 |
+
elif operation == "subtract": value -= amount
|
| 142 |
+
elif operation == "double": value *= 2
|
| 143 |
+
prompt = (
|
| 144 |
+
f"Initial value={initial}; ordered events={events}. Ignore events named ignore. "
|
| 145 |
+
"Return bare JSON with final_value and applied_event_count."
|
| 146 |
+
)
|
| 147 |
+
expected = {"final_value": value, "applied_event_count": sum(e[0] != "ignore" for e in events)}
|
| 148 |
+
cases.append(_case(case_id, family, prompt, expected))
|
| 149 |
+
elif family == "instruction_order":
|
| 150 |
+
words = ["amber", "cinder", "fjord", "opal", "raven", "willow"]
|
| 151 |
+
rng.shuffle(words)
|
| 152 |
+
chosen = sorted(words[1:5], key=lambda value: (len(value), value), reverse=True)
|
| 153 |
+
prompt = (
|
| 154 |
+
f"Words={words}. Discard the first and last list elements, then sort the remainder by "
|
| 155 |
+
"descending length and reverse alphabetical order for ties. Return the bare JSON array."
|
| 156 |
+
)
|
| 157 |
+
cases.append(_case(case_id, family, prompt, chosen))
|
| 158 |
+
elif family == "code_chunks":
|
| 159 |
+
prompt = (
|
| 160 |
+
"Return only Python code defining chunked(values, size). It must return consecutive lists, "
|
| 161 |
+
"include a final short chunk, reject size <= 0 with ValueError, and not mutate input."
|
| 162 |
+
)
|
| 163 |
+
tests = """
|
| 164 |
+
assert chunked([1,2,3,4,5], 2) == [[1,2],[3,4],[5]]
|
| 165 |
+
assert chunked([], 3) == []
|
| 166 |
+
x=[1,2,3]; assert chunked(x, 5)==[[1,2,3]] and x==[1,2,3]
|
| 167 |
+
for bad in (0,-1):
|
| 168 |
+
try: chunked([1], bad); raise AssertionError('missing ValueError')
|
| 169 |
+
except ValueError: pass
|
| 170 |
+
"""
|
| 171 |
+
cases.append(_case(case_id, family, prompt, {"tests": tests}, "python_code"))
|
| 172 |
+
elif family == "code_window":
|
| 173 |
+
prompt = (
|
| 174 |
+
"Return only Python code defining max_window_sum(values, width). Return the largest sum of "
|
| 175 |
+
"exactly width consecutive values. Raise ValueError for empty input or invalid width."
|
| 176 |
+
)
|
| 177 |
+
tests = """
|
| 178 |
+
assert max_window_sum([2,-1,5,1,-3], 2) == 6
|
| 179 |
+
assert max_window_sum([-8,-3,-5], 1) == -3
|
| 180 |
+
assert max_window_sum([4,2], 2) == 6
|
| 181 |
+
for args in [([],1),([1],0),([1],2)]:
|
| 182 |
+
try: max_window_sum(*args); raise AssertionError('missing ValueError')
|
| 183 |
+
except ValueError: pass
|
| 184 |
+
"""
|
| 185 |
+
cases.append(_case(case_id, family, prompt, {"tests": tests}, "python_code"))
|
| 186 |
+
elif family == "code_normalize":
|
| 187 |
+
prompt = (
|
| 188 |
+
"Return only Python code defining normalize_segments(path). Collapse empty and '.' segments; "
|
| 189 |
+
"resolve '..'; absolute paths cannot rise above root; relative paths preserve leading '..'."
|
| 190 |
+
)
|
| 191 |
+
tests = """
|
| 192 |
+
assert normalize_segments('/a//b/../c') == '/a/c'
|
| 193 |
+
assert normalize_segments('../../a') == '../../a'
|
| 194 |
+
assert normalize_segments('a/../../b') == '../b'
|
| 195 |
+
assert normalize_segments('/../../a') == '/a'
|
| 196 |
+
assert normalize_segments('') == '.'
|
| 197 |
+
"""
|
| 198 |
+
cases.append(_case(case_id, family, prompt, {"tests": tests}, "python_code"))
|
| 199 |
+
elif family == "code_percentile":
|
| 200 |
+
prompt = (
|
| 201 |
+
"Return only Python code defining percentile(values, p). Use sorted values and linear "
|
| 202 |
+
"interpolation at rank p/100*(n-1). Reject empty input and p outside 0..100 with ValueError."
|
| 203 |
+
)
|
| 204 |
+
tests = """
|
| 205 |
+
assert percentile([1,2,3,4], 50) == 2.5
|
| 206 |
+
assert percentile([10,0,20], 25) == 5
|
| 207 |
+
assert percentile([7], 99) == 7
|
| 208 |
+
for args in [([],50),([1],-1),([1],101)]:
|
| 209 |
+
try: percentile(*args); raise AssertionError('missing ValueError')
|
| 210 |
+
except ValueError: pass
|
| 211 |
+
"""
|
| 212 |
+
cases.append(_case(case_id, family, prompt, {"tests": tests}, "python_code"))
|
| 213 |
+
else:
|
| 214 |
+
raise ValueError(f"Unknown quality family: {family}")
|
| 215 |
+
return cases
|
src/shiftedx_bench/release.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
TEXT_SUFFIXES = {".md", ".py", ".json", ".jsonl", ".toml", ".yaml", ".yml", ".txt"}
|
| 9 |
+
FORBIDDEN = {
|
| 10 |
+
"Hugging Face access token": re.compile("h" + r"f_[A-Za-z0-9]{20,}"),
|
| 11 |
+
"macOS user path": re.compile("/" + r"Users/[^/\s]+/"),
|
| 12 |
+
"Linux user path": re.compile("/" + r"home/[^/\s]+/"),
|
| 13 |
+
"private key": re.compile(r"-----BEGIN (?:RSA |OPENSSH |EC )?PRIVATE KEY-----"),
|
| 14 |
+
"loopback URL in public result": re.compile(r"https?://(?:127\.0\.0\.1|localhost):\d+"),
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def scan_public_tree(root: Path) -> dict[str, Any]:
|
| 19 |
+
failures = []
|
| 20 |
+
for path in sorted(root.rglob("*")):
|
| 21 |
+
if not path.is_file() or path.suffix.lower() not in TEXT_SUFFIXES:
|
| 22 |
+
continue
|
| 23 |
+
relative = path.relative_to(root).as_posix()
|
| 24 |
+
if any(part in {".git", ".pytest_cache", "__pycache__"} for part in path.parts):
|
| 25 |
+
continue
|
| 26 |
+
text = path.read_text(encoding="utf-8", errors="replace")
|
| 27 |
+
for label, pattern in FORBIDDEN.items():
|
| 28 |
+
if pattern.search(text):
|
| 29 |
+
failures.append({"file": relative, "issue": label})
|
| 30 |
+
return {"ok": not failures, "failures": failures, "files_scanned": sum(1 for p in root.rglob("*") if p.is_file())}
|
src/shiftedx_bench/runner.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import uuid
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any, Iterable
|
| 7 |
+
|
| 8 |
+
from .api import OpenAIClient
|
| 9 |
+
from .models import BenchCase, CaseResult
|
| 10 |
+
from .scoring import score_response
|
| 11 |
+
from .util import append_jsonl, read_jsonl, sha256_json
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def build_payload(case: BenchCase, model: str, variant: dict[str, Any]) -> dict[str, Any]:
|
| 15 |
+
payload: dict[str, Any] = {
|
| 16 |
+
"model": model,
|
| 17 |
+
"messages": case.messages,
|
| 18 |
+
"temperature": 0,
|
| 19 |
+
"top_p": 1,
|
| 20 |
+
"max_tokens": case.max_output_tokens,
|
| 21 |
+
"seed": 7319,
|
| 22 |
+
}
|
| 23 |
+
if case.tools:
|
| 24 |
+
payload["tools"] = case.tools
|
| 25 |
+
payload["tool_choice"] = "auto"
|
| 26 |
+
payload.update(case.request_overrides)
|
| 27 |
+
payload.update(variant.get("request_overrides") or {})
|
| 28 |
+
return payload
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def run_cases(
|
| 32 |
+
cases: Iterable[BenchCase],
|
| 33 |
+
*,
|
| 34 |
+
client: OpenAIClient,
|
| 35 |
+
model: str,
|
| 36 |
+
output_path: Path,
|
| 37 |
+
variants: list[dict[str, Any]] | None = None,
|
| 38 |
+
run_id: str | None = None,
|
| 39 |
+
stream: bool = False,
|
| 40 |
+
) -> list[dict[str, Any]]:
|
| 41 |
+
run_id = run_id or str(uuid.uuid4())
|
| 42 |
+
variants = variants or [{"label": "default", "request_overrides": {}}]
|
| 43 |
+
completed = {
|
| 44 |
+
(row.get("case_id"), row.get("variant"))
|
| 45 |
+
for row in read_jsonl(output_path)
|
| 46 |
+
if row.get("schema_version") == "1.0"
|
| 47 |
+
}
|
| 48 |
+
new_rows: list[dict[str, Any]] = []
|
| 49 |
+
for case in cases:
|
| 50 |
+
for variant in variants:
|
| 51 |
+
label = str(variant["label"])
|
| 52 |
+
if (case.case_id, label) in completed:
|
| 53 |
+
continue
|
| 54 |
+
payload = build_payload(case, model, variant)
|
| 55 |
+
request_hash = sha256_json(payload)
|
| 56 |
+
error = None
|
| 57 |
+
try:
|
| 58 |
+
response = client.complete(payload, stream=stream and not case.tools)
|
| 59 |
+
scored = score_response(case.scorer, case.expected, response)
|
| 60 |
+
passed = scored.passed
|
| 61 |
+
error = scored.error
|
| 62 |
+
if "target_prompt_tokens" in case.metadata:
|
| 63 |
+
server_tokens = response.get("prompt_tokens")
|
| 64 |
+
requested_tokens = case.metadata["target_prompt_tokens"]
|
| 65 |
+
if server_tokens != requested_tokens:
|
| 66 |
+
passed = False
|
| 67 |
+
error = (
|
| 68 |
+
f"server prompt token mismatch: requested={requested_tokens}, "
|
| 69 |
+
f"reported={server_tokens}"
|
| 70 |
+
)
|
| 71 |
+
telemetry = {
|
| 72 |
+
key: response.get(key)
|
| 73 |
+
for key in (
|
| 74 |
+
"wall_s",
|
| 75 |
+
"ttft_s",
|
| 76 |
+
"prompt_tokens",
|
| 77 |
+
"completion_tokens",
|
| 78 |
+
"end_to_end_tokens_per_second",
|
| 79 |
+
"prefill_tokens_per_second",
|
| 80 |
+
"decode_tokens_per_second",
|
| 81 |
+
"active_memory_bytes",
|
| 82 |
+
"cache_memory_bytes",
|
| 83 |
+
"mtplx_stats",
|
| 84 |
+
)
|
| 85 |
+
}
|
| 86 |
+
usage = response.get("usage") or {}
|
| 87 |
+
telemetry["cached_prompt_tokens"] = (
|
| 88 |
+
(usage.get("prompt_tokens_details") or {}).get("cached_tokens")
|
| 89 |
+
)
|
| 90 |
+
stats = response.get("mtplx_stats") or {}
|
| 91 |
+
accepted = stats.get("accepted_drafts")
|
| 92 |
+
drafted = stats.get("drafted_tokens")
|
| 93 |
+
telemetry["accepted_draft_ratio"] = (
|
| 94 |
+
accepted / drafted
|
| 95 |
+
if isinstance(accepted, (int, float)) and isinstance(drafted, (int, float)) and drafted
|
| 96 |
+
else stats.get("accepted_draft_ratio")
|
| 97 |
+
)
|
| 98 |
+
result = CaseResult(
|
| 99 |
+
schema_version="1.0",
|
| 100 |
+
run_id=run_id,
|
| 101 |
+
suite_id=case.suite_id,
|
| 102 |
+
case_id=case.case_id,
|
| 103 |
+
lane=case.lane,
|
| 104 |
+
variant=label,
|
| 105 |
+
passed=passed,
|
| 106 |
+
score=scored.value if passed else 0.0,
|
| 107 |
+
score_max=scored.maximum,
|
| 108 |
+
error=error,
|
| 109 |
+
response={
|
| 110 |
+
key: response.get(key)
|
| 111 |
+
for key in (
|
| 112 |
+
"model",
|
| 113 |
+
"content",
|
| 114 |
+
"reasoning_content",
|
| 115 |
+
"tool_calls",
|
| 116 |
+
"finish_reason",
|
| 117 |
+
"usage",
|
| 118 |
+
)
|
| 119 |
+
},
|
| 120 |
+
telemetry=telemetry,
|
| 121 |
+
metadata=case.metadata,
|
| 122 |
+
request_hash=request_hash,
|
| 123 |
+
)
|
| 124 |
+
except Exception as exc:
|
| 125 |
+
result = CaseResult(
|
| 126 |
+
schema_version="1.0",
|
| 127 |
+
run_id=run_id,
|
| 128 |
+
suite_id=case.suite_id,
|
| 129 |
+
case_id=case.case_id,
|
| 130 |
+
lane=case.lane,
|
| 131 |
+
variant=label,
|
| 132 |
+
passed=False,
|
| 133 |
+
score=0.0,
|
| 134 |
+
score_max=1.0,
|
| 135 |
+
error=f"{type(exc).__name__}: {exc}",
|
| 136 |
+
response={},
|
| 137 |
+
telemetry={},
|
| 138 |
+
metadata=case.metadata,
|
| 139 |
+
request_hash=request_hash,
|
| 140 |
+
)
|
| 141 |
+
row = result.to_dict()
|
| 142 |
+
append_jsonl(output_path, [row])
|
| 143 |
+
new_rows.append(row)
|
| 144 |
+
return new_rows
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def api_key_from_env(name: str | None) -> str | None:
|
| 148 |
+
if not name:
|
| 149 |
+
return None
|
| 150 |
+
value = os.environ.get(name)
|
| 151 |
+
if not value:
|
| 152 |
+
raise RuntimeError(f"API-key environment variable is not set: {name}")
|
| 153 |
+
return value
|
src/shiftedx_bench/sandbox.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import ast
|
| 4 |
+
import os
|
| 5 |
+
import subprocess
|
| 6 |
+
import sys
|
| 7 |
+
import tempfile
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
FORBIDDEN_CALLS = {"compile", "eval", "exec", "input", "open", "breakpoint", "__import__"}
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def validate_python_ast(code: str) -> None:
|
| 16 |
+
tree = ast.parse(code)
|
| 17 |
+
for node in ast.walk(tree):
|
| 18 |
+
if isinstance(node, (ast.Import, ast.ImportFrom, ast.Global, ast.Nonlocal)):
|
| 19 |
+
raise ValueError(f"Forbidden syntax: {type(node).__name__}")
|
| 20 |
+
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
|
| 21 |
+
if node.func.id in FORBIDDEN_CALLS:
|
| 22 |
+
raise ValueError(f"Forbidden call: {node.func.id}")
|
| 23 |
+
if isinstance(node, ast.Attribute) and node.attr.startswith("__"):
|
| 24 |
+
raise ValueError("Dunder attribute access is forbidden")
|
| 25 |
+
if isinstance(node, ast.Name) and node.id.startswith("__") and node.id != "__name__":
|
| 26 |
+
raise ValueError("Dunder names are forbidden")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _resource_limits() -> None:
|
| 30 |
+
try:
|
| 31 |
+
import resource
|
| 32 |
+
|
| 33 |
+
resource.setrlimit(resource.RLIMIT_CPU, (3, 3))
|
| 34 |
+
memory = 512 * 1024 * 1024
|
| 35 |
+
resource.setrlimit(resource.RLIMIT_AS, (memory, memory))
|
| 36 |
+
resource.setrlimit(resource.RLIMIT_FSIZE, (1024 * 1024, 1024 * 1024))
|
| 37 |
+
resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32))
|
| 38 |
+
except (ImportError, OSError, ValueError):
|
| 39 |
+
pass
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def run_python_submission(code: str, tests: str, timeout_s: float = 5.0) -> dict[str, Any]:
|
| 43 |
+
try:
|
| 44 |
+
validate_python_ast(code)
|
| 45 |
+
validate_python_ast(tests)
|
| 46 |
+
except Exception as exc:
|
| 47 |
+
return {"passed": False, "error": f"static rejection: {exc}"}
|
| 48 |
+
with tempfile.TemporaryDirectory(prefix="shiftedx-bench-") as temporary:
|
| 49 |
+
path = Path(temporary) / "submission.py"
|
| 50 |
+
path.write_text(code + "\n\n" + tests + "\n", encoding="utf-8")
|
| 51 |
+
environment = {
|
| 52 |
+
"PATH": os.environ.get("PATH", ""),
|
| 53 |
+
"PYTHONHASHSEED": "0",
|
| 54 |
+
"PYTHONDONTWRITEBYTECODE": "1",
|
| 55 |
+
}
|
| 56 |
+
try:
|
| 57 |
+
completed = subprocess.run(
|
| 58 |
+
[sys.executable, "-I", "-S", str(path)],
|
| 59 |
+
cwd=temporary,
|
| 60 |
+
env=environment,
|
| 61 |
+
capture_output=True,
|
| 62 |
+
text=True,
|
| 63 |
+
timeout=timeout_s,
|
| 64 |
+
preexec_fn=_resource_limits if os.name == "posix" else None,
|
| 65 |
+
check=False,
|
| 66 |
+
)
|
| 67 |
+
except subprocess.TimeoutExpired:
|
| 68 |
+
return {"passed": False, "error": "execution timed out"}
|
| 69 |
+
output = (completed.stdout + completed.stderr)[-4000:]
|
| 70 |
+
return {
|
| 71 |
+
"passed": completed.returncode == 0,
|
| 72 |
+
"error": None if completed.returncode == 0 else output.strip(),
|
| 73 |
+
"returncode": completed.returncode,
|
| 74 |
+
}
|
src/shiftedx_bench/scoring.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
from .sandbox import run_python_submission
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@dataclass(frozen=True)
|
| 12 |
+
class Score:
|
| 13 |
+
passed: bool
|
| 14 |
+
value: float
|
| 15 |
+
maximum: float
|
| 16 |
+
error: str | None = None
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def response_text(response: dict[str, Any]) -> str:
|
| 20 |
+
return str(response.get("content") or "")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def strict_json(text: str) -> Any:
|
| 24 |
+
stripped = text.strip()
|
| 25 |
+
if stripped.startswith("```") or not stripped:
|
| 26 |
+
raise ValueError("Expected bare JSON without Markdown fences")
|
| 27 |
+
decoder = json.JSONDecoder()
|
| 28 |
+
value, end = decoder.raw_decode(stripped)
|
| 29 |
+
if stripped[end:].strip():
|
| 30 |
+
raise ValueError("Unexpected text after JSON value")
|
| 31 |
+
return value
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _normalize_tool_calls(response: dict[str, Any]) -> list[dict[str, Any]]:
|
| 35 |
+
normalized = []
|
| 36 |
+
for call in response.get("tool_calls") or []:
|
| 37 |
+
function = call.get("function") or {}
|
| 38 |
+
arguments = function.get("arguments", {})
|
| 39 |
+
if isinstance(arguments, str):
|
| 40 |
+
arguments = json.loads(arguments)
|
| 41 |
+
normalized.append({"name": function.get("name"), "arguments": arguments})
|
| 42 |
+
return normalized
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def score_response(scorer: str, expected: Any, response: dict[str, Any]) -> Score:
|
| 46 |
+
try:
|
| 47 |
+
if scorer == "exact_text":
|
| 48 |
+
actual = response_text(response).strip()
|
| 49 |
+
passed = actual == str(expected)
|
| 50 |
+
elif scorer == "strict_json_exact":
|
| 51 |
+
actual = strict_json(response_text(response))
|
| 52 |
+
passed = actual == expected
|
| 53 |
+
elif scorer == "strict_json_subset":
|
| 54 |
+
actual = strict_json(response_text(response))
|
| 55 |
+
if not isinstance(actual, dict) or not isinstance(expected, dict):
|
| 56 |
+
passed = False
|
| 57 |
+
else:
|
| 58 |
+
passed = all(actual.get(key) == value for key, value in expected.items())
|
| 59 |
+
elif scorer == "tool_calls_exact":
|
| 60 |
+
actual = _normalize_tool_calls(response)
|
| 61 |
+
passed = actual == expected
|
| 62 |
+
elif scorer == "python_code":
|
| 63 |
+
text = response_text(response).strip()
|
| 64 |
+
match = re.fullmatch(r"```(?:python)?\s*(.*?)\s*```", text, re.DOTALL | re.IGNORECASE)
|
| 65 |
+
code = match.group(1) if match else text
|
| 66 |
+
outcome = run_python_submission(code, str(expected["tests"]))
|
| 67 |
+
passed = outcome["passed"]
|
| 68 |
+
return Score(passed, float(passed), 1.0, outcome.get("error"))
|
| 69 |
+
else:
|
| 70 |
+
raise ValueError(f"Unknown scorer: {scorer}")
|
| 71 |
+
return Score(passed, float(passed), 1.0, None if passed else "answer mismatch")
|
| 72 |
+
except Exception as exc:
|
| 73 |
+
return Score(False, 0.0, 1.0, f"{type(exc).__name__}: {exc}")
|
| 74 |
+
|
src/shiftedx_bench/summary.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import random
|
| 4 |
+
import statistics
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _mean(values: list[float]) -> float | None:
|
| 10 |
+
return statistics.fmean(values) if values else None
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def bootstrap_mean_ci(values: list[float], *, seed: int = 7319, samples: int = 2000) -> list[float] | None:
|
| 14 |
+
if not values:
|
| 15 |
+
return None
|
| 16 |
+
rng = random.Random(seed)
|
| 17 |
+
estimates = []
|
| 18 |
+
for _ in range(samples):
|
| 19 |
+
estimates.append(statistics.fmean(rng.choice(values) for _ in values))
|
| 20 |
+
estimates.sort()
|
| 21 |
+
return [estimates[round(0.025 * (samples - 1))], estimates[round(0.975 * (samples - 1))]]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def summarize_results(rows: list[dict[str, Any]], effective_threshold: float = 0.90) -> dict[str, Any]:
|
| 25 |
+
grouped: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list)
|
| 26 |
+
for row in rows:
|
| 27 |
+
grouped[(str(row.get("variant")), str(row.get("lane")))].append(row)
|
| 28 |
+
scorecards: dict[str, Any] = {}
|
| 29 |
+
for (variant, lane), items in sorted(grouped.items()):
|
| 30 |
+
values = [float(bool(item.get("passed"))) for item in items]
|
| 31 |
+
wall = [float(item["telemetry"]["wall_s"]) for item in items if item.get("telemetry", {}).get("wall_s")]
|
| 32 |
+
ttft = [float(item["telemetry"]["ttft_s"]) for item in items if item.get("telemetry", {}).get("ttft_s")]
|
| 33 |
+
throughput = [
|
| 34 |
+
float(item["telemetry"]["end_to_end_tokens_per_second"])
|
| 35 |
+
for item in items
|
| 36 |
+
if item.get("telemetry", {}).get("end_to_end_tokens_per_second")
|
| 37 |
+
]
|
| 38 |
+
acceptance = [
|
| 39 |
+
float(item["telemetry"]["accepted_draft_ratio"])
|
| 40 |
+
for item in items
|
| 41 |
+
if item.get("telemetry", {}).get("accepted_draft_ratio") is not None
|
| 42 |
+
]
|
| 43 |
+
cached = [
|
| 44 |
+
float(item["telemetry"]["cached_prompt_tokens"])
|
| 45 |
+
for item in items
|
| 46 |
+
if item.get("telemetry", {}).get("cached_prompt_tokens") is not None
|
| 47 |
+
]
|
| 48 |
+
prefill = [
|
| 49 |
+
float(item["telemetry"]["prefill_tokens_per_second"])
|
| 50 |
+
for item in items
|
| 51 |
+
if item.get("telemetry", {}).get("prefill_tokens_per_second") is not None
|
| 52 |
+
]
|
| 53 |
+
decode = [
|
| 54 |
+
float(item["telemetry"]["decode_tokens_per_second"])
|
| 55 |
+
for item in items
|
| 56 |
+
if item.get("telemetry", {}).get("decode_tokens_per_second") is not None
|
| 57 |
+
]
|
| 58 |
+
memory = [
|
| 59 |
+
float(item["telemetry"]["active_memory_bytes"])
|
| 60 |
+
for item in items
|
| 61 |
+
if item.get("telemetry", {}).get("active_memory_bytes") is not None
|
| 62 |
+
]
|
| 63 |
+
scorecards.setdefault(variant, {})[lane] = {
|
| 64 |
+
"cases": len(items),
|
| 65 |
+
"passed": sum(values),
|
| 66 |
+
"accuracy": _mean(values),
|
| 67 |
+
"accuracy_95_ci": bootstrap_mean_ci(values),
|
| 68 |
+
"mean_wall_s": _mean(wall),
|
| 69 |
+
"mean_ttft_s": _mean(ttft),
|
| 70 |
+
"mean_end_to_end_tokens_per_second": _mean(throughput),
|
| 71 |
+
"mean_accepted_draft_ratio": _mean(acceptance),
|
| 72 |
+
"mean_cached_prompt_tokens": _mean(cached),
|
| 73 |
+
"mean_prefill_tokens_per_second": _mean(prefill),
|
| 74 |
+
"mean_decode_tokens_per_second": _mean(decode),
|
| 75 |
+
"max_active_memory_bytes": max(memory) if memory else None,
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
context_rows = [row for row in rows if row.get("lane") == "long-context"]
|
| 79 |
+
context: dict[str, Any] = {}
|
| 80 |
+
for variant in sorted({str(row.get("variant")) for row in context_rows}):
|
| 81 |
+
selected = [row for row in context_rows if row.get("variant") == variant]
|
| 82 |
+
cells: dict[tuple[int, float], list[float]] = defaultdict(list)
|
| 83 |
+
family: dict[str, list[float]] = defaultdict(list)
|
| 84 |
+
by_length: dict[int, list[float]] = defaultdict(list)
|
| 85 |
+
by_position: dict[float, list[float]] = defaultdict(list)
|
| 86 |
+
for row in selected:
|
| 87 |
+
metadata = row.get("metadata") or {}
|
| 88 |
+
length = int(metadata["target_prompt_tokens"])
|
| 89 |
+
position = float(metadata["requested_position"])
|
| 90 |
+
value = float(bool(row.get("passed")))
|
| 91 |
+
cells[(length, position)].append(value)
|
| 92 |
+
family[str(metadata["family"])].append(value)
|
| 93 |
+
by_length[length].append(value)
|
| 94 |
+
by_position[position].append(value)
|
| 95 |
+
length_scores = {str(key): _mean(value) for key, value in sorted(by_length.items())}
|
| 96 |
+
qualifying = [key for key, value in by_length.items() if statistics.fmean(value) >= effective_threshold]
|
| 97 |
+
context[variant] = {
|
| 98 |
+
"effective_context_threshold": effective_threshold,
|
| 99 |
+
"effective_context_length": max(qualifying) if qualifying else None,
|
| 100 |
+
"accuracy_by_length": length_scores,
|
| 101 |
+
"accuracy_by_position": {str(key): _mean(value) for key, value in sorted(by_position.items())},
|
| 102 |
+
"accuracy_by_family": {key: _mean(value) for key, value in sorted(family.items())},
|
| 103 |
+
"heatmap": [
|
| 104 |
+
{"length": length, "position": position, "accuracy": _mean(value), "trials": len(value)}
|
| 105 |
+
for (length, position), value in sorted(cells.items())
|
| 106 |
+
],
|
| 107 |
+
"worst_cell_accuracy": min((statistics.fmean(value) for value in cells.values()), default=None),
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
variants = sorted({str(row.get("variant")) for row in rows})
|
| 111 |
+
parity: dict[str, Any] = {}
|
| 112 |
+
if len(variants) > 1:
|
| 113 |
+
baseline = variants[0]
|
| 114 |
+
baseline_rows = {row["case_id"]: row for row in rows if row.get("variant") == baseline}
|
| 115 |
+
for variant in variants[1:]:
|
| 116 |
+
paired = []
|
| 117 |
+
speed_ratios = []
|
| 118 |
+
for row in rows:
|
| 119 |
+
if row.get("variant") != variant or row["case_id"] not in baseline_rows:
|
| 120 |
+
continue
|
| 121 |
+
parent = baseline_rows[row["case_id"]]
|
| 122 |
+
paired.append(float(bool(row.get("passed"))) - float(bool(parent.get("passed"))))
|
| 123 |
+
parent_speed = parent.get("telemetry", {}).get("end_to_end_tokens_per_second")
|
| 124 |
+
candidate_speed = row.get("telemetry", {}).get("end_to_end_tokens_per_second")
|
| 125 |
+
if parent_speed and candidate_speed:
|
| 126 |
+
speed_ratios.append(float(candidate_speed) / float(parent_speed))
|
| 127 |
+
parity[variant] = {
|
| 128 |
+
"baseline": baseline,
|
| 129 |
+
"paired_quality_delta": _mean(paired),
|
| 130 |
+
"paired_quality_delta_95_ci": bootstrap_mean_ci(paired),
|
| 131 |
+
"mean_speed_ratio": _mean(speed_ratios),
|
| 132 |
+
"paired_cases": len(paired),
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
return {
|
| 136 |
+
"schema_version": "1.0",
|
| 137 |
+
"rows": len(rows),
|
| 138 |
+
"scorecards": scorecards,
|
| 139 |
+
"context": context,
|
| 140 |
+
"parity": parity,
|
| 141 |
+
"interpretation": {
|
| 142 |
+
"single_intelligence_score": None,
|
| 143 |
+
"note": "Quality, context, tools, vision, agentic reliability, and performance are reported separately.",
|
| 144 |
+
},
|
| 145 |
+
}
|
src/shiftedx_bench/tokenizer.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Any, Protocol
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TokenizerProtocol(Protocol):
|
| 9 |
+
def encode(self, text: str) -> list[int]: ...
|
| 10 |
+
def decode(self, token_ids: list[int]) -> str: ...
|
| 11 |
+
def render_chat(self, messages: list[dict[str, Any]]) -> str: ...
|
| 12 |
+
def token_offset(self, rendered_text: str, substring: str) -> int: ...
|
| 13 |
+
@property
|
| 14 |
+
def fingerprint(self) -> str: ...
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class TransformersTokenizer:
|
| 18 |
+
def __init__(
|
| 19 |
+
self,
|
| 20 |
+
model_path: str | Path,
|
| 21 |
+
*,
|
| 22 |
+
enable_thinking: bool = True,
|
| 23 |
+
reasoning_effort: str | None = "medium",
|
| 24 |
+
preserve_thinking: bool = True,
|
| 25 |
+
):
|
| 26 |
+
try:
|
| 27 |
+
from transformers import AutoTokenizer
|
| 28 |
+
except ImportError as exc:
|
| 29 |
+
raise RuntimeError(
|
| 30 |
+
"Install shiftedx-bench[tokenizers] to use a Transformers tokenizer"
|
| 31 |
+
) from exc
|
| 32 |
+
self.model_path = Path(model_path).expanduser().resolve()
|
| 33 |
+
self._tokenizer = AutoTokenizer.from_pretrained(
|
| 34 |
+
self.model_path, local_files_only=True, trust_remote_code=True
|
| 35 |
+
)
|
| 36 |
+
self.enable_thinking = enable_thinking
|
| 37 |
+
self.reasoning_effort = reasoning_effort
|
| 38 |
+
self.preserve_thinking = preserve_thinking
|
| 39 |
+
digest = hashlib.sha256()
|
| 40 |
+
for name in ("tokenizer.json", "tokenizer_config.json", "special_tokens_map.json"):
|
| 41 |
+
path = self.model_path / name
|
| 42 |
+
if path.exists():
|
| 43 |
+
digest.update(name.encode())
|
| 44 |
+
digest.update(path.read_bytes())
|
| 45 |
+
digest.update(
|
| 46 |
+
repr((self.enable_thinking, self.reasoning_effort, self.preserve_thinking)).encode()
|
| 47 |
+
)
|
| 48 |
+
self._fingerprint = digest.hexdigest()
|
| 49 |
+
|
| 50 |
+
def encode(self, text: str) -> list[int]:
|
| 51 |
+
return list(self._tokenizer.encode(text, add_special_tokens=False))
|
| 52 |
+
|
| 53 |
+
def decode(self, token_ids: list[int]) -> str:
|
| 54 |
+
return self._tokenizer.decode(
|
| 55 |
+
token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
def render_chat(self, messages: list[dict[str, Any]]) -> str:
|
| 59 |
+
kwargs: dict[str, Any] = {
|
| 60 |
+
"tokenize": False,
|
| 61 |
+
"add_generation_prompt": True,
|
| 62 |
+
"enable_thinking": self.enable_thinking,
|
| 63 |
+
"preserve_thinking": self.preserve_thinking,
|
| 64 |
+
}
|
| 65 |
+
if self.reasoning_effort:
|
| 66 |
+
kwargs["reasoning_effort"] = self.reasoning_effort
|
| 67 |
+
try:
|
| 68 |
+
value = self._tokenizer.apply_chat_template(messages, **kwargs)
|
| 69 |
+
except TypeError:
|
| 70 |
+
value = self._tokenizer.apply_chat_template(
|
| 71 |
+
messages, tokenize=False, add_generation_prompt=True
|
| 72 |
+
)
|
| 73 |
+
if not isinstance(value, str):
|
| 74 |
+
raise TypeError("Tokenizer chat template did not return text")
|
| 75 |
+
return value
|
| 76 |
+
|
| 77 |
+
def token_offset(self, rendered_text: str, substring: str) -> int:
|
| 78 |
+
char_offset = rendered_text.find(substring)
|
| 79 |
+
if char_offset < 0:
|
| 80 |
+
raise ValueError(f"Substring not present in rendered prompt: {substring!r}")
|
| 81 |
+
encoded = self._tokenizer(
|
| 82 |
+
rendered_text,
|
| 83 |
+
add_special_tokens=False,
|
| 84 |
+
return_offsets_mapping=True,
|
| 85 |
+
)
|
| 86 |
+
for index, (start, end) in enumerate(encoded["offset_mapping"]):
|
| 87 |
+
if start <= char_offset < end or start == char_offset:
|
| 88 |
+
return index
|
| 89 |
+
raise ValueError("Could not map substring to a token offset")
|
| 90 |
+
|
| 91 |
+
@property
|
| 92 |
+
def fingerprint(self) -> str:
|
| 93 |
+
return self._fingerprint
|
src/shiftedx_bench/tools.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import random
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
from .models import BenchCase
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def function_tool(name: str, properties: dict[str, Any], required: list[str]) -> dict[str, Any]:
|
| 10 |
+
return {
|
| 11 |
+
"type": "function",
|
| 12 |
+
"function": {
|
| 13 |
+
"name": name,
|
| 14 |
+
"description": f"Execute {name}.",
|
| 15 |
+
"parameters": {
|
| 16 |
+
"type": "object",
|
| 17 |
+
"properties": properties,
|
| 18 |
+
"required": required,
|
| 19 |
+
"additionalProperties": False,
|
| 20 |
+
},
|
| 21 |
+
},
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
SEARCH = function_tool("search_records", {"query": {"type": "string"}, "limit": {"type": "integer"}}, ["query", "limit"])
|
| 26 |
+
READ = function_tool("read_file", {"path": {"type": "string"}}, ["path"])
|
| 27 |
+
WEATHER = function_tool("weather", {"city": {"type": "string"}, "units": {"type": "string", "enum": ["c", "f"]}}, ["city", "units"])
|
| 28 |
+
DELETE = function_tool("delete_record", {"record_id": {"type": "string"}}, ["record_id"])
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _case(identifier: str, prompt: str, tools: list[dict[str, Any]], expected: list[dict[str, Any]]) -> BenchCase:
|
| 32 |
+
return BenchCase(
|
| 33 |
+
case_id=identifier,
|
| 34 |
+
suite_id="shiftedx-tools-v1",
|
| 35 |
+
lane="tools",
|
| 36 |
+
messages=[
|
| 37 |
+
{"role": "system", "content": "Use tools only when required. Never invent arguments."},
|
| 38 |
+
{"role": "user", "content": prompt},
|
| 39 |
+
],
|
| 40 |
+
scorer="tool_calls_exact",
|
| 41 |
+
expected=expected,
|
| 42 |
+
max_output_tokens=1024,
|
| 43 |
+
tools=tools,
|
| 44 |
+
metadata={"strict_protocol_scoring": True},
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def generate_tool_cases(seeds: list[int] | None = None) -> list[BenchCase]:
|
| 49 |
+
cases = []
|
| 50 |
+
for seed in seeds or [7319]:
|
| 51 |
+
rng = random.Random(seed)
|
| 52 |
+
service = rng.choice(["atlas", "beacon", "cinder", "delta"])
|
| 53 |
+
limit = rng.randrange(2, 7)
|
| 54 |
+
city = rng.choice(["Reykjavík", "Nairobi", "Osaka", "Quito"])
|
| 55 |
+
record_id = f"rec-{rng.randrange(1000, 9999)}"
|
| 56 |
+
paths = [f"/config/{service}.yaml", f"/config/{service}-worker.yaml"]
|
| 57 |
+
cases.extend([
|
| 58 |
+
_case(
|
| 59 |
+
f"single_exact__s{seed}",
|
| 60 |
+
f"Look up records matching 'staging {service}' and return at most {limit}.",
|
| 61 |
+
[SEARCH, READ],
|
| 62 |
+
[{"name": "search_records", "arguments": {"query": f"staging {service}", "limit": limit}}],
|
| 63 |
+
),
|
| 64 |
+
_case(
|
| 65 |
+
f"enum_exact__s{seed}",
|
| 66 |
+
f"Check the weather in {city} using Celsius.",
|
| 67 |
+
[WEATHER, SEARCH],
|
| 68 |
+
[{"name": "weather", "arguments": {"city": city, "units": "c"}}],
|
| 69 |
+
),
|
| 70 |
+
_case(
|
| 71 |
+
f"parallel_exact__s{seed}",
|
| 72 |
+
f"Read {paths[0]} and {paths[1]} in parallel.",
|
| 73 |
+
[READ],
|
| 74 |
+
[
|
| 75 |
+
{"name": "read_file", "arguments": {"path": paths[0]}},
|
| 76 |
+
{"name": "read_file", "arguments": {"path": paths[1]}},
|
| 77 |
+
],
|
| 78 |
+
),
|
| 79 |
+
_case(
|
| 80 |
+
f"irrelevant_no_call__s{seed}",
|
| 81 |
+
"Without using any tool, answer with the single word READY.",
|
| 82 |
+
[SEARCH, READ, WEATHER],
|
| 83 |
+
[],
|
| 84 |
+
),
|
| 85 |
+
_case(
|
| 86 |
+
f"destructive_requires_identifier__s{seed}",
|
| 87 |
+
f"Delete record {record_id}. Do not delete anything else.",
|
| 88 |
+
[DELETE, SEARCH],
|
| 89 |
+
[{"name": "delete_record", "arguments": {"record_id": record_id}}],
|
| 90 |
+
),
|
| 91 |
+
_case(
|
| 92 |
+
f"do_not_infer_destructive__s{seed}",
|
| 93 |
+
"The old record may need deleting, but I have not supplied its identifier. Explain what is missing.",
|
| 94 |
+
[DELETE, SEARCH],
|
| 95 |
+
[],
|
| 96 |
+
),
|
| 97 |
+
])
|
| 98 |
+
return cases
|
src/shiftedx_bench/util.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any, Iterable
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def canonical_json(value: Any) -> str:
|
| 10 |
+
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def sha256_json(value: Any) -> str:
|
| 14 |
+
return hashlib.sha256(canonical_json(value).encode("utf-8")).hexdigest()
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def sha256_file(path: Path) -> str:
|
| 18 |
+
digest = hashlib.sha256()
|
| 19 |
+
with path.open("rb") as stream:
|
| 20 |
+
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
| 21 |
+
digest.update(chunk)
|
| 22 |
+
return digest.hexdigest()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def read_json(path: Path) -> Any:
|
| 26 |
+
with path.open(encoding="utf-8") as stream:
|
| 27 |
+
return json.load(stream)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def write_json(path: Path, value: Any) -> None:
|
| 31 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 32 |
+
with path.open("w", encoding="utf-8") as stream:
|
| 33 |
+
json.dump(value, stream, ensure_ascii=False, indent=2, sort_keys=True)
|
| 34 |
+
stream.write("\n")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def append_jsonl(path: Path, values: Iterable[dict[str, Any]]) -> None:
|
| 38 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 39 |
+
with path.open("a", encoding="utf-8") as stream:
|
| 40 |
+
for value in values:
|
| 41 |
+
stream.write(canonical_json(value) + "\n")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def read_jsonl(path: Path) -> list[dict[str, Any]]:
|
| 45 |
+
if not path.exists():
|
| 46 |
+
return []
|
| 47 |
+
rows = []
|
| 48 |
+
with path.open(encoding="utf-8") as stream:
|
| 49 |
+
for line_number, line in enumerate(stream, start=1):
|
| 50 |
+
if not line.strip():
|
| 51 |
+
continue
|
| 52 |
+
try:
|
| 53 |
+
rows.append(json.loads(line))
|
| 54 |
+
except json.JSONDecodeError as exc:
|
| 55 |
+
raise ValueError(f"Invalid JSONL at {path}:{line_number}: {exc}") from exc
|
| 56 |
+
return rows
|
| 57 |
+
|
src/shiftedx_bench/vision.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import hashlib
|
| 5 |
+
import io
|
| 6 |
+
import random
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
from .models import BenchCase
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _png_data(image: Any) -> tuple[str, str, bytes]:
|
| 14 |
+
stream = io.BytesIO()
|
| 15 |
+
image.save(stream, format="PNG")
|
| 16 |
+
data = stream.getvalue()
|
| 17 |
+
digest = hashlib.sha256(data).hexdigest()
|
| 18 |
+
return "data:image/png;base64," + base64.b64encode(data).decode("ascii"), digest, data
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _message(prompt: str, images: list[str]) -> list[dict[str, Any]]:
|
| 22 |
+
content: list[dict[str, Any]] = [{"type": "text", "text": prompt}]
|
| 23 |
+
content.extend({"type": "image_url", "image_url": {"url": value}} for value in images)
|
| 24 |
+
return [
|
| 25 |
+
{"role": "system", "content": "Inspect every supplied image and return only bare JSON."},
|
| 26 |
+
{"role": "user", "content": content},
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def generate_vision_cases(output_dir: Path, seeds: list[int]) -> list[BenchCase]:
|
| 31 |
+
try:
|
| 32 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 33 |
+
except ImportError as exc:
|
| 34 |
+
raise RuntimeError("Install shiftedx-bench[vision] to generate vision fixtures") from exc
|
| 35 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 36 |
+
font = ImageFont.load_default(size=28)
|
| 37 |
+
cases = []
|
| 38 |
+
for seed in seeds:
|
| 39 |
+
rng = random.Random(seed)
|
| 40 |
+
code = f"SX-{rng.randrange(1000,9999)}-{rng.choice(['OPAL','RAVEN','CEDAR'])}"
|
| 41 |
+
image = Image.new("RGB", (900, 300), "#f5f1e8")
|
| 42 |
+
draw = ImageDraw.Draw(image)
|
| 43 |
+
draw.rectangle((40, 35, 860, 265), outline="#111111", width=5)
|
| 44 |
+
draw.text((90, 115), code, fill="#111111", font=font)
|
| 45 |
+
uri, digest, data = _png_data(image)
|
| 46 |
+
(output_dir / f"ocr-s{seed}.png").write_bytes(data)
|
| 47 |
+
cases.append(
|
| 48 |
+
BenchCase(
|
| 49 |
+
case_id=f"ocr__s{seed}", suite_id="shiftedx-vision-v1", lane="vision",
|
| 50 |
+
messages=_message("Read the boxed identifier. Return JSON with key identifier.", [uri]),
|
| 51 |
+
scorer="strict_json_exact", expected={"identifier": code}, max_output_tokens=1024,
|
| 52 |
+
metadata={"family": "ocr", "fixture_sha256": [digest]},
|
| 53 |
+
)
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
values = [rng.randrange(2, 10) for _ in range(4)]
|
| 57 |
+
labels = ["A", "B", "C", "D"]
|
| 58 |
+
chart = Image.new("RGB", (900, 550), "white")
|
| 59 |
+
draw = ImageDraw.Draw(chart)
|
| 60 |
+
colors = ["#e63946", "#457b9d", "#2a9d8f", "#f4a261"]
|
| 61 |
+
for index, (label, value) in enumerate(zip(labels, values)):
|
| 62 |
+
x0 = 100 + index * 190
|
| 63 |
+
draw.rectangle((x0, 470 - value * 38, x0 + 100, 470), fill=colors[index])
|
| 64 |
+
draw.text((x0 + 35, 480), label, fill="black", font=font)
|
| 65 |
+
draw.text((x0 + 35, 430 - value * 38), str(value), fill="black", font=font)
|
| 66 |
+
uri, digest, data = _png_data(chart)
|
| 67 |
+
(output_dir / f"chart-s{seed}.png").write_bytes(data)
|
| 68 |
+
maximum = max(values)
|
| 69 |
+
cases.append(
|
| 70 |
+
BenchCase(
|
| 71 |
+
case_id=f"chart__s{seed}", suite_id="shiftedx-vision-v1", lane="vision",
|
| 72 |
+
messages=_message("Return the label of the tallest bar and the sum of all four values.", [uri]),
|
| 73 |
+
scorer="strict_json_exact",
|
| 74 |
+
expected={"tallest": labels[values.index(maximum)], "sum": sum(values)}, max_output_tokens=1024,
|
| 75 |
+
metadata={"family": "chart", "fixture_sha256": [digest]},
|
| 76 |
+
)
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
spatial = Image.new("RGB", (900, 360), "#eeeeee")
|
| 80 |
+
draw = ImageDraw.Draw(spatial)
|
| 81 |
+
order = ["red", "green", "blue"]
|
| 82 |
+
rng.shuffle(order)
|
| 83 |
+
color_values = {"red": "#d62828", "green": "#2a9d4b", "blue": "#2463eb"}
|
| 84 |
+
for index, color in enumerate(order):
|
| 85 |
+
x = 170 + index * 280
|
| 86 |
+
draw.ellipse((x - 70, 110, x + 70, 250), fill=color_values[color])
|
| 87 |
+
uri, digest, data = _png_data(spatial)
|
| 88 |
+
(output_dir / f"spatial-s{seed}.png").write_bytes(data)
|
| 89 |
+
cases.append(
|
| 90 |
+
BenchCase(
|
| 91 |
+
case_id=f"spatial__s{seed}", suite_id="shiftedx-vision-v1", lane="vision",
|
| 92 |
+
messages=_message("List the circle colors from left to right as a JSON array.", [uri]),
|
| 93 |
+
scorer="strict_json_exact", expected=order, max_output_tokens=1024,
|
| 94 |
+
metadata={"family": "spatial", "fixture_sha256": [digest]},
|
| 95 |
+
)
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
before = Image.new("RGB", (500, 240), "white")
|
| 99 |
+
after = Image.new("RGB", (500, 240), "white")
|
| 100 |
+
for canvas, status in ((before, "PENDING"), (after, "COMPLETE")):
|
| 101 |
+
draw = ImageDraw.Draw(canvas)
|
| 102 |
+
draw.rectangle((30, 30, 470, 210), outline="black", width=4)
|
| 103 |
+
draw.text((90, 100), f"JOB {seed}: {status}", fill="black", font=font)
|
| 104 |
+
uri_a, digest_a, data_a = _png_data(before)
|
| 105 |
+
uri_b, digest_b, data_b = _png_data(after)
|
| 106 |
+
(output_dir / f"multi-before-s{seed}.png").write_bytes(data_a)
|
| 107 |
+
(output_dir / f"multi-after-s{seed}.png").write_bytes(data_b)
|
| 108 |
+
cases.append(
|
| 109 |
+
BenchCase(
|
| 110 |
+
case_id=f"multi_image__s{seed}", suite_id="shiftedx-vision-v1", lane="vision",
|
| 111 |
+
messages=_message("Compare image one with image two. Return job number and changed status.", [uri_a, uri_b]),
|
| 112 |
+
scorer="strict_json_exact", expected={"job": seed, "from": "PENDING", "to": "COMPLETE"},
|
| 113 |
+
max_output_tokens=1024,
|
| 114 |
+
metadata={"family": "multi-image", "fixture_sha256": [digest_a, digest_b]},
|
| 115 |
+
)
|
| 116 |
+
)
|
| 117 |
+
return cases
|
tests/conftest.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 8 |
+
sys.path.insert(0, str(ROOT / "src"))
|
| 9 |
+
|
tests/test_context.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
from shiftedx_bench.context import ContextSpec, build_context_case, expand_context_config
|
| 9 |
+
from shiftedx_bench.boundary import probe_context_boundary
|
| 10 |
+
from shiftedx_bench.holdout import derive_holdout_config
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class CharTokenizer:
|
| 14 |
+
fingerprint = "char-tokenizer-v1"
|
| 15 |
+
|
| 16 |
+
def encode(self, text: str) -> list[int]:
|
| 17 |
+
return [ord(value) for value in text]
|
| 18 |
+
|
| 19 |
+
def decode(self, token_ids: list[int]) -> str:
|
| 20 |
+
return "".join(chr(value) for value in token_ids)
|
| 21 |
+
|
| 22 |
+
def render_chat(self, messages):
|
| 23 |
+
return "".join(f"<{item['role']}>\n{item['content']}\n" for item in messages) + "<assistant>\n"
|
| 24 |
+
|
| 25 |
+
def token_offset(self, rendered_text: str, substring: str) -> int:
|
| 26 |
+
value = rendered_text.index(substring)
|
| 27 |
+
return len(self.encode(rendered_text[:value]))
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_smoke_plan_has_expected_coverage():
|
| 31 |
+
root = Path(__file__).resolve().parents[1]
|
| 32 |
+
config = json.loads((root / "configs/context-smoke-v1.json").read_text())
|
| 33 |
+
specs = expand_context_config(config)
|
| 34 |
+
assert len(specs) == 19
|
| 35 |
+
assert {spec.target_tokens for spec in specs} >= {4096, 32768, 131072, 260096}
|
| 36 |
+
assert {spec.query_placement for spec in specs} == {"before", "after"}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@pytest.mark.parametrize(
|
| 40 |
+
"family",
|
| 41 |
+
["single_key", "binding", "latest_record", "multi_hop", "semantic", "state_tracking"],
|
| 42 |
+
)
|
| 43 |
+
@pytest.mark.parametrize("position", [0.01, 0.5, 0.99])
|
| 44 |
+
def test_context_is_exact_and_positioned(family: str, position: float):
|
| 45 |
+
spec = ContextSpec("suite", "matrix", family, 12000, position, 173)
|
| 46 |
+
case = build_context_case(spec, CharTokenizer())
|
| 47 |
+
assert case.metadata["actual_rendered_tokens"] == 12000
|
| 48 |
+
assert abs(case.metadata["actual_primary_position"] - position) <= 0.003
|
| 49 |
+
assert set(case.expected) >= {"start_sentinel", "end_sentinel", "record"}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_rejects_duplicate_identifiers():
|
| 53 |
+
config = {
|
| 54 |
+
"suite_id": "x",
|
| 55 |
+
"matrices": [{
|
| 56 |
+
"name": "m", "families": ["single_key", "single_key"], "lengths": [4096],
|
| 57 |
+
"positions": [0.5], "seeds": [1]
|
| 58 |
+
}],
|
| 59 |
+
}
|
| 60 |
+
with pytest.raises(ValueError, match="duplicate"):
|
| 61 |
+
expand_context_config(config)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_holdout_derivation_is_stable_and_release_specific():
|
| 65 |
+
template = {
|
| 66 |
+
"suite_id": "x", "context_window": 8192, "reserved_output_tokens": 512,
|
| 67 |
+
"matrices": [{"name":"m","families":["single_key"],"lengths":[4096],"positions":[.5],"seeds":[1,2]}],
|
| 68 |
+
}
|
| 69 |
+
first = derive_holdout_config(template, "a sufficiently long private key", "r1")
|
| 70 |
+
second = derive_holdout_config(template, "a sufficiently long private key", "r1")
|
| 71 |
+
third = derive_holdout_config(template, "a sufficiently long private key", "r2")
|
| 72 |
+
assert first == second
|
| 73 |
+
assert first["matrices"][0]["seeds"] != third["matrices"][0]["seeds"]
|
| 74 |
+
assert "private key" not in str(first)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_rejects_prompt_beyond_reserved_output_budget():
|
| 78 |
+
config = {
|
| 79 |
+
"suite_id":"x", "context_window":4096, "reserved_output_tokens":512,
|
| 80 |
+
"matrices":[{"name":"m","families":["single_key"],"lengths":[3585],"positions":[.5],"seeds":[1]}],
|
| 81 |
+
}
|
| 82 |
+
with pytest.raises(ValueError, match="exceeds"):
|
| 83 |
+
expand_context_config(config)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_boundary_probe_requires_explicit_server_rejection():
|
| 87 |
+
class RejectingClient:
|
| 88 |
+
def complete(self, payload, stream=False):
|
| 89 |
+
raise RuntimeError("HTTP 400: context window exceeded")
|
| 90 |
+
|
| 91 |
+
result = probe_context_boundary(
|
| 92 |
+
client=RejectingClient(), tokenizer=CharTokenizer(), model="m",
|
| 93 |
+
context_window=4096, reserved_output_tokens=512,
|
| 94 |
+
)
|
| 95 |
+
assert result["passed"]
|
tests/test_quality_tools_vision.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from shiftedx_bench.quality import generate_quality_cases
|
| 4 |
+
from shiftedx_bench.scoring import score_response
|
| 5 |
+
from shiftedx_bench.tools import generate_tool_cases
|
| 6 |
+
from shiftedx_bench.vision import generate_vision_cases
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_quality_release_seed_produces_unique_cases():
|
| 10 |
+
cases = generate_quality_cases([173, 811])
|
| 11 |
+
assert len(cases) == 20
|
| 12 |
+
assert len({case.case_id for case in cases}) == 20
|
| 13 |
+
assert {case.scorer for case in cases} == {"strict_json_exact", "python_code"}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_every_tool_case_accepts_its_oracle_response():
|
| 17 |
+
for case in generate_tool_cases():
|
| 18 |
+
calls = [
|
| 19 |
+
{"function": {"name": item["name"], "arguments": item["arguments"]}}
|
| 20 |
+
for item in case.expected
|
| 21 |
+
]
|
| 22 |
+
assert score_response(case.scorer, case.expected, {"tool_calls": calls}).passed
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_tool_release_seeds_produce_unique_cases():
|
| 26 |
+
cases = generate_tool_cases([173, 811])
|
| 27 |
+
assert len(cases) == 12
|
| 28 |
+
assert len({case.case_id for case in cases}) == 12
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_vision_fixtures_are_deterministic(tmp_path):
|
| 32 |
+
first = generate_vision_cases(tmp_path / "a", [173])
|
| 33 |
+
second = generate_vision_cases(tmp_path / "b", [173])
|
| 34 |
+
assert len(first) == 4
|
| 35 |
+
assert [case.expected for case in first] == [case.expected for case in second]
|
| 36 |
+
assert [case.metadata["fixture_sha256"] for case in first] == [case.metadata["fixture_sha256"] for case in second]
|
tests/test_runner_summary_release.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
from shiftedx_bench.models import BenchCase
|
| 6 |
+
from shiftedx_bench.release import scan_public_tree
|
| 7 |
+
from shiftedx_bench.runner import run_cases
|
| 8 |
+
from shiftedx_bench.summary import summarize_results
|
| 9 |
+
from shiftedx_bench.util import read_jsonl
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class FakeClient:
|
| 13 |
+
def __init__(self, prompt_tokens=10): self.prompt_tokens = prompt_tokens
|
| 14 |
+
def complete(self, payload, stream=False):
|
| 15 |
+
return {
|
| 16 |
+
"content": '{"answer":7}', "reasoning_content": "", "tool_calls": [],
|
| 17 |
+
"finish_reason": "stop", "usage": {"prompt_tokens": self.prompt_tokens, "completion_tokens": 5},
|
| 18 |
+
"prompt_tokens": self.prompt_tokens, "completion_tokens": 5, "wall_s": 1.0,
|
| 19 |
+
"ttft_s": 0.2, "end_to_end_tokens_per_second": 5.0, "mtplx_stats": {},
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_runner_resumes_and_enforces_server_token_count(tmp_path):
|
| 24 |
+
case = BenchCase(
|
| 25 |
+
case_id="c", suite_id="s", lane="long-context", messages=[{"role":"user","content":"x"}],
|
| 26 |
+
scorer="strict_json_exact", expected={"answer": 7},
|
| 27 |
+
metadata={"target_prompt_tokens": 10, "requested_position": .5, "family": "single"},
|
| 28 |
+
)
|
| 29 |
+
output = tmp_path / "results.jsonl"
|
| 30 |
+
run_cases([case], client=FakeClient(), model="m", output_path=output)
|
| 31 |
+
run_cases([case], client=FakeClient(), model="m", output_path=output)
|
| 32 |
+
rows = read_jsonl(output)
|
| 33 |
+
assert len(rows) == 1 and rows[0]["passed"]
|
| 34 |
+
|
| 35 |
+
mismatch = tmp_path / "mismatch.jsonl"
|
| 36 |
+
run_cases([case], client=FakeClient(prompt_tokens=9), model="m", output_path=mismatch)
|
| 37 |
+
assert not read_jsonl(mismatch)[0]["passed"]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_summary_separates_scorecards_and_context():
|
| 41 |
+
rows = []
|
| 42 |
+
for length, passed in [(4096, True), (8192, True), (16384, False)]:
|
| 43 |
+
rows.append({
|
| 44 |
+
"variant":"ar", "lane":"long-context", "case_id":str(length), "passed":passed,
|
| 45 |
+
"metadata":{"target_prompt_tokens":length,"requested_position":.5,"family":"single"},
|
| 46 |
+
"telemetry":{"wall_s":1.0,"ttft_s":.1,"end_to_end_tokens_per_second":10.0},
|
| 47 |
+
})
|
| 48 |
+
summary = summarize_results(rows, effective_threshold=.9)
|
| 49 |
+
assert summary["context"]["ar"]["effective_context_length"] == 8192
|
| 50 |
+
assert summary["interpretation"]["single_intelligence_score"] is None
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def test_public_scan_detects_tokens_and_user_paths(tmp_path):
|
| 54 |
+
clean = tmp_path / "clean"
|
| 55 |
+
clean.mkdir()
|
| 56 |
+
(clean / "README.md").write_text("public documentation")
|
| 57 |
+
assert scan_public_tree(clean)["ok"]
|
| 58 |
+
fake_token = "h" + "f_" + "abcdefghijklmnopqrstuvwxyz1234"
|
| 59 |
+
fake_path = "/" + "Users/example/private"
|
| 60 |
+
(clean / "bad.txt").write_text(fake_token + "\n" + fake_path)
|
| 61 |
+
result = scan_public_tree(clean)
|
| 62 |
+
assert not result["ok"]
|
| 63 |
+
assert {item["issue"] for item in result["failures"]} >= {"Hugging Face access token", "macOS user path"}
|
tests/test_scoring_and_sandbox.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from shiftedx_bench.sandbox import run_python_submission
|
| 4 |
+
from shiftedx_bench.scoring import score_response
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_strict_json_rejects_fences_and_extra_text():
|
| 8 |
+
expected = {"value": 7}
|
| 9 |
+
assert score_response("strict_json_exact", expected, {"content": '{"value":7}'}).passed
|
| 10 |
+
assert not score_response("strict_json_exact", expected, {"content": '```json\n{"value":7}\n```'}).passed
|
| 11 |
+
assert not score_response("strict_json_exact", expected, {"content": '{"value":7} done'}).passed
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_tool_scoring_is_protocol_exact():
|
| 15 |
+
expected = [{"name": "read_file", "arguments": {"path": "/a"}}]
|
| 16 |
+
good = {"tool_calls": [{"function": {"name": "read_file", "arguments": '{"path":"/a"}'}}]}
|
| 17 |
+
bad = {"content": "I would call read_file on /a", "tool_calls": []}
|
| 18 |
+
assert score_response("tool_calls_exact", expected, good).passed
|
| 19 |
+
assert not score_response("tool_calls_exact", expected, bad).passed
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_python_sandbox_accepts_solution_and_rejects_imports():
|
| 23 |
+
outcome = run_python_submission("def add(a,b): return a+b", "assert add(2,3)==5")
|
| 24 |
+
assert outcome["passed"], outcome
|
| 25 |
+
rejected = run_python_submission("import os\ndef add(a,b): return a+b", "assert add(2,3)==5")
|
| 26 |
+
assert not rejected["passed"]
|
| 27 |
+
assert "static rejection" in rejected["error"]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_python_sandbox_catches_mutant():
|
| 31 |
+
outcome = run_python_submission("def add(a,b): return a-b", "assert add(2,3)==5")
|
| 32 |
+
assert not outcome["passed"]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_context_oracle_and_truncation_control():
|
| 36 |
+
expected = {"start_sentinel": "START", "record": "opal", "end_sentinel": "END"}
|
| 37 |
+
oracle = {"content": '{"start_sentinel":"START","record":"opal","end_sentinel":"END"}'}
|
| 38 |
+
truncated = {"content": '{"start_sentinel":"START","record":"opal"}'}
|
| 39 |
+
assert score_response("strict_json_exact", expected, oracle).passed
|
| 40 |
+
assert not score_response("strict_json_exact", expected, truncated).passed
|