Token Classification
Transformers
ONNX
Safetensors
Transformers.js
English
modernbert
hallucination-detection
groundedness
faithfulness
span-detection
rag
guardrails
agent-forensics
observability
tamarillo
hallucination
rag-evaluation
llm-observability
Instructions to use Tamarillo/groundedness-guard-tiny-en with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Tamarillo/groundedness-guard-tiny-en with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="Tamarillo/groundedness-guard-tiny-en")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForTokenClassification tokenizer = AutoTokenizer.from_pretrained("Tamarillo/groundedness-guard-tiny-en") model = AutoModelForTokenClassification.from_pretrained("Tamarillo/groundedness-guard-tiny-en", device_map="auto") - Transformers.js
How to use Tamarillo/groundedness-guard-tiny-en with Transformers.js:
// npm i @huggingface/transformers import { pipeline } from '@huggingface/transformers'; // Allocate pipeline const pipe = await pipeline('token-classification', 'Tamarillo/groundedness-guard-tiny-en'); - Notebooks
- Google Colab
- Kaggle
Release Tamarillo/groundedness-guard-tiny-en (Apache-2.0, zero trust_remote_code RAG/agent groundedness & hallucination guard, parity-verified ONNX)
e5f3768 verified Download scripts/train_r2_tok.py from Tamarillo/groundedness-guard-tiny-en: direct link, hf CLI and curl.
- Browser
- Download file 17.1 kB
-
https://huggingface.co/Tamarillo/groundedness-guard-tiny-en/resolve/main/scripts/train_r2_tok.py
- Command line
-
hf download hf://Tamarillo/groundedness-guard-tiny-en/scripts/train_r2_tok.py
-
curl -L -o train_r2_tok.py https://huggingface.co/Tamarillo/groundedness-guard-tiny-en/resolve/main/scripts/train_r2_tok.py
17.1 kB
| """Round-2 Bet B (`tok_span_mil`): End-to-End Multi-Granular Token-Span Architecture! | |
| Architecture: Standard `ModernBertForTokenClassification` (ZERO `trust_remote_code`, 100% compatible | |
| with `KRLabsOrg/lettucedect-v2-mmbert-base` schema `0=supported, 1=hallucinated` and ONNX!). | |
| Novel 2025-2026 Hybrid Supervision Objective (bridges span-labeled AND sequence-only NLI/RAG corpora!): | |
| 1. Exact Token-Level Cross-Entropy (`L_tok`): Supervises every hypothesis token on PsiloQA gold spans, | |
| SummEdits difflib spans, Multi-Passage Composed bad-sentence spans, Minimal-Edit CF spans, AND all | |
| consistent examples from every corpus (`Mixtral-NLI`, `WANLI`, `MultiNLI`, `MiniCheck`, `DocNLI`). | |
| 2. Weakly-Supervised Top-6 Log-Mean-Exp MIL Bag Loss (`L_mil`, beta=2.0): Supervises hypothesis bag | |
| hallucination log-odds on ALL rows (including span-free negative NLI/MiniCheck/DocNLI rows!). | |
| 3. Sharp Max-Pooling Calibration Loss (`L_max`): Aligns `max_{t in hyp} z_tok(t)` with sequence label | |
| so `1 - max_{t in hyp} P(hal_t)` (single-pass LettuceDetect inference) is sharply calibrated! | |
| 4. Same-Document Contrastive Bag Pairwise Ranking (`L_rank`, CPIL + Bradley-Terry AUC): | |
| Packs same-doc (pos, neg) pairs into the same micro-batch and optimizes bag-level ROC-AUC directly! | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import contextlib | |
| import gc | |
| import json | |
| import math | |
| import os | |
| import time | |
| from collections import defaultdict | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from sklearn.metrics import accuracy_score, f1_score, roc_auc_score | |
| from torch.utils.data import DataLoader | |
| from transformers import ( | |
| AutoConfig, | |
| AutoModelForTokenClassification, | |
| AutoTokenizer, | |
| get_cosine_schedule_with_warmup, | |
| set_seed, | |
| ) | |
| from train_mg_cpil import ( | |
| LengthBucketBatchSampler, | |
| ListDataset, | |
| _encode_dataset, | |
| _load_jsonl, | |
| _topk_lme_mil, | |
| make_collate_fn, | |
| ) | |
| TOK_ID2LABEL = {0: "supported", 1: "hallucinated"} | |
| TOK_LABEL2ID = {"supported": 0, "hallucinated": 1} | |
| def _clean_reinit_tok_head(model: nn.Module) -> None: | |
| reinit_names = [] | |
| for name, mod in model.named_modules(): | |
| if name.startswith("head") or name.startswith("classifier"): | |
| if isinstance(mod, nn.Linear): | |
| nn.init.normal_(mod.weight, mean=0.0, std=0.02) | |
| if mod.bias is not None: | |
| nn.init.zeros_(mod.bias) | |
| reinit_names.append(name) | |
| elif isinstance(mod, nn.LayerNorm): | |
| nn.init.ones_(mod.weight) | |
| if mod.bias is not None: | |
| nn.init.zeros_(mod.bias) | |
| reinit_names.append(name) | |
| print(f"[init] Cleanly re-initialized token-cls head modules: {reinit_names}") | |
| def compute_tok_mil_loss( | |
| tok_logits_2: torch.Tensor, | |
| labels: torch.Tensor, | |
| group_ids: torch.Tensor, | |
| hyp_mask: torch.Tensor, | |
| span_labels: torch.Tensor, | |
| use_pair_rank: bool = True, | |
| ) -> tuple[torch.Tensor, dict[str, float]]: | |
| logits = tok_logits_2.float() # [B, L, 2] | |
| z_hal = logits[:, :, 1] - logits[:, :, 0] # [B, L] hallucination log-odds | |
| y = labels.long() # 1=consistent, 0=hallucinated | |
| y_hal = (1 - y).float() | |
| device = logits.device | |
| # 1. Exact Token-Level CE over hypothesis tokens with known span labels (pos_weight=2.0 on hallucinated) | |
| valid_sp = (span_labels != -100) & (hyp_mask > 0.5) | |
| if valid_sp.any(): | |
| sp_t = span_labels.clamp(min=0).float() | |
| bce = F.binary_cross_entropy_with_logits( | |
| z_hal, | |
| sp_t, | |
| pos_weight=torch.tensor(2.0, device=device), | |
| reduction="none", | |
| ) * valid_sp.float() | |
| per_ex_cnt = valid_sp.float().sum(dim=1) | |
| has_ex = per_ex_cnt > 0 | |
| l_tok = (bce.sum(dim=1)[has_ex] / per_ex_cnt[has_ex]).mean() | |
| else: | |
| l_tok = torch.zeros((), device=device) | |
| # 2. Weakly-Supervised Top-6 Log-Mean-Exp MIL Bag Loss (beta=2.0) | |
| z_mil, mil_valid = _topk_lme_mil(z_hal, hyp_mask, k=6, beta=2.0) | |
| if mil_valid.any(): | |
| l_mil = F.binary_cross_entropy_with_logits(z_mil[mil_valid], y_hal[mil_valid]) | |
| # 3. Sharp Max-Pooling Calibration (matches `1 - max_t P(hal_t)` inference!) | |
| z_max = z_hal.masked_fill(hyp_mask < 0.5, -1e4).max(dim=1).values | |
| l_max = F.binary_cross_entropy_with_logits(z_max[mil_valid], y_hal[mil_valid]) | |
| # 4. Same-Document Contrastive Bag Pairwise Ranking + In-Batch AUC Ranking | |
| cons_bag = -0.5 * (z_mil + z_max) # higher = more consistent | |
| pos_m = (y == 1).unsqueeze(1) & mil_valid.unsqueeze(1) | |
| neg_m = (y == 0).unsqueeze(0) & mil_valid.unsqueeze(0) | |
| diff = cons_bag.unsqueeze(1) - cons_bag.unsqueeze(0) | |
| same_doc = (group_ids.unsqueeze(1) == group_ids.unsqueeze(0)) & (group_ids.unsqueeze(1) > 0) | |
| same_pairs = pos_m & neg_m & same_doc | |
| all_pairs = pos_m & neg_m | |
| n_same = int(same_pairs.sum().item()) | |
| if use_pair_rank and n_same > 0: | |
| l_rank_same = F.softplus(-(diff[same_pairs] - 1.0)).mean() | |
| else: | |
| l_rank_same = torch.zeros((), device=device) | |
| l_rank_auc = F.softplus(-(diff[all_pairs] - 0.5)).mean() if all_pairs.any() else torch.zeros((), device=device) | |
| l_rank = l_rank_same + 0.25 * l_rank_auc | |
| else: | |
| l_mil = l_max = l_rank = torch.zeros((), device=device) | |
| n_same = 0 | |
| total = l_tok + 0.60 * l_mil + 0.25 * l_max + (0.35 if use_pair_rank else 0.15) * l_rank | |
| return total, { | |
| "l_tok": float(l_tok.item()), | |
| "l_mil": float(l_mil.item()), | |
| "l_max": float(l_max.item()), | |
| "l_rank": float(l_rank.item()), | |
| "same_pairs": n_same, | |
| } | |
| def evaluate_tok(model: nn.Module, val_loader: DataLoader, device: str, use_bf16: bool) -> dict[str, float]: | |
| model.eval() | |
| p_max_list, p_mil_list, y_list = [], [], [] | |
| dtype = torch.bfloat16 if use_bf16 else torch.float16 | |
| for batch in val_loader: | |
| input_ids = batch["input_ids"].to(device, non_blocking=True) | |
| attention_mask = batch["attention_mask"].to(device, non_blocking=True) | |
| hyp_mask = batch["hyp_mask"].to(device, non_blocking=True) | |
| with torch.amp.autocast("cuda", dtype=dtype) if device == "cuda" else contextlib.nullcontext(): | |
| logits = model(input_ids=input_ids, attention_mask=attention_mask).logits.float() | |
| probs_hal = torch.softmax(logits, dim=-1)[:, :, 1] # [B, L] | |
| max_hal = probs_hal.masked_fill(hyp_mask < 0.5, 0.0).max(dim=1).values | |
| p_cons_max = (1.0 - max_hal).cpu().numpy() | |
| z_hal = logits[:, :, 1] - logits[:, :, 0] | |
| z_mil, _ = _topk_lme_mil(z_hal, hyp_mask, k=6, beta=2.0) | |
| p_cons_mil = (1.0 - torch.sigmoid(z_mil)).cpu().numpy() | |
| p_max_list.append(p_cons_max) | |
| p_mil_list.append(p_cons_mil) | |
| y_list.append(batch["labels"].numpy()) | |
| p1 = np.concatenate(p_max_list, axis=0) | |
| p1_mil = np.concatenate(p_mil_list, axis=0) | |
| y = np.concatenate(y_list, axis=0).astype(int) | |
| pred = (p1 >= 0.5).astype(int) | |
| acc = float(accuracy_score(y, pred)) | |
| macro_f1 = float(f1_score(y, pred, average="macro", zero_division=0)) | |
| hal_f1 = float(f1_score(1 - y, 1 - pred, zero_division=0)) | |
| cons_f1 = float(f1_score(y, pred, zero_division=0)) | |
| auc = float(roc_auc_score(y, p1)) if len(set(y.tolist())) == 2 else 0.5 | |
| auc_mil = float(roc_auc_score(y, p1_mil)) if len(set(y.tolist())) == 2 else 0.5 | |
| model.train() | |
| return { | |
| "accuracy": round(acc, 5), | |
| "macro_f1": round(macro_f1, 5), | |
| "hal_f1": round(hal_f1, 5), | |
| "consistent_f1": round(cons_f1, 5), | |
| "roc_auc": round(auc, 5), | |
| "roc_auc_mil": round(auc_mil, 5), | |
| "selection_score": round(0.45 * macro_f1 + 0.55 * auc, 5), | |
| } | |
| def _run_stage( | |
| stage_name: str, | |
| model: nn.Module, | |
| train_enc: list[dict[str, Any]], | |
| val_loader: DataLoader, | |
| pad_id: int, | |
| tokenizer: Any, | |
| out_dir: Path, | |
| device: str, | |
| use_bf16: bool, | |
| epochs: float, | |
| lr: float, | |
| batch_size: int, | |
| grad_accum: int, | |
| paired: bool, | |
| seed: int, | |
| best_score: float, | |
| best_metrics: dict[str, float], | |
| val_history: list[dict[str, Any]], | |
| ) -> tuple[float, dict[str, float]]: | |
| sampler = LengthBucketBatchSampler(train_enc, batch_size=batch_size, paired=paired, seed=seed) | |
| loader = DataLoader( | |
| ListDataset(train_enc), | |
| batch_sampler=sampler, | |
| collate_fn=make_collate_fn(pad_id, with_spans=True), | |
| num_workers=4, | |
| pin_memory=(device == "cuda"), | |
| ) | |
| steps_per_epoch = max(1, math.ceil(len(loader) / grad_accum)) | |
| total_steps = max(1, int(math.ceil(steps_per_epoch * epochs))) | |
| warmup_steps = max(100, int(0.10 * total_steps)) | |
| eval_every = max(200, steps_per_epoch // 2) | |
| no_decay = ("bias", "LayerNorm.weight", "norm.weight") | |
| param_groups = [ | |
| {"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], "lr": lr, "weight_decay": 0.01}, | |
| {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "lr": lr, "weight_decay": 0.0}, | |
| ] | |
| optimizer = torch.optim.AdamW(param_groups, betas=(0.9, 0.999), eps=1e-8) | |
| scheduler = get_cosine_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps, num_training_steps=total_steps) | |
| amp_dtype = torch.bfloat16 if use_bf16 else torch.float16 | |
| scaler = torch.amp.GradScaler("cuda", enabled=(device == "cuda" and not use_bf16)) | |
| print(f"[{stage_name}] Start Token-Span MIL: rows={len(train_enc):,}, steps={total_steps}, warmup={warmup_steps}, lr={lr}") | |
| t0 = time.time() | |
| global_step = 0 | |
| running = defaultdict(float) | |
| running_n = 0 | |
| model.train() | |
| optimizer.zero_grad(set_to_none=True) | |
| for ep in range(int(math.ceil(epochs))): | |
| sampler.set_epoch(ep) | |
| accum_cnt = 0 | |
| for step_idx, batch in enumerate(loader): | |
| if global_step >= total_steps: | |
| break | |
| input_ids = batch["input_ids"].to(device, non_blocking=True) | |
| attention_mask = batch["attention_mask"].to(device, non_blocking=True) | |
| labels = batch["labels"].to(device, non_blocking=True) | |
| with torch.amp.autocast("cuda", dtype=amp_dtype) if device == "cuda" else contextlib.nullcontext(): | |
| logits = model(input_ids=input_ids, attention_mask=attention_mask).logits | |
| loss, st = compute_tok_mil_loss( | |
| tok_logits_2=logits, | |
| labels=labels, | |
| group_ids=batch["group_ids"].to(device, non_blocking=True), | |
| hyp_mask=batch["hyp_mask"].to(device, non_blocking=True), | |
| span_labels=batch["span_labels"].to(device, non_blocking=True), | |
| use_pair_rank=paired, | |
| ) | |
| for k, v in st.items(): | |
| running[k] += v | |
| running["loss"] += float(loss.item()) | |
| running_n += 1 | |
| scaled = loss / grad_accum | |
| if scaler.is_enabled(): | |
| scaler.scale(scaled).backward() | |
| else: | |
| scaled.backward() | |
| accum_cnt += 1 | |
| if accum_cnt == grad_accum or (step_idx + 1 == len(loader)): | |
| if scaler.is_enabled(): | |
| scaler.unscale_(optimizer) | |
| gnorm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0).item()) | |
| if scaler.is_enabled(): | |
| scaler.step(optimizer) | |
| scaler.update() | |
| else: | |
| optimizer.step() | |
| scheduler.step() | |
| optimizer.zero_grad(set_to_none=True) | |
| accum_cnt = 0 | |
| global_step += 1 | |
| if global_step % 150 == 0 or global_step == 10: | |
| avg = {k: round(v / max(1, running_n), 4) for k, v in running.items()} | |
| print( | |
| f"[{stage_name} {global_step:4d}/{total_steps}] lr={scheduler.get_last_lr()[0]:.2e} " | |
| f"gnorm={gnorm:.2f} elapsed={time.time() - t0:.0f}s {avg}", | |
| flush=True, | |
| ) | |
| running.clear() | |
| running_n = 0 | |
| if global_step % eval_every == 0 or global_step == total_steps: | |
| vm = evaluate_tok(model, val_loader, device, use_bf16) | |
| vm["stage"] = stage_name | |
| vm["step"] = global_step | |
| val_history.append(vm) | |
| print(f"[val {stage_name} @ {global_step}] {json.dumps(vm)}", flush=True) | |
| if vm["selection_score"] > best_score and stage_name == "stage2": | |
| best_score = vm["selection_score"] | |
| best_metrics = dict(vm) | |
| model.save_pretrained(str(out_dir), safe_serialization=True) | |
| tokenizer.save_pretrained(str(out_dir)) | |
| print(f"[ckpt] New best stage2 selection_score={best_score:.5f} saved!", flush=True) | |
| return best_score, best_metrics | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--base-model", type=str, default="jhu-clsp/mmBERT-small") | |
| parser.add_argument("--data-dir", type=str, required=True) | |
| parser.add_argument("--output-dir", type=str, required=True) | |
| parser.add_argument("--max-length", type=int, default=3584) | |
| parser.add_argument("--seed", type=int, default=42) | |
| args = parser.parse_args() | |
| os.environ.setdefault("HF_HOME", "/tmp/hf") | |
| os.environ["TOKENIZERS_PARALLELISM"] = "true" | |
| os.environ["TORCH_COMPILE_DISABLE"] = "1" | |
| if hasattr(torch, "_dynamo"): | |
| torch._dynamo.config.disable = True | |
| set_seed(args.seed) | |
| data_dir = Path(args.data_dir) | |
| out_dir = Path(args.output_dir) | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| tokenizer = AutoTokenizer.from_pretrained(args.base_model, use_fast=True) | |
| cfg = AutoConfig.from_pretrained( | |
| args.base_model, | |
| num_labels=2, | |
| id2label=TOK_ID2LABEL, | |
| label2id=TOK_LABEL2ID, | |
| ) | |
| if hasattr(cfg, "reference_compile"): | |
| cfg.reference_compile = False | |
| model = AutoModelForTokenClassification.from_pretrained(args.base_model, config=cfg, ignore_mismatched_sizes=True) | |
| _clean_reinit_tok_head(model) | |
| if hasattr(model, "gradient_checkpointing_enable"): | |
| model.gradient_checkpointing_enable() | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| use_bf16 = device == "cuda" and torch.cuda.is_bf16_supported() | |
| model.to(device) | |
| pad_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else 0 | |
| val_rows = _load_jsonl(data_dir / "val.jsonl") | |
| val_enc = _encode_dataset(val_rows, tokenizer, args.max_length, with_spans=True) | |
| del val_rows | |
| val_loader = DataLoader( | |
| ListDataset(val_enc), | |
| batch_sampler=LengthBucketBatchSampler(val_enc, batch_size=32, paired=False, seed=args.seed), | |
| collate_fn=make_collate_fn(pad_id, with_spans=True), | |
| num_workers=2, | |
| pin_memory=(device == "cuda"), | |
| ) | |
| t0 = time.time() | |
| best_score = -1.0 | |
| best_metrics: dict[str, float] = {} | |
| val_history: list[dict[str, Any]] = [] | |
| # STAGE 1: Semantic NLI Foundation via Weakly-Supervised MIL + Exact Supported Tokens (1.0 ep, lr=3.5e-5) | |
| s1_rows = _load_jsonl(data_dir / "stage1_nli.jsonl") | |
| s1_enc = _encode_dataset(s1_rows, tokenizer, 1024, with_spans=True) | |
| del s1_rows | |
| gc.collect() | |
| best_score, best_metrics = _run_stage( | |
| "stage1", model, s1_enc, val_loader, pad_id, tokenizer, out_dir, device, use_bf16, | |
| epochs=1.0, lr=3.5e-5, batch_size=32, grad_accum=2, paired=False, seed=args.seed, | |
| best_score=best_score, best_metrics=best_metrics, val_history=val_history, | |
| ) | |
| del s1_enc | |
| gc.collect() | |
| # STAGE 2: Length-Debiased Multilingual Groundedness Hybrid Span + MIL + Bag Ranking (2.0 ep, lr=2.5e-5) | |
| s2_rows = _load_jsonl(data_dir / "stage2_grounded.jsonl") | |
| s2_enc = _encode_dataset(s2_rows, tokenizer, args.max_length, with_spans=True) | |
| del s2_rows | |
| gc.collect() | |
| best_score, best_metrics = _run_stage( | |
| "stage2", model, s2_enc, val_loader, pad_id, tokenizer, out_dir, device, use_bf16, | |
| epochs=2.0, lr=2.5e-5, batch_size=16, grad_accum=4, paired=True, seed=args.seed + 17, | |
| best_score=best_score, best_metrics=best_metrics, val_history=val_history, | |
| ) | |
| summary = { | |
| "method": "r2_tok_span_mil", | |
| "base_model": args.base_model, | |
| "architecture": "ModernBertForTokenClassification", | |
| "train_runtime_sec": round(time.time() - t0, 1), | |
| "best_val_metrics": best_metrics, | |
| "val_history": val_history, | |
| } | |
| (out_dir / "training_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8") | |
| print("[train:r2_tok] DONE!", json.dumps(best_metrics, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |