Using weights with transformers huggingface

Viewed 553

I came across this tutorial which performs Text classification with the Longformer. I came across this two links - one and two which talk about using class weights when the data is unbalanced.

# instantiate the trainer class and check for available devices
trainer = Trainer(
    model=model,
    args=training_args,
    compute_metrics=compute_metrics,
    train_dataset=train_data,
    eval_dataset=test_data
)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
device

I am not sure how to modify the above piece of code to include class weights as shown below (code copied from the last link from above)

from torch import nn
from transformers import Trainer


class CustomTrainer(Trainer):
    def compute_loss(self, model, inputs, return_outputs=False):
        labels = inputs.get("labels")
        # forward pass
        outputs = model(**inputs)
        logits = outputs.get("logits")
        # compute custom loss (suppose one has 3 labels with different weights)
        loss_fct = nn.CrossEntropyLoss(weight=torch.tensor([1.0, 2.0, 3.0]))
        loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1))
        return (loss, outputs) if return_outputs else loss

Could someone clarify how to combine above two blocks?

update 1======================

as per the answer given below, if I modify code , then do I need to provide more arguments when I create trainer object so that compute_loss method gets used? would that method be called automatically? for example for that function one of the inputs is inputs and we are not feeding it when we create the trainer object

class CustomTrainer(Trainer):
    def compute_loss(self, model, inputs, return_outputs=False):
        labels = inputs.get("labels")
        # forward pass
        outputs = model(**inputs)
        logits = outputs.get("logits")
        # compute custom loss (suppose one has 3 labels with different weights)
        loss_fct = nn.CrossEntropyLoss(weight=torch.tensor([1.0, 2.0, 3.0]))
        loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1))
        return (loss, outputs) if return_outputs else loss


# instantiate the trainer class and check for available devices
trainer = CustomTrainer(
    model=model,
    args=training_args,
    compute_metrics=compute_metrics,
    train_dataset=train_data,
    eval_dataset=test_data
)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
device
1 Answers

Instead of instantiating a Trainer object, you can now simply have a CustomTrainer. This means, instead of writing

trainer = Trainer(...)

you simply write

trainer = CustomTrainer(...)

Since you inherit all the functions and default behavior from the Trainer class, the only difference will be the custom compute_loss() function.

Related