Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Port sentence_embeddings_with_sbert to Keras 3 #1647

Merged
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
76 changes: 40 additions & 36 deletions examples/nlp/ipynb/sentence_embeddings_with_sbert.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
"Let's install and import the libraries we need. We'll be using the KerasNLP library in\n",
"this example.\n",
"\n",
"We will also enable [mixed perceciosn](https://www.tensorflow.org/guide/mixed_precision)\n",
"We will also enable [mixed precision](https://www.tensorflow.org/guide/mixed_precision)\n",
"training. This will help us reduce the training time."
]
},
Expand All @@ -76,7 +76,8 @@
},
"outputs": [],
"source": [
"!pip install keras-nlp -q"
"!pip install -q --upgrade keras-nlp\n",
"!pip install -q --upgrade keras # Upgrade to Keras 3."
]
},
{
Expand All @@ -87,15 +88,17 @@
},
"outputs": [],
"source": [
"import os\n",
"\n",
"os.environ[\"KERAS_BACKEND\"] = \"tensorflow\"\n",
"\n",
"import keras\n",
"import keras_nlp\n",
"import tensorflow as tf\n",
"import tensorflow_datasets as tfds\n",
"import sklearn.cluster as cluster\n",
"\n",
"from tensorflow import keras\n",
"\n",
"policy = keras.mixed_precision.Policy(\"mixed_float16\")\n",
"keras.mixed_precision.set_global_policy(policy)"
"keras.mixed_precision.set_global_policy(\"mixed_float16\")"
]
},
{
Expand Down Expand Up @@ -166,8 +169,8 @@
"TRAIN_BATCH_SIZE = 6\n",
"VALIDATION_BATCH_SIZE = 8\n",
"\n",
"TRAIN_NUM_BATCHS = 300\n",
"VALIDATION_NUM_BATCHS = 40\n",
"TRAIN_NUM_BATCHES = 300\n",
"VALIDATION_NUM_BATCHES = 40\n",
"\n",
"AUTOTUNE = tf.data.experimental.AUTOTUNE\n",
"\n",
Expand All @@ -176,7 +179,7 @@
" return (x / 2.5) - 1\n",
"\n",
"\n",
"def prepare_dataset(dataset, num_batchs, batch_size):\n",
"def prepare_dataset(dataset, num_batches, batch_size):\n",
" dataset = dataset.map(\n",
" lambda z: (\n",
" [z[\"sentence1\"], z[\"sentence2\"]],\n",
Expand All @@ -185,7 +188,7 @@
" num_parallel_calls=AUTOTUNE,\n",
" )\n",
" dataset = dataset.batch(batch_size)\n",
" dataset = dataset.take(num_batchs)\n",
" dataset = dataset.take(num_batches)\n",
" dataset = dataset.prefetch(AUTOTUNE)\n",
" return dataset\n",
"\n",
Expand All @@ -195,8 +198,8 @@
")\n",
"stsb_train, stsb_valid = stsb_ds[\"train\"], stsb_ds[\"validation\"]\n",
"\n",
"stsb_train = prepare_dataset(stsb_train, TRAIN_NUM_BATCHS, TRAIN_BATCH_SIZE)\n",
"stsb_valid = prepare_dataset(stsb_valid, VALIDATION_NUM_BATCHS, VALIDATION_BATCH_SIZE)"
"stsb_train = prepare_dataset(stsb_train, TRAIN_NUM_BATCHES, TRAIN_BATCH_SIZE)\n",
"stsb_valid = prepare_dataset(stsb_valid, VALIDATION_NUM_BATCHES, VALIDATION_BATCH_SIZE)"
]
},
{
Expand Down Expand Up @@ -254,13 +257,13 @@
"source": [
"preprocessor = keras_nlp.models.RobertaPreprocessor.from_preset(\"roberta_base_en\")\n",
"backbone = keras_nlp.models.RobertaBackbone.from_preset(\"roberta_base_en\")\n",
"inputs = keras.Input(shape=(1), dtype=\"string\", name=\"sentence\")\n",
"inputs = keras.Input(shape=(1,), dtype=\"string\", name=\"sentence\")\n",
"x = preprocessor(inputs)\n",
"h = backbone(x)\n",
"embedding = keras.layers.GlobalAveragePooling1D(name=\"pooling_layer\")(\n",
" h, x[\"padding_mask\"]\n",
")\n",
"n_embedding = tf.linalg.normalize(embedding, axis=1)[0]\n",
"n_embedding = keras.layers.UnitNormalization(axis=1)(embedding)\n",
"roberta_normal_encoder = keras.Model(inputs=inputs, outputs=n_embedding)\n",
"\n",
"roberta_normal_encoder.summary()"
Expand Down Expand Up @@ -295,11 +298,11 @@
"\n",
"class RegressionSiamese(keras.Model):\n",
" def __init__(self, encoder, **kwargs):\n",
" inputs = keras.Input(shape=(2), dtype=\"string\", name=\"sentences\")\n",
" sen1, sen2 = tf.split(inputs, num_or_size_splits=2, axis=1, name=\"split\")\n",
" inputs = keras.Input(shape=(2,), dtype=\"string\", name=\"sentences\")\n",
" sen1, sen2 = keras.ops.split(inputs, 2, axis=1)\n",
" u = encoder(sen1)\n",
" v = encoder(sen2)\n",
" cosine_similarity_scores = tf.matmul(u, tf.transpose(v))\n",
" cosine_similarity_scores = keras.ops.matmul(u, keras.ops.transpose(v))\n",
"\n",
" super().__init__(\n",
" inputs=inputs,\n",
Expand Down Expand Up @@ -373,6 +376,7 @@
"roberta_regression_siamese.compile(\n",
" loss=keras.losses.MeanSquaredError(),\n",
" optimizer=keras.optimizers.Adam(2e-5),\n",
" jit_compile=False,\n",
")\n",
"\n",
"roberta_regression_siamese.fit(stsb_train, validation_data=stsb_valid, epochs=1)"
Expand Down Expand Up @@ -468,17 +472,17 @@
},
"outputs": [],
"source": [
"NUM_TRAIN_BATCHS = 200\n",
"NUM_TEST_BATCHS = 75\n",
"NUM_TRAIN_BATCHES = 200\n",
"NUM_TEST_BATCHES = 75\n",
"AUTOTUNE = tf.data.experimental.AUTOTUNE\n",
"\n",
"\n",
"def prepare_wiki_data(dataset, num_batchs):\n",
"def prepare_wiki_data(dataset, num_batches):\n",
" dataset = dataset.map(\n",
" lambda z: ((z[\"Sentence1\"], z[\"Sentence2\"], z[\"Sentence3\"]), 0)\n",
" )\n",
" dataset = dataset.batch(6)\n",
" dataset = dataset.take(num_batchs)\n",
" dataset = dataset.take(num_batches)\n",
" dataset = dataset.prefetch(AUTOTUNE)\n",
" return dataset\n",
"\n",
Expand All @@ -494,8 +498,8 @@
" num_epochs=1,\n",
")\n",
"\n",
"wiki_train = prepare_wiki_data(wiki_train, NUM_TRAIN_BATCHS)\n",
"wiki_test = prepare_wiki_data(wiki_test, NUM_TEST_BATCHS)"
"wiki_train = prepare_wiki_data(wiki_train, NUM_TRAIN_BATCHES)\n",
"wiki_test = prepare_wiki_data(wiki_test, NUM_TEST_BATCHES)"
]
},
{
Expand Down Expand Up @@ -525,7 +529,7 @@
"source": [
"preprocessor = keras_nlp.models.RobertaPreprocessor.from_preset(\"roberta_base_en\")\n",
"backbone = keras_nlp.models.RobertaBackbone.from_preset(\"roberta_base_en\")\n",
"input = keras.Input(shape=(1), dtype=\"string\", name=\"sentence\")\n",
"input = keras.Input(shape=(1,), dtype=\"string\", name=\"sentence\")\n",
"\n",
"x = preprocessor(input)\n",
"h = backbone(x)\n",
Expand Down Expand Up @@ -564,22 +568,21 @@
"\n",
"class TripletSiamese(keras.Model):\n",
" def __init__(self, encoder, **kwargs):\n",
"\n",
" anchor = keras.Input(shape=(1), dtype=\"string\")\n",
" positive = keras.Input(shape=(1), dtype=\"string\")\n",
" negative = keras.Input(shape=(1), dtype=\"string\")\n",
" anchor = keras.Input(shape=(1,), dtype=\"string\")\n",
" positive = keras.Input(shape=(1,), dtype=\"string\")\n",
" negative = keras.Input(shape=(1,), dtype=\"string\")\n",
"\n",
" ea = encoder(anchor)\n",
" ep = encoder(positive)\n",
" en = encoder(negative)\n",
"\n",
" positive_dist = tf.math.reduce_sum(tf.math.pow(ea - ep, 2), axis=1)\n",
" negative_dist = tf.math.reduce_sum(tf.math.pow(ea - en, 2), axis=1)\n",
" positive_dist = keras.ops.sum(keras.ops.square(ea - ep), axis=1)\n",
" negative_dist = keras.ops.sum(keras.ops.square(ea - en), axis=1)\n",
"\n",
" positive_dist = tf.math.sqrt(positive_dist)\n",
" negative_dist = tf.math.sqrt(negative_dist)\n",
" positive_dist = keras.ops.sqrt(positive_dist)\n",
" negative_dist = keras.ops.sqrt(negative_dist)\n",
"\n",
" output = tf.stack([positive_dist, negative_dist], axis=0)\n",
" output = keras.ops.stack([positive_dist, negative_dist], axis=0)\n",
"\n",
" super().__init__(inputs=[anchor, positive, negative], outputs=output, **kwargs)\n",
"\n",
Expand Down Expand Up @@ -627,8 +630,8 @@
" def call(self, y_true, y_pred):\n",
" positive_dist, negative_dist = tf.unstack(y_pred, axis=0)\n",
"\n",
" losses = tf.nn.relu(positive_dist - negative_dist + self.margin)\n",
" return tf.math.reduce_mean(losses, axis=0)\n",
" losses = keras.ops.relu(positive_dist - negative_dist + self.margin)\n",
" return keras.ops.mean(losses, axis=0)\n",
""
]
},
Expand Down Expand Up @@ -657,6 +660,7 @@
"roberta_triplet_siamese.compile(\n",
" loss=TripletLoss(),\n",
" optimizer=keras.optimizers.Adam(2e-5),\n",
" jit_compile=False,\n",
")\n",
"\n",
"roberta_triplet_siamese.fit(wiki_train, validation_data=wiki_test, epochs=1)"
Expand Down Expand Up @@ -687,7 +691,7 @@
" \"How can I improve my English?\",\n",
" \"How to earn money online?\",\n",
" \"How do I earn money online?\",\n",
" \"How to work and ean money through internet?\",\n",
" \"How to work and earn money through internet?\",\n",
"]\n",
"\n",
"encoder = roberta_triplet_siamese.get_encoder()\n",
Expand Down
Loading
Loading