jax icon indicating copy to clipboard operation
jax copied to clipboard

Python is blocked until computation is complete, contradiction with Jax docs

Open Laz4rz opened this issue 2 years ago • 5 comments

Description

After a bit of fiddling my understanding is that Jax only allows non-blocking computation if accelerator (other than CPU) is available (though I couldn't get Colabs TPU to be seen by Jax, even though TF could see it).

If above understanding is true then it its not at all clear in the Jax Asynchronous dispatch docs (https://jax.readthedocs.io/en/latest/async_dispatch.html).

When only CPU is available times of jnp.dot(x, x.T).block_until_ready() and jnp.dot(x, x.T) are equivalent.

from timeit import timeit

import jax
import jax.numpy as jnp
from jax import random

print(f"JAX uses {jax.devices()[0]}")
print(f"All devices: {jax.devices()}")


n_repetitions = 3
random_key = random.key(0)
n = m = 10000


a = random.normal(random_key, (n, m))

duration_without_blocking = timeit(lambda: jnp.dot(a, a.T), number=n_repetitions)
duration_with_blocking = timeit(lambda: jnp.dot(a, a.T).block_until_ready(), number=n_repetitions)

print(f"JAX .dot on {m, n} without blocking: {duration_without_blocking:.2f} seconds")
print(f"JAX .dot on {m, n} with blocking: {duration_with_blocking:.2f} seconds")

results in:

JAX uses TFRT_CPU_0
All devices: [CpuDevice(id=0)]
JAX .dot on (10000, 10000) without blocking: 7.59 seconds
JAX .dot on (10000, 10000) with blocking: 7.64 seconds

Running .dot on GPU returns expected difference in runtimes: image

If this is the expected behavior, I think it would be valuable to add the information that .block_until_ready() does not change the behavior of Jax on CPU. It would resolve any doubts one may have and save time.

System info (python version, jaxlib version, accelerator, etc.)

CPU environment:

jax:    0.4.23
jaxlib: 0.4.23.dev20240124
numpy:  1.26.4
python: 3.11.8 (main, Feb 26 2024, 15:36:12) [Clang 14.0.6 ]
jax.devices (1 total, 1 local): [CpuDevice(id=0)]
process_count: 1

GPU environment:

jax:    0.4.23
jaxlib: 0.4.23
numpy:  1.25.2
python: 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0]
jax.devices (1 total, 1 local): [cuda(id=0)]
process_count: 1

$ nvidia-smi
Mon Apr  1 12:04:06 2024       
+---------------------------------------------------------------------------------------+
| NVIDIA-SMI 535.104.05             Driver Version: 535.104.05   CUDA Version: 12.2     |
|-----------------------------------------+----------------------+----------------------+
| GPU  Name                 Persistence-M | Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp   Perf          Pwr:Usage/Cap |         Memory-Usage | GPU-Util  Compute M. |
|                                         |                      |               MIG M. |
|=========================================+======================+======================|
|   0  Tesla T4                       Off | 00000000:00:04.0 Off |                    0 |
| N/A   61C    P0              29W /  70W |  11455MiB / 15360MiB |      0%      Default |
|                                         |                      |                  N/A |
+-----------------------------------------+----------------------+----------------------+
                                                                                         
+---------------------------------------------------------------------------------------+
| Processes:                                                                            |
|  GPU   GI   CI        PID   Type   Process name                            GPU Memory |
|        ID   ID                                                             Usage      |
|=======================================================================================|
+---------------------------------------------------------------------------------------+

Laz4rz avatar Apr 01 '24 12:04 Laz4rz

This is sort of a bug and sort of not.

JAX may run computation asynchronously. It does not have to execute computations asynchronously. It is up to the runtime. We should probably clarify the docs, if they are unclear on this point.

That said, there's a long-standing bug on CPU which means our computations are synchronous most of the time, and @yueshengys is looking into it.

hawkinsp avatar Apr 01 '24 14:04 hawkinsp

Thanks for fast response @hawkinsp. Could you please elaborate a little bit more? Or maybe point me to some place where I can understand the topic better?

If I understand correctly: the computation is delayed as we want to wait to see whether we can optimize some composition of computations (run the composition without moving them in and out of memory?). Is this the only reason to delay them? Are these gains accelerator agnostic? Is there an issue with discussion on the CPU bug? I'd love to read more about it.

Regarding the docs: I think it would help in the understanding of this behavior. I have a little of CS background - but almost none in Comp Arch - so I am more or less able to connect the dots of how stuff works (even though I may lose a shit ton of time figuring it out). But many people coming from purely applied backgrounds may be way more flabbergasted.

Laz4rz avatar Apr 01 '24 15:04 Laz4rz

Actually, we're not delaying execution so we can do optimization. That's something we've chosen not to do in JAX so far.

For each computation on CPU, we can either choose to run it inline (synchronously) or in a thread (asynchronously). Why might you prefer the former? Suppose the computation were something really cheap, like 1 + 1. Then the cost of the thread hop will be greater than the cost of the computation itself.

As it happens, due to a bug we run almost all CPU computations inline, when our intention was that we should only run cheap computations inline. Fixing that bug is easy enough, but there's a bunch of other things that can go wrong when you suddenly make everything that was previously run synchronously asynchronous.

hawkinsp avatar Apr 01 '24 15:04 hawkinsp

I really appreciate the time you take to answer these - as I imagine - basic questions.

Just to exhaust this: if Jax chooses to delay these computations (and since Python has to run threads sequentially) are they delayed to a point where Jax has to wait for some I/O? As I understand otherwise we would still need to block the main thread to run these computations. What would be a toy example of when Jax chooses to delay CPU computations?

Does the same mechanism hold when I move computations to the accelerator different than the CPU? Meaning, do they also have to block the main Python thread, or can decide based on when I need the output of this computation?

Laz4rz avatar Apr 02 '24 11:04 Laz4rz

The computations are enqueued into C++ threadpool, so they can be executed in parallel.

We don't block the main Python thread unless you explicitly call block_until_ready or something like print the array.

yueshengys avatar Apr 02 '24 16:04 yueshengys