# Tensorflow: map\_fn and parallel execution

**URL:** <https://discuss.ai.google.dev/t/tensorflow-map-fn-and-parallel-execution/13224>\
**Category:** General Discussion\
**Tags:** help\_request, tf\_function\
**Created:** [September 27, 2021, 8:05am UTC](https://discuss.ai.google.dev/t/tensorflow-map-fn-and-parallel-execution/13224 "2021-09-27T08:05:51Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Yani\_Boshev](https://avatars.discourse-cdn.com/v4/letter/y/b9e5f3/32.png) [@Yani\_Boshev](https://discuss.ai.google.dev/u/Yani_Boshev)\
**Post date:** [September 27, 2021, 8:05am UTC](https://discuss.ai.google.dev/t/tensorflow-map-fn-and-parallel-execution/13224/1 "2021-09-27T08:05:51Z")

</div>

According to my expectations `map_fn` should execute some function in parallel. Unfortunately, it seems that it executes it sequentially. Here is a brief example I created to verify my concerns.

```auto
@tf.function
def test_mapfn():
    @tf.function
    def body(vals):
        res = tf.constant(1, dtype=tf.float32)
        for i in tf.range(5, dtype=tf.float32):
            tf.print(i)
            # Doing some random calculation below. Not important.
            res = res + tf.pow(tf.reduce_sum(tf.where(vals> 0.5, vals, tf.constant(0, dtype=tf.float32))) + tf.pow(tf.reduce_sum(vals), 0.5) - tf.pow(tf.reduce_sum(vals), tf.constant(2, dtype=tf.float32)), -i)
        return res

    tensor = tf.random.uniform(shape=(2, 100000000))
    res = tf.map_fn(body, tensor, parallel_iterations=2)

```

The printed values are

```auto
0
1
2
3
4
0
1
2
3
4

```

If executed in parallel the code above should mix the printed values in the loop but they are printed sequentially. I know that this is pretty basic test but I noticed the same behavior with functions which take longer time to execute. The CPU is not utilized completely and seems that the function is called sequentially with unrolled inputs. I know the recommendation to use `vectorized_map` but unfortunately in my use case it is not applicable since the code can’t be rewritten to comply with the requirements of `vectorized_map`. Also, changing the number of `parallel_iterations` doesn’t seem to affect the speed.

---

<div class="post-metadata">

**Author:** ![Kiran\_Sai\_Ramineni](https://d1dlmcr85iqnpo.cloudfront.net/user_avatar/discuss.ai.google.dev/kiran_sai_ramineni/32/8859_2.png) [@Kiran\_Sai\_Ramineni](https://discuss.ai.google.dev/u/Kiran_Sai_Ramineni)\
**Post date:** [September 26, 2024, 8:44am UTC](https://discuss.ai.google.dev/t/tensorflow-map-fn-and-parallel-execution/13224/3 "2024-09-26T08:44:42Z")

</div>

Hi @Yani_Boshev, I have tried the above code in another way and the execution happens in parallel. please refer to this [gist](https://gist.github.com/kiransair/06492dd552af3e61cf4ece191dffd5ca) and let us know if it is the same that you are expecting.

Thank You.
