Text Classification
Transformers
Safetensors
English
modernbert
feature-extraction
decision-model
system-one
typed-decisions
calibration
probabilistic-classification
long-context
Eval Results
text-embeddings-inference
Instructions to use helmo/DecidaBERT-large-v2 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use helmo/DecidaBERT-large-v2 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="helmo/DecidaBERT-large-v2")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModel tokenizer = AutoTokenizer.from_pretrained("helmo/DecidaBERT-large-v2") model = AutoModel.from_pretrained("helmo/DecidaBERT-large-v2", device_map="auto") - Notebooks
- Google Colab
- Kaggle
DecidaBERT-large-v2: model, inference code, eval results
Browse filesFiles changed (13)
- .eval_results/typed-decisions.yamlAdded+36
- README.mdAdded+137
- config.jsonAdded+97
- decidabert_v2/__init__.pyAdded+3
- decidabert_v2/__pycache__/__init__.cpython-313.pycAdded
- decidabert_v2/__pycache__/model.cpython-313.pycAdded
- decidabert_v2/model.pyAdded+162
- decision_config.jsonAdded+12
- decision_server.pyAdded+50
- eval/typed-decisions/predictions.jsonlAdded
- model.safetensorsAdded+3
- tokenizer.jsonAdded
- tokenizer_config.jsonAdded+17
123456789101112131415161718192021222324252627282930313233343536- dataset: id: LocalLLaMA/typed-decisions task_id: accuracy value: 0.7835 date: "2026-11-14" source: url: https://huggingface.co/datasets/LocalLLaMA/typed-decisions name: "Typed Decisions benchmark, self-run with the benchmark scorer" notes: "Model was fitted/fine-tuned on this benchmark's train split; not comparable with zero-shot rows."- dataset: id: LocalLLaMA/typed-decisions task_id: kl_from_gold value: 0.0861 date: "2026-11-14" source: url: https://huggingface.co/datasets/LocalLLaMA/typed-decisions name: "Typed Decisions benchmark, self-run with the benchmark scorer" notes: "Model was fitted/fine-tuned on this benchmark's train split; not comparable with zero-shot rows."- dataset: id: LocalLLaMA/typed-decisions task_id: brier value: 0.0473 date: "2026-11-14" source: url: https://huggingface.co/datasets/LocalLLaMA/typed-decisions name: "Typed Decisions benchmark, self-run with the benchmark scorer" notes: "Model was fitted/fine-tuned on this benchmark's train split; not comparable with zero-shot rows."- dataset: id: LocalLLaMA/typed-decisions task_id: ece value: 0.1435 date: "2026-11-14" source: url: https://huggingface.co/datasets/LocalLLaMA/typed-decisions name: "Typed Decisions benchmark, self-run with the benchmark scorer" notes: "Model was fitted/fine-tuned on this benchmark's train split; not comparable with zero-shot rows."123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137---license: apache-2.0library_name: transformerspipeline_tag: text-classificationbase_model: answerdotai/ModernBERT-largelanguage:- entags:- decision-model- system-one- typed-decisions- modernbert- calibration- probabilistic-classification- long-contextdatasets:- LocalLLaMA/typed-decisions---
# DecidaBERT-large-v2
**A one-forward-pass decision model with an 8,192-token context.** It reads a piece of state and a set of typedquestions and returns a probability distribution for every question at once. No tokens are generated.
It takes the `POST /v1/systemone` request shape: `noul` (yes or no), `choice` (one of N labels) and `score` (anordered rubric). It is the successor of [DecidaBERT-large](https://huggingface.co/helmo/DecidaBERT-large).
## Results
### Typed Decisions test split (400 cases, 2,000 questions), scored as for DecidaBERT-large
A prediction is right when its top answer equals the gold label. Intervals are 95% Wilson intervals. Both modelswere fitted on the benchmark's `train` split (**specialist mode**); the test split was never used for training,calibration or choosing a checkpoint.
| question type | questions | DecidaBERT-large | **DecidaBERT-large-v2** | v2 95% interval | random guess ||---|---|---|---|---|---|| choice | 600 | 0.722 | **0.747** | 0.710 to 0.780 | 0.233 || score | 800 | 0.694 | **0.759** | 0.728 to 0.787 | 0.244 || yes/no (`noul`) | 600 | 0.830 | **0.868** | 0.839 to 0.893 | 0.500 || **all** | 2,000 | 0.743 (0.723 to 0.762) | **0.788** | **0.770 to 0.805** | |
For `score` questions v2 is within one level of the gold level 97.6% of the time (v1: 95.5%).
### Benchmark metrics (the benchmark's own scorer)
| Accuracy ↑ | KL from gold ↓ | Brier ↓ | ECE ↓ ||---|---|---|---|| 0.7835 | 0.0861 | 0.0473 | 0.1435 |
The two accuracy figures differ only in how ties are read: the benchmark's scorer takes the most likely option ofthe gold distribution, the table above takes the gold `label`. The test predictions are in`eval/typed-decisions/predictions.jsonl` so both can be re-derived.
### Confidence
`probabilities` is the raw distribution (the one scored above): it follows the gold distributions closely, whichare soft, so the top answer's probability reads low (mean 0.64 while the top answer is right 79% of the time).Every answer therefore also carries a `confidence`: the top answer's probability after a per-type temperaturefitted on held-out `train` cases. On the test split its calibration error is **0.023** (raw: 0.144), so a`confidence` of 0.8 means right about 80% of the time; use it for thresholds and routing.
## How it works
- **Backbone:** [ModernBERT-large](https://huggingface.co/answerdotai/ModernBERT-large) (395M parameters, 28 layers), bidirectional, context 8,192 tokens (v1: trained at 512, up to 2,048).- **One pass for all questions:** the state is read once; every question and its options follow it in the same sequence, so a request with many questions costs one forward pass, not one per question.- **Readout:** a marker token per option (and one per yes/no question); three small heads (yes/no, choice, score) map the marker states to scores; a softmax (or sigmoid) gives the distribution.- **Training data:** decision records from multiple domains of IT and software work (below), balanced by design, then the `train` split of LocalLLaMA/typed-decisions. A targeted weight edit was applied before the last stage. **No test split of any benchmark was used for training.**
| Domain group | Records | Tasks ||---|---|---|| Gating and classification | 6,834 | 11 || Routing and selection | 6,834 | 9 || Agent control flow (go / no-go) | 6,833 | 9 || Ranking and scoring | 6,833 | 8 || Verification | 6,833 | 9 || Operational engineering | 6,833 | 14 || **Total** | **41,000** | **60** || LocalLLaMA/typed-decisions `train` | 1,000 | 4 workflows |
Coverage: 38 roles (developers, SREs, SOC analysts, IT technicians, architects and more), 48 settings and 24formats (logs, diffs, alerts, tickets, agent traces, configs, metrics tables and more); 165,952 questions, of which44% yes/no, 30% choice and 26% score.
## Files
| File | What it is ||---|---|| `model.safetensors`, `config.json` | encoder and decision heads (FP32), encoder config || `decision_config.json` | context and token budgets, confidence temperatures || `tokenizer.json`, `tokenizer_config.json` | tokenizer || `decidabert_v2/` | inference code || `decision_server.py` | a `/v1/systemone` server || `eval/typed-decisions/predictions.jsonl` | test-split predictions |
## Usage
```pythonimport sysfrom huggingface_hub import snapshot_download
path = snapshot_download("helmo/DecidaBERT-large-v2")sys.path.insert(0, path)from decidabert_v2 import load
model = load(path)answers = model.predict( "Alert: 41 failed SSH logins for root from one external IP in 3 minutes, then one success.", { "disposition": {"type": "choice", "instructions": "How should the alert be handled?", "criteria": {"close": "Benign, close it.", "investigate": "Open an investigation.", "contain": "Isolate the host now."}}, "true_positive": {"type": "noul", "instructions": "Is this a real attack?"}, "severity": {"type": "score", "instructions": "How severe is it?", "criteria": ["Low", "Medium", "High", "Critical"]}, },)```
### `/v1/systemone` server
```shpip install torch transformers safetensors fastapi uvicorn huggingface_hubhuggingface-cli download helmo/DecidaBERT-large-v2 --local-dir DecidaBERT-large-v2cd DecidaBERT-large-v2 && PORT=8000 python decision_server.py```
## Limits
- English only. Best when the state describes the situation in words; raw numbers are read less reliably.- Fitted on the benchmark's `train` split: its numbers there belong with other fitted models, not zero-shot ones.- The gold labels of the benchmark are a teacher model's averaged answers, so scores measure agreement with that teacher.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697{ "transformers_version": "5.23.0", "architectures": [ "ModernBertModel" ], "output_hidden_states": false, "return_dict": true, "dtype": "float32", "chunk_size_feed_forward": 0, "is_encoder_decoder": false, "id2label": { "0": "LABEL_0", "1": "LABEL_1" }, "label2id": { "LABEL_0": 0, "LABEL_1": 1 }, "problem_type": null, "vocab_size": 50368, "hidden_size": 1024, "intermediate_size": 2624, "num_hidden_layers": 28, "num_attention_heads": 16, "hidden_activation": "gelu", "max_position_embeddings": 8192, "initializer_range": 0.02, "initializer_cutoff_factor": 2.0, "norm_eps": 1e-05, "norm_bias": false, "pad_token_id": 50283, "eos_token_id": 50282, "bos_token_id": 50281, "cls_token_id": 50281, "sep_token_id": 50282, "attention_bias": false, "attention_dropout": 0.0, "layer_types": [ "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention" ], "rope_parameters": { "sliding_attention": { "rope_type": "default", "rope_theta": 10000.0 }, "full_attention": { "rope_type": "default", "rope_theta": 160000.0 } }, "local_attention": 128, "embedding_dropout": 0.0, "mlp_bias": false, "mlp_dropout": 0.0, "decoder_bias": true, "classifier_pooling": "mean", "classifier_dropout": 0.0, "classifier_bias": false, "classifier_activation": "gelu", "deterministic_flash_attn": false, "sparse_prediction": false, "sparse_pred_ignore_index": -100, "tie_word_embeddings": true, "global_attn_every_n_layers": 3, "gradient_checkpointing": false, "layer_norm_eps": 1e-05, "model_type": "modernbert", "position_embedding_type": "absolute", "output_attentions": false}123from .model import DecidaBERTv2, load
__all__ = ["DecidaBERTv2", "load"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162"""DecidaBERT-large-v2 inference: one state plus typed questions in, one probability distribution per question out,from a single forward pass of a ModernBERT-large encoder (8,192-token context). No generated text.
from decidabert_v2 import load model = load("helmo/DecidaBERT-large-v2") # or a local folder model.predict(state, questions) # {qid: {"type", ..., "probabilities", "confidence"}}
Layout: [CLS] state [SEP] q1 [SEP] q2 [SEP] ... Each question is "<type> question: <instructions>" (plus yes/nocriteria when given), then a [MASK] marker read by the yes/no head, then for choice and score one [MASK] marker peroption or level followed by its text, read by the choice or score head. Every question is answered from the samesingle read of the state. If a request is longer than the context, the end of the state is cut first.
`probabilities` are the model's raw distribution (the one scored on the typed-decisions benchmark). `confidence` isthe probability of the top answer after a per-type temperature fitted on held-out data, so that it tracks how oftenthe top answer is right (see decision_config.json)."""from __future__ import annotations
import jsonimport mathimport osfrom typing import Any
import numpy as npimport torchfrom torch import nn
TYPES = {"choice": 0, "score": 1}
def _question_text(q: dict) -> str: ins = q.get("instructions", "") ins = ins if isinstance(ins, str) else json.dumps(ins, ensure_ascii=False) t = f"{q['type']} question: {ins}" c = q.get("criteria") if q["type"] == "noul" and isinstance(c, dict): if c.get("true"): t += f" | yes means: {c['true']}" if c.get("false"): t += f" | no means: {c['false']}" return t
def _options(q: dict) -> tuple[list[str], list[str]]: c = q.get("criteria") if q["type"] == "choice": if isinstance(c, list): # bare labels are accepted, as in the System One API c = {str(x): "" for x in c} return list(c), [f"{k.replace('_', ' ')}: {v}" if v else k.replace("_", " ") for k, v in c.items()] if q["type"] == "score": levels = list(c.values()) if isinstance(c, dict) else list(c) return [str(i) for i in range(len(levels))], [f"level {i}: {v}" for i, v in enumerate(levels)] return [], []
class Layout: def __init__(self, tok, max_len: int, head_max: int, opt_max: int): self.tok, self.max_len, self.head_max, self.opt_max = tok, max_len, head_max, opt_max self.CLS, self.SEP, self.MASK, self.PAD = tok.cls_token_id, tok.sep_token_id, tok.mask_token_id, tok.pad_token_id
def _ids(self, text: str) -> list[int]: return self.tok(text, add_special_tokens=False)["input_ids"]
def encode(self, state: Any, questions: dict) -> tuple[list[int], list, list, bool]: state = state if isinstance(state, str) else json.dumps(state, ensure_ascii=False) st = self._ids(state) qs = [] for qid, q in questions.items(): keys, texts = _options(q) qs.append({"qid": qid, "type": q["type"], "head": self._ids(" " + _question_text(q)), "keys": keys, "opts": [self._ids(" " + t) for t in texts]}) cap = self.opt_max while True: qpart, marks = [], [] for q in qs: ids = q["head"][:self.head_max] qmark = len(qpart) + len(ids) ids = ids + [self.MASK] offs = [] for j in range(len(q["keys"])): offs.append(len(qpart) + len(ids)) ids = ids + [self.MASK] + q["opts"][j][:cap] ids = ids + [self.SEP] marks.append((q, qmark, offs)) qpart += ids room = self.max_len - 2 - len(qpart) if room >= 256 or cap <= 8: break cap //= 2 state_ids = st[:max(0, room)] base = 2 + len(state_ids) ids = ([self.CLS] + state_ids + [self.SEP] + qpart)[:self.max_len] noul, groups = [], [] for q, qmark, offs in marks: if q["type"] == "noul": if base + qmark < len(ids): noul.append((base + qmark, q["qid"])) elif offs and base + offs[-1] < len(ids): groups.append(([base + o for o in offs], TYPES[q["type"]], q["qid"], q["keys"])) return ids, noul, groups, len(state_ids) < len(st)
def _head(d: int) -> nn.Sequential: return nn.Sequential(nn.Linear(d, d), nn.GELU(), nn.LayerNorm(d), nn.Linear(d, 1))
class DecidaBERTv2(nn.Module): def __init__(self, encoder, layout: Layout, temperature: dict[str, float]): super().__init__() self.encoder, self.layout, self.temperature = encoder, layout, temperature d = encoder.config.hidden_size self.noul_head, self.choice_head, self.score_head = _head(d), _head(d), _head(d)
@torch.no_grad() def predict(self, state: Any, questions: dict) -> dict[str, dict]: """Answer every question about `state` in one forward pass (System One answer shape).""" dev = next(self.parameters()).device ids, noul, groups, truncated = self.layout.encode(state, questions) x = torch.tensor([ids], device=dev) h = self.encoder(input_ids=x, attention_mask=torch.ones_like(x)).last_hidden_state[0] out: dict[str, dict] = {} for pos, qid in noul: z = float(self.noul_head(h[pos]).squeeze(-1)) p = 1 / (1 + math.exp(-z)) pc = 1 / (1 + math.exp(-z / self.temperature["noul"])) out[qid] = {"type": "noul", "noul": p, "confidence": max(pc, 1 - pc)} for poss, ty, qid, keys in groups: hd = self.choice_head if ty == 0 else self.score_head z = hd(h[poss]).squeeze(-1).float().cpu().numpy() p = np.exp(z - z.max()); p /= p.sum() zt = z / self.temperature["choice" if ty == 0 else "score"] pt = np.exp(zt - zt.max()); pt /= pt.sum() probs = {k: float(v) for k, v in zip(keys, p)} if ty == 0: out[qid] = {"type": "choice", "choice": keys[int(p.argmax())], "probabilities": probs, "confidence": float(pt.max())} else: legend = questions[qid]["criteria"] legend = list(legend.values()) if isinstance(legend, dict) else list(legend) out[qid] = {"type": "score", "score": float((np.arange(len(p)) * p).sum()), "probabilities": probs, "legend": {str(i): str(c) for i, c in enumerate(legend)}, "confidence": float(pt.max())} if truncated: for a in out.values(): a["truncated_state"] = True return out
def load(path: str = "helmo/DecidaBERT-large-v2", device: str | None = None) -> DecidaBERTv2: """Load from a local folder or a Hugging Face repo id.""" from safetensors.torch import load_file from transformers import AutoConfig, AutoModel, AutoTokenizer if not os.path.isdir(path): from huggingface_hub import snapshot_download path = snapshot_download(path) device = device or ("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu") dc = json.load(open(os.path.join(path, "decision_config.json"))) cfg = AutoConfig.from_pretrained(path) enc = AutoModel.from_config(cfg, attn_implementation="sdpa") tok = AutoTokenizer.from_pretrained(path) m = DecidaBERTv2(enc, Layout(tok, dc["max_len"], dc["head_max_tokens"], dc["option_max_tokens"]), dc["confidence_temperature"]) missing, unexpected = m.load_state_dict(load_file(os.path.join(path, "model.safetensors")), strict=False) assert not unexpected and not [k for k in missing if not k.startswith("layout")], (missing, unexpected) return m.float().to(device).eval()123456789101112{ "max_len": 8192, "head_max_tokens": 256, "option_max_tokens": 96, "confidence_temperature": { "noul": 0.44, "choice": 0.51, "score": 0.38 }, "confidence_note": "per-type temperature applied only to the reported confidence (top answer), fitted on held-out train cases to the gold label; probabilities are left raw", "readout": "one [MASK] marker per option (choice/score) and per yes/no question; heads noul/choice/score"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950"""A minimal `POST /v1/systemone` server for DecidaBERT-large-v2.
pip install torch transformers safetensors fastapi uvicorn huggingface_hub PORT=8000 python decision_server.py
POST /v1/systemone {"state": ..., "questions": {qid: {"type", "instructions", "criteria"}}}POST /v1/systemone/batch {"requests": [ {"state", "questions"}, ... ]}"""import osimport time
import uvicornfrom fastapi import FastAPIfrom pydantic import BaseModel
from decidabert_v2 import load
MODEL = load(os.environ.get("MODEL_PATH", os.path.dirname(os.path.abspath(__file__))))app = FastAPI(title="DecidaBERT-large-v2")
class Request(BaseModel): state: object questions: dict model: str | None = None
class Batch(BaseModel): requests: list[Request] model: str | None = None
def _answer(r: Request) -> dict: t0 = time.perf_counter() answers = MODEL.predict(r.state, r.questions) return {"model": "DecidaBERT-large-v2", "answers": answers, "latency_ms": round((time.perf_counter() - t0) * 1000, 1)}
@app.post("/v1/systemone")def systemone(r: Request) -> dict: return _answer(r)
@app.post("/v1/systemone/batch")def batch(b: Batch) -> dict: return {"responses": [_answer(r) for r in b.requests]}
if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 8000)))123version https://git-lfs.github.com/spec/v1oid sha256:33a6ad9d6a6a1007024983720b25b0385511b4acb523c4f7c87ab5afc410719asize 15917787081234567891011121314151617{ "backend": "tokenizers", "clean_up_tokenization_spaces": true, "cls_token": "[CLS]", "is_local": false, "local_files_only": false, "mask_token": "[MASK]", "model_input_names": [ "input_ids", "attention_mask" ], "model_max_length": 8192, "pad_token": "[PAD]", "sep_token": "[SEP]", "tokenizer_class": "TokenizersBackend", "unk_token": "[UNK]"}.eval_results/typed-decisions.yamlAdded+36
README.mdAdded+137
config.jsonAdded+97
decidabert_v2/__init__.pyAdded+3
decidabert_v2/__pycache__/__init__.cpython-313.pycAdded
decidabert_v2/__pycache__/model.cpython-313.pycAdded
decidabert_v2/model.pyAdded+162
decision_config.jsonAdded+12
decision_server.pyAdded+50
eval/typed-decisions/predictions.jsonlAdded
model.safetensorsAdded+3
tokenizer.jsonAdded
tokenizer_config.jsonAdded+17