Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 32 additions & 38 deletions keras_nlp/models/distil_bert/distil_bert_backbone_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,68 +25,62 @@

class DistilBertTest(tf.test.TestCase, parameterized.TestCase):
def setUp(self):
self.model = DistilBertBackbone(
vocabulary_size=1000,
self.backbone = DistilBertBackbone(
vocabulary_size=10,
num_layers=2,
num_heads=2,
hidden_dim=64,
intermediate_dim=128,
max_sequence_length=128,
hidden_dim=2,
intermediate_dim=4,
max_sequence_length=5,
name="encoder",
)
self.batch_size = 8

self.input_batch = {
"token_ids": tf.ones(
(self.batch_size, self.model.max_sequence_length), dtype="int32"
),
"padding_mask": tf.ones(
(self.batch_size, self.model.max_sequence_length), dtype="int32"
),
"token_ids": tf.ones((2, 5), dtype="int32"),
"padding_mask": tf.ones((2, 5), dtype="int32"),
}

self.input_dataset = tf.data.Dataset.from_tensor_slices(
self.input_batch
).batch(2)

def test_valid_call_distilbert(self):
self.model(self.input_batch)
self.backbone(self.input_batch)

def test_token_embedding(self):
output = self.backbone.token_embedding(self.input_batch["token_ids"])
self.assertEqual(output.shape, (2, 5, 2))

def test_variable_sequence_length_call_distilbert(self):
for seq_length in (25, 50, 75):
for seq_length in (2, 3, 4):
input_data = {
"token_ids": tf.ones(
(self.batch_size, seq_length), dtype="int32"
),
"padding_mask": tf.ones(
(self.batch_size, seq_length), dtype="int32"
),
"token_ids": tf.ones((2, seq_length), dtype="int32"),
"mask_positions": tf.ones((2, seq_length), dtype="int32"),
"padding_mask": tf.ones((2, seq_length), dtype="int32"),
}
self.model(input_data)
self.backbone(input_data)

@parameterized.named_parameters(
("jit_compile_false", False), ("jit_compile_true", True)
)
def test_distilbert_base_compile(self, jit_compile):
self.model.compile(jit_compile=jit_compile)
self.model.predict(self.input_batch)
def test_predict(self):
self.backbone.predict(self.input_batch)
self.backbone.predict(self.input_dataset)

@parameterized.named_parameters(
("jit_compile_false", False), ("jit_compile_true", True)
)
def test_distilbert_base_compile_batched_ds(self, jit_compile):
self.model.compile(jit_compile=jit_compile)
self.model.predict(self.input_dataset)
def test_serialization(self):
new_backbone = keras.utils.deserialize_keras_object(
keras.utils.serialize_keras_object(self.backbone)
)
self.assertEqual(new_backbone.get_config(), self.backbone.get_config())

@parameterized.named_parameters(
("tf_format", "tf", "model"),
("keras_format", "keras_v3", "model.keras"),
)
@pytest.mark.large
def test_saved_model(self, save_format, filename):
model_output = self.model(self.input_batch)
model_output = self.backbone(self.input_batch)
path = os.path.join(self.get_temp_dir(), filename)
# Don't save traces in the tf format, we check compilation elsewhere.
kwargs = {"save_traces": False} if save_format == "tf" else {}
self.model.save(path, save_format=save_format, **kwargs)
self.backbone.save(path, save_format=save_format, **kwargs)
restored_model = keras.models.load_model(path)

# Check we got the real object back.
Expand All @@ -102,7 +96,7 @@ def test_saved_model(self, save_format, filename):
class DistilBertTPUTest(tf.test.TestCase, parameterized.TestCase):
def setUp(self):
with self.tpu_strategy.scope():
self.model = DistilBertBackbone(
self.backbone = DistilBertBackbone(
vocabulary_size=1000,
num_layers=2,
num_heads=2,
Expand All @@ -119,5 +113,5 @@ def setUp(self):
).batch(2)

def test_predict(self):
self.model.compile()
self.model.predict(self.input_dataset)
self.backbone.compile()
self.backbone.predict(self.input_dataset)
69 changes: 26 additions & 43 deletions keras_nlp/models/distil_bert/distil_bert_classifier_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import os

import pytest
import tensorflow as tf
from absl.testing import parameterized
from tensorflow import keras
Expand All @@ -33,30 +34,27 @@

class DistilBertClassifierTest(tf.test.TestCase, parameterized.TestCase):
def setUp(self):
self.backbone = DistilBertBackbone(
vocabulary_size=1000,
num_layers=2,
num_heads=2,
hidden_dim=64,
intermediate_dim=128,
max_sequence_length=128,
)
# Setup model

self.vocab = ["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]"]
self.vocab += ["the", "quick", "brown", "fox", "."]
self.preprocessor = DistilBertPreprocessor(
DistilBertTokenizer(vocabulary=self.vocab),
sequence_length=8,
)
self.backbone = DistilBertBackbone(
vocabulary_size=self.preprocessor.tokenizer.vocabulary_size(),
num_layers=2,
num_heads=2,
hidden_dim=2,
intermediate_dim=4,
max_sequence_length=self.preprocessor.packer.sequence_length,
)
self.classifier = DistilBertClassifier(
self.backbone,
4,
preprocessor=self.preprocessor,
)
self.classifier_no_preprocessing = DistilBertClassifier(
self.backbone,
4,
preprocessor=None,
)

self.raw_batch = tf.constant(
[
Expand All @@ -75,47 +73,32 @@ def setUp(self):
def test_valid_call_classifier(self):
self.classifier(self.preprocessed_batch)

@parameterized.named_parameters(
("jit_compile_false", False), ("jit_compile_true", True)
)
def test_classifier_predict(self, jit_compile):
self.classifier.compile(jit_compile=jit_compile)
def test_classifier_predict(self):
self.classifier.predict(self.raw_batch)
self.classifier.preprocessor = None
self.classifier.predict(self.preprocessed_batch)

@parameterized.named_parameters(
("jit_compile_false", False), ("jit_compile_true", True)
)
def test_classifier_predict_no_preprocessing(self, jit_compile):
self.classifier_no_preprocessing.compile(jit_compile=jit_compile)
self.classifier_no_preprocessing.predict(self.preprocessed_batch)

@parameterized.named_parameters(
("jit_compile_false", False), ("jit_compile_true", True)
)
def test_classifier_fit(self, jit_compile):
self.classifier.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
jit_compile=jit_compile,
)
def test_classifier_fit(self):
self.classifier.fit(self.raw_dataset)

@parameterized.named_parameters(
("jit_compile_false", False), ("jit_compile_true", True)
)
def test_classifier_fit_no_preprocessing(self, jit_compile):
self.classifier_no_preprocessing.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
jit_compile=jit_compile,
)
self.classifier_no_preprocessing.fit(self.preprocessed_dataset)
self.classifier.preprocessor = None
self.classifier.fit(self.preprocessed_dataset)

def test_distilbert_classifier_fit_default_compile(self):
self.classifier.fit(self.raw_dataset)

def test_serialization(self):
config = keras.utils.serialize_keras_object(self.classifier)
new_classifier = keras.utils.deserialize_keras_object(config)
self.assertEqual(
new_classifier.get_config(),
self.classifier.get_config(),
)

@parameterized.named_parameters(
("tf_format", "tf", "model"),
("keras_format", "keras_v3", "model.keras"),
)
@pytest.mark.large
def test_saving_model(self, save_format, filename):
model_output = self.classifier.predict(self.raw_batch)
path = os.path.join(self.get_temp_dir(), filename)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import os

import pytest
import tensorflow as tf
from absl.testing import parameterized
from tensorflow import keras
Expand Down Expand Up @@ -106,10 +107,19 @@ def test_no_masking_zero_rate(self):
self.assertAllEqual(y, [0, 0, 0, 0, 0])
self.assertAllEqual(sw, [0.0, 0.0, 0.0, 0.0, 0.0])

def test_serialization(self):
config = keras.utils.serialize_keras_object(self.preprocessor)
new_preprocessor = keras.utils.deserialize_keras_object(config)
self.assertEqual(
new_preprocessor.get_config(),
self.preprocessor.get_config(),
)

@parameterized.named_parameters(
("tf_format", "tf", "model"),
("keras_format", "keras_v3", "model.keras"),
)
@pytest.mark.large
def test_saved_model(self, save_format, filename):
input_data = tf.constant([" THE QUICK BROWN FOX."])

Expand Down
86 changes: 33 additions & 53 deletions keras_nlp/models/distil_bert/distil_bert_masked_lm_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import os

import pytest
import tensorflow as tf
from absl.testing import parameterized
from tensorflow import keras
Expand All @@ -33,90 +34,70 @@

class DistilBertMaskedLMTest(tf.test.TestCase, parameterized.TestCase):
def setUp(self):
self.backbone = DistilBertBackbone(
vocabulary_size=1000,
num_layers=2,
num_heads=2,
hidden_dim=64,
intermediate_dim=128,
max_sequence_length=128,
)
# Setup model.
self.vocab = ["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]"]
self.vocab += ["THE", "QUICK", "BROWN", "FOX"]
self.vocab += ["the", "quick", "brown", "fox"]
self.vocab += ["the", "quick", "brown", "fox", "."]
self.preprocessor = DistilBertMaskedLMPreprocessor(
DistilBertTokenizer(vocabulary=self.vocab),
sequence_length=8,
sequence_length=5,
mask_selection_length=2,
)
self.backbone = DistilBertBackbone(
vocabulary_size=self.preprocessor.tokenizer.vocabulary_size(),
num_layers=2,
num_heads=2,
hidden_dim=4,
intermediate_dim=4,
max_sequence_length=self.preprocessor.packer.sequence_length,
)
self.masked_lm = DistilBertMaskedLM(
self.backbone,
preprocessor=self.preprocessor,
)
self.masked_lm_no_preprocessing = DistilBertMaskedLM(
self.backbone,
preprocessor=None,
)

self.raw_batch = tf.constant(
[
"the quick brown fox.",
"the slow brown fox.",
"the smelly brown fox.",
"the old brown fox.",
]
)
self.preprocessed_batch = self.preprocessor(self.raw_batch)[0]
self.preprocessed_batch = self.preprocessor(self.raw_batch)
self.raw_dataset = tf.data.Dataset.from_tensor_slices(
self.raw_batch
).batch(2)
self.preprocessed_dataset = self.raw_dataset.map(self.preprocessor)

def test_valid_call_masked_lm(self):
self.masked_lm(self.preprocessed_batch)

@parameterized.named_parameters(
("jit_compile_false", False), ("jit_compile_true", True)
)
def test_distilbert_masked_lm_predict(self, jit_compile):
self.masked_lm.compile(jit_compile=jit_compile)
self.masked_lm.predict(self.raw_batch)

@parameterized.named_parameters(
("jit_compile_false", False), ("jit_compile_true", True)
)
def test_distilbert_masked_lm_predict_no_preprocessing(self, jit_compile):
self.masked_lm_no_preprocessing.compile(jit_compile=jit_compile)
self.masked_lm_no_preprocessing.predict(self.preprocessed_batch)
def test_valid_call_classifier(self):
self.masked_lm(self.preprocessed_batch[0])

def test_distil_bert_masked_lm_fit_default_compile(self):
self.masked_lm.fit(self.raw_dataset)

@parameterized.named_parameters(
("jit_compile_false", False), ("jit_compile_true", True)
)
def test_distilbert_masked_lm_fit(self, jit_compile):
self.masked_lm.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
jit_compile=jit_compile,
)
def test_classifier_predict(self):
self.masked_lm.predict(self.raw_batch)
self.masked_lm.preprocessor = None
self.masked_lm.predict(self.preprocessed_batch[0])

def test_classifier_fit(self):
self.masked_lm.fit(self.raw_dataset)
self.masked_lm.preprocessor = None
self.masked_lm.fit(self.preprocessed_dataset)

@parameterized.named_parameters(
("jit_compile_false", False), ("jit_compile_true", True)
)
def test_distilbert_masked_lm_fit_no_preprocessing(self, jit_compile):
self.masked_lm_no_preprocessing.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
jit_compile=jit_compile,
def test_classifier_fit_no_xla(self):
self.masked_lm.preprocessor = None
self.masked_lm.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=False),
jit_compile=False,
)
self.masked_lm_no_preprocessing.fit(self.preprocessed_dataset)
self.masked_lm.fit(self.preprocessed_dataset)

@parameterized.named_parameters(
("tf_format", "tf", "model"),
("keras_format", "keras_v3", "model.keras"),
)
@pytest.mark.large
def test_saved_model(self, save_format, filename):
model_output = self.masked_lm.predict(self.raw_batch)
path = os.path.join(self.get_temp_dir(), filename)
# Don't save traces in the tf format, we check compilation elsewhere.
kwargs = {"save_traces": False} if save_format == "tf" else {}
Expand All @@ -126,7 +107,6 @@ def test_saved_model(self, save_format, filename):
# Check we got the real object back.
self.assertIsInstance(restored_model, DistilBertMaskedLM)

model_output = self.masked_lm(self.preprocessed_batch)
restored_output = restored_model(self.preprocessed_batch)

# Check that output matches.
restored_output = restored_model.predict(self.raw_batch)
self.assertAllClose(model_output, restored_output, atol=0.01, rtol=0.01)
Loading