From 2d1e37ac8338c32c11fcda6481c8ba2fb130f286 Mon Sep 17 00:00:00 2001 From: Ingvar Date: Sat, 31 Oct 2026 16:26:36 +0200 Subject: [PATCH 1/6] add cross entropy loss with temperature --- gliner/__init__.py | 2 +- gliner/calibration.py | 330 ++++++++++++++++++++++++++++++ gliner/config.py | 14 ++ gliner/decoding/decoder.py | 27 +-- gliner/model.py | 3 +- gliner/modeling/base.py | 281 +++++++++++++++++++++++-- gliner/modeling/loss_functions.py | 72 +++++++ gliner/training/trainer.py | 12 ++ 8 files changed, 714 insertions(+), 27 deletions(-) create mode 100644 gliner/calibration.py diff --git a/gliner/__init__.py b/gliner/__init__.py index a2d75dcf..9c8914d7 100644 --- a/gliner/__init__.py +++ b/gliner/__init__.py @@ -1,4 +1,4 @@ -__version__ = "0.2.29" +__version__ = "0.2.30" from .model import GLiNER from .config import GLiNERConfig, StreamingSpanConfig diff --git a/gliner/calibration.py b/gliner/calibration.py new file mode 100644 index 00000000..5c2ae0c3 --- /dev/null +++ b/gliner/calibration.py @@ -0,0 +1,330 @@ +"""Post-hoc probability calibration for GLiNER. + +A trained model's logits ``s`` are mapped to probabilities with + + p = sigmoid(s / T + b) + +where the temperature ``T`` and bias ``b`` live on the model config +(``logit_temperature`` / ``logit_bias`` for entities and +``rel_logit_temperature`` / ``rel_logit_bias`` for relations). The defaults +``T=1, b=0`` leave predictions unchanged. Every decoder goes through +:func:`calibrated_sigmoid`, so a calibrated config changes the scores (and, +with ``b != 0``, which spans pass the threshold) without touching the weights. + +:func:`fit_logit_calibration` fits ``T`` (and optionally ``b``) on held-out +logits while the model stays frozen; ``scripts/calibrate.py`` runs it end to end. +""" + +from __future__ import annotations + +import math +import random +import logging +import numbers +from typing import Any, Dict, List, Tuple, Iterable, Sequence + +import torch +import torch.nn.functional as F + +logger = logging.getLogger(__name__) + +_CALIBRATION_ATTRS = { + "entity": ("logit_temperature", "logit_bias"), + "relation": ("rel_logit_temperature", "rel_logit_bias"), +} + + +def get_logit_calibration(config: Any, kind: str = "entity") -> Tuple[float, float]: + """Return ``(temperature, bias)`` stored on ``config`` for ``kind`` ('entity' or 'relation').""" + temp_attr, bias_attr = _CALIBRATION_ATTRS[kind] + temperature = getattr(config, temp_attr, None) + bias = getattr(config, bias_attr, None) + # Missing or non-numeric values (old configs, mocks) mean "uncalibrated". + temperature = float(temperature) if isinstance(temperature, numbers.Real) else 1.0 + bias = float(bias) if isinstance(bias, numbers.Real) else 0.0 + if temperature <= 0: + raise ValueError(f"{temp_attr} must be positive, got {temperature}") + return temperature, bias + + +def apply_logit_calibration(logits: torch.Tensor, config: Any, kind: str = "entity") -> torch.Tensor: + """Return ``logits / T + b``; returns ``logits`` itself when uncalibrated.""" + temperature, bias = get_logit_calibration(config, kind) + if temperature == 1.0 and bias == 0.0: + return logits + return logits / temperature + bias + + +def calibrated_sigmoid(logits: torch.Tensor, config: Any, kind: str = "entity") -> torch.Tensor: + """Sigmoid of calibrated logits. Drop-in replacement for ``torch.sigmoid`` in decoders.""" + return torch.sigmoid(apply_logit_calibration(logits, config, kind)) + + +def set_logit_calibration(config: Any, temperature: float, bias: float = 0.0, kind: str = "entity") -> None: + """Store ``(temperature, bias)`` on ``config`` for ``kind``.""" + if temperature <= 0: + raise ValueError(f"temperature must be positive, got {temperature}") + temp_attr, bias_attr = _CALIBRATION_ATTRS[kind] + setattr(config, temp_attr, float(temperature)) + setattr(config, bias_attr, float(bias)) + + +# --------------------------------------------------------------------------- +# Fitting and metrics +# --------------------------------------------------------------------------- + + +def fit_logit_calibration( + logits: torch.Tensor, + labels: torch.Tensor, + weights: torch.Tensor | None = None, + fit_bias: bool = False, + max_iter: int = 200, + device: str | torch.device | None = None, +) -> Tuple[float, float]: + """Fit temperature (and optionally bias) by minimising weighted BCE on frozen logits. + + Args: + logits: 1-D tensor of raw logits for (row, class) entries. + labels: 1-D tensor of {0, 1} targets, same length. + weights: Optional 1-D importance weights (e.g. ``1 / keep_prob`` for + subsampled negatives). + fit_bias: Also fit an additive bias ``b``. Changes which entries + pass a fixed threshold; with ``False`` only confidence changes. + max_iter: L-BFGS iterations. + device: Device for the optimisation. Defaults to ``logits.device``. + + Returns: + ``(temperature, bias)``. + """ + device = device or logits.device + x = logits.detach().to(device=device, dtype=torch.float64) + y = labels.detach().to(device=device, dtype=torch.float64) + w = None if weights is None else weights.detach().to(device=device, dtype=torch.float64) + + # Parametrise log T so the temperature stays positive. + log_t = torch.zeros((), dtype=torch.float64, device=device, requires_grad=True) + bias = torch.zeros((), dtype=torch.float64, device=device, requires_grad=fit_bias) + params = [log_t, bias] if fit_bias else [log_t] + optimizer = torch.optim.LBFGS(params, lr=0.5, max_iter=max_iter, line_search_fn="strong_wolfe") + + def closure(): + optimizer.zero_grad() + loss = _weighted_bce(x / log_t.exp() + bias, y, w) + loss.backward() + return loss + + optimizer.step(closure) + return float(log_t.exp().item()), float(bias.item()) + + +def _weighted_bce(logits: torch.Tensor, labels: torch.Tensor, weights: torch.Tensor | None) -> torch.Tensor: + loss = F.binary_cross_entropy_with_logits(logits, labels, reduction="none") + if weights is None: + return loss.mean() + return (loss * weights).sum() / weights.sum() + + +def calibration_metrics( + logits: torch.Tensor, + labels: torch.Tensor, + weights: torch.Tensor | None = None, + temperature: float = 1.0, + bias: float = 0.0, + n_bins: int = 15, + threshold: float = 0.5, + min_confidence: float = 0.1, +) -> Dict[str, float]: + """Calibration and thresholded quality metrics over (row, class) entries. + + Returns NLL, Brier score, expected calibration error (ECE) over all + entries, ECE restricted to entries with ``p >= min_confidence`` (the + region where thresholds act; the full ECE is dominated by easy + negatives), and entry-level precision / recall / F1 at ``threshold``. + """ + x = logits.detach().double() + y = labels.detach().double() + w = torch.ones_like(x) if weights is None else weights.detach().double() + + z = x / temperature + bias + p = torch.sigmoid(z) + + total = w.sum() + nll = (F.binary_cross_entropy_with_logits(z, y, reduction="none") * w).sum() / total + brier = (((p - y) ** 2) * w).sum() / total + + pred = p > threshold + tp = (w * (pred & (y > 0.5))).sum() + fp = (w * (pred & (y <= 0.5))).sum() + fn = (w * (~pred & (y > 0.5))).sum() + precision = tp / (tp + fp) if tp + fp > 0 else torch.tensor(0.0) + recall = tp / (tp + fn) if tp + fn > 0 else torch.tensor(0.0) + f1 = 2 * precision * recall / (precision + recall) if precision + recall > 0 else torch.tensor(0.0) + + confident = p >= min_confidence + return { + "nll": float(nll), + "brier": float(brier), + "ece": _ece(p, y, w, n_bins), + "ece_confident": _ece(p[confident], y[confident], w[confident], n_bins), + "precision": float(precision), + "recall": float(recall), + "f1": float(f1), + "num_entries": float(total), + "num_positives": float((w * y).sum()), + } + + +def _ece(p: torch.Tensor, y: torch.Tensor, w: torch.Tensor, n_bins: int) -> float: + total = w.sum() + if p.numel() == 0 or total <= 0: + return float("nan") + bins = torch.clamp((p * n_bins).long(), max=n_bins - 1) + ece = torch.zeros((), dtype=torch.float64) + for b in range(n_bins): + in_bin = bins == b + bw = w[in_bin].sum() + if bw <= 0: + continue + conf = (p[in_bin] * w[in_bin]).sum() / bw + acc = (y[in_bin] * w[in_bin]).sum() / bw + ece += bw / total * (conf - acc).abs() + return float(ece) + + +# --------------------------------------------------------------------------- +# Logit collection from a frozen GLiNER model +# --------------------------------------------------------------------------- + + +def dataset_entity_types(data: Iterable[Dict[str, Any]], key: str = "ner") -> List[str]: + """Sorted union of entity labels in a GLiNER-format dataset.""" + labels = set() + for example in data: + labels.update(str(ent[-1]) for ent in example.get(key, [])) + labels.update(example.get(f"{key}_labels", [])) + labels.update(example.get(f"{key}_negatives", [])) + return sorted(labels) + + +def freeze_model(model: torch.nn.Module) -> None: + """Put ``model`` in eval mode and disable gradients for all its parameters.""" + model.eval() + for param in model.parameters(): + param.requires_grad_(False) + + +def _entity_entries(output: Any, batch: Dict[str, Any]) -> Tuple[torch.Tensor, torch.Tensor]: + """Flatten (logits, labels) of valid (row, class) entries from one forward pass.""" + logits = output.logits + labels = batch["labels"] + class_mask = output.prompts_embedding_mask.bool() # (B, C) + B = logits.size(0) + + if logits.dim() == 4 and labels.dim() == 4: + # Token-level: (B, W, C, 3) start / end / inside. + W = min(logits.size(1), labels.size(1)) + C = min(logits.size(2), labels.size(2), class_mask.size(1)) + logits, labels = logits[:, :W, :C], labels[:, :W, :C] + word_mask = output.mask[:, :W].bool() + valid = word_mask[:, :, None, None] & class_mask[:, None, :C, None] + valid = valid.expand_as(logits) + else: + # Span-level: logits (B, L, K, C) or (B, S, C); labels (B, S, C). + logits = logits.reshape(B, -1, logits.size(-1)) + S = min(logits.size(1), labels.size(1)) + C = min(logits.size(2), labels.size(2), class_mask.size(1)) + logits, labels = logits[:, :S, :C], labels[:, :S, :C] + span_mask = batch.get("span_mask") + if span_mask is None: + span_mask = torch.ones(B, S, dtype=torch.bool, device=logits.device) + span_mask = span_mask.reshape(B, -1)[:, :S].bool() + valid = span_mask[:, :, None] & class_mask[:, None, :C] + + valid = valid & (labels >= 0) & torch.isfinite(logits) + return logits[valid].float(), labels[valid].float() + + +@torch.inference_mode() +def collect_entity_logits( + model: Any, + data: Sequence[Dict[str, Any]], + batch_size: int = 8, + entity_types: Sequence[str] | None = None, + labels_per_pass: int | None = None, + neg_keep_prob: float = 1.0, + seed: int = 42, + show_progress: bool = True, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Run a frozen GLiNER model over a labelled dataset and gather entity logits. + + Args: + model: A torch-runtime GLiNER model (``GLiNER.from_pretrained(...)``). + data: GLiNER-format examples: ``{"tokenized_text": [...], "ner": [[start, end, label], ...]}``. + batch_size: Examples per forward pass. + entity_types: Fixed label set given to every example (mirrors + inference). ``None`` uses training-style per-example labels + (gold types plus sampled in-batch negatives). + labels_per_pass: Split ``entity_types`` into chunks of this size, + one forward pass per chunk. ``None`` uses all labels at once. + neg_keep_prob: Keep each negative entry with this probability (to save + memory); kept negatives get weight ``1 / neg_keep_prob``. + seed: Seed for negative subsampling and label sampling. + show_progress: Log progress at INFO level. + + Returns: + ``(logits, labels, weights)``: 1-D CPU tensors over valid entries. + """ + if getattr(model, "is_runtime_model", False): + raise ValueError("Calibration needs a torch-runtime model; load it without ONNX/OpenVINO.") + if not 0.0 < neg_keep_prob <= 1.0: + raise ValueError("neg_keep_prob must be in (0, 1]") + + random.seed(seed) + generator = torch.Generator().manual_seed(seed) + collator = model._create_data_collator() + device = model.device + + label_chunks: List[List[str] | None] + if entity_types is None: + label_chunks = [None] + else: + entity_types = list(entity_types) + step = labels_per_pass or len(entity_types) or 1 + label_chunks = [entity_types[i : i + step] for i in range(0, len(entity_types), step)] + + all_logits, all_labels, all_weights = [], [], [] + num_batches = math.ceil(len(data) / batch_size) * len(label_chunks) + done = 0 + for chunk in label_chunks: + for start in range(0, len(data), batch_size): + examples = list(data[start : start + batch_size]) + if chunk is None: + batch = collator(examples) + else: + batch = collator(examples, entity_types=[list(chunk) for _ in examples]) + batch = {k: v.to(device) if torch.is_tensor(v) else v for k, v in batch.items()} + + output = model(**batch) + logits, labels = _entity_entries(output, batch) + logits, labels = logits.cpu(), labels.cpu() + + weights = torch.ones_like(logits) + if neg_keep_prob < 1.0: + is_neg = labels < 0.5 + keep = ~is_neg | (torch.rand(logits.shape, generator=generator) < neg_keep_prob) + logits, labels = logits[keep], labels[keep] + weights = torch.where(is_neg[keep], 1.0 / neg_keep_prob, 1.0) + + all_logits.append(logits) + all_labels.append(labels) + all_weights.append(weights) + + done += 1 + if show_progress and (done % 10 == 0 or done == num_batches): + logger.info("collected %d/%d batches", done, num_batches) + + if not all_logits: + empty = torch.zeros(0) + return empty, empty, empty + return torch.cat(all_logits), torch.cat(all_labels), torch.cat(all_weights) diff --git a/gliner/config.py b/gliner/config.py index 7cfc0148..d024df68 100644 --- a/gliner/config.py +++ b/gliner/config.py @@ -157,6 +157,10 @@ def __init__( # noqa: PLR0917, RUF100 neg_spans_ratio: float = 1.0, precomputed_prompts_mode: bool | None = None, id_to_classes: dict | None = None, + logit_temperature: float = 1.0, + logit_bias: float = 0.0, + rel_logit_temperature: float = 1.0, + rel_logit_bias: float = 0.0, **kwargs, ): """Initialize BaseGLiNERConfig. @@ -195,6 +199,12 @@ def __init__( # noqa: PLR0917, RUF100 neg_spans_ratio (float, optional): Ratio of negative spans. Defaults to 1.0. precomputed_prompts_mode (Optional[bool]): Whether to use precomputed prompts. Defaults to None. id_to_classes (Optional[dict]): Mapping from class IDs to class names. Defaults to None. + logit_temperature (float, optional): Post-hoc calibration temperature for entity + logits; probabilities are ``sigmoid(logit / T + b)``. Defaults to 1.0. + logit_bias (float, optional): Post-hoc calibration bias for entity logits. Defaults to 0.0. + rel_logit_temperature (float, optional): Calibration temperature for relation logits. + Defaults to 1.0. + rel_logit_bias (float, optional): Calibration bias for relation logits. Defaults to 0.0. **kwargs: Additional keyword arguments passed to parent class. """ super().__init__(**kwargs) @@ -241,6 +251,10 @@ def __init__( # noqa: PLR0917, RUF100 self.neg_spans_ratio = neg_spans_ratio self.precomputed_prompts_mode = precomputed_prompts_mode self.id_to_classes = id_to_classes + self.logit_temperature = logit_temperature + self.logit_bias = logit_bias + self.rel_logit_temperature = rel_logit_temperature + self.rel_logit_bias = rel_logit_bias class UniEncoderConfig(BaseGLiNERConfig): diff --git a/gliner/decoding/decoder.py b/gliner/decoding/decoder.py index 2345dce7..b5f3ef4b 100644 --- a/gliner/decoding/decoder.py +++ b/gliner/decoding/decoder.py @@ -6,6 +6,7 @@ import torch from .utils import has_overlapping, has_overlapping_nested +from ..calibration import calibrated_sigmoid def _expand_batch_param(value, batch_size: int, name: str) -> list: @@ -640,7 +641,7 @@ class IDs to class names. Can be a single dict (shared) or list (per-sample). List[List[Span]]: For each sample in batch, list of Span objects. """ B, _, K, _ = model_output.shape # B, L, K, C - probs = torch.sigmoid(model_output) + probs = calibrated_sigmoid(model_output, self.config) span_label_maps = [{} for _ in range(B)] @@ -717,7 +718,7 @@ def _decode_explicit_spans( input_spans=None, ): """Decode logits paired with explicit absolute span boundaries.""" - probabilities = torch.sigmoid(model_output) + probabilities = calibrated_sigmoid(model_output, self.config) if probabilities.dim() == 4: probabilities = probabilities.flatten(1, 2) span_idx = span_idx.view(span_idx.size(0), -1, 2) @@ -1039,7 +1040,7 @@ class IDs to class names. List[List[tuple]]: For each sample, list of span tuples with generated labels. """ B, _, K, _ = model_output.shape # B, L, K, C - probs = torch.sigmoid(model_output) + probs = calibrated_sigmoid(model_output, self.config) # Handle prompt mode: update id_to_classes with generated labels if self.config.decoder_mode == "prompt": @@ -1149,6 +1150,7 @@ def _decode_relations_batch( spans: List[List[tuple]], rel_id_to_classes: Dict[int, str] | List[Dict[int, str]], batch_size: int, + config: Any = None, ) -> List[List[tuple]]: """Vectorized relation decoding shared by Span and Token relex decoders. @@ -1164,6 +1166,7 @@ def _decode_relations_batch( spans: Per-sample span lists used for bounds checking. rel_id_to_classes: Class-id -> label mapping (global dict or per-sample list). batch_size: Number of samples in the batch. + config: Optional model config carrying relation calibration (temperature / bias). Returns: List of relation lists, one per sample. Each relation is a tuple @@ -1176,7 +1179,7 @@ def _decode_relations_batch( ] # 1. Sigmoid — one kernel - rel_probs = torch.sigmoid(rel_logits) + rel_probs = calibrated_sigmoid(rel_logits, config, kind="relation") num_classes = rel_probs.shape[-1] if any(len(mapping) < num_classes for mapping in rel_id_to_class_per_item): @@ -1386,7 +1389,7 @@ def _decode_relations( rel_id_to_class_per_item = [self._get_id_to_class_for_sample(rel_id_to_classes, i) for i in range(batch_size)] - rel_probs = torch.sigmoid(rel_logits) + rel_probs = calibrated_sigmoid(rel_logits, self.config, kind="relation") num_classes = rel_probs.shape[-1] if any(len(mapping) < num_classes for mapping in rel_id_to_class_per_item): valid_classes = _get_valid_classes_mask(num_classes, rel_id_to_class_per_item, rel_probs.device) @@ -1558,7 +1561,7 @@ def _get_indices_above_threshold(self, scores: torch.Tensor, threshold: float) - Returns: List[torch.Tensor]: List of tensors containing indices above threshold. """ - scores = torch.sigmoid(scores) + scores = calibrated_sigmoid(scores, self.config) return [k.tolist() for k in torch.where(scores > threshold)] def _calculate_span_score( @@ -1669,7 +1672,7 @@ class IDs to class names. spans = [] # Apply sigmoid to get probabilities - span_probs = torch.sigmoid(span_logits) + span_probs = calibrated_sigmoid(span_logits, self.config) # Batch CPU transfer to avoid per-element .item() sync span_idx_cpu = span_idx.tolist() @@ -1820,9 +1823,9 @@ class IDs to class names. span_scores = self._calculate_span_score( self._get_indices_above_threshold(start_i, threshold_i), self._get_indices_above_threshold(end_i, threshold_i), - torch.sigmoid(inside_i), - torch.sigmoid(start_i), - torch.sigmoid(end_i), + calibrated_sigmoid(inside_i, self.config), + calibrated_sigmoid(start_i, self.config), + calibrated_sigmoid(end_i, self.config), id_to_class_i, threshold_i, input_spans_i=input_spans_i, @@ -1940,7 +1943,7 @@ def _decode_relations( rel_id_to_class_per_item = [self._get_id_to_class_for_sample(rel_id_to_classes, i) for i in range(batch_size)] - rel_probs = torch.sigmoid(rel_logits) + rel_probs = calibrated_sigmoid(rel_logits, self.config, kind="relation") num_classes = rel_probs.shape[-1] if any(len(mapping) < num_classes for mapping in rel_id_to_class_per_item): valid_classes = _get_valid_classes_mask(num_classes, rel_id_to_class_per_item, rel_probs.device) @@ -2195,7 +2198,7 @@ class IDs to class names. multi_label_values = _expand_batch_param(multi_label, batch_size, "multi_label") spans = [] - span_probs = torch.sigmoid(span_logits) + span_probs = calibrated_sigmoid(span_logits, self.config) # Batch CPU transfer to avoid per-element .item() sync span_idx_cpu = span_idx.tolist() diff --git a/gliner/model.py b/gliner/model.py index ac218c4b..00f8d088 100644 --- a/gliner/model.py +++ b/gliner/model.py @@ -2493,7 +2493,8 @@ def create_training_args( # noqa: PLR0917, RUF100 bf16: Whether to use bfloat16. dataloader_num_workers: Number of dataloader workers. report_to: Where to report metrics. - **kwargs: Additional training arguments. + **kwargs: Additional training arguments, e.g. ``loss_type`` + ('focal', 'bce', 'dice', 'ce', 'ce_calibrated') and ``ce_calib_weight``. Returns: TrainingArguments instance. diff --git a/gliner/modeling/base.py b/gliner/modeling/base.py index 334e3610..60897294 100644 --- a/gliner/modeling/base.py +++ b/gliner/modeling/base.py @@ -45,7 +45,14 @@ ) from .scorers import Scorer from .span_rep import SpanRepLayer -from .loss_functions import span_dice_loss, cross_entropy_loss, focal_loss_with_logits +from ..calibration import calibrated_sigmoid, apply_logit_calibration +from .loss_functions import ( + CE_LOSS_TYPES, + span_dice_loss, + cross_entropy_loss, + focal_loss_with_logits, + calibrated_ce_with_logits, +) from .multitask.triples_layers import TriplesScoreLayer from .multitask.relations_layers import RelationsRepLayer @@ -281,6 +288,119 @@ def _loss( return all_losses + def _ce_loss( + self, + logits: torch.Tensor, + labels: torch.Tensor, + class_mask: torch.Tensor | None = None, + row_mask: torch.Tensor | None = None, + reduction: str = "sum", + negatives: float = 1.0, + masking: str = "none", + loss_type: str = "ce_calibrated", + ce_calib_weight: float = 0.5, + pos_weight: torch.Tensor | None = None, + alpha: float = -1.0, + gamma: float = 0.0, + prob_margin: float = 0.0, + label_smoothing: float = 0.0, + **kwargs: Any, + ) -> torch.Tensor: + """Reduce the calibrated cross-entropy loss over rows (spans, tokens or pairs). + + Classes must be on the last dimension. Unlike the elementwise losses, + padded classes are excluded *inside* the softmax, so they are passed in + as ``class_mask`` instead of being multiplied in afterwards. + + Args: + logits: Logits of shape (B, ..., C). + labels: Labels of shape (B, ..., C). + class_mask: Mask broadcastable to ``logits`` marking valid classes. + row_mask: Mask broadcastable to ``logits.shape[:-1]`` marking valid rows. + reduction: 'sum' or 'mean' (mean over valid rows). + negatives: Keep probability for negatives under ``masking``. + masking: Negative sampling strategy: 'none', 'global', 'label' or 'span'. + loss_type: 'ce' (no calibration term) or 'ce_calibrated'. + ce_calib_weight: Weight of the BCE calibration term for 'ce_calibrated'. + pos_weight: Optional weights broadcastable to ``logits`` for positive terms. + alpha: Focal-loss alpha; ignored (warns if set). + gamma: Focal-loss gamma; ignored (warns if set). + prob_margin: Probability margin; ignored (warns if set). + label_smoothing: Label smoothing; ignored (warns if set). + **kwargs: Unused. + + Returns: + Scalar loss tensor. + """ + if gamma > 0 or alpha >= 0 or prob_margin > 0 or label_smoothing > 0: + warnings.warn( + f"loss_type='{loss_type}' ignores focal alpha/gamma, prob_margin and label_smoothing.", + stacklevel=2, + ) + + valid = torch.ones_like(logits, dtype=torch.bool) + if class_mask is not None: + valid = valid & class_mask.bool() + if row_mask is not None: + valid = valid & row_mask.bool().unsqueeze(-1) + + if negatives < 1.0 and masking in ("global", "label", "span"): + is_pos = labels > 0.5 + if masking == "global": + drop = ~is_pos & (torch.rand_like(logits, dtype=torch.float) >= negatives) + elif masking == "label": + # Classes with no positive anywhere in the sample. + neg_cls = ~is_pos.flatten(1, -2).any(dim=1) # (B, C) + neg_cls = neg_cls.view(neg_cls.size(0), *([1] * (logits.dim() - 2)), neg_cls.size(-1)) + drop = neg_cls.expand_as(is_pos) & (torch.rand_like(neg_cls, dtype=torch.float) >= negatives) + else: + # Rows (spans) with no positive class. + neg_row = ~is_pos.any(dim=-1, keepdim=True) + drop = neg_row & (torch.rand_like(neg_row, dtype=torch.float) >= negatives) + valid = valid & ~drop + + calib_weight = ce_calib_weight if loss_type == "ce_calibrated" else 0.0 + row_losses = calibrated_ce_with_logits( + logits, labels, valid_mask=valid, calib_weight=calib_weight, pos_weight=pos_weight + ) + + if row_mask is not None: + row_losses = row_losses * row_mask.float() + + if reduction == "mean": + num_valid = row_mask.float().sum() if row_mask is not None else torch.tensor(row_losses.numel()) + return row_losses.sum() / num_valid if num_valid > 0 else torch.tensor(0.0, device=logits.device) + if reduction != "sum": + warnings.warn( + f"Invalid Value for config 'loss_reduction': '{reduction}' \n Supported reduction modes:" + f" 'none', 'mean', 'sum'. It will be used 'sum' instead.", + stacklevel=2, + ) + return row_losses.sum() + + def _token_ce_loss( + self, + scores: torch.Tensor, + labels: torch.Tensor, + prompts_embedding_mask: torch.Tensor, + word_mask: torch.Tensor, + **kwargs: Any, + ) -> torch.Tensor: + """Calibrated CE for token-level scores (B, W, C, 3) or span scores (B, N, C). + + For token-level scores each (word, start/end/inside) position is a row + and the softmax runs over entity classes. + """ + if scores.dim() == 4: + scores = scores.permute(0, 1, 3, 2) # (B, W, 3, C) + labels = labels.permute(0, 1, 3, 2) + class_mask = prompts_embedding_mask[:, None, None, :] + row_mask = word_mask[:, :, None].expand(scores.shape[:-1]) + else: + class_mask = prompts_embedding_mask[:, None, :] + row_mask = word_mask + return self._ce_loss(scores, labels, class_mask=class_mask, row_mask=row_mask, **kwargs) + @abstractmethod def loss(self, x: Any) -> torch.Tensor: """Compute the total loss for the model. @@ -601,7 +721,7 @@ def loss( reduction: Loss reduction method ('sum' or 'mean'). negatives: Negative sampling probability. masking: Masking strategy for negative sampling. - loss_type: Loss function — 'focal' (default), 'bce', or 'dice'. + loss_type: Loss function — 'focal' (default), 'bce', 'dice', 'ce' or 'ce_calibrated'. use_span_width_weight: If True, scale positive-span losses by w(k) = 1 + log(k+1) where k is the 1-indexed span width. Zero inference overhead; applied before final reduction. @@ -623,7 +743,8 @@ def loss( width_weight = 1.0 + torch.log(k_idx) # (K,) # Broadcast to (B, L, K, C); boost positives only, leave negatives at 1.0 w = width_weight.view(1, 1, K, 1) - label_clamped = labels.clamp(min=0.0) + # Labels come from the collator as (B, L*K, C); view them as (B, L, K, C). + label_clamped = labels.view(BS, _L, K, CL).clamp(min=0.0) # weight tensor: 1 everywhere, boosted by w where label=1 pos_boost = 1.0 + (w - 1.0) * label_clamped # (B, L, K, C) else: @@ -632,6 +753,24 @@ def loss( scores = scores.view(BS, -1, CL) labels = labels.view(BS, -1, CL) + if loss_type in CE_LOSS_TYPES: + return self._ce_loss( + scores, + labels, + class_mask=prompts_embedding_mask.unsqueeze(1), + row_mask=span_mask.view(BS, -1), + reduction=reduction, + negatives=negatives, + masking=masking, + loss_type=loss_type, + pos_weight=None if pos_boost is None else pos_boost.view(BS, -1, CL), + alpha=alpha, + gamma=gamma, + prob_margin=prob_margin, + label_smoothing=label_smoothing, + **kwargs, + ) + all_losses = self._loss( scores, labels, @@ -1157,7 +1296,9 @@ def __init__( def get_span_representations(self, scores, span_idx, span_mask, words_embedding, labels, threshold): if span_idx is None: - span_idx, span_mask = extract_spans_from_tokens(scores, labels, threshold) + span_idx, span_mask = extract_spans_from_tokens( + apply_logit_calibration(scores, self.config), labels, threshold + ) span_idx = span_idx * span_mask.unsqueeze(-1).long() if getattr(self.config, "represent_spans", False): @@ -1305,6 +1446,21 @@ def loss( Returns: A scalar tensor representing the aggregated loss value. """ + if kwargs.get("loss_type") in CE_LOSS_TYPES: + return self._token_ce_loss( + scores, + labels, + prompts_embedding_mask, + word_mask, + alpha=alpha, + gamma=gamma, + prob_margin=prob_margin, + label_smoothing=label_smoothing, + reduction=reduction, + negatives=negatives, + **kwargs, + ) + all_losses = self._loss(scores, labels, alpha, gamma, prob_margin, label_smoothing, negatives) # Base mask: (B, W/N, C) @@ -1639,6 +1795,8 @@ def loss( reduction: str = "sum", negatives: float = 1.0, masking: str = "none", + loss_type: str = "focal", + dice_gamma: float = 1.0, **kwargs: Any, ) -> torch.Tensor: """Compute span classification loss for bi-encoder. @@ -1654,7 +1812,9 @@ def loss( reduction: Loss reduction method ('sum' or 'mean'). negatives: Negative sampling probability. masking: Masking strategy for negative sampling. - **kwargs: Additional arguments. + loss_type: 'focal' (default), 'bce', 'dice', 'ce' or 'ce_calibrated'. + dice_gamma: Self-adjustment exponent for Dice loss. + **kwargs: Additional arguments (e.g. ``ce_calib_weight``). Returns: Scalar loss tensor. @@ -1668,7 +1828,33 @@ def loss( scores = scores.view(BS, -1, CL) labels = labels.view(BS, -1, CL) - all_losses = self._loss(scores, labels, alpha, gamma, label_smoothing, negatives=negatives, masking=masking) + if loss_type in CE_LOSS_TYPES: + return self._ce_loss( + scores, + labels, + class_mask=prompts_embedding_mask.unsqueeze(1), + row_mask=mask_label.view(BS, -1), + reduction=reduction, + negatives=negatives, + masking=masking, + loss_type=loss_type, + alpha=alpha, + gamma=gamma, + label_smoothing=label_smoothing, + **kwargs, + ) + + all_losses = self._loss( + scores, + labels, + alpha, + gamma, + label_smoothing=label_smoothing, + negatives=negatives, + masking=masking, + loss_type=loss_type, + dice_gamma=dice_gamma, + ) masked_loss = all_losses.view(batch_size, -1, num_classes) * prompts_embedding_mask.unsqueeze(1) all_losses = masked_loss.view(-1, num_classes) @@ -2093,7 +2279,7 @@ def select_span_decoder_embedding( flat_prob = span_labels.max(-1).values.view(B, L * K) keep = (flat_prob == 1) & flat_mask.bool() else: - flat_prob = torch.sigmoid(span_scores).max(-1).values.view(B, L * K) + flat_prob = calibrated_sigmoid(span_scores, self.config).max(-1).values.view(B, L * K) keep = (flat_prob > threshold) & flat_mask.bool() if top_k: @@ -2287,6 +2473,8 @@ def loss( negatives: float = 1.0, masking: str = "none", decoder_loss: torch.Tensor | None = None, + loss_type: str = "focal", + dice_gamma: float = 1.0, **kwargs: Any, ) -> torch.Tensor: """Compute combined loss for span classification and decoder. @@ -2303,7 +2491,9 @@ def loss( negatives: Negative sampling probability. masking: Masking strategy for negative sampling. decoder_loss: Optional decoder loss to combine with span loss. - **kwargs: Additional arguments. + loss_type: 'focal' (default), 'bce', 'dice', 'ce' or 'ce_calibrated'. + dice_gamma: Self-adjustment exponent for Dice loss. + **kwargs: Additional arguments (e.g. ``ce_calib_weight``). Returns: Scalar combined loss tensor. @@ -2316,7 +2506,36 @@ def loss( scores = scores.view(BS, -1, CL) labels = labels.view(BS, -1, CL) - all_losses = self._loss(scores, labels, alpha, gamma, label_smoothing, negatives=negatives, masking=masking) + if loss_type in CE_LOSS_TYPES: + loss = self._ce_loss( + scores, + labels, + class_mask=prompts_embedding_mask.unsqueeze(1), + row_mask=mask_label.view(BS, -1), + reduction=reduction, + negatives=negatives, + masking=masking, + loss_type=loss_type, + alpha=alpha, + gamma=gamma, + label_smoothing=label_smoothing, + **kwargs, + ) + if decoder_loss is not None: + loss = decoder_loss * self.config.decoder_loss_coef + loss * self.config.span_loss_coef + return loss + + all_losses = self._loss( + scores, + labels, + alpha, + gamma, + label_smoothing=label_smoothing, + negatives=negatives, + masking=masking, + loss_type=loss_type, + dice_gamma=dice_gamma, + ) masked_loss = all_losses.view(batch_size, -1, num_classes) * prompts_embedding_mask.unsqueeze(1) all_losses = masked_loss.view(-1, num_classes) @@ -2428,7 +2647,7 @@ def select_token_decoder_embedding( if self.config.decoder_mode == "prompt": return self.select_decoder_embedding(prompts_embedding, prompts_embedding_mask)[:3] - span_scores = torch.sigmoid(span_logits) + span_scores = calibrated_sigmoid(span_logits, self.config) # Flatten span representations for selection B = span_rep.size(0) @@ -2439,7 +2658,7 @@ def select_token_decoder_embedding( keep = (span_prob == 1) & span_mask.bool() else: # During inference: use predicted scores - span_scores = torch.sigmoid(span_logits).max(-1).values # (B, S) + span_scores = calibrated_sigmoid(span_logits, self.config).max(-1).values # (B, S) keep = (span_scores > 0.5) & span_mask.bool() if top_k: @@ -2819,7 +3038,7 @@ def select_span_target_embedding( span_prob_flat = span_labels.max(dim=-1).values.view(B, -1) keep = (span_prob_flat == 1).bool() elif span_scores is not None and span_scores.size(-1) > 0: - span_prob = torch.sigmoid(span_scores) + span_prob = calibrated_sigmoid(span_scores, self.config) if class_mask is not None: span_prob = span_prob * class_mask[:, None, None, : span_prob.size(-1)].to(span_prob.dtype) span_prob_flat = span_prob.max(dim=-1).values.view(B, -1) @@ -3278,6 +3497,23 @@ def rel_loss( """ B, _, C = logits.shape + if kwargs.get("loss_type") in CE_LOSS_TYPES: + # Multi-label over relation classes per entity pair; adjacency loss stays BCE. + return self._ce_loss( + logits, + labels, + class_mask=class_mask.view(B, -1, C), + row_mask=pair_mask.view(B, -1, C)[..., 0], + reduction=reduction, + negatives=negatives, + masking=masking, + alpha=alpha, + gamma=gamma, + prob_margin=prob_margin, + label_smoothing=label_smoothing, + **kwargs, + ) + all_losses = self._loss( logits, labels, alpha, gamma, prob_margin, label_smoothing, negatives=negatives, masking=masking ) @@ -3367,6 +3603,21 @@ def loss( Returns: Scalar loss tensor. """ + if kwargs.get("loss_type") in CE_LOSS_TYPES: + return self._token_ce_loss( + scores, + labels, + prompts_embedding_mask, + word_mask, + alpha=alpha, + gamma=gamma, + prob_margin=prob_margin, + label_smoothing=label_smoothing, + reduction=reduction, + negatives=negatives, + **kwargs, + ) + all_losses = self._loss(scores, labels, alpha, gamma, prob_margin, label_smoothing, negatives) masked_loss = all_losses * (word_mask.unsqueeze(-1) * prompts_embedding_mask.unsqueeze(1)).unsqueeze(-1) @@ -3401,7 +3652,11 @@ def represent_spans( if span_idx is None: span_idx, span_mask = extract_spans_from_tokens( - scores, labels, threshold, word_mask=words_mask, class_mask=prompts_mask + apply_logit_calibration(scores, self.config), + labels, + threshold, + word_mask=words_mask, + class_mask=prompts_mask, ) span_idx = span_idx * span_mask.unsqueeze(-1).long() target_span_rep = self.span_rep_layer(words_embeddings, span_idx) diff --git a/gliner/modeling/loss_functions.py b/gliner/modeling/loss_functions.py index 5a6a1694..35a838ab 100644 --- a/gliner/modeling/loss_functions.py +++ b/gliner/modeling/loss_functions.py @@ -1,6 +1,9 @@ import torch import torch.nn.functional as F +# Loss types handled by calibrated_ce_with_logits. +CE_LOSS_TYPES = ("ce", "ce_calibrated") + def span_dice_loss( inputs: torch.Tensor, @@ -234,3 +237,72 @@ def cross_entropy_loss( ) return loss + + +def calibrated_ce_with_logits( + inputs: torch.Tensor, + targets: torch.Tensor, + valid_mask: torch.Tensor | None = None, + anchor: float = 0.0, + calib_weight: float = 0.0, + pos_weight: torch.Tensor | None = None, + ignore_index: int = -100, +) -> torch.Tensor: + """Multi-label cross-entropy against a fixed "no entity" anchor, plus a BCE calibration term. + + Each row (e.g. one span) holds C class logits. A virtual "no entity" logit + fixed at ``anchor`` is added to the row, and the loss enforces + positives > anchor > negatives (the adaptive-threshold loss from ATLOP, + Zhou et al. 2021, with the threshold held constant): + + L_pos = sum_{p in P} -log(e^{s_p} / (e^{s_p} + e^{a})) = sum_p softplus(a - s_p) + L_neg = logsumexp([a, s_N]) - a + L_calib = mean_c BCE(s_c, y_c) + L = L_pos + L_neg + calib_weight * L_calib + + With ``anchor=0`` the decision rule ``sigmoid(s) > 0.5`` used by GLiNER + decoders stays valid. ``L_neg`` only pushes down the strongest negatives, + so the BCE term keeps every per-class sigmoid probability calibrated. + + Args: + inputs: Logits of shape (..., C). + targets: Labels of shape (..., C) with values in {0, 1} or ``ignore_index``. + valid_mask: Optional mask broadcastable to ``inputs``. Entries that are 0 + (padded classes, sampled-out negatives) are excluded from every term. + anchor: Logit of the virtual "no entity" class. Defaults to 0.0. + calib_weight: Weight of the per-class BCE term. 0 gives plain CE. + pos_weight: Optional weights broadcastable to ``inputs``, applied to + positive terms of ``L_pos``. + ignore_index: Target value excluded from the loss. Defaults to -100. + + Returns: + Per-row loss of shape ``inputs.shape[:-1]`` (float32). + """ + logits = inputs.float() + valid = targets != ignore_index + if valid_mask is not None: + valid = valid & valid_mask.bool() + y = targets.float().clamp(min=0.0) + + pos = valid & (y > 0.5) + neg = valid & ~pos + + # L_pos: each positive must beat the anchor. + pos_terms = F.softplus(anchor - logits) * y + if pos_weight is not None: + pos_terms = pos_terms * pos_weight.float() + l_pos = (pos_terms * pos).sum(-1) + + # L_neg: the anchor must beat all negatives (one softmax per row). + min_val = torch.finfo(logits.dtype).min + neg_logits = logits.masked_fill(~neg, min_val) + anchor_col = torch.full_like(neg_logits[..., :1], anchor) + l_neg = torch.logsumexp(torch.cat([anchor_col, neg_logits], dim=-1), dim=-1) - anchor + + loss = l_pos + l_neg + + if calib_weight > 0: + bce = F.binary_cross_entropy_with_logits(logits, y, reduction="none") * valid + loss = loss + calib_weight * bce.sum(-1) / valid.sum(-1).clamp(min=1) + + return loss diff --git a/gliner/training/trainer.py b/gliner/training/trainer.py index 20ed555a..10ff0421 100644 --- a/gliner/training/trainer.py +++ b/gliner/training/trainer.py @@ -72,6 +72,13 @@ class TrainingArguments(transformers.TrainingArguments): negatives: Ratio of negative samples to use. Defaults to 1.0. masking: Masking strategy for training ('global' or other strategies). Defaults to 'global'. + loss_type: Loss function: 'focal' (default), 'bce', 'dice', 'ce' + (multi-label cross-entropy against a fixed "no entity" logit) or + 'ce_calibrated' ('ce' plus a per-class BCE calibration term). + use_span_width_weight: Boost positive-span losses by span width. + dice_gamma: Self-adjustment exponent for the Dice loss. + ce_calib_weight: Weight of the BCE calibration term for + loss_type='ce_calibrated'. Defaults to 0.5. warmup_ratio: Fraction of training steps used for warmup when warmup_steps is zero. Retained for compatibility with Transformers v4. """ @@ -92,9 +99,13 @@ class TrainingArguments(transformers.TrainingArguments): loss_type: str | None = "focal" use_span_width_weight: bool | None = False dice_gamma: float | None = 1.0 + ce_calib_weight: float | None = 0.5 warmup_ratio: float = 0.0 def __post_init__(self): + valid_loss_types = ("focal", "bce", "dice", "ce", "ce_calibrated") + if self.loss_type is not None and self.loss_type not in valid_loss_types: + raise ValueError(f"loss_type must be one of {valid_loss_types}, got '{self.loss_type}'") if not 0.0 <= self.warmup_ratio <= 1.0: raise ValueError("warmup_ratio must lie in range [0, 1]") # Transformers 5.x maps the deprecated warmup_ratio onto warmup_steps @@ -235,6 +246,7 @@ def compute_loss( loss_type=self.args.loss_type, use_span_width_weight=self.args.use_span_width_weight, dice_gamma=self.args.dice_gamma, + ce_calib_weight=self.args.ce_calib_weight, **inputs, ) From 8358e11818c4f234decf266715a2901723cd5ab1 Mon Sep 17 00:00:00 2001 From: Ingvar Date: Sat, 31 Oct 2026 17:18:40 +0200 Subject: [PATCH 2/6] implement calibration head --- gliner/calibration.py | 401 ++++++++++++++++++++++++++++++++++ gliner/config.py | 32 +++ gliner/model.py | 110 ++++++++++ gliner/modeling/calibrator.py | 281 ++++++++++++++++++++++++ gliner/modeling/outputs.py | 3 + 5 files changed, 827 insertions(+) create mode 100644 gliner/modeling/calibrator.py diff --git a/gliner/calibration.py b/gliner/calibration.py index 5c2ae0c3..53ad6366 100644 --- a/gliner/calibration.py +++ b/gliner/calibration.py @@ -22,6 +22,7 @@ import logging import numbers from typing import Any, Dict, List, Tuple, Iterable, Sequence +from dataclasses import dataclass import torch import torch.nn.functional as F @@ -328,3 +329,403 @@ def collect_entity_logits( empty = torch.zeros(0) return empty, empty, empty return torch.cat(all_logits), torch.cat(all_labels), torch.cat(all_weights) + + +# --------------------------------------------------------------------------- +# Label sets +# --------------------------------------------------------------------------- + + +def assign_label_sets( + data: Sequence[Dict[str, Any]], + mode: str = "example", + all_labels: Sequence[str] | None = None, + seed: int = 42, + key: str = "ner", +) -> List[Dict[str, Any]]: + """Give every example a fixed ``{key}_labels`` list so collection and evaluation see the same labels. + + ``mode='dataset'`` gives every example ``all_labels``. ``mode='example'`` + gives an example its gold types plus as many random other types from + ``all_labels`` (at least one). Examples that already have ``{key}_labels`` + keep them. + """ + labels_key = f"{key}_labels" + pool = list(all_labels) if all_labels is not None else dataset_entity_types(data, key) + rng = random.Random(seed) + out = [] + for example in data: + if example.get(labels_key): + out.append(example) + continue + if mode == "dataset": + labels = list(pool) + elif mode == "example": + gold = sorted({str(ent[-1]) for ent in example.get(key, [])}) + gold_set = set(gold) + others = [label for label in pool if label not in gold_set] + negatives = rng.sample(others, min(len(others), max(1, len(gold)))) + labels = gold + negatives + rng.shuffle(labels) + else: + raise ValueError(f"mode must be 'dataset' or 'example', got {mode!r}") + out.append({**example, labels_key: labels}) + return out + + +# --------------------------------------------------------------------------- +# Calibration head: cached frozen outputs, fitting and evaluation +# --------------------------------------------------------------------------- + + +@dataclass +class CachedOutput: + """Frozen-model outputs of one example, trimmed to its words and labels.""" + + words: torch.Tensor # (W, Dw) + prompts: torch.Tensor # (C, Dl) + logits: torch.Tensor # span: (W, K, C); token: (W, C, 3) + targets: torch.Tensor # same shape as logits + mode: str = "span" # "span" or "token" + + +@torch.inference_mode() +def collect_head_examples( + model: Any, + data: Sequence[Dict[str, Any]], + batch_size: int = 8, + store_dtype: torch.dtype = torch.float16, + show_progress: bool = True, +) -> List[CachedOutput]: + """Run the frozen model over labelled data and cache what the calibration head needs. + + Examples should carry ``ner_labels`` (see :func:`assign_label_sets`). + Raw logits are cached even if a head is already attached. + """ + from .modeling.calibrator import calibrator_mode # noqa: PLC0415 + + if getattr(model, "is_runtime_model", False): + raise ValueError("Calibration needs a torch-runtime model; load it without ONNX/OpenVINO.") + if not getattr(model, "supports_calibrator", True): + raise NotImplementedError(f"{type(model).__name__} does not support a calibration head.") + if getattr(model.config, "span_mode", None) == "token_level" and getattr(model.config, "represent_spans", False): + raise NotImplementedError("Fitting a head for token models with represent_spans=True is not supported.") + mode = calibrator_mode(model.config) + + collator = model._create_data_collator() + device = model.device + cached: List[CachedOutput] = [] + num_batches = math.ceil(len(data) / batch_size) + for step, start in enumerate(range(0, len(data), batch_size), 1): + examples = list(data[start : start + batch_size]) + batch = collator(examples) + batch = {k: v.to(device) if torch.is_tensor(v) else v for k, v in batch.items()} + output = model(**batch) + logits = getattr(output, "uncalibrated_logits", None) + logits = output.logits if logits is None else logits + labels = batch["labels"] + num_words = output.mask.bool().sum(-1).tolist() + num_classes = output.prompts_embedding_mask.bool().sum(-1).tolist() + + if mode == "span": + B, L, K, _ = logits.shape + labels = labels.view(B, L, K, -1) + for i in range(logits.shape[0]): + w, c = int(num_words[i]), int(num_classes[i]) + if w == 0 or c == 0: + continue + if mode == "span": + lg, tg = logits[i, :w, :, :c], labels[i, :w, :, :c] + else: + lg, tg = logits[i, :w, :c], labels[i, :w, :c] + cached.append( + CachedOutput( + words=output.words_embedding[i, :w].to(store_dtype).cpu(), + prompts=output.prompts_embedding[i, :c].to(store_dtype).cpu(), + logits=lg.float().cpu(), + targets=tg.float().cpu(), + mode=mode, + ) + ) + if show_progress and (step % 10 == 0 or step == num_batches): + logger.info("cached %d/%d batches", step, num_batches) + return cached + + +def _collate_cached(examples: Sequence[CachedOutput], device) -> Dict[str, torch.Tensor]: + B = len(examples) + W = max(ex.words.shape[0] for ex in examples) + C = max(ex.prompts.shape[0] for ex in examples) + first = examples[0] + words = first.words.new_zeros(B, W, first.words.shape[1]) + prompts = first.prompts.new_zeros(B, C, first.prompts.shape[1]) + span_layout = first.mode == "span" + if span_layout: # (W, K, C) + K = first.logits.shape[1] + logits = torch.full((B, W, K, C), -1e4) + targets = torch.zeros(B, W, K, C) + else: # (W, C, 3) + logits = torch.full((B, W, C, 3), -1e4) + targets = torch.zeros(B, W, C, 3) + word_mask = torch.zeros(B, W, dtype=torch.bool) + class_mask = torch.zeros(B, C, dtype=torch.bool) + for i, ex in enumerate(examples): + w, c = ex.words.shape[0], ex.prompts.shape[0] + words[i, :w], prompts[i, :c] = ex.words, ex.prompts + if span_layout: + logits[i, :w, :, :c], targets[i, :w, :, :c] = ex.logits, ex.targets + else: + logits[i, :w, :c], targets[i, :w, :c] = ex.logits, ex.targets + word_mask[i, :w], class_mask[i, :c] = True, True + return { + "logits": logits.to(device), + "targets": targets.to(device), + "words": words.to(device), + "prompts": prompts.to(device), + "word_mask": word_mask.to(device), + "class_mask": class_mask.to(device), + } + + +def _iterate_candidates(calibrator, examples, device, batch_size=16, order=None, predict=True): + """Yield (calibrator output dict, candidate targets) per batch of cached examples.""" + order = list(range(len(examples))) if order is None else order + for start in range(0, len(order), batch_size): + batch = _collate_cached([examples[i] for i in order[start : start + batch_size]], device) + args = (batch["logits"], batch["words"], batch["prompts"], batch["word_mask"], batch["class_mask"]) + out = calibrator(*args) if predict else calibrator.gather(*args) + yield out, batch["targets"][out["index"]] + + +def _decision_channel(values: torch.Tensor) -> torch.Tensor: + """The channel that decides a token-level pair (inside); identity for span pairs.""" + return values[:, 2] if values.dim() == 2 else values + + +def candidate_cells(z: torch.Tensor, y: torch.Tensor, num_bins: int) -> torch.Tensor: + """(raw confidence bin over [0.5, 1]) * 2 + (raw decision at 0.5 is correct) per candidate.""" + p = torch.sigmoid(_decision_channel(z)) + t = _decision_channel(y) + confidence = torch.maximum(p, 1 - p) + bins = torch.clamp(((confidence - 0.5) * 2 * num_bins).long(), max=num_bins - 1) + return bins * 2 + ((p >= 0.5) == (t >= 0.5)).long() + + +@torch.no_grad() +def candidate_entries(calibrator, examples, device, batch_size=16) -> Tuple[torch.Tensor, torch.Tensor]: + """Raw candidate logits and targets (token channels kept as columns), on CPU.""" + zs, ys = [], [] + for out, targets in _iterate_candidates(calibrator, examples, device, batch_size, predict=False): + zs.append(out["z"].cpu()) + ys.append(targets.cpu()) + if not zs: + return torch.zeros(0), torch.zeros(0) + return torch.cat(zs), torch.cat(ys) + + +def balance_table(z: torch.Tensor, y: torch.Tensor, num_bins: int = 5, max_weight: float = 10.0) -> torch.Tensor: + """Per-cell weights giving every non-empty (confidence bin, correct / wrong) cell equal loss mass. + + Weights are clipped to ``max_weight`` and renormalised so the total mass is unchanged. + """ + cells = candidate_cells(z, y, num_bins) + mass = torch.bincount(cells, minlength=2 * num_bins).float() + target = mass.sum() / (mass > 0).sum().clamp(min=1) + weights = torch.where(mass > 0, target / mass.clamp(min=1e-12), torch.zeros_like(mass)).clamp(max=max_weight) + return weights * mass.sum() / (weights * mass).sum().clamp(min=1e-12) + + +def head_loss(out, targets, base_beta, base_bias=0.0, prior_weight=0.01, bias_prior_weight=0.01, weights=None): + """Weighted mean over candidates of NLL(sigmoid(beta * z + b)) + priors. Returns (loss, nll).""" + from .modeling.calibrator import GLiNERCalibrator # noqa: PLC0415 + + calibrated = GLiNERCalibrator.calibrated_candidate_logits(out) + nll = F.binary_cross_entropy_with_logits(calibrated, targets.clamp(min=0), reduction="none") + if nll.dim() == 2: + nll = nll.mean(-1) + beta, bias = out["beta"], out["bias"] + prior = prior_weight * (beta.clamp_min(1e-6).log() - math.log(base_beta)) ** 2 + prior = prior + bias_prior_weight * (bias - base_bias) ** 2 + if weights is None: + weights = torch.ones_like(nll) + total = weights.sum().clamp(min=1e-12) + return ((nll + prior) * weights).sum() / total, (nll * weights).sum() / total + + +def fit_calibrator( + calibrator, + train_examples: Sequence[CachedOutput], + eval_examples: Sequence[CachedOutput], + device, + base_beta: float, + base_bias: float = 0.0, + prior_weight: float = 0.01, + bias_prior_weight: float = 0.01, + cell_weights: torch.Tensor | None = None, + num_bins: int = 5, + num_epochs: int = 20, + batch_size: int = 16, + lr: float = 1e-3, + weight_decay: float = 0.01, + patience: int = 3, + seed: int = 42, + min_base_beta: float = 0.05, + log_fn=print, +): + """Train the head on cached frozen outputs, keeping the weights with the best held-out NLL. + + The head starts from global scaling (``base_beta``, ``base_bias``) and is + pulled back towards it by the priors. ``cell_weights`` (from + :func:`balance_table`) reweights training candidates by raw confidence + bin and correctness. + """ + if base_beta < min_base_beta: + log_fn(f"beta_0={base_beta:.3g} is below {min_base_beta}; using {min_base_beta}") + base_beta = min_base_beta + if not calibrator.use_bias: + base_bias = 0.0 + rng = random.Random(seed) + calibrator.to(device) + calibrator.reset_to_global_scaling(base_beta, base_bias) + optimizer = torch.optim.AdamW(calibrator.parameters(), lr=lr, weight_decay=weight_decay) + table = None if cell_weights is None else cell_weights.to(device) + + def held_out_nll(): + calibrator.eval() + total, count = 0.0, 0.0 + with torch.no_grad(): + for out, targets in _iterate_candidates(calibrator, eval_examples, device, 32): + if out["z"].shape[0] == 0: + continue + _, nll = head_loss(out, targets, base_beta, base_bias) + total += nll.item() * out["z"].shape[0] + count += out["z"].shape[0] + return total / max(count, 1) + + best = held_out_nll() + best_state = {k: v.detach().clone() for k, v in calibrator.state_dict().items()} + log_fn(f"epoch 0: held-out NLL {best:.5f} (global scaling, beta_0={base_beta:.4f}, b_0={base_bias:.4f})") + bad_epochs = 0 + for epoch in range(1, num_epochs + 1): + calibrator.train() + order = list(range(len(train_examples))) + rng.shuffle(order) + running, seen = 0.0, 0 + for out, targets in _iterate_candidates(calibrator, train_examples, device, batch_size, order): + if out["z"].shape[0] == 0: + continue + weights = None if table is None else table[candidate_cells(out["z"], targets, num_bins)] + loss, _ = head_loss(out, targets, base_beta, base_bias, prior_weight, bias_prior_weight, weights) + optimizer.zero_grad() + loss.backward() + optimizer.step() + running += loss.item() * out["z"].shape[0] + seen += out["z"].shape[0] + nll = held_out_nll() + log_fn(f"epoch {epoch}: train loss {running / max(seen, 1):.5f}, held-out NLL {nll:.5f}") + if nll < best - 1e-5: + best, bad_epochs = nll, 0 + best_state = {k: v.detach().clone() for k, v in calibrator.state_dict().items()} + else: + bad_epochs += 1 + if bad_epochs >= patience: + break + calibrator.load_state_dict(best_state) + calibrator.eval() + return calibrator + + +@torch.no_grad() +def evaluate_head_candidates(calibrator, examples, device, base_beta=None, base_bias=0.0, n_bins=15): + """Entry-level metrics on candidates for the raw model, global scaling and the head.""" + calibrator.eval() + raw, head, ys = [], [], [] + for out, targets in _iterate_candidates(calibrator, examples, device, 32): + if out["z"].shape[0] == 0: + continue + raw.append(out["z"].reshape(-1).cpu()) + head.append(calibrator.calibrated_candidate_logits(out).reshape(-1).cpu()) + ys.append(targets.reshape(-1).clamp(min=0).cpu()) + if not raw: + return {} + raw, head, ys = torch.cat(raw), torch.cat(head), torch.cat(ys) + results = { + "num_candidate_entries": int(ys.numel()), + "uncalibrated": calibration_metrics(raw, ys, n_bins=n_bins), + "calibrated": calibration_metrics(head, ys, n_bins=n_bins), + } + if base_beta is not None: + results["global_scaling"] = calibration_metrics( + raw, ys, temperature=1 / base_beta, bias=base_bias, n_bins=n_bins + ) + return results + + +# --------------------------------------------------------------------------- +# Decoded-span reliability +# --------------------------------------------------------------------------- + + +def _gold_char_spans(tokens: Sequence[str], ner) -> set: + starts, pos = [], 0 + for token in tokens: + starts.append(pos) + pos += len(token) + 1 + return {(starts[s], starts[e] + len(tokens[e]), str(label)) for s, e, label in ner} + + +def span_reliability( + model: Any, + data: Sequence[Dict[str, Any]], + min_score: float = 0.05, + n_bins: int = 10, + threshold: float = 0.5, + batch_size: int = 8, + key: str = "ner", +) -> Dict[str, Any]: + """Reliability of decoded spans: of spans with score in a bin, how many are correct. + + Runs normal inference (flat NER) on ``" ".join(tokenized_text)`` with each + example's ``{key}_labels`` and a low threshold ``min_score``. A span is correct + when its character offsets and label exactly match a gold entity. ECE is + ``sum_b n_b / N * |mean score_b - accuracy_b|`` over spans scoring ``>= min_score``. + """ + texts = [" ".join(ex["tokenized_text"]) for ex in data] + labels = [list(ex[f"{key}_labels"]) for ex in data] + preds = model.inference(texts, labels, threshold=min_score, flat_ner=True, batch_size=batch_size) + + scores, correct, num_gold = [], [], 0 + for example, entities in zip(data, preds, strict=True): + gold = _gold_char_spans(example["tokenized_text"], example.get(key, [])) + num_gold += len(gold) + for ent in entities: + scores.append(ent["score"]) + correct.append((ent["start"], ent["end"], ent["label"]) in gold) + + s = torch.tensor(scores, dtype=torch.float64) + c = torch.tensor(correct, dtype=torch.float64) + bins_out, ece = [], 0.0 + if len(s): + bins = torch.clamp((s * n_bins).long(), max=n_bins - 1) + for b in range(n_bins): + in_bin = bins == b + n = int(in_bin.sum()) + if n == 0: + bins_out.append({"bin": [b / n_bins, (b + 1) / n_bins], "count": 0}) + continue + conf, acc = float(s[in_bin].mean()), float(c[in_bin].mean()) + ece += n / len(s) * abs(conf - acc) + bins_out.append({"bin": [b / n_bins, (b + 1) / n_bins], "count": n, "mean_score": conf, "accuracy": acc}) + above = s >= threshold + tp = float(c[above].sum()) if len(s) else 0.0 + precision = tp / max(int(above.sum()), 1) + recall = tp / max(num_gold, 1) + f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0 + return { + "ece": ece, + "num_spans": len(s), + "bins": bins_out, + f"precision@{threshold}": precision, + f"recall@{threshold}": recall, + f"f1@{threshold}": f1, + } diff --git a/gliner/config.py b/gliner/config.py index d024df68..1375cc2c 100644 --- a/gliner/config.py +++ b/gliner/config.py @@ -161,6 +161,16 @@ def __init__( # noqa: PLR0917, RUF100 logit_bias: float = 0.0, rel_logit_temperature: float = 1.0, rel_logit_bias: float = 0.0, + use_calibrator: bool = False, + calibrator_mode: str | None = None, + calibrator_word_dim: int | None = None, + calibrator_label_dim: int | None = None, + calibrator_proj_size: int = 128, + calibrator_hidden_size: int = 256, + calibrator_beta_max: float = 5.0, + calibrator_dropout: float = 0.1, + calibrator_use_bias: bool = True, + calibrator_candidate_threshold: float = 0.01, **kwargs, ): """Initialize BaseGLiNERConfig. @@ -205,6 +215,18 @@ def __init__( # noqa: PLR0917, RUF100 rel_logit_temperature (float, optional): Calibration temperature for relation logits. Defaults to 1.0. rel_logit_bias (float, optional): Calibration bias for relation logits. Defaults to 0.0. + use_calibrator (bool, optional): Whether a calibration head (see + ``gliner/modeling/calibrator.py``) is attached. Defaults to False. + calibrator_mode (str, optional): 'span' or 'token'; None infers it from the architecture. + calibrator_word_dim (int, optional): Word embedding size seen by the head. None uses hidden_size. + calibrator_label_dim (int, optional): Label embedding size seen by the head. None uses hidden_size. + calibrator_proj_size (int, optional): Projection size of span / label representations. Defaults to 128. + calibrator_hidden_size (int, optional): Hidden size of the head MLP. Defaults to 256. + calibrator_beta_max (float, optional): Upper bound of the inverse temperature. Defaults to 5.0. + calibrator_dropout (float, optional): Dropout in the head MLP. Defaults to 0.1. + calibrator_use_bias (bool, optional): Whether the head also predicts a logit bias. Defaults to True. + calibrator_candidate_threshold (float, optional): Pairs with raw probability below this + keep their raw logit. Defaults to 0.01. **kwargs: Additional keyword arguments passed to parent class. """ super().__init__(**kwargs) @@ -255,6 +277,16 @@ def __init__( # noqa: PLR0917, RUF100 self.logit_bias = logit_bias self.rel_logit_temperature = rel_logit_temperature self.rel_logit_bias = rel_logit_bias + self.use_calibrator = use_calibrator + self.calibrator_mode = calibrator_mode + self.calibrator_word_dim = calibrator_word_dim + self.calibrator_label_dim = calibrator_label_dim + self.calibrator_proj_size = calibrator_proj_size + self.calibrator_hidden_size = calibrator_hidden_size + self.calibrator_beta_max = calibrator_beta_max + self.calibrator_dropout = calibrator_dropout + self.calibrator_use_bias = calibrator_use_bias + self.calibrator_candidate_threshold = calibrator_candidate_threshold class UniEncoderConfig(BaseGLiNERConfig): diff --git a/gliner/model.py b/gliner/model.py index 00f8d088..571adc12 100644 --- a/gliner/model.py +++ b/gliner/model.py @@ -6,6 +6,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Mapping, Optional from pathlib import Path from threading import RLock +from contextlib import contextmanager import torch import transformers @@ -90,6 +91,7 @@ UniEncoderTokenDecoderProcessor, RelationExtractionTokenProcessor, ) +from .modeling.calibrator import GLiNERCalibrator, calibrator_mode, apply_calibrator, build_calibrator from .data_processing.utils import prepare_streaming_span_idx from .data_processing.collator import ( BiEncoderSpanDataCollator, @@ -389,6 +391,8 @@ class BaseGLiNER(ABC, nn.Module, PyTorchModelHubMixin): data_processor_class: type = None data_collator_class: type = None decoder_class: type = None + # Whether a calibration head (gliner/modeling/calibrator.py) can be attached. + supports_calibrator: bool = True def __init__( self, @@ -445,6 +449,109 @@ def __init__( self._keys_to_ignore_on_save = None self._inference_packing_config: InferencePackingConfig | None = None + self._calibrator_hook = None + self.calibrator_enabled = True + if getattr(config, "use_calibrator", False): + if self.runtime_model: + warnings.warn( + "This model has a calibration head, but it is not applied with the " + f"'{self.runtime}' runtime; scores are uncalibrated.", + stacklevel=2, + ) + elif self.supports_calibrator: + self._attach_calibrator(build_calibrator(config)) + + # ------------------------------------------------------------------ + # Calibration head + # ------------------------------------------------------------------ + + def _core_model(self) -> nn.Module: + """The underlying model, looking through torch.compile wrappers.""" + return getattr(self.model, "_orig_mod", self.model) + + @property + def calibrator(self) -> GLiNERCalibrator | None: + """The attached calibration head, or None.""" + if self.runtime_model: + return None + return getattr(self._core_model(), "calibrator", None) + + def add_calibrator( + self, + word_dim: int | None = None, + label_dim: int | None = None, + **calibrator_kwargs: Any, + ) -> GLiNERCalibrator: + """Attach a fresh calibration head and record it in the config. + + The head starts as the identity (beta = 1, bias = 0); fit it with + ``gliner.calibration.fit_calibrator`` or ``scripts/calibrate.py --method head``. + + Args: + word_dim: Size of ``words_embedding``. Defaults to ``config.hidden_size``. + label_dim: Size of ``prompts_embedding``. Defaults to ``config.hidden_size``. + **calibrator_kwargs: Overrides for ``calibrator_*`` config fields, e.g. + ``hidden_size=256``, ``beta_max=5.0``, ``use_bias=True``, + ``candidate_threshold=0.01``. + + Returns: + The new calibrator module. + """ + if self.runtime_model: + raise RuntimeError("A calibration head can only be attached to a PyTorch-backed model.") + if not self.supports_calibrator: + raise NotImplementedError(f"{type(self).__name__} does not support a calibration head.") + for key, value in calibrator_kwargs.items(): + attr = f"calibrator_{key}" + if not hasattr(self.config, attr): + raise TypeError(f"Unknown calibrator option '{key}'") + setattr(self.config, attr, value) + self.config.calibrator_word_dim = word_dim or self.config.calibrator_word_dim or self.config.hidden_size + self.config.calibrator_label_dim = label_dim or self.config.calibrator_label_dim or self.config.hidden_size + self.config.calibrator_mode = self.config.calibrator_mode or calibrator_mode(self.config) + self.config.use_calibrator = True + + reference = next(self._core_model().parameters()) + calibrator = build_calibrator(self.config).to(device=reference.device) + self._attach_calibrator(calibrator) + return calibrator + + def remove_calibrator(self) -> None: + """Detach the calibration head and mark the config as uncalibrated.""" + core = self._core_model() + if hasattr(core, "calibrator"): + del core.calibrator + if self._calibrator_hook is not None: + self._calibrator_hook.remove() + self._calibrator_hook = None + self.config.use_calibrator = False + + def _attach_calibrator(self, calibrator: GLiNERCalibrator) -> None: + # Registered as a child of the core model so save_pretrained / from_pretrained carry it. + self._core_model().calibrator = calibrator + if self._calibrator_hook is None: + # A forward hook covers every inference path that calls self.model(...). + self._calibrator_hook = self._core_model().register_forward_hook(self._calibrator_forward_hook) + + def _calibrator_forward_hook(self, module: nn.Module, args: Any, output: Any) -> Any: + calibrator = getattr(module, "calibrator", None) + if calibrator is None or not self.calibrator_enabled or module.training: + return None + # Training / loss computation (labels given) always sees raw logits. + if getattr(output, "loss", None) is not None or not hasattr(output, "logits"): + return None + return apply_calibrator(calibrator, output) + + @contextmanager + def calibrator_disabled(self): + """Context manager that temporarily returns uncalibrated logits.""" + previous = self.calibrator_enabled + self.calibrator_enabled = False + try: + yield self + finally: + self.calibrator_enabled = previous + @abstractmethod def _create_model(self, config, backbone_from_pretrained, cache_dir, **kwargs): """ @@ -3924,6 +4031,9 @@ def forward( class StreamingSpanGLiNER(BaseEncoderGLiNER): """Causal-decoder span model with optional per-session streaming state.""" + # Session logits are merged across calls, so a per-call head would be inconsistent. + supports_calibrator = False + config_class = StreamingSpanConfig model_class = StreamingSpanModel data_processor_class = StreamingSpanProcessor diff --git a/gliner/modeling/calibrator.py b/gliner/modeling/calibrator.py new file mode 100644 index 00000000..4124a6f0 --- /dev/null +++ b/gliner/modeling/calibrator.py @@ -0,0 +1,281 @@ +"""Calibration head for GLiNER: per-(span, label) inverse temperature and bias. + +Adapted from the GLiClass calibrator. For every *candidate* pair, i.e. a (span, label) +whose raw probability is at least ``candidate_threshold``, an MLP predicts an inverse +temperature ``beta`` in ``(0, beta_max)`` and, optionally, a bias ``b``. The calibrated +logit is ``beta * z + b``. Pairs below the threshold keep their raw logit: they are +almost all trivial negatives, are never decoded at usual thresholds, and skipping them +keeps the head cheap (the full L x K x C grid is huge). + +The head is fitted with the backbone frozen (see ``gliner/calibration.py``) and is +initialised to a global temperature / Platt fit, so it starts as global scaling. + +Modes: + * ``"span"``: logits (B, L, K, C) over the start x width grid, or (B, S, C) + with explicit ``span_idx`` (B, S, 2). A pair is (span, label). + * ``"token"``: logits (B, W, C, 3) with start / end / inside channels. A pair + is (word, label); one beta / bias scales all three channels. +""" + +from __future__ import annotations + +import math +from typing import Any, Dict + +import torch +from torch import nn + +NUM_STAT_FEATURES = 6 + + +def calibrator_mode(config: Any) -> str: + """'token' for token-level models decoded from token logits, else 'span'.""" + if getattr(config, "span_mode", None) == "token_level" and not getattr(config, "represent_spans", False): + return "token" + return "span" + + +class GLiNERCalibrator(nn.Module): + """MLP over (span repr, label repr, score statistics) -> (beta, bias) per candidate pair.""" + + def __init__( + self, + word_dim: int, + label_dim: int, + mode: str = "span", + proj_size: int = 128, + hidden_size: int = 256, + beta_max: float = 5.0, + dropout: float = 0.1, + use_bias: bool = True, + candidate_threshold: float = 0.01, + max_width: int = 12, + ): + super().__init__() + if mode not in ("span", "token"): + raise ValueError(f"mode must be 'span' or 'token', got {mode!r}") + self.mode = mode + self.beta_max = beta_max + self.use_bias = use_bias + self.candidate_threshold = candidate_threshold + self.max_width = max_width + + # Span repr = [start word, end word, mean word]; projected first because there + # can be many candidates per batch. + self.word_proj = nn.Sequential(nn.LayerNorm(3 * word_dim), nn.Linear(3 * word_dim, proj_size)) + self.label_proj = nn.Sequential(nn.LayerNorm(label_dim), nn.Linear(label_dim, proj_size)) + self.mlp = nn.Sequential( + nn.Linear(4 * proj_size + NUM_STAT_FEATURES, hidden_size), + nn.GELU(), + nn.Dropout(dropout), + nn.Linear(hidden_size, hidden_size), + nn.GELU(), + nn.Dropout(dropout), + nn.Linear(hidden_size, 2 if use_bias else 1), + ) + self.reset_to_global_scaling(1.0) + + @property + def candidate_logit(self) -> float: + p = min(max(self.candidate_threshold, 1e-12), 1 - 1e-12) + return math.log(p / (1 - p)) + + def reset_to_global_scaling(self, base_beta: float, base_bias: float = 0.0) -> None: + """Zero the output layer so (beta, b) == (base_beta, base_bias) for every pair.""" + ratio = min(max(base_beta / self.beta_max, 1e-4), 1 - 1e-4) + output = self.mlp[-1] + with torch.no_grad(): + output.weight.zero_() + output.bias[0] = math.log(ratio / (1 - ratio)) + if self.use_bias: + output.bias[1] = base_bias + + # ------------------------------------------------------------------ + # Candidate selection and features (no parameters involved) + # ------------------------------------------------------------------ + + @torch.no_grad() + def gather( + self, + logits: torch.Tensor, + words_embedding: torch.Tensor, + prompts_embedding: torch.Tensor, + word_mask: torch.Tensor, + class_mask: torch.Tensor, + span_idx: torch.Tensor | None = None, + span_mask: torch.Tensor | None = None, + ) -> Dict[str, torch.Tensor]: + """Select candidate pairs and build their inputs. + + Returns a dict with ``index`` (tuple of index tensors into ``logits``), ``z`` + (n,) or (n, 3) raw logits, ``word_feats`` (n, 3 * Dw), ``label_feats`` (n, Dl) + and ``stats`` (n, NUM_STAT_FEATURES). + """ + z = logits.float() + C = min(z.shape[-2] if self.mode == "token" else z.shape[-1], prompts_embedding.shape[1], class_mask.shape[1]) + if self.mode == "token": + z = z[:, :, :C] + else: + z = z[..., :C] + class_valid = class_mask[:, :C].bool() + num_words = word_mask.bool().sum(-1) # (B,) + num_labels = class_valid.sum(-1).clamp(min=1).float() # (B,) + + if self.mode == "token": + return self._gather_token(z, words_embedding, prompts_embedding, word_mask, class_valid, num_labels) + + if z.dim() == 4: # (B, L, K, C) grid + B, L, K, _ = z.shape + starts = torch.arange(L, device=z.device).view(1, L, 1).expand(B, L, K) + ends = starts + torch.arange(K, device=z.device).view(1, 1, K) + span_valid = ends < num_words.view(B, 1, 1) + else: # (B, S, C) explicit spans + if span_idx is None: + raise ValueError("span logits of shape (B, S, C) need span_idx") + starts, ends = span_idx[..., 0], span_idx[..., 1] + span_valid = (ends < num_words.view(-1, 1)) & (starts >= 0) & (starts <= ends) + if span_mask is not None: + span_valid = span_valid & span_mask.bool() + + masked = z.masked_fill(~class_valid.view(class_valid.size(0), *([1] * (z.dim() - 2)), -1), float("-inf")) + cand = (masked >= self.candidate_logit) & span_valid.unsqueeze(-1) + index = cand.nonzero(as_tuple=True) + b, c = index[0], index[-1] + pos = index[1:-1] # (l, k) or (s,) + start, end = starts[(b, *pos)], ends[(b, *pos)] + + zc = z[index] + best = masked.amax(-1)[(b, *pos)] + mean = (z * class_valid.view(class_valid.size(0), *([1] * (z.dim() - 2)), -1)).sum(-1)[(b, *pos)] + mean = mean / num_labels[b] + width = (end - start + 1).float() / self.max_width + stats = torch.stack([zc, zc.abs(), zc - best, zc - mean, width, num_labels[b].log()], dim=-1) + + word_feats = self._span_word_features(words_embedding, b, start, end) + return { + "index": index, + "z": zc, + "word_feats": word_feats, + "label_feats": prompts_embedding[b, c].float(), + "stats": stats, + } + + def _gather_token(self, z, words_embedding, prompts_embedding, word_mask, class_valid, num_labels): + W = min(z.shape[1], words_embedding.shape[1], word_mask.shape[1]) + z = z[:, :W] + word_valid = word_mask[:, :W].bool() + valid = word_valid[:, :, None] & class_valid[:, None, :] + cand = (z.amax(-1) >= self.candidate_logit) & valid + index = cand.nonzero(as_tuple=True) # (b, w, c) + b, w, c = index + + zc = z[index] # (n, 3) + inside = z[..., 2].masked_fill(~class_valid[:, None, :], float("-inf")) + best = inside.amax(-1)[b, w] + mean = (z[..., 2] * class_valid[:, None, :]).sum(-1)[b, w] / num_labels[b] + zi = zc[:, 2] + stats = torch.stack([zc[:, 0], zc[:, 1], zi, zi - best, zi - mean, num_labels[b].log()], dim=-1) + + word = words_embedding[b, w].float() + return { + "index": index, + "z": zc, + "word_feats": torch.cat([word, word, word], dim=-1), + "label_feats": prompts_embedding[b, c].float(), + "stats": stats, + } + + @staticmethod + def _span_word_features(words_embedding, b, start, end): + words = words_embedding.float() + prefix = torch.nn.functional.pad(words.cumsum(1), (0, 0, 1, 0)) # (B, W + 1, D) + mean = (prefix[b, end + 1] - prefix[b, start]) / (end - start + 1).unsqueeze(-1).float() + return torch.cat([words[b, start], words[b, end], mean], dim=-1) + + # ------------------------------------------------------------------ + # Head + # ------------------------------------------------------------------ + + def predict(self, word_feats, label_feats, stats): + """(beta, bias) of shape (n,) for gathered candidates.""" + dtype = self.mlp[0].weight.dtype + w = self.word_proj(word_feats.to(dtype)) + lab = self.label_proj(label_feats.to(dtype)) + features = torch.cat([w, lab, w * lab, (w - lab).abs(), stats.to(dtype)], dim=-1) + out = self.mlp(features).float() + # Clamped away from 0 so a positive logit never becomes exactly 0 (sign is preserved). + beta = (self.beta_max * torch.sigmoid(out[:, 0])).clamp(min=1e-6) + bias = out[:, 1] if self.use_bias else torch.zeros_like(beta) + return beta, bias + + def forward(self, logits, words_embedding, prompts_embedding, word_mask, class_mask, span_idx=None, span_mask=None): + """Gather candidates and predict their (beta, bias). Returns the gathered dict plus 'beta', 'bias'.""" + gathered = self.gather(logits, words_embedding, prompts_embedding, word_mask, class_mask, span_idx, span_mask) + if gathered["z"].shape[0] == 0: + empty = gathered["z"].new_zeros(0) + return {**gathered, "beta": empty, "bias": empty} + beta, bias = self.predict(gathered["word_feats"], gathered["label_feats"], gathered["stats"]) + return {**gathered, "beta": beta, "bias": bias} + + @staticmethod + def calibrated_candidate_logits(out: Dict[str, torch.Tensor]) -> torch.Tensor: + """Calibrated logits ``beta * z + b`` of gathered candidates, (n,) or (n, 3).""" + beta, bias = out["beta"], out["bias"] + if out["z"].dim() == 2: + beta, bias = beta.unsqueeze(-1), bias.unsqueeze(-1) + return beta * out["z"] + bias + + @torch.no_grad() + def calibrate( + self, logits, words_embedding, prompts_embedding, word_mask, class_mask, span_idx=None, span_mask=None + ): + """Return a copy of ``logits`` with candidate pairs replaced by calibrated logits.""" + out = self.forward(logits, words_embedding, prompts_embedding, word_mask, class_mask, span_idx, span_mask) + calibrated = logits.clone() + if out["z"].shape[0]: + calibrated[out["index"]] = self.calibrated_candidate_logits(out).to(logits.dtype) + return calibrated + + +def build_calibrator(config: Any) -> GLiNERCalibrator: + """Build a calibrator from ``calibrator_*`` config fields.""" + return GLiNERCalibrator( + word_dim=config.calibrator_word_dim or config.hidden_size, + label_dim=config.calibrator_label_dim or config.hidden_size, + mode=config.calibrator_mode or calibrator_mode(config), + proj_size=config.calibrator_proj_size, + hidden_size=config.calibrator_hidden_size, + beta_max=config.calibrator_beta_max, + dropout=config.calibrator_dropout, + use_bias=config.calibrator_use_bias, + candidate_threshold=config.calibrator_candidate_threshold, + max_width=getattr(config, "max_width", 12) or 12, + ) + + +def apply_calibrator(calibrator: GLiNERCalibrator, output: Any) -> Any: + """Calibrate the logits that get decoded, keeping the raw ones in ``uncalibrated_*``.""" + words = getattr(output, "words_embedding", None) + prompts = getattr(output, "prompts_embedding", None) + word_mask = getattr(output, "mask", None) + class_mask = getattr(output, "prompts_embedding_mask", None) + if words is None or prompts is None or word_mask is None or class_mask is None: + return output + + span_logits = getattr(output, "span_logits", None) + if span_logits is not None and getattr(output, "span_idx", None) is not None and calibrator.mode == "span": + # Token models with represent_spans decode from span_logits. + output.uncalibrated_span_logits = span_logits + output.span_logits = calibrator.calibrate( + span_logits, words, prompts, word_mask, class_mask, output.span_idx, output.span_mask + ) + return output + + logits = output.logits + if logits is None: + return output + span_idx = output.span_idx if logits.dim() == 3 else None + span_mask = output.span_mask if logits.dim() == 3 else None + output.uncalibrated_logits = logits + output.logits = calibrator.calibrate(logits, words, prompts, word_mask, class_mask, span_idx, span_mask) + return output diff --git a/gliner/modeling/outputs.py b/gliner/modeling/outputs.py index bc4d4dff..bb676f75 100644 --- a/gliner/modeling/outputs.py +++ b/gliner/modeling/outputs.py @@ -42,6 +42,9 @@ class GLiNERBaseOutput(ModelOutput): span_mask: torch.Tensor | None = None span_logits: torch.FloatTensor | None = None span_embeddings: torch.FloatTensor | None = field(default=None, kw_only=True) + # Set when a calibration head is attached: ``logits`` / ``span_logits`` are then calibrated. + uncalibrated_logits: torch.FloatTensor | None = field(default=None, kw_only=True) + uncalibrated_span_logits: torch.FloatTensor | None = field(default=None, kw_only=True) @dataclass From 6d00d3bebbafdbb2f0fa330ff31f2f9eea270184 Mon Sep 17 00:00:00 2001 From: Ingvar Date: Sat, 31 Oct 2026 17:18:59 +0200 Subject: [PATCH 3/6] update docs --- docs/training.md | 64 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/docs/training.md b/docs/training.md index cde2f7c9..f32f7314 100644 --- a/docs/training.md +++ b/docs/training.md @@ -373,6 +373,70 @@ Run training: python train.py --config config.yaml ``` +## Loss Functions and Calibration + +Pick the loss with `loss_type` (in `create_training_args`, `train_model` kwargs or `training.loss_type` in the YAML config): + +| `loss_type` | Description | +|---|---| +| `focal` (default) | Per-(span, class) BCE with optional focal weighting (`focal_loss_alpha`, `focal_loss_gamma`). | +| `bce` | Same as `focal` with `alpha=-1, gamma=0`. | +| `dice` | Self-adjusting Dice loss (`dice_gamma`); span models only. | +| `ce` | Multi-label cross-entropy against a fixed "no entity" logit at 0: every positive class must beat it, and it must beat every negative class. | +| `ce_calibrated` | `ce` plus `ce_calib_weight` × mean per-class BCE, which keeps every sigmoid probability calibrated. | + +Because the "no entity" logit is fixed at 0, models trained with `ce` / `ce_calibrated` keep the usual `sigmoid(score) > threshold` decoding. These losses ignore `focal_loss_*`, `label_smoothing` and `focal_loss_prob_margin`, and support every architecture (span, token, bi-encoder, decoder, relation extraction). The relation adjacency loss always stays BCE. + +```python +model.train_model( + train_dataset=train_data, + eval_dataset=None, + output_dir="models", + loss_type="ce_calibrated", + ce_calib_weight=0.5, +) +``` + +### Post-hoc calibration of a trained model + +`scripts/calibrate.py` freezes a trained model and fits a temperature `T` (and, with `--fit-bias`, a bias `b`) on a held-out dataset in GLiNER format, so that `sigmoid(logit / T + b)` matches how often predictions are correct: + +```bash +python scripts/calibrate.py --model models/checkpoint-1000 --data dev.json --output-dir models/calibrated +``` + +The weights are untouched. The values are stored in the config as `logit_temperature` / `logit_bias` (and `rel_logit_temperature` / `rel_logit_bias` for relations, which can be set by hand), and every decoder applies them. With the temperature alone, predictions at threshold 0.5 stay the same; scores and the meaning of other thresholds change. A bias also moves the 0.5 boundary. The script reports NLL, Brier score, ECE and entry-level precision/recall/F1 before and after, and writes `calibration_report.json` next to the model. + +### Calibration head + +`--method head` fits a small calibration head, adapted from GLiClass, with the backbone frozen. For every *candidate* (span, label) pair (raw probability at least `--candidate-threshold`, default 0.01), an MLP looks at: + +- the span's boundary and mean word embeddings, +- the label embedding, +- score statistics: the logit, its gap to the best and mean class, span width, and the number of labels. + +It predicts an inverse temperature β and a bias b, and the calibrated score is `sigmoid(β · logit + b)`. Pairs below the threshold keep their raw score. For token-level models, the pair is (word, label), and β and b scale its start / end / inside logits together. + +```bash +python scripts/calibrate.py --model models/checkpoint-1000 --data dev.json --eval-data test.json \ + --method head --output-dir models/calibrated +``` + +How the head is fitted: + +- It starts from a global Platt fit on the candidates and is pulled back toward it by a prior (`--prior-weight`, `--bias-prior-weight`). +- It trains on 80% of `--data` and early-stops on the remaining 20% (`--eval-ratio`). +- `--balance` (off by default) reweights candidates by raw confidence bin and correctness, as in GLiClass. On NER data it made held-out NLL worse. + +The script reports, for the raw model, global scaling and the head, which share of decoded spans in each score bin are correct, plus the calibration error (ECE). + +How the head is used: + +- It is saved with the model (`use_calibrator` and `calibrator_*` in the config, weights under `calibrator.*`) and applied on every PyTorch inference path. +- Raw logits stay available as `uncalibrated_logits` on the model output. +- `model.calibrator_disabled()` switches it off temporarily; `model.add_calibrator()` and `model.remove_calibrator()` attach and detach it. +- It is not applied during training (when labels are passed), with the ONNX / OpenVINO runtimes, or for streaming models. + ## Best Practices 1. **Start with a pretrained model**: Fine-tuning is almost always better than training from scratch From 57ac9bce8fc1d78f1db50812988c2ce9236936bc Mon Sep 17 00:00:00 2001 From: Ingvar Date: Sat, 31 Oct 2026 17:19:12 +0200 Subject: [PATCH 4/6] add calibration script --- scripts/calibrate.py | 424 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 424 insertions(+) create mode 100644 scripts/calibrate.py diff --git a/scripts/calibrate.py b/scripts/calibrate.py new file mode 100644 index 00000000..a5d5bdbb --- /dev/null +++ b/scripts/calibrate.py @@ -0,0 +1,424 @@ +"""Calibrate a trained GLiNER model's entity probabilities on a labelled dataset. + +The backbone is frozen. Two methods: + +* ``--method temperature`` (default): fit one temperature ``T`` (and optionally a + bias ``b``) so that ``sigmoid(logit / T + b)`` matches observed frequencies. + The values go to the config (``logit_temperature`` / ``logit_bias``). +* ``--method head``: fit a calibration head (as in GLiClass) that predicts an + inverse temperature ``beta`` and bias ``b`` for every candidate (span, label) + pair from the span / label representations and score statistics: + ``sigmoid(beta * logit + b)``. It starts from, and is regularised towards, a + global Platt / temperature fit, and is early-stopped on a held-out part of + ``--data``. The head is saved with the model and applied on every inference. + +Both report entry-level metrics and the reliability of decoded spans (of the +spans with score in a bin, what share is correct) on ``--eval-data`` (or the +held-out part of ``--data``). + +Dataset format (GLiNER JSON list, or JSONL with one example per line): + + [{"tokenized_text": ["Barack", "Obama", "visited", "Paris", "."], + "ner": [[0, 1, "person"], [3, 3, "location"]]}, ...] + +Examples: + + # Fit temperature on a dev set, compare before/after, save a calibrated copy + python scripts/calibrate.py --model path/to/model --data dev.json --output-dir path/to/model-calibrated + + # Also fit a bias (shifts which spans pass a fixed threshold) and only report + python scripts/calibrate.py --model urchade/gliner_small-v2.1 --data dev.json --fit-bias --no-save + + # Calibration head, evaluated on a separate test set + python scripts/calibrate.py --model path/to/model --data dev.json --eval-data test.json \ + --method head --output-dir path/to/model-calibrated + +Use held-out data (not the training set): training logits are overconfident +and would give a temperature that is too low. +""" + +from __future__ import annotations + +import sys +import json +import random +import logging +import argparse +from pathlib import Path + +import torch + +from gliner import GLiNER +from gliner.calibration import ( + freeze_model, + balance_table, + fit_calibrator, + span_reliability, + assign_label_sets, + candidate_entries, + calibration_metrics, + dataset_entity_types, + collect_entity_logits, + collect_head_examples, + fit_logit_calibration, + get_logit_calibration, + set_logit_calibration, + evaluate_head_candidates, +) + +AUTO_DATASET_LABELS_LIMIT = 50 + + +def load_dataset(path: str) -> list: + """Load a GLiNER-format dataset from JSON or JSONL.""" + with open(path, encoding="utf-8") as f: + if path.endswith(".jsonl"): + data = [json.loads(line) for line in f if line.strip()] + else: + data = json.load(f) + data = [ex for ex in data if ex.get("tokenized_text")] + for ex in data: + ex.setdefault("ner", []) + return data + + +def parse_args(argv=None) -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--model", required=True, help="Path or Hub id of a trained GLiNER model.") + parser.add_argument("--data", required=True, help="GLiNER-format calibration dataset (.json or .jsonl).") + parser.add_argument("--output-dir", help="Where to save the calibrated model (weights unchanged, config updated).") + parser.add_argument("--no-save", action="store_true", help="Only fit and report; do not save.") + parser.add_argument("--fit-bias", action="store_true", help="Fit a bias b as well as the temperature T.") + parser.add_argument( + "--label-mode", + choices=["auto", "dataset", "example"], + default="auto", + help=( + "'dataset': give every example the full label set of the dataset (mirrors inference). " + "'example': training-style labels (gold types + sampled negatives; honours ner_labels / ner_negatives). " + f"'auto': 'dataset' if it has <= {AUTO_DATASET_LABELS_LIMIT} labels, else 'example'." + ), + ) + parser.add_argument( + "--labels", nargs="+", help="Explicit label set for every example (implies --label-mode dataset)." + ) + parser.add_argument( + "--labels-per-pass", type=int, help="Split the label set into chunks of this size per forward pass." + ) + parser.add_argument("--batch-size", type=int, default=8) + parser.add_argument("--max-examples", type=int, help="Use at most this many (randomly chosen) examples.") + parser.add_argument( + "--neg-keep-prob", + type=float, + default=1.0, + help="Keep each negative (span, class) entry with this probability to save memory; kept ones are reweighted.", + ) + parser.add_argument("--threshold", type=float, default=0.5, help="Threshold for the reported precision/recall/F1.") + parser.add_argument("--n-bins", type=int, default=15, help="Bins for expected calibration error.") + parser.add_argument( + "--eval-data", help="Optional separate GLiNER-format set for the final report (decoded-span reliability)." + ) + parser.add_argument( + "--span-eval", + action=argparse.BooleanOptionalAction, + default=True, + help="Report decoded-span reliability (runs inference once per variant).", + ) + parser.add_argument("--span-eval-min-score", type=float, default=0.05, help="Lowest decoded score evaluated.") + parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu") + + head = parser.add_argument_group("calibration head (--method head)") + parser.add_argument("--method", choices=["temperature", "head"], default="temperature") + head.add_argument("--eval-ratio", type=float, default=0.2, help="Share of --data held out for early stopping.") + head.add_argument("--candidate-threshold", type=float, default=0.01, help="Raw probability for a candidate pair.") + head.add_argument("--hidden-size", type=int, default=256) + head.add_argument("--proj-size", type=int, default=128) + head.add_argument("--beta-max", type=float, default=5.0, help="Upper bound of the inverse temperature.") + head.add_argument("--dropout", type=float, default=0.1) + head.add_argument( + "--use-bias", + action=argparse.BooleanOptionalAction, + default=True, + help="Also predict a per-pair bias (fixes base-rate miscalibration; may flip decisions at 0.5).", + ) + head.add_argument("--prior-weight", type=float, default=0.01, help="Weight of (log beta - log beta_0)^2.") + head.add_argument("--bias-prior-weight", type=float, default=0.01, help="Weight of (b - b_0)^2.") + head.add_argument( + "--balance", + action=argparse.BooleanOptionalAction, + default=False, + help="Reweight candidates so every (raw confidence bin, correct / wrong) cell has equal mass.", + ) + head.add_argument("--balance-bins", type=int, default=5) + head.add_argument("--balance-max-weight", type=float, default=10.0) + head.add_argument("--num-epochs", type=int, default=20) + head.add_argument("--head-batch-size", type=int, default=16, help="Examples per head training step.") + head.add_argument("--lr", type=float, default=1e-3) + head.add_argument("--weight-decay", type=float, default=0.01) + head.add_argument("--patience", type=int, default=3) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--local-files-only", action="store_true") + args = parser.parse_args(argv) + if not args.no_save and not args.output_dir: + parser.error("--output-dir is required unless --no-save is given") + return args + + +def format_metrics(name: str, m: dict) -> str: + return ( + f"{name:<12} NLL={m['nll']:.5f} Brier={m['brier']:.5f} ECE={m['ece']:.5f} " + f"ECE(p>=0.1)={m['ece_confident']:.4f} P={m['precision']:.4f} R={m['recall']:.4f} F1={m['f1']:.4f}" + ) + + +def main(argv=None) -> int: + args = parse_args(argv) + sys.stdout.reconfigure(line_buffering=True) + logging.basicConfig(format="%(message)s") + logging.getLogger("gliner.calibration").setLevel(logging.INFO) + random.seed(args.seed) + torch.manual_seed(args.seed) + + data = load_dataset(args.data) + if args.max_examples and len(data) > args.max_examples: + data = random.sample(data, args.max_examples) + if not data: + print("No usable examples in dataset.", file=sys.stderr) + return 1 + + print(f"Loading model: {args.model}") + model = GLiNER.from_pretrained(args.model, local_files_only=args.local_files_only) + orig_dtype = next(model.parameters()).dtype + model = model.to(device=args.device, dtype=torch.float32) + freeze_model(model) + if any(p.requires_grad for p in model.parameters()): + raise RuntimeError("Model parameters are not frozen.") + + old_t, old_b = get_logit_calibration(model.config) + print(f"Current calibration: T={old_t:.4f}, b={old_b:.4f} (fitting starts from raw logits)") + + if args.labels: + mode, all_labels = "dataset", list(args.labels) + else: + all_labels = dataset_entity_types(data) + mode = args.label_mode + if mode == "auto": + mode = "dataset" if len(all_labels) <= AUTO_DATASET_LABELS_LIMIT else "example" + print(f"Label mode: {mode} ({len(all_labels)} labels in dataset)") + + eval_data = None + if args.eval_data: + eval_data = load_dataset(args.eval_data) + eval_pool = all_labels if args.labels else dataset_entity_types(eval_data) + eval_data = assign_label_sets(eval_data, mode, eval_pool, seed=args.seed + 1) + + if args.method == "head": + return run_head(args, model, orig_dtype, data, eval_data, mode, all_labels) + + entity_types = all_labels if mode == "dataset" else None + + print(f"Collecting logits on {len(data)} examples (model frozen)...") + logits, labels, weights = collect_entity_logits( + model, + data, + batch_size=args.batch_size, + entity_types=entity_types, + labels_per_pass=args.labels_per_pass, + neg_keep_prob=args.neg_keep_prob, + seed=args.seed, + ) + num_pos = int((labels > 0.5).sum()) + print(f"Collected {logits.numel()} (span, class) entries, {num_pos} positives") + if num_pos == 0: + print("No positive entries found; check the 'ner' annotations and label set.", file=sys.stderr) + return 1 + + temperature, bias = fit_logit_calibration(logits, labels, weights, fit_bias=args.fit_bias, device=args.device) + print(f"Fitted calibration: T={temperature:.4f}, b={bias:.4f}") + + metric_kwargs = dict(weights=weights, n_bins=args.n_bins, threshold=args.threshold) + before = calibration_metrics(logits, labels, temperature=1.0, bias=0.0, **metric_kwargs) + after = calibration_metrics(logits, labels, temperature=temperature, bias=bias, **metric_kwargs) + print("Entry-level metrics on the calibration set:") + print(format_metrics("uncalibrated", before)) + print(format_metrics("calibrated", after)) + if (old_t, old_b) != (1.0, 0.0): + previous = calibration_metrics(logits, labels, temperature=old_t, bias=old_b, **metric_kwargs) + print(format_metrics("previous", previous)) + + report = { + "model": args.model, + "data": args.data, + "method": "temperature", + "num_examples": len(data), + "fit_bias": args.fit_bias, + "logit_temperature": temperature, + "logit_bias": bias, + "previous": {"logit_temperature": old_t, "logit_bias": old_b}, + "metrics_uncalibrated": before, + "metrics_calibrated": after, + } + + if args.span_eval and eval_data: + set_logit_calibration(model.config, 1.0, 0.0) + with model.calibrator_disabled(): + report["span_reliability"] = {"uncalibrated": span_reliability_report(model, eval_data, args)} + set_logit_calibration(model.config, temperature, bias) + report["span_reliability"]["calibrated"] = span_reliability_report(model, eval_data, args) + print_span_reliability(report["span_reliability"]) + + if args.no_save: + print(json.dumps(report, indent=2)) + return 0 + + set_logit_calibration(model.config, temperature, bias) + model = model.to(dtype=orig_dtype) + output_dir = Path(args.output_dir) + model.save_pretrained(output_dir) + with open(output_dir / "calibration_report.json", "w", encoding="utf-8") as f: + json.dump(report, f, indent=2) + print(f"Saved calibrated model and calibration_report.json to {output_dir}") + return 0 + + +def span_reliability_report(model, data, args) -> dict: + return span_reliability( + model, data, min_score=args.span_eval_min_score, threshold=args.threshold, batch_size=args.batch_size + ) + + +def print_span_reliability(results: dict) -> None: + print("Decoded-span reliability (share of spans in each score bin that are correct):") + names = list(results) + print(" bin " + "".join(f"{name:>18}" for name in names)) + for i, row in enumerate(results[names[0]]["bins"]): + cells = [] + for name in names: + b = results[name]["bins"][i] + cells.append(f"{b['accuracy']:6.1%} (n={b['count']:>5})" if b["count"] else f"{'-':>16}") + print(f" {row['bin'][0]:.1f}-{row['bin'][1]:.1f} " + "".join(f"{c:>18}" for c in cells)) + t = next(k for k in results[names[0]] if k.startswith("f1@")).split("@")[1] + for name in names: + r = results[name] + print( + f" {name:<15} ECE={r['ece']:.4f} spans={r['num_spans']} " + f"P@{t}={r[f'precision@{t}']:.3f} R@{t}={r[f'recall@{t}']:.3f} F1@{t}={r[f'f1@{t}']:.3f}" + ) + + +def run_head(args, model, orig_dtype, data, eval_data, mode, all_labels) -> int: + """Fit a calibration head with the backbone frozen.""" + data = assign_label_sets(data, mode, all_labels, seed=args.seed) + data = list(data) + random.Random(args.seed).shuffle(data) + num_held_out = max(1, int(len(data) * args.eval_ratio)) + held_out, train = data[:num_held_out], data[num_held_out:] + print(f"Calibration examples: {len(train)} train, {len(held_out)} held-out for early stopping") + + if model.calibrator is not None: + print("Replacing the existing calibration head") + model.remove_calibrator() + set_logit_calibration(model.config, 1.0, 0.0) # the head replaces global scaling + + print("Caching frozen outputs...") + train_cached = collect_head_examples(model, train, batch_size=args.batch_size) + held_cached = collect_head_examples(model, held_out, batch_size=args.batch_size) + if not train_cached: + print("No usable training examples.", file=sys.stderr) + return 1 + + calibrator = model.add_calibrator( + word_dim=train_cached[0].words.shape[1], + label_dim=train_cached[0].prompts.shape[1], + hidden_size=args.hidden_size, + proj_size=args.proj_size, + beta_max=args.beta_max, + dropout=args.dropout, + use_bias=args.use_bias, + candidate_threshold=args.candidate_threshold, + ).float() + + z, y = candidate_entries(calibrator, train_cached, args.device) + num_pos = int((y > 0.5).any(-1).sum()) if y.dim() == 2 else int((y > 0.5).sum()) + print(f"Training candidates (raw p >= {args.candidate_threshold}): {z.shape[0]}, positives: {num_pos}") + if num_pos == 0: + print("No positive candidates; check annotations / label sets.", file=sys.stderr) + return 1 + + temperature, base_bias = fit_logit_calibration( + z.reshape(-1), y.reshape(-1).clamp(min=0), fit_bias=args.use_bias, device=args.device + ) + base_beta = 1.0 / temperature + print(f"Global {'Platt' if args.use_bias else 'temperature'} scaling: beta_0={base_beta:.4f}, b_0={base_bias:.4f}") + + cell_weights = None + if args.balance: + cell_weights = balance_table(z, y, args.balance_bins, args.balance_max_weight) + print(f"Balancing cell weights: {[round(w, 3) for w in cell_weights.tolist()]}") + + fit_calibrator( + calibrator, + train_cached, + held_cached, + args.device, + base_beta=base_beta, + base_bias=base_bias, + prior_weight=args.prior_weight, + bias_prior_weight=args.bias_prior_weight, + cell_weights=cell_weights, + num_bins=args.balance_bins, + num_epochs=args.num_epochs, + batch_size=args.head_batch_size, + lr=args.lr, + weight_decay=args.weight_decay, + patience=args.patience, + seed=args.seed, + ) + + candidates = evaluate_head_candidates(calibrator, held_cached, args.device, base_beta, base_bias, args.n_bins) + print("Candidate-level metrics on the held-out part of --data:") + for name in ("uncalibrated", "global_scaling", "calibrated"): + if name in candidates: + print(format_metrics(name[:12], candidates[name])) + + report = { + "model": args.model, + "data": args.data, + "method": "head", + "num_train": len(train), + "num_held_out": len(held_out), + "base_beta": base_beta, + "base_bias": base_bias, + "candidate_metrics_held_out": candidates, + "args": vars(args), + } + + if args.span_eval: + target = eval_data if eval_data else held_out + which = "--eval-data" if eval_data else "held-out part of --data" + print(f"Evaluating decoded spans on {which} ({len(target)} examples)...") + results = {} + with model.calibrator_disabled(): + results["uncalibrated"] = span_reliability_report(model, target, args) + set_logit_calibration(model.config, temperature, base_bias) + results["global_scaling"] = span_reliability_report(model, target, args) + set_logit_calibration(model.config, 1.0, 0.0) + results["calibrated"] = span_reliability_report(model, target, args) + report["span_reliability"] = results + print_span_reliability(results) + + if args.no_save: + return 0 + + model = model.to(dtype=orig_dtype) + model.calibrator.float() # keep the small head in full precision + output_dir = Path(args.output_dir) + model.save_pretrained(output_dir) + with open(output_dir / "calibration_report.json", "w", encoding="utf-8") as f: + json.dump(report, f, indent=2) + print(f"Saved model with calibration head and calibration_report.json to {output_dir}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 3e45d7202c642a7a330cec48c14b57a4083a2da7 Mon Sep 17 00:00:00 2001 From: Ingvar Date: Sat, 31 Oct 2026 17:19:22 +0200 Subject: [PATCH 5/6] update tests --- tests/test_calibrated_ce.py | 416 +++++++++++++++++++++++++++++++++ tests/test_calibration_head.py | 310 ++++++++++++++++++++++++ 2 files changed, 726 insertions(+) create mode 100644 tests/test_calibrated_ce.py create mode 100644 tests/test_calibration_head.py diff --git a/tests/test_calibrated_ce.py b/tests/test_calibrated_ce.py new file mode 100644 index 00000000..cd5195ab --- /dev/null +++ b/tests/test_calibrated_ce.py @@ -0,0 +1,416 @@ +"""Tests for the calibrated cross-entropy loss and post-hoc logit calibration.""" + +import json +from unittest.mock import Mock + +import torch +import pytest +import torch.nn.functional as F + +from gliner.config import ( + BiEncoderSpanConfig, + UniEncoderSpanConfig, + UniEncoderTokenConfig, + UniEncoderSpanRelexConfig, + UniEncoderTokenRelexConfig, + UniEncoderSpanDecoderConfig, +) +from gliner.calibration import ( + calibrated_sigmoid, + calibration_metrics, + fit_logit_calibration, + get_logit_calibration, + set_logit_calibration, + apply_logit_calibration, +) +from gliner.modeling.base import ( + BiEncoderSpanModel, + UniEncoderSpanModel, + UniEncoderTokenModel, + UniEncoderSpanRelexModel, + UniEncoderTokenRelexModel, + UniEncoderSpanDecoderModel, +) +from gliner.decoding.decoder import SpanDecoder, TokenDecoder +from gliner.modeling.loss_functions import calibrated_ce_with_logits + +# --------------------------------------------------------------------------- +# Loss function +# --------------------------------------------------------------------------- + + +class TestCalibratedCEFunction: + def test_matches_hand_computed_value(self): + s = torch.tensor([[2.0, -1.0, 0.5]]) + y = torch.tensor([[1.0, 0.0, 0.0]]) + loss = calibrated_ce_with_logits(s, y) + # L_pos = softplus(0 - 2); L_neg = logsumexp([0, -1, 0.5]) + expected = F.softplus(torch.tensor(-2.0)) + torch.logsumexp(torch.tensor([0.0, -1.0, 0.5]), 0) + assert loss.shape == (1,) + assert torch.allclose(loss[0], expected) + + def test_single_class_equals_two_way_softmax_ce(self): + s = torch.randn(64, 1) + y = torch.randint(0, 2, (64, 1)).float() + loss = calibrated_ce_with_logits(s, y) + two_way = torch.cat([torch.zeros_like(s), s], dim=-1) # [anchor, class] + expected = F.cross_entropy(two_way, y[:, 0].long(), reduction="none") + assert torch.allclose(loss, expected, atol=1e-6) + + def test_negative_only_row_is_softmax_ce_on_anchor(self): + s = torch.randn(8, 5) + y = torch.zeros(8, 5) + loss = calibrated_ce_with_logits(s, y) + logits = torch.cat([torch.zeros(8, 1), s], dim=-1) + expected = F.cross_entropy(logits, torch.zeros(8, dtype=torch.long), reduction="none") + assert torch.allclose(loss, expected, atol=1e-6) + + def test_padded_classes_do_not_change_loss(self): + s = torch.randn(4, 3) + y = torch.zeros(4, 3) + y[0, 1] = 1.0 + base = calibrated_ce_with_logits(s, y, calib_weight=0.5) + + padded_s = torch.cat([s, torch.full((4, 2), 50.0)], dim=-1) + padded_y = torch.cat([y, torch.zeros(4, 2)], dim=-1) + mask = torch.tensor([1, 1, 1, 0, 0]).bool() + padded = calibrated_ce_with_logits(padded_s, padded_y, valid_mask=mask, calib_weight=0.5) + assert torch.allclose(base, padded, atol=1e-6) + + def test_ignore_index_excluded(self): + s = torch.tensor([[1.0, 30.0]]) + y = torch.tensor([[1.0, -100.0]]) + expected = calibrated_ce_with_logits(s[:, :1], y[:, :1]) + assert torch.allclose(calibrated_ce_with_logits(s, y), expected) + + def test_gradients_push_positives_up_and_top_negative_down(self): + s = torch.tensor([[-0.5, 1.0, -3.0]], requires_grad=True) + y = torch.tensor([[1.0, 0.0, 0.0]]) + calibrated_ce_with_logits(s, y).sum().backward() + assert s.grad[0, 0] < 0 # positive is pushed up + assert s.grad[0, 1] > 0 # strongest negative is pushed down + assert s.grad[0, 1] > s.grad[0, 2] >= 0 + + def test_calibration_term_adds_mean_bce(self): + s = torch.randn(6, 4) + y = (torch.rand(6, 4) > 0.7).float() + plain = calibrated_ce_with_logits(s, y) + calib = calibrated_ce_with_logits(s, y, calib_weight=0.3) + bce = F.binary_cross_entropy_with_logits(s, y, reduction="none").mean(-1) + assert torch.allclose(calib - plain, 0.3 * bce, atol=1e-6) + + def test_pos_weight_scales_positive_terms(self): + s = torch.tensor([[-1.0, -2.0]]) + y = torch.tensor([[1.0, 0.0]]) + base = calibrated_ce_with_logits(s, y) + weighted = calibrated_ce_with_logits(s, y, pos_weight=torch.tensor([[3.0, 3.0]])) + assert torch.allclose(weighted - base, 2 * F.softplus(torch.tensor(1.0))) + + def test_fully_masked_rows_and_half_precision_are_finite(self): + s = torch.randn(3, 4, dtype=torch.float16) * 20 + y = torch.zeros(3, 4, dtype=torch.float16) + mask = torch.zeros(3, 4, dtype=torch.bool) + loss = calibrated_ce_with_logits(s, y, valid_mask=mask, calib_weight=0.5) + assert torch.isfinite(loss).all() + assert torch.allclose(loss, torch.zeros(3)) + + loss = calibrated_ce_with_logits(s, y, calib_weight=0.5) + assert torch.isfinite(loss).all() + + def test_training_learns_positive_above_anchor_above_negatives(self): + torch.manual_seed(0) + s = torch.zeros(32, 6, requires_grad=True) + y = (torch.rand(32, 6) > 0.8).float() + opt = torch.optim.SGD([s], lr=1.0) + for _ in range(300): + opt.zero_grad() + calibrated_ce_with_logits(s, y, calib_weight=0.5).sum().backward() + opt.step() + assert (s[y > 0.5] > 0).all() + assert (s[y < 0.5] < 0).all() + + +# --------------------------------------------------------------------------- +# Model losses +# --------------------------------------------------------------------------- + + +def _span_config(cls=UniEncoderSpanConfig, **extra): + return cls( + model_name="bert-base-uncased", + hidden_size=64, + dropout=0.1, + max_width=12, + span_mode="markerV0", + class_token_index=103, + post_fusion_schema="", + embed_ent_token=True, + **extra, + ) + + +def _span_tensors(B=2, L=6, K=12, C=4): + torch.manual_seed(0) + scores = torch.randn(B, L, K, C, requires_grad=True) + labels = torch.zeros(B, L * K, C) + labels[0, 3, 1] = 1.0 + labels[1, 7, 0] = 1.0 + labels[1, 7, 2] = 1.0 + prompts_mask = torch.ones(B, C) + prompts_mask[1, -1] = 0 + span_mask = torch.ones(B, L * K) + span_mask[1, -10:] = 0 + return scores, labels, prompts_mask, span_mask + + +@pytest.mark.parametrize("loss_type", ["ce", "ce_calibrated"]) +@pytest.mark.parametrize("masking", ["none", "global", "label", "span"]) +def test_span_model_ce_loss(loss_type, masking): + model = UniEncoderSpanModel(_span_config(), from_pretrained=False) + scores, labels, prompts_mask, span_mask = _span_tensors() + loss = model.loss(scores, labels, prompts_mask, span_mask, loss_type=loss_type, masking=masking, negatives=0.5) + assert loss.ndim == 0 and torch.isfinite(loss) and loss > 0 + loss.backward() + assert scores.grad is not None and torch.isfinite(scores.grad).all() + + +def test_span_model_ce_ignores_padded_classes_and_spans(): + model = UniEncoderSpanModel(_span_config(), from_pretrained=False) + scores, labels, prompts_mask, span_mask = _span_tensors() + base = model.loss(scores, labels, prompts_mask, span_mask, loss_type="ce_calibrated") + + noisy = scores.detach().clone().view(2, -1, 4) + noisy[1, :, -1] = 100.0 # padded class + noisy[1, -10:, :] = 100.0 # padded spans + other = model.loss(noisy.view_as(scores), labels, prompts_mask, span_mask, loss_type="ce_calibrated") + assert torch.allclose(base, other) + + +def test_span_model_ce_mean_reduction_divides_by_valid_spans(): + model = UniEncoderSpanModel(_span_config(), from_pretrained=False) + scores, labels, prompts_mask, span_mask = _span_tensors() + total = model.loss(scores, labels, prompts_mask, span_mask, loss_type="ce", reduction="sum") + mean = model.loss(scores, labels, prompts_mask, span_mask, loss_type="ce", reduction="mean") + assert torch.allclose(mean, total / span_mask.sum()) + + +def test_span_model_ce_with_span_width_weight(): + model = UniEncoderSpanModel(_span_config(), from_pretrained=False) + scores, labels, prompts_mask, span_mask = _span_tensors() + plain = model.loss(scores, labels, prompts_mask, span_mask, loss_type="ce") + weighted = model.loss(scores, labels, prompts_mask, span_mask, loss_type="ce", use_span_width_weight=True) + assert weighted > plain + + +def test_span_model_ce_forward_with_kwargs(): + model = UniEncoderSpanModel(_span_config(), from_pretrained=False) + B, L, W, C, K = 2, 20, 6, 3, 12 + inputs = { + "input_ids": torch.randint(0, 1000, (B, L)), + "attention_mask": torch.ones(B, L, dtype=torch.long), + "words_mask": torch.randint(0, W, (B, L)), + "text_lengths": torch.tensor([W, W - 2]).unsqueeze(-1), + "span_idx": torch.randint(0, W, (B, L * K, 2)), + "span_mask": torch.randint(0, 2, (B, L * K)), + "labels": torch.zeros(B, L * K, C), + } + out = model(**inputs, loss_type="ce_calibrated", ce_calib_weight=0.25) + assert torch.isfinite(out.loss) + + +def test_bi_encoder_span_ce_loss(): + model = BiEncoderSpanModel( + _span_config(BiEncoderSpanConfig, labels_encoder="bert-base-uncased"), from_pretrained=False + ) + scores, labels, prompts_mask, span_mask = _span_tensors() + loss = model.loss(scores, labels, prompts_mask, span_mask, loss_type="ce_calibrated") + assert torch.isfinite(loss) and loss > 0 + + +def test_span_decoder_ce_loss_combines_decoder_loss(): + config = _span_config( + UniEncoderSpanDecoderConfig, labels_decoder="gpt2", decoder_mode="span", full_decoder_context=True + ) + model = UniEncoderSpanDecoderModel(config, from_pretrained=False) + scores, labels, prompts_mask, span_mask = _span_tensors() + span_only = model.loss(scores, labels, prompts_mask, span_mask, loss_type="ce") + combined = model.loss(scores, labels, prompts_mask, span_mask, loss_type="ce", decoder_loss=torch.tensor(2.0)) + expected = 2.0 * config.decoder_loss_coef + span_only * config.span_loss_coef + assert torch.allclose(combined, expected) + + +@pytest.mark.parametrize("last_dim", [3, None]) +def test_token_model_ce_loss(last_dim): + config = UniEncoderTokenConfig( + model_name="bert-base-uncased", hidden_size=64, class_token_index=103, post_fusion_schema="" + ) + model = UniEncoderTokenModel(config, from_pretrained=False) + B, W, C = 2, 10, 4 + shape = (B, W, C, last_dim) if last_dim else (B, W, C) + scores = torch.randn(*shape, requires_grad=True) + labels = torch.zeros(*shape) + labels[0, 2, 1] = 1.0 + prompts_mask = torch.ones(B, C) + prompts_mask[0, -1] = 0 + word_mask = torch.ones(B, W) + word_mask[1, -3:] = 0 + loss = model.loss(scores, labels, prompts_mask, word_mask, loss_type="ce_calibrated") + assert torch.isfinite(loss) and loss > 0 + loss.backward() + + noisy = scores.detach().clone() + noisy[0, :, -1] = 100.0 + noisy[1, -3:] = 100.0 + assert torch.allclose(loss, model.loss(noisy, labels, prompts_mask, word_mask, loss_type="ce_calibrated")) + + +def _relex_config(cls): + return cls( + model_name="bert-base-uncased", + hidden_size=64, + max_width=12, + span_mode="markerV0", + class_token_index=103, + post_fusion_schema="", + relations_layer="mlp", + triples_layer=None, + embed_rel_token=True, + rel_token_index=104, + rel_token="<>", + ) + + +def test_relex_relation_ce_loss(): + model = UniEncoderSpanRelexModel(_relex_config(UniEncoderSpanRelexConfig), from_pretrained=False) + B, N, C = 2, 5, 3 + logits = torch.randn(B, N, C, requires_grad=True) + labels = torch.zeros(B, N, C) + labels[0, 1, 2] = 1.0 + pair_mask = torch.ones(B, N, C) + pair_mask[1, -2:] = 0 + class_mask = torch.ones(B, N, C) + loss = model.rel_loss(logits, labels, pair_mask, class_mask, loss_type="ce_calibrated") + assert torch.isfinite(loss) and loss > 0 + loss.backward() + assert logits.grad[1, -2:].abs().sum() == 0 + + +def test_token_relex_ce_loss(): + model = UniEncoderTokenRelexModel(_relex_config(UniEncoderTokenRelexConfig), from_pretrained=False) + B, W, C = 2, 8, 3 + scores = torch.randn(B, W, C, 3) + labels = torch.zeros(B, W, C, 3) + labels[0, 1, 0, 0] = 1.0 + loss = model.loss(scores, labels, torch.ones(B, C), torch.ones(B, W), loss_type="ce", span_mask=None) + assert torch.isfinite(loss) and loss > 0 + + +def test_focal_path_unchanged_by_default(): + model = UniEncoderSpanModel(_span_config(), from_pretrained=False) + scores, labels, prompts_mask, span_mask = _span_tensors() + focal = model.loss(scores, labels, prompts_mask, span_mask) + expected = ( + F.binary_cross_entropy_with_logits(scores.view(2, -1, 4), labels, reduction="none") + * prompts_mask[:, None] + * span_mask[..., None] + ).sum() + assert torch.allclose(focal, expected, atol=1e-3) + + +# --------------------------------------------------------------------------- +# Training arguments +# --------------------------------------------------------------------------- + + +def test_training_args_accept_ce_and_reject_unknown(tmp_path): + pytest.importorskip("accelerate") + from gliner.training import TrainingArguments + + args = TrainingArguments(output_dir=str(tmp_path), loss_type="ce_calibrated", ce_calib_weight=0.25) + assert args.loss_type == "ce_calibrated" and args.ce_calib_weight == 0.25 + with pytest.raises(ValueError, match="loss_type"): + TrainingArguments(output_dir=str(tmp_path), loss_type="cross_entropy") + + +# --------------------------------------------------------------------------- +# Post-hoc calibration +# --------------------------------------------------------------------------- + + +class TestLogitCalibration: + def test_defaults_are_identity(self): + config = UniEncoderSpanConfig() + logits = torch.randn(3, 4) + assert get_logit_calibration(config) == (1.0, 0.0) + assert apply_logit_calibration(logits, config) is logits + # Mocks and objects without the attributes are treated as uncalibrated. + assert apply_logit_calibration(logits, Mock()) is logits + assert apply_logit_calibration(logits, None) is logits + + def test_temperature_and_bias_applied(self): + config = UniEncoderSpanConfig(logit_temperature=2.0, logit_bias=-0.5, rel_logit_temperature=4.0) + logits = torch.tensor([2.0, -2.0]) + assert torch.allclose(calibrated_sigmoid(logits, config), torch.sigmoid(logits / 2 - 0.5)) + assert torch.allclose(calibrated_sigmoid(logits, config, kind="relation"), torch.sigmoid(logits / 4)) + + def test_invalid_temperature_rejected(self): + with pytest.raises(ValueError): + set_logit_calibration(UniEncoderSpanConfig(), temperature=0.0) + + def test_config_round_trip(self, tmp_path): + config = UniEncoderSpanConfig() + set_logit_calibration(config, 1.7, 0.2) + path = tmp_path / "config.json" + config.to_json_file(path) + data = json.loads(path.read_text()) + assert data["logit_temperature"] == pytest.approx(1.7) + assert UniEncoderSpanConfig(**data).logit_bias == pytest.approx(0.2) + + @pytest.mark.parametrize("fit_bias", [False, True]) + def test_fit_recovers_known_parameters(self, fit_bias): + torch.manual_seed(0) + true_t, true_b = 2.5, (-1.0 if fit_bias else 0.0) + logits = torch.randn(200_000) * 4 + labels = torch.bernoulli(torch.sigmoid(logits / true_t + true_b)) + t, b = fit_logit_calibration(logits, labels, fit_bias=fit_bias) + assert t == pytest.approx(true_t, rel=0.05) + assert b == pytest.approx(true_b, abs=0.05) + + before = calibration_metrics(logits, labels) + after = calibration_metrics(logits, labels, temperature=t, bias=b) + assert after["nll"] < before["nll"] + assert after["ece"] < before["ece"] + + def test_weighted_fit_matches_unweighted_on_duplicated_data(self): + torch.manual_seed(1) + logits = torch.randn(5000) * 3 + labels = torch.bernoulli(torch.sigmoid(logits / 2)) + w = torch.randint(1, 4, (5000,)).float() + t_weighted, _ = fit_logit_calibration(logits, labels, weights=w) + t_repeated, _ = fit_logit_calibration(logits.repeat_interleave(w.long()), labels.repeat_interleave(w.long())) + assert t_weighted == pytest.approx(t_repeated, rel=1e-3) + + def test_span_decoder_uses_calibrated_scores(self): + logits = torch.full((1, 3, 2, 1), -10.0) + logits[0, 0, 0, 0] = 2.0 + tokens = [["a", "b", "c"]] + raw = SpanDecoder(UniEncoderSpanConfig(max_width=2)) + calibrated = SpanDecoder(UniEncoderSpanConfig(max_width=2, logit_temperature=2.0)) + kwargs = dict(tokens=tokens, id_to_classes={1: "X"}, model_output=logits, threshold=0.5) + (raw_span,) = raw.decode(**kwargs)[0] + (cal_span,) = calibrated.decode(**kwargs)[0] + assert raw_span.score == pytest.approx(torch.sigmoid(torch.tensor(2.0)).item(), abs=1e-5) + assert cal_span.score == pytest.approx(torch.sigmoid(torch.tensor(1.0)).item(), abs=1e-5) + + # A bias moves the decision boundary. + shifted = SpanDecoder(UniEncoderSpanConfig(max_width=2, logit_bias=-3.0)) + assert shifted.decode(**kwargs) == [[]] + + def test_token_decoder_uses_calibrated_scores(self): + logits = torch.full((1, 3, 1, 3), -10.0) + logits[0, 1, 0, :] = 3.0 # start, end, inside at word 1 + kwargs = dict(tokens=[["a", "b", "c"]], id_to_classes={1: "X"}, model_output=logits, threshold=0.5) + raw = TokenDecoder(UniEncoderTokenConfig()).decode(**kwargs)[0] + cal = TokenDecoder(UniEncoderTokenConfig(logit_temperature=3.0)).decode(**kwargs)[0] + assert len(raw) == len(cal) == 1 + assert cal[0].score < raw[0].score diff --git a/tests/test_calibration_head.py b/tests/test_calibration_head.py new file mode 100644 index 00000000..c5bed0cb --- /dev/null +++ b/tests/test_calibration_head.py @@ -0,0 +1,310 @@ +"""Tests for the GLiNER calibration head (gliner/modeling/calibrator.py) and its fitting utilities.""" + +from types import SimpleNamespace + +import torch +import pytest + +from gliner.calibration import ( + CachedOutput, + balance_table, + fit_calibrator, + head_loss, + span_reliability, + assign_label_sets, + candidate_cells, + candidate_entries, +) +from gliner.modeling.calibrator import GLiNERCalibrator, apply_calibrator + +D = 16 + + +def _span_inputs(B=2, L=5, K=3, C=3, seed=0): + g = torch.Generator().manual_seed(seed) + logits = torch.randn(B, L, K, C, generator=g) * 3 + words = torch.randn(B, L, D, generator=g) + prompts = torch.randn(B, C, D, generator=g) + word_mask = torch.ones(B, L, dtype=torch.bool) + word_mask[1, -2:] = False # sample 1 has 3 words + class_mask = torch.ones(B, C, dtype=torch.bool) + class_mask[1, -1] = False + return logits, words, prompts, word_mask, class_mask + + +def test_starts_at_global_scaling_and_only_touches_candidates(): + cal = GLiNERCalibrator(D, D, mode="span", candidate_threshold=0.2, max_width=3).eval() + cal.reset_to_global_scaling(0.5, -1.0) + logits, words, prompts, word_mask, class_mask = _span_inputs() + out = cal(logits, words, prompts, word_mask, class_mask) + assert torch.allclose(out["beta"], torch.full_like(out["beta"], 0.5), atol=1e-4) + assert torch.allclose(out["bias"], torch.full_like(out["bias"], -1.0)) + + calibrated = cal.calibrate(logits, words, prompts, word_mask, class_mask) + is_cand = torch.zeros_like(logits, dtype=torch.bool) + is_cand[out["index"]] = True + assert torch.equal(calibrated[~is_cand], logits[~is_cand]) + assert torch.allclose(calibrated[is_cand], 0.5 * logits[is_cand] - 1.0, atol=1e-4) + + +def test_candidates_respect_threshold_span_bounds_and_padded_classes(): + cal = GLiNERCalibrator(D, D, mode="span", candidate_threshold=0.2, max_width=3) + logits, words, prompts, word_mask, class_mask = _span_inputs() + b, l, k, c = cal.gather(logits, words, prompts, word_mask, class_mask)["index"] + assert (torch.sigmoid(logits[b, l, k, c]) >= 0.2 - 1e-6).all() + num_words = word_mask.sum(-1) + assert (l + k < num_words[b]).all() + assert not ((b == 1) & (c == 2)).any() + + # Every eligible pair is a candidate. + expected = 0 + for bi in range(2): + for li in range(5): + for ki in range(3): + for ci in range(3): + valid = li + ki < num_words[bi] and class_mask[bi, ci] + expected += bool(valid and torch.sigmoid(logits[bi, li, ki, ci]) >= 0.2) + assert len(b) == expected + + +def test_explicit_span_mode_uses_span_idx(): + cal = GLiNERCalibrator(D, D, mode="span", candidate_threshold=0.0).eval() + logits = torch.zeros(1, 3, 2) + span_idx = torch.tensor([[[0, 1], [2, 2], [3, 4]]]) # last span runs past 3 words + span_mask = torch.tensor([[True, True, True]]) + words, prompts = torch.randn(1, 3, D), torch.randn(1, 2, D) + out = cal( + logits, + words, + prompts, + torch.ones(1, 3, dtype=torch.bool), + torch.ones(1, 2, dtype=torch.bool), + span_idx, + span_mask, + ) + assert sorted(set(out["index"][1].tolist())) == [0, 1] + # Mean feature of span (0, 1) is the mean of words 0 and 1. + first = (out["index"][1] == 0).nonzero()[0, 0] + assert torch.allclose(out["word_feats"][first, 2 * D :], words[0, :2].mean(0), atol=1e-5) + + +def test_token_mode_scales_all_channels_together(): + cal = GLiNERCalibrator(D, D, mode="token", candidate_threshold=0.1).eval() + cal.reset_to_global_scaling(2.0, 0.5) + logits = torch.randn(2, 4, 3, 3) * 3 + words, prompts = torch.randn(2, 4, D), torch.randn(2, 3, D) + word_mask = torch.ones(2, 4, dtype=torch.bool) + class_mask = torch.ones(2, 3, dtype=torch.bool) + out = cal(logits, words, prompts, word_mask, class_mask) + assert out["z"].shape[1] == 3 + calibrated = cal.calibrate(logits, words, prompts, word_mask, class_mask) + b, w, c = out["index"] + assert torch.allclose(calibrated[b, w, c], 2.0 * logits[b, w, c] + 0.5, atol=1e-4) + assert (torch.sigmoid(logits[b, w, c]).amax(-1) >= 0.1 - 1e-6).all() + + +def test_without_bias_decisions_never_flip(): + cal = GLiNERCalibrator(D, D, use_bias=False, candidate_threshold=0.0) + for p in cal.parameters(): + torch.nn.init.normal_(p, std=1.0) + logits, words, prompts, word_mask, class_mask = _span_inputs() + calibrated = cal.calibrate(logits, words, prompts, word_mask, class_mask) + assert torch.equal(calibrated > 0, logits > 0) + + +def test_apply_calibrator_keeps_raw_logits(): + cal = GLiNERCalibrator(D, D, candidate_threshold=0.0, max_width=3).eval() + cal.reset_to_global_scaling(0.5, 0.0) + logits, words, prompts, word_mask, class_mask = _span_inputs() + output = SimpleNamespace( + logits=logits, + words_embedding=words, + prompts_embedding=prompts, + mask=word_mask, + prompts_embedding_mask=class_mask, + span_logits=None, + span_idx=None, + span_mask=None, + ) + apply_calibrator(cal, output) + assert output.uncalibrated_logits is logits + assert not torch.equal(output.logits, logits) + + +def _cached(label_vecs, n=40, seed=0): + """Two labels, both with confident raw logits; label 0 is always wrong, label 1 always right.""" + g = torch.Generator().manual_seed(seed) + examples = [] + for _ in range(n): + W, K = 4, 2 + logits = torch.full((W, K, 2), -10.0) + targets = torch.zeros(W, K, 2) + logits[0, 0, 0] = 3.0 + torch.rand(1, generator=g).item() # wrong + logits[1, 0, 1] = 3.0 + torch.rand(1, generator=g).item() # right + targets[1, 0, 1] = 1.0 + examples.append(CachedOutput(torch.randn(W, D, generator=g), label_vecs.clone(), logits, targets, "span")) + return examples + + +def test_fit_learns_where_backbone_is_wrong(): + torch.manual_seed(0) + labels = torch.randn(2, D) * 3 + train, held = _cached(labels, 60, seed=1), _cached(labels, 20, seed=2) + cal = GLiNERCalibrator(D, D, candidate_threshold=0.01, dropout=0.0, max_width=2) + fit_calibrator( + cal, + train, + held, + "cpu", + base_beta=1.0, + base_bias=0.0, + num_epochs=30, + lr=3e-3, + patience=10, + log_fn=lambda *_: None, + ) + batch = held[0] + out = cal( + batch.logits[None], + batch.words[None].float(), + batch.prompts[None].float(), + torch.ones(1, 4, dtype=torch.bool), + torch.ones(1, 2, dtype=torch.bool), + ) + probs = torch.sigmoid(cal.calibrated_candidate_logits(out)) + wrong = probs[out["index"][-1] == 0] + right = probs[out["index"][-1] == 1] + assert wrong.max() < 0.3 < 0.7 < right.min() + + +def test_head_loss_prior_is_zero_at_base(): + out = {"z": torch.tensor([1.0, -2.0]), "beta": torch.tensor([0.5, 0.5]), "bias": torch.tensor([0.2, 0.2])} + targets = torch.tensor([1.0, 0.0]) + loss, nll = head_loss(out, targets, base_beta=0.5, base_bias=0.2) + assert torch.allclose(loss, nll) + loss2, _ = head_loss(out, targets, base_beta=1.0, base_bias=0.0) + assert loss2 > loss + + +def test_balance_table_equalises_cell_mass(): + torch.manual_seed(0) + z = torch.randn(5000) * 3 + y = torch.bernoulli(torch.sigmoid(z / 3)) + table = balance_table(z, y, num_bins=5, max_weight=1e9) + cells = candidate_cells(z, y, 5) + mass = torch.zeros(10).index_add_(0, cells, table[cells]) + nonzero = mass[mass > 0] + assert torch.allclose(nonzero, nonzero.mean().expand_as(nonzero), rtol=1e-4) + assert torch.isclose(mass.sum(), torch.tensor(5000.0)) + + +def test_candidate_entries_token_layout(): + cal = GLiNERCalibrator(D, D, mode="token", candidate_threshold=0.5) + logits = torch.full((3, 2, 3), -5.0) + logits[1, 0] = torch.tensor([2.0, 2.0, 2.0]) + targets = torch.zeros(3, 2, 3) + targets[1, 0] = 1.0 + ex = CachedOutput(torch.randn(3, D), torch.randn(2, D), logits, targets, "token") + z, y = candidate_entries(cal, [ex], "cpu") + assert z.shape == (1, 3) and torch.equal(y, torch.ones(1, 3)) + + +def test_assign_label_sets_deterministic_and_contains_gold(): + data = [{"tokenized_text": ["a"], "ner": [[0, 0, "x"]]}, {"tokenized_text": ["b"], "ner": []}] + pool = ["x", "y", "z", "w"] + a = assign_label_sets(data, "example", pool, seed=3) + b = assign_label_sets(data, "example", pool, seed=3) + assert a == b + assert "x" in a[0]["ner_labels"] and len(a[0]["ner_labels"]) == 2 + assert len(a[1]["ner_labels"]) == 1 + assert assign_label_sets(data, "dataset", pool)[1]["ner_labels"] == pool + kept = assign_label_sets([{**data[0], "ner_labels": ["q"]}], "example", pool) + assert kept[0]["ner_labels"] == ["q"] + + +def test_span_reliability_bins_and_correctness(): + data = [ + { + "tokenized_text": ["Barack", "Obama", "in", "Paris"], + "ner": [[0, 1, "person"], [3, 3, "city"]], + "ner_labels": ["person", "city"], + } + ] + + class FakeModel: + def inference(self, texts, labels, **kwargs): + assert texts == ["Barack Obama in Paris"] + return [ + [ + {"start": 0, "end": 12, "label": "person", "score": 0.95}, # correct + {"start": 16, "end": 21, "label": "person", "score": 0.92}, # wrong label + {"start": 16, "end": 21, "label": "city", "score": 0.35}, # correct + ] + ] + + r = span_reliability(FakeModel(), data, n_bins=10) + assert r["num_spans"] == 3 + top = r["bins"][9] + assert top["count"] == 2 and top["accuracy"] == pytest.approx(0.5) + assert r["bins"][3]["accuracy"] == pytest.approx(1.0) + expected = 2 / 3 * abs(0.935 - 0.5) + 1 / 3 * abs(0.35 - 1.0) + assert r["ece"] == pytest.approx(expected) + assert r["precision@0.5"] == pytest.approx(0.5) + assert r["recall@0.5"] == pytest.approx(0.5) + + +# --------------------------------------------------------------------------- +# GLiNER integration +# --------------------------------------------------------------------------- + + +@pytest.fixture(scope="module") +def tiny_gliner(): + from gliner import GLiNER # noqa: PLC0415 + + model = GLiNER.from_config( + {"model_name": "bert-base-uncased", "hidden_size": 32, "max_width": 4, "max_len": 64}, + ) + return model.to(torch.float32).eval() + + +def test_gliner_hook_calibrates_inference_and_round_trips(tiny_gliner, tmp_path): + from gliner import GLiNER # noqa: PLC0415 + + model = tiny_gliner + text, labels = "Barack Obama visited Paris", ["person", "city"] + collator = model.create_collator() + batch = collator([{"tokenized_text": text.split(), "ner": []}], entity_types=labels) + raw = model.run_batch(batch).logits.clone() + + calibrator = model.add_calibrator(candidate_threshold=0.0) + assert model.config.use_calibrator and model.calibrator is calibrator + calibrator.reset_to_global_scaling(0.5, 0.25) + out = model.run_batch(batch) + assert torch.allclose(out.uncalibrated_logits, raw) + valid = torch.isfinite(raw) & (raw > -1e3) + changed = ~torch.isclose(out.logits, raw) + assert changed.any() and (changed <= valid).all() + + with model.calibrator_disabled(): + assert torch.allclose(model.run_batch(batch).logits, raw) + + # With labels (training / loss computation) the hook is a no-op. + train_batch = model._create_data_collator()([{"tokenized_text": text.split(), "ner": [[0, 1, "person"]]}]) + train_out = model(**train_batch) + assert train_out.uncalibrated_logits is None + + model.save_pretrained(tmp_path) + loaded = GLiNER.from_pretrained(str(tmp_path)).to(torch.float32).eval() + assert type(loaded.calibrator).__name__ == "GLiNERCalibrator" + assert torch.allclose(loaded.run_batch(batch).logits, out.logits, atol=1e-5) + + model.remove_calibrator() + assert model.calibrator is None and not model.config.use_calibrator + assert torch.allclose(model.run_batch(batch).logits, raw) + + +def test_add_calibrator_rejects_unknown_options(tiny_gliner): + with pytest.raises(TypeError): + tiny_gliner.add_calibrator(not_an_option=1) + tiny_gliner.remove_calibrator() From 520e5debcf428e7c499868f0840e916a81f449f2 Mon Sep 17 00:00:00 2001 From: Ingvar Date: Sat, 31 Oct 2026 18:05:13 +0200 Subject: [PATCH 6/6] update transformers version --- pyproject.toml | 2 +- tests/test_models.py | 15 -- uv.lock | 350 +++++++++++++++++++++++++++++-------------- 3 files changed, 239 insertions(+), 128 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 1718d2cd..25efa6c0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,7 +36,7 @@ maintainers = [ dependencies = [ "torch>=2.0.0", - "transformers>=4.51.3,<5.17.0", + "transformers>=4.51.3,<5.23.0", "huggingface_hub>=0.21.4", "numpy", "packaging", diff --git a/tests/test_models.py b/tests/test_models.py index 32d1c7bb..0257c200 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -1,7 +1,6 @@ import torch import pytest -from gliner import GLiNER from gliner.model import ( BaseEncoderGLiNER, BiEncoderSpanGLiNER, @@ -27,20 +26,6 @@ def _minimal_encoder_model(cls=BaseEncoderGLiNER): return model -def test_span_model(): - model = GLiNER.from_pretrained("gliner-community/gliner_small-v2.5") - - text = """ - Cristiano Ronaldo dos Santos Aveiro (Portuguese pronunciation: [kɾiʃˈtjɐnu ʁɔˈnaldu]; born 5 February 1985) is a Portuguese professional footballer who plays as a forward for and captains both Saudi Pro League club Al Nassr and the Portugal national team. Widely regarded as one of the greatest players of all time, Ronaldo has won five Ballon d'Or awards,[note 3] a record three UEFA Men's Player of the Year Awards, and four European Golden Shoes, the most by a European player. He has won 33 trophies in his career, including seven league titles, five UEFA Champions Leagues, the UEFA European Championship and the UEFA Nations League. Ronaldo holds the records for most appearances (183), goals (140) and assists (42) in the Champions League, goals in the European Championship (14), international goals (128) and international appearances (205). He is one of the few players to have made over 1,200 professional career appearances, the most by an outfield player, and has scored over 850 official senior career goals for club and country, making him the top goalscorer of all time. - """ - - labels = ["person", "award", "date", "competitions", "teams", "person"] - - entities = model.predict_entities(text, labels) - - assert len(entities) > 0 - - def test_prepare_batch_aligns_per_text_labels_after_empty_text_filtering(): model = _minimal_encoder_model() diff --git a/uv.lock b/uv.lock index a853bec9..2fb77808 100644 --- a/uv.lock +++ b/uv.lock @@ -406,7 +406,8 @@ dependencies = [ { name = "tabulate" }, { name = "torch" }, { name = "tqdm" }, - { name = "transformers" }, + { name = "transformers", version = "5.20.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "transformers", version = "5.22.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/3c/68/f72e7c2d511aacc355dd0f96a4912ee03f49fbc09a559b593b4010e3997a/camel_tools-1.5.2.tar.gz", hash = "sha256:fb9973f4eb15678e3a3a8d4298954314fefab8a7d47d98d136ea0a9a1738b79a", size = 68366, upload-time = "2023-03-17T13:17:02.96Z" } wheels = [ @@ -620,14 +621,11 @@ wheels = [ [[package]] name = "click" -version = "8.3.2" +version = "8.5.0" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/57/75/31212c6bf2503fdf920d87fee5d7a86a2e3bcf444984126f13d8e4016804/click-8.3.2.tar.gz", hash = "sha256:14162b8b3b3550a7d479eafa77dfd3c38d9dc8951f6f69c78913a8f9a7540fd5", size = 302856, upload-time = "2026-04-03T19:14:45.118Z" } +sdist = { url = "https://files.pythonhosted.org/packages/c7/0e/7fa0ef50764b67090eca4114772a2abf8b6148198475e54c660b97caeee6/click-8.5.0.tar.gz", hash = "sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34", size = 382235, upload-time = "2026-08-26T13:33:14.56Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e4/20/71885d8b97d4f3dde17b1fdb92dbd4908b00541c5a3379787137285f602e/click-8.3.2-py3-none-any.whl", hash = "sha256:1924d2c27c5653561cd2cae4548d1406039cb79b858b747cfea24924bbc1616d", size = 108379, upload-time = "2026-04-03T19:14:43.505Z" }, + { url = "https://files.pythonhosted.org/packages/58/50/6c0d534c5f134586a8e1ba4e330569e32f057e33372ae556463212fb4cd3/click-8.5.0-py3-none-any.whl", hash = "sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360", size = 125251, upload-time = "2026-08-26T13:33:12.928Z" }, ] [[package]] @@ -1182,7 +1180,8 @@ dependencies = [ { name = "sentencepiece" }, { name = "torch" }, { name = "tqdm" }, - { name = "transformers" }, + { name = "transformers", version = "5.20.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "transformers", version = "5.22.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] [package.optional-dependencies] @@ -1249,7 +1248,7 @@ requires-dist = [ { name = "stanza", marker = "extra == 'tokenizers'" }, { name = "torch", specifier = ">=2.0.0" }, { name = "tqdm" }, - { name = "transformers", specifier = ">=4.51.3,<5.17.0" }, + { name = "transformers", specifier = ">=4.51.3,<5.23.0" }, ] provides-extras = ["onnx", "gpu", "openvino", "tokenizers", "training", "stanza", "serve"] @@ -1373,34 +1372,26 @@ wheels = [ [[package]] name = "hf-xet" -version = "1.4.3" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/53/92/ec9ad04d0b5728dca387a45af7bc98fbb0d73b2118759f5f6038b61a57e8/hf_xet-1.4.3.tar.gz", hash = "sha256:8ddedb73c8c08928c793df2f3401ec26f95be7f7e516a7bee2fbb546f6676113", size = 670477, upload-time = "2026-03-31T22:40:07.874Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/72/43/724d307b34e353da0abd476e02f72f735cdd2bc86082dee1b32ea0bfee1d/hf_xet-1.4.3-cp313-cp313t-macosx_10_12_x86_64.whl", hash = "sha256:7551659ba4f1e1074e9623996f28c3873682530aee0a846b7f2f066239228144", size = 3800935, upload-time = "2026-03-31T22:39:49.618Z" }, - { url = "https://files.pythonhosted.org/packages/2b/d2/8bee5996b699262edb87dbb54118d287c0e1b2fc78af7cdc41857ba5e3c4/hf_xet-1.4.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:bee693ada985e7045997f05f081d0e12c4c08bd7626dc397f8a7c487e6c04f7f", size = 3558942, upload-time = "2026-03-31T22:39:47.938Z" }, - { url = "https://files.pythonhosted.org/packages/c3/a1/e993d09cbe251196fb60812b09a58901c468127b7259d2bf0f68bf6088eb/hf_xet-1.4.3-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:21644b404bb0100fe3857892f752c4d09642586fd988e61501c95bbf44b393a3", size = 4207657, upload-time = "2026-03-31T22:39:39.69Z" }, - { url = "https://files.pythonhosted.org/packages/64/44/9eb6d21e5c34c63e5e399803a6932fa983cabdf47c0ecbcfe7ea97684b8c/hf_xet-1.4.3-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:987f09cfe418237812896a6736b81b1af02a3a6dcb4b4944425c4c4fca7a7cf8", size = 3986765, upload-time = "2026-03-31T22:39:37.936Z" }, - { url = "https://files.pythonhosted.org/packages/ea/7b/8ad6f16fdb82f5f7284a34b5ec48645bd575bdcd2f6f0d1644775909c486/hf_xet-1.4.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:60cf7fc43a99da0a853345cf86d23738c03983ee5249613a6305d3e57a5dca74", size = 4188162, upload-time = "2026-03-31T22:39:58.382Z" }, - { url = "https://files.pythonhosted.org/packages/1b/c4/39d6e136cbeea9ca5a23aad4b33024319222adbdc059ebcda5fc7d9d5ff4/hf_xet-1.4.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:2815a49a7a59f3e2edf0cf113ae88e8cb2ca2a221bf353fb60c609584f4884d4", size = 4424525, upload-time = "2026-03-31T22:40:00.225Z" }, - { url = "https://files.pythonhosted.org/packages/46/f2/adc32dae6bdbc367853118b9878139ac869419a4ae7ba07185dc31251b76/hf_xet-1.4.3-cp313-cp313t-win_amd64.whl", hash = "sha256:42ee323265f1e6a81b0e11094564fb7f7e0ec75b5105ffd91ae63f403a11931b", size = 3671610, upload-time = "2026-03-31T22:40:10.42Z" }, - { url = "https://files.pythonhosted.org/packages/e2/19/25d897dcc3f81953e0c2cde9ec186c7a0fee413eb0c9a7a9130d87d94d3a/hf_xet-1.4.3-cp313-cp313t-win_arm64.whl", hash = "sha256:27c976ba60079fb8217f485b9c5c7fcd21c90b0367753805f87cb9f3cdc4418a", size = 3528529, upload-time = "2026-03-31T22:40:09.106Z" }, - { url = "https://files.pythonhosted.org/packages/ec/36/3e8f85ca9fe09b8de2b2e10c63b3b3353d7dda88a0b3d426dffbe7b8313b/hf_xet-1.4.3-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:5251d5ece3a81815bae9abab41cf7ddb7bcb8f56411bce0827f4a3071c92fdc6", size = 3801019, upload-time = "2026-03-31T22:39:56.651Z" }, - { url = "https://files.pythonhosted.org/packages/b5/9c/defb6cb1de28bccb7bd8d95f6e60f72a3d3fa4cb3d0329c26fb9a488bfe7/hf_xet-1.4.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1feb0f3abeacee143367c326a128a2e2b60868ec12a36c225afb1d6c5a05e6d2", size = 3558746, upload-time = "2026-03-31T22:39:54.766Z" }, - { url = "https://files.pythonhosted.org/packages/c1/bd/8d001191893178ff8e826e46ad5299446e62b93cd164e17b0ffea08832ec/hf_xet-1.4.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8b301fc150290ca90b4fccd079829b84bb4786747584ae08b94b4577d82fb791", size = 4207692, upload-time = "2026-03-31T22:39:46.246Z" }, - { url = "https://files.pythonhosted.org/packages/ce/48/6790b402803250e9936435613d3a78b9aaeee7973439f0918848dde58309/hf_xet-1.4.3-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:d972fbe95ddc0d3c0fc49b31a8a69f47db35c1e3699bf316421705741aab6653", size = 3986281, upload-time = "2026-03-31T22:39:44.648Z" }, - { url = "https://files.pythonhosted.org/packages/51/56/ea62552fe53db652a9099eda600b032d75554d0e86c12a73824bfedef88b/hf_xet-1.4.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:c5b48db1ee344a805a1b9bd2cda9b6b65fe77ed3787bd6e87ad5521141d317cd", size = 4187414, upload-time = "2026-03-31T22:40:04.951Z" }, - { url = "https://files.pythonhosted.org/packages/7d/f5/bc1456d4638061bea997e6d2db60a1a613d7b200e0755965ec312dc1ef79/hf_xet-1.4.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:22bdc1f5fb8b15bf2831440b91d1c9bbceeb7e10c81a12e8d75889996a5c9da8", size = 4424368, upload-time = "2026-03-31T22:40:06.347Z" }, - { url = "https://files.pythonhosted.org/packages/e4/76/ab597bae87e1f06d18d3ecb8ed7f0d3c9a37037fc32ce76233d369273c64/hf_xet-1.4.3-cp314-cp314t-win_amd64.whl", hash = "sha256:0392c79b7cf48418cd61478c1a925246cf10639f4cd9d94368d8ca1e8df9ea07", size = 3672280, upload-time = "2026-03-31T22:40:16.401Z" }, - { url = "https://files.pythonhosted.org/packages/62/05/2e462d34e23a09a74d73785dbed71cc5dbad82a72eee2ad60a72a554155d/hf_xet-1.4.3-cp314-cp314t-win_arm64.whl", hash = "sha256:681c92a07796325778a79d76c67011764ecc9042a8c3579332b61b63ae512075", size = 3528945, upload-time = "2026-03-31T22:40:14.995Z" }, - { url = "https://files.pythonhosted.org/packages/ac/9f/9c23e4a447b8f83120798f9279d0297a4d1360bdbf59ef49ebec78fe2545/hf_xet-1.4.3-cp37-abi3-macosx_10_12_x86_64.whl", hash = "sha256:d0da85329eaf196e03e90b84c2d0aca53bd4573d097a75f99609e80775f98025", size = 3805048, upload-time = "2026-03-31T22:39:53.105Z" }, - { url = "https://files.pythonhosted.org/packages/0b/f8/7aacb8e5f4a7899d39c787b5984e912e6c18b11be136ef13947d7a66d265/hf_xet-1.4.3-cp37-abi3-macosx_11_0_arm64.whl", hash = "sha256:e23717ce4186b265f69afa66e6f0069fe7efbf331546f5c313d00e123dc84583", size = 3562178, upload-time = "2026-03-31T22:39:51.295Z" }, - { url = "https://files.pythonhosted.org/packages/df/9a/a24b26dc8a65f0ecc0fe5be981a19e61e7ca963b85e062c083f3a9100529/hf_xet-1.4.3-cp37-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:fc360b70c815bf340ed56c7b8c63aacf11762a4b099b2fe2c9bd6d6068668c08", size = 4212320, upload-time = "2026-03-31T22:39:42.922Z" }, - { url = "https://files.pythonhosted.org/packages/53/60/46d493db155d2ee2801b71fb1b0fd67696359047fdd8caee2c914cc50c79/hf_xet-1.4.3-cp37-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:39f2d2e9654cd9b4319885733993807aab6de9dfbd34c42f0b78338d6617421f", size = 3991546, upload-time = "2026-03-31T22:39:41.335Z" }, - { url = "https://files.pythonhosted.org/packages/bc/f5/067363e1c96c6b17256910830d1b54099d06287e10f4ec6ec4e7e08371fc/hf_xet-1.4.3-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:49ad8a8cead2b56051aa84d7fce3e1335efe68df3cf6c058f22a65513885baac", size = 4193200, upload-time = "2026-03-31T22:40:01.936Z" }, - { url = "https://files.pythonhosted.org/packages/42/4b/53951592882d9c23080c7644542fda34a3813104e9e11fa1a7d82d419cb8/hf_xet-1.4.3-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:7716d62015477a70ea272d2d68cd7cad140f61c52ee452e133e139abfe2c17ba", size = 4429392, upload-time = "2026-03-31T22:40:03.492Z" }, - { url = "https://files.pythonhosted.org/packages/8a/21/75a6c175b4e79662ad8e62f46a40ce341d8d6b206b06b4320d07d55b188c/hf_xet-1.4.3-cp37-abi3-win_amd64.whl", hash = "sha256:6b591fcad34e272a5b02607485e4f2a1334aebf1bc6d16ce8eb1eb8978ac2021", size = 3677359, upload-time = "2026-03-31T22:40:13.619Z" }, - { url = "https://files.pythonhosted.org/packages/8a/7c/44314ecd0e89f8b2b51c9d9e5e7a60a9c1c82024ac471d415860557d3cd8/hf_xet-1.4.3-cp37-abi3-win_arm64.whl", hash = "sha256:7c2c7e20bcfcc946dc67187c203463f5e932e395845d098cc2a93f5b67ca0b47", size = 3533664, upload-time = "2026-03-31T22:40:12.152Z" }, +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2f/18/d91c20f815df6cc496a5d0ad8db6d274dad5c0cfcd59babfa2440a9aba44/hf_xet-1.8.0.tar.gz", hash = "sha256:10ed23b51dacf7917d64f335c25048deb470efa755e9989b218fc0531386138e", size = 1013014, upload-time = "2026-10-30T10:04:33.741Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/18/db7ebc58820d82fd5506aa405a75611e7a4398f573dc436f7387603bf63d/hf_xet-1.8.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:c74e3751cbcdae9222c5170e8d788e83201a03dc5e5f4308a20f17a5b6023b56", size = 3883873, upload-time = "2026-10-30T10:04:03.24Z" }, + { url = "https://files.pythonhosted.org/packages/37/bd/6c9ed89aafbeb4a7ee0d76d6b7b9365221e3e7ee47958aeecdc2c60a0511/hf_xet-1.8.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:56735c2d4f416d7473fc986586b26a8756e067832ca4b7fdaad32a0d6f2ce740", size = 3594510, upload-time = "2026-10-30T10:04:05.364Z" }, + { url = "https://files.pythonhosted.org/packages/0e/1f/c26154b3a053b637c0984db0db9fdacbbfc257bdc2e95e9bc0782b745b0c/hf_xet-1.8.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3ecfe2934448cca55a4c42732b60f985266aecb241905945219b3d388aceb7ba", size = 4281780, upload-time = "2026-10-30T10:04:07.35Z" }, + { url = "https://files.pythonhosted.org/packages/e3/9e/d84c31f8e3acc286c9c6a4fd85f7f332e3db40636595f0de5ad776b69beb/hf_xet-1.8.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:7edeb21c5d381903ee5f4857fc746fa7b52a4b374035e8811ecfb67ee27add0c", size = 4060223, upload-time = "2026-10-30T10:04:09.029Z" }, + { url = "https://files.pythonhosted.org/packages/a4/70/c142e4ad8a679ff6ffe40964a9d017fa0211aabca9ca4d3d547c3a2fc165/hf_xet-1.8.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:07a06d7481702616726c2d8578cfb00052a5b3f21beed6a674592bc837a10330", size = 4263619, upload-time = "2026-10-30T10:04:11.085Z" }, + { url = "https://files.pythonhosted.org/packages/9d/08/92e03e3ac4eaeab046359093c447c03c8c30b577c2b1e1687dc747654f1c/hf_xet-1.8.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f42940869572dc2b05dfe06f4cc398c6291503e086ddc4eddfb7a6ab9409ad01", size = 4493381, upload-time = "2026-10-30T10:04:13.022Z" }, + { url = "https://files.pythonhosted.org/packages/61/63/a512b2906d0f92b5d325f58169d1fd8c3202a9ee61bd8405ec78c67e5315/hf_xet-1.8.0-cp314-cp314t-win_amd64.whl", hash = "sha256:23c262e9f5e137b18dadbce60becfeea84156b0d43119c320bffe260d32cd2fa", size = 3901344, upload-time = "2026-10-30T10:04:15.051Z" }, + { url = "https://files.pythonhosted.org/packages/2d/5e/b453f82690cb36f176c4b01e64d6d32757fabbf34dbb9bcbdf747e429a79/hf_xet-1.8.0-cp314-cp314t-win_arm64.whl", hash = "sha256:62b056aedb89ac809f78940baf465fe553b70c8b25ee56890fbab3039fffec1b", size = 3731681, upload-time = "2026-10-30T10:04:16.855Z" }, + { url = "https://files.pythonhosted.org/packages/97/74/d89d5235524bc14d8519e12ca8bc5204f45009ae83d63a410f52c29eb4a8/hf_xet-1.8.0-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e00d8f60170cd3dd55d98306e41dbaf28b27ff1bcfefbfa84279d197221be83e", size = 3875002, upload-time = "2026-10-30T10:04:18.958Z" }, + { url = "https://files.pythonhosted.org/packages/d4/f2/ef25e2085e92dcaeaa675331e443923aed2006f6fe2d984e15d8b8d40766/hf_xet-1.8.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:3e8934784425781f0f779b91044df441f3a7af4dab47375d7e3aeaecbb8eecb4", size = 3600947, upload-time = "2026-10-30T10:04:20.906Z" }, + { url = "https://files.pythonhosted.org/packages/f8/1e/1e8ecc05ef034e9a95c18ed32d2ec07905a7cd2ca611a9d88e25ee1f4850/hf_xet-1.8.0-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:29dab7c904cd1914a0439c6e1306c12c7497c8bd32290fbe563ebf51ca4b6d6d", size = 4292483, upload-time = "2026-10-30T10:04:22.875Z" }, + { url = "https://files.pythonhosted.org/packages/35/c4/127a1548df019ea4c80f06e685f263e146075143335a02e78a3c41dbc4eb/hf_xet-1.8.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:8800e3444770f2c630b361bc6d5c6ebb770b7830646cf632fbb79d0e5bbc9e7f", size = 4069340, upload-time = "2026-10-30T10:04:24.664Z" }, + { url = "https://files.pythonhosted.org/packages/a5/d5/281cd82736c3e181e597588589d2204d3a5c388a464d4a2a8c546995bae9/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:a584a7b3268da62f23c3187cc7201ca01f7b610985a36b1b6119c66bccb0383c", size = 4272344, upload-time = "2026-10-30T10:04:26.519Z" }, + { url = "https://files.pythonhosted.org/packages/48/77/886f09e91a5eadb054ce03b8855323cd2a72f20db76ab4119e0ecda65eef/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1ebaf248c9bef8bb0c9d1d8d71db1fdf0cac14f922cc7a936a81adbf12eb5f01", size = 4500689, upload-time = "2026-10-30T10:04:28.394Z" }, + { url = "https://files.pythonhosted.org/packages/97/4d/2c76a992b370ff77d0b5219275779f8c9a7dabb8ee649deb265dfed84d0f/hf_xet-1.8.0-cp38-abi3-win_amd64.whl", hash = "sha256:92188598dedc1e1f5609bd718d4db8687a6c89915553912571e2f587892eecec", size = 3911559, upload-time = "2026-10-30T10:04:30.165Z" }, + { url = "https://files.pythonhosted.org/packages/87/91/fdb1454a43eff8011047d176ada2f0fb4926cf3d74b87357ff35793f6d98/hf_xet-1.8.0-cp38-abi3-win_arm64.whl", hash = "sha256:42b66fdc688eaa4ff3eb77dc9275e5a0f1258ecc9fdd083ddaf43bb49bec925b", size = 3738458, upload-time = "2026-10-30T10:04:31.882Z" }, ] [[package]] @@ -1416,6 +1407,45 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, ] +[[package]] +name = "httpcore2" +version = "2.14.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "h11", marker = "python_full_version < '3.11'" }, + { name = "truststore", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/30/ff/b53af1b49bb2cb5fa97c92215614b173ca5c1a99ded80e2d52f15a94fa6d/httpcore2-2.14.0.tar.gz", hash = "sha256:4f57a1a8249fe6af589d935cfd456f1d13bbdcb0f0fc72af9142368fc94811d7", size = 69096, upload-time = "2026-10-18T16:29:21.898Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/02/06/a8d6a8f90d11b76d9086242b6bb0ee4b503473bfc8be34c2d5b067275c22/httpcore2-2.14.0-py3-none-any.whl", hash = "sha256:4c4f64f4b544afeb778c42c0ffb5941b29e671157e90ed3f6dc787c4bca90cd1", size = 84291, upload-time = "2026-10-18T16:29:19.743Z" }, +] + +[[package]] +name = "httpcore2" +version = "2.16.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.11.*' and sys_platform == 'win32'", + "python_full_version == '3.11.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "h11", marker = "python_full_version >= '3.11' and sys_platform != 'emscripten'" }, + { name = "truststore", marker = "python_full_version >= '3.11' and sys_platform != 'emscripten'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c0/61/afa9d6b7452f9eca73f73d45324eb0bb52f098fd5e6049bf6b8263be9b4e/httpcore2-2.16.0.tar.gz", hash = "sha256:c72cd0413563b17e1cd8354677dff887466f8ec2551679759e93126534428643", size = 69886, upload-time = "2026-10-21T07:09:45.31Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/af/c2/ce417c397afa5181f0e3c6ff01a4d01639414e1adef08730d97571297151/httpcore2-2.16.0-py3-none-any.whl", hash = "sha256:5c4358319f2602d984ad93182c9fee5160f22e9da7babdda870a5e7c4e2dc34f", size = 85070, upload-time = "2026-10-21T07:09:42.802Z" }, +] + [[package]] name = "httptools" version = "0.7.1" @@ -1474,33 +1504,94 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, ] +[[package]] +name = "httpx2" +version = "2.14.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "anyio", marker = "python_full_version < '3.11' and sys_platform != 'emscripten'" }, + { name = "httpcore2", version = "2.14.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11' and sys_platform != 'emscripten'" }, + { name = "idna", marker = "python_full_version < '3.11'" }, + { name = "truststore", marker = "python_full_version < '3.11' and sys_platform != 'emscripten'" }, + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e8/67/58353f1848b4ba568e1ec22ea1e0d8e039f0bca5fde7e2d1f07739fd83e7/httpx2-2.14.0.tar.gz", hash = "sha256:47ad61a3c40282cd8d0dc96311531f00f5bfc71a066c6fe3b36d8f63fb9e4f6e", size = 102036, upload-time = "2026-10-18T16:29:22.627Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/5a/469616aa8c2cbb0bb9dd67a3c18d07c01ab604cc0b236ee1c47d260c7f6e/httpx2-2.14.0-py3-none-any.whl", hash = "sha256:9d20c13a10bae1773a0be3b0f1e5beeb4bdd549bc3a2ba18efa32897c65403e4", size = 96901, upload-time = "2026-10-18T16:29:20.819Z" }, +] + +[[package]] +name = "httpx2" +version = "2.16.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.11.*' and sys_platform == 'win32'", + "python_full_version == '3.11.*' and sys_platform == 'emscripten'", + "python_full_version == '3.11.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "anyio", marker = "python_full_version >= '3.11' and sys_platform != 'emscripten'" }, + { name = "httpcore2", version = "2.16.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11' and sys_platform != 'emscripten'" }, + { name = "httpx2-jsfetch", marker = "python_full_version >= '3.12' and sys_platform == 'emscripten'" }, + { name = "idna", marker = "python_full_version >= '3.11'" }, + { name = "truststore", marker = "python_full_version >= '3.11' and sys_platform != 'emscripten'" }, + { name = "typing-extensions", marker = "python_full_version >= '3.11' and python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/43/73/5ca2cedf5e4e50423d1c258877865a6b62793633b561c58499f8aeb33b7e/httpx2-2.16.0.tar.gz", hash = "sha256:0d54c98128e8f2ff7fbbde0fca8c359e5f032edeaaaac443cdb7f31f685bcd7f", size = 103116, upload-time = "2026-10-21T07:09:46.348Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7b/3d/2e4bc4fd1ef9770871669adb348d612a6e4786b303a23f9935b81c48dd60/httpx2-2.16.0-py3-none-any.whl", hash = "sha256:fd2c5d7909e8d86fe92d53020c310ca0e4e431b838c207c5754b9bbf0308d49a", size = 97880, upload-time = "2026-10-21T07:09:44.01Z" }, +] + +[[package]] +name = "httpx2-jsfetch" +version = "1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/c4/0e5636363151a2a1795e0a77617168b9ca438e1748ec05fc9b5687f93d64/httpx2_jsfetch-1.0.tar.gz", hash = "sha256:70a0e3eabfef7cce5ad9c629f7d01ca05e418f586646f4ddf14782e4c1454c60", size = 6872, upload-time = "2026-08-07T00:13:07.492Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9b/43/832f631d32e4f1211caa2ba368317739fe71f0b8530e4c9d15dc454bac2a/httpx2_jsfetch-1.0-py3-none-any.whl", hash = "sha256:cb916b707601e69a07721aabc8f3f6659be3a6893bc1ff5c6f9e02241df2da32", size = 6382, upload-time = "2026-08-07T00:13:06.567Z" }, +] + [[package]] name = "huggingface-hub" -version = "1.11.0" +version = "2.4.0" source = { registry = "https://pypi.org/simple" } dependencies = [ + { name = "click" }, { name = "filelock" }, { name = "fsspec" }, - { name = "hf-xet", marker = "platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" }, - { name = "httpx" }, + { name = "hf-xet", marker = "platform_machine == 'AMD64' or platform_machine == 'ARM64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" }, + { name = "httpx2", version = "2.14.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "httpx2", version = "2.16.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "packaging" }, { name = "pyyaml" }, + { name = "tomli", marker = "python_full_version < '3.11'" }, { name = "tqdm" }, - { name = "typer" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/dc/89/e7aa12d8a6b9259bed10671abb25ae6fa437c0f88a86ecbf59617bae7759/huggingface_hub-1.11.0.tar.gz", hash = "sha256:15fb3713c7f9cdff7b808a94fd91664f661ab142796bb48c9cd9493e8d166278", size = 761749, upload-time = "2026-04-16T13:07:39.73Z" } +sdist = { url = "https://files.pythonhosted.org/packages/b5/3b/2fcef1eabe52aec90fc8cd253cc154da1d02a446d7bbcdec59b4a51d4be7/huggingface_hub-2.4.0.tar.gz", hash = "sha256:13a6158b9e3393d9d3f248ce99074d50c2a0a1449fb9d8e2f710751e2084c188", size = 1066194, upload-time = "2026-10-29T15:30:12.321Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/37/02/4f3f8997d1ea7fe0146b343e5e14bd065fa87af790d07e5576d31b31cc18/huggingface_hub-1.11.0-py3-none-any.whl", hash = "sha256:42a6de0afbfeb5e022222d36398f029679db4eb4778801aafda32257ae9131ab", size = 645499, upload-time = "2026-04-16T13:07:37.716Z" }, + { url = "https://files.pythonhosted.org/packages/d4/55/ff47f1b082ecf5f43f4bc1e3b932d68eead171dabbbd1a92666c686301d7/huggingface_hub-2.4.0-py3-none-any.whl", hash = "sha256:42ecfd93ede47bdd333daebbf66a32d7bfe2e18752754fe4d2d4f98a0179d801", size = 857021, upload-time = "2026-10-29T15:30:10.421Z" }, ] [[package]] name = "idna" -version = "3.11" +version = "3.20" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/6f/6d/0703ccc57f3a7233505399edb88de3cbd678da106337b9fcde432b65ed60/idna-3.11.tar.gz", hash = "sha256:795dafcc9c04ed0c1fb032c2aa73654d8e8c5023a7df64a53f39190ada629902", size = 194582, upload-time = "2025-10-12T14:55:20.501Z" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/0e/61/66938bbb5fc52dbdf84594873d5b51fb1f7c7794e9c0f5bd885f30bc507b/idna-3.11-py3-none-any.whl", hash = "sha256:771a87f49d9defaf64091e6e6fe9c18d4833f140bd19464795bc32d966ca37ea", size = 71008, upload-time = "2025-10-12T14:55:18.883Z" }, + { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, ] [[package]] @@ -3838,28 +3929,26 @@ wheels = [ [[package]] name = "safetensors" -version = "0.7.0" +version = "0.8.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/29/9c/6e74567782559a63bd040a236edca26fd71bc7ba88de2ef35d75df3bca5e/safetensors-0.7.0.tar.gz", hash = "sha256:07663963b67e8bd9f0b8ad15bb9163606cd27cc5a1b96235a50d8369803b96b0", size = 200878, upload-time = "2025-11-19T15:18:43.199Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/fa/47/aef6c06649039accf914afef490268e1067ed82be62bcfa5b7e886ad15e8/safetensors-0.7.0-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:c82f4d474cf725255d9e6acf17252991c3c8aac038d6ef363a4bf8be2f6db517", size = 467781, upload-time = "2025-11-19T15:18:35.84Z" }, - { url = "https://files.pythonhosted.org/packages/e8/00/374c0c068e30cd31f1e1b46b4b5738168ec79e7689ca82ee93ddfea05109/safetensors-0.7.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:94fd4858284736bb67a897a41608b5b0c2496c9bdb3bf2af1fa3409127f20d57", size = 447058, upload-time = "2025-11-19T15:18:34.416Z" }, - { url = "https://files.pythonhosted.org/packages/f1/06/578ffed52c2296f93d7fd2d844cabfa92be51a587c38c8afbb8ae449ca89/safetensors-0.7.0-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e07d91d0c92a31200f25351f4acb2bc6aff7f48094e13ebb1d0fb995b54b6542", size = 491748, upload-time = "2025-11-19T15:18:09.79Z" }, - { url = "https://files.pythonhosted.org/packages/ae/33/1debbbb70e4791dde185edb9413d1fe01619255abb64b300157d7f15dddd/safetensors-0.7.0-cp38-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8469155f4cb518bafb4acf4865e8bb9d6804110d2d9bdcaa78564b9fd841e104", size = 503881, upload-time = "2025-11-19T15:18:16.145Z" }, - { url = "https://files.pythonhosted.org/packages/8e/1c/40c2ca924d60792c3be509833df711b553c60effbd91da6f5284a83f7122/safetensors-0.7.0-cp38-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:54bef08bf00a2bff599982f6b08e8770e09cc012d7bba00783fc7ea38f1fb37d", size = 623463, upload-time = "2025-11-19T15:18:21.11Z" }, - { url = "https://files.pythonhosted.org/packages/9b/3a/13784a9364bd43b0d61eef4bea2845039bc2030458b16594a1bd787ae26e/safetensors-0.7.0-cp38-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:42cb091236206bb2016d245c377ed383aa7f78691748f3bb6ee1bfa51ae2ce6a", size = 532855, upload-time = "2025-11-19T15:18:25.719Z" }, - { url = "https://files.pythonhosted.org/packages/a0/60/429e9b1cb3fc651937727befe258ea24122d9663e4d5709a48c9cbfceecb/safetensors-0.7.0-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dac7252938f0696ddea46f5e855dd3138444e82236e3be475f54929f0c510d48", size = 507152, upload-time = "2025-11-19T15:18:33.023Z" }, - { url = "https://files.pythonhosted.org/packages/3c/a8/4b45e4e059270d17af60359713ffd83f97900d45a6afa73aaa0d737d48b6/safetensors-0.7.0-cp38-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:1d060c70284127fa805085d8f10fbd0962792aed71879d00864acda69dbab981", size = 541856, upload-time = "2025-11-19T15:18:31.075Z" }, - { url = "https://files.pythonhosted.org/packages/06/87/d26d8407c44175d8ae164a95b5a62707fcc445f3c0c56108e37d98070a3d/safetensors-0.7.0-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:cdab83a366799fa730f90a4ebb563e494f28e9e92c4819e556152ad55e43591b", size = 674060, upload-time = "2025-11-19T15:18:37.211Z" }, - { url = "https://files.pythonhosted.org/packages/11/f5/57644a2ff08dc6325816ba7217e5095f17269dada2554b658442c66aed51/safetensors-0.7.0-cp38-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:672132907fcad9f2aedcb705b2d7b3b93354a2aec1b2f706c4db852abe338f85", size = 771715, upload-time = "2025-11-19T15:18:38.689Z" }, - { url = "https://files.pythonhosted.org/packages/86/31/17883e13a814bd278ae6e266b13282a01049b0c81341da7fd0e3e71a80a3/safetensors-0.7.0-cp38-abi3-musllinux_1_2_i686.whl", hash = "sha256:5d72abdb8a4d56d4020713724ba81dac065fedb7f3667151c4a637f1d3fb26c0", size = 714377, upload-time = "2025-11-19T15:18:40.162Z" }, - { url = "https://files.pythonhosted.org/packages/4a/d8/0c8a7dc9b41dcac53c4cbf9df2b9c83e0e0097203de8b37a712b345c0be5/safetensors-0.7.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b0f6d66c1c538d5a94a73aa9ddca8ccc4227e6c9ff555322ea40bdd142391dd4", size = 677368, upload-time = "2025-11-19T15:18:41.627Z" }, - { url = "https://files.pythonhosted.org/packages/05/e5/cb4b713c8a93469e3c5be7c3f8d77d307e65fe89673e731f5c2bfd0a9237/safetensors-0.7.0-cp38-abi3-win32.whl", hash = "sha256:c74af94bf3ac15ac4d0f2a7c7b4663a15f8c2ab15ed0fc7531ca61d0835eccba", size = 326423, upload-time = "2025-11-19T15:18:45.74Z" }, - { url = "https://files.pythonhosted.org/packages/5d/e6/ec8471c8072382cb91233ba7267fd931219753bb43814cbc71757bfd4dab/safetensors-0.7.0-cp38-abi3-win_amd64.whl", hash = "sha256:d1239932053f56f3456f32eb9625590cc7582e905021f94636202a864d470755", size = 341380, upload-time = "2025-11-19T15:18:44.427Z" }, - { url = "https://files.pythonhosted.org/packages/a7/6a/4d08d89a6fcbe905c5ae68b8b34f0791850882fc19782d0d02c65abbdf3b/safetensors-0.7.0-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f4729811a6640d019a4b7ba8638ee2fd21fa5ca8c7e7bdf0fed62068fcaac737", size = 492430, upload-time = "2025-11-19T15:18:11.884Z" }, - { url = "https://files.pythonhosted.org/packages/dd/29/59ed8152b30f72c42d00d241e58eaca558ae9dbfa5695206e2e0f54c7063/safetensors-0.7.0-pp310-pypy310_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:12f49080303fa6bb424b362149a12949dfbbf1e06811a88f2307276b0c131afd", size = 503977, upload-time = "2025-11-19T15:18:17.523Z" }, - { url = "https://files.pythonhosted.org/packages/d3/0b/4811bfec67fa260e791369b16dab105e4bae82686120554cc484064e22b4/safetensors-0.7.0-pp310-pypy310_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0071bffba4150c2f46cae1432d31995d77acfd9f8db598b5d1a2ce67e8440ad2", size = 623890, upload-time = "2025-11-19T15:18:22.666Z" }, - { url = "https://files.pythonhosted.org/packages/58/5b/632a58724221ef03d78ab65062e82a1010e1bef8e8e0b9d7c6d7b8044841/safetensors-0.7.0-pp310-pypy310_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:473b32699f4200e69801bf5abf93f1a4ecd432a70984df164fc22ccf39c4a6f3", size = 531885, upload-time = "2025-11-19T15:18:27.146Z" }, +sdist = { url = "https://files.pythonhosted.org/packages/45/06/f955dbbb1859e3bd23c8ac6141af5106e7ad5fedec4a3a6e3d60f94b7001/safetensors-0.8.0.tar.gz", hash = "sha256:fabaf3e0f18a6618d9b36560682562157f77c2b71fcffc7b432be2baed9d753d", size = 325846, upload-time = "2026-06-09T07:52:25.563Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/39/a0/f718cda65b05407d228f97602cf60dca269c979867aa5beb25410de26cd3/safetensors-0.8.0-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:c554f85858e05226d3c2828e32395e677434685d6d94594a41643361c5e837f0", size = 473568, upload-time = "2026-06-09T07:52:18.829Z" }, + { url = "https://files.pythonhosted.org/packages/f5/b1/fa7c600e7dceae12e9606c7578cbc9ff1e1ed55844883ee5c92205e86226/safetensors-0.8.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c80201d22cbf405b80647a60ada77bba06c8fba2da2743ba1e89cdcc39a81f25", size = 484562, upload-time = "2026-06-09T07:52:17.518Z" }, + { url = "https://files.pythonhosted.org/packages/09/7d/65a7de0af421317bb36a067241e4235fff194eed60b961ed6d3f59a3fc60/safetensors-0.8.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7a46e5ff292c356d6991e60942ba7f79817682d3a2cef0702136448cb9c4d235", size = 502844, upload-time = "2026-06-09T07:52:07.624Z" }, + { url = "https://files.pythonhosted.org/packages/91/4f/3175c9d75634e0e0dda0082794193521035edd7c70a6f212bf33ca06ddf4/safetensors-0.8.0-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4124502b78f03534117c848f87a39b8f31e577b15eff423bf8bfb95f2a8c30d0", size = 511823, upload-time = "2026-06-09T07:52:09.565Z" }, + { url = "https://files.pythonhosted.org/packages/20/87/846c289e7aa2299eff406335717cf43ce8777194ece8aad75772e0411615/safetensors-0.8.0-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7bc0a787ba8a35be368ee3574edfa2b1ad389eebd0a72e482ae275490e3f6c98", size = 633461, upload-time = "2026-06-09T07:52:11.128Z" }, + { url = "https://files.pythonhosted.org/packages/76/22/8d64d9df2c45d5ded401df889d0ad90882804ca172d79ec4f0df8f727fe0/safetensors-0.8.0-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:040070828e36dc8e122178bbbd5830ff9e97920affb84cbe0f46442497bed358", size = 545148, upload-time = "2026-06-09T07:52:13.603Z" }, + { url = "https://files.pythonhosted.org/packages/28/50/f203ff3a3ddfe19308efc83c5a3a29ed02bf786732ec35e68bf9162f3365/safetensors-0.8.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd6f3f93c9a0a7cc2788ee63fb763353d4bd2e89b0751bc78fcf7dda00bea774", size = 516040, upload-time = "2026-06-09T07:52:16.29Z" }, + { url = "https://files.pythonhosted.org/packages/46/fb/cdaed17ceb2948784fd9c36b6fd3e951b608547cea81a48e8ee6f8cfdfcb/safetensors-0.8.0-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:fcdd41ec4628fee5799f807c73c353629130fbd942aa23d83c623dd6c9d52d78", size = 513832, upload-time = "2026-06-09T07:52:12.37Z" }, + { url = "https://files.pythonhosted.org/packages/0d/49/1e15de264dcc3b77943d2d0c56a95809956883b1c2d6d585c792523f180b/safetensors-0.8.0-cp310-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8e9f537aa183a38ace122d27303dcd986b26bd2a7591f9181d7f0c396f4677ca", size = 559930, upload-time = "2026-06-09T07:52:14.743Z" }, + { url = "https://files.pythonhosted.org/packages/2a/43/bf38443278eab4b1be1fce2931e2b012ad9cb7df52ada751d0aab8f7659a/safetensors-0.8.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:87eec7ffed2b809f05a398a8becb7d013f19f7837cd15d9748580d6cf30dbaf4", size = 678670, upload-time = "2026-06-09T07:52:20.032Z" }, + { url = "https://files.pythonhosted.org/packages/72/e3/68cd3fa5b48488e84add63e04cb12f3bc28ae4638c06d4508c6e88823d0e/safetensors-0.8.0-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:4a95ae2b05d7726d751da4ebf626a2ca782b706e101bd894c95bc2450b1cffcc", size = 786679, upload-time = "2026-06-09T07:52:21.322Z" }, + { url = "https://files.pythonhosted.org/packages/29/4b/1c19c509d56e01f4fbb3d0a2e597450f6cc04d1d56cf52defb0a62dfd715/safetensors-0.8.0-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:3ae091f16662658bdc019a4ff6cb4c085bb7d725eb5978b183ffd265863b6d2d", size = 765683, upload-time = "2026-06-09T07:52:22.594Z" }, + { url = "https://files.pythonhosted.org/packages/27/43/41c1621732edd934d868a00d1b891584c892a7b62a9aab82ea5a0a5623ee/safetensors-0.8.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:8e080062fcde23be189565e1c3305d16751a218ecf9412c8601e64204eb6f846", size = 722361, upload-time = "2026-06-09T07:52:23.924Z" }, + { url = "https://files.pythonhosted.org/packages/8e/3f/73ccf82579412b4a71c4ca673f10b5f1f888d7cf5af7fe24f27d30307be4/safetensors-0.8.0-cp310-abi3-win32.whl", hash = "sha256:2ddf52eac562eda224f99acfa7889d02968c1fd59a5b011ae7d8137c37e9c02d", size = 342401, upload-time = "2026-06-09T07:52:28.895Z" }, + { url = "https://files.pythonhosted.org/packages/1b/6d/3fba214c1e5e0f69991677ec3bc17023f0421776975e1de0c682dca475e2/safetensors-0.8.0-cp310-abi3-win_amd64.whl", hash = "sha256:096ec1a98435df7beb08853bb5aa9081a84f23d0adc67ed1a0a10550f608373f", size = 355540, upload-time = "2026-06-09T07:52:27.832Z" }, + { url = "https://files.pythonhosted.org/packages/8d/fc/7eedc3510d97878876e32774eebbeb61c43f148a96e915c84229a3e967aa/safetensors-0.8.0-cp310-abi3-win_arm64.whl", hash = "sha256:f7838e5135a406ad3e02efdcb8cf2e5397d368b0154537c4fec682dbc544d452", size = 340500, upload-time = "2026-06-09T07:52:26.745Z" }, ] [[package]] @@ -4708,32 +4797,36 @@ wheels = [ [[package]] name = "tokenizers" -version = "0.22.2" +version = "0.23.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "huggingface-hub" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/73/6f/f80cfef4a312e1fb34baf7d85c72d4411afde10978d4657f8cdd811d3ccc/tokenizers-0.22.2.tar.gz", hash = "sha256:473b83b915e547aa366d1eee11806deaf419e17be16310ac0a14077f1e28f917", size = 372115, upload-time = "2026-01-05T10:45:15.988Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/92/97/5dbfabf04c7e348e655e907ed27913e03db0923abb5dfdd120d7b25630e1/tokenizers-0.22.2-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:544dd704ae7238755d790de45ba8da072e9af3eea688f698b137915ae959281c", size = 3100275, upload-time = "2026-01-05T10:41:02.158Z" }, - { url = "https://files.pythonhosted.org/packages/2e/47/174dca0502ef88b28f1c9e06b73ce33500eedfac7a7692108aec220464e7/tokenizers-0.22.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:1e418a55456beedca4621dbab65a318981467a2b188e982a23e117f115ce5001", size = 2981472, upload-time = "2026-01-05T10:41:00.276Z" }, - { url = "https://files.pythonhosted.org/packages/d6/84/7990e799f1309a8b87af6b948f31edaa12a3ed22d11b352eaf4f4b2e5753/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2249487018adec45d6e3554c71d46eb39fa8ea67156c640f7513eb26f318cec7", size = 3290736, upload-time = "2026-01-05T10:40:32.165Z" }, - { url = "https://files.pythonhosted.org/packages/78/59/09d0d9ba94dcd5f4f1368d4858d24546b4bdc0231c2354aa31d6199f0399/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:25b85325d0815e86e0bac263506dd114578953b7b53d7de09a6485e4a160a7dd", size = 3168835, upload-time = "2026-01-05T10:40:38.847Z" }, - { url = "https://files.pythonhosted.org/packages/47/50/b3ebb4243e7160bda8d34b731e54dd8ab8b133e50775872e7a434e524c28/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bfb88f22a209ff7b40a576d5324bf8286b519d7358663db21d6246fb17eea2d5", size = 3521673, upload-time = "2026-01-05T10:40:56.614Z" }, - { url = "https://files.pythonhosted.org/packages/e0/fa/89f4cb9e08df770b57adb96f8cbb7e22695a4cb6c2bd5f0c4f0ebcf33b66/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1c774b1276f71e1ef716e5486f21e76333464f47bece56bbd554485982a9e03e", size = 3724818, upload-time = "2026-01-05T10:40:44.507Z" }, - { url = "https://files.pythonhosted.org/packages/64/04/ca2363f0bfbe3b3d36e95bf67e56a4c88c8e3362b658e616d1ac185d47f2/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:df6c4265b289083bf710dff49bc51ef252f9d5be33a45ee2bed151114a56207b", size = 3379195, upload-time = "2026-01-05T10:40:51.139Z" }, - { url = "https://files.pythonhosted.org/packages/2e/76/932be4b50ef6ccedf9d3c6639b056a967a86258c6d9200643f01269211ca/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:369cc9fc8cc10cb24143873a0d95438bb8ee257bb80c71989e3ee290e8d72c67", size = 3274982, upload-time = "2026-01-05T10:40:58.331Z" }, - { url = "https://files.pythonhosted.org/packages/1d/28/5f9f5a4cc211b69e89420980e483831bcc29dade307955cc9dc858a40f01/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:29c30b83d8dcd061078b05ae0cb94d3c710555fbb44861139f9f83dcca3dc3e4", size = 9478245, upload-time = "2026-01-05T10:41:04.053Z" }, - { url = "https://files.pythonhosted.org/packages/6c/fb/66e2da4704d6aadebf8cb39f1d6d1957df667ab24cff2326b77cda0dcb85/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:37ae80a28c1d3265bb1f22464c856bd23c02a05bb211e56d0c5301a435be6c1a", size = 9560069, upload-time = "2026-01-05T10:45:10.673Z" }, - { url = "https://files.pythonhosted.org/packages/16/04/fed398b05caa87ce9b1a1bb5166645e38196081b225059a6edaff6440fac/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:791135ee325f2336f498590eb2f11dc5c295232f288e75c99a36c5dbce63088a", size = 9899263, upload-time = "2026-01-05T10:45:12.559Z" }, - { url = "https://files.pythonhosted.org/packages/05/a1/d62dfe7376beaaf1394917e0f8e93ee5f67fea8fcf4107501db35996586b/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:38337540fbbddff8e999d59970f3c6f35a82de10053206a7562f1ea02d046fa5", size = 10033429, upload-time = "2026-01-05T10:45:14.333Z" }, - { url = "https://files.pythonhosted.org/packages/fd/18/a545c4ea42af3df6effd7d13d250ba77a0a86fb20393143bbb9a92e434d4/tokenizers-0.22.2-cp39-abi3-win32.whl", hash = "sha256:a6bf3f88c554a2b653af81f3204491c818ae2ac6fbc09e76ef4773351292bc92", size = 2502363, upload-time = "2026-01-05T10:45:20.593Z" }, - { url = "https://files.pythonhosted.org/packages/65/71/0670843133a43d43070abeb1949abfdef12a86d490bea9cd9e18e37c5ff7/tokenizers-0.22.2-cp39-abi3-win_amd64.whl", hash = "sha256:c9ea31edff2968b44a88f97d784c2f16dc0729b8b143ed004699ebca91f05c48", size = 2747786, upload-time = "2026-01-05T10:45:18.411Z" }, - { url = "https://files.pythonhosted.org/packages/72/f4/0de46cfa12cdcbcd464cc59fde36912af405696f687e53a091fb432f694c/tokenizers-0.22.2-cp39-abi3-win_arm64.whl", hash = "sha256:9ce725d22864a1e965217204946f830c37876eee3b2ba6fc6255e8e903d5fcbc", size = 2612133, upload-time = "2026-01-05T10:45:17.232Z" }, - { url = "https://files.pythonhosted.org/packages/84/04/655b79dbcc9b3ac5f1479f18e931a344af67e5b7d3b251d2dcdcd7558592/tokenizers-0.22.2-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:753d47ebd4542742ef9261d9da92cd545b2cacbb48349a1225466745bb866ec4", size = 3282301, upload-time = "2026-01-05T10:40:34.858Z" }, - { url = "https://files.pythonhosted.org/packages/46/cd/e4851401f3d8f6f45d8480262ab6a5c8cb9c4302a790a35aa14eeed6d2fd/tokenizers-0.22.2-pp310-pypy310_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e10bf9113d209be7cd046d40fbabbaf3278ff6d18eb4da4c500443185dc1896c", size = 3161308, upload-time = "2026-01-05T10:40:40.737Z" }, - { url = "https://files.pythonhosted.org/packages/6f/6e/55553992a89982cd12d4a66dddb5e02126c58677ea3931efcbe601d419db/tokenizers-0.22.2-pp310-pypy310_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:64d94e84f6660764e64e7e0b22baa72f6cd942279fdbb21d46abd70d179f0195", size = 3718964, upload-time = "2026-01-05T10:40:46.56Z" }, - { url = "https://files.pythonhosted.org/packages/59/8c/b1c87148aa15e099243ec9f0cf9d0e970cc2234c3257d558c25a2c5304e6/tokenizers-0.22.2-pp310-pypy310_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f01a9c019878532f98927d2bacb79bbb404b43d3437455522a00a30718cdedb5", size = 3373542, upload-time = "2026-01-05T10:40:52.803Z" }, +sdist = { url = "https://files.pythonhosted.org/packages/e0/7c/2cabb2174e772636683008f2c5621949b645da7d303c596589e84516a184/tokenizers-0.23.3.tar.gz", hash = "sha256:cded33237c77caeef62944d32aa9a7ef42bdce2b3497e18d137e072a8c4be438", size = 385286, upload-time = "2026-10-09T10:16:55.759Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/aa/2e/4ce5b9716f26e526eff6b0502ebed4ea8d7161f03b3c77617c9f25528e97/tokenizers-0.23.3-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:9d2b5c97daf61688c2ad1803ca851800feaba50fb68d5821779e9ea5880d968c", size = 3148800, upload-time = "2026-10-09T10:00:51.457Z" }, + { url = "https://files.pythonhosted.org/packages/b2/72/01e49f032bb346e5aaf06c10c74fe8aeec847173adbadd66eb7c53054bf2/tokenizers-0.23.3-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:68649e97d5b43c44c031d8d848874a6eecae8f8fe40ea989aa777a5a83aca716", size = 3101381, upload-time = "2026-10-09T10:00:54.063Z" }, + { url = "https://files.pythonhosted.org/packages/15/fc/ae987741829b1cd547668c4c94be732ae3eefd1d74344e64c3d2ca714acd/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ec82e80e65a862275b97c3d90b7a523df8d9519ee48aeb4e9625b2cc909274e0", size = 3519944, upload-time = "2026-10-09T10:00:55.885Z" }, + { url = "https://files.pythonhosted.org/packages/1c/da/cc8f6c030afaf05fbddc608158fbb761dca46913cbeba6b112e59fc82e2a/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c64a0713180ff16829d4e7f39a658b77ea11443af4e1aa46523692943c9b1414", size = 3397695, upload-time = "2026-10-09T10:00:57.444Z" }, + { url = "https://files.pythonhosted.org/packages/ec/f1/256f78d1365fa2cd3ea6db716883d74667c8cbb6a21f15fa5b89a773cdc2/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ddedfd4b3b4be6be24ff6ca645c4a37fddfd305f6f3e354c54cf10b715c48215", size = 3753125, upload-time = "2026-10-09T10:01:00.165Z" }, + { url = "https://files.pythonhosted.org/packages/60/93/eee007ac2fcbf4ecfce7fbc354826cf3611f56bdb886f3e91b1f7dd06b8f/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2a89614730d7b80940a5d2ed9320e1ec8add5a745c6151d8d05071b7215505b6", size = 4018598, upload-time = "2026-10-09T10:01:02.05Z" }, + { url = "https://files.pythonhosted.org/packages/bf/f9/0c96c4739461fce9d8d865b416728081bf6230022d7163bd6244f35f4b31/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e88646b8580c5ad7f4361477f1298e9cc01771a1ee9aecfe32c47b8ff614cc38", size = 3602442, upload-time = "2026-10-09T10:01:03.77Z" }, + { url = "https://files.pythonhosted.org/packages/3a/40/6706b82693715581457c6d5423eaa7faae576bb0526c5738a57085eb4449/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:376851d22bcf9d650a5c3090bb83e6cf9e895fbf0595369fa4cd43c1f69b5f87", size = 3396193, upload-time = "2026-10-09T10:01:05.48Z" }, + { url = "https://files.pythonhosted.org/packages/fe/0c/85946de40e25b7364b8f1bcf56def129069acd5bb364b7c86a32919e1a23/tokenizers-0.23.3-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:bf501c40b72d2d5c8623620210430e9cac1ce47a46e45b34107b70a1557d46b0", size = 3553483, upload-time = "2026-10-09T10:01:07.387Z" }, + { url = "https://files.pythonhosted.org/packages/f1/6b/8d615d92cad1d511ca5ab188d1c7c167f0b3d295cc0d96207f9f82d486d8/tokenizers-0.23.3-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:114e2b55ed177179d59f4ab98200a4471e11e78f9e4b5a922d146740f96fcf52", size = 9972248, upload-time = "2026-10-09T10:01:09.437Z" }, + { url = "https://files.pythonhosted.org/packages/c9/7d/a922e37ddd58d1b463bbc2ad08120c8f59c60b814cd353519a116b24f8ba/tokenizers-0.23.3-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:d3407fb7b9c4d75dd68850ffd7180bc0a5d2dbaf0762d888e612f31fec3f9c6b", size = 9802957, upload-time = "2026-10-09T10:01:11.869Z" }, + { url = "https://files.pythonhosted.org/packages/4b/06/5d3f506a86ae0699a0e4ea05c05978f9aee169ef2c1d844e68c971cf8194/tokenizers-0.23.3-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:84513ef0aeb8bf8f4ea11a2e8a7ac163ec5288aa115e649a59b470ac5c3107df", size = 10145487, upload-time = "2026-10-09T10:01:14.268Z" }, + { url = "https://files.pythonhosted.org/packages/26/e5/065625317690ea3548d834dad81f48ea1fd32e4964610e658e195d7fe28e/tokenizers-0.23.3-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:e05ab7baf7f47b406a95fea6f3b0a484b2ddcd9e1d14b68844c457eb755085a3", size = 10266026, upload-time = "2026-10-09T10:16:33.054Z" }, + { url = "https://files.pythonhosted.org/packages/77/4e/babede85d0d19f5e3deeef0063e01848141329934d3d77c31b5cab5ac2b4/tokenizers-0.23.3-cp310-abi3-win32.whl", hash = "sha256:1ebf28794e7e4954e20a7f70fbea410b2d1f0418f7dbbca97ca384fcfef38c25", size = 2588086, upload-time = "2026-10-09T10:16:35.686Z" }, + { url = "https://files.pythonhosted.org/packages/d1/6c/24f074c9a0efb98e61b20aafe6b2641922d5db24e447d5d6daffd9e17555/tokenizers-0.23.3-cp310-abi3-win_amd64.whl", hash = "sha256:1f0823bb00c5fdc98e487354d54dd55a03848d61a1a0bf29a68c77f24f3b26c3", size = 2872101, upload-time = "2026-10-09T10:16:37.533Z" }, + { url = "https://files.pythonhosted.org/packages/53/77/a476b6f73a661c11d113a342d2326b91506cf2285f0995d1212a6bb2022d/tokenizers-0.23.3-cp310-abi3-win_arm64.whl", hash = "sha256:7e48734d2de9260d86f03ab056d2cfeeff3869f61dbd49aaa15a2793b5f3458b", size = 2742580, upload-time = "2026-10-09T10:16:39.244Z" }, + { url = "https://files.pythonhosted.org/packages/65/46/f66baaedd42414a3f583c47379dc350e3e1f858a690d2574fd85ae70681b/tokenizers-0.23.3-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:efa3d7318406b4d115dce61ad5061953f1f44b128e79c020ce4615d763e23b6e", size = 3154274, upload-time = "2026-10-09T10:16:40.876Z" }, + { url = "https://files.pythonhosted.org/packages/c6/41/8de8c63b2d935eee5a0f42011fb7b786ffafeab0b8eb6d17acb8af2293b7/tokenizers-0.23.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:a4fbb3662f9f59d199d61338e54b4bcc11d07ebbb1aeb3540dacb2be9c521cb7", size = 3077805, upload-time = "2026-10-09T10:16:42.856Z" }, + { url = "https://files.pythonhosted.org/packages/e3/08/b1cbae8dc8fc7c91f992ac2d87a086e9b3f25a28814047ca16a82fe8c87b/tokenizers-0.23.3-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:de536665495cb4b409d25bade41963f801aff4225c19a6b804b048f7d14e34c7", size = 3491678, upload-time = "2026-10-09T10:16:45.093Z" }, + { url = "https://files.pythonhosted.org/packages/3e/0d/aac0cb2f3a1fdbef514145b4c5f2df4d05deeb1ee8f73ae641a1b4a62a85/tokenizers-0.23.3-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5cc24bb457dd4a8af89c8fcb40074d570129ec473df2a866c276ee55db4749d7", size = 3367420, upload-time = "2026-10-09T10:16:47.112Z" }, + { url = "https://files.pythonhosted.org/packages/1e/1d/41a697d0c193a320b243fbd68b2057b6eb2f01ecf80899e1a16e646ff699/tokenizers-0.23.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:acd5c57b4bd3e56e246e2731a3a3a6825a7a7d89b7e3b761ba80bc521710f04b", size = 9945973, upload-time = "2026-10-09T10:16:49.326Z" }, + { url = "https://files.pythonhosted.org/packages/37/e9/b56e619fcd583000a2b1254bb46af8dc6a174d3ba3329f454ad5a95a2be2/tokenizers-0.23.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:82eb480f6f1c21cea3349dec32cf1a6384c6c1e775f00f83b0d51197bc013687", size = 10237491, upload-time = "2026-10-09T10:16:51.943Z" }, + { url = "https://files.pythonhosted.org/packages/6f/68/f58b3beb95f3b62816e91e5e768e684cd63e58f9cbece22036dae3b1c971/tokenizers-0.23.3-cp314-cp314t-win_amd64.whl", hash = "sha256:1554a6eed34d9d6a78d23360f4e06df8dffab1ae08c7e8488e0b3e3b36cc266f", size = 2847654, upload-time = "2026-10-09T10:16:54.166Z" }, ] [[package]] @@ -4856,23 +4949,59 @@ wheels = [ [[package]] name = "transformers" -version = "5.1.0" +version = "5.20.2" source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] dependencies = [ - { name = "huggingface-hub" }, + { name = "huggingface-hub", marker = "python_full_version < '3.11'" }, { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "packaging", marker = "python_full_version < '3.11'" }, + { name = "pyyaml", marker = "python_full_version < '3.11'" }, + { name = "regex", marker = "python_full_version < '3.11'" }, + { name = "safetensors", marker = "python_full_version < '3.11'" }, + { name = "tokenizers", marker = "python_full_version < '3.11'" }, + { name = "tqdm", marker = "python_full_version < '3.11'" }, + { name = "typer", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8c/4e/3cd6f08cc84ee612d40f3cdb1649475e7c997f2d5cbd95ade8780708af62/transformers-5.20.2.tar.gz", hash = "sha256:080871e061546d720be57f5846fce426f46b44d61574907cc7404c2cba49d180", size = 10225379, upload-time = "2026-10-19T17:46:03.092Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/96/b6/724faefed06913dd3e42e0476fe2c42448675c42f687a12bf810aa098005/transformers-5.20.2-py3-none-any.whl", hash = "sha256:7ae75dbc1fb3922aff1b6c97b9e5479d6cf26fd86a8866bfb71324190479f807", size = 12844921, upload-time = "2026-10-19T17:45:59.293Z" }, +] + +[[package]] +name = "transformers" +version = "5.22.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'emscripten'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.11.*' and sys_platform == 'win32'", + "python_full_version == '3.11.*' and sys_platform == 'emscripten'", + "python_full_version == '3.11.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "huggingface-hub", marker = "python_full_version >= '3.11'" }, { name = "numpy", version = "2.4.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "packaging" }, - { name = "pyyaml" }, - { name = "regex" }, - { name = "safetensors" }, - { name = "tokenizers" }, - { name = "tqdm" }, - { name = "typer-slim" }, + { name = "packaging", marker = "python_full_version >= '3.11'" }, + { name = "pyyaml", marker = "python_full_version >= '3.11'" }, + { name = "regex", marker = "python_full_version >= '3.11'" }, + { name = "safetensors", marker = "python_full_version >= '3.11'" }, + { name = "tokenizers", marker = "python_full_version >= '3.11'" }, + { name = "tqdm", marker = "python_full_version >= '3.11'" }, + { name = "typer", marker = "python_full_version >= '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/c9/1d/a7d91500a6c02ec76058bc9e65fcdec1bdb8882854dec8e4adf12d0aa8b0/transformers-5.1.0.tar.gz", hash = "sha256:c60d6180e5845ea1b4eed38d7d1b06fcc4cc341c6b7fa5c1dc767d7e25fe0139", size = 8531810, upload-time = "2026-02-05T15:41:42.932Z" } +sdist = { url = "https://files.pythonhosted.org/packages/17/d6/a610b37bbc3450c056ea68c7f5016d06da8e787c1ac32b20ce58d18a1eb0/transformers-5.22.1.tar.gz", hash = "sha256:bed9fd76d6f43b4a1a9fc5d0c565ace7c77edbd029784f8cbcdf772cb5e924d8", size = 10381794, upload-time = "2026-10-30T07:48:03.721Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b7/66/57042d4b0f1ede8046d7ae6409bf3640df996e9cbc3fe20467aa29badc54/transformers-5.1.0-py3-none-any.whl", hash = "sha256:de534b50c9b2ce6217fc56421075a1734241fb40704fdc90f50f6a08fc533d59", size = 10276537, upload-time = "2026-02-05T15:41:40.358Z" }, + { url = "https://files.pythonhosted.org/packages/75/75/47ebe0e2f1b04a180000e3a49ebdf4669dbab0c63489bcecf7855c26e4f4/transformers-5.22.1-py3-none-any.whl", hash = "sha256:c940b4bf98de4f568723895f330ba1460a398bd83061b93b70238c3fe32e4389", size = 13051755, upload-time = "2026-10-30T07:47:59.888Z" }, ] [[package]] @@ -4896,6 +5025,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f6/56/6113c23ff46c00aae423333eb58b3e60bdfe9179d542781955a5e1514cb3/triton-3.6.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:46bd1c1af4b6704e554cad2eeb3b0a6513a980d470ccfa63189737340c7746a7", size = 188397994, upload-time = "2026-01-20T16:01:14.236Z" }, ] +[[package]] +name = "truststore" +version = "0.10.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ee/9f/c5201d42a484c061e528825fc8e2d565f5abd50a4ced6fb7d29c4ec99b2b/truststore-0.10.5.tar.gz", hash = "sha256:30d36967ccaded5cbb38d602c433f53600036c79d502f4533a49b60a03bbefcd", size = 28091, upload-time = "2026-10-12T22:27:31.808Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/e9/3a7820be2bb0fe53b6bc9c3be26d3d1158004e4c3ab953aa6840b955b1e9/truststore-0.10.5-py3-none-any.whl", hash = "sha256:9aaaedaefaf06d8b206278cf8b5012bc897f485a874503501e12d776df78951c", size = 19017, upload-time = "2026-10-12T22:27:30.377Z" }, +] + [[package]] name = "typer" version = "0.24.1" @@ -4911,18 +5049,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/4a/91/48db081e7a63bb37284f9fbcefda7c44c277b18b0e13fbc36ea2335b71e6/typer-0.24.1-py3-none-any.whl", hash = "sha256:112c1f0ce578bfb4cab9ffdabc68f031416ebcc216536611ba21f04e9aa84c9e", size = 56085, upload-time = "2026-02-21T16:54:41.616Z" }, ] -[[package]] -name = "typer-slim" -version = "0.24.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "typer" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a7/a7/e6aecc4b4eb59598829a3b5076a93aff291b4fdaa2ded25efc4e1f4d219c/typer_slim-0.24.0.tar.gz", hash = "sha256:f0ed36127183f52ae6ced2ecb2521789995992c521a46083bfcdbb652d22ad34", size = 4776, upload-time = "2026-02-16T22:08:51.2Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a7/24/5480c20380dfd18cf33d14784096dca45a24eae6102e91d49a718d3b6855/typer_slim-0.24.0-py3-none-any.whl", hash = "sha256:d5d7ee1ee2834d5020c7c616ed5e0d0f29b9a4b1dd283bdebae198ec09778d0e", size = 3394, upload-time = "2026-02-16T22:08:49.92Z" }, -] - [[package]] name = "typing-extensions" version = "4.15.0"