stackifiers-repo / modeling_stackifiers.py
Machacini's picture
Publish verified mmbert-small full-finetune checkpoint, loader and evaluation card
aa142c2 verified
Raw History Blame Contribute Delete
8.8 kB
"""Hugging Face inference for full-context, five-score Stackifiers models."""
import torch
from torch import nn
from torch.nn import functional as F
from transformers import AutoConfig, AutoModel, PreTrainedModel
from transformers.modeling_outputs import SequenceClassifierOutput
from .configuration_stackifiers import StackifiersConfig
def chunk_ids(ids, tokenizer, max_length):
"""Retain all tokens, matching the special-token layout used in training."""
capacity = max_length - tokenizer.num_special_tokens_to_add(pair=False)
if capacity < 1:
raise ValueError('max_length leaves no room for content tokens')
chunks, weights = [], []
for start in range(0, max(1, len(ids)), capacity):
content = ids[start:start + capacity]
builder = getattr(tokenizer, 'build_inputs_with_special_tokens', None)
if builder is not None:
sequence = builder(content)
else:
# Transformers 5 tokenizer backends expose the layout through a mask.
layout = getattr(tokenizer, '_stackifiers_special_layout', None)
if layout is None:
probe = tokenizer('a', add_special_tokens=True, return_special_tokens_mask=True)
mask = probe['special_tokens_mask']
ordinary = [i for i, value in enumerate(mask) if not value]
if not ordinary or any(mask[ordinary[0]:ordinary[-1] + 1]):
raise ValueError('Unsupported interleaved special-token layout')
layout = (probe['input_ids'][:ordinary[0]], probe['input_ids'][ordinary[-1] + 1:])
if sum(map(len, layout)) != tokenizer.num_special_tokens_to_add(pair=False):
raise ValueError('Special-token layout disagrees with the token budget')
tokenizer._stackifiers_special_layout = layout
sequence = layout[0] + list(content) + layout[1]
if len(sequence) > max_length:
raise ValueError('Special-token budget changed')
chunks.append(sequence)
weights.append(max(1, len(content)))
return chunks, weights
class StackifiersHead(nn.Module):
def __init__(self, hidden_size, dropout):
super().__init__()
self.norm = nn.LayerNorm(hidden_size)
self.dropout = nn.Dropout(dropout)
self.output = nn.Linear(hidden_size, 5)
def forward(self, features):
# Keep the small head arithmetic in FP32 even with a lower-precision encoder.
with torch.autocast(device_type=features.device.type, enabled=False):
normalized = F.layer_norm(features.float(), self.norm.normalized_shape,
self.norm.weight.float(), self.norm.bias.float(), self.norm.eps)
return 5 * torch.sigmoid(F.linear(self.dropout(normalized),
self.output.weight.float(), self.output.bias.float()))
class StackifiersModel(PreTrainedModel):
config_class = StackifiersConfig
base_model_prefix = 'backbone'
_supports_sdpa = True
_no_split_modules = ['ModernBertEncoderLayer']
def __init__(self, config):
super().__init__(config)
parameters = dict(config.backbone_config)
model_type = parameters.pop('model_type', 'modernbert')
backbone_config = AutoConfig.for_model(model_type, **parameters)
backbone_config.use_cache = False
backbone_config.reference_compile = False
attention = getattr(config, '_attn_implementation', None) or 'sdpa'
self.backbone = AutoModel.from_config(backbone_config, attn_implementation=attention)
self.head = StackifiersHead(backbone_config.hidden_size, config.head_dropout)
self.post_init()
def _encode(self, input_ids, attention_mask):
hidden = self.backbone(input_ids=input_ids, attention_mask=attention_mask,
return_dict=True).last_hidden_state
return ((hidden * attention_mask.unsqueeze(-1)).sum(dim=1, dtype=torch.float32)
/ attention_mask.sum(dim=1, keepdim=True).clamp_min(1))
def forward(self, input_ids, attention_mask=None, owners=None, chunk_weights=None,
num_contexts=None, labels=None, **kwargs):
"""Score tokenized contexts or pre-chunked contexts with owner/weight tensors.
``logits`` are the final bounded 0–5 scores; do not apply softmax/sigmoid.
Use ``predict`` to tokenize and chunk arbitrary-length source automatically.
"""
if attention_mask is None:
attention_mask = torch.ones_like(input_ids)
pooled = self._encode(input_ids, attention_mask)
if owners is not None:
if chunk_weights is None or num_contexts is None:
raise ValueError('owners requires chunk_weights and num_contexts')
owners = owners.to(device=pooled.device, dtype=torch.long)
weights = chunk_weights.to(device=pooled.device, dtype=torch.float32)
features = torch.zeros((num_contexts, pooled.shape[-1]), device=pooled.device, dtype=torch.float32)
totals = torch.zeros((num_contexts, 1), device=pooled.device, dtype=torch.float32)
features.index_add_(0, owners, pooled * weights[:, None])
totals.index_add_(0, owners, weights[:, None])
pooled = features / totals.clamp_min(1)
scores = self.head(pooled)
loss = None
if labels is not None:
mask = torch.isfinite(labels) & (labels >= 0) & (labels <= 5)
targets = torch.where(mask, labels.float(), torch.zeros_like(labels, dtype=torch.float32))
sums = ((scores.float() - targets).square() * mask).sum(dim=0)
counts = mask.sum(dim=0).float()
loss = (sums / counts.clamp_min(1)).sum() / (counts > 0).sum().clamp_min(1)
return SequenceClassifierOutput(loss=loss, logits=scores)
@torch.inference_mode()
def predict(self, texts, tokenizer, chunk_batch_size=8):
"""Return named scores for a string or list of strings, without truncation.
``chunk_batch_size`` bounds encoder memory, independently of text length.
Content-token weights exclude special tokens, matching the trained model.
"""
single = isinstance(texts, str)
texts = [texts] if single else list(texts)
if not texts or any(not isinstance(text, str) or not text.strip() for text in texts):
raise ValueError('Supply nonempty source text strings')
if type(chunk_batch_size) is not int or chunk_batch_size < 1:
raise ValueError('chunk_batch_size must be a positive integer')
if tokenizer.pad_token_id is None:
raise ValueError('Use the tokenizer shipped with this checkpoint (pad_token_id is required)')
device = next(self.parameters()).device
features = torch.zeros((len(texts), self.head.output.in_features), device=device, dtype=torch.float32)
totals = torch.zeros((len(texts), 1), device=device, dtype=torch.float32)
pending = []
def flush():
width = max(len(ids) for _, ids, _ in pending)
ids = torch.full((len(pending), width), tokenizer.pad_token_id, dtype=torch.long, device=device)
mask = torch.zeros_like(ids)
for i, (_, sequence, _) in enumerate(pending):
ids[i, :len(sequence)] = torch.as_tensor(sequence, dtype=torch.long, device=device)
mask[i, :len(sequence)] = 1
owners = torch.tensor([owner for owner, _, _ in pending], device=device, dtype=torch.long)
weights = torch.tensor([weight for _, _, weight in pending], device=device, dtype=torch.float32)
pooled = self._encode(ids, mask)
features.index_add_(0, owners, pooled * weights[:, None])
totals.index_add_(0, owners, weights[:, None])
pending.clear()
training = self.training
self.eval()
try:
for owner, text in enumerate(texts):
tokens = tokenizer.encode(text, add_special_tokens=False, truncation=False)
sequences, weights = chunk_ids(tokens, tokenizer, self.config.max_length)
for sequence, weight in zip(sequences, weights):
pending.append((owner, sequence, weight))
if len(pending) == chunk_batch_size:
flush()
if pending:
flush()
scores = self.head(features / totals.clamp_min(1)).cpu().tolist()
finally:
self.train(training)
result = [dict(zip(self.config.metrics, values)) for values in scores]
return result[0] if single else result
StackifiersModel.register_for_auto_class('AutoModel')