yezdata commited on
Commit
3d69832
·
verified ·
1 Parent(s): ee1a5ca

Delete modeling_emcoder.py

Browse files
Files changed (1) hide show
  1. modeling_emcoder.py +0 -186
modeling_emcoder.py DELETED
@@ -1,186 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
- from transformers import PreTrainedModel, AutoConfig, AutoModel
4
-
5
- from .configuration_emcoder import EmCoderConfig
6
-
7
-
8
- class EmCoderEncoder(nn.Module):
9
- """The core encoder architecture of EmCoder Transformer."""
10
-
11
- def __init__(self, config: EmCoderConfig):
12
- super().__init__()
13
-
14
- self.token_embedding = nn.Embedding(config.vocab_size, config.d_model)
15
- self.pos_embedding = nn.Embedding(config.max_seq_len, config.d_model)
16
- self.embed_norm = nn.LayerNorm(config.d_model)
17
-
18
- encoder_layer = nn.TransformerEncoderLayer(
19
- d_model=config.d_model,
20
- nhead=config.n_head,
21
- dim_feedforward=config.d_ffn,
22
- dropout=config.dropout,
23
- activation="gelu",
24
- norm_first=True,
25
- batch_first=True,
26
- )
27
- self.encoder = nn.TransformerEncoder(
28
- encoder_layer=encoder_layer, num_layers=config.n_layers, enable_nested_tensor=False
29
- )
30
-
31
- self.final_norm = nn.LayerNorm(config.d_model)
32
- self.dropout = nn.Dropout(config.dropout)
33
-
34
- def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
35
- """Standard forward pass through the encoder."""
36
- seq_len = x.size(1)
37
- pos_ids = torch.arange(seq_len, device=x.device).unsqueeze(0)
38
-
39
- x = self.token_embedding(x) + self.pos_embedding(pos_ids)
40
-
41
- x = self.embed_norm(x)
42
- x = self.dropout(x)
43
-
44
- padding_mask = mask == 0
45
-
46
- encoded = self.encoder(x, src_key_padding_mask=padding_mask)
47
- return self.final_norm(encoded)
48
-
49
-
50
- class EmCoder(PreTrainedModel):
51
- """The full EmCoder model, including the classification head."""
52
-
53
- config_class = EmCoderConfig
54
-
55
- def __init__(self, config: EmCoderConfig):
56
- super().__init__(config)
57
-
58
- self.encoder = EmCoderEncoder(config)
59
- self.classifier = nn.Sequential(
60
- nn.Linear(config.d_model, config.d_model),
61
- nn.GELU(),
62
- nn.Dropout(config.dropout),
63
- nn.Linear(config.d_model, config.num_labels),
64
- )
65
-
66
- self.post_init()
67
-
68
-
69
- def _init_weights(self, module: nn.Module) -> None:
70
- if isinstance(module, nn.Linear):
71
- nn.init.trunc_normal_(module.weight, std=0.02)
72
- if module.bias is not None:
73
- nn.init.zeros_(module.bias)
74
- elif isinstance(module, nn.Embedding):
75
- nn.init.trunc_normal_(module.weight, std=0.02)
76
- if hasattr(module, "padding_idx") and module.padding_idx is not None:
77
- module.weight.data[module.padding_idx].zero_()
78
- elif isinstance(module, nn.LayerNorm):
79
- nn.init.ones_(module.weight)
80
- nn.init.zeros_(module.bias)
81
-
82
-
83
-
84
- def _set_mc_dropout(self, active: bool = True):
85
- for m in self.modules():
86
- if isinstance(m, nn.Dropout) or isinstance(m, nn.MultiheadAttention):
87
- m.train(active)
88
-
89
- @staticmethod
90
- def _masked_mean_pooling(
91
- features: torch.Tensor, mask: torch.Tensor
92
- ) -> torch.Tensor:
93
- mask = mask.unsqueeze(-1) # (B, S, 1)
94
- masked_features = features * mask # (B, S, D)
95
- sum_masked_features = masked_features.sum(dim=1) # (B, D)
96
- count_tokens = torch.clamp(mask.sum(dim=1), min=1e-9) # (B, 1)
97
- return sum_masked_features / count_tokens # (B, D)
98
-
99
-
100
- def mc_forward(
101
- self,
102
- input_ids: torch.Tensor | None = None,
103
- attention_mask: torch.Tensor | None = None,
104
- n_samples: int = 10,
105
- max_batch_size: int | None = None,
106
- return_dict: bool | None = None,
107
- **kwargs,
108
- ) -> torch.Tensor:
109
- """
110
- Performs Monte Carlo Dropout inference to quantify epistemic uncertainty.
111
-
112
- Args:
113
- x: Input token IDs of shape (B, S).
114
- mask: Attention mask of shape (B, S).
115
- n_samples: Total number of Monte Carlo samples.
116
- max_batch_size: Maximum number of samples in one forward pass.
117
-
118
- Returns:
119
- Logits of shape (n_samples, B, num_labels).
120
- """
121
- x = input_ids if input_ids is not None else kwargs.get("x")
122
- mask = attention_mask if attention_mask is not None else kwargs.get("mask")
123
-
124
- if x is None or mask is None:
125
- raise ValueError("input_ids (x) and attention_mask (mask) must be provided")
126
-
127
- if max_batch_size is None:
128
- max_batch_size = n_samples
129
-
130
-
131
- B, S = x.shape
132
- num_labels = self.classifier[-1].out_features
133
-
134
- all_logits = torch.empty((n_samples, B, num_labels), device=x.device)
135
-
136
- is_training = self.training
137
- self._set_mc_dropout(active=True)
138
- try:
139
- for i in range(0, n_samples, max_batch_size):
140
- batch_samples = min(max_batch_size, n_samples - i)
141
-
142
- x_stacked = x.repeat(batch_samples, 1) # (batch_samples * B, S)
143
- mask_stacked = mask.repeat(batch_samples, 1) # (batch_samples * B, S)
144
-
145
- features = self.encoder(
146
- x_stacked, mask_stacked
147
- ) # (batch_samples * B, S, D)
148
-
149
- pooled = self._masked_mean_pooling(features, mask_stacked)
150
- logits = self.classifier(pooled) # (n_samples * B, num_labels)
151
-
152
- all_logits[i : i + batch_samples] = logits.view(batch_samples, B, -1)
153
- finally:
154
- self._set_mc_dropout(active=is_training)
155
-
156
- return all_logits
157
-
158
-
159
-
160
-
161
- def forward(
162
- self,
163
- input_ids: torch.Tensor | None = None,
164
- attention_mask: torch.Tensor | None = None,
165
- return_dict: bool | None = None,
166
- **kwargs,
167
- ) -> torch.Tensor:
168
- """Standard forward pass without MC Dropout."""
169
-
170
- x = input_ids if input_ids is not None else kwargs.get("x")
171
- mask = attention_mask if attention_mask is not None else kwargs.get("mask")
172
-
173
- if x is None or mask is None:
174
- raise ValueError("input_ids (x) and attention_mask (mask) must be provided")
175
-
176
- features = self.encoder(x, mask)
177
-
178
- pooled = self._masked_mean_pooling(features, mask)
179
- return self.classifier(pooled)
180
-
181
-
182
- try:
183
- AutoConfig.register("emcoder", EmCoderConfig)
184
- AutoModel.register(EmCoderConfig, EmCoder)
185
- except ValueError:
186
- pass