init
This commit is contained in:
0
transformers/tests/models/luke/__init__.py
Normal file
0
transformers/tests/models/luke/__init__.py
Normal file
954
transformers/tests/models/luke/test_modeling_luke.py
Normal file
954
transformers/tests/models/luke/test_modeling_luke.py
Normal file
@@ -0,0 +1,954 @@
|
||||
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
"""Testing suite for the PyTorch LUKE model."""
|
||||
|
||||
import unittest
|
||||
|
||||
from transformers import LukeConfig, is_torch_available
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
|
||||
from ...test_configuration_common import ConfigTester
|
||||
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
|
||||
from ...test_pipeline_mixin import PipelineTesterMixin
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
import torch
|
||||
|
||||
from transformers import (
|
||||
LukeForEntityClassification,
|
||||
LukeForEntityPairClassification,
|
||||
LukeForEntitySpanClassification,
|
||||
LukeForMaskedLM,
|
||||
LukeForMultipleChoice,
|
||||
LukeForQuestionAnswering,
|
||||
LukeForSequenceClassification,
|
||||
LukeForTokenClassification,
|
||||
LukeModel,
|
||||
LukeTokenizer,
|
||||
)
|
||||
|
||||
|
||||
class LukeModelTester:
|
||||
def __init__(
|
||||
self,
|
||||
parent,
|
||||
batch_size=13,
|
||||
seq_length=7,
|
||||
is_training=True,
|
||||
entity_length=3,
|
||||
mention_length=5,
|
||||
use_attention_mask=True,
|
||||
use_token_type_ids=True,
|
||||
use_entity_ids=True,
|
||||
use_entity_attention_mask=True,
|
||||
use_entity_token_type_ids=True,
|
||||
use_entity_position_ids=True,
|
||||
use_labels=True,
|
||||
vocab_size=99,
|
||||
entity_vocab_size=10,
|
||||
entity_emb_size=6,
|
||||
hidden_size=32,
|
||||
num_hidden_layers=2,
|
||||
num_attention_heads=4,
|
||||
intermediate_size=37,
|
||||
hidden_act="gelu",
|
||||
hidden_dropout_prob=0.1,
|
||||
attention_probs_dropout_prob=0.1,
|
||||
max_position_embeddings=512,
|
||||
type_vocab_size=16,
|
||||
type_sequence_label_size=2,
|
||||
initializer_range=0.02,
|
||||
num_labels=3,
|
||||
num_choices=4,
|
||||
num_entity_classification_labels=9,
|
||||
num_entity_pair_classification_labels=6,
|
||||
num_entity_span_classification_labels=4,
|
||||
use_entity_aware_attention=True,
|
||||
scope=None,
|
||||
):
|
||||
self.parent = parent
|
||||
self.batch_size = batch_size
|
||||
self.seq_length = seq_length
|
||||
self.is_training = is_training
|
||||
self.entity_length = entity_length
|
||||
self.mention_length = mention_length
|
||||
self.use_attention_mask = use_attention_mask
|
||||
self.use_token_type_ids = use_token_type_ids
|
||||
self.use_entity_ids = use_entity_ids
|
||||
self.use_entity_attention_mask = use_entity_attention_mask
|
||||
self.use_entity_token_type_ids = use_entity_token_type_ids
|
||||
self.use_entity_position_ids = use_entity_position_ids
|
||||
self.use_labels = use_labels
|
||||
self.vocab_size = vocab_size
|
||||
self.entity_vocab_size = entity_vocab_size
|
||||
self.entity_emb_size = entity_emb_size
|
||||
self.hidden_size = hidden_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.intermediate_size = intermediate_size
|
||||
self.hidden_act = hidden_act
|
||||
self.hidden_dropout_prob = hidden_dropout_prob
|
||||
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.type_vocab_size = type_vocab_size
|
||||
self.type_sequence_label_size = type_sequence_label_size
|
||||
self.initializer_range = initializer_range
|
||||
self.num_labels = num_labels
|
||||
self.num_choices = num_choices
|
||||
self.num_entity_classification_labels = num_entity_classification_labels
|
||||
self.num_entity_pair_classification_labels = num_entity_pair_classification_labels
|
||||
self.num_entity_span_classification_labels = num_entity_span_classification_labels
|
||||
self.scope = scope
|
||||
self.use_entity_aware_attention = use_entity_aware_attention
|
||||
|
||||
self.encoder_seq_length = seq_length
|
||||
self.key_length = seq_length
|
||||
self.num_hidden_states_types = 2 # hidden_states and entity_hidden_states
|
||||
|
||||
def prepare_config_and_inputs(self):
|
||||
# prepare words
|
||||
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
||||
|
||||
attention_mask = None
|
||||
if self.use_attention_mask:
|
||||
attention_mask = random_attention_mask([self.batch_size, self.seq_length])
|
||||
|
||||
token_type_ids = None
|
||||
if self.use_token_type_ids:
|
||||
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
||||
|
||||
# prepare entities
|
||||
entity_ids = ids_tensor([self.batch_size, self.entity_length], self.entity_vocab_size)
|
||||
|
||||
entity_attention_mask = None
|
||||
if self.use_entity_attention_mask:
|
||||
entity_attention_mask = random_attention_mask([self.batch_size, self.entity_length])
|
||||
|
||||
entity_token_type_ids = None
|
||||
if self.use_token_type_ids:
|
||||
entity_token_type_ids = ids_tensor([self.batch_size, self.entity_length], self.type_vocab_size)
|
||||
|
||||
entity_position_ids = None
|
||||
if self.use_entity_position_ids:
|
||||
entity_position_ids = ids_tensor(
|
||||
[self.batch_size, self.entity_length, self.mention_length], self.mention_length
|
||||
)
|
||||
|
||||
sequence_labels = None
|
||||
token_labels = None
|
||||
choice_labels = None
|
||||
entity_labels = None
|
||||
entity_classification_labels = None
|
||||
entity_pair_classification_labels = None
|
||||
entity_span_classification_labels = None
|
||||
|
||||
if self.use_labels:
|
||||
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
||||
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
||||
choice_labels = ids_tensor([self.batch_size], self.num_choices)
|
||||
|
||||
entity_labels = ids_tensor([self.batch_size, self.entity_length], self.entity_vocab_size)
|
||||
|
||||
entity_classification_labels = ids_tensor([self.batch_size], self.num_entity_classification_labels)
|
||||
entity_pair_classification_labels = ids_tensor(
|
||||
[self.batch_size], self.num_entity_pair_classification_labels
|
||||
)
|
||||
entity_span_classification_labels = ids_tensor(
|
||||
[self.batch_size, self.entity_length], self.num_entity_span_classification_labels
|
||||
)
|
||||
|
||||
config = self.get_config()
|
||||
|
||||
return (
|
||||
config,
|
||||
input_ids,
|
||||
attention_mask,
|
||||
token_type_ids,
|
||||
entity_ids,
|
||||
entity_attention_mask,
|
||||
entity_token_type_ids,
|
||||
entity_position_ids,
|
||||
sequence_labels,
|
||||
token_labels,
|
||||
choice_labels,
|
||||
entity_labels,
|
||||
entity_classification_labels,
|
||||
entity_pair_classification_labels,
|
||||
entity_span_classification_labels,
|
||||
)
|
||||
|
||||
def get_config(self):
|
||||
return LukeConfig(
|
||||
vocab_size=self.vocab_size,
|
||||
entity_vocab_size=self.entity_vocab_size,
|
||||
entity_emb_size=self.entity_emb_size,
|
||||
hidden_size=self.hidden_size,
|
||||
num_hidden_layers=self.num_hidden_layers,
|
||||
num_attention_heads=self.num_attention_heads,
|
||||
intermediate_size=self.intermediate_size,
|
||||
hidden_act=self.hidden_act,
|
||||
hidden_dropout_prob=self.hidden_dropout_prob,
|
||||
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
||||
max_position_embeddings=self.max_position_embeddings,
|
||||
type_vocab_size=self.type_vocab_size,
|
||||
is_decoder=False,
|
||||
initializer_range=self.initializer_range,
|
||||
use_entity_aware_attention=self.use_entity_aware_attention,
|
||||
)
|
||||
|
||||
def create_and_check_model(
|
||||
self,
|
||||
config,
|
||||
input_ids,
|
||||
attention_mask,
|
||||
token_type_ids,
|
||||
entity_ids,
|
||||
entity_attention_mask,
|
||||
entity_token_type_ids,
|
||||
entity_position_ids,
|
||||
sequence_labels,
|
||||
token_labels,
|
||||
choice_labels,
|
||||
entity_labels,
|
||||
entity_classification_labels,
|
||||
entity_pair_classification_labels,
|
||||
entity_span_classification_labels,
|
||||
):
|
||||
model = LukeModel(config=config)
|
||||
model.to(torch_device)
|
||||
model.eval()
|
||||
# test with words + entities
|
||||
result = model(
|
||||
input_ids,
|
||||
attention_mask=attention_mask,
|
||||
token_type_ids=token_type_ids,
|
||||
entity_ids=entity_ids,
|
||||
entity_attention_mask=entity_attention_mask,
|
||||
entity_token_type_ids=entity_token_type_ids,
|
||||
entity_position_ids=entity_position_ids,
|
||||
)
|
||||
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
||||
self.parent.assertEqual(
|
||||
result.entity_last_hidden_state.shape, (self.batch_size, self.entity_length, self.hidden_size)
|
||||
)
|
||||
|
||||
# test with words only
|
||||
result = model(input_ids, token_type_ids=token_type_ids)
|
||||
result = model(input_ids)
|
||||
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
||||
|
||||
def create_and_check_for_masked_lm(
|
||||
self,
|
||||
config,
|
||||
input_ids,
|
||||
attention_mask,
|
||||
token_type_ids,
|
||||
entity_ids,
|
||||
entity_attention_mask,
|
||||
entity_token_type_ids,
|
||||
entity_position_ids,
|
||||
sequence_labels,
|
||||
token_labels,
|
||||
choice_labels,
|
||||
entity_labels,
|
||||
entity_classification_labels,
|
||||
entity_pair_classification_labels,
|
||||
entity_span_classification_labels,
|
||||
):
|
||||
config.num_labels = self.num_entity_classification_labels
|
||||
model = LukeForMaskedLM(config)
|
||||
model.to(torch_device)
|
||||
model.eval()
|
||||
|
||||
result = model(
|
||||
input_ids,
|
||||
attention_mask=attention_mask,
|
||||
token_type_ids=token_type_ids,
|
||||
entity_ids=entity_ids,
|
||||
entity_attention_mask=entity_attention_mask,
|
||||
entity_token_type_ids=entity_token_type_ids,
|
||||
entity_position_ids=entity_position_ids,
|
||||
labels=token_labels,
|
||||
entity_labels=entity_labels,
|
||||
)
|
||||
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
||||
if entity_ids is not None:
|
||||
self.parent.assertEqual(
|
||||
result.entity_logits.shape, (self.batch_size, self.entity_length, self.entity_vocab_size)
|
||||
)
|
||||
else:
|
||||
self.parent.assertIsNone(result.entity_logits)
|
||||
|
||||
def create_and_check_for_entity_classification(
|
||||
self,
|
||||
config,
|
||||
input_ids,
|
||||
attention_mask,
|
||||
token_type_ids,
|
||||
entity_ids,
|
||||
entity_attention_mask,
|
||||
entity_token_type_ids,
|
||||
entity_position_ids,
|
||||
sequence_labels,
|
||||
token_labels,
|
||||
choice_labels,
|
||||
entity_labels,
|
||||
entity_classification_labels,
|
||||
entity_pair_classification_labels,
|
||||
entity_span_classification_labels,
|
||||
):
|
||||
config.num_labels = self.num_entity_classification_labels
|
||||
model = LukeForEntityClassification(config)
|
||||
model.to(torch_device)
|
||||
model.eval()
|
||||
|
||||
result = model(
|
||||
input_ids,
|
||||
attention_mask=attention_mask,
|
||||
token_type_ids=token_type_ids,
|
||||
entity_ids=entity_ids,
|
||||
entity_attention_mask=entity_attention_mask,
|
||||
entity_token_type_ids=entity_token_type_ids,
|
||||
entity_position_ids=entity_position_ids,
|
||||
labels=entity_classification_labels,
|
||||
)
|
||||
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_entity_classification_labels))
|
||||
|
||||
def create_and_check_for_entity_pair_classification(
|
||||
self,
|
||||
config,
|
||||
input_ids,
|
||||
attention_mask,
|
||||
token_type_ids,
|
||||
entity_ids,
|
||||
entity_attention_mask,
|
||||
entity_token_type_ids,
|
||||
entity_position_ids,
|
||||
sequence_labels,
|
||||
token_labels,
|
||||
choice_labels,
|
||||
entity_labels,
|
||||
entity_classification_labels,
|
||||
entity_pair_classification_labels,
|
||||
entity_span_classification_labels,
|
||||
):
|
||||
config.num_labels = self.num_entity_pair_classification_labels
|
||||
model = LukeForEntityClassification(config)
|
||||
model.to(torch_device)
|
||||
model.eval()
|
||||
|
||||
result = model(
|
||||
input_ids,
|
||||
attention_mask=attention_mask,
|
||||
token_type_ids=token_type_ids,
|
||||
entity_ids=entity_ids,
|
||||
entity_attention_mask=entity_attention_mask,
|
||||
entity_token_type_ids=entity_token_type_ids,
|
||||
entity_position_ids=entity_position_ids,
|
||||
labels=entity_pair_classification_labels,
|
||||
)
|
||||
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_entity_pair_classification_labels))
|
||||
|
||||
def create_and_check_for_entity_span_classification(
|
||||
self,
|
||||
config,
|
||||
input_ids,
|
||||
attention_mask,
|
||||
token_type_ids,
|
||||
entity_ids,
|
||||
entity_attention_mask,
|
||||
entity_token_type_ids,
|
||||
entity_position_ids,
|
||||
sequence_labels,
|
||||
token_labels,
|
||||
choice_labels,
|
||||
entity_labels,
|
||||
entity_classification_labels,
|
||||
entity_pair_classification_labels,
|
||||
entity_span_classification_labels,
|
||||
):
|
||||
config.num_labels = self.num_entity_span_classification_labels
|
||||
model = LukeForEntitySpanClassification(config)
|
||||
model.to(torch_device)
|
||||
model.eval()
|
||||
|
||||
entity_start_positions = ids_tensor([self.batch_size, self.entity_length], self.seq_length)
|
||||
entity_end_positions = ids_tensor([self.batch_size, self.entity_length], self.seq_length)
|
||||
|
||||
result = model(
|
||||
input_ids,
|
||||
attention_mask=attention_mask,
|
||||
token_type_ids=token_type_ids,
|
||||
entity_ids=entity_ids,
|
||||
entity_attention_mask=entity_attention_mask,
|
||||
entity_token_type_ids=entity_token_type_ids,
|
||||
entity_position_ids=entity_position_ids,
|
||||
entity_start_positions=entity_start_positions,
|
||||
entity_end_positions=entity_end_positions,
|
||||
labels=entity_span_classification_labels,
|
||||
)
|
||||
self.parent.assertEqual(
|
||||
result.logits.shape, (self.batch_size, self.entity_length, self.num_entity_span_classification_labels)
|
||||
)
|
||||
|
||||
def create_and_check_for_question_answering(
|
||||
self,
|
||||
config,
|
||||
input_ids,
|
||||
attention_mask,
|
||||
token_type_ids,
|
||||
entity_ids,
|
||||
entity_attention_mask,
|
||||
entity_token_type_ids,
|
||||
entity_position_ids,
|
||||
sequence_labels,
|
||||
token_labels,
|
||||
choice_labels,
|
||||
entity_labels,
|
||||
entity_classification_labels,
|
||||
entity_pair_classification_labels,
|
||||
entity_span_classification_labels,
|
||||
):
|
||||
model = LukeForQuestionAnswering(config=config)
|
||||
model.to(torch_device)
|
||||
model.eval()
|
||||
result = model(
|
||||
input_ids,
|
||||
attention_mask=attention_mask,
|
||||
token_type_ids=token_type_ids,
|
||||
entity_ids=entity_ids,
|
||||
entity_attention_mask=entity_attention_mask,
|
||||
entity_token_type_ids=entity_token_type_ids,
|
||||
entity_position_ids=entity_position_ids,
|
||||
start_positions=sequence_labels,
|
||||
end_positions=sequence_labels,
|
||||
)
|
||||
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
|
||||
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
|
||||
|
||||
def create_and_check_for_sequence_classification(
|
||||
self,
|
||||
config,
|
||||
input_ids,
|
||||
attention_mask,
|
||||
token_type_ids,
|
||||
entity_ids,
|
||||
entity_attention_mask,
|
||||
entity_token_type_ids,
|
||||
entity_position_ids,
|
||||
sequence_labels,
|
||||
token_labels,
|
||||
choice_labels,
|
||||
entity_labels,
|
||||
entity_classification_labels,
|
||||
entity_pair_classification_labels,
|
||||
entity_span_classification_labels,
|
||||
):
|
||||
config.num_labels = self.num_labels
|
||||
model = LukeForSequenceClassification(config)
|
||||
model.to(torch_device)
|
||||
model.eval()
|
||||
result = model(
|
||||
input_ids,
|
||||
attention_mask=attention_mask,
|
||||
token_type_ids=token_type_ids,
|
||||
entity_ids=entity_ids,
|
||||
entity_attention_mask=entity_attention_mask,
|
||||
entity_token_type_ids=entity_token_type_ids,
|
||||
entity_position_ids=entity_position_ids,
|
||||
labels=sequence_labels,
|
||||
)
|
||||
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
|
||||
|
||||
def create_and_check_for_token_classification(
|
||||
self,
|
||||
config,
|
||||
input_ids,
|
||||
attention_mask,
|
||||
token_type_ids,
|
||||
entity_ids,
|
||||
entity_attention_mask,
|
||||
entity_token_type_ids,
|
||||
entity_position_ids,
|
||||
sequence_labels,
|
||||
token_labels,
|
||||
choice_labels,
|
||||
entity_labels,
|
||||
entity_classification_labels,
|
||||
entity_pair_classification_labels,
|
||||
entity_span_classification_labels,
|
||||
):
|
||||
config.num_labels = self.num_labels
|
||||
model = LukeForTokenClassification(config=config)
|
||||
model.to(torch_device)
|
||||
model.eval()
|
||||
result = model(
|
||||
input_ids,
|
||||
attention_mask=attention_mask,
|
||||
token_type_ids=token_type_ids,
|
||||
entity_ids=entity_ids,
|
||||
entity_attention_mask=entity_attention_mask,
|
||||
entity_token_type_ids=entity_token_type_ids,
|
||||
entity_position_ids=entity_position_ids,
|
||||
labels=token_labels,
|
||||
)
|
||||
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
|
||||
|
||||
def create_and_check_for_multiple_choice(
|
||||
self,
|
||||
config,
|
||||
input_ids,
|
||||
attention_mask,
|
||||
token_type_ids,
|
||||
entity_ids,
|
||||
entity_attention_mask,
|
||||
entity_token_type_ids,
|
||||
entity_position_ids,
|
||||
sequence_labels,
|
||||
token_labels,
|
||||
choice_labels,
|
||||
entity_labels,
|
||||
entity_classification_labels,
|
||||
entity_pair_classification_labels,
|
||||
entity_span_classification_labels,
|
||||
):
|
||||
config.num_choices = self.num_choices
|
||||
model = LukeForMultipleChoice(config=config)
|
||||
model.to(torch_device)
|
||||
model.eval()
|
||||
multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
||||
multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
||||
multiple_choice_attention_mask = attention_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
||||
multiple_choice_entity_ids = entity_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
||||
multiple_choice_entity_token_type_ids = (
|
||||
entity_token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
||||
)
|
||||
multiple_choice_entity_attention_mask = (
|
||||
entity_attention_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
||||
)
|
||||
multiple_choice_entity_position_ids = (
|
||||
entity_position_ids.unsqueeze(1).expand(-1, self.num_choices, -1, -1).contiguous()
|
||||
)
|
||||
result = model(
|
||||
multiple_choice_inputs_ids,
|
||||
attention_mask=multiple_choice_attention_mask,
|
||||
token_type_ids=multiple_choice_token_type_ids,
|
||||
entity_ids=multiple_choice_entity_ids,
|
||||
entity_attention_mask=multiple_choice_entity_attention_mask,
|
||||
entity_token_type_ids=multiple_choice_entity_token_type_ids,
|
||||
entity_position_ids=multiple_choice_entity_position_ids,
|
||||
labels=choice_labels,
|
||||
)
|
||||
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
|
||||
|
||||
def prepare_config_and_inputs_for_common(self):
|
||||
config_and_inputs = self.prepare_config_and_inputs()
|
||||
(
|
||||
config,
|
||||
input_ids,
|
||||
attention_mask,
|
||||
token_type_ids,
|
||||
entity_ids,
|
||||
entity_attention_mask,
|
||||
entity_token_type_ids,
|
||||
entity_position_ids,
|
||||
sequence_labels,
|
||||
token_labels,
|
||||
choice_labels,
|
||||
entity_labels,
|
||||
entity_classification_labels,
|
||||
entity_pair_classification_labels,
|
||||
entity_span_classification_labels,
|
||||
) = config_and_inputs
|
||||
inputs_dict = {
|
||||
"input_ids": input_ids,
|
||||
"token_type_ids": token_type_ids,
|
||||
"attention_mask": attention_mask,
|
||||
"entity_ids": entity_ids,
|
||||
"entity_token_type_ids": entity_token_type_ids,
|
||||
"entity_attention_mask": entity_attention_mask,
|
||||
"entity_position_ids": entity_position_ids,
|
||||
}
|
||||
return config, inputs_dict
|
||||
|
||||
|
||||
@require_torch
|
||||
class LukeModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
||||
all_model_classes = (
|
||||
(
|
||||
LukeModel,
|
||||
LukeForMaskedLM,
|
||||
LukeForEntityClassification,
|
||||
LukeForEntityPairClassification,
|
||||
LukeForEntitySpanClassification,
|
||||
LukeForQuestionAnswering,
|
||||
LukeForSequenceClassification,
|
||||
LukeForTokenClassification,
|
||||
LukeForMultipleChoice,
|
||||
)
|
||||
if is_torch_available()
|
||||
else ()
|
||||
)
|
||||
pipeline_model_mapping = (
|
||||
{
|
||||
"feature-extraction": LukeModel,
|
||||
"fill-mask": LukeForMaskedLM,
|
||||
"question-answering": LukeForQuestionAnswering,
|
||||
"text-classification": LukeForSequenceClassification,
|
||||
"token-classification": LukeForTokenClassification,
|
||||
"zero-shot": LukeForSequenceClassification,
|
||||
}
|
||||
if is_torch_available()
|
||||
else {}
|
||||
)
|
||||
test_pruning = False
|
||||
test_torchscript = False
|
||||
test_resize_embeddings = True
|
||||
test_head_masking = True
|
||||
|
||||
# TODO: Fix the failed tests
|
||||
def is_pipeline_test_to_skip(
|
||||
self,
|
||||
pipeline_test_case_name,
|
||||
config_class,
|
||||
model_architecture,
|
||||
tokenizer_name,
|
||||
image_processor_name,
|
||||
feature_extractor_name,
|
||||
processor_name,
|
||||
):
|
||||
if pipeline_test_case_name in ["QAPipelineTests", "ZeroShotClassificationPipelineTests"]:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
|
||||
entity_inputs_dict = {k: v for k, v in inputs_dict.items() if k.startswith("entity")}
|
||||
inputs_dict = {k: v for k, v in inputs_dict.items() if not k.startswith("entity")}
|
||||
|
||||
inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
|
||||
if model_class == LukeForMultipleChoice:
|
||||
entity_inputs_dict = {
|
||||
k: v.unsqueeze(1).expand(-1, self.model_tester.num_choices, -1).contiguous()
|
||||
if v.ndim == 2
|
||||
else v.unsqueeze(1).expand(-1, self.model_tester.num_choices, -1, -1).contiguous()
|
||||
for k, v in entity_inputs_dict.items()
|
||||
}
|
||||
inputs_dict.update(entity_inputs_dict)
|
||||
|
||||
if model_class == LukeForEntitySpanClassification:
|
||||
inputs_dict["entity_start_positions"] = torch.zeros(
|
||||
(self.model_tester.batch_size, self.model_tester.entity_length), dtype=torch.long, device=torch_device
|
||||
)
|
||||
inputs_dict["entity_end_positions"] = torch.ones(
|
||||
(self.model_tester.batch_size, self.model_tester.entity_length), dtype=torch.long, device=torch_device
|
||||
)
|
||||
|
||||
if return_labels:
|
||||
if model_class in (
|
||||
LukeForEntityClassification,
|
||||
LukeForEntityPairClassification,
|
||||
LukeForSequenceClassification,
|
||||
LukeForMultipleChoice,
|
||||
):
|
||||
inputs_dict["labels"] = torch.zeros(
|
||||
self.model_tester.batch_size, dtype=torch.long, device=torch_device
|
||||
)
|
||||
elif model_class == LukeForEntitySpanClassification:
|
||||
inputs_dict["labels"] = torch.zeros(
|
||||
(self.model_tester.batch_size, self.model_tester.entity_length),
|
||||
dtype=torch.long,
|
||||
device=torch_device,
|
||||
)
|
||||
elif model_class == LukeForTokenClassification:
|
||||
inputs_dict["labels"] = torch.zeros(
|
||||
(self.model_tester.batch_size, self.model_tester.seq_length),
|
||||
dtype=torch.long,
|
||||
device=torch_device,
|
||||
)
|
||||
elif model_class == LukeForMaskedLM:
|
||||
inputs_dict["labels"] = torch.zeros(
|
||||
(self.model_tester.batch_size, self.model_tester.seq_length),
|
||||
dtype=torch.long,
|
||||
device=torch_device,
|
||||
)
|
||||
inputs_dict["entity_labels"] = torch.zeros(
|
||||
(self.model_tester.batch_size, self.model_tester.entity_length),
|
||||
dtype=torch.long,
|
||||
device=torch_device,
|
||||
)
|
||||
|
||||
return inputs_dict
|
||||
|
||||
def setUp(self):
|
||||
self.model_tester = LukeModelTester(self)
|
||||
self.config_tester = ConfigTester(self, config_class=LukeConfig, hidden_size=37)
|
||||
|
||||
def test_config(self):
|
||||
self.config_tester.run_common_tests()
|
||||
|
||||
def test_model(self):
|
||||
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
||||
self.model_tester.create_and_check_model(*config_and_inputs)
|
||||
|
||||
@slow
|
||||
def test_model_from_pretrained(self):
|
||||
model_name = "studio-ousia/luke-base"
|
||||
model = LukeModel.from_pretrained(model_name)
|
||||
self.assertIsNotNone(model)
|
||||
|
||||
def test_for_masked_lm(self):
|
||||
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
||||
self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
|
||||
|
||||
def test_for_masked_lm_with_word_only(self):
|
||||
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
||||
config_and_inputs = (*config_and_inputs[:4], *((None,) * len(config_and_inputs[4:])))
|
||||
self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
|
||||
|
||||
def test_for_question_answering(self):
|
||||
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
||||
self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
|
||||
|
||||
def test_for_sequence_classification(self):
|
||||
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
||||
self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
|
||||
|
||||
def test_for_token_classification(self):
|
||||
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
||||
self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
|
||||
|
||||
def test_for_multiple_choice(self):
|
||||
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
||||
self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
|
||||
|
||||
def test_for_entity_classification(self):
|
||||
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
||||
self.model_tester.create_and_check_for_entity_classification(*config_and_inputs)
|
||||
|
||||
def test_for_entity_pair_classification(self):
|
||||
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
||||
self.model_tester.create_and_check_for_entity_pair_classification(*config_and_inputs)
|
||||
|
||||
def test_for_entity_span_classification(self):
|
||||
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
||||
self.model_tester.create_and_check_for_entity_span_classification(*config_and_inputs)
|
||||
|
||||
def test_attention_outputs(self):
|
||||
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
||||
config.return_dict = True
|
||||
|
||||
seq_length = self.model_tester.seq_length
|
||||
entity_length = self.model_tester.entity_length
|
||||
key_length = seq_length + entity_length
|
||||
|
||||
for model_class in self.all_model_classes:
|
||||
inputs_dict["output_attentions"] = True
|
||||
inputs_dict["output_hidden_states"] = False
|
||||
config.return_dict = True
|
||||
model = model_class._from_config(config, attn_implementation="eager")
|
||||
config = model.config
|
||||
model.to(torch_device)
|
||||
model.eval()
|
||||
with torch.no_grad():
|
||||
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
||||
attentions = outputs.attentions
|
||||
self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
|
||||
|
||||
# check that output_attentions also work using config
|
||||
del inputs_dict["output_attentions"]
|
||||
config.output_attentions = True
|
||||
model = model_class(config)
|
||||
model.to(torch_device)
|
||||
model.eval()
|
||||
with torch.no_grad():
|
||||
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
||||
attentions = outputs.attentions
|
||||
self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
|
||||
|
||||
self.assertListEqual(
|
||||
list(attentions[0].shape[-3:]),
|
||||
[self.model_tester.num_attention_heads, seq_length + entity_length, key_length],
|
||||
)
|
||||
out_len = len(outputs)
|
||||
|
||||
# Check attention is always last and order is fine
|
||||
inputs_dict["output_attentions"] = True
|
||||
inputs_dict["output_hidden_states"] = True
|
||||
model = model_class(config)
|
||||
model.to(torch_device)
|
||||
model.eval()
|
||||
with torch.no_grad():
|
||||
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
||||
|
||||
added_hidden_states = self.model_tester.num_hidden_states_types
|
||||
self.assertEqual(out_len + added_hidden_states, len(outputs))
|
||||
|
||||
self_attentions = outputs.attentions
|
||||
|
||||
self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers)
|
||||
self.assertListEqual(
|
||||
list(self_attentions[0].shape[-3:]),
|
||||
[self.model_tester.num_attention_heads, seq_length + entity_length, key_length],
|
||||
)
|
||||
|
||||
def test_entity_hidden_states_output(self):
|
||||
def check_hidden_states_output(inputs_dict, config, model_class):
|
||||
model = model_class(config)
|
||||
model.to(torch_device)
|
||||
model.eval()
|
||||
|
||||
with torch.no_grad():
|
||||
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
||||
|
||||
entity_hidden_states = outputs.entity_hidden_states
|
||||
|
||||
expected_num_layers = getattr(
|
||||
self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1
|
||||
)
|
||||
self.assertEqual(len(entity_hidden_states), expected_num_layers)
|
||||
|
||||
entity_length = self.model_tester.entity_length
|
||||
|
||||
self.assertListEqual(
|
||||
list(entity_hidden_states[0].shape[-2:]),
|
||||
[entity_length, self.model_tester.hidden_size],
|
||||
)
|
||||
|
||||
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
||||
|
||||
for model_class in self.all_model_classes:
|
||||
inputs_dict["output_hidden_states"] = True
|
||||
check_hidden_states_output(inputs_dict, config, model_class)
|
||||
|
||||
# check that output_hidden_states also work using config
|
||||
del inputs_dict["output_hidden_states"]
|
||||
config.output_hidden_states = True
|
||||
|
||||
check_hidden_states_output(inputs_dict, config, model_class)
|
||||
|
||||
def test_retain_grad_entity_hidden_states(self):
|
||||
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
||||
config.output_hidden_states = True
|
||||
config.output_attentions = True
|
||||
|
||||
# no need to test all models as different heads yield the same functionality
|
||||
model_class = self.all_model_classes[0]
|
||||
model = model_class(config)
|
||||
model.to(torch_device)
|
||||
|
||||
inputs = self._prepare_for_class(inputs_dict, model_class)
|
||||
|
||||
outputs = model(**inputs)
|
||||
|
||||
output = outputs[0]
|
||||
|
||||
entity_hidden_states = outputs.entity_hidden_states[0]
|
||||
entity_hidden_states.retain_grad()
|
||||
|
||||
output.flatten()[0].backward(retain_graph=True)
|
||||
|
||||
self.assertIsNotNone(entity_hidden_states.grad)
|
||||
|
||||
@unittest.skip(
|
||||
reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
|
||||
)
|
||||
def test_training_gradient_checkpointing(self):
|
||||
pass
|
||||
|
||||
@unittest.skip(
|
||||
reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
|
||||
)
|
||||
def test_training_gradient_checkpointing_use_reentrant(self):
|
||||
pass
|
||||
|
||||
@unittest.skip(
|
||||
reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
|
||||
)
|
||||
def test_training_gradient_checkpointing_use_reentrant_false(self):
|
||||
pass
|
||||
|
||||
|
||||
@require_torch
|
||||
class LukeModelIntegrationTests(unittest.TestCase):
|
||||
@slow
|
||||
def test_inference_base_model(self):
|
||||
model = LukeModel.from_pretrained("studio-ousia/luke-base").eval()
|
||||
model.to(torch_device)
|
||||
|
||||
tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-base", task="entity_classification")
|
||||
text = (
|
||||
"Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped"
|
||||
" the new world number one avoid a humiliating second- round exit at Wimbledon ."
|
||||
)
|
||||
span = (39, 42)
|
||||
encoding = tokenizer(text, entity_spans=[span], add_prefix_space=True, return_tensors="pt")
|
||||
|
||||
# move all values to device
|
||||
for key in encoding:
|
||||
encoding[key] = encoding[key].to(torch_device)
|
||||
|
||||
outputs = model(**encoding)
|
||||
|
||||
# Verify word hidden states
|
||||
expected_shape = torch.Size((1, 42, 768))
|
||||
self.assertEqual(outputs.last_hidden_state.shape, expected_shape)
|
||||
|
||||
expected_slice = torch.tensor(
|
||||
[[0.0037, 0.1368, -0.0091], [0.1099, 0.3329, -0.1095], [0.0765, 0.5335, 0.1179]]
|
||||
).to(torch_device)
|
||||
torch.testing.assert_close(outputs.last_hidden_state[0, :3, :3], expected_slice, rtol=1e-4, atol=1e-4)
|
||||
|
||||
# Verify entity hidden states
|
||||
expected_shape = torch.Size((1, 1, 768))
|
||||
self.assertEqual(outputs.entity_last_hidden_state.shape, expected_shape)
|
||||
|
||||
expected_slice = torch.tensor([[0.1457, 0.1044, 0.0174]]).to(torch_device)
|
||||
torch.testing.assert_close(outputs.entity_last_hidden_state[0, :3, :3], expected_slice, rtol=1e-4, atol=1e-4)
|
||||
|
||||
@slow
|
||||
def test_inference_large_model(self):
|
||||
model = LukeModel.from_pretrained("studio-ousia/luke-large").eval()
|
||||
model.to(torch_device)
|
||||
|
||||
tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-large", task="entity_classification")
|
||||
text = (
|
||||
"Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped"
|
||||
" the new world number one avoid a humiliating second- round exit at Wimbledon ."
|
||||
)
|
||||
span = (39, 42)
|
||||
encoding = tokenizer(text, entity_spans=[span], add_prefix_space=True, return_tensors="pt")
|
||||
|
||||
# move all values to device
|
||||
for key in encoding:
|
||||
encoding[key] = encoding[key].to(torch_device)
|
||||
|
||||
outputs = model(**encoding)
|
||||
|
||||
# Verify word hidden states
|
||||
expected_shape = torch.Size((1, 42, 1024))
|
||||
self.assertEqual(outputs.last_hidden_state.shape, expected_shape)
|
||||
|
||||
expected_slice = torch.tensor(
|
||||
[[0.0133, 0.0865, 0.0095], [0.3093, -0.2576, -0.7418], [-0.1720, -0.2117, -0.2869]]
|
||||
).to(torch_device)
|
||||
torch.testing.assert_close(outputs.last_hidden_state[0, :3, :3], expected_slice, rtol=1e-4, atol=1e-4)
|
||||
|
||||
# Verify entity hidden states
|
||||
expected_shape = torch.Size((1, 1, 1024))
|
||||
self.assertEqual(outputs.entity_last_hidden_state.shape, expected_shape)
|
||||
|
||||
expected_slice = torch.tensor([[0.0466, -0.0106, -0.0179]]).to(torch_device)
|
||||
torch.testing.assert_close(outputs.entity_last_hidden_state[0, :3, :3], expected_slice, rtol=1e-4, atol=1e-4)
|
||||
667
transformers/tests/models/luke/test_tokenization_luke.py
Normal file
667
transformers/tests/models/luke/test_tokenization_luke.py
Normal file
@@ -0,0 +1,667 @@
|
||||
# Copyright 2021 The HuggingFace Team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import unittest
|
||||
|
||||
from transformers import AddedToken, LukeTokenizer
|
||||
from transformers.testing_utils import get_tests_dir, require_torch, slow
|
||||
|
||||
from ...test_tokenization_common import TokenizerTesterMixin
|
||||
|
||||
|
||||
SAMPLE_VOCAB = get_tests_dir("fixtures/vocab.json")
|
||||
SAMPLE_MERGE_FILE = get_tests_dir("fixtures/merges.txt")
|
||||
SAMPLE_ENTITY_VOCAB = get_tests_dir("fixtures/test_entity_vocab.json")
|
||||
|
||||
|
||||
class LukeTokenizerTest(TokenizerTesterMixin, unittest.TestCase):
|
||||
from_pretrained_id = "studio-ousia/luke-base"
|
||||
tokenizer_class = LukeTokenizer
|
||||
test_rust_tokenizer = False
|
||||
from_pretrained_kwargs = {"cls_token": "<s>"}
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
|
||||
cls.special_tokens_map = {"entity_token_1": "<ent>", "entity_token_2": "<ent2>"}
|
||||
|
||||
@classmethod
|
||||
def get_tokenizer(cls, task=None, **kwargs):
|
||||
kwargs.update(cls.special_tokens_map)
|
||||
tokenizer = LukeTokenizer(
|
||||
vocab_file=SAMPLE_VOCAB,
|
||||
merges_file=SAMPLE_MERGE_FILE,
|
||||
entity_vocab_file=SAMPLE_ENTITY_VOCAB,
|
||||
task=task,
|
||||
**kwargs,
|
||||
)
|
||||
return tokenizer
|
||||
|
||||
def get_input_output_texts(self, tokenizer):
|
||||
input_text = "lower newer"
|
||||
output_text = "lower newer"
|
||||
return input_text, output_text
|
||||
|
||||
def test_full_tokenizer(self):
|
||||
tokenizer = self.get_tokenizer()
|
||||
text = "lower newer"
|
||||
bpe_tokens = ["l", "o", "w", "er", "Ġ", "n", "e", "w", "er"]
|
||||
tokens = tokenizer.tokenize(text) # , add_prefix_space=True)
|
||||
self.assertListEqual(tokens, bpe_tokens)
|
||||
|
||||
input_tokens = tokens + [tokenizer.unk_token]
|
||||
input_bpe_tokens = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
|
||||
self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), input_bpe_tokens)
|
||||
|
||||
@slow
|
||||
def test_sequence_builders(self):
|
||||
tokenizer = self.tokenizer_class.from_pretrained("studio-ousia/luke-large")
|
||||
|
||||
text = tokenizer.encode("sequence builders", add_special_tokens=False)
|
||||
text_2 = tokenizer.encode("multi-sequence build", add_special_tokens=False)
|
||||
|
||||
encoded_text_from_decode = tokenizer.encode(
|
||||
"sequence builders", add_special_tokens=True, add_prefix_space=False
|
||||
)
|
||||
encoded_pair_from_decode = tokenizer.encode(
|
||||
"sequence builders", "multi-sequence build", add_special_tokens=True, add_prefix_space=False
|
||||
)
|
||||
|
||||
encoded_sentence = tokenizer.build_inputs_with_special_tokens(text)
|
||||
encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2)
|
||||
|
||||
self.assertEqual(encoded_sentence, encoded_text_from_decode)
|
||||
self.assertEqual(encoded_pair, encoded_pair_from_decode)
|
||||
|
||||
def get_clean_sequence(self, tokenizer, max_length=20) -> tuple[str, list]:
|
||||
txt = "Beyonce lives in Los Angeles"
|
||||
ids = tokenizer.encode(txt, add_special_tokens=False)
|
||||
return txt, ids
|
||||
|
||||
def test_space_encoding(self):
|
||||
tokenizer = self.get_tokenizer()
|
||||
|
||||
sequence = "Encode this sequence."
|
||||
space_encoding = tokenizer.byte_encoder[b" "[0]]
|
||||
|
||||
# Testing encoder arguments
|
||||
encoded = tokenizer.encode(sequence, add_special_tokens=False, add_prefix_space=False)
|
||||
first_char = tokenizer.convert_ids_to_tokens(encoded[0])[0]
|
||||
self.assertNotEqual(first_char, space_encoding)
|
||||
|
||||
encoded = tokenizer.encode(sequence, add_special_tokens=False, add_prefix_space=True)
|
||||
first_char = tokenizer.convert_ids_to_tokens(encoded[0])[0]
|
||||
self.assertEqual(first_char, space_encoding)
|
||||
|
||||
tokenizer.add_special_tokens({"bos_token": "<s>"})
|
||||
encoded = tokenizer.encode(sequence, add_special_tokens=True)
|
||||
first_char = tokenizer.convert_ids_to_tokens(encoded[1])[0]
|
||||
self.assertNotEqual(first_char, space_encoding)
|
||||
|
||||
# Testing spaces after special tokens
|
||||
mask = "<mask>"
|
||||
tokenizer.add_special_tokens(
|
||||
{"mask_token": AddedToken(mask, lstrip=True, rstrip=False)}
|
||||
) # mask token has a left space
|
||||
mask_ind = tokenizer.convert_tokens_to_ids(mask)
|
||||
|
||||
sequence = "Encode <mask> sequence"
|
||||
sequence_nospace = "Encode <mask>sequence"
|
||||
|
||||
encoded = tokenizer.encode(sequence)
|
||||
mask_loc = encoded.index(mask_ind)
|
||||
first_char = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1])[0]
|
||||
self.assertEqual(first_char, space_encoding)
|
||||
|
||||
encoded = tokenizer.encode(sequence_nospace)
|
||||
mask_loc = encoded.index(mask_ind)
|
||||
first_char = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1])[0]
|
||||
self.assertNotEqual(first_char, space_encoding)
|
||||
|
||||
@unittest.skip
|
||||
def test_pretokenized_inputs(self):
|
||||
pass
|
||||
|
||||
def test_embedded_special_tokens(self):
|
||||
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
|
||||
with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
|
||||
tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs)
|
||||
tokenizer_p = self.get_tokenizer(pretrained_name, **kwargs)
|
||||
sentence = "A, <mask> AllenNLP sentence."
|
||||
tokens_r = tokenizer_r.encode_plus(sentence, add_special_tokens=True, return_token_type_ids=True)
|
||||
tokens_p = tokenizer_p.encode_plus(sentence, add_special_tokens=True, return_token_type_ids=True)
|
||||
|
||||
# token_type_ids should put 0 everywhere
|
||||
self.assertEqual(sum(tokens_r["token_type_ids"]), sum(tokens_p["token_type_ids"]))
|
||||
|
||||
# attention_mask should put 1 everywhere, so sum over length should be 1
|
||||
self.assertEqual(
|
||||
sum(tokens_r["attention_mask"]) / len(tokens_r["attention_mask"]),
|
||||
sum(tokens_p["attention_mask"]) / len(tokens_p["attention_mask"]),
|
||||
)
|
||||
|
||||
tokens_p_str = tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"])
|
||||
|
||||
# Rust correctly handles the space before the mask while python doesn't
|
||||
self.assertSequenceEqual(tokens_p["input_ids"], [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2])
|
||||
|
||||
self.assertSequenceEqual(
|
||||
tokens_p_str, ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"]
|
||||
)
|
||||
|
||||
def test_padding_entity_inputs(self):
|
||||
tokenizer = self.get_tokenizer()
|
||||
|
||||
sentence = "Japanese is an East Asian language spoken by about 128 million people, primarily in Japan."
|
||||
span = (15, 34)
|
||||
pad_id = tokenizer.entity_vocab["[PAD]"]
|
||||
mask_id = tokenizer.entity_vocab["[MASK]"]
|
||||
|
||||
encoding = tokenizer([sentence, sentence], entity_spans=[[span], [span, span]], padding=True)
|
||||
self.assertEqual(encoding["entity_ids"], [[mask_id, pad_id], [mask_id, mask_id]])
|
||||
|
||||
# test with a sentence with no entity
|
||||
encoding = tokenizer([sentence, sentence], entity_spans=[[], [span, span]], padding=True)
|
||||
self.assertEqual(encoding["entity_ids"], [[pad_id, pad_id], [mask_id, mask_id]])
|
||||
|
||||
def test_if_tokenize_single_text_raise_error_with_invalid_inputs(self):
|
||||
tokenizer = self.get_tokenizer()
|
||||
|
||||
sentence = "Japanese is an East Asian language spoken by about 128 million people, primarily in Japan."
|
||||
spans = [(15, 34)]
|
||||
entities = ["East Asian language"]
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
tokenizer(sentence, entities=tuple(entities), entity_spans=spans)
|
||||
|
||||
with self.assertRaises(TypeError):
|
||||
tokenizer(sentence, entities=entities, entity_spans=tuple(spans))
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
tokenizer(sentence, entities=[0], entity_spans=spans)
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
tokenizer(sentence, entities=entities, entity_spans=[0])
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
tokenizer(sentence, entities=entities, entity_spans=spans + [(0, 9)])
|
||||
|
||||
def test_if_tokenize_entity_classification_raise_error_with_invalid_inputs(self):
|
||||
tokenizer = self.get_tokenizer(task="entity_classification")
|
||||
|
||||
sentence = "Japanese is an East Asian language spoken by about 128 million people, primarily in Japan."
|
||||
span = (15, 34)
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
tokenizer(sentence, entity_spans=[])
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
tokenizer(sentence, entity_spans=[span, span])
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
tokenizer(sentence, entity_spans=[0])
|
||||
|
||||
def test_if_tokenize_entity_pair_classification_raise_error_with_invalid_inputs(self):
|
||||
tokenizer = self.get_tokenizer(task="entity_pair_classification")
|
||||
|
||||
sentence = "Japanese is an East Asian language spoken by about 128 million people, primarily in Japan."
|
||||
# head and tail information
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
tokenizer(sentence, entity_spans=[])
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
tokenizer(sentence, entity_spans=[0, 0])
|
||||
|
||||
def test_if_tokenize_entity_span_classification_raise_error_with_invalid_inputs(self):
|
||||
tokenizer = self.get_tokenizer(task="entity_span_classification")
|
||||
|
||||
sentence = "Japanese is an East Asian language spoken by about 128 million people, primarily in Japan."
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
tokenizer(sentence, entity_spans=[])
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
tokenizer(sentence, entity_spans=[0, 0, 0])
|
||||
|
||||
|
||||
@slow
|
||||
@require_torch
|
||||
class LukeTokenizerIntegrationTests(unittest.TestCase):
|
||||
tokenizer_class = LukeTokenizer
|
||||
from_pretrained_kwargs = {"cls_token": "<s>"}
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
|
||||
def test_single_text_no_padding_or_truncation(self):
|
||||
tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-base", return_token_type_ids=True)
|
||||
sentence = "Top seed Ana Ivanovic said on Thursday she could hardly believe her luck."
|
||||
entities = ["Ana Ivanovic", "Thursday", "Dummy Entity"]
|
||||
spans = [(9, 21), (30, 38), (39, 42)]
|
||||
|
||||
encoding = tokenizer(sentence, entities=entities, entity_spans=spans, return_token_type_ids=True)
|
||||
|
||||
self.assertEqual(
|
||||
tokenizer.decode(encoding["input_ids"], spaces_between_special_tokens=False),
|
||||
"<s>Top seed Ana Ivanovic said on Thursday she could hardly believe her luck.</s>",
|
||||
)
|
||||
self.assertEqual(
|
||||
tokenizer.decode(encoding["input_ids"][3:6], spaces_between_special_tokens=False), " Ana Ivanovic"
|
||||
)
|
||||
self.assertEqual(
|
||||
tokenizer.decode(encoding["input_ids"][8:9], spaces_between_special_tokens=False), " Thursday"
|
||||
)
|
||||
self.assertEqual(tokenizer.decode(encoding["input_ids"][9:10], spaces_between_special_tokens=False), " she")
|
||||
|
||||
self.assertEqual(
|
||||
encoding["entity_ids"],
|
||||
[
|
||||
tokenizer.entity_vocab["Ana Ivanovic"],
|
||||
tokenizer.entity_vocab["Thursday"],
|
||||
tokenizer.entity_vocab["[UNK]"],
|
||||
],
|
||||
)
|
||||
self.assertEqual(encoding["entity_attention_mask"], [1, 1, 1])
|
||||
self.assertEqual(encoding["entity_token_type_ids"], [0, 0, 0])
|
||||
# fmt: off
|
||||
self.assertEqual(
|
||||
encoding["entity_position_ids"],
|
||||
[
|
||||
[3, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
|
||||
[8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
|
||||
[9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
|
||||
]
|
||||
)
|
||||
# fmt: on
|
||||
|
||||
def test_single_text_only_entity_spans_no_padding_or_truncation(self):
|
||||
tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-base", return_token_type_ids=True)
|
||||
sentence = "Top seed Ana Ivanovic said on Thursday she could hardly believe her luck."
|
||||
spans = [(9, 21), (30, 38), (39, 42)]
|
||||
|
||||
encoding = tokenizer(sentence, entity_spans=spans, return_token_type_ids=True)
|
||||
|
||||
self.assertEqual(
|
||||
tokenizer.decode(encoding["input_ids"], spaces_between_special_tokens=False),
|
||||
"<s>Top seed Ana Ivanovic said on Thursday she could hardly believe her luck.</s>",
|
||||
)
|
||||
self.assertEqual(
|
||||
tokenizer.decode(encoding["input_ids"][3:6], spaces_between_special_tokens=False), " Ana Ivanovic"
|
||||
)
|
||||
self.assertEqual(
|
||||
tokenizer.decode(encoding["input_ids"][8:9], spaces_between_special_tokens=False), " Thursday"
|
||||
)
|
||||
self.assertEqual(tokenizer.decode(encoding["input_ids"][9:10], spaces_between_special_tokens=False), " she")
|
||||
|
||||
mask_id = tokenizer.entity_vocab["[MASK]"]
|
||||
self.assertEqual(encoding["entity_ids"], [mask_id, mask_id, mask_id])
|
||||
self.assertEqual(encoding["entity_attention_mask"], [1, 1, 1])
|
||||
self.assertEqual(encoding["entity_token_type_ids"], [0, 0, 0])
|
||||
# fmt: off
|
||||
self.assertEqual(
|
||||
encoding["entity_position_ids"],
|
||||
[
|
||||
[3, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
|
||||
[8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ],
|
||||
[9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ]
|
||||
]
|
||||
)
|
||||
# fmt: on
|
||||
|
||||
def test_single_text_padding_pytorch_tensors(self):
|
||||
tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-base", return_token_type_ids=True)
|
||||
sentence = "Top seed Ana Ivanovic said on Thursday she could hardly believe her luck."
|
||||
entities = ["Ana Ivanovic", "Thursday", "Dummy Entity"]
|
||||
spans = [(9, 21), (30, 38), (39, 42)]
|
||||
|
||||
encoding = tokenizer(
|
||||
sentence,
|
||||
entities=entities,
|
||||
entity_spans=spans,
|
||||
return_token_type_ids=True,
|
||||
padding="max_length",
|
||||
max_length=30,
|
||||
max_entity_length=16,
|
||||
return_tensors="pt",
|
||||
)
|
||||
|
||||
# test words
|
||||
self.assertEqual(encoding["input_ids"].shape, (1, 30))
|
||||
self.assertEqual(encoding["attention_mask"].shape, (1, 30))
|
||||
self.assertEqual(encoding["token_type_ids"].shape, (1, 30))
|
||||
|
||||
# test entities
|
||||
self.assertEqual(encoding["entity_ids"].shape, (1, 16))
|
||||
self.assertEqual(encoding["entity_attention_mask"].shape, (1, 16))
|
||||
self.assertEqual(encoding["entity_token_type_ids"].shape, (1, 16))
|
||||
self.assertEqual(encoding["entity_position_ids"].shape, (1, 16, tokenizer.max_mention_length))
|
||||
|
||||
def test_text_pair_no_padding_or_truncation(self):
|
||||
tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-base", return_token_type_ids=True)
|
||||
sentence = "Top seed Ana Ivanovic said on Thursday"
|
||||
sentence_pair = "She could hardly believe her luck."
|
||||
entities = ["Ana Ivanovic", "Thursday"]
|
||||
entities_pair = ["Dummy Entity"]
|
||||
spans = [(9, 21), (30, 38)]
|
||||
spans_pair = [(0, 3)]
|
||||
|
||||
encoding = tokenizer(
|
||||
sentence,
|
||||
sentence_pair,
|
||||
entities=entities,
|
||||
entities_pair=entities_pair,
|
||||
entity_spans=spans,
|
||||
entity_spans_pair=spans_pair,
|
||||
return_token_type_ids=True,
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
tokenizer.decode(encoding["input_ids"], spaces_between_special_tokens=False),
|
||||
"<s>Top seed Ana Ivanovic said on Thursday</s></s>She could hardly believe her luck.</s>",
|
||||
)
|
||||
self.assertEqual(
|
||||
tokenizer.decode(encoding["input_ids"][3:6], spaces_between_special_tokens=False), " Ana Ivanovic"
|
||||
)
|
||||
self.assertEqual(
|
||||
tokenizer.decode(encoding["input_ids"][8:9], spaces_between_special_tokens=False), " Thursday"
|
||||
)
|
||||
self.assertEqual(tokenizer.decode(encoding["input_ids"][11:12], spaces_between_special_tokens=False), "She")
|
||||
|
||||
self.assertEqual(
|
||||
encoding["entity_ids"],
|
||||
[
|
||||
tokenizer.entity_vocab["Ana Ivanovic"],
|
||||
tokenizer.entity_vocab["Thursday"],
|
||||
tokenizer.entity_vocab["[UNK]"],
|
||||
],
|
||||
)
|
||||
self.assertEqual(encoding["entity_attention_mask"], [1, 1, 1])
|
||||
self.assertEqual(encoding["entity_token_type_ids"], [0, 0, 0])
|
||||
# fmt: off
|
||||
self.assertEqual(
|
||||
encoding["entity_position_ids"],
|
||||
[
|
||||
[3, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
|
||||
[8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
|
||||
[11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
|
||||
]
|
||||
)
|
||||
# fmt: on
|
||||
|
||||
def test_text_pair_only_entity_spans_no_padding_or_truncation(self):
|
||||
tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-base", return_token_type_ids=True)
|
||||
sentence = "Top seed Ana Ivanovic said on Thursday"
|
||||
sentence_pair = "She could hardly believe her luck."
|
||||
spans = [(9, 21), (30, 38)]
|
||||
spans_pair = [(0, 3)]
|
||||
|
||||
encoding = tokenizer(
|
||||
sentence,
|
||||
sentence_pair,
|
||||
entity_spans=spans,
|
||||
entity_spans_pair=spans_pair,
|
||||
return_token_type_ids=True,
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
tokenizer.decode(encoding["input_ids"], spaces_between_special_tokens=False),
|
||||
"<s>Top seed Ana Ivanovic said on Thursday</s></s>She could hardly believe her luck.</s>",
|
||||
)
|
||||
self.assertEqual(
|
||||
tokenizer.decode(encoding["input_ids"][3:6], spaces_between_special_tokens=False), " Ana Ivanovic"
|
||||
)
|
||||
self.assertEqual(
|
||||
tokenizer.decode(encoding["input_ids"][8:9], spaces_between_special_tokens=False), " Thursday"
|
||||
)
|
||||
self.assertEqual(tokenizer.decode(encoding["input_ids"][11:12], spaces_between_special_tokens=False), "She")
|
||||
|
||||
mask_id = tokenizer.entity_vocab["[MASK]"]
|
||||
self.assertEqual(encoding["entity_ids"], [mask_id, mask_id, mask_id])
|
||||
self.assertEqual(encoding["entity_attention_mask"], [1, 1, 1])
|
||||
self.assertEqual(encoding["entity_token_type_ids"], [0, 0, 0])
|
||||
# fmt: off
|
||||
self.assertEqual(
|
||||
encoding["entity_position_ids"],
|
||||
[
|
||||
[3, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
|
||||
[8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
|
||||
[11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
|
||||
]
|
||||
)
|
||||
# fmt: on
|
||||
|
||||
def test_text_pair_padding_pytorch_tensors(self):
|
||||
tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-base", return_token_type_ids=True)
|
||||
sentence = "Top seed Ana Ivanovic said on Thursday"
|
||||
sentence_pair = "She could hardly believe her luck."
|
||||
entities = ["Ana Ivanovic", "Thursday"]
|
||||
entities_pair = ["Dummy Entity"]
|
||||
spans = [(9, 21), (30, 38)]
|
||||
spans_pair = [(0, 3)]
|
||||
|
||||
encoding = tokenizer(
|
||||
sentence,
|
||||
sentence_pair,
|
||||
entities=entities,
|
||||
entities_pair=entities_pair,
|
||||
entity_spans=spans,
|
||||
entity_spans_pair=spans_pair,
|
||||
return_token_type_ids=True,
|
||||
padding="max_length",
|
||||
max_length=30,
|
||||
max_entity_length=16,
|
||||
return_tensors="pt",
|
||||
)
|
||||
|
||||
# test words
|
||||
self.assertEqual(encoding["input_ids"].shape, (1, 30))
|
||||
self.assertEqual(encoding["attention_mask"].shape, (1, 30))
|
||||
self.assertEqual(encoding["token_type_ids"].shape, (1, 30))
|
||||
|
||||
# test entities
|
||||
self.assertEqual(encoding["entity_ids"].shape, (1, 16))
|
||||
self.assertEqual(encoding["entity_attention_mask"].shape, (1, 16))
|
||||
self.assertEqual(encoding["entity_token_type_ids"].shape, (1, 16))
|
||||
self.assertEqual(encoding["entity_position_ids"].shape, (1, 16, tokenizer.max_mention_length))
|
||||
|
||||
def test_entity_classification_no_padding_or_truncation(self):
|
||||
tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-base", task="entity_classification")
|
||||
sentence = (
|
||||
"Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped"
|
||||
" the new world number one avoid a humiliating second- round exit at Wimbledon ."
|
||||
)
|
||||
span = (39, 42)
|
||||
|
||||
encoding = tokenizer(sentence, entity_spans=[span], return_token_type_ids=True)
|
||||
|
||||
# test words
|
||||
self.assertEqual(len(encoding["input_ids"]), 42)
|
||||
self.assertEqual(len(encoding["attention_mask"]), 42)
|
||||
self.assertEqual(len(encoding["token_type_ids"]), 42)
|
||||
self.assertEqual(
|
||||
tokenizer.decode(encoding["input_ids"], spaces_between_special_tokens=False),
|
||||
"<s>Top seed Ana Ivanovic said on Thursday<ent> she<ent> could hardly believe her luck as a fortuitous"
|
||||
" netcord helped the new world number one avoid a humiliating second- round exit at Wimbledon.</s>",
|
||||
)
|
||||
self.assertEqual(
|
||||
tokenizer.decode(encoding["input_ids"][9:12], spaces_between_special_tokens=False), "<ent> she<ent>"
|
||||
)
|
||||
|
||||
# test entities
|
||||
self.assertEqual(encoding["entity_ids"], [2])
|
||||
self.assertEqual(encoding["entity_attention_mask"], [1])
|
||||
self.assertEqual(encoding["entity_token_type_ids"], [0])
|
||||
# fmt: off
|
||||
self.assertEqual(
|
||||
encoding["entity_position_ids"],
|
||||
[
|
||||
[9, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
|
||||
]
|
||||
)
|
||||
# fmt: on
|
||||
|
||||
def test_entity_classification_padding_pytorch_tensors(self):
|
||||
tokenizer = LukeTokenizer.from_pretrained(
|
||||
"studio-ousia/luke-base", task="entity_classification", return_token_type_ids=True
|
||||
)
|
||||
sentence = (
|
||||
"Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped"
|
||||
" the new world number one avoid a humiliating second- round exit at Wimbledon ."
|
||||
)
|
||||
# entity information
|
||||
span = (39, 42)
|
||||
|
||||
encoding = tokenizer(
|
||||
sentence, entity_spans=[span], return_token_type_ids=True, padding="max_length", return_tensors="pt"
|
||||
)
|
||||
|
||||
# test words
|
||||
self.assertEqual(encoding["input_ids"].shape, (1, 512))
|
||||
self.assertEqual(encoding["attention_mask"].shape, (1, 512))
|
||||
self.assertEqual(encoding["token_type_ids"].shape, (1, 512))
|
||||
|
||||
# test entities
|
||||
self.assertEqual(encoding["entity_ids"].shape, (1, 1))
|
||||
self.assertEqual(encoding["entity_attention_mask"].shape, (1, 1))
|
||||
self.assertEqual(encoding["entity_token_type_ids"].shape, (1, 1))
|
||||
self.assertEqual(
|
||||
encoding["entity_position_ids"].shape, (1, tokenizer.max_entity_length, tokenizer.max_mention_length)
|
||||
)
|
||||
|
||||
def test_entity_pair_classification_no_padding_or_truncation(self):
|
||||
tokenizer = LukeTokenizer.from_pretrained(
|
||||
"studio-ousia/luke-base", task="entity_pair_classification", return_token_type_ids=True
|
||||
)
|
||||
sentence = "Top seed Ana Ivanovic said on Thursday she could hardly believe her luck."
|
||||
# head and tail information
|
||||
spans = [(9, 21), (39, 42)]
|
||||
|
||||
encoding = tokenizer(sentence, entity_spans=spans, return_token_type_ids=True)
|
||||
|
||||
self.assertEqual(
|
||||
tokenizer.decode(encoding["input_ids"], spaces_between_special_tokens=False),
|
||||
"<s>Top seed<ent> Ana Ivanovic<ent> said on Thursday<ent2> she<ent2> could hardly believe her luck.</s>",
|
||||
)
|
||||
self.assertEqual(
|
||||
tokenizer.decode(encoding["input_ids"][3:8], spaces_between_special_tokens=False),
|
||||
"<ent> Ana Ivanovic<ent>",
|
||||
)
|
||||
self.assertEqual(
|
||||
tokenizer.decode(encoding["input_ids"][11:14], spaces_between_special_tokens=False), "<ent2> she<ent2>"
|
||||
)
|
||||
|
||||
self.assertEqual(encoding["entity_ids"], [2, 3])
|
||||
self.assertEqual(encoding["entity_attention_mask"], [1, 1])
|
||||
self.assertEqual(encoding["entity_token_type_ids"], [0, 0])
|
||||
# fmt: off
|
||||
self.assertEqual(
|
||||
encoding["entity_position_ids"],
|
||||
[
|
||||
[3, 4, 5, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
|
||||
[11, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
|
||||
]
|
||||
)
|
||||
# fmt: on
|
||||
|
||||
def test_entity_pair_classification_padding_pytorch_tensors(self):
|
||||
tokenizer = LukeTokenizer.from_pretrained(
|
||||
"studio-ousia/luke-base", task="entity_pair_classification", return_token_type_ids=True
|
||||
)
|
||||
sentence = "Top seed Ana Ivanovic said on Thursday she could hardly believe her luck."
|
||||
# head and tail information
|
||||
spans = [(9, 21), (39, 42)]
|
||||
|
||||
encoding = tokenizer(
|
||||
sentence,
|
||||
entity_spans=spans,
|
||||
return_token_type_ids=True,
|
||||
padding="max_length",
|
||||
max_length=30,
|
||||
return_tensors="pt",
|
||||
)
|
||||
|
||||
# test words
|
||||
self.assertEqual(encoding["input_ids"].shape, (1, 30))
|
||||
self.assertEqual(encoding["attention_mask"].shape, (1, 30))
|
||||
self.assertEqual(encoding["token_type_ids"].shape, (1, 30))
|
||||
|
||||
# test entities
|
||||
self.assertEqual(encoding["entity_ids"].shape, (1, 2))
|
||||
self.assertEqual(encoding["entity_attention_mask"].shape, (1, 2))
|
||||
self.assertEqual(encoding["entity_token_type_ids"].shape, (1, 2))
|
||||
self.assertEqual(
|
||||
encoding["entity_position_ids"].shape, (1, tokenizer.max_entity_length, tokenizer.max_mention_length)
|
||||
)
|
||||
|
||||
def test_entity_span_classification_no_padding_or_truncation(self):
|
||||
tokenizer = LukeTokenizer.from_pretrained(
|
||||
"studio-ousia/luke-base", task="entity_span_classification", return_token_type_ids=True
|
||||
)
|
||||
sentence = "Top seed Ana Ivanovic said on Thursday she could hardly believe her luck."
|
||||
spans = [(0, 8), (9, 21), (39, 42)]
|
||||
|
||||
encoding = tokenizer(sentence, entity_spans=spans, return_token_type_ids=True)
|
||||
|
||||
self.assertEqual(
|
||||
tokenizer.decode(encoding["input_ids"], spaces_between_special_tokens=False),
|
||||
"<s>Top seed Ana Ivanovic said on Thursday she could hardly believe her luck.</s>",
|
||||
)
|
||||
|
||||
self.assertEqual(encoding["entity_ids"], [2, 2, 2])
|
||||
self.assertEqual(encoding["entity_attention_mask"], [1, 1, 1])
|
||||
self.assertEqual(encoding["entity_token_type_ids"], [0, 0, 0])
|
||||
# fmt: off
|
||||
self.assertEqual(
|
||||
encoding["entity_position_ids"],
|
||||
[
|
||||
[1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
|
||||
[3, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
|
||||
[9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
|
||||
]
|
||||
)
|
||||
# fmt: on
|
||||
self.assertEqual(encoding["entity_start_positions"], [1, 3, 9])
|
||||
self.assertEqual(encoding["entity_end_positions"], [2, 5, 9])
|
||||
|
||||
def test_entity_span_classification_padding_pytorch_tensors(self):
|
||||
tokenizer = LukeTokenizer.from_pretrained(
|
||||
"studio-ousia/luke-base", task="entity_span_classification", return_token_type_ids=True
|
||||
)
|
||||
sentence = "Top seed Ana Ivanovic said on Thursday she could hardly believe her luck."
|
||||
spans = [(0, 8), (9, 21), (39, 42)]
|
||||
|
||||
encoding = tokenizer(
|
||||
sentence,
|
||||
entity_spans=spans,
|
||||
return_token_type_ids=True,
|
||||
padding="max_length",
|
||||
max_length=30,
|
||||
max_entity_length=16,
|
||||
return_tensors="pt",
|
||||
)
|
||||
|
||||
# test words
|
||||
self.assertEqual(encoding["input_ids"].shape, (1, 30))
|
||||
self.assertEqual(encoding["attention_mask"].shape, (1, 30))
|
||||
self.assertEqual(encoding["token_type_ids"].shape, (1, 30))
|
||||
|
||||
# test entities
|
||||
self.assertEqual(encoding["entity_ids"].shape, (1, 16))
|
||||
self.assertEqual(encoding["entity_attention_mask"].shape, (1, 16))
|
||||
self.assertEqual(encoding["entity_token_type_ids"].shape, (1, 16))
|
||||
self.assertEqual(encoding["entity_position_ids"].shape, (1, 16, tokenizer.max_mention_length))
|
||||
self.assertEqual(encoding["entity_start_positions"].shape, (1, 16))
|
||||
self.assertEqual(encoding["entity_end_positions"].shape, (1, 16))
|
||||
Reference in New Issue
Block a user