tensorflow_probability sample() is too slow
I need to use tensorflow_probability in my PPO code , but sample() is too slow . So I tried to sample one data 1000 times , the result show that tf2 was hundreds of times slower than pytorch.
#tensorfow 2.4
import tensorflow_probability as tfp
import timeit
tfd = tfp.distributions
dist = tfd.Normal(0.,1.)
print(timeit.timeit(lambda: dist.sample(), number=1000))
# 0.5568850869999551
#pytorch
import torch
dist = torch.distributions.Normal(0.,1.)
print(timeit.timeit(lambda: dist.sample(), number=1000))
#0.019572936000031405
according to #898 , I change my code to
@tf.function
def cal_():
return dist.sample()
print(timeit.timeit(lambda:cal_(), number=1000))
#0.113001856999972
it's still very slow.All the above result is tested on my MacBook 19. When I test it in my PC with Ubuntu18, RTX 2080Ti, the result was even worse.
print(tf.test.is_gpu_available()
#True
@tf.function
def cal_():
return dist.sample()
print(timeit.timeit(lambda:cal_(), number=1000))
#0.39419427106622607
It might help to know what your goal here is? dist.sample(1000) is a much more efficient way of generating 1000 samples (this is also true in pytorch, with sample_n).
One issue might be that tf.function is often more efficient on the outside of the biggest function you have. For example (running on https://colab.research.google.com/),
@tf.function
def cal_():
dist = tfd.Normal(0., 1.)
return [dist.sample() for _ in range(1000)]
cal_() # First call traces
print(timeit.timeit(lambda:cal_(), number=1000))
# 9.743449628000008
Compared to
dist = torch.distributions.Normal(0.,1.)
print(timeit.timeit(lambda: [dist.sample() for _ in range(1000)], number=1000))
# 13.254004783000028
Note that:
- Again,
tfd.Normal(0., 1.).sample([1000, 1000])takes 51ms, which is what you should use, if possible. - I skipped including the first call in the
timeitrun -- it amortizes asnumbergets larger. - I bet there are ways to optimize the pytorch calls as well, but I don't know them.
Hi, I'm going to close this issue. As Colin mentioned above, I would generally prefer calling our methods in a vectorized fashion for the most speed (specifically calling sample with a batch).
Same issue, very slow.
It is still an issue. Could you please provide an user-friendly solution?