-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslides_onepage.html
1204 lines (696 loc) · 34.7 KB
/
slides_onepage.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<title>Python & Jupyter Notebooks on Savio</title>
<meta charset="utf-8">
<style>
@import url(https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz);
@import url(https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic);
@import url(https://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic);
body { font-family: 'Droid Serif'; }
h1, h2, h3 {
font-family: 'Yanone Kaffeesatz';
font-weight: normal;
}
.remark-code, .remark-inline-code { font-family: 'Ubuntu Mono'; }
.remark-slide-scaler { overflow-y: auto; }
.red { color: red; }
.green { color: green; }
.blue { color: blue; }
img { max-width: 100%; }
.footnote {
position: absolute;
bottom: 12px;
font-size: 14px;
max-width: 80%;
}
.remark-inline-code {
color: #4c33ff;
}
/* Two-column layouts */
.left-column { width: 49%; float: left; }
.right-column { width: 49%; float: right; }
.right-column ~ p { clear: both; }
.right-column ~ ul { clear: both; }
</style>
</head>
<body>
<textarea id="source">
# Using Python & Jupyter Notebooks on Savio
# Announcements
- Research IT is hiring several [graduate student Domain Consultants](https://docs.google.com/document/d/18-ea-CsRsSVSu8hhFqnPFs-i7RvcG1ObGCW_1olUdJg/edit) for flexible, 10% to 25% (4-10 hours/week) appointments. Email your cover letter and CV to: [[email protected]](mailto:[email protected])
- Our next [Cloud Computing Meetup](https://www.meetup.com/ucberkeley_cloudmeetup/) is on **Thursday, December 9 at 1pm** and focused on **startups using cloud technologies**.
- We are looking for researchers working with **sensitive data**. Get in touch for more information: [[email protected]](mailto:[email protected])
- If you have any data or compute questions, please visit us at our weekly office hours on **Wednesdays from 1:30-3pm** and **Thursdays from 9:30-11am**. See https://research-it.berkeley.edu/consulting for Zoom link.
# Outline
- Python package management on the cluster
- Overview and pros/cons of using pip and conda
- Best practices when using conda environments
- Using Jupyter notebooks via Open OnDemand on Savio
- Monitoring and debugging OOD jobs
- Creating your own Jupyter kernels from a conda env
- Modifying the kernel to use the module system
- Basic parallelization strategies in Python
- ipyparallel
- Dask
- Ray
- Parallel processing in Jupyter notebooks
# Introduction
We'll do this mostly as a demonstration. We encourage you to login to your account and try out the various examples yourself as we go through them.
Much of this material is based on the extensive Savio documention we have prepared and continue to prepare, available at [https://docs-research-it.berkeley.edu/services/high-performance-computing/](https://docs-research-it.berkeley.edu/services/high-performance-computing/).
The materials for this tutorial are available using git at the short URL ([tinyurl.com/brc-nov21](https://tinyurl.com/brc-nov21)), the GitHub URL ([https://github.com/ucb-rit/savio-training-python-jupyter-fall-2021](https://github.com/ucb-rit/savio-training-python-jupyter-fall-2021)), or simply as a [zip file](https://github.com/ucb-rit/savio-training-python-jupyter-fall-2021/archive/main.zip).
# Python on Savio
First step, load in Python:
```sh
# loads latest version on system 3.7
module load python
# or load specific version
module load python/3.6 #
```
To see what versions are available on the system:
```sh
[jpduncan@ln002 ~]$ module avail python
/global/software/sl-7.x86_64/modfiles/langs
python/2.7 python/3.5 python/3.6 python/3.7
...
```
## Don't forget...
...to `module load python`.
If you forget you will still have a default version available (but no `pip` or `conda`):
```sh
[jpduncan@ln002 ~]$ which python
/usr/bin/python
[jpduncan@ln002 ~]$ python version
Python 2.7.5
[jpduncan@ln002 ~]$ which {pip,conda}
/usr/bin/which: no pip in (/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/global/home/groups/allhands/bin:/global/home/users/jpduncan/bin)
/usr/bin/which: no conda in (/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/global/home/groups/allhands/bin:/global/home/users/jpduncan/bin)
```
.red[WARNING:] We strongly caution against using Python 2 which is no longer supported by the Python Software Foundation.
# System default Python packages
Run `conda list` to see what packages are already available.
```sh
[jpduncan@ln001 ~]$ conda list | head
# packages in environment at /global/software/sl-7.x86_64/modules/langs/python/3.7:
#
# Name Version Build Channel
_anaconda_depends 2019.03 py37_0 anaconda
_ipyw_jlab_nb_ext_conf 0.1.0 py37_0
_libgcc_mutex 0.1 main
alabaster 0.7.12 py37_0
anaconda custom py37_1
anaconda-client 1.7.2 py37_0
anaconda-navigator 1.9.7 py37_0
```
Includes many common packages and their dependencies, such as:
- **Scientific computing**: numpy, scipy
- **Visualization**: bokeh, seaborn, matplotlib
- **Parallel computing**: dask, ipyparallel
- **Data ingest/manipulation**: hdf5, pandas
- **Data science**: pyspark, scikit-learn, statsmodels
- many more
# More ML packages
A few machine learning packages in the module system:
```sh
[jpduncan@ln002 ~]$ module avail ml
/global/software/sl-7.x86_64/modfiles/apps
ml/caffe/rc5 ml/tensorflow/1.12.0-cpu-py36
ml/cntk/2.0.beta15-py27 ml/tensorflow/1.12.0-py36
ml/cntk/2.0.beta15-py35 ml/tensorflow/1.7.0-py27
ml/mxnet/0.9.3-py27 ml/tensorflow/1.7.0-py35
ml/mxnet/0.9.3-py35 ml/tensorflow/1.7.0-py36
ml/mxnet/0.9.3-py36 ml/tensorflow/2.0-py36
ml/mxnet/0.9.3-r-3.2.5 ml/tensorflow/2.1.0-py37
ml/tensorflow/1.0.0-py27 ml/tensorflow/2.3.0-py37
ml/tensorflow/1.0.0-py35 ml/tensorflow/2.5.0-py37
ml/tensorflow/1.0.0-py36 ml/torch/torch7
```
```sh
[jpduncan@ln002 ~]$ module avail pytorch
/global/home/groups/consultsw/sl-7.x86_64/modfiles
pytorch/0.3.1-py3.5-cuda9.0 pytorch/0.4.0-py36-cuda9.0 pytorch/1.0.0-py36-cuda9.0
```
# Installing additional packages with pip
pip stands for "package installer for Python".
You can use it to install packages from:
- PyPI the Python Package Index
```sh
# user to install in ~/.local
# upgrade to get newer version of package than already installed
pip install user upgrade scikit-learn
```
- PyPI the Python Package Index
- Version control systems (VCS) such as `git`
```sh
pip install user git+https://github.com/scikit-learn/scikit-learn
```
- PyPI the Python Package Index
- Version control systems (VCS) such as `git`
- Local project directories
```sh
# -e is for "editable" installs (can also be used with VCS)
# this is similar to `python setup.py develop`
pip install user -e path/to/your/project
```
- PyPI the Python Package Index
- Version control systems (VCS) such as `git`
- Local project directories
- Local or remote source archives
```sh
pip install user https://github.com/scikit-learn/scikit-learn/archive/refs/tags/1.0.1.tar.gz
```
- PyPI the Python Package Index
- Version control systems (VCS) such as `git`
- Local project directories
- Local or remote source archives
- From a `requirements.txt` file
```
pip install user -r requirements.txt
```
.red[WARNING:] `conda list` won't show the packages installed via the default
version of pip that is available after `module load python`. Use `pip list
user` instead.
# pip default user install directory
By default, using `pip install user` puts package Python code, library files, and metadata into `~/.local/lib/python3.7/site-packages` (assuming Python 3.7).
```sh
[jpduncan@ln003 ~]$ pip install user upgrade scikit-learn
[jpduncan@ln003 ~]$ ls ~/.local/lib/python3.7/site-packages/
__pycache__ sklearn
scikit_learn-1.0.1.dist-info threadpoolctl-3.0.0.dist-info
scikit_learn.libs threadpoolctl.py
```
To avoid taking up too much room in your home directory, you can move this directory to scratch and create a symlink:
```sh
cp -pr ~/.local /global/scratch/users/$USER/.local
rm -rf ~/.local
ln -s /global/scratch/users/$USER/.local ~/.local
```
Alternatively, you can change this directory for your session by setting the environmental variable `PYTHONUSERBASE`, or permanently by setting it in `~/.bashrc`.
<!Alternatively, you can use `target` with `pip install`, but it's more cumbersome.>
## Uninstalling packages previously installed with pip
```sh
# uninstall a single package
pip uninstall scikit-learn
# uninstall all user packages
pip freeze user | xargs pip uninstall -y
# uninstall all user packages with specific prefix
pip freeze user | grep scikit- | xargs pip uninstall -y
```
Sadly, `pip uninstall` does not remove package dependencies (but `pip-autoremove` package may help).
More info on various pip commands in docs: https://pip.pypa.io/en/stable/
## Managing your Python environment with conda
The second package manager available by default when you `module load python` is conda. Unlike pip, conda is also an environment manager.
Create a conda environment.
```sh
# create an empty conda env called my-env
[jpduncan@ln003 ~]$ conda create name my-env
```
This creates a directory `~/.conda/envs/my-env`. Activate it:
```sh
[jpduncan@ln003 ~]$ source activate my-env
(my-env) [jpduncan@ln003 ~]$ conda install numpy # also installs Python 3.9
(my-env) [jpduncan@ln003 ~]$ source deactivate
DeprecationWarning: 'source deactivate' is deprecated. Use 'conda deactivate'.
[jpduncan@ln003 ~]$
```
.red[WARNING:] You may be used to using `conda activate` to activate an environment, but this requires you to run `conda init` first which we don't recommend on Savio. If you do use `conda init`, we recommend you also run `conda config set auto_activate_base False`.
# Installing additional packages with conda
`conda` is a bit more restrictive than `pip`. There are two main ways to install packages:
- From various conda "channels" such as `default` (https://anaconda.org/), `conda-forge`, `bioconda`, among others.
```sh
(my-env) [jpduncan@ln003 ~]$ conda install scipy # using the default channel
# -c is short for channel
(my-env) [jpduncan@ln003 ~]$ conda install -c bioconda samtools
# update scipy using the conda-forge channel
(my-env) [jpduncan@ln003 ~]$ conda update scipy channel conda-forge
```
- Advanced: You can also install from an archive (e.g., .tar.bz2), but doing so won't resolve the package's dependencies.
.red[WARNING]: Be sure to activate a conda environment before using `conda install`, otherwise conda will try to put the packages in a read-only system location.
# Conda config
You can customize conda's configuration using `conda config`.
- Add `conda-forge` with highest priority for all envs
```sh
(my-env) [jpduncan@ln003 ~]$ conda config add channels conda-forge
```
- Add `conda-forge` with lowest priority for all envs:
```sh
(my-env) [jpduncan@ln003 ~]$ conda config append channels conda-forge
```
- Add `bioconda` with highest priority for a specific env:
```sh
(my-env) [jpduncan@ln003 ~]$ conda config env add channels bioconda
```
The first two will add or modify `~/.condarc`, while the third will create `~/.conda/envs/my-env/.condarc`.
# Using pip within a conda env
.red[WARNING]: This can cause issues because conda doesn't consider pip-installed packages when installing additional packages. Be careful when using pip in a conda environment.
First be sure that pip is available already installed in the environment and follow these [best practices](https://www.anaconda.com/blog/using-pip-in-a-conda-environment):
- Use pip only after conda
- If conda changes are needed after using pip, create new environment
- Don't use `user` when calling `pip install`
- Always run pip with `upgrade-strategy only-if-needed` (the default)
- Experimental: Use `pip_interop_enabled` setting [see here](https://docs.conda.io/projects/conda/en/latest/user-guide/configuration/pip-interoperability.html)
## Upgrading packages and rolling back conda environment changes
Say you changed your environment (e.g., updated a package) and suddenly your code has errors.
```sh
(my-env) [jpduncan@ln003 ~]$ conda update samtools # breaks environment!
```
You can roll those changes back as follows:
```sh
# find the last working revision number
(my-env) [jpduncan@ln003 ~]$ conda list revisions
# restore to revision 3
(my-env) [jpduncan@ln003 ~]$ conda install revision=3
```
.blue[NOTE]: conda doesn't show revisions for changes made by pip, so they can't be rolled back this way.
# Changing installation directory with conda
When an environment is active, packages will install in its directory.
You can also install packages to specific environments or paths without activating first:
```sh
# install to the my-env environment
[jpduncan@ln003 ~]$ conda install name my-env scipy
# create env and install packages at the same time
[jpduncan@ln003 ~]$ conda create prefix $SCRATCH/conda/envs/scratch-env scipy
# give full path to env to activate
[jpduncan@ln003 ~]$ source activate $SCRATCH/conda/envs/scratch-env
```
Like `~/.local`, you can also consider moving `~/.conda` to scratch and symlinking.
## Removing packages, removing conda environments, and cleaning up
To remove a specific package in a specific environment:
```sh
[jpduncan@ln003 ~]$ conda remove scipy name my-env
```
To remove an entire environment (deactivate first):
```sh
[jpduncan@ln003 ~]$ conda remove name my-env all
```
`conda clean` helps remove unused packages and tarballs:
```sh
[jpduncan@ln003 ~]$ conda clean dry-run all
```
## pip pros and cons
.green[\+] can use system packages
.green[\+] new package versions come out on PyPI first
.green[\+] larger number of packages on PyPI
.green[\+] more flexible package installation
.green[\+] a bit faster than conda
.red[\-] doesn't check for simultaneous compatibility of all dependencies
.red[\-] limited to system Python versions
.red[\-] no automated dependency cleanup
.red[\-] Python packages only
## conda pros and cons
.green[\+] environments self-contained, can use any version of Python
.green[\+] `conda clean` helps remove unused packages
.green[\+] if you make a change that didn't go well, roll back
.green[\+] not just Python packages
.green[\+] ensures that all dependencies are compatible
.red[\-] `conda install` tends to be slower than `pip install`
.red[\-] environments can become quite large on disk and/or cause I/O issues
.red[\-] more limited number of Python packages available
# Best practices for reproducibility
**pip** use a requirements.txt
```sh
pip freeze > requirements.txt
```
**conda** use an environment.yml file
```sh
conda env export > environment.yml
```
**even better** use a container
See our [training on using containers on Savio](https://docs-research-it.berkeley.edu/services/high-performance-computing/getting-help/training-and-tutorials/#savio-introduction-to-containers-on-savio-creating-reproducible-scalable-and-portable-workflows).
- .green[\+] Prevents I/O issues on the system
- .green[\+] Very portable
- .red[\-] more of a learning curve
.center[![Open OnDemand Logo](images/ood-logo.png)]
Open OnDemand (OOD) allows various interactive applications to access the full Savio infrastructure, including:
- Jupyter Notebooks (our focus)
- RStudio
- Matlab
- VS Code
For more info on the OOD project: https://openondemand.org/
# Jupyter Notebooks overview
Jupyter Notebooks provide an interactive environment for writing and executing
Python code, visualizing results, and creating documentation.
A Jupyter Notebook can serve as a reproducible record for your analysis.
Let's take a quick look at Jupyter on OOD now: https://ood.brc.berkeley.edu
.center[![Open On Demand on Savio](images/ood.png)]
## Using Jupyter on Savio partitions via Slurm
Select appropriate Slurm flags:
.center[![Slurm config for Jupyter server](images/jupyter-slurm.png)]
## Connect to Jupyter
.center[![Interactive sessions](images/my-interactive-sessions.png)]
Clicking on the **Session ID** will take you to the a directory with scripts and logs for the session at `~/ondemand/data/sys/dashboard/batch_connect/sys/brc_jupyter-compute/output/<SESSIONID>`.
## The Jupyter file tree
.center[![Jupyter file tree](images/jupyter-tree.png)]
You can switch to Jupyter Lab by replacing everything from `/tree` with `/lab` in the URL.
## Selecting and changing the notebook kernel
.left-column[![New Jupyter notebook](images/new-notebook.png)]
.right-column[![Change notebook kernel](images/change-kernel.png)]
## Some OOD troubleshooting tips
- If you're having trouble getting the Slurm flags right when starting an OOD session, try running an analogous [interactive job](https://docs-research-it.berkeley.edu/services/high-performance-computing/user-guide/running-your-jobs/submitting-jobs/#interactive-jobs) from the command line.
- If running via Slurm, you can see the status of your job with `squeue -u $USER` (or `sq`) as with a usual Slurm job.
```sh
[jpduncan@ln001 ~]$ squeue -u $USER
JOBID PARTITION NAME USER ST TIME NODES NODELIST(REASON)
10080336 savio2 OOD_batc jpduncan R 54:45 1 n0090.savio2
```
- If you see that OOD is repeatedly giving you an authentication window, you need to **close any other browser tabs using OOD**, or go back to your previous tab.
- Compute on shared Jupyter node for debugging/exploration is limited to **1 core** and **2 GB memory**.
# Jupyter kernels
Every Jupyter Notebook uses a kernel, which provides programming language
support. In particular, the default IPython kernel allows Jupyter Notebooks to
run Python.
On Savio we have a number of Jupyter kernels available by default:
- Python 2.7, 3.6, 3.7
- TensorFlow kernels
- pyspark
See here for a list of kernels for other programming languages that may work on
Savio: https://github.com/jupyter/jupyter/wiki/Jupyter-kernels
# Making your own Jupyter kernel
If the default kernels don't meet your needs, you can create your own. There are
various methods, but a straightforward one is to use an environment.
We could use conda to create an environment which we then convert to an
ipykernel:
```sh
module load python
conda create -n py39 python=3.9 ipykernel
source activate py39
python -m ipykernel install user name=py39 display-name="Python 3.9"
source deactivate
```
.blue[NOTE]: If you don't need a different version of Python from what the system provides, then using a `virtualenv` may take less space on disk than a conda environment.
## Modifying your kernels to use system modules
Say we want to create an kernel that uses the `ml/tensorflow/2.5.0-py37` module.
```sh
module load ml/tensorflow/2.5.0-py37
python -m ipykernel install user name=tf25 display-name="Python3.7 TF2.5.0"
```
This creates `~/.local/jupyter/kernels/tf25/kernel.json`:
```json
{
"argv": [
"/global/software/sl-7.x86_64/modules/langs/python/3.7/bin/python",
"-m",
"ipykernel_launcher",
"-f",
"{connection_file}"
],
"display_name": "Python3.7 TF-2.5.0",
"language": "python"
}
```
We'll need to edit this file so that the kernel has access to module and its dependencies.
We'll add a dictionary called `"env"` with environmental variables to set when starting up the kernel.
You'll want to see `env` with environmental variables as they are after you run `module load ml/tensorflow/2.5.0-py37`. To see what it does, run `module show ml/tensorflow/2.5.0-py37`.
In this case, we'll copy paste these variables to the `env` dictionary:
```sh
echo $PATH
echo $LD_LIBRARY_PATH
echo $PYTHONPATH
```
In my case, the final `kernel.json` looks like this:
```json
{
"argv": [
"/global/software/sl-7.x86_64/modules/langs/python/3.7/bin/python",
"-m",
"ipykernel_launcher",
"-f",
"{connection_file}"
],
"display_name": "Python3.7 TF-2.5.0",
"language": "python",
"env": {
"PATH": "/global/software/sl-7.x86_64/modules/apps/ml/tensorflow/2.5.0-py37/bin:/global/software/sl-7.x86_64/modules/langs/cuda/11.2/bin:/global/software/sl-7.x86_64/modules/langs/python/3.7/bin:/global/software/sl-7.x86_64/modules/langs/python/3.7/condabin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/global/home/groups/allhands/bin:/global/home/users/jpduncan/bin",
"LD_LIBRARY_PATH": "/global/software/sl-7.x86_64/modules/cuda/11.2/cudnn/8.1.1/lib64:/global/software/sl-7.x86_64/modules/langs/cuda/11.2/lib64/stubs:/global/software/sl-7.x86_64/modules/langs/cuda/11.2/lib64",
"PYTHONPATH" : "/global/software/sl-7.x86_64/modules/apps/ml/tensorflow/2.5.0-py37/lib/python3.7/site-packages"
}
}
```
Now I can use my new TensorFlow kernel on a GPU node.
.center[![Jupyter with TensorFlow kernel](images/jupyter-tf.png)]
# Basic parallelization using ipyparallel
We'll start by using the IPython parallel package (`ipyparallel`), which allows one to parallelize on a single machine or across multiple machines.
`ipyparallel` allows one to easily split up tasks that can be computed independently and send those tasks out to Python worker processes to run in parallel. The results are then collected back on the main Python process.
Since the workers are separate Python processes, we need to start up those processes, either from within Python (possible as of version 7 of ipyparallel) or from the command line.
# Starting workers on one node
```
## In newer versions of ipyparallel (v. 7 and later)
import ipyparallel as ipp
ipp.__version__
cluster = ipp.Cluster(n=4)
cluster.start_cluster_sync()
```
```
c = cluster.connect_client_sync()
## Check that we have the number of workers expected:
c.ids
```
Side note: You can also start the workers from the command line (this was required in older versions of ipyparallel, probably before version 7).
```
# in the shell
ipcluster start -n 4
```
```
# in python
import ipyparallel as ipp
c = ipp.Client()
c.ids
```
# Testing our cluster
Let's just verify that things seem set up ok and we can interact with all our workers:
```
dview = c[:]
dview
## Set blocking so that we wait for the result of the parallel execution
dview.block = True
dview.apply(lambda : "Hello, World")
```
`dview` stands for a 'direct view', which is an interface to our cluster that allows us to 'manually' send tasks to the workers.
# Parallelized machine learning example
Now let's see an example of how we can use our workers to run code in parallel.
We'll carry out a statistics/machine learning prediction method (random forest regression) with leave-one-out cross-validation, parallelizing over different held out data.
First let's set up packages, data and our main function on the workers:
```
dview.execute('from sklearn.ensemble import RandomForestRegressor as rfr')
dview.execute('import numpy as np')
def looFit(index, Ylocal, Xlocal):
rf = rfr(n_estimators=100)
fitted = rf.fit(np.delete(Xlocal, index, axis = 0), np.delete(Ylocal, index))
pred = rf.predict(np.array([Xlocal[index, :]]))
return(pred[0])
import numpy as np
np.random.seed(0)
n = 500
p = 50
X = np.random.normal(0, 1, size = (n, p))
Y = X[: , 0] + pow(abs(X[:,1] * X[:,2]), 0.5) + X[:,1] - X[:,2] + np.random.normal(0, 1, n)
mydict = dict(X = X, Y = Y, looFit = looFit)
dview.push(mydict)
```
# Parallelized machine learning example (2)
Now let's set up a "load-balanced view". With this type of interface, one submits the tasks and the controller decides how to divide up the tasks, ideally achieving good load balancing. A load-balanced computation is one that keeps all the workers busy throughout the computation
```
lview = c.load_balanced_view()
lview.block = True
# We'll leave out only 50 observations, for the sake of time
nSub = 50
# need a wrapper function because map() only operates on one argument
def wrapper(i):
return(looFit(i, Y, X))
# Now run the fitting, predicting on each held-out observation:
import time
pred = lview.map(wrapper, range(nSub))
pred
```
# Using multiple nodes
When using multiple nodes, we will generally start up a controller process on the first node that Slurm gives us and then use `srun` (within our running `srun` or `sbatch` session) to start up workers on the nodes.
First we'll start our Slurm job using `sbatch` or `srun`.
Then once the job starts (if using `srun`) or within our submission script (if using `sbatch`):
```
ipcontroller ip='*' &
sleep 30
## The next line starts one worker per SLURM task
## (which should equal the number of cores)
srun ipengine &
sleep 45 # wait until all engines have successfully started
```
At this point you should be able to connect to the running cluster using the syntax seen for single-node usage.
.blue[WARNING:] Be careful to set the sleep period long enough that the controller starts before trying to start the workers and the workers start before trying to connect to the workers from within Python.
# Using ipyparallel in a Jupyter notebook
As of our recent upgrade to version 7 of the ipyparallel package, you can start the ipyparallel workers from within Python and therefore from within your notebook. This is the same as we just saw in our basic Python session.
Previously, one needed to either start the workers via the "IPython Clusters" tab of the Jupyter interface or start the workers using `ipcluster start` from a terminal session and then connecting to them from the notebook.
As before, the number of workers should generally match the number of cores you requested (e.g., on `savio2_htc`) or (ideally) the number of cores on the machine (for partitions allocated on a per node basis).
If you've started the workers outside of Python, you need to connect to the running cluster. As before with the ipyparallel examples, 'c' gives us a 'handle' object.
```
import ipyparallel as ipp
c = ipp.Client(profile='default', cluster_id='')
c.ids # this should show the number of workers equal to the number you requeste
```
# Multiple nodes
This may be possible. Feel free to ask us and we can explore it further.
# Dask overview
Python's Dask package provides powerful tools for parallelizing computations on a single machine or across multiple machines.
In addition to providing tools that allow you to parallelize independent computations as we did with `ipyparallel`, Dask also allows you to run computations across datasets in parallel using distributed data objects.
There's lots of information about Dask online, including [this tutorial](https://github.com/berkeley-scf/tutorial-dask-future) prepared by Chris Paciorek.
# Distributed data in Dask
The idea here is to split up large datasets into chunks (also called 'partitions' or 'shards') and operate in parallel on those chunks. This generally assumes that / works best when the operations can be done independently on the chunks and limited information needs be communicated between chunks.
Some advantages of this are:
- increasing speed by using multiple cores to process the data.
- when using multiple nodes, increasing the amount of total memory that can be used by having the data split across the nodes.
# Dask's distributed data types
Some of the key types of distributed data objects in Dask are:
- distributed dataframes - each chunk is a Pandas dataframe
- distributed arrays - each subset of the array is a Numpy array
- bags - distributed lists, where each chunk contains some of the elements
# Dask's 'schedulers'
Dask can set up the parallel workers in a variety of ways, which are called schedulers. Here are the options:
|Type|Description|Multi-node|Copies of objects made?|
|-||-||
|synchronous|not in parallel|no|no|
|threaded|threads within current Python session|no|no|
|processes|background Python sessions|no|yes|
|distributed|Python sessions across multiple nodes|yes or no|yes|
.blue[NOTE:] Because of Python's Global Interpreter Lock (GIL), many computations done in pure Python code won't be parallelized using the 'threaded' scheduler; however computations on numeric data in numpy arrays, Pandas dataframes and other C/C++/Cython-based code will parallelize.
Here's an example of setting the 'processes' scheduler for a computation:
```
import dask.multiprocessing
# spread work across multiple cores, one worker per core
dask.config.set(scheduler='processes', num_workers = 4)
```
# Dask bag example - context
Let's read in a bunch of data from multiple files and put it into a Dask bag.
Here's the format of the input files. They're actually tabular type data (i.e., we can think of rows as observations and columns (space separated here) as fields/variables. But in working with the data using a bag, we'll treat each row as arbitrary observation that is simply a string.