Instructions to use TCMVince/HOP4NLP2 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use TCMVince/HOP4NLP2 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("fill-mask", model="TCMVince/HOP4NLP2", trust_remote_code=True)# Load model directly from transformers import AutoModelForMaskedLM model = AutoModelForMaskedLM.from_pretrained("TCMVince/HOP4NLP2", trust_remote_code=True, dtype="auto") - Notebooks
- Google Colab
- Kaggle
File size: 15,005 Bytes
587e3b7 | 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 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 | import torch
import torch.nn as nn
from torch.nn.functional import gelu
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from transformers import PreTrainedModel
from transformers.modeling_outputs import (
BaseModelOutput,
MaskedLMOutput,
SequenceClassifierOutput,
)
from hopfield import HopfieldLayer
from hf_configuration import BertEnergyConfig
from positional import PositionalEncoding
class EnergyLMHead(nn.Module):
"""
MLM head for the energy backbone.
Architecture:
hidden -> dense -> gelu -> layer_norm -> decoder(vocab)
"""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.embedding_dim, config.embedding_dim)
self.layer_norm = nn.LayerNorm(
config.embedding_dim,
eps=config.layer_norm_eps,
)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.decoder = nn.Linear(config.embedding_dim, config.vocab_size, bias=True)
@property
def bias(self):
return self.decoder.bias
def forward(self, hidden_states):
x = self.dense(hidden_states)
x = gelu(x)
x = self.layer_norm(x)
x = self.dropout(x)
x = self.decoder(x)
return x
def _tie_weights(self):
pass
class AlbertMLMHead(nn.Module):
"""
ALBERT-style MLM head:
hidden (H) -> embedding (E) -> LN -> vocab (V)
"""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.embedding_dim)
self.layer_norm = nn.LayerNorm(config.embedding_dim, eps=config.layer_norm_eps)
self.decoder = nn.Linear(config.embedding_dim, config.vocab_size, bias=True)
def forward(self, hidden_states):
x = self.dense(hidden_states)
x = gelu(x)
x = self.layer_norm(x)
return self.decoder(x)
class MLMHead(nn.Module):
"""
Standard BERT/RoBERTa-style MLM head.
"""
def __init__(self, input_dim, hidden_dim, config):
super().__init__()
self.dense = nn.Linear(input_dim, hidden_dim)
self.layer_norm = nn.LayerNorm(hidden_dim, eps=config.layer_norm_eps)
self.decoder = nn.Linear(hidden_dim, config.vocab_size, bias=True)
@property
def bias(self):
return self.decoder.bias
def forward(self, features, **kwargs):
x = self.dense(features)
x = gelu(x)
x = self.layer_norm(x)
x = self.decoder(x)
return x
def _tie_weights(self):
pass
class BertPreTrainedModel(PreTrainedModel):
"""
Common pretrained model base.
"""
config_class = BertEnergyConfig
def _init_weights(self, module):
if isinstance(module, nn.Linear):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
class BertModel(BertPreTrainedModel):
"""
Standard transformer backbone.
Outputs: last hidden state, optional hidden state history.
"""
config_class = BertEnergyConfig
def __init__(self, config, add_pooling_layer=True, pad_idx=None, **kwargs):
super().__init__(config)
self.Emb_in = nn.Embedding(config.vocab_size, config.embedding_dim, padding_idx=pad_idx)
self.posn = (
PositionalEncoding(
config.embedding_dim,
max_len=config.max_position_embeddings,
)
if config.positional
else None
)
self.embed_norm = nn.LayerNorm(config.embedding_dim, eps=config.layer_norm_eps)
self.embed_dropout = nn.Dropout(config.hidden_dropout_prob)
self.num_layers = config.num_hidden_layers
self.share_layers = config.share_layers
if self.share_layers:
self.embedding_hidden_in = nn.Linear(config.embedding_dim, config.hidden_size)
layer = nn.TransformerEncoderLayer(
d_model=config.hidden_size,
nhead=config.num_attention_heads,
activation=config.activation,
dim_feedforward=config.hidden_size,
dropout=config.hidden_dropout_prob,
layer_norm_eps=config.layer_norm_eps,
batch_first=True,
norm_first=True,
)
self.layers = nn.ModuleList([layer])
self.output_dim = config.hidden_size
else:
self.embedding_hidden_in = None
self.layers = nn.ModuleList(
[
nn.TransformerEncoderLayer(
d_model=config.embedding_dim,
nhead=config.num_attention_heads,
dim_feedforward=config.intermediate_size,
dropout=config.hidden_dropout_prob,
layer_norm_eps=config.layer_norm_eps,
batch_first=True,
norm_first=True,
)
for _ in range(config.num_hidden_layers)
]
)
self.output_dim = config.embedding_dim
self.post_init()
def get_input_embeddings(self):
return self.Emb_in
def set_input_embeddings(self, new_embeddings):
self.Emb_in = new_embeddings
def forward(self, input_ids, attention_mask=None, **kwargs):
x = self.Emb_in(input_ids)
if self.posn is not None:
x = x + self.posn(x)
x = self.embed_norm(x)
x = self.embed_dropout(x)
if self.share_layers:
x = self.embedding_hidden_in(x)
history = None if self.training else [x]
pad_mask = None
if attention_mask is not None:
pad_mask = ~attention_mask.to(torch.bool)
for i in range(self.num_layers):
layer = self.layers[0] if self.share_layers else self.layers[i]
x = layer(x, src_key_padding_mask=pad_mask)
if not self.training:
history.append(x)
return BaseModelOutput(
last_hidden_state=x,
hidden_states=history,
attentions=None,
)
class BertModelForMaskedLM(BertPreTrainedModel):
"""
Standard transformer model for MLM.
"""
config_class = BertEnergyConfig
ignore_index = -100
_tied_weights_keys = ["lm_head.decoder.weight"]
def __init__(self, config, add_pooling_layer=True, pad_idx=None):
super().__init__(config)
self.config = config
self.model = BertModel(config, pad_idx=pad_idx)
if config.share_layers:
self.lm_head = AlbertMLMHead(config)
else:
self.lm_head = MLMHead(config.embedding_dim, config.embedding_dim, config)
self.post_init()
if self.config.tie_word_embeddings:
self.tie_weights()
def get_input_embeddings(self):
return self.model.Emb_in
def set_input_embeddings(self, new_embeddings):
self.model.set_input_embeddings(new_embeddings)
def get_output_embeddings(self):
return self.lm_head.decoder
def set_output_embeddings(self, new_embeddings):
self.lm_head.decoder = new_embeddings
def forward(self, input_ids, attention_mask=None, labels=None, **kwargs):
outputs = self.model(input_ids, attention_mask=attention_mask, **kwargs)
logits = self.lm_head(outputs.last_hidden_state)
loss = None
if labels is not None:
if attention_mask is not None:
labels = labels.masked_fill(attention_mask == 0, self.ignore_index)
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
return MaskedLMOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
class BertModelForSequenceClassification(BertPreTrainedModel):
"""
Standard transformer model for sequence classification.
"""
config_class = BertEnergyConfig
def __init__(
self,
config,
add_pooling_layer=True,
pad_idx=None,
num_labels=2,
classifier_dropout=None,
return_dict=True,
):
super().__init__(config)
self.config = config
self.num_labels = num_labels
self.return_dict = return_dict
self.model = BertModel(config, pad_idx=pad_idx)
output_dim = self.model.output_dim
dropout = classifier_dropout if classifier_dropout is not None else config.hidden_dropout_prob
self.dropout = nn.Dropout(dropout)
self.norm = nn.LayerNorm(output_dim, eps=config.layer_norm_eps)
self.classifier = nn.Linear(output_dim, num_labels)
self.post_init()
def forward(self, input_ids, labels=None, return_dict=None, **kwargs):
if return_dict is None:
return_dict = self.return_dict
outputs = self.model(input_ids, **kwargs)
last_hidden_state = self.norm(outputs.last_hidden_state)
x = last_hidden_state[:, 0, :]
x = self.dropout(x)
logits = self.classifier(x)
loss = None
if labels is not None:
labels = labels.to(logits.device)
if self.config.problem_type is None:
if self.num_labels == 1:
self.config.problem_type = "regression"
elif self.num_labels > 1 and labels.dtype in (torch.long, torch.int):
self.config.problem_type = "single_label_classification"
else:
self.config.problem_type = "multi_label_classification"
if self.config.problem_type == "regression":
loss_fct = MSELoss()
loss = loss_fct(logits.squeeze(), labels.squeeze()) if self.num_labels == 1 else loss_fct(logits, labels)
elif self.config.problem_type == "single_label_classification":
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
else:
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if not return_dict:
output = (logits, outputs.hidden_states, outputs.attentions)
return ((loss,) + output) if loss is not None else output
return SequenceClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
class BertEnergyModel(BertPreTrainedModel):
"""
Energy-based backbone.
Update rule:
g = LayerNorm(X)
X <- X - alpha * layer(g)
"""
config_class = BertEnergyConfig
def __init__(self, config, add_pooling_layer=True, pad_idx=None, **kwargs):
super().__init__(config)
self.config = config
self.num_layers = config.num_hidden_layers
self.alpha = config.alpha
self.Emb_in = nn.Embedding(
config.vocab_size,
config.embedding_dim,
padding_idx=pad_idx,
)
self.posn = (
PositionalEncoding(
config.embedding_dim,
max_len=config.max_position_embeddings,
)
if config.positional
else None
)
self.embed_dropout = nn.Dropout(config.hidden_dropout_prob)
# External normalization, as in the original ET implementation
self.norm = nn.LayerNorm(config.embedding_dim, eps=config.layer_norm_eps)
self.layer = HopfieldLayer(
embedding_dim=config.embedding_dim,
nheads=config.num_attention_heads,
forward_memories=config.hidden_size,
forward_activation=config.activation,
bias=config.bias,
beta=config.beta,
device=None,
dropout=0.0,
initializer_range=config.initializer_hopfield_range,
)
self.post_init()
def set_input_embeddings(self, new_embeddings):
self.Emb_in = new_embeddings
def forward(self, input_ids, attention_mask=None, **kwargs):
x = self.Emb_in(input_ids)
if self.posn is not None:
x = x + self.posn(x)
x = self.embed_dropout(x)
keep_mask = attention_mask.to(torch.bool) if attention_mask is not None else None
history = None if self.training else [x]
for _ in range(self.num_layers):
g = self.norm(x)
update = self.layer(
g,
attention_mask=keep_mask,
)
x = x - self.alpha * update
if not self.training:
history.append(x)
return BaseModelOutput(
last_hidden_state=x,
hidden_states=history,
attentions=None,
)
class BertEnergyModelForMaskedLM(BertPreTrainedModel):
"""
Energy-based model for MLM.
"""
config_class = BertEnergyConfig
ignore_index = -100
_tied_weights_keys = ["lm_head.decoder.weight"]
def __init__(self, config, add_pooling_layer=True, pad_idx=None):
super().__init__(config)
self.config = config
self.model = BertEnergyModel(config, pad_idx=pad_idx)
self.lm_head = EnergyLMHead(config)
self.post_init()
if self.config.tie_word_embeddings:
self.tie_weights()
def get_input_embeddings(self):
return self.model.Emb_in
def set_input_embeddings(self, new_embeddings):
self.model.set_input_embeddings(new_embeddings)
def get_output_embeddings(self):
return self.lm_head.decoder
def set_output_embeddings(self, new_embeddings):
self.lm_head.decoder = new_embeddings
def forward(self, input_ids, attention_mask=None, labels=None, **kwargs):
outputs = self.model(input_ids, attention_mask=attention_mask, **kwargs)
logits = self.lm_head(outputs.last_hidden_state)
loss = None
if labels is not None:
if attention_mask is not None:
labels = labels.masked_fill(attention_mask == 0, self.ignore_index)
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
return MaskedLMOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
) |