probability icon indicating copy to clipboard operation
probability copied to clipboard

tensorflow_probability sample() is too slow

Open Brycebywang opened this issue 5 years ago • 5 comments

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

Brycebywang avatar Dec 23 '20 14:12 Brycebywang

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

Brycebywang avatar Dec 24 '20 07:12 Brycebywang

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:

  1. Again, tfd.Normal(0., 1.).sample([1000, 1000]) takes 51ms, which is what you should use, if possible.
  2. I skipped including the first call in the timeit run -- it amortizes as number gets larger.
  3. I bet there are ways to optimize the pytorch calls as well, but I don't know them.

ColCarroll avatar Dec 28 '20 15:12 ColCarroll

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).

srvasude avatar Feb 10 '21 11:02 srvasude

Same issue, very slow.

GoingMyWay avatar Aug 07 '23 09:08 GoingMyWay

It is still an issue. Could you please provide an user-friendly solution?

GoingMyWay avatar Aug 07 '23 12:08 GoingMyWay