| 240 | loss_tracker = tf.keras.metrics.Mean(name="loss") |
| 241 | |
| 242 | class MaskedLanguageModel(tf.keras.Model): |
| 243 | def train_step(self, inputs): |
| 244 | if len(inputs) == 3: |
| 245 | features, labels, sample_weight = inputs |
| 246 | else: |
| 247 | features, labels = inputs |
| 248 | sample_weight = None |
| 249 | |
| 250 | with tf.GradientTape() as tape: |
| 251 | predictions = self(features, training=True) |
| 252 | loss = loss_fn(labels, predictions, sample_weight=sample_weight) |
| 253 | |
| 254 | # Compute gradients |
| 255 | trainable_vars = self.trainable_variables |
| 256 | gradients = tape.gradient(loss, trainable_vars) |
| 257 | |
| 258 | # Update weights |
| 259 | self.optimizer.apply_gradients(zip(gradients, trainable_vars)) |
| 260 | |
| 261 | # Compute our own metrics |
| 262 | loss_tracker.update_state(loss, sample_weight=sample_weight) |
| 263 | |
| 264 | # Return a dict mapping metric names to current value |
| 265 | return {"loss": loss_tracker.result()} |
| 266 | |
| 267 | @property |
| 268 | def metrics(self): |
| 269 | # We list our `Metric` objects here so that `reset_states()` can be |
| 270 | # called automatically at the start of each epoch |
| 271 | # or at the start of `evaluate()`. |
| 272 | # If you don't implement this property, you have to call |
| 273 | # `reset_states()` yourself at the time of your choosing. |
| 274 | return [loss_tracker] |
| 275 | |
| 276 | def create_masked_language_bert_model(): |
| 277 | inputs = layers.Input((config.MAX_LEN,), dtype=tf.int64) |
no outgoing calls
no test coverage detected