Feature Extraction
Transformers
Safetensors
English
vfm
verification
guardrails
llm-as-a-judge
agent-governance
custom_code
Run this model with HF Jobs
Run spitis/VFM-0.6B 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/spitis/VFM-0.6B. 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/spitis/VFM-0.6B 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 spitis/VFM-0.6B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use spitis/VFM-0.6B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="spitis/VFM-0.6B", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("spitis/VFM-0.6B", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Commit ·
d573d3f
0
Parent(s):
VFM public release
Browse filesFiles changed (12)
- .gitattributesAdded+36
- LICENSEAdded+202
- README.mdAdded+85
- collator_vfm.pyAdded+114
- config.jsonAdded+100
- configuration_vfm.pyAdded+67
- merges.txtAdded
- model.safetensorsAdded+3
- modeling_vfm.pyAdded+288
- tokenizer.jsonAdded+3
- tokenizer_config.jsonAdded+239
- vocab.jsonAdded
123456789101112131415161718192021222324252627282930313233343536*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.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 -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
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 2024 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.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485---license: apache-2.0base_model: Qwen/Qwen3-0.6Bdatasets:- spitis/CriteriaBanklanguage:- enlibrary_name: transformerstags:- verification- guardrails- llm-as-a-judge- agent-governance---
# VFM-0.6B
VFM-0.6B verifies natural-language criteria against a context and target text. It uses a Qwen3-0.6B backbone and a three-class head, pretrained on [CriteriaBank](https://huggingface.co/datasets/spitis/CriteriaBank) for *Runtime Verification of Multiple Natural Language Criteria for Agent Governance* (NeurIPS 2026).
Each criterion receives **YES** (satisfied), **NO** (not satisfied), or **N/A** (inapplicable or insufficient evidence). Criteria are scored independently over a shared prefix, without text generation. [Code and training recipes](https://github.com/spitis/vfm).
**Use**
```bashpip install git+https://github.com/spitis/vfm```
```pythonfrom vfm import VFM
vfm = VFM.from_pretrained("spitis/VFM-0.6B")verdicts = vfm.verify( context="Describe today's weather.", target="It is sunny today.", criteria=["Does the response mention sunshine?", "Does the response mention rain?"],)for v in verdicts: print(v["criterion"], v["verdict"], v["p_yes"], v["p_no"], v["p_na"])```
`context` accepts a string or chat messages; `target` is appended as the next turn. Outputs also include `logits` and `p_yes_binary = p_yes / (p_yes + p_no)`. Use `verify_batch` for separate traces.
Keep criteria short and atomic. Prefixes are left-truncated at 4,096 tokens by default (`max_length`); criterion blocks at 64 tokens, including chat-template tokens. `verify` reuses the prefix cache across chunks of 64 criteria (`chunk_size`).
**Training and results**
Full-parameter pretraining uses 393,531 model-labelled CriteriaBank rows, cross-entropy plus KL to the frozen base model (λ = 1), AdamW, and batch size 128. The released checkpoint is the one saved at **step 2,000 of the 3,075 pretraining steps**.
Paper results below use the released weights for zero-shot evaluation; ternary benchmarks use their YES/NO subset.
| Benchmark | Zero-shot ROC-AUC ||---|---:|| InFoBench | 0.887 || Synthetic governance | 0.880 || ContractNLI | 0.857 || INSURE-Dial | 0.713 || BeaverTails | 0.722 || IFEval | 0.654 || PRM800K | 0.635 || LLM-AggreFact | 0.736 |
After benchmark finetuning (mean ± standard deviation over three seeds):
- Synthetic governance accuracy: **87.2 ± 0.5%**, with **75.1 ± 1.4%** on transfer domains.- INSURE-Dial accuracy: **82.6 ± 0.6%**.- Across six learning curves, macro AULC is **0.789**, versus 0.772 without KL and 0.736 for Direct-FT.
Finetuned results require separate benchmark training. Governance uses dev selection; INSURE-Dial uses five-fold checkpoint selection over real calls.
**Limitations**
Finetune and tune decision thresholds for your domain. Zero-shot calibration and N/A prediction are weak. Labels are model-generated; evaluations are English-only and text-only. Even the best finetuned 4B verifier approves about 20% of gold violations on INSURE-Dial. Use for monitoring and escalation, not standalone enforcement.
**License:** Apache-2.0, including the Qwen3-0.6B base model. Tokenizer files are unchanged from Qwen3.
**Citation**
```bibtex@inproceedings{pitis2026vfm, title = {Runtime Verification of Multiple Natural Language Criteria for Agent Governance}, author = {Pitis, Silviu and Alamdari, Parand A. and Tang, Jessica and Klassen, Toryn Q. and McIlraith, Sheila A.}, booktitle = {Advances in Neural Information Processing Systems}, year = {2026}}```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114"""Tokenization and batching for the VFM.
The (context, target) prefix is rendered with the backbone's chat template, with thetarget appended as the next turn. Each criterion is rendered as its own one-turn chatprompt (user message + assistant generation prompt) and padded to a fixed block of`max_criterion_length` tokens; the head reads the last non-padding token of each block."""from __future__ import annotations
import warningsfrom typing import Any, Dict, List, Optional, Sequence, Union
import torch
from .configuration_vfm import LABEL_NAMES
Messages = List[Dict[str, Any]]
def _messages(context: Union[str, Messages, None]) -> Messages: if context is None: return [] if isinstance(context, str): return [{"role": "user", "content": context}] return list(context)
def _next_role(messages: Messages) -> str: """Role of the target turn: assistant after a user turn, otherwise user.""" if not messages: return "user" return "assistant" if messages[-1].get("role", "user") == "user" else "user"
def format_prefix(tokenizer, context: Union[str, Messages, None], target: Optional[str]) -> str: """Render the shared (context, target) prefix as text.""" messages = _messages(context) if target: messages = messages + [{"role": _next_role(messages), "content": target}] return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False, enable_thinking=False)
def format_criterion(tokenizer, criterion: str) -> str: """Render one criterion as a one-turn chat prompt ending at the answer position (with thinking disabled, so the template inserts an empty think block).""" return tokenizer.apply_chat_template([{"role": "user", "content": criterion}], tokenize=False, add_generation_prompt=True, enable_thinking=False)
class VFMCollator: """Turns VFM rows into model inputs.
Each row is a dict with `context`, `target`, `criteria` (list of N strings) and optionally `labels` (list of N labels). All rows in a batch must have the same N (single-criterion rows are the common case for training).
Returns `input_ids`/`attention_mask` (B, L), left-padded and left-truncated, and `criterion_input_ids`/`criterion_attention_mask` (B, N*T) with T = `max_criterion_length`, plus `labels` (B, N) when labels are present. """
def __init__(self, tokenizer, max_length: int = 4096, max_criterion_length: int = 64): self.tokenizer = tokenizer self.max_length = max_length self.max_criterion_length = max_criterion_length if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token self._warned_long = False
def _tokenize(self, texts: List[str], max_length: int, padding_side: str, padding): tok = self.tokenizer old = (tok.padding_side, tok.truncation_side) tok.padding_side, tok.truncation_side = padding_side, "left" try: return tok(texts, padding=padding, truncation=True, max_length=max_length, return_tensors="pt") finally: tok.padding_side, tok.truncation_side = old
def encode_prefixes(self, rows: Sequence[Dict[str, Any]]) -> Dict[str, torch.Tensor]: texts = [format_prefix(self.tokenizer, r.get("context"), r.get("target")) for r in rows] enc = self._tokenize(texts, self.max_length, "left", "longest") return {"input_ids": enc["input_ids"], "attention_mask": enc["attention_mask"]}
def encode_criteria(self, criteria: Sequence[str]) -> Dict[str, torch.Tensor]: """Tokenize criteria into fixed-size blocks: returns (N, T) tensors.""" texts = [format_criterion(self.tokenizer, c) for c in criteria] if not self._warned_long: lengths = [len(self.tokenizer(t, add_special_tokens=False)["input_ids"]) for t in texts] if max(lengths, default=0) > self.max_criterion_length: warnings.warn( f"Some criteria exceed {self.max_criterion_length} tokens including the chat " "template and are truncated from the left, as in training. Keep criteria short " "and atomic.", stacklevel=3) self._warned_long = True enc = self._tokenize(texts, self.max_criterion_length, "right", "max_length") return {"criterion_input_ids": enc["input_ids"], "criterion_attention_mask": enc["attention_mask"]}
def __call__(self, rows: Sequence[Dict[str, Any]]) -> Dict[str, torch.Tensor]: n = len(rows[0]["criteria"]) if any(len(r["criteria"]) != n for r in rows): raise ValueError("All rows in a batch must have the same number of criteria") batch = self.encode_prefixes(rows) crit = self.encode_criteria([c for r in rows for c in r["criteria"]]) B, T = len(rows), self.max_criterion_length batch["criterion_input_ids"] = crit["criterion_input_ids"].reshape(B, n * T) batch["criterion_attention_mask"] = crit["criterion_attention_mask"].reshape(B, n * T) if rows[0].get("labels") is not None: batch["labels"] = torch.tensor([[LABEL_NAMES.index(l) for l in r["labels"]] for r in rows], dtype=torch.long) return batch
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100{ "architectures": [ "VFMForCriteriaVerification" ], "auto_map": { "AutoConfig": "configuration_vfm.VFMConfig", "AutoModel": "modeling_vfm.VFMForCriteriaVerification" }, "backbone_config": { "_name_or_path": "Qwen/Qwen3-0.6B", "architectures": [ "Qwen3Model" ], "attention_bias": false, "attention_dropout": 0.0, "bos_token_id": 151643, "dtype": "bfloat16", "eos_token_id": 151645, "head_dim": 128, "hidden_act": "silu", "hidden_size": 1024, "initializer_range": 0.02, "intermediate_size": 3072, "layer_types": [ "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention" ], "max_position_embeddings": 40960, "max_window_layers": 28, "model_type": "qwen3", "num_attention_heads": 16, "num_hidden_layers": 28, "num_key_value_heads": 8, "rms_norm_eps": 1e-06, "rope_scaling": null, "rope_theta": 1000000, "sliding_window": null, "tie_word_embeddings": true, "use_cache": true, "use_sliding_window": false, "vocab_size": 151936 }, "base_model_name_or_path": "Qwen/Qwen3-0.6B", "dtype": "bfloat16", "enable_thinking": false, "id2label": { "0": "YES", "1": "NO", "2": "N/A" }, "isolate_criteria": true, "label2id": { "N/A": 2, "NO": 1, "YES": 0 }, "max_criterion_length": 64, "max_prefix_length": 4096, "model_type": "vfm", "preserve_lambda": 1.0, "preserve_loss": "kl_base", "tie_word_embeddings": false, "transformers_version": "4.57.1", "verbalizer_token_ids": [ 7414, 2753, 21693 ], "verbalizers": [ " Yes", "No", " Unknown" ]}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667"""Configuration for the VFM criterion verifier."""from __future__ import annotations
from typing import Any, Dict, List, Optional, Union
from transformers import AutoConfig, PretrainedConfig
LABEL_NAMES = ["YES", "NO", "N/A"]
class VFMConfig(PretrainedConfig): r"""Configuration of a VFM: a decoder-only backbone plus a 3-way (YES / NO / N/A) head.
Args: backbone_config (`dict` or `PretrainedConfig`): configuration of the backbone (e.g. a `Qwen3Config`). The backbone is built from this config, so loading a VFM never downloads the base model. max_criterion_length (`int`, defaults to 64): token length of each criterion block, including the chat-template tokens. Longer criteria are truncated from the left, as in training. max_prefix_length (`int`, defaults to 4096): default maximum token length of the shared (context, target) prefix. Longer prefixes are truncated from the left. verbalizers (`list[str]`): verbalizer strings whose unembedding rows initialized the head (training provenance only). verbalizer_token_ids (`list[int]`): token ids of `verbalizers`. base_model_name_or_path (`str`): the base model the backbone was trained from (provenance only; not loaded). preserve_loss (`str`): pretraining regularizer, `"kl_base"` or `"none"` (training metadata only). preserve_lambda (`float`): weight of the pretraining regularizer. """
model_type = "vfm" sub_configs = {"backbone_config": AutoConfig}
def __init__( self, backbone_config: Optional[Union[Dict[str, Any], PretrainedConfig]] = None, max_criterion_length: int = 64, max_prefix_length: int = 4096, verbalizers: Optional[List[str]] = None, verbalizer_token_ids: Optional[List[int]] = None, base_model_name_or_path: Optional[str] = None, preserve_loss: str = "none", preserve_lambda: float = 0.0, **kwargs, ): if isinstance(backbone_config, dict): backbone_config = dict(backbone_config) model_type = backbone_config.pop("model_type", "qwen3") backbone_config = AutoConfig.for_model(model_type, **backbone_config) self.backbone_config = backbone_config self.max_criterion_length = max_criterion_length self.max_prefix_length = max_prefix_length self.verbalizers = verbalizers self.verbalizer_token_ids = verbalizer_token_ids self.base_model_name_or_path = base_model_name_or_path self.preserve_loss = preserve_loss self.preserve_lambda = preserve_lambda kwargs.setdefault("id2label", {i: n for i, n in enumerate(LABEL_NAMES)}) kwargs.setdefault("label2id", {n: i for i, n in enumerate(LABEL_NAMES)}) kwargs.setdefault("tie_word_embeddings", False) super().__init__(**kwargs)
@property def hidden_size(self) -> int: return self.backbone_config.hidden_size123version https://git-lfs.github.com/spec/v1oid sha256:e2a66be03fe742e9ae030405b4009a66d85c5680e779621aa43946aba578d4ebsize 1192142366123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288"""VFM: a criterion verifier with tree attention over a shared (context, target) prefix.
The backbone reads the prefix once, followed by N criterion blocks. A 4D attention masklets each criterion attend to the full prefix and causally to itself, but not to othercriteria, and the prefix never attends to criteria. Every criterion block starts at theposition right after the prefix, so verdicts do not depend on how many criteria arescored or in what order. A linear head maps the hidden state of the last token of eachblock to YES / NO / N/A logits."""from __future__ import annotations
from dataclasses import dataclassfrom typing import Any, Dict, List, Optional, Sequence
import torchimport torch.nn as nnfrom transformers import AutoModel, PreTrainedModelfrom transformers.utils import ModelOutput
from .collator_vfm import VFMCollatorfrom .configuration_vfm import LABEL_NAMES, VFMConfig
@dataclassclass VFMOutput(ModelOutput): """Outputs of `VFMForCriteriaVerification`.
logits: (B, N, 3) YES / NO / N/A logits, one row per criterion. loss: cross-entropy against `labels` when given (ignore index -100). prefix_hidden_states: (B, L, H) last-layer prefix states, only when requested (used by the KL regularizer during pretraining). """
loss: Optional[torch.FloatTensor] = None logits: Optional[torch.FloatTensor] = None prefix_hidden_states: Optional[torch.FloatTensor] = None
def _criterion_mask(n_blocks: int, block: int, crit_mask: torch.Tensor) -> torch.Tensor: """(B, 1, n_blocks*block, n_blocks*block) boolean mask among criterion tokens: causal within each block, no attention across blocks.""" device = crit_mask.device idx = torch.arange(n_blocks * block, device=device) r, c = idx.unsqueeze(1), idx.unsqueeze(0) allowed = (r >= c) & (r // block == c // block) return allowed.unsqueeze(0).unsqueeze(0) & (crit_mask.unsqueeze(1).unsqueeze(1) == 1)
def _readout(hidden: torch.Tensor, crit_mask: torch.Tensor, n_blocks: int, block: int) -> torch.Tensor: """Hidden state at the last non-padding token of each criterion block: (B, N, H).""" B, _, H = hidden.shape blocks = hidden.reshape(B, n_blocks, block, H) last = (crit_mask.reshape(B, n_blocks, block).sum(-1).long() - 1).clamp(min=0) return torch.gather(blocks, 2, last[:, :, None, None].expand(-1, -1, 1, H)).squeeze(2)
class VFMPreTrainedModel(PreTrainedModel): config_class = VFMConfig base_model_prefix = "vfm" supports_gradient_checkpointing = True _supports_sdpa = True _supports_flash_attn = False _supports_flash_attn_2 = False _no_split_modules = ["Qwen3DecoderLayer"]
def _init_weights(self, module): std = getattr(self.config.backbone_config, "initializer_range", 0.02) if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) elif hasattr(module, "weight") and module.__class__.__name__.endswith("RMSNorm"): module.weight.data.fill_(1.0)
class VFMForCriteriaVerification(VFMPreTrainedModel): """Backbone + ternary verification head. See the module docstring for the layout."""
def __init__(self, config: VFMConfig, backbone: Optional[nn.Module] = None): super().__init__(config) bcfg = backbone.config if backbone is not None else config.backbone_config # The tree mask is a dense 4D mask, which flash-attention kernels do not accept. if getattr(bcfg, "_attn_implementation", None) in (None, "flash_attention_2", "flash_attention_3"): bcfg._attn_implementation = "sdpa" if backbone is None: backbone = AutoModel.from_config(bcfg) self.backbone = backbone self.verification_head = nn.Linear(config.hidden_size, len(LABEL_NAMES), bias=True) self.post_init()
# ------------------------------------------------------------------ helpers def get_input_embeddings(self): return self.backbone.get_input_embeddings()
def set_input_embeddings(self, value): self.backbone.set_input_embeddings(value)
def _float_mask(self, mask_bool: torch.Tensor, dtype: torch.dtype) -> torch.Tensor: zero = torch.tensor(0.0, dtype=dtype, device=mask_bool.device) neg = torch.tensor(torch.finfo(dtype).min, dtype=dtype, device=mask_bool.device) return torch.where(mask_bool, zero, neg)
# ------------------------------------------------------------------ forward def forward( self, input_ids: torch.LongTensor, criterion_input_ids: torch.LongTensor, attention_mask: Optional[torch.LongTensor] = None, criterion_attention_mask: Optional[torch.LongTensor] = None, labels: Optional[torch.LongTensor] = None, output_prefix_hidden_states: bool = False, **kwargs, ) -> VFMOutput: """Score N criteria per row in one pass.
input_ids, attention_mask: (B, L) left-padded prefix. criterion_input_ids, criterion_attention_mask: (B, N*T) right-padded criterion blocks of T = config.max_criterion_length tokens each. labels: optional (B, N) with 0=YES, 1=NO, 2=N/A, -100=ignore. """ B, L = input_ids.shape T = self.config.max_criterion_length device = input_ids.device if attention_mask is None: attention_mask = torch.ones_like(input_ids) if criterion_attention_mask is None: criterion_attention_mask = torch.ones_like(criterion_input_ids) if criterion_input_ids.shape[1] % T: raise ValueError(f"criterion_input_ids length must be a multiple of {T}") N = criterion_input_ids.shape[1] // T C = N * T
embed = self.get_input_embeddings() inputs_embeds = torch.cat([embed(input_ids), embed(criterion_input_ids)], dim=1)
# Positions: prefix 0..L-1; every criterion block continues from the prefix end. prefix_pos = torch.arange(L, device=device).unsqueeze(0).expand(B, -1) crit_pos = (L + torch.arange(T, device=device)).repeat(N).unsqueeze(0).expand(B, -1) position_ids = torch.cat([prefix_pos, crit_pos], dim=1)
# Tree attention mask (True = may attend). key_ok = attention_mask.unsqueeze(1).unsqueeze(1) == 1 # (B,1,1,L) mask = torch.zeros((B, 1, L + C, L + C), dtype=torch.bool, device=device) causal = torch.tril(torch.ones((L, L), dtype=torch.bool, device=device)) mask[:, :, :L, :L] = causal.unsqueeze(0).unsqueeze(0) & key_ok mask[:, :, L:, :L] = key_ok.expand(B, 1, C, L) mask[:, :, L:, L:] = _criterion_mask(N, T, criterion_attention_mask)
out = self.backbone(inputs_embeds=inputs_embeds, position_ids=position_ids, attention_mask=self._float_mask(mask, inputs_embeds.dtype), use_cache=False, return_dict=True) hidden = out.last_hidden_state logits = self.verification_head(_readout(hidden[:, L:], criterion_attention_mask, N, T))
loss = None if labels is not None: loss = nn.functional.cross_entropy(logits.reshape(-1, logits.shape[-1]).float(), labels.reshape(-1).to(device), ignore_index=-100) return VFMOutput(loss=loss, logits=logits, prefix_hidden_states=hidden[:, :L] if output_prefix_hidden_states else None)
# -------------------------------------------------------- prefix-cached path @torch.no_grad() def encode_prefix(self, input_ids: torch.LongTensor, attention_mask: Optional[torch.LongTensor] = None): """Run the backbone on the prefix only; returns (cache, prefix_length).""" from transformers import DynamicCache
L = input_ids.shape[1] if attention_mask is None: attention_mask = torch.ones_like(input_ids) position_ids = torch.arange(L, device=input_ids.device).unsqueeze(0).expand(input_ids.shape[0], -1) cache = DynamicCache(config=self.backbone.config) out = self.backbone(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=cache, use_cache=True, return_dict=True) return out.past_key_values, L
@torch.no_grad() def score_with_prefix_cache(self, criterion_input_ids, criterion_attention_mask, cache, prefix_length, prefix_attention_mask=None) -> torch.Tensor: """Logits (B, N, 3) for criterion blocks attending to a cached prefix.
The cache is cropped back to the prefix afterwards, so it can be reused for the next chunk of criteria. """ B = criterion_input_ids.shape[0] T = self.config.max_criterion_length N = criterion_input_ids.shape[1] // T C = N * T L = prefix_length device = criterion_input_ids.device if prefix_attention_mask is None: prefix_attention_mask = torch.ones((B, L), dtype=torch.long, device=device) inputs_embeds = self.get_input_embeddings()(criterion_input_ids) position_ids = (L + torch.arange(T, device=device)).repeat(N).unsqueeze(0).expand(B, -1) mask = torch.zeros((B, 1, C, L + C), dtype=torch.bool, device=device) mask[:, :, :, :L] = (prefix_attention_mask.unsqueeze(1).unsqueeze(1) == 1).expand(B, 1, C, L) mask[:, :, :, L:] = _criterion_mask(N, T, criterion_attention_mask) try: out = self.backbone(inputs_embeds=inputs_embeds, position_ids=position_ids, attention_mask=self._float_mask(mask, inputs_embeds.dtype), past_key_values=cache, cache_position=torch.arange(L, L + C, device=device), use_cache=True, return_dict=True) finally: extra = cache.get_seq_length() - L if extra > 0: cache.crop(-extra) return self.verification_head(_readout(out.last_hidden_state, criterion_attention_mask, N, T))
# ------------------------------------------------------------- high level def _collator(self, tokenizer, max_length: Optional[int] = None) -> VFMCollator: return VFMCollator(tokenizer, max_length=max_length or self.config.max_prefix_length, max_criterion_length=self.config.max_criterion_length)
@staticmethod def _verdicts(criteria: Sequence[str], logits: torch.Tensor) -> List[Dict[str, Any]]: logits = logits.float() probs = logits.softmax(-1).tolist() binary = logits[:, :2].softmax(-1)[:, 0].tolist() out = [] for c, p, pb, lg in zip(criteria, probs, binary, logits.tolist()): out.append({"criterion": c, "verdict": LABEL_NAMES[max(range(3), key=p.__getitem__)], "p_yes": p[0], "p_no": p[1], "p_na": p[2], "p_yes_binary": pb, "logits": lg}) return out
@torch.no_grad() def verify(self, tokenizer, context, target: Optional[str], criteria: Sequence[str], chunk_size: int = 64, max_length: Optional[int] = None) -> List[Dict[str, Any]]: """Score many criteria against one (context, target).
The prefix is encoded once and its key-value cache is reused for chunks of `chunk_size` criteria, so memory stays flat in the number of criteria.
Args: tokenizer: the model's tokenizer. context: a string (one user turn) or a list of {"role", "content"} messages. target: the text being verified (e.g. the assistant response), or None. criteria: natural-language yes/no questions. Returns: One dict per criterion: criterion, verdict (YES / NO / N/A), p_yes, p_no, p_na, p_yes_binary (P(YES) renormalized over YES and NO), and the raw logits. """ if isinstance(criteria, str): criteria = [criteria] if not criteria: return [] self.eval() device = next(self.parameters()).device col = self._collator(tokenizer, max_length) pre = col.encode_prefixes([{"context": context, "target": target}]) cache, L = self.encode_prefix(pre["input_ids"].to(device), pre["attention_mask"].to(device)) results = [] for i in range(0, len(criteria), chunk_size): chunk = list(criteria[i:i + chunk_size]) enc = col.encode_criteria(chunk) ids = enc["criterion_input_ids"].reshape(1, -1).to(device) am = enc["criterion_attention_mask"].reshape(1, -1).to(device) logits = self.score_with_prefix_cache(ids, am, cache, L, pre["attention_mask"].to(device)) results.extend(self._verdicts(chunk, logits[0])) return results
@torch.no_grad() def verify_batch(self, tokenizer, rows: Sequence[Dict[str, Any]], batch_size: int = 16, max_length: Optional[int] = None) -> List[Dict[str, Any]]: """Score single-criterion rows {context, target, criterion}, batched with padding.
Use this for many different (context, target) pairs; use `verify` for many criteria on one pair. """ self.eval() device = next(self.parameters()).device col = self._collator(tokenizer, max_length) results = [] for i in range(0, len(rows), batch_size): chunk = [{"context": r.get("context"), "target": r.get("target"), "criteria": [r["criterion"]]} for r in rows[i:i + batch_size]] batch = col(chunk) out = self(input_ids=batch["input_ids"].to(device), attention_mask=batch["attention_mask"].to(device), criterion_input_ids=batch["criterion_input_ids"].to(device), criterion_attention_mask=batch["criterion_attention_mask"].to(device)) results.extend(self._verdicts([r["criteria"][0] for r in chunk], out.logits[:, 0])) return results
VFMConfig.register_for_auto_class()VFMForCriteriaVerification.register_for_auto_class("AutoModel")123version https://git-lfs.github.com/spec/v1oid sha256:aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4size 11422654123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239{ "add_bos_token": false, "add_prefix_space": false, "added_tokens_decoder": { "151643": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151644": { "content": "<|im_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151645": { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151646": { "content": "<|object_ref_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151647": { "content": "<|object_ref_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151648": { "content": "<|box_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151649": { "content": "<|box_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151650": { "content": "<|quad_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151651": { "content": "<|quad_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151652": { "content": "<|vision_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151653": { "content": "<|vision_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151654": { "content": "<|vision_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151655": { "content": "<|image_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151656": { "content": "<|video_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151657": { "content": "<tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151658": { "content": "</tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151659": { "content": "<|fim_prefix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151660": { "content": "<|fim_middle|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151661": { "content": "<|fim_suffix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151662": { "content": "<|fim_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151663": { "content": "<|repo_name|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151664": { "content": "<|file_sep|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151665": { "content": "<tool_response>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151666": { "content": "</tool_response>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151667": { "content": "<think>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151668": { "content": "</think>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false } }, "additional_special_tokens": [ "<|im_start|>", "<|im_end|>", "<|object_ref_start|>", "<|object_ref_end|>", "<|box_start|>", "<|box_end|>", "<|quad_start|>", "<|quad_end|>", "<|vision_start|>", "<|vision_end|>", "<|vision_pad|>", "<|image_pad|>", "<|video_pad|>" ], "bos_token": null, "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0].content + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if message.content is string %}\n {%- set content = message.content %}\n {%- else %}\n {%- set content = '' %}\n {%- endif %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- else %}\n {%- if '</think>' in content %}\n {%- set reasoning_content = content.split('</think>')[0].rstrip('\\n').split('<think>')[-1].lstrip('\\n') %}\n {%- set content = content.split('</think>')[-1].lstrip('\\n') %}\n {%- endif %}\n {%- endif %}\n {%- if loop.index0 > ns.last_query_index %}\n {%- if loop.last or (not loop.last and reasoning_content) %}\n {{- '<|im_start|>' + message.role + '\\n<think>\\n' + reasoning_content.strip('\\n') + '\\n</think>\\n\\n' + content.lstrip('\\n') }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '<think>\\n\\n</think>\\n\\n' }}\n {%- endif %}\n{%- endif %}", "clean_up_tokenization_spaces": false, "eos_token": "<|im_end|>", "errors": "replace", "model_max_length": 131072, "pad_token": "<|endoftext|>", "split_special_tokens": false, "tokenizer_class": "Qwen2Tokenizer", "unk_token": null}.gitattributesAdded+36
LICENSEAdded+202
README.mdAdded+85
collator_vfm.pyAdded+114
config.jsonAdded+100
configuration_vfm.pyAdded+67
merges.txtAdded
model.safetensorsAdded+3
modeling_vfm.pyAdded+288
tokenizer.jsonAdded+3
tokenizer_config.jsonAdded+239
vocab.jsonAdded