You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 11e7d82
Browse filesBrowse the repository at this point in the historyBrowse files
Copy file name to clipboardExpand all lines: lectures/jax_intro.md
+38-28Lines changed: 38 additions & 28 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -46,20 +46,21 @@ import numpy as np
46
46
import quantecon as qe
47
47
```
48
48
49
-
Notice that we import `jax.numpy as jnp`, which provides a NumPy-like interface.
50
49
51
50
52
51
## JAX as a NumPy Replacement
53
52
54
-
One of the attractive features of JAX is that, whenever possible, its array
55
-
processing operations conform to the NumPy API.
56
-
57
-
This means that, in many cases, we can use JAX as a drop-in NumPy replacement.
58
-
59
53
Let's look at the similarities and differences between JAX and NumPy.
60
54
61
55
### Similarities
62
56
57
+
Above we import `jax.numpy as jnp`, which provides a NumPy-like interface to
58
+
array operations.
59
+
60
+
One of the attractive features of JAX is that, whenever possible, this interface
61
+
conform to the NumPy API.
62
+
63
+
As a result, we can often use JAX as a drop-in NumPy replacement.
63
64
64
65
Here are some standard array operations using `jnp`:
65
66
@@ -79,7 +80,7 @@ print(jnp.sum(a))
79
80
print(jnp.dot(a, a))
80
81
```
81
82
82
-
However, the array object `a` is not a NumPy array:
83
+
It should be remembered, however, that the array object `a` is not a NumPy array:
83
84
84
85
```{code-cell} ipython3
85
86
a
@@ -104,11 +105,13 @@ Let's now look at some differences between JAX and NumPy array operations.
104
105
(jax_speed)=
105
106
#### Speed!
106
107
107
-
Let's say we want to evaluate the cosine function at many points.
108
+
One major difference is that JAX is faster --- and sometimes much faster.
109
+
110
+
To illustrate, suppose that we want to evaluate the cosine function at many points.
108
111
109
112
```{code-cell}
110
113
n = 50_000_000
111
-
x = np.linspace(0, 10, n)
114
+
x = np.linspace(0, 10, n) # NumPy array
112
115
```
113
116
114
117
##### With NumPy
@@ -150,28 +153,24 @@ with qe.Timer():
150
153
# First run
151
154
y = jnp.cos(x)
152
155
# Hold the interpreter until the array operation finishes
153
-
jax.block_until_ready(y);
156
+
y.block_until_ready()
154
157
```
155
158
156
159
```{note}
157
-
Here, in order to measure actual speed, we use the `block_until_ready` method
158
-
to hold the interpreter until the results of the computation are returned.
159
-
160
-
This is necessary because JAX uses asynchronous dispatch, which
160
+
Above, the `block_until_ready` method
161
+
holds the interpreter until the results of the computation are returned.
162
+
This is necessary for timing execution because JAX uses asynchronous dispatch, which
161
163
allows the Python interpreter to run ahead of numerical computations.
162
-
163
-
For non-timed code, you can drop the line containing `block_until_ready`.
164
164
```
165
165
166
-
And let's time it again.
167
-
166
+
Now let's time it again.
168
167
169
168
```{code-cell}
170
169
with qe.Timer():
171
170
# Second run
172
171
y = jnp.cos(x)
173
172
# Hold interpreter
174
-
jax.block_until_ready(y);
173
+
y.block_until_ready()
175
174
```
176
175
177
176
On a GPU, this code runs much faster than its NumPy equivalent.
@@ -190,7 +189,11 @@ being used (as well as the data type).
190
189
The size matters for generating optimized code because efficient parallelization
191
190
requires matching the size of the task to the available hardware.
192
191
193
-
We can verify the claim that JAX specializes on array size by changing the input size and watching the runtimes.
192
+
193
+
#### Size Experiment
194
+
195
+
We can verify the claim that JAX specializes on array size by changing the input
196
+
size and watching the runtimes.
194
197
195
198
```{code-cell}
196
199
x = jnp.linspace(0, 10, n + 1)
@@ -201,7 +204,7 @@ with qe.Timer():
201
204
# First run
202
205
y = jnp.cos(x)
203
206
# Hold interpreter
204
-
jax.block_until_ready(y);
207
+
y.block_until_ready()
205
208
```
206
209
207
210
@@ -210,7 +213,7 @@ with qe.Timer():
210
213
# Second run
211
214
y = jnp.cos(x)
212
215
# Hold interpreter
213
-
jax.block_until_ready(y);
216
+
y.block_until_ready()
214
217
```
215
218
216
219
The run time increases and then falls again (this will be more obvious on the GPU).
@@ -263,7 +266,8 @@ a[0] = 1
263
266
a
264
267
```
265
268
266
-
In JAX this fails!
269
+
In JAX this fails 😱.
270
+
267
271
268
272
```{code-cell} ipython3
269
273
a = jnp.linspace(0, 1, 3)
@@ -278,14 +282,19 @@ except Exception as e:
278
282
279
283
```
280
284
281
-
The designers of JAX chose to make arrays immutable because JAX uses a
282
-
functional programming style, which we discuss below.
285
+
The designers of JAX chose to make arrays immutable because
286
+
287
+
1. JAX uses a *functional programming style* and
288
+
2. functional programming typically avoids mutable data
289
+
290
+
We discuss these ideas {ref}`below <jax_func>`.
283
291
284
292
285
-
#### A workaround
293
+
(jax_at_workaround)=
294
+
#### A Workaround
286
295
287
-
We note that JAX does provide an alternative to in-place array modification
288
-
using the [`at` method](https://docs.jax.dev/en/latest/_autosummary/jax.numpy.ndarray.at.html).
296
+
JAX does provide a direct alternative to in-place array modification
297
+
via the [`at` method](https://docs.jax.dev/en/latest/_autosummary/jax.numpy.ndarray.at.html).
289
298
290
299
```{code-cell} ipython3
291
300
a = jnp.linspace(0, 1, 3)
@@ -308,6 +317,7 @@ Hence, for the most part, we try to avoid this syntax.
308
317
(Although it can in fact be efficient inside JIT-compiled functions -- but let's put this aside for now.)
* We hold `n` static because it affects array size and hence JAX wants to specialize on its value in the compiled code.
510
+
* We pin to the CPU via `device=cpu` because this sequential workload consists of many small operations, leaving little opportunity for GPU parallelism.
511
+
512
+
Although `at[t].set` appears to create a new array at each step, inside a JIT-compiled function the compiler detects that the old array is no longer needed and performs the update in place.
513
+
514
+
Let's time it with the same parameters:
515
+
516
+
```{code-cell} ipython3
517
+
with qe.Timer():
518
+
# First run
519
+
x_jax = qm_jax_fori(0.1, n)
520
+
# Hold interpreter
521
+
x_jax.block_until_ready()
522
+
```
523
+
524
+
Let's run it again to eliminate compilation overhead:
525
+
526
+
```{code-cell} ipython3
527
+
with qe.Timer():
528
+
# Second run
529
+
x_jax = qm_jax_fori(0.1, n)
530
+
# Hold interpreter
531
+
x_jax.block_until_ready()
532
+
```
533
+
534
+
JAX is also quite efficient for this sequential operation.
535
+
536
+
537
+
There's another way we can implement the loop that uses `lax.scan`.
538
+
539
+
This alternative is arguably more in line with JAX's functional approach ---
This code is not easy to read but, in essence, `lax.scan` repeatedly calls `update` and accumulates the returns `x_new` into an array.
507
555
508
-
```{note}
509
-
We specify `device=cpu` in the `jax.jit` decorator because this computation
510
-
consists of many small sequential operations, leaving little opportunity for the
511
-
GPU to exploit parallelism. As a result, kernel-launch overhead tends to
512
-
dominate on the GPU, making the CPU a better
513
-
fit.
514
-
```
515
-
516
556
Let's time it with the same parameters:
517
557
518
558
```{code-cell} ipython3
519
559
with qe.Timer():
520
560
# First run
521
-
x_jax = qm_jax(0.1, n)
561
+
x_jax = qm_jax_scan(0.1, n)
522
562
# Hold interpreter
523
563
x_jax.block_until_ready()
524
564
```
@@ -528,13 +568,11 @@ Let's run it again to eliminate compilation overhead:
528
568
```{code-cell} ipython3
529
569
with qe.Timer():
530
570
# Second run
531
-
x_jax = qm_jax(0.1, n)
571
+
x_jax = qm_jax_scan(0.1, n)
532
572
# Hold interpreter
533
573
x_jax.block_until_ready()
534
574
```
535
575
536
-
JAX is also quite efficient for this sequential operation.
537
-
538
576
Both JAX and Numba deliver strong performance after compilation.
539
577
540
578
@@ -547,9 +585,11 @@ array and fill it element by element using a standard Python loop.
547
585
548
586
This is exactly how most programmers think about the algorithm.
549
587
550
-
The JAX version, on the other hand, requires using `lax.scan`, which is significantly less intuitive.
588
+
The JAX versions, on the other hand, require either `lax.fori_loop` or
589
+
`lax.scan`, both of which are less intuitive than a standard Python loop.
551
590
552
-
Additionally, JAX's immutable arrays mean we cannot simply update array elements in place, making it hard to directly replicate the algorithm used by Numba.
591
+
While JAX's `at[t].set` syntax does allow element-wise updates, the overall code
592
+
remains harder to read than the Numba equivalent.
553
593
554
594
For this type of sequential operation, Numba is the clear winner in terms of
555
595
code clarity and ease of implementation.
@@ -575,12 +615,12 @@ For **sequential operations**, Numba has clear advantages.
575
615
The code is natural and readable --- just a Python loop with a decorator ---
576
616
and performance is excellent.
577
617
578
-
JAX can handle sequential problems via `lax.scan`, but the syntax is less
579
-
intuitive.
618
+
JAX can handle sequential problems via `lax.fori_loop` or `lax.scan`, but
619
+
the syntax is less intuitive.
580
620
581
621
```{note}
582
-
One important advantage of `lax.scan` is that it supports automatic
583
-
differentiation through the loop, which Numba cannot do.
622
+
One important advantage of `lax.fori_loop` and `lax.scan` is that they
623
+
support automatic differentiation through the loop, which Numba cannot do.
584
624
If you need to differentiate through a sequential computation (e.g., computing
585
625
sensitivities of a trajectory to model parameters), JAX is the better choice
0 commit comments