/
slides.Rmd
716 lines (477 loc) · 16.9 KB
/
slides.Rmd
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
---
title: "A survival guide to large-scale data analysis in R"
author: Peter Carbonetto
output:
beamer_presentation:
template: beamer.tex
keep_tex: false
---
```{r knitr-options, echo=FALSE}
knitr::opts_chunk$set(comment = "#",collapse = TRUE,fig.align = "center",
results = "hide", fig.show = "hide", message = FALSE,
warning = FALSE)
```
Tutorial aims
=============
1. Develop skills for large-scale data analysis in R, and apply these
skills to a large-ish data set.
2. Learn how to use R **non-interactively** within a high-performance
computing environment.
3. Make more effective use of the most precious commodity in
computing---**memory**---and appreciate that R often makes poor use of it.
4. Learn through **live coding**---this includes learning from mistakes!
Outline of tutorial
===================
+ Brief introduction.
+ Initial setup steps.
+ Vignettes:
1. How to measure memory in R, and use it effectively.
2. How to automate an R analysis on the RCC cluster.
3. Speeding up R with multithreaded matrix operations.*
4. Multithreaded R computation with parLapply.*
5. Distributing your computation on the RCC cluster using
the SLURM engine.*
\* Incomplete.
Elements of my hands-on tutorial approach
=========================================
+ Developing good tutorials is *hard*; developing good hands-on
tutorials is *harder*.
+ Don't have all the setup upfront.
+ Follow Software Carpentry (and Stefano Allesina's) "live coding"
approach, but not strictly.
+ Don't make participants write their own code.
+ Don't make participants use the RCC cluster.
+ Don't provide a handout---all code should be in the slides.
+ Flip between typing (running the examples) and talking about it
(what happened?).
+ Reduce dependencies between examples.
+ Create slides using R Markdown:
```
cd docs
make slides
make test
```
It's your choice
================
Your may choose to...
+ Work through the examples on the RCC cluster.
+ Work through the examples on your laptop.
+ Pair up with your neighbour.
+ Follow what I do on the projector.
*However*,
1. A few of the examples will only run on the RCC cluster.
2. The examples may not produce the exact same result on your laptop.
Software requirements
=====================
1. R (ideally, version 3.4.0 or greater)
2. python 3.x
3. SLURM (this is the job scheduler on the RCC cluster)
Outline of tutorial
===================
+ Brief introduction.
+ **Initial setup steps.**
+ Vignettes.
Initial setup (part 1)
======================
+ WiFi
+ Power outlets
+ YubiKeys
+ Pace, questions (e.g., keyboard shortcuts).
Initial setup (part 2)
======================
Download the workshop packet to your laptop.
+ URL: https://github.com/pcarbo/R-survival-large-scale
+ Open **slides.pdf** from the **docs** folder. This is useful for
viewing and copying the code from the slides.
+ We may also take a look at some of the code in the **code**
folder. The source code can be viewed with your favourite text editor,
or browsed on GitHub.
Initial setup (part 3)
======================
If you are using the RCC cluster, set up your cluster computing
environment:
+ Connect to midway2.
- See https://rcc.uchicago.edu/docs/connecting
+ Request a midway2 ("Broadwell") compute node with 8 CPUs and 15 GB
of memory:
```
screen -S r-tutorial # Optional.
sinteractive --partition=broadwl --mem=15G \
--cpus-per-task=8 --time=3:00:00
```
+ Make note of the compute node you have connected to:
```
echo $HOSTNAME
```
Initial setup (part 4)
======================
If you are using the RCC cluster, run these commands to download the
workshop packet to your home directory (no spaces in URL):
```{bash, eval=FALSE}
cd $HOME
git clone https://github.com/pcarbo/
R-survival-large-scale.git
```
Initial setup (part 5)
======================
Next, we set up **htop** for monitoring processes.
Open up a separate Terminal window and connect to midway2.
Connect to the same compute node:
```{bash, eval=FALSE}
ssh $HOSTNAME
```
Copy my htop configuration:
```{bash, eval=FALSE}
mkdir -p ~/.config/htop
cp extras/htoprc ~/.config/htop/
```
Start htop:
```{bash, eval=FALSE}
htop --user=<username>
```
+ Some useful htop keyboard shortcuts:
- q to quit
- M to sort processes by memory
- p to toggle program paths
- H to toggle threads (for multithreaded computing)
Initial setup (part 6)
======================
Move to the **code** folder in the git repository. And on the RCC
cluster, load Python3 and R:
```{bash, eval=FALSE}
cd code
module load python/3.5.2
module load R
```
Start up an interactive R environment:
```{bash, eval=FALSE}
R --no-save
```
Check which version of R you are running (hopefully version 3.4.0 or
greater):
```{r check-r-version}
version$version.string
```
Also, before continuing, check your working directory:
```{r check-wd}
getwd() # Should be .../code
```
What's in the workshop packet
=============================
```
R-survival-large-scale
/code # Source code used in demos
# (and R Markdown for slides).
/data # "Raw" and processed data.
/docs # Slides and other materials.
/extras # Additional useful files.
/output # All results are stored here.
```
Outline of tutorial
===================
+ Brief introduction.
+ Initial setup steps.
+ Vignettes:
1. **How to measure memory in R, and use it effectively.**
2. How to automate an R analysis on the RCC cluster.
3. Speeding up R with multithreaded matrix operations.*
4. Multithreaded R computation with parLapply.*
5. Distributing your computation on the RCC cluster using
the SLURM engine.*
\* Incomplete.
Vignette #1: How to measure memory in R, and use it effectively
===============================================================
We have two tasks:
1. Compute the SNP minor allele frequencies (MAFs) from the a large
genotype data matrix.
2. Center and scale the columns of the genotype matrix.
We will use R for both tasks.
+ We will monitor memory allocation in R, and find ways to reduce it.
+ To monitor memory allocation, we will use:
1. **htop**
2. **monitor_memory.py**, a Python script.
Vignette #1: How to measure memory in R, and use it effectively
===============================================================
Outline of the vignette:
1. Simulate a genotype data matrix, and save the data.
2. Monitor memory needed to compute MAFs.
3. Monitor memory needed to scale genotypes.
4. Attempt to reduce memory used in scaling genotypes.
Generate genotype data
======================
We generate an $n \times p$ genotype matrix with $n = 1000$ samples,
$p = 300,\!000$ SNPs and 1% missing genotypes.
```{r, sim-geno}
source("sim.geno.R")
set.seed(1)
geno <- sim.geno(n = 1000,p = 3e5,na.rate = 0.01)
save(list = "geno",file = "../data/geno.RData")
```
Compute and summarize MAFs
==========================
We will run this code non-interactively to compute the MAFs:
```{r summarize-maf}
# Compute MAFs.
maf <- colMeans(geno,na.rm = TRUE)/2
maf <- pmin(maf,1 - maf)
# Summarize distribution of MAFs.
print(quantile(maf,seq(0,1,0.1)),digits = 2)
```
+ Quit R.
+ Run these commands in the shell:
```
pwd # Should be .../code
Rscript summarize.maf.R
```
Monitoring memory allocation
============================
While the R script is running, use **htop** in a separate Terminal
session to profile memory allocation (look at the **RES** column).
+ If necessary, re-run the code.
Re-run the R script again, this time using the Python program to
measure memory usage every 0.01 s:
```{bash, eval=FALSE}
export MEM_CHECK_INTERVAL=0.01
./monitor_memory.py Rscript summarize.maf.R
```
How well does the **htop** estimate agree with **max rss_memory** from
the Python script?
Center and scale the genotype matrix
====================================
Next, we will run this code non-interactively to center and scale the
genotype matrix:
```{r scale-geno}
source("scale.R")
cat("Loading genotype data.\n")
load("../data/geno.RData")
cat("Centering and scaling genotype matrix.\n")
geno <- scale(geno)
```
Using the same methods as before, monitor memory usage.
```{bash, eval=FALSE}
./monitor_memory.py Rscript scale.geno.R
```
Does the scaling operation require more memory than computing MAFs?
+ If so, how much more?
+ How do you explain this result?
A better implementation of "scale"
==================================
Motivated by out observations in the previous slide, let's try to
reduce the memory usage by writing our own **scale** function.
```{r scale-geno-better}
scale_better <- function (X) {
for (i in 1:ncol(X)) {
X[,i] <- X[,i] - mean(X[,i],na.rm = TRUE)
X[,i] <- X[,i] / sd(X[,i],na.rm = TRUE)
}
return(X)
}
```
Now run the script that uses our custom scaling function:
```{bash, eval=FALSE}
./monitor_memory.py Rscript scale.geno.better.R
```
Does **scale_better** require less memory than **scale**? Why? Is
there more room to reduce memory usage?
Matrix scaling: a second attempt
================================
This next script attempts to reduce memory usage even further by
avoiding any function calls that modify `geno` within a local
environment.
```{bash, eval=FALSE}
./monitor_memory.py Rscript \
scale.geno.even.better.R
```
This is the code:
```{r scale-geno-even-better}
load("../data/geno.RData")
for (i in 1:ncol(geno)) {
x <- geno[,i]
x <- x - mean(x,na.rm = TRUE)
x <- x / sd(x,na.rm = TRUE)
geno[,i] <- x
}
```
Is this an improvement over our previous attempt? Is there still room
for improvement?
Matrix scaling: one last attempt using Rcpp
===========================================
The root issue is that R does not allow for "copying in place".
+ We can circumvent this by implementing a C++ function *that modifies
the input matrix directly.*
+ See files **scale.cpp** and **scale.geno.rcpp.R** for how this is
implemented using the **Rcpp** package.
Now try monitoring memory usage in the script that uses the Rcpp
implementation:
```{bash, eval=FALSE}
./monitor_memory.py Rscript scale.geno.rcpp.R
```
Does this implementation have a smaller memory footprint than previous
attempts? Is there still room for improvement?
Memory allocation in R: take-home points
========================================
+ R duplicates objects aggressively ("copy on modify"). This can be an
issue with objects are large.
+ Rcpp can circumvent some of R's limitations, but requires much more
effort!
+ An interesting effort is the **purrr** package. But it does not yet
handle matrices.
+ To accurately assess memory needs, run the code in a fresh R session.
+ For more advanced tools for memory profiling, see:
- http://adv-r.had.co.nz/memory.html
- https://adv-r.hadley.nz/memory.html
- profmem R package
Outline of tutorial
===================
+ Brief introduction.
+ Initial setup steps.
+ Vignettes:
1. How to measure memory in R, and use it effectively.
2. **How to automate an R analysis on the RCC cluster.**
3. Speeding up R with multithreaded matrix operations.*
4. Multithreaded R computation with parLapply.*
5. Distributing your computation on the RCC cluster using
the SLURM engine.*
\* Incomplete.
Vignette #2: How to automate an R analysis on the RCC cluster
=============================================================
Now that we have a good understanding of the memory needs for the
matrix scaling task, let's automate the analysis.
+ We want this script to work for any genotype data file provided as
input, and we want to be able to choose the location where the scaled
matrix is saved.
On the RCC cluster, this will involve two steps:
1. Develop an R script that accepts arguments from the command-line shell.
2. Develop a script for automating the job submission with the SLURM
scheduler.
Running an R script from the shell
==================================
We take these steps to automate the analysis:
+ Use the **commandArgs** function to read in command-line arguments.
+ This is implemented in **scale.geno.automated.R**.
To illustrate its features, let's use **R CMD BATCH** instead of
Rscript to run the script from the command line:
```{bash, eval=FALSE}
R CMD BATCH --no-save --no-restore \
'--args ../data/geno.RData
../output/geno.scaled.RData' \
scale.geno.automated.R \
../output/geno.scaled.automated.out
```
Submitting an R script to SLURM (part 1)
========================================
On the RCC cluster, a completely automated analysis should include
instructions for allocating resources with SLURM.
+ We still want this script to work for any input and output file.
This is the most basic script for accomplishing this:
```{bash, eval=FALSE}
#SBATCH --partition=broadwl
#SBATCH --mem=3G
#SBATCH --time=00:10:00
INPUT=${1}
OUTPUT=${2}
module load R/3.4.3
R CMD BATCH --no-save --no-restore \
'--args ${INPUT} ${OUTPUT}' \
scale.geno.automated.R \
../output/geno.scaled.automated.Rout
```
See also file **scale.geno.sbatch**.
Submitting an R script to SLURM (part 2)
========================================
Run this command to schedule an analysis:
```{bash, eval=FALSE}
sbatch scale.geno.sbatch ../data/geno.RData \
../output/geno.scaled.RData
```
While it is running, we can monitor the job's status:
```{bash, eval=FALSE}
squeue --user=<cnetid> | less -S
```
+ Optionally, add the lines in **extras/bashrc** to your `~/.bashrc`
file.
+ What happens when we change "3G" to "2G" in the sbatch script?
Automating an R analysis on the RCC cluster: take-home points
=============================================================
+ I *always* first run R code interactively (on smaller data sets) to
assess time and memory needs.
+ Automation is most useful when a script needs to be run many times,
or for a long-running computation.
+ For long-running scripts, it is helpful to print progress to the
console, e.g., `cat("Centering and scaling genotype matrix.\n")`.
+ A side benefit of the sbatch script is that it records the
computational setup (compute time, memory, software used).
+ Below we will see an example of combining R scripts with sbatch
scripts in multiple layers.
Outline of tutorial
===================
+ Brief introduction.
+ Initial setup steps.
+ Vignettes:
1. How to measure memory in R, and use it effectively.
2. How to automate an R analysis on the RCC cluster.
3. **Speeding up R with multithreaded matrix operations.**\*
4. Multithreaded R computation with parLapply.*
5. Distributing your computation on the RCC cluster using
the SLURM engine.*
\* Incomplete.
Vignette #3: Speeding up R with multithreaded matrix operations
===============================================================
+ Many of the problems we solve in our area involve matrix-vector
computations, often with large matrices and vectors.
+ For these problems, we can get multithreading (parallel computation)
for free because multithreaded operations are already implemented in
many BLAS and LAPACK library configurations. However, R needs to be
set up to take advantage of these configurations.
- On midway2, R 3.4.3 is installed from source and linked to
OpenBLAS.
+ This is a very system-dependent feature of R! May require
installation from source.
- See also Microsoft R Open.
Vignette #3: Speeding up R with multithreaded matrix operations
===============================================================
First generate the data set by running:
```{bash, eval=FALSE}
Rscript sim.gwas.R
```
This will create a file `gwas.RData` in the data directory.
Vignette #3: Speeding up R with multithreaded matrix operations
===============================================================
Try running the analysis with no multithreaded matrix operations:
```{bash, eval=FALSE}
export OPENBLAS_NUM_THREADS=1
Rscript calc.pve.R
```
Then try running it with 8 threads:
```{bash, eval=FALSE}
export OPENBLAS_NUM_THREADS=$SLURM_CPUS_ON_NODE
Rscript calc.pve.R
```
+ Explain how to interpret `system.time`.
+ How much of a computation time improvement do we get from making
more threads available to OpenBLAS?
Vignette #4: Multithreaded R computation with parLapply
=======================================================
Here we will run the same analysis as the previous vignette, but we
will se `parLapply` to speed up the computation when multiple cores
(CPUs) are available.
First try with 8 threads for OpenBLAS, and no parLapply
multithreading:
```{bash, eval=FALSE}
export OPENBLAS_NUM_THREADS=8
Rscript calc.pve.multicore.R 1
```
Next, try with 8 threads for parLapply, and no multithreaded matrix
operations:
```{bash, eval=FALSE}
export OPENBLAS_NUM_THREADS=1
Rscript calc.pve.multicore.R 8
```
Which parallel computing scheme is more efficient---parLapply, or
multithreaded matrix operations?
Vignette #5: Distributing computation using SLURM
=================================================
*Add introduction to vignette here.*
Some final thoughts
===================
*Add final thoughts and recap here.*