Upload custom_modeling.py with huggingface_hub
Browse files- custom_modeling.py +48 -49
custom_modeling.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
from transformers import
|
| 2 |
from transformers.modeling_outputs import TokenClassifierOutput
|
| 3 |
import torch
|
| 4 |
import torch.nn as nn
|
|
@@ -7,33 +7,19 @@ from typing import Optional, Union, Tuple, List
|
|
| 7 |
import os
|
| 8 |
import json
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
config_class = AutoConfig
|
| 13 |
-
base_model_prefix = "bert"
|
| 14 |
-
|
| 15 |
-
def _init_weights(self, module):
|
| 16 |
-
"""Initialize the weights"""
|
| 17 |
-
if isinstance(module, nn.Linear):
|
| 18 |
-
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range if hasattr(self.config, 'initializer_range') else 0.02)
|
| 19 |
-
if module.bias is not None:
|
| 20 |
-
module.bias.data.zero_()
|
| 21 |
-
elif isinstance(module, nn.Embedding):
|
| 22 |
-
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range if hasattr(self.config, 'initializer_range') else 0.02)
|
| 23 |
-
if module.padding_idx is not None:
|
| 24 |
-
module.weight.data[module.padding_idx].zero_()
|
| 25 |
-
elif isinstance(module, nn.LayerNorm):
|
| 26 |
-
module.bias.data.zero_()
|
| 27 |
-
module.weight.data.fill_(1.0)
|
| 28 |
-
|
| 29 |
-
class BertCRFForTokenClassification(BertCRFPreTrainedModel):
|
| 30 |
def __init__(self, config):
|
| 31 |
super().__init__(config)
|
| 32 |
self.num_labels = config.num_labels
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
| 34 |
self.dropout = nn.Dropout(config.hidden_dropout_prob if hasattr(config, 'hidden_dropout_prob') else 0.1)
|
| 35 |
-
self.classifier = nn.Linear(
|
| 36 |
|
|
|
|
| 37 |
self.use_crf = config.use_crf if hasattr(config, 'use_crf') else False
|
| 38 |
if self.use_crf:
|
| 39 |
self.crf = CRF(num_tags=self.num_labels, batch_first=True)
|
|
@@ -43,28 +29,27 @@ class BertCRFForTokenClassification(BertCRFPreTrainedModel):
|
|
| 43 |
|
| 44 |
# Initialize weights and apply final processing
|
| 45 |
self.post_init()
|
|
|
|
| 46 |
|
| 47 |
def forward(
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
|
| 60 |
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 61 |
|
| 62 |
-
outputs = self.
|
| 63 |
input_ids,
|
| 64 |
attention_mask=attention_mask,
|
| 65 |
-
token_type_ids=token_type_ids,
|
| 66 |
position_ids=position_ids,
|
| 67 |
-
head_mask=head_mask,
|
| 68 |
inputs_embeds=inputs_embeds,
|
| 69 |
output_attentions=output_attentions,
|
| 70 |
output_hidden_states=output_hidden_states,
|
|
@@ -74,7 +59,7 @@ class BertCRFForTokenClassification(BertCRFPreTrainedModel):
|
|
| 74 |
sequence_output = outputs[0]
|
| 75 |
sequence_output = self.dropout(sequence_output)
|
| 76 |
logits = self.classifier(sequence_output)
|
| 77 |
-
|
| 78 |
loss = None
|
| 79 |
if labels is not None:
|
| 80 |
if self.crf is not None:
|
|
@@ -100,11 +85,11 @@ class BertCRFForTokenClassification(BertCRFPreTrainedModel):
|
|
| 100 |
"""Save model with custom CRF layer"""
|
| 101 |
# Save the config
|
| 102 |
self.config.use_crf = self.use_crf
|
| 103 |
-
self.config.save_pretrained(save_directory)
|
| 104 |
-
|
| 105 |
# Save the model weights
|
| 106 |
-
super().save_pretrained(save_directory, **kwargs)
|
| 107 |
-
|
| 108 |
if self.crf is not None:
|
| 109 |
crf_path = os.path.join(save_directory, "crf.pt")
|
| 110 |
torch.save(self.crf.state_dict(), crf_path)
|
|
@@ -112,11 +97,25 @@ class BertCRFForTokenClassification(BertCRFPreTrainedModel):
|
|
| 112 |
@classmethod
|
| 113 |
def from_pretrained(cls, pretrained_model_name_or_path: str, *model_args, **kwargs):
|
| 114 |
"""Load model with custom CRF layer"""
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
if os.path.exists(crf_path) and model.use_crf:
|
| 120 |
-
model.crf.load_state_dict(torch.load(crf_path))
|
| 121 |
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import AutoModelForTokenClassification, AutoModel, AutoConfig
|
| 2 |
from transformers.modeling_outputs import TokenClassifierOutput
|
| 3 |
import torch
|
| 4 |
import torch.nn as nn
|
|
|
|
| 7 |
import os
|
| 8 |
import json
|
| 9 |
|
| 10 |
+
|
| 11 |
+
class TransformerCRFForTokenClassification(AutoModelForTokenClassification):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
def __init__(self, config):
|
| 13 |
super().__init__(config)
|
| 14 |
self.num_labels = config.num_labels
|
| 15 |
+
|
| 16 |
+
self.base_model = AutoModel.from_config(config=config, use_safetensors=True)
|
| 17 |
+
hidden_size = config.hidden_size if hasattr(config, 'hidden_size') else 768
|
| 18 |
+
|
| 19 |
self.dropout = nn.Dropout(config.hidden_dropout_prob if hasattr(config, 'hidden_dropout_prob') else 0.1)
|
| 20 |
+
self.classifier = nn.Linear(hidden_size, config.num_labels)
|
| 21 |
|
| 22 |
+
|
| 23 |
self.use_crf = config.use_crf if hasattr(config, 'use_crf') else False
|
| 24 |
if self.use_crf:
|
| 25 |
self.crf = CRF(num_tags=self.num_labels, batch_first=True)
|
|
|
|
| 29 |
|
| 30 |
# Initialize weights and apply final processing
|
| 31 |
self.post_init()
|
| 32 |
+
|
| 33 |
|
| 34 |
def forward(
|
| 35 |
+
self,
|
| 36 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 37 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 38 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 39 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 40 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 41 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 42 |
+
labels: Optional[torch.Tensor] = None,
|
| 43 |
+
output_attentions: Optional[bool] = None,
|
| 44 |
+
output_hidden_states: Optional[bool] = None,
|
| 45 |
+
return_dict: Optional[bool] = None,
|
| 46 |
) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
|
| 47 |
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 48 |
|
| 49 |
+
outputs = self.base_model(
|
| 50 |
input_ids,
|
| 51 |
attention_mask=attention_mask,
|
|
|
|
| 52 |
position_ids=position_ids,
|
|
|
|
| 53 |
inputs_embeds=inputs_embeds,
|
| 54 |
output_attentions=output_attentions,
|
| 55 |
output_hidden_states=output_hidden_states,
|
|
|
|
| 59 |
sequence_output = outputs[0]
|
| 60 |
sequence_output = self.dropout(sequence_output)
|
| 61 |
logits = self.classifier(sequence_output)
|
| 62 |
+
|
| 63 |
loss = None
|
| 64 |
if labels is not None:
|
| 65 |
if self.crf is not None:
|
|
|
|
| 85 |
"""Save model with custom CRF layer"""
|
| 86 |
# Save the config
|
| 87 |
self.config.use_crf = self.use_crf
|
| 88 |
+
self.config.save_pretrained(save_directory, safe_serialization=True)
|
| 89 |
+
|
| 90 |
# Save the model weights
|
| 91 |
+
super().save_pretrained(save_directory, safe_serialization=True, **kwargs)
|
| 92 |
+
|
| 93 |
if self.crf is not None:
|
| 94 |
crf_path = os.path.join(save_directory, "crf.pt")
|
| 95 |
torch.save(self.crf.state_dict(), crf_path)
|
|
|
|
| 97 |
@classmethod
|
| 98 |
def from_pretrained(cls, pretrained_model_name_or_path: str, *model_args, **kwargs):
|
| 99 |
"""Load model with custom CRF layer"""
|
| 100 |
+
if 'config' in kwargs:
|
| 101 |
+
config = kwargs.pop('config')
|
| 102 |
+
else:
|
| 103 |
+
config = AutoConfig.from_pretrained(pretrained_model_name_or_path)
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
# Ensure use_crf is set in the configuration
|
| 106 |
+
if not hasattr(config, 'use_crf'):
|
| 107 |
+
config.use_crf = False # or True, depending on your default
|
| 108 |
+
|
| 109 |
+
# Load the model
|
| 110 |
+
model = super().from_pretrained(pretrained_model_name_or_path, config=config, use_safetensors=True, *model_args, **kwargs)
|
| 111 |
+
|
| 112 |
+
# Initialize CRF if needed
|
| 113 |
+
if config.use_crf:
|
| 114 |
+
model.crf = CRF(num_tags=config.num_labels, batch_first=True)
|
| 115 |
+
crf_path = os.path.join(pretrained_model_name_or_path, "crf.pt")
|
| 116 |
+
if os.path.exists(crf_path):
|
| 117 |
+
model.crf.load_state_dict(torch.load(crf_path))
|
| 118 |
+
else:
|
| 119 |
+
model.crf = None
|
| 120 |
+
|
| 121 |
+
return model
|