Download modeling_sb.py from sarathi-balakrishnan/browser-decision-model-base: direct link, hf CLI and curl.
- Browser
- Download file 6.69 kB
-
https://huggingface.co/sarathi-balakrishnan/browser-decision-model-base/resolve/main/modeling_sb.py
- Command line
-
hf download hf://sarathi-balakrishnan/browser-decision-model-base/modeling_sb.py
-
curl -L -o modeling_sb.py https://huggingface.co/sarathi-balakrishnan/browser-decision-model-base/resolve/main/modeling_sb.py
6.69 kB
| """SB Decision Model: the inference architecture, self-contained (torch + transformers only). | |
| This file ships inside the Hugging Face repo, so the model loads with | |
| ``AutoModel.from_pretrained(repo, trust_remote_code=True)`` and no other package. | |
| Architecture: a ModernBERT encoder reads ``<<LABEL>>name: definition … <<SEP>>text`` in one pass; the hidden | |
| state at each ``<<LABEL>>`` token (projected) is dotted with the projected [CLS] state to give one logit per option. | |
| The state-dict layout matches the training checkpoint (``model.encoder_model.*``, ``model.text_projector.*``, | |
| ``model.classes_projector.*``), so fine-tuned weights load unchanged. | |
| Copyright 2026 Sarathi Balakrishnan. Apache-2.0. See NOTICE for the encoder and recipe this builds on. | |
| """ | |
| from __future__ import annotations | |
| import torch | |
| from torch import nn | |
| from transformers import AutoConfig, AutoModel, PretrainedConfig, PreTrainedModel | |
| from transformers.activations import ACT2FN | |
| from transformers.modeling_outputs import SequenceClassifierOutput | |
| LABEL_TOKEN = "<<LABEL>>" | |
| SEP_TOKEN = "<<SEP>>" | |
| class SBDecisionConfig(PretrainedConfig): | |
| model_type = "sb_decision" | |
| def __init__( | |
| self, | |
| encoder_config: dict | PretrainedConfig | None = None, | |
| hidden_size: int = 768, | |
| class_token_index: int = 50368, | |
| text_token_index: int = 50369, | |
| calibration_temperature: float = 1.0, | |
| projector_hidden_act: str = "gelu", | |
| dropout: float = 0.1, | |
| max_options: int = 12, | |
| **kwargs, | |
| ) -> None: | |
| super().__init__(**kwargs) | |
| if isinstance(encoder_config, dict): | |
| encoder_config = AutoConfig.for_model(**encoder_config) | |
| self.encoder_config = encoder_config | |
| self.hidden_size = hidden_size | |
| self.class_token_index = class_token_index | |
| self.text_token_index = text_token_index | |
| self.calibration_temperature = calibration_temperature # "temperature" alone is reserved for generation | |
| self.projector_hidden_act = projector_hidden_act | |
| self.dropout = dropout | |
| self.max_options = max_options | |
| def to_dict(self) -> dict: | |
| d = super().to_dict() | |
| if self.encoder_config is not None: | |
| d["encoder_config"] = self.encoder_config.to_dict() | |
| return d | |
| class Projector(nn.Module): | |
| def __init__(self, enc_dim: int, hidden: int, act: str, dropout: float) -> None: | |
| super().__init__() | |
| self.linear_1 = nn.Linear(enc_dim, hidden) | |
| self.act = ACT2FN[act] | |
| self.dropout = nn.Dropout(dropout) | |
| self.linear_2 = nn.Linear(hidden, enc_dim) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| return self.linear_2(self.dropout(self.act(self.linear_1(x)))) | |
| class DotScorer(nn.Module): | |
| def forward(self, text: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: | |
| return torch.einsum("bd,bkd->bk", text, labels) | |
| class SBDecisionCore(nn.Module): | |
| def __init__(self, cfg: SBDecisionConfig) -> None: | |
| super().__init__() | |
| enc_dim = cfg.encoder_config.hidden_size | |
| self.encoder_model = AutoModel.from_config(cfg.encoder_config) | |
| self.text_projector = Projector(enc_dim, cfg.hidden_size, cfg.projector_hidden_act, cfg.dropout) | |
| self.classes_projector = Projector(enc_dim, cfg.hidden_size, cfg.projector_hidden_act, cfg.dropout) | |
| self.logit_scale = nn.Parameter(torch.tensor(1.0)) # present in the checkpoint, unused at inference | |
| self.scorer = DotScorer() | |
| def label_positions_from_ids(input_ids: torch.Tensor, label_token_id: int, k: int | None = None) -> torch.Tensor: | |
| """[B, K] index of each <<LABEL>> token, -1 padded.""" | |
| mask = input_ids == label_token_id | |
| k = k or int(mask.sum(-1).max().item()) | |
| pos = torch.full((input_ids.shape[0], k), -1, dtype=torch.long, device=input_ids.device) | |
| for b in range(input_ids.shape[0]): | |
| idx = mask[b].nonzero().flatten()[:k] | |
| pos[b, : idx.numel()] = idx | |
| return pos | |
| class SBDecisionModel(PreTrainedModel): | |
| config_class = SBDecisionConfig | |
| base_model_prefix = "model" | |
| def __init__(self, config: SBDecisionConfig) -> None: | |
| super().__init__(config) | |
| self.model = SBDecisionCore(config) | |
| self.post_init() | |
| def forward( | |
| self, | |
| input_ids: torch.Tensor, | |
| attention_mask: torch.Tensor | None = None, | |
| label_positions: torch.Tensor | None = None, | |
| max_num_classes: int | None = None, | |
| calibrated: bool = False, | |
| **kwargs, | |
| ) -> SequenceClassifierOutput: | |
| """logits[b, k] for option k of row b; padded slots are -1e4. ``calibrated`` divides by the temperature.""" | |
| m = self.model | |
| hidden = m.encoder_model(input_ids=input_ids, attention_mask=attention_mask)[0] # [B, S, D] | |
| if label_positions is None: | |
| label_positions = label_positions_from_ids(input_ids, self.config.class_token_index, max_num_classes) | |
| valid = (label_positions >= 0).to(hidden.dtype) | |
| idx = label_positions.clamp(min=0).unsqueeze(-1).expand(-1, -1, hidden.shape[-1]) | |
| labels = m.classes_projector(torch.gather(hidden, 1, idx)) # [B, K, D] | |
| text = m.text_projector(hidden[:, 0, :]) # [B, D] | |
| logits = m.scorer(text, labels) * valid + (valid - 1.0) * 1e4 | |
| if calibrated: | |
| logits = logits / self.config.calibration_temperature | |
| return SequenceClassifierOutput(logits=logits) | |
| def build_input(text: str, options: list[dict]) -> str: | |
| labels = [f"{o['name']}: {o['definition']}" if o.get("definition") else o["name"] for o in options] | |
| return "".join(LABEL_TOKEN + label for label in labels) + SEP_TOKEN + text | |
| def score(self, tokenizer, text: str, options: list[dict], mode: str = "single", max_len: int = 1024) -> dict: | |
| """Calibrated probability per option. mode "single" = softmax (pick one), "multi" = sigmoid (independent).""" | |
| if not 2 <= len(options) <= self.config.max_options: | |
| raise ValueError(f"2..{self.config.max_options} options, got {len(options)}") | |
| enc = tokenizer(self.build_input(text, options), truncation=True, max_length=max_len, return_tensors="pt") | |
| enc = {k: v.to(self.device) for k, v in enc.items()} | |
| z = self(**enc, max_num_classes=len(options), calibrated=True).logits[0].float() | |
| p = torch.softmax(z, -1) if mode == "single" else torch.sigmoid(z) | |
| return {o["name"]: round(float(p[i]), 4) for i, o in enumerate(options)} | |
| AutoConfig.register("sb_decision", SBDecisionConfig, exist_ok=True) | |
| AutoModel.register(SBDecisionConfig, SBDecisionModel, exist_ok=True) | |