tensorflow
map_fn
tensor
multiple tensors
deep learning

Does tensorflow map_fn support taking more than one tensor?

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

TensorFlow's tf.map_fn is a functional programming operation that applies a given function across the elements of one or more tensors. A common question is whether tf.map_fn can handle multiple input tensors at once. The answer is yes. You can pass multiple tensors by wrapping them in a tuple or a nested structure. This article explains how to use tf.map_fn with single and multiple tensors, covering the syntax, practical examples, and performance considerations.

Understanding tf.map_fn

The tf.map_fn function works similarly to Python's built-in map. It takes a function and one or more tensors, then applies the function to each element along the first dimension (axis 0) of those tensors. The results are stacked back into a tensor.

Basic Syntax

python
1tf.map_fn(
2    fn,
3    elems,
4    dtype=None,
5    parallel_iterations=None,
6    back_prop=True,
7    swap_memory=False,
8    infer_shape=True,
9    name=None
10)

Key parameters:

  • fn: A callable that takes one argument (or a structured argument when using multiple tensors) and returns one output.
  • elems: A tensor or a nested structure of tensors. The function iterates over the first dimension.
  • dtype: The output data type. Required when the output type differs from the input type.
  • parallel_iterations: Number of iterations to run in parallel (default is 10).

Single Tensor Example

Here is a simple example that squares each element.

python
1import tensorflow as tf
2
3tensor = tf.constant([1, 2, 3, 4, 5])
4
5result = tf.map_fn(lambda x: x * x, tensor)
6print(result.numpy())
7# Output: [ 1  4  9 16 25]

The function receives one scalar at a time (each element along axis 0) and returns the squared value.

Multiple Tensors Using a Tuple

To pass multiple tensors, wrap them in a tuple. The function then receives a tuple of corresponding elements from each tensor.

python
1import tensorflow as tf
2
3tensor_a = tf.constant([1, 2, 3, 4])
4tensor_b = tf.constant([10, 20, 30, 40])
5
6def add_fn(x):
7    return x[0] + x[1]
8
9result = tf.map_fn(add_fn, (tensor_a, tensor_b), dtype=tf.int32)
10print(result.numpy())
11# Output: [11 22 33 44]

When you pass (tensor_a, tensor_b) as elems, TensorFlow iterates over both tensors in parallel. At each step, x is a tuple containing one element from tensor_a and the corresponding element from tensor_b. The function adds them together, producing an element-wise sum.

Note that both tensors must have the same size along the first dimension. If tensor_a has 4 elements and tensor_b has 4 elements, the function runs 4 times.

Multiple Tensors with Different Dtypes

When the input tensors have different data types, you need to specify fn_output_signature (TensorFlow 2.x) or dtype to tell TensorFlow what the output looks like.

python
1import tensorflow as tf
2
3floats = tf.constant([1.5, 2.5, 3.5])
4ints = tf.constant([1, 2, 3])
5
6def multiply_fn(x):
7    return tf.cast(x[0], tf.float32) * tf.cast(x[1], tf.float32)
8
9result = tf.map_fn(
10    multiply_fn,
11    (floats, ints),
12    fn_output_signature=tf.float32
13)
14print(result.numpy())
15# Output: [1.5 5.0 10.5]

Using fn_output_signature is the recommended approach in TensorFlow 2.x because it replaces the older dtype parameter and provides clearer semantics.

Returning Multiple Outputs

The function inside tf.map_fn can also return a tuple, which produces multiple output tensors.

python
1import tensorflow as tf
2
3values = tf.constant([4.0, 9.0, 16.0, 25.0])
4
5def sqrt_and_square(x):
6    return tf.sqrt(x), x * x
7
8result = tf.map_fn(
9    sqrt_and_square,
10    values,
11    fn_output_signature=(tf.float32, tf.float32)
12)
13
14sqrt_result, square_result = result
15print("Sqrt:", sqrt_result.numpy())
16print("Square:", square_result.numpy())
17# Sqrt: [2. 3. 4. 5.]
18# Square: [ 16.  81. 256. 625.]

The fn_output_signature must match the structure of the function's return value, in this case a tuple of two float32 tensors.

Performance Considerations

While tf.map_fn is flexible, it has performance trade-offs you should understand.

  • Vectorized alternatives are faster: Operations like tf.add, tf.multiply, and tf.reduce_sum already operate element-wise across tensors. Use tf.map_fn only when your function contains logic that cannot be expressed as a vectorized operation (for example, conditional branching per element).
  • parallel_iterations: Increase this from the default of 10 to allow more iterations to run concurrently. This helps when individual iterations are lightweight.
  • Graph overhead: Each call to tf.map_fn unrolls into a loop in the TensorFlow graph. For very large tensors, this can increase graph construction time.
  • tf.vectorized_map: TensorFlow also provides tf.vectorized_map, which attempts to automatically vectorize the function. It is often significantly faster than tf.map_fn when the function is compatible with vectorization.
python
# Faster alternative when possible
result = tf.vectorized_map(add_fn, (tensor_a, tensor_b))

Common Pitfalls

  • Shape mismatch on first dimension: All tensors in the elems tuple must have the same size along axis 0. A mismatch causes a runtime error.
  • Missing dtype or fn_output_signature: If the output type differs from the input type and you do not specify it, TensorFlow may raise an error or infer the wrong type.
  • Using Python control flow inside fn: Avoid using Python if/else inside the mapped function. Use tf.cond or tf.where instead, because Python control flow executes at graph construction time, not at runtime.
  • Forgetting that iteration is along axis 0: If your data has batch dimensions arranged differently, you may need to transpose before calling tf.map_fn.

Summary

tf.map_fn fully supports multiple input tensors by accepting a tuple of tensors as the elems argument. The mapped function receives corresponding elements from each tensor at every iteration. You can also return multiple outputs by having the function return a tuple, paired with a matching fn_output_signature. For performance-critical code, consider tf.vectorized_map or native vectorized operations as faster alternatives. Always ensure that all input tensors share the same first-dimension size and that the output signature matches the function's return structure.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design