'pooler_output' 的 Electra 序列分类与 pytorch 闪电问题
Electra sequence classification with pytorch lightning issues with 'pooler_output'
我正在处理一个句子分类任务,每个句子都有多个二进制标签。我正在使用 Electra 和 pytorch lightning 来完成这项工作,但我 运行 遇到了问题。当我 运行 宁 trainer.fit(model, data)
我得到以下错误:
AttributeError: 'tuple' object has no attribute 'pooler_output'
错误指的是我定义的部分中的第 13 行 pl.LightningModule
:
class CrowdCodedTagger(pl.LightningModule):
def __init__(self, n_classes: int, n_training_steps=None, n_warmup_steps=None):
super().__init__()
self.electra = ElectraModel.from_pretrained(ELECTRA_MODEL_NAME, return_dict=False) #changed ElectraModel to ElectraForSequenceClassification
self.classifier = nn.Linear(self.electra.config.hidden_size, n_classes)
self.n_training_steps = n_training_steps
self.n_warmup_steps = n_warmup_steps
self.criterion = nn.BCELoss()
def forward(self, input_ids, attention_mask, labels=None):
output = self.electra(input_ids, attention_mask=attention_mask)
output = self.classifier(output.pooler_output) # <---- this is the line the error is referring to.
output = torch.sigmoid(output)
loss = 0
if labels is not None:
loss = self.criterion(output, labels)
return loss, output
def training_step(self, batch, batch_idx):
input_ids = batch["input_ids"]
attention_mask = batch["attention_mask"]
labels = batch["labels"]
loss, outputs = self(input_ids, attention_mask, labels)
self.log("train_loss", loss, prog_bar=True, logger=True)
return {"loss": loss, "predictions": outputs, "labels": labels}
def validation_step(self, batch, batch_idx):
input_ids = batch["input_ids"]
attention_mask = batch["attention_mask"]
labels = batch["labels"]
loss, outputs = self(input_ids, attention_mask, labels)
self.log("val_loss", loss, prog_bar=True, logger=True)
return loss
def test_step(self, batch, batch_idx):
input_ids = batch["input_ids"]
attention_mask = batch["attention_mask"]
labels = batch["labels"]
loss, outputs = self(input_ids, attention_mask, labels)
self.log("test_loss", loss, prog_bar=True, logger=True)
return loss
def training_epoch_end(self, outputs):
labels = []
predictions = []
for output in outputs:
for out_labels in output["labels"].detach().cpu():
labels.append(out_labels)
for out_predictions in output["predictions"].detach().cpu():
predictions.append(out_predictions)
labels = torch.stack(labels).int()
predictions = torch.stack(predictions)
for i, name in enumerate(LABEL_COLUMNS):
class_roc_auc = auroc(predictions[:, i], labels[:, i])
self.logger.experiment.add_scalar(f"{name}_roc_auc/Train", class_roc_auc, self.current_epoch)
def configure_optimizers(self):
optimizer = AdamW(self.parameters(), lr=2e-5)
scheduler = get_linear_schedule_with_warmup(
optimizer,
num_warmup_steps=self.n_warmup_steps,
num_training_steps=self.n_training_steps
)
return dict(
optimizer=optimizer,
lr_scheduler=dict(
scheduler=scheduler,
interval='step'
)
)
任何人都可以指出我修复错误的方向吗?
数据结构示例(CSV 格式):
sentence label_1 label_2 label_3
Lorem ipsum dolor sit amet 1 0 1
consectetur adipiscing elit 0 0 0
sed do eiusmod tempor 0 1 1
incididunt ut labore et 1 0 0
Lorem ipsum dolor sit amet 1 0 1
ELECTRA has no pooler layer like BERT(比较 return 部分以获得更多信息)。
如果您只想使用 [CLS] 标记进行序列分类,您可以简单地使用 last_hidden_state 的第一个元素(在没有 return_dict=False
的情况下初始化 electra):
output = self.classifier(output.last_hidden_state[:, 0])
我正在处理一个句子分类任务,每个句子都有多个二进制标签。我正在使用 Electra 和 pytorch lightning 来完成这项工作,但我 运行 遇到了问题。当我 运行 宁 trainer.fit(model, data)
我得到以下错误:
AttributeError: 'tuple' object has no attribute 'pooler_output'
错误指的是我定义的部分中的第 13 行 pl.LightningModule
:
class CrowdCodedTagger(pl.LightningModule):
def __init__(self, n_classes: int, n_training_steps=None, n_warmup_steps=None):
super().__init__()
self.electra = ElectraModel.from_pretrained(ELECTRA_MODEL_NAME, return_dict=False) #changed ElectraModel to ElectraForSequenceClassification
self.classifier = nn.Linear(self.electra.config.hidden_size, n_classes)
self.n_training_steps = n_training_steps
self.n_warmup_steps = n_warmup_steps
self.criterion = nn.BCELoss()
def forward(self, input_ids, attention_mask, labels=None):
output = self.electra(input_ids, attention_mask=attention_mask)
output = self.classifier(output.pooler_output) # <---- this is the line the error is referring to.
output = torch.sigmoid(output)
loss = 0
if labels is not None:
loss = self.criterion(output, labels)
return loss, output
def training_step(self, batch, batch_idx):
input_ids = batch["input_ids"]
attention_mask = batch["attention_mask"]
labels = batch["labels"]
loss, outputs = self(input_ids, attention_mask, labels)
self.log("train_loss", loss, prog_bar=True, logger=True)
return {"loss": loss, "predictions": outputs, "labels": labels}
def validation_step(self, batch, batch_idx):
input_ids = batch["input_ids"]
attention_mask = batch["attention_mask"]
labels = batch["labels"]
loss, outputs = self(input_ids, attention_mask, labels)
self.log("val_loss", loss, prog_bar=True, logger=True)
return loss
def test_step(self, batch, batch_idx):
input_ids = batch["input_ids"]
attention_mask = batch["attention_mask"]
labels = batch["labels"]
loss, outputs = self(input_ids, attention_mask, labels)
self.log("test_loss", loss, prog_bar=True, logger=True)
return loss
def training_epoch_end(self, outputs):
labels = []
predictions = []
for output in outputs:
for out_labels in output["labels"].detach().cpu():
labels.append(out_labels)
for out_predictions in output["predictions"].detach().cpu():
predictions.append(out_predictions)
labels = torch.stack(labels).int()
predictions = torch.stack(predictions)
for i, name in enumerate(LABEL_COLUMNS):
class_roc_auc = auroc(predictions[:, i], labels[:, i])
self.logger.experiment.add_scalar(f"{name}_roc_auc/Train", class_roc_auc, self.current_epoch)
def configure_optimizers(self):
optimizer = AdamW(self.parameters(), lr=2e-5)
scheduler = get_linear_schedule_with_warmup(
optimizer,
num_warmup_steps=self.n_warmup_steps,
num_training_steps=self.n_training_steps
)
return dict(
optimizer=optimizer,
lr_scheduler=dict(
scheduler=scheduler,
interval='step'
)
)
任何人都可以指出我修复错误的方向吗?
数据结构示例(CSV 格式):
sentence label_1 label_2 label_3
Lorem ipsum dolor sit amet 1 0 1
consectetur adipiscing elit 0 0 0
sed do eiusmod tempor 0 1 1
incididunt ut labore et 1 0 0
Lorem ipsum dolor sit amet 1 0 1
ELECTRA has no pooler layer like BERT(比较 return 部分以获得更多信息)。
如果您只想使用 [CLS] 标记进行序列分类,您可以简单地使用 last_hidden_state 的第一个元素(在没有 return_dict=False
的情况下初始化 electra):
output = self.classifier(output.last_hidden_state[:, 0])