C.W.K.
Stream
Lesson 04 of 07 · published

The call() Method

~9 min · subclass

Level 0Keras Apprentice
0 XP0/97 lessons0/20 achievements
0/120 XP to next level120 XP to go0% complete

call() is the contract

Everything a layer does lives in call(). It takes the input tensor and returns the output tensor, and the signature carries two arguments Keras passes in automatically when they apply:

  • training — a boolean that flips behavior between train and inference. Dropout drops units only when training=True; BatchNormalization uses the current batch's statistics during training but its accumulated moving statistics during inference. If your layer wraps either, you must accept this flag and pass it down.
  • mask — an optional boolean tensor that marks which timesteps are real versus padding, so attention and recurrent layers can ignore the padded positions.

This is where the Python freedom pays off

Because call() is just a method, you can put real control flow inside it — an if training: branch, a loop, a shape-dependent computation. That's the whole reason to subclass instead of using the Functional API (see the Code block). The one discipline that keeps that freedom portable: do your tensor math with keras.ops, never with a backend's native ops. Write keras.ops.relu(x) and the same layer runs on TensorFlow, PyTorch, and JAX unchanged.

Code

A call() with a training-only branch·python
class ConditionalLayer(keras.layers.Layer):
    def call(self, inputs, training=False):
        # Use keras.ops for backend-agnostic code!
        x = keras.ops.relu(inputs)
        if training:
            x = keras.ops.nn.dropout(x, rate=0.5)
        return x

External links

Exercise

Subclass a Layer that applies Dropout(0.5) only during training. Verify by calling layer(x, training=True) vs layer(x, training=False) — outputs should differ vs match the input pattern.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.