Understanding masking & padding

Complete guide to using mask-aware sequence layers in Keras.
Author

Scott Zhu, Francois Chollet

Setup

library(tensorflow)
library(keras)

Introduction

Masking is a way to tell sequence-processing layers that certain timesteps in an input are missing, and thus should be skipped when processing the data.

Padding is a special form of masking where the masked steps are at the start or the end of a sequence. Padding comes from the need to encode sequence data into contiguous batches: in order to make all sequences in a batch fit a given standard length, it is necessary to pad or truncate some sequences.

Let’s take a close look.

Padding sequence data

When processing sequence data, it is very common for individual samples to have different lengths. Consider the following example (text tokenized as words):

list(
  c("Hello", "world", "!"),
  c("How", "are", "you", "doing", "today"),
  c("The", "weather", "will", "be", "nice", "tomorrow")
)
[[1]]
[1] "Hello" "world" "!"    

[[2]]
[1] "How"   "are"   "you"   "doing" "today"

[[3]]
[1] "The"      "weather"  "will"     "be"       "nice"     "tomorrow"

After vocabulary lookup, the data might be vectorized as integers, e.g.:

list(
  c(71, 1331, 4231),
  c(73, 8, 3215, 55, 927),
  c(83, 91, 1, 645, 1253, 927)
)
[[1]]
[1]   71 1331 4231

[[2]]
[1]   73    8 3215   55  927

[[3]]
[1]   83   91    1  645 1253  927

The data is a nested list where individual samples have length 3, 5, and 6, respectively. Since the input data for a deep learning model must be a single tensor (of shape e.g. (batch_size, 6, vocab_size) in this case), samples that are shorter than the longest item need to be padded with some placeholder value (alternatively, one might also truncate long samples before padding short samples).

Keras provides a utility function to truncate and pad lists to a common length: pad_sequences().

raw_inputs <- list(
  c(711, 632, 71),
  c(73, 8, 3215, 55, 927),
  c(83, 91, 1, 645, 1253, 927)
)

# By default, this will pad using 0s; it is configurable via the
# "value" parameter.
# Note that you could use "pre" padding (at the beginning) or
# "post" padding (at the end).
# We recommend using "post" padding when working with RNN layers
# (in order to be able to use the
# CuDNN implementation of the layers).

padded_inputs <- pad_sequences(raw_inputs, padding = "post")
Loaded Tensorflow version 2.9.1
print(padded_inputs)
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]  711  632   71    0    0    0
[2,]   73    8 3215   55  927    0
[3,]   83   91    1  645 1253  927

Masking

Now that all samples have a uniform length, the model must be informed that some part of the data is actually padding and should be ignored. That mechanism is masking.

There are three ways to introduce input masks in Keras models:

  • Add a layer_masking() layer.
  • Configure a layer_embedding() layer with mask_zero = TRUE.
  • Pass a mask argument manually when calling layers that support this argument (e.g. RNN layers).

Mask-generating layers: embedding and masking

Under the hood, these layers will create a mask tensor (2D tensor with shape (batch, sequence_length)), and attach it to the tensor output returned by the layer_masking() or layer_embedding() layer.

embedding <- layer_embedding(input_dim = 5000, output_dim = 16, mask_zero = TRUE)
masked_output <- embedding(padded_inputs)

print(masked_output$`_keras_mask`)
tf.Tensor(
[[ True  True  True False False False]
 [ True  True  True  True  True False]
 [ True  True  True  True  True  True]], shape=(3, 6), dtype=bool)
masking_layer <- layer_masking()
# Simulate the embedding lookup by expanding the 2D input to 3D,
# with embedding dimension of 10.
unmasked_embedding <- tf$cast(
    tf$tile(tf$expand_dims(padded_inputs, axis = -1L), c(1L, 1L, 10L)), tf$float32
)
masked_embedding <- masking_layer(unmasked_embedding)
print(masked_embedding$`_keras_mask`)
tf.Tensor(
[[ True  True  True False False False]
 [ True  True  True  True  True False]
 [ True  True  True  True  True  True]], shape=(3, 6), dtype=bool)

As you can see from the printed result, the mask is a 2D boolean tensor with shape (batch_size, sequence_length), where each individual FALSE entry indicates that the corresponding timestep should be ignored during processing.

Mask propagation in the Functional API and Sequential API

When using the Functional API or the Sequential API, a mask generated by an layer_embedding() or layer_masking() will be propagated through the network for any layer that is capable of using them (for example, RNN layers). Keras will automatically fetch the mask corresponding to an input and pass it to any layer that knows how to use it.

For instance, in the following Sequential model, the LSTM layer will automatically receive a mask, which means it will ignore padded values:

model <- keras_model_sequential() %>% 
  layer_embedding(input_dim = 5000, output_dim = 16, mask_zero = TRUE) %>% 
  layer_lstm(32)

This is also the case for the following Functional API model:

inputs <- layer_input(shape = shape(NULL), dtype = "int32")
outputs <- inputs %>% 
  layer_embedding(input_dim = 5000, output_dim = 16, mask_zero = TRUE) %>% 
  layer_lstm(units = 32)
model <- keras_model(inputs, outputs)

Passing mask tensors directly to layers

Layers that can handle masks (such as the LSTM layer) have a mask argument in their call method.

Meanwhile, layers that produce a mask (e.g. Embedding) expose a compute_mask(input, previous_mask) method which you can call.

Thus, you can pass the output of the compute_mask() method of a mask-producing layer to the call method of a mask-consuming layer, like this:

my_layer <- new_layer_class(
  "my_layer",
  initialize = function(...) {
    super()$`__init__`(...)
    self$embedding <- layer_embedding(
      input_dim = 5000, 
      output_dim = 16, 
      mask_zero = TRUE
    )
    self$lstm <- layer_lstm(units = 32)
  },
  call = function(inputs) {
    x <- self$embedding(inputs)
    # Note that you could also prepare a `mask` tensor manually.
    # It only needs to be a boolean tensor
    # with the right shape, i$e. (batch_size, timesteps).
    mask <- self$embedding$compute_mask(inputs)
    output <- self$lstm(x, mask = mask)  # The layer will ignore the masked values
    output
  }
)


layer <- my_layer()
x <- array(as.integer(runif(32*10)*100), dim = c(32, 10))
layer(x)
tf.Tensor(
[[ 3.3238861e-03  8.8161658e-03 -4.6604574e-03 ...  2.9808443e-04
  -4.6976949e-03 -9.1661196e-03]
 [-9.8711392e-04 -4.7741998e-03  9.9169789e-04 ...  3.2503013e-03
  -9.3929539e-04  1.9399440e-03]
 [-1.4668978e-03  1.5159376e-03  2.2681677e-03 ...  1.7861301e-05
  -5.1243077e-03 -1.1163743e-02]
 ...
 [-2.3654662e-03  6.5680984e-03 -8.1697162e-03 ...  2.9306496e-03
   8.0709462e-04 -4.4205068e-03]
 [-4.5497305e-04 -1.0025433e-02  5.6873313e-03 ... -7.7879243e-03
  -3.4422067e-03  1.0313809e-02]
 [ 1.4288073e-03  2.0973580e-03 -8.5060867e-03 ...  1.2249695e-02
   1.2900957e-03  1.2297687e-02]], shape=(32, 32), dtype=float32)

Supporting masking in your custom layers

Sometimes, you may need to write layers that generate a mask (like Embedding), or layers that need to modify the current mask.

For instance, any layer that produces a tensor with a different time dimension than its input, such as a Concatenate layer that concatenates on the time dimension, will need to modify the current mask so that downstream layers will be able to properly take masked timesteps into account.

To do this, your layer should implement the layer$compute_mask() method, which produces a new mask given the input and the current mask.

Here is an example of a temporal_split layer that needs to modify the current mask.

layer_temporal_split <- new_layer_class(
  "temporal_split",
  call = function(inputs) {
    # Expect the input to be 3D and mask to be 2D, split the input tensor into 2
    # subtensors along the time axis (axis 1).
    tf$split(inputs, 2L, axis = 1L)
  },
  compute_mask = function(inputs, mask = NULL) {
    # Also split the mask into 2 if it presents.
    if (is.null(mask)) return(NULL)
    tf$split(mask, 2L, axis = 1L)
  }
)

c(first_half, second_half) %<-% layer_temporal_split()(masked_embedding)
print(first_half$`_keras_mask`)
tf.Tensor(
[[ True  True  True]
 [ True  True  True]
 [ True  True  True]], shape=(3, 3), dtype=bool)
print(second_half$`_keras_mask`)
tf.Tensor(
[[False False False]
 [ True  True False]
 [ True  True  True]], shape=(3, 3), dtype=bool)

Here is another example of a custom_embedding layer that is capable of generating a mask from input values:

layer_custom_embedding <- new_layer_class(
  "custom_embedding",
  initialize = function(input_dim, output_dim, mask_zero = FALSE, ...) {
    super()$ `__init__`(...)
    self$input_dim <- input_dim
    self$output_dim <- output_dim
    self$mask_zero <- mask_zero  
  },
  build = function(input_shape) {
    self$embeddings <- self$add_weight(
      shape = shape(self$input_dim, self$output_dim),
      initializer = "random_normal",
      dtype = "float32"
    )
  },
  call = function(inputs) {
    tf$nn$embedding_lookup(self$embeddings, inputs)
  },
  compute_mask = function(inputs, mask = NULL) {
    if (!self$mask_zero) return(NULL)
    tf$not_equal(inputs, 0L)
  }
)

layer <- layer_custom_embedding(
  input_dim = 10, 
  output_dim = 32, 
  mask_zero = TRUE
)

x <- array(as.integer(runif(3*10)*9), dim = c(3, 10))
y <- layer(x)
mask <- layer$compute_mask(x)

print(mask)
tf.Tensor(
[[ True  True False  True False False  True  True  True  True]
 [ True  True  True False  True False  True  True  True  True]
 [ True  True  True  True  True  True False  True  True  True]], shape=(3, 10), dtype=bool)

Note: For more details about format limitations related to masking, see the serialization guide.

Opting-in to mask propagation on compatible layers

Most layers don’t modify the time dimension, so don’t need to modify the current mask. However, they may still want to be able to propagate the current mask, unchanged, to the next layer. This is an opt-in behavior. By default, a custom layer will destroy the current mask (since the framework has no way to tell whether propagating the mask is safe to do).

If you have a custom layer that does not modify the time dimension, and if you want it to be able to propagate the current input mask, you should set self$supports_masking = TRUE in the layer constructor. In this case, the default behavior of compute_mask() is to just pass the current mask through.

Here’s an example of a layer that is whitelisted for mask propagation:

layer_my_activation <- new_layer_class(
  "my_activation",
  initialize = function(...) {
    super()$`__init__`(...)
    self$supports_masking <- TRUE
  },
  call = function(inputs) {
    tf$nn$relu(inputs)
  }
)

You can now use this custom layer in-between a mask-generating layer (like Embedding) and a mask-consuming layer (like LSTM), and it will pass the mask along so that it reaches the mask-consuming layer.

inputs <- layer_input(shape = shape(NULL), dtype = "int32")
x <- inputs %>% 
  layer_embedding(input_dim = 5000, output_dim = 16, mask_zero = TRUE) %>% 
  layer_my_activation() # Will pass the mask along
print(x$`_keras_mask`)
KerasTensor(type_spec=TensorSpec(shape=(None, None), dtype=tf.bool, name=None), name='Placeholder_1:0')
outputs <- layer_lstm(x, 32)# Will receive the mask
model <- keras_model(inputs, outputs)

Writing layers that need mask information

Some layers are mask consumers: they accept a mask argument in call and use it to determine whether to skip certain time steps.

To write such a layer, you can simply add a mask = NULL argument in your call signature. The mask associated with the inputs will be passed to your layer whenever it is available.

Here’s a simple example below: a layer that computes a softmax over the time dimension (axis 1) of an input sequence, while discarding masked timesteps.

layer_temporal_softmax <- new_layer_class(
  "temporal_softmax",
  call = function(inputs, mask = NULL) {
   broadcast_float_mask <- tf$expand_dims(tf$cast(mask, "float32"), -1L)
   inputs_exp <- tf$exp(inputs) * broadcast_float_mask
   inputs_sum <- tf$reduce_sum(
     inputs_exp * broadcast_float_mask, 
     axis = -1L, 
     keepdims = TRUE
   )
   inputs_exp / inputs_sum 
  }
)

inputs <- layer_input(shape = shape(NULL), dtype = "int32")
outputs <- inputs %>% 
  layer_embedding(input_dim = 10, output_dim = 32, mask_zero = TRUE) %>% 
  layer_dense(1) %>% 
  layer_temporal_softmax()

model <- keras_model(inputs, outputs)
y <- model(
  array(sample.int(9, 32*100, replace = TRUE), dim = c(32, 100)),
  array(runif(32*100), dim = c(32, 100, 1))
)

Summary

That is all you need to know about padding & masking in Keras. To recap:

  • “Masking” is how layers are able to know when to skip / ignore certain timesteps in sequence inputs.
  • Some layers are mask-generators: Embedding can generate a mask from input values (if mask_zero = TRUE), and so can the Masking layer.
  • Some layers are mask-consumers: they expose a mask argument in their __call__ method. This is the case for RNN layers.
  • In the Functional API and Sequential API, mask information is propagated automatically.
  • When using layers in a standalone way, you can pass the mask arguments to layers manually.
  • You can easily write layers that modify the current mask, that generate a new mask, or that consume the mask associated with the inputs.

Environment Details

tensorflow::tf_config()
TensorFlow v2.9.1 (~/.virtualenvs/r-tensorflow-site/lib/python3.9/site-packages/tensorflow)
Python v3.9 (~/.virtualenvs/r-tensorflow-site/bin/python)
sessionInfo()
R version 4.2.1 (2022-06-23)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 20.04.4 LTS

Matrix products: default
BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/libmkl_rt.so

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] keras_2.9.0.9000      tensorflow_2.9.0.9000

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.9           knitr_1.39           whisker_0.4         
 [4] magrittr_2.0.3       here_1.0.1           lattice_0.20-45     
 [7] R6_2.5.1             rlang_1.0.4          fastmap_1.1.0       
[10] stringr_1.4.0        tools_4.2.1          grid_4.2.1          
[13] xfun_0.31            png_0.1-7            cli_3.3.0           
[16] htmltools_0.5.2      tfruns_1.5.0         rprojroot_2.0.3     
[19] yaml_2.3.5           digest_0.6.29        Matrix_1.4-1        
[22] base64enc_0.1-3      htmlwidgets_1.5.4    zeallot_0.1.0       
[25] evaluate_0.15        rmarkdown_2.14       stringi_1.7.8       
[28] compiler_4.2.1       generics_0.1.3       reticulate_1.25-9000
[31] jsonlite_1.8.0      
system2(reticulate::py_exe(), c("-m pip freeze"), stdout = TRUE) |> writeLines()
absl-py==1.1.0
asttokens==2.0.5
astunparse==1.6.3
backcall==0.2.0
cachetools==5.2.0
certifi==2022.6.15
charset-normalizer==2.1.0
decorator==5.1.1
dill==0.3.5.1
etils==0.6.0
executing==0.8.3
flatbuffers==1.12
gast==0.4.0
google-auth==2.9.0
google-auth-oauthlib==0.4.6
google-pasta==0.2.0
googleapis-common-protos==1.56.4
grpcio==1.47.0
h5py==3.7.0
idna==3.3
importlib-metadata==4.12.0
importlib-resources==5.8.0
ipython==8.4.0
jedi==0.18.1
keras==2.9.0
Keras-Preprocessing==1.1.2
keras-tuner==1.1.2
kt-legacy==1.0.4
libclang==14.0.1
Markdown==3.3.7
matplotlib-inline==0.1.3
numpy==1.23.1
oauthlib==3.2.0
opt-einsum==3.3.0
packaging==21.3
pandas==1.4.3
parso==0.8.3
pexpect==4.8.0
pickleshare==0.7.5
Pillow==9.2.0
promise==2.3
prompt-toolkit==3.0.30
protobuf==3.19.4
ptyprocess==0.7.0
pure-eval==0.2.2
pyasn1==0.4.8
pyasn1-modules==0.2.8
pydot==1.4.2
Pygments==2.12.0
pyparsing==3.0.9
python-dateutil==2.8.2
pytz==2022.1
PyYAML==6.0
requests==2.28.1
requests-oauthlib==1.3.1
rsa==4.8
scipy==1.8.1
six==1.16.0
stack-data==0.3.0
tensorboard==2.9.1
tensorboard-data-server==0.6.1
tensorboard-plugin-wit==1.8.1
tensorflow==2.9.1
tensorflow-datasets==4.6.0
tensorflow-estimator==2.9.0
tensorflow-hub==0.12.0
tensorflow-io-gcs-filesystem==0.26.0
tensorflow-metadata==1.9.0
termcolor==1.1.0
toml==0.10.2
tqdm==4.64.0
traitlets==5.3.0
typing_extensions==4.3.0
urllib3==1.26.10
wcwidth==0.2.5
Werkzeug==2.1.2
wrapt==1.14.1
zipp==3.8.1
TF Devices:
-  PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU') 
-  PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU') 
CPU cores: 12 
Date rendered: 2022-07-14 
Page render time: 5 seconds