Image Classification
Transformers
Safetensors
qwen3_5
feature-extraction
clef
bitsandbytes
quantized
8-bit precision
Run this model with HF Jobs
Run Aikimi/clef-flash-int8 on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/Aikimi/clef-flash-int8. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Aikimi/clef-flash-int8 on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use Aikimi/clef-flash-int8 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Aikimi/clef-flash-int8 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-classification", model="Aikimi/clef-flash-int8") pipe("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/parrots.png")# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModel processor = AutoProcessor.from_pretrained("Aikimi/clef-flash-int8") model = AutoModel.from_pretrained("Aikimi/clef-flash-int8", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Add files using upload-large-folder tool
Browse filesFiles changed (26)
- .gitattributes+1
- LICENSEAdded+202
- README.mdAdded+76
- chat_template.jinjaAdded+154
- clef_runtime/__init__.pyAdded+1
- clef_runtime/bundle.pyAdded+78
- clef_runtime/cache.pyAdded+39
- clef_runtime/core.pyAdded+339
- clef_runtime/runtime.pyAdded+203
- complete.jsonAdded+132
- config.jsonAdded+128
- inference.pyAdded+41
- joint_head.safetensorsAdded+3
- joint_head_config.jsonAdded+8
- joint_schema_model.pyAdded+576
- lm-head.safetensorsAdded+3
- model-00001-of-00005.safetensorsAdded+3
- model-00002-of-00005.safetensorsAdded+3
- model-00003-of-00005.safetensorsAdded+3
- model-00004-of-00005.safetensorsAdded+3
- model-00005-of-00005.safetensorsAdded+3
- model.safetensors.index.jsonAdded
- processor_config.jsonAdded+60
- requirements.txtAdded+8
- tokenizer.jsonAdded+3
- tokenizer_config.jsonAdded+30
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 Alibaba Cloud
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576---
license: apache-2.0
base_model: Cloudflare/clef-flash
base_model_relation: quantized
library_name: transformers
tags:
- clef
- bitsandbytes
- image-classification
- quantized
---
# Clef-Flash 9B INT8
Quantized from [Cloudflare/clef-flash](https://huggingface.co/Cloudflare/clef-flash/tree/17f0b0ad64efb65d273590632833508766b2aae6)
at `17f0b0ad64efb65d273590632833508766b2aae6`. The original model, schema encoder and joint head are
by Cloudflare. This derived release packages INT8 decoder weights with the
original BF16 vision encoder, joint head and dense input/output vocabulary.
It includes every inference asset; the original BF16 checkpoint is not required.
The output vocabulary is in `lm-head.safetensors` and indexed separately.
Clef performs a single forward pass over a schema of choice, score and noul
(boolean) questions. It does not generate free-form text. Probabilities are
distributions over the supplied alternatives, not calibrated accuracy estimates.
## Usage
Use Forge Neo's Clef setup and GUI, or this repository's standalone CLI:
```powershell
python -m pip install torch==2.13.0 torchvision==0.28.0 --index-url https://download.pytorch.org/whl/cu130
python -m pip install -r requirements.txt
python inference.py --profile flash-int8 --image example.png
python inference.py --profile flash-int8 --image example.png --questions questions.json
```
`questions.json` is the original Clef schema: each question ID maps to a `type`,
`instructions`, and, for choice/score, `criteria`. Use `--state` for context,
`--max-pixels` for image processing (default 262144), and `--max-length` for the
total input token cap (default 2048). Inputs exceeding the cap are refused.
An NVIDIA CUDA GPU with BF16 support is required. The standalone loader reads
weights locally and never downloads code during inference.
The 27B release is shared by `clef-24gb` and `clef-16gb`. The latter keeps the
input embedding on CPU. Both keep the dense output vocabulary on CPU and move
only requested rows to CUDA; decoder layers remain on CUDA. The 9B INT8 release
uses `flash-int8`. Packed lm_head replacement and whole-layer CPU offload are
not part of these profiles. The supplied loader is required for this placement.
## Validation and limits
Verified on Windows, RTX 3090 24GB, RAM 64GB, with Transformers 5.10.2,
bitsandbytes 0.50.2, safetensors 0.8.0 and PyTorch 2.13.0+cu130. We use SDPA,
batch=1, no KV cache, and safetensors `pread` to avoid persistent Windows
copy-on-write mappings of all shards.
Four images and a text-only request were checked with the same schemas.
27B 16GB and 24GB profiles produced identical answers and probabilities.
Peak image allocations were 13.38 GiB and 15.73 GiB respectively. The 16GB
profile passed with a 15 GiB PyTorch allocator budget on the 3090; an actual
16GB card was not available. The 9B INT8 peak was 9.82 GiB versus 16.26 GiB
for BF16, with no choice changes in those four images and a maximum probability
difference of 0.0423. This small comparison is not a general accuracy evaluation.
INT8 was slower than BF16 on this test; its benefit here is lower memory use.
Longer inputs or more image pixels require more memory.
## Provenance and license
Apache-2.0; see `LICENSE` and the upstream model card. The original
`joint_schema_model.py`, head, vocabulary values and processor assets are
retained. Decoder linear layers were converted with bitsandbytes and saved
using Transformers. Vision and the judgment head remain BF16. The included
`clef_runtime` and `inference.py` add CPU row gathering, profile selection,
input validation and Windows `pread` loading. `complete.json` records the
upstream commit, quantization settings, file sizes and SHA-256 hashes.
No user images, evaluation histories, local configuration or credentials are
included in this model release.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154{%- set image_count = namespace(value=0) %}{%- set video_count = namespace(value=0) %}{%- macro render_content(content, do_vision_count, is_system_content=false) %} {%- if content is string %} {{- content }} {%- elif content is iterable and content is not mapping %} {%- for item in content %} {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} {%- if is_system_content %} {{- raise_exception('System message cannot contain images.') }} {%- endif %} {%- if do_vision_count %} {%- set image_count.value = image_count.value + 1 %} {%- endif %} {%- if add_vision_id %} {{- 'Picture ' ~ image_count.value ~ ': ' }} {%- endif %} {{- '<|vision_start|><|image_pad|><|vision_end|>' }} {%- elif 'video' in item or item.type == 'video' %} {%- if is_system_content %} {{- raise_exception('System message cannot contain videos.') }} {%- endif %} {%- if do_vision_count %} {%- set video_count.value = video_count.value + 1 %} {%- endif %} {%- if add_vision_id %} {{- 'Video ' ~ video_count.value ~ ': ' }} {%- endif %} {{- '<|vision_start|><|video_pad|><|vision_end|>' }} {%- elif 'text' in item %} {{- item.text }} {%- else %} {{- raise_exception('Unexpected item type in content.') }} {%- endif %} {%- endfor %} {%- elif content is none or content is undefined %} {{- '' }} {%- else %} {{- raise_exception('Unexpected content type.') }} {%- endif %}{%- endmacro %}{%- if not messages %} {{- raise_exception('No messages provided.') }}{%- endif %}{%- if tools and tools is iterable and tools is not mapping %} {{- '<|im_start|>system\n' }} {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }} {%- for tool in tools %} {{- "\n" }} {{- tool | tojson }} {%- endfor %} {{- "\n</tools>" }} {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }} {%- if messages[0].role == 'system' %} {%- set content = render_content(messages[0].content, false, true)|trim %} {%- if content %} {{- '\n\n' + content }} {%- endif %} {%- endif %} {{- '<|im_end|>\n' }}{%- else %} {%- if messages[0].role == 'system' %} {%- set content = render_content(messages[0].content, false, true)|trim %} {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} {%- endif %}{%- endif %}{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}{%- for message in messages[::-1] %} {%- set index = (messages|length - 1) - loop.index0 %} {%- if ns.multi_step_tool and message.role == "user" %} {%- set content = render_content(message.content, false)|trim %} {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %} {%- set ns.multi_step_tool = false %} {%- set ns.last_query_index = index %} {%- endif %} {%- endif %}{%- endfor %}{%- if ns.multi_step_tool %} {{- raise_exception('No user query found in messages.') }}{%- endif %}{%- for message in messages %} {%- set content = render_content(message.content, true)|trim %} {%- if message.role == "system" %} {%- if not loop.first %} {{- raise_exception('System message must be at the beginning.') }} {%- endif %} {%- elif message.role == "user" %} {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} {%- elif message.role == "assistant" %} {%- set reasoning_content = '' %} {%- if message.reasoning_content is string %} {%- set reasoning_content = message.reasoning_content %} {%- else %} {%- if '</think>' in content %} {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %} {%- set content = content.split('</think>')[-1].lstrip('\n') %} {%- endif %} {%- endif %} {%- set reasoning_content = reasoning_content|trim %} {%- if loop.index0 > ns.last_query_index %} {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }} {%- else %} {{- '<|im_start|>' + message.role + '\n' + content }} {%- endif %} {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} {%- for tool_call in message.tool_calls %} {%- if tool_call.function is defined %} {%- set tool_call = tool_call.function %} {%- endif %} {%- if loop.first %} {%- if content|trim %} {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- else %} {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- endif %} {%- else %} {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- endif %} {%- if tool_call.arguments is defined %} {%- for args_name, args_value in tool_call.arguments|items %} {{- '<parameter=' + args_name + '>\n' }} {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} {{- args_value }} {{- '\n</parameter>\n' }} {%- endfor %} {%- endif %} {{- '</function>\n</tool_call>' }} {%- endfor %} {%- endif %} {{- '<|im_end|>\n' }} {%- elif message.role == "tool" %} {%- if loop.previtem and loop.previtem.role != "tool" %} {{- '<|im_start|>user' }} {%- endif %} {{- '\n<tool_response>\n' }} {{- content }} {{- '\n</tool_response>' }} {%- if not loop.last and loop.nextitem.role != "tool" %} {{- '<|im_end|>\n' }} {%- elif loop.last %} {{- '<|im_end|>\n' }} {%- endif %} {%- else %} {{- raise_exception('Unexpected message role.') }} {%- endif %}{%- endfor %}{%- if add_generation_prompt %} {{- '<|im_start|>assistant\n' }} {%- if enable_thinking is defined and enable_thinking is false %} {{- '<think>\n\n</think>\n\n' }} {%- else %} {{- '<think>\n' }} {%- endif %}{%- endif %}1"""Local Clef decision models and the shared Forge Studio interface."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""Validate complete, self-contained quantized releases without importing torch."""
from __future__ import annotations
import jsonfrom pathlib import Path
from .cache import cache_directory, identityfrom .core import PROFILES, ClefError, sha256, source_manifest
SUPPORT_FILES = ( "joint_head.safetensors", "joint_head_config.json", "joint_schema_model.py", "tokenizer.json", "tokenizer_config.json", "processor_config.json", "chat_template.jinja", "LICENSE",)PORTABLE_MODULES = ("__init__.py", "core.py", "cache.py", "bundle.py", "runtime.py")REQUIRED_FILES = { *SUPPORT_FILES, "config.json", "model.safetensors.index.json", "lm-head.safetensors", "README.md", "inference.py", "requirements.txt", *("clef_runtime/" + name for name in PORTABLE_MODULES),}
def bundle_directory(root, profile): converted = cache_directory(root, profile) return converted.with_name(converted.name + "-bundle") if converted is not None else None
def read_bundle(directory, profile, *, verify_hashes=False): directory = Path(directory) try: manifest = json.loads((directory / "complete.json").read_text(encoding="utf-8")) expected = {**identity(profile), "bundle_format": 1} if any(manifest.get(key) != value for key, value in expected.items()): raise ClefError("Clef量子化配布の版・精度が一致しません。セットアップを再実行してください。") files = manifest["files"] names = {item["path"] for item in files} if not REQUIRED_FILES <= names or len(names) != len(files): raise ClefError("Clef量子化配布の構成が不足しています。セットアップを再実行してください。") for item in files: path = directory / item["path"] if ( not path.resolve().is_relative_to(directory.resolve()) or not path.is_file() or path.stat().st_size != item["size"] ): raise ClefError(f"Clef量子化配布が不足・変更されています: {item['path']}") if (verify_hashes or path.suffix == ".py") and sha256(path) != item["sha256"]: raise ClefError(f"ClefのSHA-256が一致しません: {item['path']}") index = json.loads((directory / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"] if ( index.get("lm_head.weight") != "lm-head.safetensors" or "language_model.embed_tokens.weight" not in index or not set(index.values()) <= names ): raise ClefError("Clef量子化配布の語彙・本体の構成が一致しません。") return directory, manifest except ClefError: raise except (OSError, ValueError, KeyError, TypeError) as exc: raise ClefError("Clef量子化モデル未導入です。aikimi-clef-setup.batを実行してください。") from exc
def bundle_manifest(root, profile, *, verify_hashes=False): directory = bundle_directory(root, profile) if directory is None: return source_manifest(root, PROFILES[profile]["model"], verify_hashes=verify_hashes) return read_bundle(directory, profile, verify_hashes=verify_hashes)123456789101112131415161718192021222324252627282930313233343536373839"""Storage location and fixed conversion provenance shared by release tools."""
from __future__ import annotations
import jsonfrom pathlib import Path
from .core import MODELS, PROFILES
def cache_directory(root, profile): settings = PROFILES[profile] if settings["precision"] == "bf16": return None root = Path(root) try: storage = json.loads((root / "storage.json").read_text(encoding="utf-8")) except FileNotFoundError: base = root / "quantized" except (OSError, ValueError) as exc: raise ValueError("Clefのstorage.jsonを読み込めません。--cache-dirで保存先を設定し直してください。") from exc else: destination = storage.get("quantized") if isinstance(storage, dict) else None if not isinstance(destination, str) or not Path(destination).is_absolute(): raise ValueError("Clefの量子化キャッシュ保存先は絶対パスで指定してください。") base = Path(destination) return base / f"{settings['model']}-{settings['precision']}"
def identity(profile): settings = PROFILES[profile] return { **MODELS[settings["model"]], "precision": settings["precision"], "format": 1, "transformers": "5.10.2", "bitsandbytes": "0.50.2", "vision": "bf16", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339"""Small, torch-free contracts for images, schemas and immutable decision runs."""
from __future__ import annotations
import copyimport csvimport hashlibimport ioimport jsonimport mathimport osfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[2]RUNTIME = ROOT / "models" / "Clef"OUTPUTS = ROOT / "outputs" / "clef"MODELS = { "clef-flash": {"repo": "Cloudflare/clef-flash", "revision": "17f0b0ad64efb65d273590632833508766b2aae6"}, "clef": {"repo": "Cloudflare/clef", "revision": "2f3de3dd85f379784083b0814d997ab627200f0c"},}PROFILES = { "flash-int8": { "label": "Flash INT8 · 軽量", "model": "clef-flash", "precision": "int8", "cpu_embeddings": False, "min_vram_gib": 12, }, "clef-24gb": { "label": "Clef NF4 · 24GB", "model": "clef", "precision": "nf4", "cpu_embeddings": False, "min_vram_gib": 20, }, "clef-16gb": { "label": "Clef NF4 · 16GB", "model": "clef", "precision": "nf4", "cpu_embeddings": True, "min_vram_gib": 14, }, "flash-bf16": { "label": "Flash BF16 · 比較用", "model": "clef-flash", "precision": "bf16", "cpu_embeddings": False, "min_vram_gib": 20, },}TEMPLATES = { "画像の評価": { "style": { "type": "choice", "instructions": "画像の主な表現形式を分類してください。", "criteria": { "photo": "写真または写実的な画像", "illustration": "イラスト・アニメ・絵画", "design": "図・ポスター・グラフィックデザイン", }, }, "quality": { "type": "score", "instructions": "画像の見た目の完成度を評価してください。", "criteria": [ "大きな破綻や欠落がある", "目立つ問題があり修正が必要", "おおむね整っている", "細部まで整い完成度が高い", ], }, "text": {"type": "noul", "instructions": "画像に読める文字が含まれている。"}, }, "生成画像の確認": { "artifact": {"type": "noul", "instructions": "画像に不自然な形、重複、形状の破綻が見られる。"}, "composition": { "type": "score", "instructions": "構図の明瞭さと主題の伝わりやすさを評価してください。", "criteria": ["主題が不明瞭", "主題は分かるが構図に問題がある", "主題が明瞭で構図が整っている"], }, }, "文章・JSONの分類": { "department": { "type": "choice", "instructions": "問い合わせを担当するチームはどれですか。", "criteria": {"billing": "請求や支払い", "technical": "技術的な問題や障害", "other": "その他"}, }, "outage": {"type": "noul", "instructions": "サービスが停止している。"}, },}
class ClefError(ValueError): """An input or installation problem to show directly in the Studio."""
def atomic_json(path, data): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + ".tmp") temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2, allow_nan=False), encoding="utf-8") os.replace(temporary, path)
def sha256(path): digest = hashlib.sha256() with Path(path).open("rb") as stream: for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): digest.update(chunk) return digest.hexdigest()
def canonical_hash(value): return hashlib.sha256( json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() ).hexdigest()
def _unique(pairs): result = {} for key, value in pairs: if key in result: raise ClefError(f"IDが重複しています: {key}") result[key] = value return result
def parse_schema(value): if isinstance(value, str): if len(value) > 100_000: raise ClefError("判断項目のJSONは100,000文字以内にしてください。") try: value = json.loads(value, object_pairs_hook=_unique) except json.JSONDecodeError as exc: raise ClefError(f"JSONの{exc.lineno}行目・{exc.colno}文字目を確認してください。") from exc if not isinstance(value, dict) or not 1 <= len(value) <= 32: raise ClefError("判断項目は1〜32件のオブジェクトにしてください。") for qid, question in value.items(): if not isinstance(qid, str) or not qid.strip() or len(qid) > 80: raise ClefError("項目IDは1〜80文字にしてください���") if not isinstance(question, dict) or question.get("type") not in {"choice", "score", "noul"}: raise ClefError(f"{qid}: 種類はchoice / score / noulを指定してください。") if set(question) - {"type", "instructions", "criteria"}: raise ClefError(f"{qid}: 未対応の設定があります。") if not isinstance(question.get("instructions", ""), str): raise ClefError(f"{qid}: 判断することは文章で指定してください。") criteria, kind = question.get("criteria"), question["type"] if kind == "choice": if not isinstance(criteria, dict) or not 2 <= len(criteria) <= 64: raise ClefError(f"{qid}: 選択肢はIDと説明の組を2〜64件指定してください。") if any( not isinstance(k, str) or not k.strip() or not isinstance(v, str) or not v.strip() for k, v in criteria.items() ): raise ClefError(f"{qid}: 選択肢のIDと説明を入力してください。") elif kind == "score": if ( not isinstance(criteria, list) or not 2 <= len(criteria) <= 32 or any(not isinstance(x, str) or not x.strip() for x in criteria) ): raise ClefError(f"{qid}: 段階の説明を低い順に2〜32件指定してください。") elif criteria is not None and ( not isinstance(criteria, dict) or set(criteria) - {"true", "false"} or any(not isinstance(x, str) for x in criteria.values()) ): raise ClefError(f"{qid}: 真偽の説明はtrue / falseで指定してください。") return copy.deepcopy(value)
def edit_question(schema, previous, qid, kind, instructions, options): result = copy.deepcopy(schema) qid = (qid or "").strip() if qid in result and qid != previous: raise ClefError(f"IDが重複しています: {qid}") question = {"type": kind, "instructions": (instructions or "").strip()} lines = [x.strip() for x in (options or "").splitlines() if x.strip()] if kind == "choice": pairs = [] for line in lines: if ":" not in line: raise ClefError("選択肢は1行に「ID: 説明」の形で指定してください。") key, description = line.split(":", 1) pairs.append((key.strip(), description.strip())) question["criteria"] = _unique(pairs) elif kind == "score": question["criteria"] = lines if previous and previous != qid: result.pop(previous, None) result[qid] = question return parse_schema(result)
def integer(value, label, lower, upper): try: number = int(value) if ( isinstance(value, bool) or not math.isfinite(float(value)) or float(value) != number or not lower <= number <= upper ): raise ValueError return number except (ValueError, TypeError, OverflowError) as exc: raise ClefError(f"{label}は{lower}〜{upper}の整数にしてください。") from exc
def validate_request(request): profile = request.get("profile") if profile not in PROFILES: raise ClefError("実行プロファイルを選んでください。") schema = parse_schema(request.get("questions")) state = request.get("state", "") if not isinstance(state, (str, dict, list, int, float, bool, type(None))): raise ClefError("補足入力は文章またはJSONにしてください。") if len(json.dumps(state, ensure_ascii=False)) > 60_000: raise ClefError("補足入力は60,000文字以内にしてください。") return { "profile": profile, "questions": schema, "state": state, "max_pixels": integer(request.get("max_pixels", 262144), "画像の最大画素数", 65536, 1048576), "max_length": integer(request.get("max_length", 4096), "入力トークン上限", 512, 8192), }
def fingerprint(request, items): profile = PROFILES[request["profile"]] return canonical_hash( { "request": request, "model": MODELS[profile["model"]], "profile": profile, "images": [item["sha256"] for item in items], "preprocessing": "exif-rgb-v1", } )
def summary(answer, question): kind = answer["type"] if kind == "noul": return f"P(真) {answer['noul']:.3f}" if kind == "choice": choice = answer["choice"] return f"{choice} · p={answer['confidence']:.3f}" return f"期待値 {answer['score']:.2f} (0–{len(question['criteria']) - 1})"
def ambiguity(answer): if answer["type"] == "noul": return 1 - 2 * abs(answer["noul"] - 0.5) probabilities = list(answer["probabilities"].values()) return -sum(p * math.log(p) for p in probabilities if p > 0) / math.log(len(probabilities))
def compare_runs(left, right): for key in ("questions", "state", "max_pixels"): if canonical_hash(left["request"].get(key)) != canonical_hash(right["request"].get(key)): raise ClefError("比較には判断項目・補足入力・処理解像度の一致が必要です。") other = {x["sha256"]: x for x in right["items"] if x["status"] == "done"} rows = [] for item in left["items"]: if item["status"] != "done" or item["sha256"] not in other: continue differences = {} for qid, answer in item["answers"].items(): target = other[item["sha256"]]["answers"][qid] if answer["type"] == "noul": delta = target["noul"] - answer["noul"] differences[qid] = { "delta": delta, "changed": (answer["noul"] >= 0.5) != (target["noul"] >= 0.5), "max_probability_delta": abs(delta), } else: delta = max(abs(p - target["probabilities"][key]) for key, p in answer["probabilities"].items()) changed = ( answer.get("choice") != target.get("choice") if answer["type"] == "choice" else max(answer["probabilities"], key=answer["probabilities"].get) != max(target["probabilities"], key=target["probabilities"].get) ) differences[qid] = {"changed": changed, "max_probability_delta": delta} if answer["type"] == "score": differences[qid]["delta"] = target["score"] - answer["score"] rows.append( { "name": item["name"], "sha256": item["sha256"], "differences": differences, "changed": any(x["changed"] for x in differences.values()), "max_probability_delta": max(x["max_probability_delta"] for x in differences.values()), } ) return sorted(rows, key=lambda x: x["max_probability_delta"], reverse=True)
def export_csv(run): schema = run["request"]["questions"] columns = ["name", "sha256", "status", "error"] + [ col for qid in schema for col in ("answer:" + qid, "confidence:" + qid) ] stream = io.StringIO(newline="") writer = csv.DictWriter(stream, fieldnames=columns) writer.writeheader() for item in run["items"]: row = {key: item.get(key, "") for key in columns[:4]} for qid, answer in item.get("answers", {}).items(): row["answer:" + qid] = answer.get("choice", answer.get("score", answer.get("noul", ""))) row["confidence:" + qid] = answer.get("confidence", "") for key, value in row.items(): if isinstance(value, str) and value.lstrip().startswith(("=", "+", "-", "@")): row[key] = "'" + value writer.writerow(row) return stream.getvalue()
def source_manifest(root, model, verify_hashes=False): directory = Path(root) / "source" / model try: manifest = json.loads((directory / "release.json").read_text(encoding="utf-8")) except (OSError, ValueError) as exc: raise ClefError(f"{model}のBF16元重みは未導入です。aikimi-clef-setup.bat --source --model {model}を実行してください。") from exc if manifest.get("revision") != MODELS[model]["revision"] or manifest.get("repo") != MODELS[model]["repo"]: raise ClefError("Clefの固定リビジョンが一致しません。セットアップを再実行してください。") for item in manifest["files"]: path = directory / item["path"] if ( not path.resolve().is_relative_to(directory.resolve()) or not path.is_file() or path.stat().st_size != item["size"] ): raise ClefError(f"Clef配布物が不足・変更されています: {item['path']}") if (verify_hashes or path.suffix == ".py") and sha256(path) != item["sha256"]: raise ClefError(f"ClefのSHA-256が一致しません: {item['path']}") return directory, manifest123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203"""Keep the official joint head while moving only vocabulary rows over PCIe."""
from __future__ import annotations
import gcimport importlib.utilimport jsonimport sysfrom contextlib import contextmanagerfrom functools import partial
import torch
from .bundle import bundle_manifest, read_bundlefrom .core import PROFILES
class LexicalRows: def __init__(self, weight, *, device, dtype): if weight.device.type != "cpu" or weight.is_meta: raise ValueError("語彙行列には実体のあるCPUテンソルが必要です。") self.weight, self.device, self.dtype = weight, device, dtype
def __getitem__(self, token_ids): shape = (*token_ids.shape, self.weight.shape[1]) return self.weight.index_select(0, token_ids.reshape(-1).cpu()).reshape(shape).to(self.device, dtype=self.dtype)
class CPUEmbedding(torch.nn.Module): def __init__(self, weight, *, device, dtype): super().__init__() self.rows = LexicalRows(weight, device=device, dtype=dtype) self.weight = torch.nn.Parameter(weight, requires_grad=False)
def forward(self, tokens): return self.rows[tokens]
def load_options(profile): settings = PROFILES[profile] result = {"device_map": {"": 0}} if settings["cpu_embeddings"]: result["device_map"] = { "visual": 0, "language_model.embed_tokens": "cpu", "language_model.layers": 0, "language_model.norm": 0, "language_model.rotary_emb": 0, } if settings["precision"] != "bf16": quantization = { "llm_int8_skip_modules": ["visual", "lm_head"], "llm_int8_enable_fp32_cpu_offload": settings["cpu_embeddings"], } if settings["precision"] == "int8": quantization["load_in_8bit"] = True else: quantization.update( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16, ) result["quantization"] = quantization return result
def encode_complete(official, processor, record, max_length): # The release silently truncates state. Encode once without truncation and # refuse overflow before collating or allocating decoder activations. encoded = official.encode_record(processor.tokenizer, record, processor=processor, max_length=1_000_000) if len(encoded.input_ids) > max_length: raise ValueError( f"入力は{len(encoded.input_ids)}トークンです。上限{max_length}を超えます。補足や項目を短くするか処理解像度を下げてください。" ) return encoded
def tensor_from_source(source, key): from safetensors import safe_open
index = json.loads((source / "model.safetensors.index.json").read_text()) with safe_open(source / index["weight_map"][key], framework="pt", device="cpu", backend="pread") as stream: return stream.get_tensor(key)
@contextmanagerdef stream_weights(): import transformers.modeling_utils as loading
# Windows reserves commit for every copy-on-write mmap, including unread # pages. Keep TF's lazy tensor loading without retaining all shard maps. original = loading.safe_open loading.safe_open = partial(original, backend="pread") try: yield finally: loading.safe_open = original
class Runner: @classmethod def from_directory(cls, directory, profile): return cls(None, profile, directory=directory)
def __init__(self, root, profile, *, directory=None): from safetensors.torch import load_file from transformers import AutoProcessor, BitsAndBytesConfig, Qwen3_5Model
if not torch.cuda.is_available() or not torch.cuda.is_bf16_supported(): raise RuntimeError("ClefにはBF16対応のNVIDIA CUDA GPUが必要です。") self.settings, self.profile = PROFILES[profile], profile total = torch.cuda.get_device_properties(0).total_memory / 2**30 if total < self.settings["min_vram_gib"]: raise RuntimeError( f"{self.settings['label']}のGPUメモリが不足しています。16GB設定またはFlashを選んでください。" ) source, _ = read_bundle(directory, profile) if directory is not None else bundle_manifest(root, profile) spec = importlib.util.spec_from_file_location( "clef_release_" + self.settings["model"].replace("-", "_"), source / "joint_schema_model.py" ) self.official = importlib.util.module_from_spec(spec) sys.modules[spec.name] = self.official spec.loader.exec_module(self.official) options = load_options(profile) saved = source if self.settings["precision"] != "bf16" else None if "quantization" in options: options["quantization_config"] = BitsAndBytesConfig(**options.pop("quantization")) print(f"{self.settings['label']}: {'保存済み' if saved else '公式重み'}を読み込み中", flush=True) # noqa: T201 with stream_weights(): self.backbone, loading = Qwen3_5Model.from_pretrained( saved or source, dtype=torch.bfloat16, local_files_only=True, attn_implementation="sdpa", output_loading_info=True, **options, ) expected_extra = {"lm_head.weight"} if loading["missing_keys"] or set(loading["unexpected_keys"]) != expected_extra: raise RuntimeError(f"Clef本体のキーが一致しません: {loading}") self.backbone.eval() self.backbone.config.use_cache = False if self.settings["cpu_embeddings"]: # Read the bundle's BF16 rows directly; CPU offload may cast to FP32. # Discard the old embedding together with its hook. Detaching a # hook can temporarily restore the entire vocabulary onto CUDA. embedding = tensor_from_source(source, "language_model.embed_tokens.weight") self.backbone.language_model.embed_tokens = CPUEmbedding(embedding, device="cuda:0", dtype=torch.bfloat16) gc.collect() self.lexical = LexicalRows(tensor_from_source(source, "lm_head.weight"), device="cuda:0", dtype=torch.bfloat16) self.head = self.official.JointSchemaHead(**json.loads((source / "joint_head_config.json").read_text())) self.head.load_state_dict(load_file(source / "joint_head.safetensors", backend="pread"), strict=True) self.head = self.head.to(device="cuda:0", dtype=torch.bfloat16).eval() self.processor = AutoProcessor.from_pretrained(source, local_files_only=True) self.source = source self.root, self.saved = root, saved
@torch.inference_mode() def decide(self, request, image=None): record = { "model": self.settings["model"], "state": request["state"], "questions": request["questions"], "media_kwargs": {"max_pixels": request["max_pixels"]}, } if image is not None: record["images"] = [image] encoded = encode_complete(self.official, self.processor, record, request["max_length"]) batch = self.official.collate_records([encoded], self.processor.tokenizer.pad_token_id, torch.device("cuda:0")) torch.cuda.reset_peak_memory_stats() media = batch.get("media") or {} model = self.backbone if media else self.backbone.language_model outputs = model( input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], use_cache=False, return_dict=True, **media, ) logits = self.head( outputs.last_hidden_state, batch["input_ids"], batch["attention_mask"], batch["records"], self.lexical )[0] answers = { q.question_id: self.official.systemone_answer( request["questions"][q.question_id], dict(zip(q.option_ids, logit.float().softmax(-1).tolist(), strict=True)), ) for q, logit in zip(encoded.questions, logits, strict=True) } torch.cuda.synchronize() return { "model": self.settings["model"], "answers": answers, "usage": {"input_tokens": len(encoded.input_ids), "output_tokens": 0}, "peak_allocated_gib": torch.cuda.max_memory_allocated() / 2**30, "peak_reserved_gib": torch.cuda.max_memory_reserved() / 2**30, }
def close(self): self.backbone = self.head = self.lexical = self.processor = None gc.collect() torch.cuda.empty_cache()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132{
"repo": "Cloudflare/clef-flash",
"revision": "17f0b0ad64efb65d273590632833508766b2aae6",
"precision": "int8",
"format": 1,
"transformers": "5.10.2",
"bitsandbytes": "0.50.2",
"vision": "bf16",
"bundle_format": 1,
"files": [
{
"path": "LICENSE",
"size": 11544,
"sha256": "bbedc3fda3305820b977265f01b8619d87570a6739de3a5582c3464840f1e57a"
},
{
"path": "README.md",
"size": 3913,
"sha256": "8c2553f158a27717a0e5128bebdb576b3e81fa089b821bc79d71a3cfde77a256"
},
{
"path": "chat_template.jinja",
"size": 7756,
"sha256": "a4aee8afcf2e0711942cf848899be66016f8d14a889ff9ede07bca099c28f715"
},
{
"path": "clef_runtime/__init__.py",
"size": 72,
"sha256": "8252a7c5618dd1324b6c4c307a0c7d574712eb5481d3e129947b99dba14775ca"
},
{
"path": "clef_runtime/bundle.py",
"size": 3307,
"sha256": "4abd7c664fbf94e7217b4554657a5ba5ea6e1fea633a43455b2c213cb9b09ba2"
},
{
"path": "clef_runtime/cache.py",
"size": 1351,
"sha256": "431f466374141ab80af41d4cc0ddca93dfc9fc74a28de8de792f5be690eed1cb"
},
{
"path": "clef_runtime/core.py",
"size": 14153,
"sha256": "15edc6a89e4a011a308bc283ac182c793c7c72227dbe06788d4f9888e377ab36"
},
{
"path": "clef_runtime/runtime.py",
"size": 8826,
"sha256": "69df25f5118190fe066199225f0c9c2b25f10b93e1e550ff50890252aafa02b6"
},
{
"path": "config.json",
"size": 3479,
"sha256": "ff6de63fbfcd26ce6d0fed3c40039ddcf2c6833c6f07a189473ec2eeb59ac884"
},
{
"path": "inference.py",
"size": 1521,
"sha256": "9667ef47476bd4e8dddaa66d7d02f45733d542e815629ebb30ec5fc7639fb135"
},
{
"path": "joint_head.safetensors",
"size": 243538016,
"sha256": "19cdcec8c81dc9212be320fff47462ab342fbc1278be4368fb3da71241cf5ba0"
},
{
"path": "joint_head_config.json",
"size": 119,
"sha256": "77efe959a38b5b17b241543e129e695f3c77465ece55a25985279bd8176279a0"
},
{
"path": "joint_schema_model.py",
"size": 23263,
"sha256": "0e304cf7c6500e8bb59bef7e2afd2c6373f82596dfb3b57d1aa93c175e2dc3a3"
},
{
"path": "lm-head.safetensors",
"size": 2034237568,
"sha256": "dd63614f1dc80dce2d83be3f3e69af1f8a0ebc8add9b8e0abf3910f563e44344"
},
{
"path": "model-00001-of-00005.safetensors",
"size": 2034237592,
"sha256": "9c5483aa32a952b3a9a5d75f3c000c9ff934d3cbbb317b228cadff89e25bcffa"
},
{
"path": "model-00002-of-00005.safetensors",
"size": 1984182833,
"sha256": "6999510bfc3c9ea6536090fb76b70bb786a0f4bd76f290ea35f35f58aa77e4f6"
},
{
"path": "model-00003-of-00005.safetensors",
"size": 1983829880,
"sha256": "efa24fbcede25d84116de286e544554513bd0400c40c66b99c32e846f5096cdd"
},
{
"path": "model-00004-of-00005.safetensors",
"size": 1983498867,
"sha256": "7a5dd174473310a090c74abe907de00da6b85c46f8a3b5bcaec20267449fbdbd"
},
{
"path": "model-00005-of-00005.safetensors",
"size": 1886989356,
"sha256": "1463c85bac6efd374bb5189d3beda19df628a786a9068b00de74dd3504f12df9"
},
{
"path": "model.safetensors.index.json",
"size": 112960,
"sha256": "493691fe586b33a34830abaf788dc940ec43fcf4913139c9ed5dd1ba069542e3"
},
{
"path": "processor_config.json",
"size": 1191,
"sha256": "d89ef49ce9cd37fbf510158e13c1ef063d9286411c1ec9049932dbe0487143b1"
},
{
"path": "requirements.txt",
"size": 194,
"sha256": "6ea662f95ec818e7f7a17742211ba0e6de4744ac61055565f01214e8a818588a"
},
{
"path": "tokenizer.json",
"size": 19989325,
"sha256": "06b9509352d2af50381ab2247e083b80d32d5c0aba91c272ca9ff729b6a0e523"
},
{
"path": "tokenizer_config.json",
"size": 1075,
"sha256": "91a08f825d370d085d692e04cf117cdd7faad7bf18e996f1e6031b6dab03db72"
}
]
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128{
"architectures": [
"Qwen3_5Model"
],
"dtype": "bfloat16",
"image_token_id": 248056,
"model_type": "qwen3_5",
"quantization_config": {
"_load_in_4bit": false,
"_load_in_8bit": true,
"bnb_4bit_compute_dtype": "float32",
"bnb_4bit_quant_storage": "uint8",
"bnb_4bit_quant_type": "fp4",
"bnb_4bit_use_double_quant": false,
"llm_int8_enable_fp32_cpu_offload": false,
"llm_int8_has_fp16_weight": false,
"llm_int8_skip_modules": [
"visual",
"lm_head"
],
"llm_int8_threshold": 6.0,
"load_in_4bit": false,
"load_in_8bit": true,
"quant_method": "bitsandbytes"
},
"text_config": {
"attention_bias": false,
"attention_dropout": 0.0,
"attn_output_gate": true,
"bos_token_id": null,
"dtype": "bfloat16",
"eos_token_id": 248044,
"full_attention_interval": 4,
"head_dim": 256,
"hidden_act": "silu",
"hidden_size": 4096,
"initializer_range": 0.02,
"intermediate_size": 12288,
"layer_types": [
"linear_attention",
"linear_attention",
"linear_attention",
"full_attention",
"linear_attention",
"linear_attention",
"linear_attention",
"full_attention",
"linear_attention",
"linear_attention",
"linear_attention",
"full_attention",
"linear_attention",
"linear_attention",
"linear_attention",
"full_attention",
"linear_attention",
"linear_attention",
"linear_attention",
"full_attention",
"linear_attention",
"linear_attention",
"linear_attention",
"full_attention",
"linear_attention",
"linear_attention",
"linear_attention",
"full_attention",
"linear_attention",
"linear_attention",
"linear_attention",
"full_attention"
],
"linear_conv_kernel_dim": 4,
"linear_key_head_dim": 128,
"linear_num_key_heads": 16,
"linear_num_value_heads": 32,
"linear_value_head_dim": 128,
"mamba_ssm_dtype": "float32",
"max_position_embeddings": 262144,
"mlp_only_layers": [],
"model_type": "qwen3_5_text",
"mtp_num_hidden_layers": 0,
"mtp_use_dedicated_embeddings": false,
"num_attention_heads": 16,
"num_hidden_layers": 32,
"num_key_value_heads": 4,
"pad_token_id": null,
"partial_rotary_factor": 0.25,
"rms_norm_eps": 1e-06,
"rope_parameters": {
"mrope_interleaved": true,
"mrope_section": [
11,
11,
10
],
"partial_rotary_factor": 0.25,
"rope_theta": 10000000,
"rope_type": "default"
},
"tie_word_embeddings": false,
"use_cache": true,
"vocab_size": 248320
},
"tie_word_embeddings": false,
"transformers_version": "5.10.2",
"use_cache": false,
"video_token_id": 248057,
"vision_config": {
"deepstack_visual_indexes": [],
"depth": 27,
"dtype": "bfloat16",
"hidden_act": "gelu_pytorch_tanh",
"hidden_size": 1152,
"in_channels": 3,
"initializer_range": 0.02,
"intermediate_size": 4304,
"model_type": "qwen3_5_vision",
"num_heads": 16,
"num_position_embeddings": 2304,
"out_hidden_size": 4096,
"patch_size": 16,
"spatial_merge_size": 2,
"temporal_patch_size": 2
},
"vision_end_token_id": 248054,
"vision_start_token_id": 248053
}1234567891011121314151617181920212223242526272829303132333435363738394041"""Run a downloaded Clef quantized bundle, without Forge or source checkpoints."""
from __future__ import annotations
import argparseimport jsonfrom pathlib import Path
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--profile", choices=["flash-int8", "clef-24gb", "clef-16gb"], required=True) parser.add_argument("--image", type=Path) parser.add_argument("--questions", type=Path) parser.add_argument("--state", default="添付画像を評価してください。") parser.add_argument("--max-pixels", type=int, default=262144) parser.add_argument("--max-length", type=int, default=2048) args = parser.parse_args() from clef_runtime.core import TEMPLATES, validate_request from clef_runtime.runtime import Runner
questions = json.loads(args.questions.read_text(encoding="utf-8")) if args.questions else TEMPLATES["画像の評価"] request = validate_request( { "profile": args.profile, "questions": questions, "state": args.state, "max_pixels": args.max_pixels, "max_length": args.max_length, } ) runner = Runner.from_directory(Path(__file__).resolve().parent, args.profile) try: result = runner.decide(request, str(args.image.resolve()) if args.image else None) print(json.dumps(result, ensure_ascii=False, indent=2), flush=True) # noqa: T201 finally: runner.close()
if __name__ == "__main__": main()123version https://git-lfs.github.com/spec/v1oid sha256:19cdcec8c81dc9212be320fff47462ab342fbc1278be4368fb3da71241cf5ba0size 24353801612345678{ "hidden_size": 4096, "width": 1024, "routing_layers": 2, "layers": 4, "heads": 16, "feedforward": 4096}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576"""Clef: a multimodal Qwen backbone with a joint schema head for typed decisions.
A record provides a ``state`` (any JSON value), optional ``images`` and ``videos``,and ``questions``. Each question has a ``type`` (``noul``, ``choice``, or ``score``),``instructions``, and, for ``choice`` and ``score``, ``criteria`` describing theallowed options. The model returns one logit per allowed option for every question.``systemone`` answers a Jev/SystemOne ``/v1/systemone`` request body with the sameresponse body."""
from __future__ import annotations
import jsonimport mathfrom dataclasses import dataclassfrom dataclasses import field as dataclass_fieldfrom pathlib import Pathfrom typing import Any
import torchimport torch.nn.functional as functional
SYSTEM_PROMPT = ( "Read the complete state and schema. Decide every field jointly. Each answer " "must be exactly one of that field's allowed options.")IMAGE_PLACEHOLDER = "<|vision_start|><|image_pad|><|vision_end|>"VIDEO_PLACEHOLDER = "<|vision_start|><|video_pad|><|vision_end|>"MEDIA_BATCH_KEYS = ("pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw")MEDIA_TOKEN_KEYS = ("mm_token_type_ids",)QUESTION_TYPES = {"noul": 0, "choice": 1, "score": 2}
def render(value: Any) -> str: if isinstance(value, str): return value return json.dumps( value, ensure_ascii=False, separators=(",", ":"), sort_keys=True, )
def question_options(question: dict[str, Any]) -> list[tuple[str, Any]]: question_type = str(question["type"]) if question_type == "noul": criteria = { "true": "The proposition is true or the answer is yes.", "false": "The proposition is false or the answer is no.", } criteria.update(question.get("criteria") or {}) return [(key, criteria[key]) for key in ("true", "false")] if question_type == "choice": return sorted((str(key), value) for key, value in question["criteria"].items()) return [(str(index), value) for index, value in enumerate(question["criteria"])]
@dataclass(frozen=True)class EncodedQuestion: question_id: str question_type: int question_span: tuple[int, int] option_spans: tuple[tuple[int, int], ...] option_ids: tuple[str, ...]
@dataclass(frozen=True)class EncodedRecord: input_ids: tuple[int, ...] questions: tuple[EncodedQuestion, ...] record_id: str media: dict[str, Any] | None = dataclass_field(default=None, compare=False, repr=False)
def _tokens(tokenizer: Any, text: str) -> list[int]: return tokenizer(text, add_special_tokens=False).input_ids
def _encode_media(processor: Any, record: dict[str, Any]) -> tuple[list[int], dict[str, Any] | None]: images = list(record.get("images") or []) videos = list(record.get("videos") or []) if not images and not videos: return [], None if processor is None: raise ValueError("records with images or videos require a processor") text = IMAGE_PLACEHOLDER * len(images) + VIDEO_PLACEHOLDER * len(videos) + "\n" encoded = processor( text=[text], images=images or None, videos=videos or None, return_tensors="pt", **(record.get("media_kwargs") or {}), ) media = {key: encoded[key] for key in MEDIA_BATCH_KEYS if key in encoded} for key in MEDIA_TOKEN_KEYS: if key in encoded: media[key] = encoded[key][0].tolist() return encoded["input_ids"][0].tolist(), media
def encode_record( tokenizer: Any, record: dict[str, Any], max_length: int = 16384, max_state_tokens: int | None = None, processor: Any | None = None,) -> EncodedRecord: schema_ids = _tokens(tokenizer, "\n\nSCHEMA FIELDS:\n") questions: list[EncodedQuestion] = [] for question_index, (question_id, question) in enumerate(record["questions"].items()): schema_ids.extend( _tokens( tokenizer, f"\nFIELD {question_index + 1}\nID: {question_id}\nTYPE: {question['type']}\nINSTRUCTION: ", ) ) question_start = len(schema_ids) instructions = question.get("instructions") if instructions is None or instructions == "": instructions = str(question_id) schema_ids.extend(_tokens(tokenizer, render(instructions))) question_end = len(schema_ids) schema_ids.extend(_tokens(tokenizer, "\nALLOWED OPTIONS:\n"))
option_spans: list[tuple[int, int]] = [] option_ids: list[str] = [] for option_index, (option_id, description) in enumerate(question_options(question)): schema_ids.extend(_tokens(tokenizer, f"OPTION {option_index + 1}: ")) option_start = len(schema_ids) semantics = {"option_id": option_id} if description is not None: semantics["description"] = description schema_ids.extend(_tokens(tokenizer, render(semantics))) option_spans.append((option_start, len(schema_ids))) option_ids.append(option_id) schema_ids.extend(_tokens(tokenizer, "\n")) schema_ids.extend(_tokens(tokenizer, "END FIELD\n")) questions.append( EncodedQuestion( question_id=str(question_id), question_type=QUESTION_TYPES[str(question["type"])], question_span=(question_start, question_end), option_spans=tuple(option_spans), option_ids=tuple(option_ids), ) )
prefix_ids = _tokens( tokenizer, f"<|im_start|>system\n{SYSTEM_PROMPT}<|im_end|>\n<|im_start|>user\nSTATE:\n", ) suffix_ids = _tokens( tokenizer, "\n<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\nJOINT SCHEMA DECISIONS:", ) media_ids, media = _encode_media(processor, record) if media is not None: media["token_offset"] = len(prefix_ids) prefix_ids = prefix_ids + media_ids state_ids = _tokens(tokenizer, render(record["state"])) if max_state_tokens is not None: state_ids = state_ids[:max_state_tokens] fixed_length = len(prefix_ids) + len(schema_ids) + len(suffix_ids) if fixed_length > max_length: raise ValueError( f"schema requires {fixed_length} tokens before state; maximum is {max_length}" ) state_ids = state_ids[: max_length - fixed_length] schema_offset = len(prefix_ids) + len(state_ids) shifted_questions = tuple( EncodedQuestion( question_id=question.question_id, question_type=question.question_type, question_span=( question.question_span[0] + schema_offset, question.question_span[1] + schema_offset, ), option_spans=tuple( (start + schema_offset, end + schema_offset) for start, end in question.option_spans ), option_ids=question.option_ids, ) for question in questions ) input_ids = tuple(prefix_ids + state_ids + schema_ids + suffix_ids) if not input_ids or not shifted_questions: raise ValueError("record produced no model input or questions") return EncodedRecord( input_ids=input_ids, questions=shifted_questions, record_id=str(record.get("id", "unknown")), media=media, )
def collate_records( records: list[EncodedRecord], pad_token_id: int, device: torch.device,) -> dict[str, Any]: maximum_length = max(len(record.input_ids) for record in records) input_ids = torch.full( (len(records), maximum_length), pad_token_id, dtype=torch.long, device=device, ) attention_mask = torch.zeros( (len(records), maximum_length), dtype=torch.long, device=device, ) for index, record in enumerate(records): length = len(record.input_ids) input_ids[index, :length] = torch.tensor(record.input_ids, device=device) attention_mask[index, :length] = 1 media: dict[str, torch.Tensor] = {} for key in MEDIA_BATCH_KEYS: values = [record.media[key] for record in records if record.media and key in record.media] if values: media[key] = torch.cat(values, dim=0).to(device) for key in MEDIA_TOKEN_KEYS: if any(record.media and key in record.media for record in records): token_values = torch.zeros((len(records), maximum_length), dtype=torch.long, device=device) for index, record in enumerate(records): if record.media and key in record.media: offset = record.media["token_offset"] values = torch.tensor(record.media[key], dtype=torch.long, device=device) token_values[index, offset : offset + len(values)] = values media[key] = token_values return { "input_ids": input_ids, "attention_mask": attention_mask, "records": records, "media": media, }
class EvidenceRoutingLayer(torch.nn.Module): def __init__( self, width: int, heads: int, feedforward: int, dropout: float = 0.0, ) -> None: super().__init__() self.query_norm = torch.nn.LayerNorm(width) self.memory_norm = torch.nn.LayerNorm(width) self.attention = torch.nn.MultiheadAttention( width, heads, dropout=dropout, batch_first=True, ) self.attention_dropout = torch.nn.Dropout(dropout) self.feedforward_norm = torch.nn.LayerNorm(width) self.feedforward = torch.nn.Sequential( torch.nn.Linear(width, feedforward), torch.nn.GELU(), torch.nn.Dropout(dropout), torch.nn.Linear(feedforward, width), torch.nn.Dropout(dropout), )
def forward(self, queries: torch.Tensor, memory: torch.Tensor) -> torch.Tensor: normalized_queries = self.query_norm(queries) routed, _ = self.attention( normalized_queries, self.memory_norm(memory), self.memory_norm(memory), need_weights=False, ) queries = queries + self.attention_dropout(routed) return queries + self.feedforward(self.feedforward_norm(queries))
class JointSchemaHead(torch.nn.Module): def __init__( self, hidden_size: int, width: int, routing_layers: int, layers: int, heads: int, feedforward: int, dropout: float = 0.0, ) -> None: super().__init__() self.hidden_norm = torch.nn.LayerNorm(hidden_size) self.memory_projection = torch.nn.Linear(hidden_size, width, bias=False) self.question_projection = torch.nn.Linear(hidden_size, width, bias=False) self.option_question_projection = torch.nn.Linear(hidden_size, width, bias=False) self.global_projection = torch.nn.Linear(hidden_size, width, bias=False) self.option_context_projection = torch.nn.Linear(hidden_size, width, bias=False) self.option_lexical_projection = torch.nn.Linear(hidden_size, width, bias=False) self.type_embedding = torch.nn.Embedding(3, width) self.evidence_layers = torch.nn.ModuleList( [ EvidenceRoutingLayer( width=width, heads=heads, feedforward=feedforward, dropout=dropout, ) for _ in range(routing_layers) ] ) self.option_summary_norm = torch.nn.LayerNorm(width) self.layers = torch.nn.ModuleList( [ torch.nn.TransformerDecoderLayer( d_model=width, nhead=heads, dim_feedforward=feedforward, dropout=dropout, activation="gelu", batch_first=True, norm_first=True, ) for _ in range(layers) ] ) self.field_norm = torch.nn.LayerNorm(width) self.option_norm = torch.nn.LayerNorm(width) self.residual_scorer = torch.nn.Sequential( torch.nn.Linear(width * 4, width), torch.nn.GELU(), torch.nn.Dropout(dropout), torch.nn.Linear(width, 1), ) self.prior_logit_scale = torch.nn.Parameter(torch.zeros(())) self.joint_logit_scale = torch.nn.Parameter(torch.zeros(())) self.residual_gate = torch.nn.Parameter(torch.zeros(()))
@staticmethod def _mean_span(values: torch.Tensor, span: tuple[int, int]) -> torch.Tensor: start, end = span return values[start:end].mean(dim=0)
def forward( self, hidden_states: torch.Tensor, input_ids: torch.Tensor, attention_mask: torch.Tensor, records: list[EncodedRecord], output_embedding_weight: torch.Tensor, ) -> list[list[torch.Tensor]]: results: list[list[torch.Tensor]] = [] normalized_hidden = self.hidden_norm(hidden_states) for batch_index, record in enumerate(records): sequence_length = int(attention_mask[batch_index].sum().item()) sequence_hidden = normalized_hidden[batch_index, :sequence_length] memory = self.memory_projection(sequence_hidden).unsqueeze(0) global_vector = sequence_hidden[-1] question_vectors = torch.stack( [ self._mean_span(sequence_hidden, question.question_span) for question in record.questions ] ) type_ids = torch.tensor( [question.question_type for question in record.questions], device=hidden_states.device, ) option_contexts: list[torch.Tensor] = [] lexical_options: list[torch.Tensor] = [] option_counts = [] for question in record.questions: context_vectors = torch.stack( [ self._mean_span(sequence_hidden, span) for span in question.option_spans ] ) lexical_vectors = [] for start, end in question.option_spans: token_ids = input_ids[batch_index, start:end] lexical_vectors.append(output_embedding_weight[token_ids].mean(dim=0)) lexical = torch.stack(lexical_vectors) option_contexts.append(context_vectors) lexical_options.append(lexical) option_counts.append(len(question.option_spans))
option_queries = [] for question_index, (context_vectors, lexical) in enumerate( zip(option_contexts, lexical_options) ): option_queries.append( self.option_context_projection(context_vectors) + self.option_lexical_projection(lexical) + self.option_question_projection( question_vectors[question_index] ).unsqueeze(0) ) routed_options = torch.cat(option_queries, dim=0).unsqueeze(0) for layer in self.evidence_layers: routed_options = layer(routed_options, memory) routed_options = routed_options[0] split_options = list(torch.split(routed_options, option_counts, dim=0))
base_fields = self.question_projection(question_vectors) option_summaries = [] for field, options in zip(base_fields, split_options): routing_weights = torch.softmax( torch.matmul(options, field) / math.sqrt(options.shape[-1]), dim=0, ) option_summaries.append( torch.sum(routing_weights.unsqueeze(-1) * options, dim=0) ) fields = ( base_fields + self.option_summary_norm(torch.stack(option_summaries)) + self.global_projection(global_vector).unsqueeze(0) + self.type_embedding(type_ids) ) fields = fields.unsqueeze(0) for layer in self.layers: fields = layer(fields, memory) fields = self.field_norm(fields[0])
record_logits: list[torch.Tensor] = [] for field, question, lexical, routed in zip( fields, record.questions, lexical_options, split_options, ): anchor = functional.normalize( question_vectors[len(record_logits)] + global_vector, dim=-1, ) lexical_anchor = functional.normalize(lexical, dim=-1) prior_scale = self.prior_logit_scale.clamp(max=math.log(100.0)).exp() prior = prior_scale * torch.matmul(lexical_anchor, anchor) options = self.option_norm(routed) repeated_field = field.unsqueeze(0).expand_as(options) cosine = functional.cosine_similarity(repeated_field, options, dim=-1) features = torch.cat( [ repeated_field, options, repeated_field * options, torch.abs(repeated_field - options), ], dim=-1, ) residual = self.residual_scorer(features).squeeze(-1) joint_scale = self.joint_logit_scale.clamp(max=math.log(100.0)).exp() joint = joint_scale * cosine + residual record_logits.append( prior + torch.sigmoid(self.residual_gate) * joint ) results.append(record_logits) return results
class ClefModel(torch.nn.Module): def __init__(self, language_model: Any, head: JointSchemaHead) -> None: super().__init__() self.language_model = language_model self.head = head
def forward(self, batch: dict[str, Any]) -> list[list[torch.Tensor]]: base_model = ( self.language_model.get_base_model() if hasattr(self.language_model, "get_base_model") else self.language_model ) media = batch.get("media") or {} text_model = base_model.model if not media and hasattr(text_model, "language_model"): text_model = text_model.language_model outputs = text_model( input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], use_cache=False, return_dict=True, **media, ) return self.head( outputs.last_hidden_state, batch["input_ids"], batch["attention_mask"], batch["records"], base_model.get_output_embeddings().weight, )
def load_release_model( model_path: str | Path, device: str | torch.device = "cuda", dtype: torch.dtype = torch.bfloat16, **from_pretrained_kwargs: Any,) -> tuple[ClefModel, Any]: """Load a Clef release (merged backbone, joint schema head, and processor).""" from huggingface_hub import snapshot_download from safetensors.torch import load_file from transformers import AutoProcessor, Qwen3_5ForConditionalGeneration
path = Path(model_path) if not path.is_dir(): path = Path(snapshot_download(str(model_path))) backbone = Qwen3_5ForConditionalGeneration.from_pretrained( path, dtype=dtype, device_map={"": str(device)}, **from_pretrained_kwargs, ) backbone.config.use_cache = False head_config = json.loads((path / "joint_head_config.json").read_text()) head = JointSchemaHead(**head_config) head.load_state_dict(load_file(path / "joint_head.safetensors"), strict=True) head = head.to(device=device, dtype=dtype) processor = AutoProcessor.from_pretrained(path) return ClefModel(backbone, head).eval(), processor
def systemone_answer(question: dict[str, Any], probabilities: dict[str, float]) -> dict[str, Any]: """Convert per-option probabilities for one question into a SystemOne answer.""" if question["type"] == "noul": return {"type": "noul", "noul": round(probabilities["true"], 4)} if question["type"] == "choice": options = [str(option) for option in question["criteria"]] choice = max(options, key=probabilities.__getitem__) return { "type": "choice", "choice": choice, "confidence": round(probabilities[choice], 4), "probabilities": {option: round(probabilities[option], 4) for option in options}, } levels = [str(index) for index in range(len(question["criteria"]))] return { "type": "score", "score": round(sum(index * probabilities[level] for index, level in enumerate(levels)), 4), "confidence": round(max(probabilities[level] for level in levels), 4), "legend": dict(zip(levels, question["criteria"])), "probabilities": {level: round(probabilities[level], 4) for level in levels}, }
@torch.inference_mode()def systemone(model: ClefModel, processor: Any, request: dict[str, Any], max_length: int = 16384) -> dict[str, Any]: """Answer a Jev/SystemOne ``/v1/systemone`` request body with a SystemOne response body.
The request has ``model``, ``state``, and ``questions``, plus optional ``images`` and ``videos``. """ questions = request.get("questions") if not isinstance(request.get("model"), str) or "state" not in request: raise ValueError("model and state are required") if not isinstance(questions, dict) or not questions: raise ValueError("at least one question is required") for question_id, question in questions.items(): if question.get("type") not in QUESTION_TYPES: raise ValueError(f"{question_id}: type must be noul, choice, or score") if question["type"] != "noul" and not question.get("criteria"): raise ValueError(f"{question_id}: criteria must not be empty") encoded = encode_record(processor.tokenizer, request, max_length=max_length, processor=processor) device = next(model.parameters()).device logits = model(collate_records([encoded], processor.tokenizer.pad_token_id, device))[0] answers = { question.question_id: systemone_answer( questions[question.question_id], dict(zip(question.option_ids, question_logits.float().softmax(-1).tolist())), ) for question, question_logits in zip(encoded.questions, logits) } return { "model": request["model"], "answers": answers, "usage": {"input_tokens": len(encoded.input_ids), "output_tokens": 0}, }123version https://git-lfs.github.com/spec/v1oid sha256:dd63614f1dc80dce2d83be3f3e69af1f8a0ebc8add9b8e0abf3910f563e44344size 2034237568123version https://git-lfs.github.com/spec/v1oid sha256:9c5483aa32a952b3a9a5d75f3c000c9ff934d3cbbb317b228cadff89e25bcffasize 2034237592123version https://git-lfs.github.com/spec/v1oid sha256:6999510bfc3c9ea6536090fb76b70bb786a0f4bd76f290ea35f35f58aa77e4f6size 1984182833123version https://git-lfs.github.com/spec/v1oid sha256:efa24fbcede25d84116de286e544554513bd0400c40c66b99c32e846f5096cddsize 1983829880123version https://git-lfs.github.com/spec/v1oid sha256:7a5dd174473310a090c74abe907de00da6b85c46f8a3b5bcaec20267449fbdbdsize 1983498867123version https://git-lfs.github.com/spec/v1oid sha256:1463c85bac6efd374bb5189d3beda19df628a786a9068b00de74dd3504f12df9size 1886989356123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960{ "image_processor": { "do_convert_rgb": true, "do_normalize": true, "do_rescale": true, "do_resize": true, "image_mean": [ 0.5, 0.5, 0.5 ], "image_processor_type": "Qwen2VLImageProcessor", "image_std": [ 0.5, 0.5, 0.5 ], "merge_size": 2, "patch_size": 16, "resample": 3, "rescale_factor": 0.00392156862745098, "size": { "longest_edge": 16777216, "shortest_edge": 65536 }, "temporal_patch_size": 2 }, "processor_class": "Qwen3VLProcessor", "video_processor": { "do_convert_rgb": true, "do_normalize": true, "do_rescale": true, "do_resize": true, "do_sample_frames": true, "fps": 2, "image_mean": [ 0.5, 0.5, 0.5 ], "image_std": [ 0.5, 0.5, 0.5 ], "max_frames": 768, "merge_size": 2, "min_frames": 4, "patch_size": 16, "resample": 3, "rescale_factor": 0.00392156862745098, "return_metadata": false, "size": { "longest_edge": 25165824, "shortest_edge": 4096 }, "temporal_patch_size": 2, "video_processor_type": "Qwen3VLVideoProcessor" }}12345678# Isolated from Forge and the diffusion-model runtimes.transformers==5.10.2bitsandbytes==0.50.2accelerate==1.15.0huggingface_hub==1.5.0safetensors==0.8.0Pillow==12.3.0torchvision==0.28.0123version https://git-lfs.github.com/spec/v1oid sha256:06b9509352d2af50381ab2247e083b80d32d5c0aba91c272ca9ff729b6a0e523size 19989325123456789101112131415161718192021222324252627282930{ "add_prefix_space": false, "audio_bos_token": "<|audio_start|>", "audio_eos_token": "<|audio_end|>", "audio_token": "<|audio_pad|>", "backend": "tokenizers", "bos_token": null, "clean_up_tokenization_spaces": false, "eos_token": "<|im_end|>", "errors": "replace", "image_token": "<|image_pad|>", "model_max_length": 262144, "model_specific_special_tokens": { "audio_bos_token": "<|audio_start|>", "audio_eos_token": "<|audio_end|>", "audio_token": "<|audio_pad|>", "image_token": "<|image_pad|>", "video_token": "<|video_pad|>", "vision_bos_token": "<|vision_start|>", "vision_eos_token": "<|vision_end|>" }, "pad_token": "<|endoftext|>", "pretokenize_regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", "split_special_tokens": false, "tokenizer_class": "Qwen2Tokenizer", "unk_token": null, "video_token": "<|video_pad|>", "vision_bos_token": "<|vision_start|>", "vision_eos_token": "<|vision_end|>"}.gitattributes+1
LICENSEAdded+202
README.mdAdded+76
chat_template.jinjaAdded+154
clef_runtime/__init__.pyAdded+1
clef_runtime/bundle.pyAdded+78
clef_runtime/cache.pyAdded+39
clef_runtime/core.pyAdded+339
clef_runtime/runtime.pyAdded+203
complete.jsonAdded+132
config.jsonAdded+128
inference.pyAdded+41
joint_head.safetensorsAdded+3
joint_head_config.jsonAdded+8
joint_schema_model.pyAdded+576
lm-head.safetensorsAdded+3
model-00001-of-00005.safetensorsAdded+3
model-00002-of-00005.safetensorsAdded+3
model-00003-of-00005.safetensorsAdded+3
model-00004-of-00005.safetensorsAdded+3
model-00005-of-00005.safetensorsAdded+3
model.safetensors.index.jsonAdded
processor_config.jsonAdded+60
requirements.txtAdded+8
tokenizer.jsonAdded+3
tokenizer_config.jsonAdded+30