Let's say I have a function that takes a Tensor in input (of a given dimensionality) and returns another Tensor in output. I would like to use that function on a batch of inputs and I would like it to return a batch of outputs. So both the input and the output would have one more dimension.
I could write a tf.while_loop to execute my function on all the inputs in the batch, but I am unsure on how to store the output of the single elements in the batch.
I have an Idea on how to do this that should also clarify what I am trying to do, but I am not sure it would be optimal.
batch = tf.random.uniform([4,3,2]) #batch of size 4 of (3,2) shaped tensors
output = tf.zeros([0,5]) #let's say that the output should be a batch of 4 (4,5) shaped tensors.
#I will concatenate the single outputs to this tensor and then reshape it
for i in tf.range(len(batch)):
output = tf.concat((output,MyVeryNiceFunction(batch[i])),0) #MyVeryNiceFunction returns a (4,5) shaped tensor
output = tf.reshape(output,(4,4,5)) #(batch_size,(shape of tensor))
return output
This code for sure gives the output I want, but would it allow to parallelize each execution of the loop? Is there a better way to do this? Is there a proper data structure that would allow me to store the output for each loop execution, and then efficiently build the output Tensor from that?