File size: 8,800 Bytes
aa142c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
"""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')