File size: 3,610 Bytes
838f544
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""InDIM models (Cobuild Tech): ModernBERT encoder + factorized word embedding.

    from transformers import AutoTokenizer, AutoModel, AutoModelForMaskedLM
    tok = AutoTokenizer.from_pretrained("CobuildX-AI/InDIM-small")
    model = AutoModel.from_pretrained("CobuildX-AI/InDIM-small", trust_remote_code=True)

Classes: InDIMModel (encoder), InDIMForMaskedLM, InDIMForSequenceClassification, InDIMForTokenClassification.
The task heads are the stock ModernBERT heads (`classifier_pooling` "cls" or "mean"); only the word embedding differs.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers.modeling_outputs import MaskedLMOutput
from transformers.models.modernbert.modeling_modernbert import (
    ModernBertForSequenceClassification,
    ModernBertForTokenClassification,
    ModernBertModel,
    ModernBertPredictionHead,
    ModernBertPreTrainedModel,
)

try:
    from .configuration_indim import InDIMConfig
except ImportError:                                    # loaded as a plain module (local checks)
    from configuration_indim import InDIMConfig


class FactorizedEmbedding(nn.Module):
    """ids -> table[V x r] -> up[r -> hidden]. `weight` is the table (also the masked-LM output layer)."""

    def __init__(self, vocab_size, rank, hidden_size):
        super().__init__()
        self.weight = nn.Parameter(torch.empty(vocab_size, rank))
        self.up = nn.Linear(rank, hidden_size, bias=False)

    def forward(self, input_ids):
        return self.up(F.embedding(input_ids, self.weight))


def _factorize(model, config):
    model.embeddings.tok_embeddings = FactorizedEmbedding(config.vocab_size, config.embedding_rank, config.hidden_size)
    std = config.initializer_range
    nn.init.trunc_normal_(model.embeddings.tok_embeddings.weight, std=std, a=-3 * std, b=3 * std)
    nn.init.trunc_normal_(model.embeddings.tok_embeddings.up.weight, std=std, a=-3 * std, b=3 * std)


class InDIMModel(ModernBertModel):
    config_class = InDIMConfig

    def __init__(self, config):
        super().__init__(config)
        _factorize(self, config)


class InDIMForMaskedLM(ModernBertPreTrainedModel):
    config_class = InDIMConfig

    def __init__(self, config):
        super().__init__(config)
        self.model = InDIMModel(config)
        self.head = ModernBertPredictionHead(config)
        self.down = nn.Linear(config.hidden_size, config.embedding_rank, bias=False)
        self.decoder_bias = nn.Parameter(torch.zeros(config.vocab_size))
        self.post_init()

    def get_output_embeddings(self):
        return None                                    # tied to the factorized table inside forward

    def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs):
        h = self.model(input_ids=input_ids, attention_mask=attention_mask, **kwargs).last_hidden_state
        logits = F.linear(self.down(self.head(h)), self.model.embeddings.tok_embeddings.weight, self.decoder_bias)
        loss = None
        if labels is not None:
            loss = F.cross_entropy(logits.view(-1, logits.size(-1)).float(), labels.view(-1), ignore_index=-100)
        return MaskedLMOutput(loss=loss, logits=logits)


class InDIMForSequenceClassification(ModernBertForSequenceClassification):
    config_class = InDIMConfig

    def __init__(self, config):
        super().__init__(config)
        _factorize(self.model, config)


class InDIMForTokenClassification(ModernBertForTokenClassification):
    config_class = InDIMConfig

    def __init__(self, config):
        super().__init__(config)
        _factorize(self.model, config)